UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

242 lines (241 loc) • 13 kB
import { s as resolveOpenClawCliInvocation } from "../cli-invocation-ZSPsKRWa.mjs"; import { n as isNodeRuntime } from "../runtime-binary-QwVVJ9cA.mjs"; import { c as isWindowsTaskSupervisorChildArgument, l as readWindowsTaskSupervisorRestartExitCode } from "../windows-task-supervisor-contract-DV_hv_so.mjs"; import { n as isTruthyEnvValue } from "../env-HehwidXj.mjs"; import { t as formatErrorMessage } from "../errors-BKzCeTYb.mjs"; import { a as rewritePnpmVersionedOpenClawEntryPath } from "../openclaw-root-C-ayo09z.mjs"; import { s as resolveOpenClawStateSqlitePath } from "../openclaw-state-db.paths-R3ArRCcz.mjs"; import { S as resolveStateOwnerIdentity, h as assertPersistedStateDatabaseAccessAllowed } from "../gateway-state-owner-Bnv5owvG.mjs"; import { d as registerChildRuntimeRecovery, l as probeChildRuntimeExecutable } from "../child-runtime-viability-DFyU3D5D.mjs"; import { x as rotateAgentEventLifecycleGeneration } from "../agent-events-BdfWYmot.mjs"; import { m as markGatewayRestartDraining, w as runWithGatewayIndependentRootWorkAdmission } from "../gateway-work-admission-79pid1hQ.mjs"; import { t as isContainerEnvironment } from "../container-environment-BQP66a3c.mjs"; import { D as waitForActiveCronJobs, E as resetCronActiveJobs, t as advanceCronActiveJobGeneration } from "../active-jobs-DAhIn24S.mjs"; import { a as stopActiveManagedProviderLocalServices } from "../provider-runtime-lifecycle-BIMpRRUs.mjs"; import { i as retireActiveCronTaskRunTracking, o as waitForActiveCronTaskRuns, t as abortActiveCronTaskRuns } from "../active-run-cancellation-lx4m2Fu3.mjs"; import { l as resetAllLanes } from "../command-queue-BenRlAaO.mjs"; import { c as resetGatewaySuspendCoordinatorForLifecycleRestart } from "../gateway-suspend-coordinator-DwPh5h96.mjs"; import { o as writeDiagnosticStabilityBundleForFailureSync } from "../diagnostic-stability-bundle-BXCQCLKc.mjs"; import { o as writeGatewayRestartHandoff } from "../restart-handoff-Cby-pPDg.mjs"; import { a as markGatewayRestartHandled, c as resetGatewayRestartStateForInProcessRestart, g as abortPendingChannelReloads, i as isGatewayRestartExternallyAllowed, l as rollbackGatewayRestartSignalAdmission, n as consumeGatewayRestartIntent, o as peekGatewayRestartReason, p as triggerOpenClawRestart, s as requestGatewayRestartWithSignalAdmission, t as consumeGatewayRestartAuthorization, u as scheduleGatewayRestart } from "../restart-LzysM26p.mjs"; import { n as prepareGatewayRestartIntentConsumption } from "../restart-intent-D5xKHHxG.mjs"; import { t as mergeGatewayServiceEnv } from "../service-env-merge-994N__ny.mjs"; import { T as writeRestartSentinelIfUnchanged, h as readRestartSentinelReadOnly, p as markUpdateRestartSentinelFailure } from "../restart-sentinel-DinoFPf6.mjs"; import { n as scheduleDetachedLaunchdRestartHandoff } from "../launchd-restart-handoff-C8Iy_8IG.mjs"; import { n as detectGatewayRespawnSupervisor, r as detectGatewayRespawnSupervisorIdentity } from "../supervisor-markers-D25wJZrm.mjs"; import { a as waitForSystemServiceUpdateHandoffs } from "../update-managed-service-handoff-current-CwrdJfhF.mjs"; import { a as commitManagedServiceUpdateHandoff, c as isForegroundUpdateHandoff, i as claimManagedServiceUpdateHandoff, n as cancelManagedServiceUpdateHandoff, o as completeForegroundUpdateHandoffAfterClose, r as captureForegroundUpdateHandoffStop, u as requestManagedServiceUpdateHandoffPark } from "../update-managed-service-handoff-9S3IktCr.mjs"; import { n as waitForGatewayHealthyRestart } from "../restart-health-C1P8c-k3.mjs"; import { c as readGatewayLastShutdownAsync } from "../gateway-boot-lifecycle-CkLg5ugv.mjs"; import { n as reportGatewayRuntimeRecoveryOnly, t as registerGatewayNativeWorkerRecovery } from "../gateway-native-worker-recovery-BfsiLax0.mjs"; import { spawn } from "node:child_process"; import { isSupported } from "@openclaw/proc-safe/systemd"; //#region src/infra/process-respawn.ts function assertGatewayRespawnOutsideMaintenance(e) { const t = resolveOpenClawStateSqlitePath(e); assertPersistedStateDatabaseAccessAllowed({ databasePath: t, ownerPath: resolveStateOwnerIdentity(t).ownerPath, assertMaintenance: () => { throw new Error("Gateway respawn is blocked while offline maintenance owns the state."); } }); } function resolveGatewayRestartDecision() { if (isTruthyEnvValue(process.env.OPENCLAW_NO_RESPAWN)) return { mode: "disabled", reason: "no-respawn" }; const e = detectGatewayRespawnSupervisor(process.env); if (e) return { mode: "supervised", supervisor: e }; return { mode: "disabled", reason: "unmanaged", detail: process.platform === "win32" ? "win32: detached respawn unsupported without Scheduled Task markers" : isContainerEnvironment() ? "container: use in-process restart to keep PID 1 alive" : "unmanaged: use in-process restart to keep custom supervisor PID tracking stable" }; } const CHILD_RUNTIME_RESTART_REASON = "gateway.runtime-unavailable"; const NATIVE_WORKER_RESTART_REASON = "gateway.native-worker-unsettled"; /** Bind automatic recovery to the existing process lifecycle, never a worker pool. */ function registerGatewayRuntimeRecovery(e) { const { decision: t } = e; const n = e.ownsProcessLifecycle && t.mode === "supervised" && t.supervisor === "systemd" ? isSupported() : true; const r = (e.ownsProcessLifecycle && t.mode === "supervised" ? Promise.resolve().then(() => readGatewayLastShutdownAsync()) : Promise.resolve(void 0)).then((e) => ({ shutdown: e }), (e) => ({ error: e })); let i = true; const recover = async (a, o, s) => { if (!e.ownsProcessLifecycle || t.mode !== "supervised" || t.supervisor === "external") return reportGatewayRuntimeRecoveryOnly("no verified native service restart target."); if (!n) return reportGatewayRuntimeRecoveryOnly("native systemd inspection was unavailable at Gateway startup."); const c = await r; if ("error" in c) return reportGatewayRuntimeRecoveryOnly("restart history could not be read."); if (c.shutdown?.reason?.includes(a) && Date.now() - c.shutdown.completedAtMs < 3e5) return reportGatewayRuntimeRecoveryOnly("a runtime recovery restart happened within the last five minutes."); let l; if (t.supervisor === "launchd") { const { readLoadedLaunchAgentState: e, readCorrespondingLaunchAgentCommand: t } = await import("../launchd-runtime-CpKCV4oj.mjs"); const n = await e(process.env, { timeoutMs: 5e3 }); const r = n.launchAgent ? await t(process.env, n.launchAgent, 5e3) : null; l = { ...n, command: r, env: mergeGatewayServiceEnv(process.env, r) }; } else { const { resolveGatewayService: e } = await import("../service-D5ZNJZsc.mjs"); const { readGatewayServiceState: t } = await import("../service-state-Dr3ZeXNq.mjs"); l = await t(e(), { env: process.env, requireEffective: true, requireLoadedCommand: true, timeoutMs: 5e3 }); } const u = l.command?.programArguments[0]; if (!l.running || !u || !isNodeRuntime(u)) return reportGatewayRuntimeRecoveryOnly("the service has no verified Node command."); const d = await probeChildRuntimeExecutable(u, { env: l.env, cwd: l.command?.workingDirectory }); if (d.error || d.status !== 0 || !/^v\d+\.\d+\.\d+\s*$/.test(d.stdout)) return reportGatewayRuntimeRecoveryOnly("the service Node cannot start. Repair the service runtime, then restart the Gateway."); if (!i || !e.isCurrent()) return reportGatewayRuntimeRecoveryOnly("the Gateway lifecycle is already stopping."); return runWithGatewayIndependentRootWorkAdmission(async () => { if (!i || !e.isCurrent()) return reportGatewayRuntimeRecoveryOnly("the Gateway lifecycle is already stopping."); if (!o()) return reportGatewayRuntimeRecoveryOnly("the native worker has already settled."); const t = s ? requestGatewayRestartWithSignalAdmission(a, s) : requestGatewayRestartWithSignalAdmission(a); return t.status === "emitted" ? { status: "restart-requested", reason: s?.requireFreshProcess ? "Service Node verified; requested a bounded fresh-process restart for the unsettled native worker." : "Service Node verified; requested a graceful fresh-process restart for the unavailable child runtime." } : reportGatewayRuntimeRecoveryOnly(`restart request ${t.status}.`); }, a); }; const a = registerChildRuntimeRecovery(() => recover(CHILD_RUNTIME_RESTART_REASON, () => true)); let o; let s; const c = /* @__PURE__ */ new Set(); const request = (e) => { if (s) return Promise.resolve(s); c.add(e.isCurrent); o ??= recover(NATIVE_WORKER_RESTART_REASON, () => [...c].some((e) => e()), { force: true, waitMs: 0, requireFreshProcess: true }).then((e) => { if (e.status === "restart-requested") s = e; return e; }).finally(() => { o = void 0; c.clear(); }); return o; }; const l = registerGatewayNativeWorkerRecovery(request); return () => { i = false; a(); l(); }; } /** * Attempt to restart this process with a fresh PID. * - supervised environments (launchd/systemd/schtasks): caller should exit and let supervisor restart * - OPENCLAW_NO_RESPAWN=1: caller should keep in-process restart behavior (tests/dev) * - unmanaged environments: caller should keep in-process restart behavior so * custom supervisors keep tracking the same gateway PID */ function restartGatewayProcessWithFreshPid(e = {}) { const t = e.decision ?? resolveGatewayRestartDecision(); if (t.mode === "disabled") return t.reason === "no-respawn" ? { mode: "disabled" } : { mode: "disabled", detail: t.detail }; try { assertGatewayRespawnOutsideMaintenance({ ...process.env, ...e.env }); } catch (e) { return { mode: "failed", detail: formatErrorMessage(e) }; } const { supervisor: n } = t; if (n === "launchd") { const e = scheduleDetachedLaunchdRestartHandoff({ mode: "start-after-exit", waitForPid: process.pid }); return e.ok ? { mode: "supervised", handoffSpawned: e.value } : { mode: "failed", detail: e.error }; } if (n === "schtasks") { if (process.argv.some(isWindowsTaskSupervisorChildArgument)) { const e = readWindowsTaskSupervisorRestartExitCode(process.argv); if (e === void 0) return { mode: "failed", detail: "Windows task supervisor restart marker is missing or invalid" }; return { mode: "supervised", exitCode: e }; } const e = triggerOpenClawRestart(); if (!e.ok) return { mode: "failed", detail: e.detail ?? `${e.method} restart failed` }; } return { mode: "supervised" }; } /** * Update restarts must replace the OS process so the new code runs from a * fresh module graph after package files have changed on disk. * * The caller resolves supervisor ownership first; this path is only for an * unmanaged process whose installed package contents have been replaced. */ function respawnGatewayProcessForUpdate(e = {}) { const t = e.decision ?? resolveGatewayRestartDecision(); if (t.mode === "disabled" && t.reason === "no-respawn") return { mode: "disabled", detail: "OPENCLAW_NO_RESPAWN" }; try { const t = e.env ? { ...process.env, ...e.env } : process.env; const [n, ...r] = process.argv.slice(1); const i = resolveOpenClawCliInvocation({ entryPath: n ? rewritePnpmVersionedOpenClawEntryPath(n) : void 0, args: r }); assertGatewayRespawnOutsideMaintenance(t); const a = spawn(i.command, i.args, { env: t, detached: true, stdio: "inherit" }); a.on("error", () => {}); a.unref(); return { mode: "spawned", pid: a.pid ?? void 0, child: a }; } catch (e) { return { mode: "failed", detail: formatErrorMessage(e) }; } } //#endregion export { abortActiveCronTaskRuns, abortPendingChannelReloads, advanceCronActiveJobGeneration, cancelManagedServiceUpdateHandoff, captureForegroundUpdateHandoffStop, claimManagedServiceUpdateHandoff, commitManagedServiceUpdateHandoff, completeForegroundUpdateHandoffAfterClose, consumeGatewayRestartAuthorization, consumeGatewayRestartIntent, detectGatewayRespawnSupervisorIdentity, isForegroundUpdateHandoff, isGatewayRestartExternallyAllowed, markGatewayRestartDraining as markGatewayDraining, markGatewayRestartHandled, markUpdateRestartSentinelFailure, peekGatewayRestartReason, prepareGatewayRestartIntentConsumption, readRestartSentinelReadOnly, registerGatewayRuntimeRecovery, requestGatewayRestartWithSignalAdmission, requestManagedServiceUpdateHandoffPark, resetAllLanes, resetCronActiveJobs, resetGatewayRestartStateForInProcessRestart, resetGatewaySuspendCoordinatorForLifecycleRestart, resolveGatewayRestartDecision, respawnGatewayProcessForUpdate, restartGatewayProcessWithFreshPid, retireActiveCronTaskRunTracking, rollbackGatewayRestartSignalAdmission, rotateAgentEventLifecycleGeneration, scheduleGatewayRestart, stopActiveManagedProviderLocalServices, waitForActiveCronJobs, waitForActiveCronTaskRuns, waitForGatewayHealthyRestart, waitForSystemServiceUpdateHandoffs, writeDiagnosticStabilityBundleForFailureSync, writeGatewayRestartHandoff, writeRestartSentinelIfUnchanged };