UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

522 lines (521 loc) • 21.5 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import "./model-ref-shared-DqE2RqZv.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { a as normalizeOptionalAgentRuntimeId, r as isDefaultAgentRuntimeId } from "./agent-runtime-id-D8s1CaYB.mjs"; import { r as modelKey } from "./provider-registry-index-DhPtwFh_.mjs"; import { n as findAgentRunTerminalOutcome } from "./agent-run-terminal-error-CbmFnPGI.mjs"; import { i as FailoverError, u as isFailoverError } from "./error-BCRqSFIY.mjs"; import { d as isAgentRunSupersededAbortReason, f as isSessionPlacementSettlementClosedError, l as isAgentRunDirectAbortReason, u as isAgentRunRestartAbortReason } from "./run-termination-0Ig0-bk6.mjs"; import { i as MissingAgentHarnessError, l as resolveAgentHarnessPreflightOwner, o as isAgentHarnessPreflightError } from "./errors-0Ou7CzqA.mjs"; import { n as renewAgentRunDeadline } from "./agent-run-deadline-DbHYb3rG.mjs"; import { t as resolveAgentHarnessPolicy } from "./policy-DzaOuofI.mjs"; import { n as getRegisteredAgentHarness } from "./registry-ubpieJjd.mjs"; import { t as isCliProvider } from "./model-selection-cli-CkH04Wst.mjs"; import { r as isCliRuntimeAlias } from "./model-runtime-aliases-DZy9Ea2c.mjs"; import { r as externalCliDiscoveryForProviders } from "./external-cli-discovery-DZ419koV.mjs"; import { n as isLikelyContextOverflowError } from "./context-overflow-C7ex88b9.mjs"; import "./classify-o7Whl-By.mjs"; import { i as describeFailoverError, m as resolveModelFallbackError, s as hasModelFallbackStop, t as buildFailoverRemediationHint } from "./failover-error-CbIiC30n.mjs"; import { a as runWithDeferredSessionSuspension, o as suspendSession } from "./session-suspension-DpEUvu5N.mjs"; import { o as isCommandLaneTaskTimeoutError } from "./command-queue-BenRlAaO.mjs"; import { i as TRANSCRIPT_NOT_CONTINUABLE_ERROR_CODE } from "./errors-D_CW6sfd.mjs"; import { n as isSandboxProvisioningError } from "./provisioning-error-19aGMcmG.mjs"; import { r as isCronTerminalAbortReasonText } from "./execution-errors-aeOsnaMY.mjs"; import { i as isOpenClawAbortableWrapper } from "./abortable-z1NE23aa.mjs"; import { n as buildTextObservationFields } from "./embedded-agent-error-observation-CgMe33_n.mjs"; //#region src/agents/model-fallback-observation.ts const decisionLog = createSubsystemLogger("model-fallback").child("decision"); const AUTH_DECISION_LOG_COALESCE_WINDOW_MS = 3e4; const AUTH_DECISION_LOG_COALESCE_MAX_ENTRIES = 100; /** Return whether fallback decision logging is enabled for warn-level events. */ function isModelFallbackDecisionLogEnabled() { return decisionLog.isEnabled("warn"); } function buildErrorObservationFields(e) { return { errorHash: e.textHash, errorFingerprint: e.textFingerprint, httpCode: e.httpCode, providerErrorType: e.providerErrorType, requestIdHash: e.requestIdHash }; } const authDecisionLogCoalesceEntries = /* @__PURE__ */ new Map(); function formatModelRef(e) { return `${e.provider}/${e.model}`; } function resolveAuthDecisionLogCoalescing(e, t) { if (e.decision !== "candidate_failed" && e.decision !== "skip_candidate" || e.reason !== "auth" && e.reason !== "auth_permanent") return { shouldLog: true }; const n = Date.now(); const r = JSON.stringify([ e.sessionId ?? e.runId, e.lane, e.requestedProvider, e.requestedModel, e.decision, e.candidate.provider, e.candidate.model, e.candidate.routeOrigin, e.candidate.routeResolution, e.attempt, e.total, e.reason, e.status, e.code, t.httpCode, t.providerErrorType, t.errorFingerprint ?? t.errorHash, e.nextCandidate ? formatModelRef(e.nextCandidate) : null, e.nextCandidate ? e.nextCandidate.routeOrigin : null, e.nextCandidate ? e.nextCandidate.routeResolution : null, e.isPrimary, e.requestedModelMatched, e.fallbackConfigured ]); const i = authDecisionLogCoalesceEntries.get(r); const a = i ? n - i.lastLoggedAt : Infinity; if (i && a < AUTH_DECISION_LOG_COALESCE_WINDOW_MS) { i.suppressed += 1; return { shouldLog: false }; } const o = AUTH_DECISION_LOG_COALESCE_WINDOW_MS * 2; const s = a < o ? i?.suppressed : void 0; if (a >= o) { authDecisionLogCoalesceEntries.delete(r); for (const [e, t] of authDecisionLogCoalesceEntries) if (t.lastLoggedAt < n - o) authDecisionLogCoalesceEntries.delete(e); if (authDecisionLogCoalesceEntries.size >= AUTH_DECISION_LOG_COALESCE_MAX_ENTRIES) { let e; let t = Infinity; for (const [n, r] of authDecisionLogCoalesceEntries) if (r.lastLoggedAt < t) { t = r.lastLoggedAt; e = n; } if (e !== void 0) authDecisionLogCoalesceEntries.delete(e); } } authDecisionLogCoalesceEntries.set(r, { lastLoggedAt: n, suppressed: 0 }); return { shouldLog: true, suppressedDuplicateCount: s }; } function buildFallbackStepFields(e, t) { if (e.decision === "probe_cooldown_candidate") return; const n = e.decision === "candidate_succeeded"; const r = n ? e.previousAttempts?.at(-1) : void 0; if (n && !r) return; const i = r ?? e.candidate; const a = n ? e.candidate : e.nextCandidate; const o = n ? r?.reason : e.reason; const s = n ? r?.error : t; return { fallbackStepType: "fallback_step", fallbackStepFromModel: formatModelRef(i), ...a ? { fallbackStepToModel: formatModelRef(a) } : {}, ...o ? { fallbackStepFromFailureReason: o } : {}, ...s ? { fallbackStepFromFailureDetail: s } : {}, ...e.attempt !== void 0 ? { fallbackStepChainPosition: e.attempt } : {}, fallbackStepFinalOutcome: n ? "succeeded" : e.nextCandidate ? "next_fallback" : "chain_exhausted" }; } function logModelFallbackDecision(e) { const t = e.decision === "candidate_succeeded" ? e.previousAttempts?.find((e) => e.reason === "context_overflow" || e.reason === "model_not_found") : void 0; if (t) { const n = t.reason === "context_overflow" ? "exceeded its context window" : "not found"; decisionLog.warn(`Model "${sanitizeForLog(formatModelRef(t))}" ${n}. Fell back to "${sanitizeForLog(formatModelRef(e.candidate))}".`); } const n = e.nextCandidate ? `${sanitizeForLog(e.nextCandidate.provider)}/${sanitizeForLog(e.nextCandidate.model)}` : "none"; const r = e.reason ?? "unknown"; const i = buildTextObservationFields(e.error); const a = buildErrorObservationFields(i); const o = buildFallbackStepFields(e, i.providerErrorMessagePreview ?? i.textPreview); const s = a.providerErrorType ? ` providerErrorType=${sanitizeForLog(a.providerErrorType)}` : ""; const c = resolveAuthDecisionLogCoalescing(e, a); if (!c.shouldLog) return o; const l = c.suppressedDuplicateCount ?? 0; const u = l > 0 ? ` (${l} duplicates suppressed in last ${AUTH_DECISION_LOG_COALESCE_WINDOW_MS / 1e3}s)` : ""; decisionLog.warn("model fallback decision", { event: "model_fallback_decision", tags: [ "error_handling", "model_fallback", e.decision ], runId: e.runId, sessionId: e.sessionId, lane: e.lane, decision: e.decision, requestedProvider: e.requestedProvider, requestedModel: e.requestedModel, candidateProvider: e.candidate.provider, candidateModel: e.candidate.model, candidateRouteOrigin: e.candidate.routeOrigin, candidateRouteResolution: e.candidate.routeResolution, attempt: e.attempt, total: e.total, reason: e.reason, status: e.status, code: e.code, ...a, ...o ? { fallbackStepType: o.fallbackStepType, fallbackStepFromModel: o.fallbackStepFromModel, fallbackStepToModel: o.fallbackStepToModel, fallbackStepFromFailureReason: o.fallbackStepFromFailureReason, fallbackStepChainPosition: o.fallbackStepChainPosition, fallbackStepFinalOutcome: o.fallbackStepFinalOutcome } : {}, nextCandidateProvider: e.nextCandidate?.provider, nextCandidateModel: e.nextCandidate?.model, nextCandidateRouteOrigin: e.nextCandidate?.routeOrigin, nextCandidateRouteResolution: e.nextCandidate?.routeResolution, isPrimary: e.isPrimary, requestedModelMatched: e.requestedModelMatched, fallbackConfigured: e.fallbackConfigured, allowTransientCooldownProbe: e.allowTransientCooldownProbe, profileCount: e.profileCount, ...l > 0 ? { suppressedDuplicateCount: l } : {}, previousAttempts: e.previousAttempts?.map((e) => ({ provider: e.provider, model: e.model, reason: e.reason, status: e.status, code: e.code, ...buildErrorObservationFields(buildTextObservationFields(e.error)) })), consoleMessage: `model fallback decision: decision=${e.decision} requested=${sanitizeForLog(e.requestedProvider)}/${sanitizeForLog(e.requestedModel)} candidate=${sanitizeForLog(e.candidate.provider)}/${sanitizeForLog(e.candidate.model)} reason=${r}${s} next=${n}${u}` }); return o; } /** Record a local or terminal stop separately from provider-failure decisions. */ function logModelFallbackChainStopped(e) { if (!decisionLog.isEnabled("warn")) return; let t; try { const n = e.error instanceof Error ? e.error.name : void 0; t = typeof n === "string" && n ? n : void 0; } catch {} decisionLog.warn("model fallback chain stopped", { event: "model_fallback_chain_stopped", tags: [ "error_handling", "model_fallback", "chain_stopped" ], sessionId: e.sessionId, lane: e.lane, reason: e.reason, candidateProvider: e.provider, candidateModel: e.model, errorName: t, consoleMessage: `model fallback chain stopped: reason=${e.reason} candidate=${sanitizeForLog(e.provider)}/${sanitizeForLog(e.model)}` + (t ? ` errorName=${sanitizeForLog(t)}` : "") }); } //#endregion //#region src/agents/model-fallback-attempt.ts function isFallbackSummaryError(e) { return isFailoverError(e) && Array.isArray(e.attempts) && e.soonestCooldownExpiry !== void 0; } function resolveFallbackAuthScope(e) { return e.userLockedAuthProfileId || e.profileIds?.find((e) => e.trim())?.trim(); } function isTranscriptNotContinuableError(e) { return Boolean(e) && typeof e === "object" && e.code === "openclaw_transcript_not_continuable"; } function isTerminalAbortCandidate(e) { if (typeof e === "string") return isCronTerminalAbortReasonText(e); if (!(e instanceof Error)) return false; return isAgentRunRestartAbortReason(e) || e.name === "TimeoutError" || e.name === "ClientDisconnectError" || isCronTerminalAbortReasonText(e.message); } function isTerminalAbortFromError(e) { if (!(e instanceof Error)) return false; if (isAgentRunRestartAbortReason(e)) return true; if (e.name !== "AbortError") return false; const t = [e.cause, e.cause instanceof Error ? e.cause.cause : void 0]; if (t.some(isAgentRunRestartAbortReason)) return true; return isOpenClawAbortableWrapper(e) && t.some(isTerminalAbortCandidate); } /** Preserve stop precedence while naming the first matching condition. */ function resolveChainStopReason(e) { const { err: t } = e; if (findAgentRunTerminalOutcome(t)?.status === "timeout") return "agent_run_terminal_timeout"; if (isCommandLaneTaskTimeoutError(t)) return "command_lane_task_timeout"; if (e.harnessPreflight && !e.captureHarnessPreflight) return "agent_harness_preflight"; if (isSandboxProvisioningError(t)) return "sandbox_provisioning"; if (e.callerSignalAborted) return "caller_signal_aborted"; if (isAgentRunDirectAbortReason(t)) return "agent_run_direct_abort"; if (isAgentRunRestartAbortReason(t)) return "agent_run_restart_abort"; return isAgentRunSupersededAbortReason(t) ? "agent_run_superseded_abort" : isSessionPlacementSettlementClosedError(t) ? "session_placement_settlement_closed" : isTerminalAbortFromError(t) ? "terminal_abort_wrapper" : void 0; } async function runFallbackAttempt(e) { if (e.attempt > 1) { e.abortSignal?.throwIfAborted(); renewAgentRunDeadline(e.attribution?.runId); } let t; try { const run = () => e.options ? e.run(e.provider, e.model, e.options) : e.run(e.provider, e.model); t = e.deferSessionSuspension ? await runWithDeferredSessionSuspension(run, e.onDeferredSessionSuspension) : await run(); } catch (t) { const n = isAgentHarnessPreflightError(t); const r = resolveChainStopReason({ err: t, harnessPreflight: n, captureHarnessPreflight: e.captureHarnessPreflight, callerSignalAborted: e.abortSignal?.aborted === true }); if (r) { logModelFallbackChainStopped({ reason: r, provider: e.provider, model: e.model, sessionId: e.attribution?.sessionId, lane: e.attribution?.lane, error: t }); throw t; } let i = t; if (!n) { const n = resolveModelFallbackError(t, { provider: e.provider, model: e.model, sessionId: e.attribution?.sessionId, lane: e.attribution?.lane }); if (n.kind === "coordination") throw t; i = n.error; } if (hasModelFallbackStop(i)) throw i; return { error: i }; } const n = await e.classifyResult?.({ result: t, provider: e.provider, model: e.model, attempt: e.attempt, total: e.total }); const r = resolveResultClassificationError(n, e); if (r && e.abortSignal?.aborted) throw toErrorObject(r, "Non-Error thrown"); if (hasModelFallbackStop(r)) throw r; const buildClassifiedResult = () => ({ result: t, provider: e.provider, model: e.model }); if (!r) { const t = n && "stopReason" in n ? n.stopReason : void 0; if (t && e.total > 1) logModelFallbackChainStopped({ reason: t, provider: e.provider, model: e.model, ...e.attribution }); return { ...t ? { stopped: true } : {}, success: { outcome: "completed", ...buildClassifiedResult(), attempts: e.attempts } }; } const i = n && "preserveResultOnExhaustion" in n && n.preserveResultOnExhaustion === true; return { error: r, classifiedResult: buildClassifiedResult(), ...i ? { exhaustionResult: { ...buildClassifiedResult(), priority: n.preserveResultPriority ?? 0 } } : {} }; } function resolveResultClassificationError(e, t) { if (!e || "stopReason" in e) return null; if ("error" in e) return e.error; const n = normalizeOptionalString(e.message); return n ? new FailoverError(n, { reason: e.reason ?? "unknown", provider: t.provider, model: t.model, sessionId: t.attribution?.sessionId, lane: t.attribution?.lane, status: e.status, code: e.code, rawError: e.rawError, rateLimitRetriesExhausted: e.rateLimitRetriesExhausted }) : null; } function resolveNextFallbackCandidateIndex(e) { for (let t = e.currentIndex + 1; t < e.candidates.length; t += 1) { const n = e.candidates[t]; if (n && !e.excludedProviders.has(n.provider)) return t; } return e.candidates.length; } /** Index of the next candidate that will not repeat a harness-local preflight failure, or undefined when the error is chain-global or none remains. */ function resolveHarnessPreflightFallbackIndex(e) { const t = resolveAgentHarnessPreflightOwner(e.error); if (!t) return; for (let n = e.currentIndex + 1; n < e.candidates.length; n += 1) { const r = e.candidates[n]; if (!r || e.excludedProviders.has(r.provider)) continue; if (resolveModelFallbackCandidateAgentRuntime({ ...e.runtime, ...r }).runtime !== t) return n; } } async function resolveModelFallbackCandidateHarnessAuthPrecheck(e) { const { agentHarnessRuntimeOverride: t, explicitAgentRuntime: n, runtime: r, runtimeSource: i } = resolveModelFallbackCandidateAgentRuntime(e); const result = (e) => ({ skipsProviderAuthCooldown: e, agentHarnessRuntimeOverride: t }); if (!e.cfg || e.skipAuthProfileRuntime) return result(false); if (!n && isCliProvider(e.provider, e.cfg)) return result(true); if (!r) return result(false); if (r === "openclaw" || r === "auto" || r === "codex" && i === "implicit") return result(false); await e.prepareAgentHarnessRuntime?.({ provider: e.provider, model: e.model, agentHarnessRuntimeOverride: t }); if (getRegisteredAgentHarness(r)) return result(true); const a = normalizeOptionalString(r); if (a && (isCliRuntimeAlias(a) || isCliProvider(a, e.cfg))) return result(true); throw new MissingAgentHarnessError(r); } function resolveModelFallbackCandidateAgentRuntime(e) { const t = e.resolveAgentHarnessRuntimeOverride?.(e.provider, e.model); const n = normalizeOptionalAgentRuntimeId(t); const r = n && !isDefaultAgentRuntimeId(n) ? n : void 0; if (!e.cfg) return { agentHarnessRuntimeOverride: t, explicitAgentRuntime: r, runtime: r }; const i = resolveAgentHarnessPolicy({ provider: e.provider, modelId: e.model, config: e.cfg, agentId: e.agentId, sessionKey: e.sessionKey }); return { agentHarnessRuntimeOverride: t, explicitAgentRuntime: r, runtime: r ?? i.runtime, runtimeSource: r ? "model" : i.runtimeSource }; } function buildFailedCandidateAttempt(e, t) { return { provider: e.provider, model: e.model, error: t.rawError && (!t.provider || t.provider === e.provider && (!t.model || t.model === e.model)) ? t.rawError : t.message, reason: t.reason ?? "unknown", rateLimitRetriesExhausted: t.rateLimitRetriesExhausted, authMode: t.authMode, status: t.status, code: t.code }; } function recordFailedCandidateAttempt(e) { const { attempts: t, error: n, ...r } = e; const i = describeFailoverError(n); const a = buildFailedCandidateAttempt(e.candidate, i); t.push(a); return logModelFallbackDecision({ ...r, decision: "candidate_failed", requestedProvider: e.requestedProvider ?? e.candidate.provider, requestedModel: e.requestedModel ?? e.candidate.model, reason: i.reason, status: i.status, code: i.code, error: a.error }); } function appendFailedCandidateAttempt(e) { const t = describeFailoverError(e.error); e.attempts.push(buildFailedCandidateAttempt(e.candidate, t)); } function resolveLiveSessionModelSwitchRedirectIndex(e) { const t = modelKey(e.error.provider, e.error.model); const n = e.candidates.findIndex((e) => modelKey(e.provider, e.model) === t); if (n === -1) throw e.error; return n > e.currentIndex ? n : null; } function hasDifferentLiveSessionRuntimeSelection(e) { const normalizeRuntime = (e) => { const t = normalizeOptionalAgentRuntimeId(e); return t && !isDefaultAgentRuntimeId(t) ? t : void 0; }; return normalizeRuntime(e.currentAgentHarnessRuntimeOverride) !== normalizeRuntime(e.error.agentRuntimeOverride); } function throwFallbackFailureSummary(e) { if (e.attempts.length <= 1 && e.lastError) throw toErrorObject(e.lastError, "Non-Error thrown"); if (e.attribution?.sessionId) suspendSession({ cfg: e.cfg, agentId: e.agentId, agentDir: e.agentDir, sessionId: e.attribution.sessionId, reason: "circuit_open", failedProvider: e.attempts.at(-1)?.provider ?? "unknown", failedModel: e.attempts.at(-1)?.model ?? "unknown" }); const t = e.attempts.length > 0 ? e.attempts.map(e.formatAttempt).join(" | ") : "unknown"; const n = buildFailoverRemediationHint(e.lastError); const r = `All ${e.label} failed (${e.attempts.length || e.candidates.length}): ${t}${n ? `. ${n}` : ""}`; const i = e.attempts.map((e) => ({ ...e, reason: e.reason ?? "unknown" })); const a = i.at(-1); throw new FailoverError(r, { reason: a?.reason ?? "unknown", provider: a?.provider, model: a?.model, authMode: a?.authMode, status: a?.status, rateLimitRetriesExhausted: a?.rateLimitRetriesExhausted, code: a?.code, cause: e.lastError instanceof Error ? e.lastError : void 0, sessionId: e.attribution?.sessionId, lane: e.attribution?.lane, attempts: i, soonestCooldownExpiry: e.soonestCooldownExpiry ?? null }); } async function resolveFallbackSoonestCooldownExpiry(e) { if (!e.authRuntime || e.profileIdsByCandidate.size === 0) return null; const t = await e.authRuntime.loadAuthProfileStoreForRuntimeAsync(e.agentDir, { readOnly: true, profileId: e.userLockedAuthProfileId, externalCli: externalCliDiscoveryForProviders({ cfg: e.cfg, providers: [...e.profileIdsByCandidate.keys()].map((e) => e.provider) }) }); let n = null; for (const [r, i] of e.profileIdsByCandidate) { const a = e.authRuntime.getSoonestCooldownExpiry(t, i, { forModel: r.model }); if (a !== null && (n === null || a < n)) n = a; } return n; } function shouldDiscardDeferredSessionSuspension(e) { if (e.abortSignal?.aborted || findAgentRunTerminalOutcome(e.error)?.status === "timeout" || isAgentRunDirectAbortReason(e.error) || isAgentRunRestartAbortReason(e.error) || isAgentRunSupersededAbortReason(e.error) || isSessionPlacementSettlementClosedError(e.error) || isTerminalAbortFromError(e.error) || isCommandLaneTaskTimeoutError(e.error)) return true; const t = resolveModelFallbackError(e.error); return t.kind === "coordination" || t.kind !== "terminal" && (isTranscriptNotContinuableError(e.error) || isLikelyContextOverflowError(formatErrorMessage(e.error))); } //#endregion export { recordFailedCandidateAttempt as a, resolveHarnessPreflightFallbackIndex as c, resolveNextFallbackCandidateIndex as d, runFallbackAttempt as f, logModelFallbackDecision as g, isModelFallbackDecisionLogEnabled as h, isTranscriptNotContinuableError as i, resolveLiveSessionModelSwitchRedirectIndex as l, throwFallbackFailureSummary as m, hasDifferentLiveSessionRuntimeSelection as n, resolveFallbackAuthScope as o, shouldDiscardDeferredSessionSuspension as p, isFallbackSummaryError as r, resolveFallbackSoonestCooldownExpiry as s, appendFailedCandidateAttempt as t, resolveModelFallbackCandidateHarnessAuthPrecheck as u };