UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

420 lines (419 loc) • 17.4 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { E as parseStrictNonNegativeInteger } from "./number-coercion-D6u-4YD8.mjs"; import { i as asOptionalObjectRecord, p as readStringField } from "./record-coerce-CVPuDqcc.mjs"; import { d as readErrorName, r as collectErrorGraphCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { n as containsAsciiControlCharacter } from "./string-normalization-DLmfYZXI.mjs"; import "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { i as isLocalStorageOutcomeError } from "./sqlite-error-diagnostics-6_hREUnq.mjs"; import { i as isSqliteTranscriptMutationConflict } from "./session-mutation-conflict-error-DsnM4Ef8.mjs"; import { r as isAgentRunStaleLifecycleError } from "./agent-lifecycle-error-C4eSNOaP.mjs"; import { v as resolveExecutionApprovalFailureMessage } from "./message-patterns-xrpp7Aip.mjs"; import { f as isTimeoutError, i as FailoverError, m as readDirectErrorMessage, p as readDirectErrorCode, s as findErrorProperty, u as isFailoverError } from "./error-BCRqSFIY.mjs"; import { d as isAgentRunSupersededAbortReason, f as isSessionPlacementSettlementClosedError } from "./run-termination-0Ig0-bk6.mjs"; import { C as renderRateLimitRetryExhaustion } from "./user-copy-DFvWpx47.mjs"; import { a as failoverReasonFromClassification, d as isUnclassifiedNoBodyHttpSignal } from "./classification-rules-DfXxEGkP.mjs"; import { t as extractFailoverSignalDetails } from "./signal-details-D8xKpbDw.mjs"; import { o as isAgentHarnessPreflightError, r as AgentHarnessSessionSupersededError } from "./errors-0Ou7CzqA.mjs"; import { a as isSessionWorkStartInvalidatedError } from "./work-start-error-DaHE71YG.mjs"; import { t as isRecordedModelFallbackStop } from "./model-fallback-stop-BN_k3Te_.mjs"; import { n as copyErrorDiagnostic } from "./error-diagnostics-CD3FocGA.mjs"; import { t as PreparedModelRuntimeOwnerNotPublishedError } from "./prepared-model-runtime-admission-errors-LxrcCg4d.mjs"; import { s as isChannelRunAuthorizationError } from "./host-context-builder-BXWPIn7b.mjs"; import "./prepared-model-runtime.errors-BRsU9-dm.mjs"; import { t as SkillResourceDeliveryLimitError } from "./resource-delivery-error-CFKvWByr.mjs"; import { n as classifyFailoverSignal } from "./classify-o7Whl-By.mjs"; import { n as findLocalWorkerTaskFailure } from "./local-preparation-error-DZuxVfQu.mjs"; import { t as isSessionTranscriptTurnMismatchErrorMessage } from "./transcript-turn-error-yJQy4oFe.mjs"; //#region src/agents/failover-error.ts const MAX_FAILOVER_CAUSE_DEPTH = 25; const MISSING_TOOL_RESULT_REASON = "missing_tool_result"; const MISSING_TOOL_RESULT_TEXT_RE = /native Codex tool\.call without a matching tool\.result/i; const RUNTIME_COORDINATION_ERROR_NAMES = /* @__PURE__ */ new Set([ "CodexNodeExecServerDisconnectedError", "GatewayDrainingError", "NodeRunnerUpdateRequiredError", "WorkerRunnerUnavailableError", "WorkerRunnerCapacityError", "WorkerWorkspaceReconciliationError", "ActiveTurnClaimError", "CliHistoryOwnerChangedError", "SessionEntryChangedDuringReadError", "SessionTranscriptReadFenceError", "SqliteWorkerError", "SessionCapabilityMetadataChangedError", "SessionDeliveryGenerationUnavailableError", "SessionDeliveryGenerationRevokedError" ]); function hasRecordedModelFallbackStop(e) { return collectErrorGraphCandidates(e, resolveNestedErrors).some(isRecordedModelFallbackStop); } function hasModelFallbackStop(e) { return isSessionPlacementSettlementClosedError(e) || isAgentRunSupersededAbortReason(e) || collectErrorGraphCandidates(e, resolveNestedErrors).some((e) => isRecordedModelFallbackStop(e) || isSessionTranscriptTurnMismatchErrorMessage(readDirectErrorMessage(e)) || isFailoverError(e) && isCliTerminalStopCode(e.code)); } function resolveNestedErrors(e) { const t = e.errors; const n = [ e.error, e.cause, ...Array.isArray(t) ? t : [] ]; try { n.push(e.suppressed); } catch {} return n; } function findCliFailoverError(e, t, n) { const r = isFailoverError(e) ? t(e) : void 0; if (r) return r; if (!e || typeof e !== "object" || n.has(e)) return; n.add(e); for (const r of resolveNestedErrors(e)) { const e = findCliFailoverError(r, t, n); if (e) return e; } } const CLI_TERMINAL_STOP_CODES = /* @__PURE__ */ new Set(["cli_max_turns", "cli_turn_stopped"]); function isCliTerminalStopCode(e) { return e !== void 0 && CLI_TERMINAL_STOP_CODES.has(e); } function findCliTerminalStopError(e) { return findCliFailoverError(e, (e) => isCliTerminalStopCode(e.code) ? e : void 0, /* @__PURE__ */ new Set()); } function hasCliTimeoutContext(e) { const t = e.cliTimeout; return Boolean(t && (t.mode === "overall" || t.mode === "no-output") && Number.isFinite(t.timeoutSeconds) && t.timeoutSeconds >= 0 && typeof t.observedActivity === "boolean" && Number.isInteger(t.activeToolCount) && t.activeToolCount >= 0 && Number.isInteger(t.backgroundTaskCount) && t.backgroundTaskCount >= 0); } function findCliTimeoutError(e) { return findCliFailoverError(e, (e) => hasCliTimeoutContext(e) ? e : void 0, /* @__PURE__ */ new Set()); } /** Map a failover reason to the closest HTTP-like status code. */ function resolveFailoverStatus(e, t) { return normalizeFailoverStatus(FAILOVER_STATUS.get(e), t); } function normalizeFailoverStatus(e, t) { return t === "selected_auth_profile_unavailable" ? void 0 : e; } const FAILOVER_STATUS = /* @__PURE__ */ new Map([ ["billing", 402], ["server_error", 500], ["rate_limit", 429], ["overloaded", 503], ["auth", 401], ["auth_permanent", 403], ["timeout", 408], ["tls_certificate", 502], ["context_overflow", 413], ["format", 400], ["model_not_found", 404], ["session_expired", 410] ]); function readDirectStatusCode(e) { const t = asOptionalObjectRecord(e); const n = t?.status ?? t?.statusCode; if (typeof n === "number") return n; if (typeof n === "string") return parseStrictNonNegativeInteger(n); } function readStableProviderErrorType(e) { const t = e.trim(); return /^[A-Z][A-Z0-9_:-]*$/.test(t) && !/^(?:api|authentication|invalid_request|not_found|overloaded|permission|rate_limit|server)_error$/i.test(t) ? t : void 0; } function readDirectErrorType(e) { const t = asOptionalObjectRecord(e); if (!t) return; const n = t.errorType; if (typeof n === "string") return readStableProviderErrorType(n); const r = t.detail?.type; if (typeof r === "string") return readStableProviderErrorType(r); const i = normalizeOptionalString(t.type); return i && !/^(?:error|exception)$/i.test(i) ? readStableProviderErrorType(i) : void 0; } function readDirectProvider(e) { return normalizeOptionalString(asOptionalObjectRecord(e)?.provider); } function readDirectErrorDetails(e) { const t = asOptionalObjectRecord(e); if (!t) return; return extractFailoverSignalDetails(t.param, t.errorBody, t.body, t.detail, t.error); } function hasSessionTranscriptWriterClaimRebound(e, t = /* @__PURE__ */ new Set()) { if (readErrorName(e) === "SessionTranscriptWriterClaimReboundError") return true; const n = asOptionalObjectRecord(e); if (!n || t.has(n)) return false; t.add(n); return hasSessionTranscriptWriterClaimRebound(n.error, t) || hasSessionTranscriptWriterClaimRebound(n.cause, t) || hasSessionTranscriptWriterClaimRebound(n.reason, t); } function readMissingToolResultMarker(e) { const t = readDirectErrorMessage(e); if (t && MISSING_TOOL_RESULT_TEXT_RE.test(t)) return true; const n = asOptionalObjectRecord(e); for (const e of [ "code", "reason", "status" ]) if (readStringField(n, e)?.trim() === MISSING_TOOL_RESULT_REASON) return true; const r = readStringField(n, "output"); if (r && MISSING_TOOL_RESULT_TEXT_RE.test(r)) return true; const i = readStringField(asOptionalObjectRecord(n?.result), "reason"); const a = readStringField(asOptionalObjectRecord(n?.detail), "reason"); if (i === MISSING_TOOL_RESULT_REASON || a === MISSING_TOOL_RESULT_REASON) return true; } function hasMissingToolResultFailure(e) { return findErrorProperty(e, readMissingToolResultMarker) === true; } function hasStaleAgentRunLifecycleFailure(e) { return findErrorProperty(e, (e) => isAgentRunStaleLifecycleError(e) ? true : void 0) === true; } function hasRuntimeCoordinationFailure(e) { if (isChannelRunAuthorizationError(e) || isLocalStorageOutcomeError(e)) return true; return collectErrorGraphCandidates(e, resolveNestedErrors).some((e) => e instanceof SkillResourceDeliveryLimitError || isSessionWorkStartInvalidatedError(e) || RUNTIME_COORDINATION_ERROR_NAMES.has(readErrorName(e)) || resolveExecutionApprovalFailureMessage(readDirectErrorMessage(e)) !== void 0); } function hasPreparedModelRuntimeOwnerNotPublished(e) { return collectErrorGraphCandidates(e, resolveNestedErrors).some((e) => e instanceof PreparedModelRuntimeOwnerNotPublishedError); } function hasDirectProviderFailureIdentity(e) { if (isFailoverError(e)) return true; const t = normalizeErrorSignal(e, void 0, "direct"); return Boolean(t.status || t.code || t.errorType || t.provider); } /** Local coordination failures stop fallback because changing models cannot repair them. */ function isNonProviderRuntimeCoordinationError(e) { return resolveModelFallbackError(e).kind === "coordination"; } function normalizeErrorSignal(e, t, n = "nested") { const read = (t) => n === "direct" ? t(e) : findErrorProperty(e, t); const r = read(readDirectErrorMessage); const i = read(readDirectErrorCode); return { status: normalizeFailoverStatus(read(readDirectStatusCode), i), code: i, errorType: read(readDirectErrorType), message: r || void 0, provider: read(readDirectProvider) ?? t, details: readDirectErrorDetails(e) }; } function getNestedErrorCandidates(e) { const t = asOptionalObjectRecord(e); return [t?.error, t?.cause].filter((t) => t !== void 0 && t !== e); } function isFormatClassification(e) { return e?.kind === "reason" && e.reason === "format"; } function decideNestedFormatOverride(e, t, n, r) { if (r > MAX_FAILOVER_CAUSE_DEPTH) return null; if (e && typeof e === "object") { if (n.has(e)) return null; n.add(e); } const i = normalizeErrorSignal(e, void 0, "direct"); const a = getNestedErrorCandidates(e); const o = i.status ?? t; const s = Boolean(i.message?.trim()); if (s && isUnclassifiedNoBodyHttpSignal({ ...i, status: o })) return true; if (s && (a.length === 0 || classifyFailoverSignal(i))) return false; for (const e of a) { const t = decideNestedFormatOverride(e, o, n, r + 1); if (t !== null) return t; } return null; } function resolveFailoverClassificationFromErrorInternal(e, t, n, r) { if (n > MAX_FAILOVER_CAUSE_DEPTH) return null; if (e && typeof e === "object") { if (t.has(e)) return null; t.add(e); } if (isFailoverError(e)) { const t = classifyFailoverSignal({ ...normalizeErrorSignal(e, r), message: e.rawError ?? e.message }); if (t?.kind === "reason" && t.sameModelRetry === false) return { kind: "reason", reason: e.reason, sameModelRetry: false }; return { kind: "reason", reason: e.reason }; } const i = normalizeErrorSignal(e, r); const a = classifyFailoverSignal(i); const o = getNestedErrorCandidates(e); if (!a || a.kind === "context_overflow") for (const e of o) { const i = resolveFailoverClassificationFromErrorInternal(e, t, n + 1, r); if (i) return i; } if (isFormatClassification(a)) for (const e of o) { const r = decideNestedFormatOverride(e, i.status, t, n + 1); if (r === true) return null; if (r === false) break; } if (a) return a; if (isTimeoutError(e)) return { kind: "reason", reason: "timeout" }; return null; } function resolveFailoverClassificationFromError(e, t) { if (isAgentHarnessPreflightError(e) || findLocalWorkerTaskFailure(e)) return null; if (!isFailoverError(e) && hasRuntimeCoordinationFailure(e)) return null; return resolveFailoverClassificationFromErrorInternal(e, /* @__PURE__ */ new Set(), 0, t); } function resolveFailoverReasonFromError(e, t) { return failoverReasonFromClassification(resolveFailoverClassificationFromError(e, t)); } /** Build a copy-pasteable reauthentication hint for attributed auth failures. */ function buildFailoverRemediationHint(e) { if (!isFailoverError(e) || e.code === "selected_auth_profile_unavailable") return; if (e.reason !== "auth" && e.reason !== "auth_permanent") return; const t = e.provider?.trim(); if (!t) return; if (t === "google-gemini-cli") return `Authenticate in Gemini CLI directly, or configure a supported Google API key with: ${formatCliCommand("openclaw configure")}`; const n = buildProviderReauthCommand(t); return n ? `Re-authenticate with: ${n}` : void 0; } function quotePosixShellArg(e) { return `'${e.replaceAll("'", "'\\''")}'`; } function buildProviderReauthCommand(e, t = process.env) { const n = e.trim(); if (!n || containsAsciiControlCharacter(n)) return; return formatCliCommand(`openclaw models auth login --provider ${quotePosixShellArg(n)} --force`, t); } function describeFailoverError(e) { const t = findLocalWorkerTaskFailure(e); if (t) return { message: t.message }; if (isAgentHarnessPreflightError(e)) return { message: e.message }; if (isFailoverError(e)) return { message: e.message, rawError: e.rawError, rateLimitRetriesExhausted: e.rateLimitRetriesExhausted, reason: e.reason, status: normalizeFailoverStatus(e.status, e.code), code: e.code, provider: e.provider, model: e.model, profileId: e.profileId, authMode: e.authMode, sessionId: e.sessionId, lane: e.lane }; const n = normalizeErrorSignal(e); return { message: n.message ?? String(e), reason: resolveFailoverReasonFromError(e) ?? void 0, status: n.status, code: n.code, provider: n.provider }; } /** Convert a classified raw error into a FailoverError with optional request context. */ function coerceToFailoverError(e, t) { if (isFailoverError(e)) { if (findLocalWorkerTaskFailure(e)) return null; const n = normalizeFailoverStatus(e.status, e.code); if (!Object.is(n, e.status) || t?.authMode && !e.authMode || t?.timeout && !e.timeout || t?.rateLimitRetriesExhausted !== void 0) { const r = typeof e.message === "string" ? e.message : String(e); const i = new FailoverError(renderRateLimitRetryExhaustion(t?.rateLimitRetriesExhausted) ?? r, { reason: e.reason, provider: e.provider, model: e.model, profileId: e.profileId, authMode: e.authMode ?? t?.authMode, status: n, code: e.code, rawError: e.rawError ?? (t?.rateLimitRetriesExhausted !== void 0 ? r : void 0), rateLimitRetriesExhausted: t?.rateLimitRetriesExhausted ?? e.rateLimitRetriesExhausted, authProfileFailure: e.authProfileFailure, sessionId: e.sessionId, lane: e.lane, cause: e.cause, suspend: e.suspend, cliTimeout: e.cliTimeout, timeout: e.timeout ?? t?.timeout, attempts: e.attempts, soonestCooldownExpiry: e.soonestCooldownExpiry }); copyErrorDiagnostic(e, i); return i; } return e; } const n = resolveFailoverReasonFromError(e, t?.provider); if (!n) return null; const r = normalizeErrorSignal(e); const i = r.message ?? String(e); const a = r.code; const o = r.status ?? resolveFailoverStatus(n, a); const s = Boolean(t?.sessionId) && (n === "rate_limit" || n === "billing"); return new FailoverError(renderRateLimitRetryExhaustion(t?.rateLimitRetriesExhausted) ?? i, { reason: n, rateLimitRetriesExhausted: t?.rateLimitRetriesExhausted, provider: t?.provider ?? r.provider, model: t?.model, profileId: t?.profileId, authMode: t?.authMode, sessionId: t?.sessionId, lane: t?.lane, status: o, code: a, rawError: i, cause: e instanceof Error ? e : void 0, timeout: t?.timeout, suspend: s }); } /** Classify one candidate failure once so fallback routing and diagnostics share it. */ function resolveModelFallbackError(e, t) { if (e instanceof AgentHarnessSessionSupersededError || isSqliteTranscriptMutationConflict(e)) return { kind: "coordination", error: e }; if (hasPreparedModelRuntimeOwnerNotPublished(e)) return { kind: "coordination", error: e }; if (hasRuntimeCoordinationFailure(e) || findLocalWorkerTaskFailure(e)) return { kind: "coordination", error: e }; const n = hasStaleAgentRunLifecycleFailure(e); if (n && (isAgentRunStaleLifecycleError(e) || !hasDirectProviderFailureIdentity(e))) return { kind: "coordination", error: e }; if (hasSessionTranscriptWriterClaimRebound(e)) return { kind: "coordination", error: e }; if (hasModelFallbackStop(e)) return { kind: "terminal", error: e }; if (isAgentHarnessPreflightError(e)) return { kind: "coordination", error: e }; const r = coerceToFailoverError(e, t); if (r) return { kind: "failover", error: r }; if (hasMissingToolResultFailure(e) || n) return { kind: "coordination", error: e }; return { kind: "unknown", error: e }; } //#endregion export { findCliTerminalStopError as a, hasRecordedModelFallbackStop as c, resolveFailoverClassificationFromError as d, resolveFailoverReasonFromError as f, describeFailoverError as i, isCliTerminalStopCode as l, resolveModelFallbackError as m, buildProviderReauthCommand as n, findCliTimeoutError as o, resolveFailoverStatus as p, coerceToFailoverError as r, hasModelFallbackStop as s, buildFailoverRemediationHint as t, isNonProviderRuntimeCoordinationError as u };