UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

164 lines (163 loc) • 13.6 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { p as asPositiveSafeInteger } from "./number-coercion-D6u-4YD8.mjs"; import { n as safeParseJsonRecord } from "./json-coercion-CaJLaav-.mjs"; import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { T as parseApiErrorInfo, g as extractErrorHttpStatus, m as CONTEXT_OVERFLOW_ERROR_MESSAGE, s as redactSensitiveText, x as formatTransportErrorCopy } from "./redact-Mj7pppxC.mjs"; import { t as classifyGatewayStorageFailure } from "./sqlite-error-diagnostics-6_hREUnq.mjs"; import { g as isUnsupportedReasoningEffortParameterError, m as isSessionTranscriptValidationErrorMessage, p as isServerErrorMessage, v as resolveExecutionApprovalFailureMessage } from "./message-patterns-xrpp7Aip.mjs"; import { t as escapeMarkdownText } from "./escape-markdown-DXmHvlOt.mjs"; import { n as isContextOverflowErrorFromTables } from "./context-overflow-tables-CeoOZL8Z.mjs"; import { n as classifyFailoverSignalCore } from "./classify-core-Bs2jauQR.mjs"; import { t as extractFailoverSignalDetails } from "./signal-details-D8xKpbDw.mjs"; //#region src/agents/failover/assistant-request-failure-copy.ts const ERROR_PREFIX_RE = /^(?:error|(?:[a-z][\w-]*\s+)?api\s*error|openai\s*error|anthropic\s*error|gateway\s*error|codex\s*error|request failed|failed|exception)(?:\s+\d{3})?[:\s-]+/i; const PROVIDER_SCHEMA_REJECTION_USER_TEXT = "The AI service couldn't accept this request. Try a new conversation with /new, or choose another model in the Control UI."; const PROVIDER_OUTPUT_TOKEN_LIMIT_RE = /^['"]?max_(?:tokens|output_tokens|completion_tokens|new_tokens)['"]?\s*(?:[:=]\s*)?\(?(\d[\d,]*)\)?\s+exceeds?\b.{0,120}?\b(?:maximum|max|limit)\b(?:\s+(?:output\s+)?tokens?)?(?:\s+(?:is|of)|\s*[:=])?\s*\(?(\d[\d,]*)\)?(?:\D|$)/i; const PROVIDER_CACHE_CONTROL_LIMIT_RE = /^A maximum of (\d{1,6}) blocks with cache_control may be provided\. Found (\d{1,6})\.$/i; const ERROR_DETAILS_HINT = "For details, open Settings → Logs in the Control UI or run `openclaw logs --follow` in your terminal."; const STORAGE_FAILURE_COPY = { unavailable: "The database connection was lost. This operation was rolled back; nothing from it was saved. Please retry.", SQLITE_BUSY: "OpenClaw is busy saving your conversation. Wait a moment, then check the conversation before trying again.", SQLITE_LOCKED: "OpenClaw is busy saving your conversation. Wait a moment, then check the conversation before trying again.", SQLITE_FULL: "OpenClaw couldn't save your conversation because the disk is full. Free up space on the computer running OpenClaw before continuing.", SQLITE_READONLY: "OpenClaw doesn't have permission to save your conversation. Check folder permissions on the computer running OpenClaw.", SQLITE_IOERR: "OpenClaw couldn't save your conversation. Check the storage on the computer running OpenClaw before continuing.", transcript_writer_fenced: "This conversation changed while OpenClaw was working. Check its latest messages before continuing.", session_actor_reconciliation: "OpenClaw couldn't confirm the last update to this conversation. Some work may have been saved. Wait for current work to finish, then reopen the conversation and check its history before trying again. If it still fails, restart OpenClaw.", "57014": "PostgreSQL canceled a database operation or its statement timed out. Check the conversation for completed work before trying again. If it happens again, ask the operator to check PostgreSQL timeouts and server activity." }; const RUNTIME_COORDINATION_FAILURE_CODE_COPY = { child_completion_delivery_failed: "The child result couldn't be delivered to this conversation. Your conversation is preserved. Check the child sessions for saved work, then retry or resend your request.", codex_node_disconnected: "Codex execution node disconnected. Start a fresh attempt.", node_runner_update_required: "The device worker requires an update before it can host sessions. Run `openclaw update`, reconnect it, then run `openclaw node restart` on a headless node before trying again.", "runner-offline": "The device runner is offline. Reconnect it, retry later, or bring the session back to this gateway." }; const ITEM_CONFLICT_USER_TEXT = "⚠️ The AI service could not recover saved conversation state (item_conflict). Retry this turn. If it still fails, run /compact or choose another model, and share the Gateway logs with the operator."; const ASSISTANT_REQUEST_FAILURE_COPY = { auth: "Couldn't sign in to the AI service. Sign in again under Models in the Control UI or run `openclaw configure`.", auth_permanent: "The AI service isn't accepting your login. Sign in again under Models in the Control UI or run `openclaw configure`.", format: PROVIDER_SCHEMA_REJECTION_USER_TEXT, rate_limit: "The AI service needs a short break. Please try again in a few minutes.", overloaded: "The AI service is busy. Please try again in a moment, or choose another model.", billing: "The AI service reported a billing problem. Check your account's credit balance and usage limits before trying again.", server_error: "The AI service is having trouble. Please try again in a moment.", timeout: "The request took too long. Check the conversation for any completed work before trying again.", tls_certificate: `Couldn't connect securely to the AI service. ${ERROR_DETAILS_HINT}`, context_overflow: CONTEXT_OVERFLOW_ERROR_MESSAGE, model_not_found: "This model was not found. Choose another model in the Control UI or run `openclaw configure`.", session_expired: "Your AI session expired. Start a new conversation with /new. If it happens again, sign in under Models in the Control UI.", empty_response: "The AI service returned an empty reply. Please try again.", no_error_details: "", unclassified: "", unknown: "" }; /** Plain storage copy for length-limited surfaces such as session rows. */ function renderStorageFailureSummary(e) { return e ? STORAGE_FAILURE_COPY[e] : void 0; } /** Render classified facts without exposing raw provider response text. */ function renderAssistantRequestFailureCopy(e) { if (e.storageFailure) return `⚠️ ${STORAGE_FAILURE_COPY[e.storageFailure]} ${ERROR_DETAILS_HINT}`; if (e.code === "item_conflict") return ITEM_CONFLICT_USER_TEXT; if (e.code === "incomplete_tool_call") return "⚠️ The task couldn't finish. Some actions may have completed; check their results before continuing."; const t = e.reason === "timeout" && typeof e.status === "number" && e.status >= 500 ? "server_error" : e.reason; const n = t ? ASSISTANT_REQUEST_FAILURE_COPY[t] : void 0; if (n) return `⚠️ ${n}`; if (!(e.status !== void 0 && Number.isInteger(e.status) && e.status >= 100 && e.status <= 599) && !e.provider?.trim() && !e.model?.trim()) return; return `⚠️ OpenClaw couldn't finish this reply. ${ERROR_DETAILS_HINT}`; } /** Render already-classified coordination facts without loading provider runtime. */ function renderRuntimeCoordinationFailureCopy(e) { const t = e ? RUNTIME_COORDINATION_FAILURE_CODE_COPY[e] : void 0; return t ? `⚠️ ${t}` : void 0; } /** Preserve the rejection diagnostic without publishing the surrounding response body. */ function renderFormatErrorCopy(e) { const t = e.trim(); const n = extractErrorHttpStatus(t)?.rest ?? t.replace(ERROR_PREFIX_RE, "").trim(); let r = extractErrorHttpStatus(n)?.rest ?? n; for (let e = 0; e < 4; e++) { r = (extractErrorHttpStatus(r)?.rest ?? r).replace(/^(?:bad request|unprocessable (?:entity|content))\s*:?\s*(?=[{[<])/iu, ""); const e = parseApiErrorInfo(r)?.message?.trim(); if (!e || e === r) break; r = e; } if (isSessionTranscriptValidationErrorMessage(r)) return "OpenClaw couldn't read this conversation's history. Ask the Gateway operator to try `openclaw doctor --fix`. If it still fails, preserve the history and contact support with the Gateway logs."; const i = r.match(/^"([\w./:-]{1,200})" does not support chat$/u)?.[1]; if (i) return `${escapeMarkdownText(redactSensitiveText(i, { mode: "tools" }))} is an embedding model and cannot chat; pick a chat model with /model (or remove it from models.providers.ollama.models).`; if (PROVIDER_CACHE_CONTROL_LIMIT_RE.test(r)) return "The AI service couldn't accept this conversation. Start a new conversation with /new, or choose another model in the Control UI."; if (isUnsupportedReasoningEffortParameterError(r)) return "This model endpoint does not support reasoning_effort. Set compat.supportsReasoningEffort: false on this model in your custom provider configuration and try again."; if (r.length > 300 || !PROVIDER_OUTPUT_TOKEN_LIMIT_RE.test(r)) { if (!r || /^[{<]/u.test(r)) return PROVIDER_SCHEMA_REJECTION_USER_TEXT; if (r.startsWith("[")) try { JSON.parse(r); return PROVIDER_SCHEMA_REJECTION_USER_TEXT; } catch { if (!/^\[[a-z_$][\w$.-]*\](?:\s|:|$)/iu.test(r)) return PROVIDER_SCHEMA_REJECTION_USER_TEXT; } const e = redactSensitiveText(r, { mode: "tools" }).replace(/[\p{Cc}\p{Cf}\s]+/gu, " ").trim(); if (!e) return PROVIDER_SCHEMA_REJECTION_USER_TEXT; const t = e.length > 600 ? `${truncateUtf16Safe(e, 600)}…` : e; return `LLM request rejected: ${escapeMarkdownText(t)}`; } return "The reply length is set too high for this model. Lower its reply limit in the Control UI settings, or choose another model."; } /** Share bounded request-limit facts between live failures and persisted chat history. */ function renderAssistantFormatFailureCopy(e, t) { if (e.errorCode === "item_conflict" || e.errorMessage === ITEM_CONFLICT_USER_TEXT) return ITEM_CONFLICT_USER_TEXT; for (const [n, r] of [[true, e.errorBody], [false, e.errorMessage]]) { if (typeof r !== "string") continue; const i = parseApiErrorInfo(r); if (i?.code === "item_conflict" || /^(?:LLM request rejected: )?An input item conflicts with an existing record\.$/u.test(i?.message ?? r.trim())) return ITEM_CONFLICT_USER_TEXT; if (n && !i?.message) continue; const a = extractErrorHttpStatus(r)?.code; if (t !== "format" && !(typeof e.errorType === "string" && e.errorType.toLowerCase().includes("invalid_request")) && !i?.type?.toLowerCase().includes("invalid_request") && a !== 400 && a !== 422) continue; const o = renderFormatErrorCopy(r); if (o !== "The AI service couldn't accept this request. Try a new conversation with /new, or choose another model in the Control UI.") return o; } } /** Render loading facts without trusting provider diagnostics or recovery instructions. */ function renderModelLoadFailureCopy(e) { if (e.errorCode !== "model_load_failed" || typeof e.errorBody !== "string" || typeof e.model !== "string") return; const t = asPositiveSafeInteger(safeParseJsonRecord(e.errorBody)?.requestedContextLength); const n = redactSensitiveText(e.model, { mode: "tools" }).replace(/[\p{Cc}\p{Cf}\s]+/gu, " ").trim(); if (!t || !n) return; return `Could not load model "${escapeMarkdownText(truncateUtf16Safe(n, 200))}" with ${t} context tokens. Wait for loading to finish on the model server, then retry, or lower the model's configured context size.`; } /** Classify saved error facts without loading providers or publishing their raw diagnostics. */ function renderRecordedAssistantFailureCopy(e) { const t = renderModelLoadFailureCopy(e); if (t) return t; const n = resolveExecutionApprovalFailureMessage(typeof e.errorMessage === "string" ? e.errorMessage : void 0); if (n) return `⚠️ ${n}`; const r = typeof e.errorMessage === "string" ? e.errorMessage.trim() : ""; if (r === "Worker inference result exceeds the transcript message limit.") return "The worker could not save the model response because it exceeded the message size limit. Retry with a smaller response or continue on the Gateway. Earlier actions may have completed; verify their results before continuing."; if (r === "Cloud worker could not preserve authoritative provider replay. Stop or reclaim the cloud worker, then retry locally.") return "The worker could not preserve the model's continuation data. Stop or reclaim the worker, then retry on the Gateway. Earlier actions may have completed; verify their results before continuing."; const i = parseApiErrorInfo(r); const a = typeof e.errorCode === "string" ? e.errorCode : i?.code; const o = extractErrorHttpStatus(r)?.code; const s = classifyFailoverSignalCore({ message: r, code: a, errorType: typeof e.errorType === "string" ? e.errorType : i?.type, status: o, details: extractFailoverSignalDetails(e.errorBody) }); if (s?.kind === "context_overflow" || [ e.errorCode, e.errorType, r ].some((e) => typeof e === "string" && (normalizeLowercaseStringOrEmpty(e) === "context_overflow" || isContextOverflowErrorFromTables(e)))) return CONTEXT_OVERFLOW_ERROR_MESSAGE; const c = !s?.reason || s.reason === "format" ? renderAssistantFormatFailureCopy(e, s?.reason) : void 0; if (c) return c; const l = renderAssistantRequestFailureCopy({ storageFailure: classifyGatewayStorageFailure(e), code: a, status: o, reason: s?.reason === "timeout" && isServerErrorMessage(r) ? "server_error" : s?.reason }); if (o !== void 0 || s && s.reason !== "timeout") return l; return formatTransportErrorCopy([r, a].filter(Boolean).join(" ")) ?? l; } //#endregion export { renderAssistantRequestFailureCopy as a, renderRecordedAssistantFailureCopy as c, renderAssistantFormatFailureCopy as i, renderRuntimeCoordinationFailureCopy as l, ERROR_PREFIX_RE as n, renderFormatErrorCopy as o, PROVIDER_SCHEMA_REJECTION_USER_TEXT as r, renderModelLoadFailureCopy as s, ERROR_DETAILS_HINT as t, renderStorageFailureSummary as u };