import { hasEngineErrorCode } from "./errors.js";
export async function runModelAttempts({ attempts, isFallbackModel, isNamedModelSelection, envHasKeyFor, formatMissingModelError, onAutoSkip, onAutoFailure, onFixedModelError, runAttempt, }) {
    let result = null;
    let usedAttempt = null;
    let lastError = null;
    let sawOpenRouterNoAllowedProviders = false;
    const missingRequiredEnvs = new Set();
    for (const attempt of attempts) {
        const hasKey = envHasKeyFor(attempt.requiredEnv);
        if (!hasKey) {
            if (isFallbackModel) {
                // Auto mode keeps going; named auto presets should still surface missing keys later.
                if (isNamedModelSelection) {
                    missingRequiredEnvs.add(attempt.requiredEnv);
                }
                else {
                    onAutoSkip?.(attempt);
                }
                continue;
            }
            throw new Error(formatMissingModelError(attempt));
        }
        try {
            result = await runAttempt(attempt);
            usedAttempt = attempt;
            break;
        }
        catch (error) {
            if (hasEngineErrorCode(error, "SUMMARY_STREAM_INTERRUPTED")) {
                throw error;
            }
            lastError = error;
            if (isNamedModelSelection &&
                error instanceof Error &&
                /No allowed providers are available for the selected model/i.test(error.message)) {
                sawOpenRouterNoAllowedProviders = true;
            }
            if (!isFallbackModel) {
                if (onFixedModelError) {
                    onFixedModelError(attempt, error);
                }
                throw error;
            }
            onAutoFailure?.(attempt, error);
        }
    }
    return { result, usedAttempt, missingRequiredEnvs, lastError, sawOpenRouterNoAllowedProviders };
}
//# sourceMappingURL=model-attempts.js.map