UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

747 lines (746 loc) • 24.9 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { r as resolveGlobalMap } from "./global-singleton-D7yf05nR.mjs"; import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import "./model-ref-shared-DqE2RqZv.mjs"; import { a as emitFailoverEvent } from "./diagnostic-events-BjAH1Kbx.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { t as createLazyImportLoader } from "./lazy-promise-DiCvjz9w.mjs"; import { w as isProfileInCooldown } from "./user-model-account-authority-CRj924IP.mjs"; import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs"; import { r as assertOperatorModelAllowed, t as assertAdmittedRunOperatorAuthority } from "./admitted-run-context-D3Jvk_f_.mjs"; import { i as FailoverError, u as isFailoverError } from "./error-BCRqSFIY.mjs"; import { o as isAgentHarnessPreflightError, s as isMissingAgentHarnessError } from "./errors-0Ou7CzqA.mjs"; import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs"; import { p as resolveSubscriptionAuthModeForProfiles } from "./order-jOvee2J6.mjs"; import { l as isNonSecretApiKeyMarker } from "./model-auth-markers-4YSUG71a.mjs"; import { n as hasAnyAuthProfileStoreSourceAsync } from "./source-check-1bfdqQg5.mjs"; import { i as externalCliDiscoveryScoped } from "./external-cli-discovery-DZ419koV.mjs"; import { b as resolveUsableCustomProviderApiKey, f as resolveConfigAwareEnvApiKey } from "./model-auth-provider-config-Bnc4upRS.mjs"; import { a as resolveBundledStaticCatalogModel, o as resolveManifestModelCatalogProviderAliasMetadata } from "./model.static-catalog-BYAE0w4W.mjs"; import { i as resolveConfiguredProviderConfig } from "./model.configured-overrides-ACgGOHL7.mjs"; import { t as normalizeConfiguredProviderModel } from "./model.registry-resolution-CV_hSCul.mjs"; import { n as isLikelyContextOverflowError } from "./context-overflow-C7ex88b9.mjs"; import { r as resolveModelCandidateChain, t as preferContextFitFallbackCandidates } from "./model-fallback-candidates-CFJLuJlL.mjs"; import "./classify-o7Whl-By.mjs"; import { i as describeFailoverError, n as buildProviderReauthCommand, r as coerceToFailoverError, u as isNonProviderRuntimeCoordinationError } from "./failover-error-CbIiC30n.mjs"; import { i as resolveSessionSuspensionReason, o as suspendSession } from "./session-suspension-DpEUvu5N.mjs"; import { n as getProviderRateLimitState } from "./provider-rate-limit-CuKCrLfX.mjs"; import { i as LiveSessionModelSwitchError, n as shouldPreserveTransientCooldownProbeSlot, r as shouldUseTransientCooldownProbeSlot, t as shouldAllowCooldownProbeForReason } from "./failover-policy-BJz7cR8u.mjs"; import { r as prepareAgentRuntimeAuth } from "./prepare-auth-Ck7RPVAG.mjs"; import { n as isFallbackCandidateSkipped, r as markFallbackCandidateSkipped, t as getFallbackCandidateSkipReason } from "./fallback-skip-cache-BcsSf_sg.mjs"; import { a as recordFailedCandidateAttempt, c as resolveHarnessPreflightFallbackIndex, d as resolveNextFallbackCandidateIndex, f as runFallbackAttempt, g as logModelFallbackDecision, h as isModelFallbackDecisionLogEnabled, i as isTranscriptNotContinuableError, l as resolveLiveSessionModelSwitchRedirectIndex, m as throwFallbackFailureSummary, n as hasDifferentLiveSessionRuntimeSelection, o as resolveFallbackAuthScope, p as shouldDiscardDeferredSessionSuspension, s as resolveFallbackSoonestCooldownExpiry, t as appendFailedCandidateAttempt, u as resolveModelFallbackCandidateHarnessAuthPrecheck } from "./model-fallback-attempt-DPZU4qST.mjs"; //#region src/agents/model-fallback-cooldown.ts const lastProbeAttempt = /* @__PURE__ */ new Map(); const MIN_PROBE_INTERVAL_MS = 3e4; const PROBE_MARGIN_MS = 12e4; const PROBE_SCOPE_DELIMITER = "::"; const MAX_PROBE_KEYS = 256; function resolveProbeThrottleKey(e, t) { const n = normalizeOptionalString(t) ?? ""; return n ? `${n}${PROBE_SCOPE_DELIMITER}${e}` : e; } function isProbeThrottleOpen(e, t) { return e - (lastProbeAttempt.get(t) ?? 0) >= MIN_PROBE_INTERVAL_MS; } function markProbeAttempt(e, t) { lastProbeAttempt.delete(t); lastProbeAttempt.set(t, e); pruneMapToMaxSize(lastProbeAttempt, MAX_PROBE_KEYS); } function resolveCooldownDecision(e) { const t = e.authRuntime.resolveProfilesUnavailableReason({ store: e.authStore, profileIds: e.profileIds, now: e.now }) ?? "unknown"; let n = e.isPrimary && isProbeThrottleOpen(e.now, e.probeThrottleKey); if (n && e.hasFallbackCandidates) { const t = e.authRuntime.getSoonestCooldownExpiry(e.authStore, e.profileIds, { now: e.now, forModel: e.candidate.model }); n = t === null || e.now >= t - PROBE_MARGIN_MS; } if (t === "auth" || t === "auth_permanent") return { type: "skip", reason: t, error: `Provider ${e.candidate.provider} has ${t} issue (skipping all models)` }; if (!(t === "billing" ? e.isPrimary && n : e.isPrimary && (!e.requestedModel || n) || !e.isPrimary && shouldUseTransientCooldownProbeSlot(t))) return { type: "suspend_session", reason: t }; return { type: "attempt", reason: t, markProbe: e.isPrimary && n }; } //#endregion //#region src/agents/model-fallback.types.ts const MODEL_FALLBACK_SKIPPED_CODE = "MODEL_FALLBACK_SKIPPED"; //#endregion //#region src/agents/model-fallback-rate-limit.ts /** Orders already admitted candidates from a shared health snapshot without changing policy. */ function orderFallbackCandidatesByRateLimit(e, t) { const n = e.toSorted((e, n) => { const r = t.get(e); const i = t.get(n); const a = r?.eligible === false ? Infinity : r?.retryAt ?? -Infinity; const o = i?.eligible === false ? Infinity : i?.retryAt ?? -Infinity; return a < o ? -1 : a > o ? 1 : 0; }); const r = n[0]; if (!r) return { candidates: e, attempts: [] }; const i = e.indexOf(r); return { candidates: n, attempts: e.slice(0, i).filter((e) => t.get(e)?.retryAt !== void 0).map(({ provider: e, model: t }) => ({ provider: e, model: t, reason: "rate_limit", code: MODEL_FALLBACK_SKIPPED_CODE, error: `Shared model token rate limit; trying ${r.provider}/${r.model} first` })) }; } /** Keeps routing and retry eligibility on one read of the canonical account/model owners. */ function prepareModelFallbackRateLimit(e, t) { const n = new Map(e.length > 1 ? e.map((e) => [e, readFallbackCandidateRateLimit({ ...t, candidate: e })]) : []); return { ...orderFallbackCandidatesByRateLimit(e, n), isFinalAttempt(e, t, r) { return !e.slice(t + 1).some((e) => !r.has(e.provider) && n.get(e)?.eligible !== false); } }; } /** Reads shared health only from routes and accounts the auth owner can already identify. */ function readFallbackCandidateRateLimit(e) { const { candidate: t, cfg: n, authStore: r } = e; try { const i = { provider: t.provider, modelId: t.model, cfg: n }; const a = normalizeConfiguredProviderModel({ ...i, providerConfig: resolveConfiguredProviderConfig(n, t.provider), discoveredModel: resolveBundledStaticCatalogModel(i), manifestAlias: resolveManifestModelCatalogProviderAliasMetadata(i) }); if (!a) return { eligible: true }; const o = e.resolveAgentHarnessRuntimeOverride?.(t.provider, t.model) ?? resolveAgentHarnessPolicy({ ...i, config: n, modelApi: a.api, modelBaseUrl: a.baseUrl, agentId: e.agentId, sessionKey: e.sessionKey }).runtime; if (o !== "openclaw" && o !== "auto") return { eligible: true }; const s = prepareAgentRuntimeAuth({ provider: t.provider, modelId: t.model, modelApi: a.api, modelBaseUrl: a.baseUrl, config: n, agentId: e.agentId, agentDir: e.agentDir, authProfileStore: r ?? { version: 1, profiles: {} }, sessionAuthProfileId: e.userLockedAuthProfileId, sessionAuthProfileSource: e.userLockedAuthProfileId ? "user" : void 0, allowTransientCooldownProbe: true, harnessId: "openclaw" }); const c = e.userLockedAuthProfileId ?? s.plan.forwardedAuthProfileId; if (t.routeOrigin !== "requested" && e.sessionId && isFallbackCandidateSkipped({ sessionId: e.sessionId, ...t, authScope: c })) return { eligible: false }; const l = s.attempts[0]; if (!l || l.kind === "profile" && r && isProfileInCooldown(r, l.profileId, void 0, t.model)) return { eligible: true }; let u = Infinity; const d = l.kind === "profile" ? r?.profiles[l.profileId] : void 0; const f = l.plan.credentialSource; const p = f?.kind === "direct" ? f.evidence : void 0; const m = d ? [d.type === "api_key" ? d.keyRef ? void 0 : d.key : d.type === "token" ? d.tokenRef ? void 0 : d.token : void 0] : p === "provider-config" || p === "environment" ? [resolveUsableCustomProviderApiKey({ cfg: n, provider: t.provider })?.apiKey, ...p === "environment" ? [resolveConfigAwareEnvApiKey(n, t.provider)?.apiKey] : []].filter((e) => Boolean(e)) : []; const h = l.plan.modelRoute; for (const e of m.length ? m : [void 0]) { const t = getProviderRateLimitState(h ? { ...a, baseUrl: h.baseUrl } : a, { apiKey: e && !isNonSecretApiKeyMarker(e) ? e : void 0 }); if (!t) return { eligible: true }; u = Math.min(u, t.retryAt); } return { eligible: true, ...Number.isFinite(u) ? { retryAt: u } : {} }; } catch (e) { return { eligible: !isFailoverError(e) }; } } //#endregion //#region src/agents/model-fallback-sticky.ts const IDLE_WINDOW_MS = 6e5; const HARD_CAP_MS = 18e5; const MAX_STICKY_SESSIONS = 1024; const log$1 = createSubsystemLogger("model-fallback"); const stickyFallbacks = resolveGlobalMap(Symbol.for("openclaw.stickyRateLimitFallbacks"), "close-and-restart"); function takeStickyRateLimitFallback(e, t) { const n = e.sessionId; if (e.stickyRateLimitFallback !== true || !n) return; const r = stickyFallbacks.get(n); stickyFallbacks.delete(n); const i = t.find((e) => e.routeOrigin === "requested"); const a = i ? modelKey(i.provider, i.model) : void 0; const o = Date.now(); const s = r && a === modelKey(r.requested.provider, r.requested.model) && o - r.lastUsedAtMs <= IDLE_WINDOW_MS && o - r.stuckAtMs <= HARD_CAP_MS ? t.findIndex((e) => modelKey(e.provider, e.model) === modelKey(r.fallback.provider, r.fallback.model)) : -1; const c = s > 0 ? t[s] : void 0; let l = t; let u; if (c && i) { u = { provider: i.provider, model: i.model, error: `Trying ${modelKey(c.provider, c.model)} first after a recent rate limit in this session`, reason: "rate_limit", code: MODEL_FALLBACK_SKIPPED_CODE }; l = [ c, ...t.slice(0, s), ...t.slice(s + 1) ]; log$1.info(`Session ${n}: trying sticky rate-limit fallback ${modelKey(c.provider, c.model)} before ${a}`); } return { candidates: l, /** Seeds the run's attempts: a skipped selected model keeps the fallback reason visible. */ attempts: u ? [u] : [], record(e, t) { const o = modelKey(e.provider, e.model); if (!i || o === a) return; const s = c && o === modelKey(c.provider, c.model); if (!s && !t.some((e) => e !== u && e.reason === "rate_limit" && modelKey(e.provider, e.model) === a)) return; const l = Date.now(); stickyFallbacks.delete(n); stickyFallbacks.set(n, { requested: { provider: i.provider, model: i.model }, fallback: { provider: e.provider, model: e.model }, stuckAtMs: s && r ? r.stuckAtMs : l, lastUsedAtMs: l }); pruneMapToMaxSize(stickyFallbacks, MAX_STICKY_SESSIONS); } }; } //#endregion //#region src/agents/model-fallback-runner.ts const log = createSubsystemLogger("model-fallback"); const modelFallbackAuthRuntimeLoader = createLazyImportLoader(() => import("./agents/auth-profiles.runtime.js")); function flushDeferredSessionSuspension(e) { const t = e.pending; if (!t) return; e.pending = void 0; suspendSession(t); } async function runWithModelFallback(e) { const t = {}; try { const n = await runWithModelFallbackInternal(e, t); if (n.outcome === "exhausted") flushDeferredSessionSuspension(t); return n; } catch (n) { if (!shouldDiscardDeferredSessionSuspension({ error: n, abortSignal: e.abortSignal })) flushDeferredSessionSuspension(t); throw n; } } async function runWithModelFallbackInternal(e, t) { const n = e.operatorAuthority; if (n) { assertAdmittedRunOperatorAuthority(n); n.assertCurrent(); } const r = resolveModelCandidateChain({ cfg: e.cfg, agentId: e.agentId, provider: e.provider, model: e.model, fallbacksOverride: e.fallbacksOverride, requestedRouteResolution: e.requestedRouteResolution, manifestPlugins: e.manifestPlugins }); const i = n?.modelPolicy; let a = i ? r.filter(i.allows) : r; if (i && a.length === 0) assertOperatorModelAllowed(n, void 0); const o = takeStickyRateLimitFallback(e, a); a = o?.candidates ?? a; await e.prepareCandidateChain?.(a); const s = e.userLockedAuthProfileId?.trim() || void 0; const c = !e.skipAuthProfileRuntime && e.cfg && (s || await hasAnyAuthProfileStoreSourceAsync(e.agentDir)) ? await modelFallbackAuthRuntimeLoader.load() : null; const l = c ? await c.ensureAuthProfileStoreAsync(e.agentDir, { profileId: s, externalCli: externalCliDiscoveryScoped({ config: e.cfg, allowKeychainPrompt: false, providerIds: a.map((e) => e.provider), ...s ? { profileIds: [s] } : {} }) }) : null; const u = prepareModelFallbackRateLimit(a, { ...e, authStore: l }); a = u.candidates; const d = [...o?.attempts ?? [], ...u.attempts]; const f = /* @__PURE__ */ new Map(); let p; let m = false; let h; let g; const _ = /* @__PURE__ */ new Set(); const v = /* @__PURE__ */ new Set(); const notifyFallbackStep = async (t) => { try { await e.onFallbackStep?.(t); } catch { log.warn("Model fallback observer failed; preserving execution outcome."); } }; const observeDecision = async (t) => { if (!e.onFallbackStep && !isModelFallbackDecisionLogEnabled()) return; const n = logModelFallbackDecision(t); if (n) await notifyFallbackStep(n); }; const observeFailedCandidate = async (t) => { if (!e.onFallbackStep && !isModelFallbackDecisionLogEnabled()) appendFailedCandidateAttempt(t); else { const e = recordFailedCandidateAttempt(t); if (e) await notifyFallbackStep(e); } if (e.sessionId && t.nextCandidate) { const n = describeFailoverError(t.error); emitFailoverEvent({ sessionId: e.sessionId, sessionKey: e.sessionKey, lane: e.lane, fromProvider: t.candidate.provider, fromModel: t.candidate.model, toProvider: t.nextCandidate.provider, toModel: t.nextCandidate.model, reason: n.reason ?? "unknown", cascadeDepth: t.attempt - 1, suspended: false }); } }; const y = a.length > 1; const b = a.find((e) => e.routeOrigin === "requested"); const x = { runId: e.runId, sessionId: e.sessionId, lane: e.lane }; const S = { ...x, requestedProvider: e.provider, requestedModel: e.model, fallbackConfigured: y }; for (let r = 0; r < a.length; r += 1) { const i = a.at(r); if (!i) throw new Error(`Missing model fallback candidate at index ${r}`); if (v.has(i.provider)) continue; const C = { provider: i.provider, model: i.model }; n?.assertCurrent(); if (n?.modelPolicy?.allows(C) === false) continue; const w = resolveNextFallbackCandidateIndex({ candidates: a, currentIndex: r, excludedProviders: v }); const T = a[w]; const E = T !== void 0; const D = await resolveModelFallbackCandidateHarnessAuthPrecheck({ cfg: e.cfg, agentId: e.agentId, sessionKey: e.sessionKey, resolveAgentHarnessRuntimeOverride: e.resolveAgentHarnessRuntimeOverride, prepareAgentHarnessRuntime: e.prepareAgentHarnessRuntime, skipAuthProfileRuntime: e.skipAuthProfileRuntime, ...i }); const O = i.routeOrigin === "requested"; const k = b !== void 0 && i.provider === b.provider && i.model === b.model; const A = { attempt: r + 1, total: a.length }; const j = { ...S, candidate: i, ...A, nextCandidate: T, isPrimary: O, requestedModelMatched: k }; const observeCandidateDecision = (e, t = {}) => observeDecision({ decision: e, ...j, ...t }); const pushSkippedAttempt = (e, t, n) => d.push({ ...C, error: e, reason: t, code: MODEL_FALLBACK_SKIPPED_CODE, authMode: n }); const recordFailure = async (t, n) => { await observeFailedCandidate({ attempts: d, ...j, error: t, nextCandidate: n }); await e.onError?.({ ...C, error: t, ...A }); }; let M; let N = false; let P = false; if (c && l) { P = s !== void 0 && c.resolveAuthProfileEligibility({ cfg: e.cfg, store: l, provider: i.provider, profileId: s, includePendingOAuthRefresh: true }).eligible; let t = c.resolveAuthProfileOrder({ cfg: e.cfg, store: l, provider: i.provider, forModel: i.model, includePendingOAuthRefresh: true }); if (P && s) t = [.../* @__PURE__ */ new Set([s, ...t])]; N = (await c.maybeReprobeWhamBlockedProfiles({ store: l, profileIds: t, agentDir: e.agentDir, cfg: e.cfg, forModel: i.model }))?.requiresAuthPreparation === true; if (!D.skipsProviderAuthCooldown) { M = t; f.set(i, M); } } const F = resolveFallbackAuthScope({ userLockedAuthProfileId: P ? s : void 0, profileIds: M }); if (!O && e.sessionId) { if (isFallbackCandidateSkipped({ sessionId: e.sessionId, ...C, authScope: F })) { const t = getFallbackCandidateSkipReason({ sessionId: e.sessionId, ...C, authScope: F }) ?? "auth"; const n = buildProviderReauthCommand(i.provider); const r = n ? `run \`${n}\` to re-authenticate` : "re-authenticate that provider"; const a = `Skipping ${i.provider}/${i.model}: recent ${t} failure in this session (${r})`; pushSkippedAttempt(a, t); await observeCandidateDecision("skip_candidate", { reason: t, error: a }); continue; } } let I; let L = false; let R = null; if (c && l && M && !N && !D.skipsProviderAuthCooldown) { const n = M; const r = n.some((e) => !c.isProfileInCooldown(l, e, void 0, i.model)); if (n.length > 0 && !r) { const r = Date.now(); const a = resolveProbeThrottleKey(i.provider, e.agentDir); const o = resolveCooldownDecision({ candidate: i, isPrimary: O, requestedModel: k, hasFallbackCandidates: y, now: r, probeThrottleKey: a, authRuntime: c, authStore: l, profileIds: n }); const s = o.reason === "billing" || o.reason === "auth" || o.reason === "auth_permanent" || o.reason === "session_expired" ? resolveSubscriptionAuthModeForProfiles({ store: l, profileIds: n }) : void 0; if (o.type !== "attempt") { const r = o.type === "skip" ? o.error : `Provider ${i.provider} is in cooldown`; pushSkippedAttempt(r, o.reason, s); if (o.type === "suspend_session" && e.sessionId) { emitFailoverEvent({ sessionId: e.sessionId, lane: e.lane, fromProvider: i.provider, fromModel: i.model, reason: o.reason, suspended: !E }); if (!E) { t.pending = void 0; suspendSession({ cfg: e.cfg, agentId: e.agentId, agentDir: e.agentDir, sessionId: e.sessionId, reason: resolveSessionSuspensionReason(o.reason), failedProvider: i.provider, failedModel: i.model }); } } await observeCandidateDecision("skip_candidate", { reason: o.reason, error: r, profileCount: n.length }); continue; } if (o.markProbe) markProbeAttempt(r, a); if (shouldAllowCooldownProbeForReason(o.reason)) { const e = shouldUseTransientCooldownProbeSlot(o.reason); if (e && _.has(i.provider)) { const e = `Provider ${i.provider} is in cooldown (check already attempted this run)`; pushSkippedAttempt(e, o.reason, s); await observeCandidateDecision("skip_candidate", { reason: o.reason, error: e, profileCount: n.length }); continue; } I = { allowTransientCooldownProbe: true }; if (e) R = i.provider; } L = true; await observeCandidateDecision("probe_cooldown_candidate", { reason: o.reason, allowTransientCooldownProbe: I?.allowTransientCooldownProbe, profileCount: n.length }); } } n?.assertCurrent(); if (n?.modelPolicy?.allows(C) === false) continue; const z = await runFallbackAttempt({ run: e.run, ...i, attempts: d, captureHarnessPreflight: true, options: { ...I, isFinalFallbackAttempt: u.isFinalAttempt(a, r, v), modelRoutingProvenance: { requestedProvider: e.provider, requestedModel: e.model, stage: O ? "initial" : "fallback", selectionChanged: m, fallbackReason: O ? void 0 : d.at(-1)?.reason } }, deferSessionSuspension: E, onDeferredSessionSuspension: (e) => { t.pending = e; }, classifyResult: e.classifyResult, ...A, attribution: x, abortSignal: e.abortSignal }); if ("success" in z) { if (!z.stopped && !m) o?.record(i, d); if (!z.stopped && (r > 0 || d.length > 0 || L)) await observeCandidateDecision("candidate_succeeded", { previousAttempts: d }); return z.success; } const B = z.error; if (isAgentHarnessPreflightError(B)) { const t = resolveHarnessPreflightFallbackIndex({ error: B, candidates: a, currentIndex: r, excludedProviders: v, runtime: { cfg: e.cfg, agentId: e.agentId, sessionKey: e.sessionKey, resolveAgentHarnessRuntimeOverride: e.resolveAgentHarnessRuntimeOverride } }); const n = t === void 0 ? void 0 : a[t]; if (t === void 0 || !n) throw B; p = B; await recordFailure(B, n); r = t - 1; continue; } if (!z.classifiedResult && e.canFallbackAfterError && !await e.canFallbackAfterError({ ...C, error: B, ...A })) throw B; if (z.classifiedResult) h = z.classifiedResult; if (z.exhaustionResult && (!g || z.exhaustionResult.priority >= g.priority)) g = z.exhaustionResult; if (isNonProviderRuntimeCoordinationError(B) || isTranscriptNotContinuableError(B)) throw B; if (R) { const e = describeFailoverError(B).reason; if (!shouldPreserveTransientCooldownProbeSlot(e)) _.add(R); } if (isMissingAgentHarnessError(B)) throw B; const V = { ...C, ...x }; const H = coerceToFailoverError(B, V) ?? (isLikelyContextOverflowError(formatErrorMessage(B)) ? new FailoverError(formatErrorMessage(B), { reason: "context_overflow", ...V, cause: B }) : B); if (B instanceof LiveSessionModelSwitchError) { m = true; if (hasDifferentLiveSessionRuntimeSelection({ error: B, currentAgentHarnessRuntimeOverride: D.agentHarnessRuntimeOverride })) throw B; const e = resolveLiveSessionModelSwitchRedirectIndex({ error: B, candidates: a, currentIndex: r }); if (e !== null) { r = e - 1; continue; } const t = B.message; const n = new FailoverError(t, { reason: "unknown", ...C, ...x }); p = n; await observeFailedCandidate({ attempts: d, ...j, error: n }); continue; } const U = isFailoverError(H); if (!U && !E) throw B; if (U && !O && e.sessionId && (H.reason === "auth" || H.reason === "auth_permanent")) markFallbackCandidateSkipped({ sessionId: e.sessionId, ...C, authScope: H.profileId?.trim() || F, reason: H.reason }); if (U && H.reason === "tls_certificate") v.add(i.provider); a = preferContextFitFallbackCandidates({ candidates: a, failedIndex: r, error: H, cfg: e.cfg }); const W = resolveNextFallbackCandidateIndex({ candidates: a, currentIndex: r, excludedProviders: v }); p = H; await recordFailure(H, a[W]); if (W > r + 1) r = W - 1; } if (g) { const t = h && e.mergeExhaustedResult ? { ...h, result: e.mergeExhaustedResult({ latestResult: h.result, preferredResult: g.result }) } : g; return { outcome: "exhausted", result: t.result, provider: t.provider, model: t.model, attempts: d }; } if (n?.modelPolicy && d.length === 0) assertOperatorModelAllowed(n, void 0); return throwFallbackFailureSummary({ attempts: d, candidates: a, lastError: p, label: "models", formatAttempt: (e) => `${e.provider}/${e.model}: ${e.error}${e.reason ? ` (${e.reason})` : ""}`, soonestCooldownExpiry: await resolveFallbackSoonestCooldownExpiry({ authRuntime: c, userLockedAuthProfileId: s, agentDir: e.agentDir, cfg: e.cfg, profileIdsByCandidate: f }), attribution: { sessionId: e.sessionId, lane: e.lane }, cfg: e.cfg, agentId: e.agentId, agentDir: e.agentDir }); } //#endregion export { MODEL_FALLBACK_SKIPPED_CODE as n, runWithModelFallback as t };