UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

198 lines (197 loc) • 8.84 kB
import { s as pathMayExistSync } from "./path-existence-Co7-GyVr.mjs"; import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { c as resolveRuntimeServiceCommit, t as VERSION } from "./version-GlxUMdxI.mjs"; import { s as resolveOpenClawStateSqlitePath } from "./openclaw-state-db.paths-R3ArRCcz.mjs"; import { s as resolveGatewayPlatformSupervisor } from "./gateway-supervision-C1X-e8qk.mjs"; import { n as executeExistingOpenClawStateRead } from "./openclaw-state-db-readonly-B6YHb1oF.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { n as createSqliteWorkerWriteAdmission } from "./sqlite-worker-store-D51tD0Vp.mjs"; import { i as runOpenClawStateWorkerOperation } from "./openclaw-state-worker-store-2LoAv_8B.mjs"; import { l as runOpenClawStateWriteTransaction } from "./openclaw-state-db-ARhwdPJg.mjs"; import { i as publishGatewayRecentCrashes, n as formatGatewayCrash } from "./gateway-crash-D22VnCOp.mjs"; import { r as detectGatewayRespawnSupervisorIdentity } from "./supervisor-markers-D25wJZrm.mjs"; import { i as buildGatewayCrashLoopBreakerDecision, o as maintenanceStartupReasons } from "./gateway-boot-lifecycle.kernel-BYOJzAob.mjs"; //#region src/infra/gateway-boot-lifecycle.ts async function readGatewayRecentCrashesAsync(e = process.env) { return (await executeExistingOpenClawStateRead({ env: e }, { type: "gatewayBoot.crashes", input: void 0 }, { signal: getAsyncWorkSignal(), current: true }))?.crashes ?? []; } /** Reports the predecessor once, after startup, through the boot owner's worker. */ async function reportPreviousGatewayCrash(e, t, n = process.env) { let r = e; try { const { readGatewayCrashCause: t } = await import("./gateway-crash-cause-CzdaNZoE.mjs"); const i = await t(e, n); if (i) { const t = captureOpenClawStateWorkerContext({ env: n }); const a = await runOpenClawStateWorkerOperation(t, (t) => t.execute({ type: "gatewayBoot.enrichCrash", input: { bootId: e.bootId, evidence: i } })); publishGatewayRecentCrashes(a.crashes); r = a.crash ?? e; } } catch {} t.warn(`previous Gateway run ended unexpectedly: ${formatGatewayCrash(r)}`); } function formatGatewayRepeatedSignalHint(e, t, n = "received") { return `${n} ${e} ${t} times in 5 min: another supervisor may be managing this Gateway — see \`openclaw gateway status --deep\``; } /** * The breaker only self-clears after the full window drains. Operator surfaces name the manual * override command, not the internal RPC. Account hints carry accountId to avoid starting a * different default account than the warning named. */ function formatGatewayCrashLoopManualChannelStartHint(e) { const t = JSON.stringify({ channel: e?.channelId ?? "<id>", ...e?.accountId ? { accountId: e.accountId } : {} }); return `Start a channel manually with: ${formatCliCommand("openclaw gateway call channels.start")} --params '${t}'`; } const gatewayLifecycleLog = createSubsystemLogger("gateway/lifecycle"); /** Inspection keeps snapshot preparation off the caller's event loop. */ async function readLastShutdownRecord(e, t) { return (await executeExistingOpenClawStateRead({ env: e }, { type: "gatewayBoot.lastShutdown", input: void 0 }, { signal: getAsyncWorkSignal(), current: t }))?.shutdown; } const isInstallationReplacement = (e) => e?.startsWith("gateway.installation_replaced:") === true; async function readGatewayLastShutdownAsync(e = process.env) { const t = await readLastShutdownRecord(e); return t && { reason: t.reason, completedAtMs: t.completedAtMs }; } async function readGatewayLastInstallationReplacementAsync(e = process.env) { const t = await readGatewayLastShutdownAsync(e); return isInstallationReplacement(t?.reason) ? { reason: t.reason, completedAtMs: t.completedAtMs } : void 0; } /** Match the latest shutdown to the inspected process using a fresh owner read. */ async function didGatewayExitForReplacedInstallation(e, t = process.env) { const n = await readLastShutdownRecord(t, true); return n?.pid === e && isInstallationReplacement(n.reason); } /** Decide from prior boots, then record this boot in the existing lifecycle writer. */ async function beginGatewayBootLifecycle(e = process.env, t = Date.now(), n) { publishGatewayRecentCrashes([]); try { const r = captureOpenClawStateWorkerContext({ env: e }); const i = detectGatewayRespawnSupervisorIdentity(); const a = await runOpenClawStateWorkerOperation(r, (r) => r.execute({ type: "gatewayBoot.begin", input: { nowMs: t, previousOwner: n, metadata: { version: VERSION, commit: resolveRuntimeServiceCommit() ?? void 0, runtime: process.versions.bun ? `Bun ${process.versions.bun}` : `Node ${process.versions.node}`, supervisor: i ?? void 0, systemdInvocationId: i?.kind === "systemd" ? e.INVOCATION_ID : void 0 } } })); if (a.crashes) publishGatewayRecentCrashes(a.crashes); return a; } catch (e) { gatewayLifecycleLog.warn(`crash-loop breaker state unavailable; fail-open: ${String(e)}`); return { decision: buildGatewayCrashLoopBreakerDecision({ uncleanBoots: 0 }), id: void 0 }; } } /** Runtime readers share the boot owner's decision without opening SQLite on the main thread. */ async function inspectGatewayCrashLoopBreakerAsync(e = process.env, t = Date.now(), n) { return (await executeExistingOpenClawStateRead({ env: e }, { type: "gatewayBoot.breaker", input: t }, { signal: n, current: true }))?.decision ?? buildGatewayCrashLoopBreakerDecision({ uncleanBoots: 0 }); } /** * Split a stable safe-mode lifetime before channel autostart resumes. A fresh * open row makes a process death during recovered channel startup count toward * the next breaker decision instead of aging out with the original boot. */ async function recordGatewayCrashLoopRecovery(e, t = process.env, n, r) { try { const i = captureOpenClawStateWorkerContext({ env: t }); return await runOpenClawStateWorkerOperation(i, (t) => t.execute({ type: "gatewayBoot.recover", input: { bootId: e, nowMs: n } }), { assertCurrent: r, createAdmission: createSqliteWorkerWriteAdmission(() => { i.admission.assertCurrent(); r?.(); }, [i.admission.databasePath]) }); } catch (e) { gatewayLifecycleLog.warn(`failed to persist gateway crash-loop recovery; fail-safe: ${String(e)}`); return; } } async function completeGatewayBootLifecycle(e, t, n = process.env, r = Date.now()) { if (!e) return; const i = t.outcome !== "clean_stop" ? void 0 : t.reason === "stop (SIGTERM)" ? "SIGTERM" : t.reason === "stop (SIGINT)" ? "SIGINT" : void 0; try { const a = captureOpenClawStateWorkerContext({ env: n }); const o = await runOpenClawStateWorkerOperation(a, (n) => n.execute({ type: "gatewayBoot.complete", input: { bootId: e, completion: t, nowMs: r, countSignalStops: i !== void 0 } })); if (i && o !== void 0 && o >= 3) { const e = resolveGatewayPlatformSupervisor(n); if (e) gatewayLifecycleLog.info(`stopped after ${i} ${o} times in 5 min (${e === "kubernetes" ? "Kubernetes" : "external supervisor"} manages this Gateway)`); else gatewayLifecycleLog.warn(formatGatewayRepeatedSignalHint(i, o, "stopped after")); } } catch (e) { gatewayLifecycleLog.warn(`failed to persist gateway boot outcome; fail-open: ${String(e)}`); } } function repairGatewayMaintenanceStartupFailures(e = process.env) { if (!pathMayExistSync(resolveOpenClawStateSqlitePath(e))) return 0; try { return runOpenClawStateWriteTransaction(({ db: e }) => { const t = getNodeSqliteKysely(e); const n = executeSqliteQuerySync(e, t.updateTable("gateway_boot_lifecycle").set({ outcome: "startup_failure_repaired" }).where("outcome", "=", "startup_failed").where("startup_reason", "in", maintenanceStartupReasons)); return Number(n.numAffectedRows ?? 0); }, { env: e }); } catch (e) { gatewayLifecycleLog.warn(`failed to repair maintenance startup history; fail-open: ${String(e)}`); return 0; } } //#endregion export { formatGatewayRepeatedSignalHint as a, readGatewayLastShutdownAsync as c, repairGatewayMaintenanceStartupFailures as d, reportPreviousGatewayCrash as f, formatGatewayCrashLoopManualChannelStartHint as i, readGatewayRecentCrashesAsync as l, completeGatewayBootLifecycle as n, inspectGatewayCrashLoopBreakerAsync as o, didGatewayExitForReplacedInstallation as r, readGatewayLastInstallationReplacementAsync as s, beginGatewayBootLifecycle as t, recordGatewayCrashLoopRecovery as u };