UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

187 lines (186 loc) • 8.63 kB
import { s as getRootOptionAwareCommandPath } from "./cli-root-options-xlQx6o4R.mjs"; import { r as isForegroundGatewayRunArgv } from "./gateway-run-argv-DfcBAs2-.mjs"; import { n as isTruthyEnvValue } from "./env-HehwidXj.mjs"; import { i as collectNestedErrorCandidates } from "./error-coercion-hDrHOSGy.mjs"; import { i as restoreRuntimeTerminalState, r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { r as formatUncaughtError, t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { t as exitAfterSignalExitBarriers } from "./signal-exit-barrier-BOGtFHQL.mjs"; import { r as findStartupMaintenanceRequiredError } from "./startup-maintenance-required-DEn4Krys.mjs"; import { t as UpdateSchemaRefusalError } from "./openclaw-update-schema-refusal-DQDN1MLl.mjs"; import { s as isInvalidConfigError } from "./io.invalid-config-DK-BYZ4Y.mjs"; import { t as runFatalErrorHooks } from "./fatal-error-hooks-Bhtt3ct0.mjs"; import { s as isGatewayTransportError } from "./transport-error-BL_kuysc.mjs"; import { a as isUncaughtExceptionHandled, n as isBenignUncaughtExceptionError } from "./unhandled-rejections-DhcwsfYr.mjs"; import { r as isJsonOutputModeActive } from "./json-output-mode-DSme4Xvd.mjs"; //#region src/cli/failure-output.ts function handleCliUncaughtException(e, t) { if (isUncaughtExceptionHandled(e)) return; if (isBenignUncaughtExceptionError(e)) { console.warn("[openclaw] Non-fatal uncaught exception (continuing):", formatUncaughtError(e)); return; } if (isJsonOutputModeActive(t ?? process.argv)) defaultRuntime.writeJson(formatCliJsonFailure(e)); for (const n of formatCliFailureLines({ title: "OpenClaw hit an unexpected runtime error.", error: e, argv: t ?? process.argv })) console.error(n); for (const t of runFatalErrorHooks({ reason: "uncaught_exception", error: e })) console.error("[openclaw]", t); restoreRuntimeTerminalState("uncaught exception"); exitAfterSignalExitBarriers(1, "uncaught exception"); } const gatewayRunFailures = /* @__PURE__ */ new WeakMap(); /** Agent dispatch supplies observed Gateway IDs; error identity and human output stay intact. */ function recordCliGatewayRunFailure(e, t) { if (e instanceof Error && t) gatewayRunFailures.set(e, { runId: t, origin: "gateway" }); } /** Human diagnostics (agent transport-loss hint) read back the run identity recorded at dispatch. */ function readCliGatewayRunFailure(e) { return e instanceof Error ? gatewayRunFailures.get(e) : void 0; } var ExpectedCliError = class extends Error { constructor(e) { super(e.message, e.cause === void 0 ? void 0 : { cause: e.cause }); this.name = "ExpectedCliError"; this.humanOutput = e.humanOutput; this.humanOutputWritten = e.humanOutputWritten ?? false; this.machineOutput = e.machineOutput; this.matches = e.matches; } }; function throwExpectedCliError(e) { throw new ExpectedCliError({ message: e, humanOutput: e, machineOutput: e }); } function isGatewayCredentialsCliError(e) { if (!(e instanceof Error)) return false; return e.name === "GatewayCredentialsRequiredError" && "method" in e && typeof e.method === "string" && "configPath" in e && typeof e.configPath === "string"; } const EXPECTED_CLI_ERROR_NAMES = /* @__PURE__ */ new Set([ "GatewayExplicitAuthRequiredError", "AgentSelectionRequiredError", "ConfigReadOnlyError", "NixModeConfigMutationError", "LocalStateOwnerError", "CompletionCacheMissingError", "CompletionProfileEncodingError" ]); function isExpectedCliError(e) { return e instanceof ExpectedCliError || isGatewayCredentialsCliError(e) || e instanceof Error && EXPECTED_CLI_ERROR_NAMES.has(e.name) || isGatewayTransportError(e); } /** * Plugin actions and command hooks report their failure message like core command * boundaries; the root renderer still owns JSON envelopes and exit codes. */ function toPluginCommandFailure(e) { if (isExpectedCliError(e) || e instanceof Error && (e.name === "CommanderError" || e.name === "ExitError")) return e; const t = e !== null && typeof e === "object" && "code" in e && typeof e.code === "string" && e.code.startsWith("commander."); if (shouldShowDebugDetails() && !t) return e; const n = formatCliOperatorError(e); return new ExpectedCliError({ message: n, humanOutput: n, machineOutput: n, cause: e }); } function rethrowExpectedCliError(e) { if (isExpectedCliError(e)) throw e; } function resolveExpectedCliOutput(e) { return e instanceof ExpectedCliError ? e : { humanOutput: e.message, humanOutputWritten: false, machineOutput: e.message }; } /** Canonical machine-readable failure envelope for CLI-owned errors. */ function formatCliJsonFailure(e, t = {}) { const n = isExpectedCliError(e) ? formatErrorMessage(resolveExpectedCliOutput(e).machineOutput.trimEnd()) : formatCliOperatorError(e, t); return { ok: false, ...readCliGatewayRunFailure(e), error: { type: "cli_error", message: n, ...e instanceof ExpectedCliError && e.matches ? { matches: e.matches } : {}, ...e instanceof UpdateSchemaRefusalError ? { code: e.code, databases: e.databases, updaterVersion: e.updaterVersion, targetVersion: e.targetVersion, commands: e.commands } : {} } }; } function shouldShowDebugDetails(e = process.argv, t = process.env) { for (const t of e ?? []) { if (t === "--") break; if (t === "--debug" || t === "--verbose") return true; } return isTruthyEnvValue(t.OPENCLAW_DEBUG); } function formatCliOperatorError(e, t = {}) { const n = !shouldShowDebugDetails(t.argv, t.env) && e instanceof Error ? e.message || e.name || "Error" : e; return formatErrorMessage(n); } function formatCliFailureLines(e) { const t = e.env ?? process.env; const n = e.argv ?? process.argv; const r = shouldShowDebugDetails(e.argv, t); const i = getRootOptionAwareCommandPath(n, 2); const a = i[0] === "update"; const o = i[0] === "plugins" && i[1] === "update"; const s = i[0] === "node" && i[1] === "run"; const c = ["0", "1"].includes(t.OPENCLAW_UPDATE_IN_PROGRESS ?? ""); if (isGatewayTransportError(e.error) && !r && !c && !a) { const t = e.error; return [ t.kind === "timeout" ? "OpenClaw took too long to respond." : t.requestDispatched ? "Lost the connection to OpenClaw." : "Couldn't connect to OpenClaw.", ...t.requestDispatched ? ["Your request may have completed. Check its result before trying again."] : [], `Check the Control UI or run \`${formatCliCommand("openclaw gateway status", e.env)}\` in your terminal.` ]; } if (isExpectedCliError(e.error)) { const t = resolveExpectedCliOutput(e.error); return t.humanOutputWritten ? [] : t.humanOutput.trimEnd().split("\n"); } const l = collectNestedErrorCandidates(e.error); const u = l.some((e) => e instanceof Error && e.name === "GatewayStateOwnerContentionError"); const d = findStartupMaintenanceRequiredError(e.error) ?? l.find((e) => e instanceof Error && (e.name === "StateDatabaseAccessError" || e.name === "StateDatabaseMaintenanceScopeError")); const reason = (e) => `[openclaw] Reason: ${formatCliOperatorError(e, { argv: n, env: t })}`; if (!r && !c) { if (e.error instanceof UpdateSchemaRefusalError || e.error instanceof Error && (e.error.name === "DoctorUnreadableStateDatabaseError" || e.error.name === "OpenClawDatabaseSchemaPreflightError")) return ["[openclaw] OpenClaw needs a manual recovery step.", reason(e.error)]; if (d) return [`[openclaw] ${e.title}`, reason(d)]; const r = isInvalidConfigError(e.error) ? !e.error.diagnosticEmitted : a || o || s || isForegroundGatewayRunArgv(n); return [ `[openclaw] ${e.title}`, ...r ? [reason(e.error)] : [], u ? "[openclaw] Another OpenClaw process is using your data. Wait for it to finish before trying again." : `[openclaw] For help, run \`${formatCliCommand("openclaw doctor", t)}\`.` ]; } const f = [`[openclaw] ${e.title}`, reason(e.error)]; if (r) { f.push("[openclaw] Stack:"); for (const t of formatUncaughtError(e.error).split("\n")) if (t.trim().length > 0) f.push(`[openclaw] ${t}`); } if (!u) f.push(`[openclaw] Try: ${formatCliCommand("openclaw doctor", t)}`); f.push(`[openclaw] Help: ${formatCliCommand("openclaw --help", t)}`); return f; } //#endregion export { handleCliUncaughtException as a, readCliGatewayRunFailure as c, throwExpectedCliError as d, toPluginCommandFailure as f, formatCliOperatorError as i, recordCliGatewayRunFailure as l, formatCliFailureLines as n, isExpectedCliError as o, formatCliJsonFailure as r, isGatewayCredentialsCliError as s, ExpectedCliError as t, rethrowExpectedCliError as u };