UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

844 lines (843 loc) • 35.4 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import "./src-H3RMXyFL.mjs"; import { t as expectDefined } from "./expect-DDakjvvQ.mjs"; import { o as writeRuntimeJson, r as defaultRuntime } from "./runtime-B-SLYP-m.mjs"; import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs"; import { r as parseTcpPortFromArgs } from "./tcp-port-CuNPxuH-.mjs"; import { b as resolveGatewayPort, h as resolveConfigPathCandidate } from "./paths-DAcAg5aV.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { o as getAsyncWorkSignal } from "./async-work-scope-BXagjUap.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { a as ignoreNonCleanupCommandError, i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { c as resolveGatewayServiceMutationError, i as formatExternalSupervisorActionRequired, o as isGatewayExternallySupervised, r as assertGatewayServiceMutationAllowed } from "./gateway-supervision-C1X-e8qk.mjs"; import { t as parseDurationMs } from "./parse-duration-D6UJm52I.mjs"; import { r as readGatewayOwnerLease } from "./gateway-owner-lease-I0ETcEQK.mjs"; import { a as terminateStaleGatewayPids } from "./restart-stale-pids-GhDopwa0.mjs"; import { a as readBestEffortConfig, l as readConfigFileSnapshotForWrite } from "./io.runtime-DsJ2dLCQ.mjs"; import "./io-4QsrsWTJ.mjs"; import { f as withCommandProcessScope } from "./exec-spawn-DMKoejF-.mjs"; import { t as GATEWAY_SERVER_CAPS } from "./server-capabilities-BDosLJeN.mjs"; import "./config-CMA-J084.mjs"; import { r as theme } from "./theme-BOI0xyRZ.mjs"; import { n as isRestartEnabled } from "./commands.flags-bgyYi4vf.mjs"; import { n as resolveGatewayRestartDrainTimeoutMs, t as resolveGatewayRestartDeferralTimeoutMs } from "./restart-budget-Cn-1gpwB.mjs"; import { t as resolveGatewayStartupTiming } from "./gateway-startup-timing-BGts4IhB.mjs"; import { i as hasGatewayServiceEnvironmentDifference, o as hasGatewayServiceLauncherOverride, s as resolveManagedGatewayServiceCommand, t as assertServiceDefinitionWritable } from "./service-types-DdxELPHF.mjs"; import { i as assertGatewayServiceUpdateCurrent, r as assertGatewayServiceFallbackAllowed } from "./service-update-authority-wlK0pAdP.mjs"; import { a as isSameGatewayLockIdentity, f as captureStalledGatewayStartup, o as readActiveGatewayLockIdentity, s as readActiveGatewayLockPort } from "./gateway-lock-IYOwJQai.mjs"; import { i as writeGatewayRestartIntentSync, t as clearGatewayRestartIntentSync } from "./restart-intent-D5xKHHxG.mjs"; import { t as mergeGatewayServiceEnv } from "./service-env-merge-994N__ny.mjs"; import { t as createNullWriter } from "./null-writer-Ds5ZVrDy.mjs"; import { g as createDaemonActionContext, u as renderGatewayServiceStartHints } from "./shared-cDUnFvXF.mjs"; import { i as callGatewayCli } from "./call-DVCK1deJ.mjs"; import { a as resolveBunRuntimeInfo, s as resolvePinnedDaemonRuntimePath } from "./runtime-paths-xW9-a89Z.mjs"; import { a as formatGatewayServiceStartRepairIssues, d as OPENCLAW_WRAPPER_ENV_KEY, h as resolveOpenClawWrapperPath, n as resolveGatewayService } from "./service-hQiIzcTo.mjs"; import { n as probePortUsage } from "./ports-probe-DVN9Sc3E.mjs"; import { t as resolveGatewayServiceProbeHosts } from "./gateway-service-probe-hosts-DHzuaIDi.mjs"; import { a as readDaemonRuntimePin, c as withDaemonRuntimePinMigration } from "./runtime-pin-state-DXPlp4E4.mjs"; import { E as stopStalledGatewayStartup } from "./service-state-uYnG1mTd.mjs"; import { n as formatGatewayPidList, r as signalVerifiedGatewayPidSync, t as findVerifiedGatewayListenerPidsOnPortSync } from "./gateway-processes-DJBvSEAj.mjs"; import { i as findInstalledSystemdGatewayScope } from "./systemd-scope-BRv8e8-N.mjs"; import { i as stopSystemdService, n as restartSystemdService } from "./systemd-lifecycle-yGkIpc48.mjs"; import { i as refreshLegacySystemdServiceMetadata } from "./systemd-k-QLc2ED.mjs"; import { n as createGatewayRestartDeadline } from "./restart-health-deadline-C9ASZjXK.mjs"; import { n as DEFAULT_RESTART_HEALTH_DELAY_MS, t as DEFAULT_RESTART_HEALTH_ATTEMPTS } from "./restart-health.constants-BJKsCEH8.mjs"; import { o as waitForGatewayHttpReadiness } from "./restart-health-probe-CQiYaScK.mjs"; import { n as waitForGatewayHealthyRestart, r as waitForGatewayHealthyListener } from "./restart-health-C1P8c-k3.mjs"; import { i as renderRestartDiagnostics, r as renderGatewayPortHealthDiagnostics, t as formatGatewayRestartFailure } from "./restart-health-diagnostics-srDMkmNC.mjs"; import { t as recoverInstalledLaunchAgent } from "./launchd-recovery-B8w_CwED.mjs"; import { n as probeGateway } from "./probe-yxDLQFmi.mjs"; import { n as NON_INTERACTIVE_GATEWAY_STOP_MESSAGE, r as isTerminalInteractive } from "./terminal-interactivity-B_L_vZTP.mjs"; import { i as resolveGatewayDaemonRuntime } from "./daemon-runtime-agdJw6fb.mjs"; import { a as runServiceUninstall, i as runServiceStop, n as runServiceRestart, o as appendGatewayLifecycleAudit, r as runServiceStart, s as createGatewayLifecycleMutationAudit, t as commandInterrupted } from "./lifecycle-core-DaTVXHQN.mjs"; import { t as buildGatewayInstallPlan } from "./daemon-install-helpers-DYNaMvoO.mjs"; import { t as resolveGatewayInstallToken } from "./gateway-install-token-BUEEPvbI.mjs"; import { t as mergeInstallInvocationEnv } from "./install-BSU8lH13.mjs"; import { n as resolveGatewayConfigPorts, r as resolveGatewayLifecycleContext } from "./lifecycle-context-fR3xRDR1.mjs"; import path from "node:path"; //#region src/cli/daemon-cli/lifecycle-safe-restart.ts const SAFE_RESTART_METADATA_REFRESH_TIMEOUT_MS = 5e3; function resolveGatewayRestartIntentOptions(e) { if (e.force && e.wait !== void 0) throw new Error("--force cannot be combined with --wait"); if (e.force) return { force: true, waitMs: resolveGatewayRestartDeferralTimeoutMs() }; return e.wait === void 0 ? void 0 : { waitMs: parseDurationMs(e.wait) }; } /** Request an OpenClaw-aware restart through the running Gateway. */ async function runSafeGatewayRestart(e, t) { if (e.force) throw new Error("--safe cannot be combined with --force; omit --safe to begin a forced restart"); if (e.wait !== void 0) throw new Error("--safe cannot be combined with --wait; safe restart uses gateway deferral"); const n = e.skipDeferral === true; const r = { reason: "gateway.restart.safe", ...t ? { safe: true, target: { pid: t.pid, ownerId: t.ownerId, port: t.port } } : {}, ...n ? { skipDeferral: true } : {} }; if (process.platform === "linux") { const reportRefreshError = (e) => { defaultRuntime.error(theme.warn(`Warning: legacy systemd metadata was not refreshed: ${formatErrorMessage(e)}`)); }; const e = resolveGatewayServiceMutationError("refresh legacy systemd service metadata", process.env); if (e) reportRefreshError(e); else await refreshLegacySystemdServiceMetadata(process.env, SAFE_RESTART_METADATA_REFRESH_TIMEOUT_MS).catch(reportRefreshError); } const i = await callGatewayCli({ method: "gateway.restart.request", params: r, ...t ? { ignoreEnvUrlOverride: true, localPortOverride: t.port, requiredCapabilities: [GATEWAY_SERVER_CAPS.GATEWAY_RESTART_TARGET_SAFE] } : {}, timeoutMs: 1e4 }); if (t && i.restart.pid !== t.pid) throw new Error("invalid safe restart acknowledgement"); appendGatewayLifecycleAudit({ action: "restart", source: "safe-rpc", mode: i.status, pid: i.restart.pid }); const a = i.status === "coalesced" ? "safe restart request joined an existing pending gateway restart" : i.status === "deferred" ? "safe restart requested; gateway will restart after active work drains (bounded wait; may force after the timeout expires)" : n ? "safe restart requested; gateway bypassing active-work deferral; shutdown may still wait for pending replies to drain" : "safe restart requested; gateway will restart momentarily"; const o = { ok: true, result: i.status, message: a, preflight: i.preflight, restart: i.restart, warnings: i.preflight.blockers.length === 0 ? void 0 : [i.preflight.summary] }; if (e.json) writeRuntimeJson(defaultRuntime, o); else { defaultRuntime.log(a); if (i.preflight.blockers.length > 0) defaultRuntime.log(theme.warn(i.preflight.summary)); } return true; } //#endregion //#region src/cli/daemon-cli/lifecycle-unmanaged.ts async function assertUnmanagedGatewayRestartEnabled(e) { const t = (await readBestEffortConfig({ observe: false }).catch(() => void 0))?.gateway?.tls?.enabled ? "wss" : "ws"; const n = await probeGateway({ url: `${t}://127.0.0.1:${e}`, auth: { token: normalizeOptionalString(process.env.OPENCLAW_GATEWAY_TOKEN), password: normalizeOptionalString(process.env.OPENCLAW_GATEWAY_PASSWORD) }, timeoutMs: 1e3 }).catch(() => null); if (!n?.ok) return; if (isRecord(n.configSnapshot) && !isRestartEnabled({ commands: n.configSnapshot.commands })) throw new Error("Gateway restart is disabled in the running gateway config (commands.restart=false)"); } async function signalGatewayRestart(e, t) { const n = t.restartIntent?.force ? { force: true, drainBudgetMs: t.restartIntent.waitMs } : t.restartIntent; const r = findVerifiedGatewayListenerPidsOnPortSync(e, { env: t.env }); if (r.length === 0) return null; if (r.length > 1) throw new Error(`multiple gateway processes are listening on port ${e}: ${formatGatewayPidList(r)}; use "openclaw gateway status --deep" before retrying restart`); const i = expectDefined(r[0], "pids entry at 0"); if (t.ownerLease && t.ownerLease.pid !== i) throw new Error(`Port ${e} is owned by pid ${i}, not the recorded foreground Gateway pid ${t.ownerLease.pid}; refusing restart`); const a = process.platform === "win32"; const o = await readActiveGatewayLockIdentity({ env: t.env }); if (!o || o.pid !== i || o.port !== e) throw new Error(`gateway lock identity does not match the verified listener on port ${e}; use "openclaw gateway status --deep" and restart through its supervisor or original terminal`); const assertTargetCurrent = async () => { const n = await readActiveGatewayLockIdentity({ env: t.env }); const r = findVerifiedGatewayListenerPidsOnPortSync(e, { env: t.env }); if (r.length !== 1 || r[0] !== i) throw new Error(`Gateway listener changed before restart on port ${e}`); if (!n || n.pid !== i || n.port !== e || n.ownerId !== o.ownerId || !isSameGatewayLockIdentity(o, n)) throw new Error(`gateway lock owner changed before the restart request could be delivered on port ${e}; run "openclaw gateway status --deep" before retrying`); if (t.ownerLease) { const n = readGatewayOwnerLease({ env: t.env }); if (!n || n.state !== "live" || n.owner !== t.ownerLease.owner || n.pid !== i || n.startedAt !== t.ownerLease.startedAt || n.mode !== "foreground" || n.port !== e || o.ownerId !== n.owner) throw new Error(`Foreground Gateway owner changed before restart on port ${e}`); } }; if (t.enforceRestartConfig) { await assertTargetCurrent(); await assertUnmanagedGatewayRestartEnabled(e); await assertTargetCurrent(); } const s = o.ownerId ? false : writeGatewayRestartIntentSync({ targetPid: i, reason: "gateway.restart", ...t.restartIntent ? { intent: t.restartIntent } : {} }); if (!o.ownerId && !s) throw new Error("failed to persist the gateway restart intent"); try { await assertTargetCurrent(); const r = o.ownerId; if (r || a) { const t = await callGatewayCli({ method: "gateway.restart.request", params: r ? { reason: "gateway.restart", target: { pid: i, ownerId: r, port: e }, ...n ? { restartIntent: n } : {} } : { reason: "gateway.restart", skipDeferral: true }, localPortOverride: e, ignoreEnvUrlOverride: true, timeoutMs: 1e4 }); if (r) expectDefined(t.pid === i ? t : void 0, "invalid restart acknowledgement"); } else signalVerifiedGatewayPidSync(i, "SIGUSR1", { env: t.env, port: e }); } catch (e) { if (s) clearGatewayRestartIntentSync(); throw e; } appendGatewayLifecycleAudit({ action: "restart", source: t.auditSource, mode: o.ownerId || a ? "rpc" : "sigusr1", pid: i }); return { result: "restarted", pid: i, previousLockIdentity: o, message: `Gateway restart request sent to ${t.processLabel} process on port ${e}: ${i}.` }; } //#endregion //#region src/cli/daemon-cli/start-repair.ts const GATEWAY_TARGET_ENV_KEYS = [ "HOME", "USERPROFILE", "OPENCLAW_HOME", "OPENCLAW_PROFILE", "OPENCLAW_STATE_DIR", "OPENCLAW_CONFIG_PATH", "OPENCLAW_GATEWAY_PORT" ]; function resolveInstalledGatewayTargetEnvironment(e) { const t = {}; for (const n of GATEWAY_TARGET_ENV_KEYS) { const r = e?.[n]?.trim(); if (r) t[n] = r; } return t; } function normalizeTargetPath(e) { const t = path.resolve(e); return process.platform === "win32" ? t.toLowerCase() : t; } function assertGatewayRepairTargetMatches(e) { const t = resolveInstalledGatewayTargetEnvironment(e.existingEnvironment); const n = t.OPENCLAW_STATE_DIR?.trim(); const r = t.OPENCLAW_HOME?.trim() || t.HOME?.trim() || t.USERPROFILE?.trim(); if (!n && !r) throw new Error(`Refusing to repair the managed Gateway service because its installed state directory cannot be determined from the service definition. Run \`openclaw gateway install --force\` to replace it intentionally.`); const i = resolveStateDir(t); const a = resolveConfigPathCandidate(t); const o = resolveStateDir(process.env); const s = resolveConfigPathCandidate(process.env); const c = resolveGatewayPort(e.config, process.env); const l = normalizeTargetPath(a) === normalizeTargetPath(s); const u = e.installedPort ?? (l ? resolveGatewayPort(e.config, t) : null); const d = []; for (const [e, t, n] of [[ "OPENCLAW_STATE_DIR", i, o ], [ "OPENCLAW_CONFIG_PATH", a, s ]]) if (normalizeTargetPath(t) !== normalizeTargetPath(n)) d.push({ name: e, installed: t, ambient: n }); if (u !== null && u !== c) d.push({ name: "gateway.port", installed: String(u), ambient: String(c) }); if (d.length === 0) return u ?? c; const f = d.map(({ name: e, installed: t, ambient: n }) => `- ${e}: installed=${JSON.stringify(t)}, ambient=${JSON.stringify(n)}`).join("\n"); throw new Error(`Refusing to repair the managed Gateway service because the current invocation targets a different Gateway:\n${f}\nRun \`openclaw gateway ${e.action}\` with the installed state directory, config path, and port (or unset conflicting environment overrides). To retarget intentionally, run \`openclaw gateway install --force\`.`); } async function repairLoadedGatewayServiceForStart(e) { assertGatewayServiceMutationAllowed("repair the gateway service"); const t = await e.service.readDefinitionMutationCapability?.({ env: process.env, environment: e.state.env }).catch(() => ({ kind: "unknown", reason: "inspection-failed" })); if (t) assertServiceDefinitionWritable(t); if (hasGatewayServiceLauncherOverride(e.state.command) || hasGatewayServiceEnvironmentDifference(e.state.command, GATEWAY_TARGET_ENV_KEYS)) { if (process.platform === "win32") throw new Error("Refusing to repair the managed Gateway service because an operator-owned Scheduled Task override changes its command, working directory, or Gateway target environment. Inspect the task's registered action and working directory in Task Scheduler, then resolve the override before retrying."); const t = path.basename(e.state.command?.sourcePath ?? "<unit>"); throw new Error(`Refusing to repair the managed Gateway service because a systemd drop-in overrides its command, working directory, or Gateway target environment. Inspect the unit with \`systemctl --user cat ${t}\`, then update or remove the operator-owned drop-in before retrying.`); } const n = resolveManagedGatewayServiceCommand(e.state.command); const { snapshot: r, writeOptions: i } = await readConfigFileSnapshotForWrite(); const a = r.valid ? r.sourceConfig : r.config; const o = n?.environment; const s = n?.environmentValueSources; const c = parseTcpPortFromArgs(n?.programArguments); const l = assertGatewayRepairTargetMatches({ action: e.action ?? "start", config: a, existingEnvironment: o, installedPort: c }); const u = mergeInstallInvocationEnv({ env: process.env, existingServiceEnv: o }); const d = await resolveOpenClawWrapperPath(u[OPENCLAW_WRAPPER_ENV_KEY]); const f = await withDaemonRuntimePinMigration(u, () => readDaemonRuntimePin({ kind: "gateway", env: u }, e.state.command)); const p = d ? void 0 : f.pin?.path; const m = !d && f.pin?.runtime || resolveGatewayDaemonRuntime(p ? [p] : n?.programArguments); if (!d) await resolvePinnedDaemonRuntimePath(p, m, u); const h = m === "bun" || m === "standalone" ? p ?? n?.programArguments[0] : void 0; if (m === "standalone" && !p) await resolvePinnedDaemonRuntimePath(h, "standalone", u); const g = h && m === "bun" ? await resolveBunRuntimeInfo(h) : void 0; if (g?.status === "probe-failed") throw g.error; if (g?.status === "unsupported" && g.sqliteSelectionError) throw new Error(g.sqliteSelectionError); const _ = p || m === "standalone" ? m : g?.status === "supported" ? "bun" : "node"; const v = await resolveGatewayInstallToken({ config: a, env: u, generateIfMissing: { snapshot: r, writeOptions: i } }); if (v.unavailableReason) throw new Error(v.unavailableReason); const y = [formatGatewayServiceStartRepairIssues(e.issues), ...v.warnings].filter((e) => e.trim().length > 0); if (!e.json) { defaultRuntime.log("Gateway service definition needs repair:"); for (const e of y) defaultRuntime.log(`- ${e}`); } const { programArguments: b, workingDirectory: x, environment: S, environmentValueSources: C } = await buildGatewayInstallPlan({ env: u, port: l, runtime: _, runtimePath: _ === "bun" || _ === "standalone" ? h : void 0, pinnedRuntimePath: f.pin?.path, wrapperPath: d, existingCommand: e.state.command, existingEnvironment: o, existingEnvironmentValueSources: s, config: a, warn: (t) => { y.push(t); if (!e.json) defaultRuntime.log(`- ${t}`); } }); await e.service.install({ runtimePinUpdate: { expected: f, pin: f.pin }, env: u, stdout: e.stdout, warn: e.warn, programArguments: b, workingDirectory: x, environment: S, environmentValueSources: C }); const w = await e.service.isLoaded({ env: u }); if (!w) throw new Error("Gateway service is not loaded after repair."); return { result: e.action === "restart" ? "restarted" : "started", message: e.action === "restart" ? "Gateway service definition repaired and restarted." : "Gateway service definition repaired and started. Reopen the Control UI with `openclaw dashboard` or copy a fresh auth URL with `openclaw dashboard --no-open`.", warnings: y.length ? y : void 0, loaded: w }; } //#endregion //#region src/cli/daemon-cli/lifecycle.ts function postRestartHealthAttempts() { return process.platform === "win32" ? Math.ceil(resolveGatewayStartupTiming().deadlineMs / 500) : DEFAULT_RESTART_HEALTH_ATTEMPTS; } async function handleSystemScopeSystemdGateway(e) { if (process.platform !== "linux") return null; const t = await findInstalledSystemdGatewayScope(process.env).catch(() => null); if (t?.scope !== "system") return null; const n = createNullWriter(); await (e === "stop" ? stopSystemdService : restartSystemdService)({ stdout: n, env: process.env, onMutation: createGatewayLifecycleMutationAudit({ action: e }) }); const r = e === "stop" ? "stopped" : "restarted"; return { result: r, message: `Gateway ${r} via system-scope systemd unit ${t.unitName}.` }; } async function stopGatewayWithoutServiceManager(e, t, n) { const r = await handleSystemScopeSystemdGateway("stop"); if (r) return r; const i = mergeGatewayServiceEnv(n?.env ?? process.env, n?.command ?? null); const a = captureStalledGatewayStartup(i); if (a) { await stopStalledGatewayStartup(a, assertGatewayServiceUpdateCurrent); appendGatewayLifecycleAudit({ action: "stop", source: "cli", mode: "sigterm", pid: a.pid, env: i }); return { result: "stopped", message: `Stopped stalled Gateway startup pid ${a.pid}.` }; } const o = findVerifiedGatewayListenerPidsOnPortSync(e, { env: i }); const s = o.length > 0 ? o : t ? [t] : []; if (s.length === 0) { const t = await resolveGatewayServiceProbeHosts(n ?? {}); const r = await probePortUsage(e, t); if (r !== "free") throw new Error(r === "busy" ? `Port ${e} is in use but the owning process could not be identified.` : `Could not determine whether port ${e} is still in use, so the gateway cannot be confirmed stopped.`); return null; } for (const t of s) { signalVerifiedGatewayPidSync(t, "SIGTERM", { env: i, port: e }); appendGatewayLifecycleAudit({ action: "stop", source: "cli", mode: "sigterm", pid: t }); } return { result: "stopped", message: `Gateway stop signal sent to unmanaged process${s.length === 1 ? "" : "es"} on port ${e}: ${formatGatewayPidList(s)}.` }; } function resolveRestartListenerHealthWait(e) { const t = resolveGatewayRestartDrainTimeoutMs(e); const n = postRestartHealthAttempts() + Math.ceil((t ?? 0) / 500); return { attempts: n, waitIndefinitelyForPreviousOwner: t === void 0, timeoutSeconds: Math.round(n * 500 / 1e3) }; } async function restartUnmanaged(e, t, n = true) { const r = n ? await handleSystemScopeSystemdGateway("restart") : null; if (r) return r; return await signalGatewayRestart(e, { restartIntent: t, enforceRestartConfig: true, processLabel: "unmanaged", auditSource: "cli" }); } function isGatewaySignalRestartResult(e) { return e !== null && "pid" in e && typeof e.pid === "number"; } async function runExternalSupervisorRestart(e) { const { emitMessage: t, fail: n } = createDaemonActionContext({ action: "restart", json: Boolean(e.json) }); const r = resolveGatewayRestartIntentOptions(e); const i = await readActiveGatewayLockIdentity().catch(() => void 0); if (!i?.ownerId) { n("Gateway restart failed: the active Gateway lock predates targeted restart ownership; update the running Gateway before retrying"); return false; } if (e.safe) return await runSafeGatewayRestart(e, { ...i, ownerId: i.ownerId }); let a; try { a = await signalGatewayRestart(i.port, { restartIntent: r, enforceRestartConfig: false, processLabel: "externally supervised", auditSource: "supervisor" }); } catch (e) { n(`Gateway restart failed: ${String(e)}`); return false; } if (!a) { n(`No verified gateway process is listening on port ${i.port}. ${formatExternalSupervisorActionRequired("start the gateway")}`); return false; } const o = resolveRestartListenerHealthWait(r); let s; try { s = await waitForGatewayHealthyListener({ port: i.port, attempts: o.attempts, delayMs: 500, previousLockIdentity: a.previousLockIdentity, waitIndefinitelyForPreviousOwner: o.waitIndefinitelyForPreviousOwner, signal: getAsyncWorkSignal() }); } catch (e) { if (!commandInterrupted(e)) throw e; return false; } if (!s.healthy) { n(`Gateway restart timed out after ${o.timeoutSeconds}s waiting for health checks.`, renderGatewayPortHealthDiagnostics(s)); return false; } t({ ok: true, result: a.result, message: a.message }); return true; } function renderGatewayServiceStopHints() { return [`Run ${formatCliCommand("openclaw gateway status --deep")} to inspect the service, then retry.`]; } function renderGatewayServiceUninstallHints() { return [...renderGatewayServiceStopHints(), "To remove the service manually, see https://docs.openclaw.ai/install/uninstall#manual-service-removal-cli-not-installed"]; } /** Uninstall the managed Gateway service after stopping it. */ async function runDaemonUninstall(e = {}) { assertGatewayServiceMutationAllowed("uninstall the gateway service"); return await runServiceUninstall({ serviceNoun: "Gateway", service: resolveGatewayService(), renderFailureHints: renderGatewayServiceUninstallHints, opts: e, stopBeforeUninstall: true, assertNotLoadedAfterUninstall: true }); } /** Start the managed Gateway service, repairing stale service definitions when possible. */ async function runDaemonStart(e = {}) { assertGatewayServiceMutationAllowed("start the gateway"); const t = resolveGatewayService(); const n = (await resolveGatewayConfigPorts()).explicit; return await runServiceStart({ serviceNoun: "Gateway", service: t, renderStartHints: renderGatewayServiceStartHints, onNotLoaded: process.platform === "darwin" ? async () => { const e = await recoverInstalledLaunchAgent({ result: "started" }); if (e) appendGatewayLifecycleAudit({ action: "start", source: "cli", mode: "launchd-bootstrap" }); return e; } : void 0, repairLoadedService: async ({ json: e, stdout: n, warn: r, state: i, issues: a }) => await repairLoadedGatewayServiceForStart({ service: t, json: e, stdout: n, warn: r, state: i, issues: a }), postStartCheck: async ({ fail: e, warnings: r }) => { const { deadlineMs: i } = resolveGatewayStartupTiming(); const a = await resolveGatewayLifecycleContext(t); const o = n ?? a.port; const s = performance.now() + i; const c = Math.ceil(i / 500); const l = createGatewayRestartDeadline({ timeoutMs: i, signal: getAsyncWorkSignal() }); const [u, d] = await Promise.all([withCommandProcessScope(() => waitForGatewayHealthyRestart({ service: t, port: o, attempts: c, delayMs: 500, timeoutMs: i, deadline: l, deadlineOutcome: "snapshot", env: a.env, supervisorKeepsAlive: process.platform === "darwin", signal: getAsyncWorkSignal() }), l.signal).finally(() => l.dispose()), waitForGatewayHttpReadiness({ config: a.config, port: o, attempts: c, deadlineAt: s, delayMs: 500, signal: getAsyncWorkSignal() })]); if (u.healthy && d.healthz === 200 && d.readyz === 200) return; r.push(...renderRestartDiagnostics(u)); r.push(`Gateway HTTP readiness: /healthz=${d.healthz ?? "unreachable"}; /readyz=${d.readyz ?? "unreachable"}.`); e(formatGatewayRestartFailure({ health: u, port: o, defaultTimeoutSeconds: Math.round(i / 1e3), action: "start" }).failMessage, [formatCliCommand("openclaw gateway status --deep"), formatCliCommand("openclaw doctor")], u.waitOutcome === "still-starting" ? "still-starting" : void 0); }, expectedPort: n, opts: e }); } /** Stop the managed Gateway service or verified unmanaged listener fallback. */ async function runDaemonStop(e = {}) { if (!isTerminalInteractive() && !e.force) { const { fail: t } = createDaemonActionContext({ action: "stop", json: Boolean(e.json) }); t(NON_INTERACTIVE_GATEWAY_STOP_MESSAGE); return; } assertGatewayServiceUpdateCurrent(); assertGatewayServiceMutationAllowed("stop the gateway"); const t = resolveGatewayService(); return await runServiceStop({ serviceNoun: "Gateway", service: t, renderFailureHints: renderGatewayServiceStopHints, opts: e, stopWhenNotLoaded: process.platform === "darwin" && Boolean(e.disable), onNotLoaded: async ({ stdout: e }) => { if (process.platform === "linux") { if ((await t.readRuntime(process.env).catch(ignoreNonCleanupCommandError))?.status === "running") { await t.stop({ env: process.env, stdout: e, onMutation: createGatewayLifecycleMutationAudit({ action: "stop" }) }); return { result: "stopped" }; } } assertGatewayServiceFallbackAllowed("unmanaged stop"); const n = await readActiveGatewayLockIdentity().catch(() => void 0); const r = n ? null : await resolveGatewayLifecycleContext(t).catch(ignoreNonCleanupCommandError); return await stopGatewayWithoutServiceManager(n?.port ?? r?.port ?? (await resolveGatewayConfigPorts()).fallback, n?.pid, r ?? void 0); } }); } /** Restart the Gateway service or a verified unmanaged listener, then prove health. */ async function runDaemonRestart(e = {}) { let t = Boolean(e.preserveDefinition); if (t) { assertGatewayServiceMutationAllowed("restart the gateway"); if (e.safe) throw new Error("--preserve-definition requires a native restart without --safe"); } if (e.skipDeferral && !e.safe) throw new Error("--skip-deferral requires --safe"); if (isGatewayExternallySupervised()) { assertGatewayServiceFallbackAllowed("external-supervisor restart"); return await runExternalSupervisorRestart(e); } if (e.safe) { assertGatewayServiceFallbackAllowed("safe RPC restart"); return await runSafeGatewayRestart(e); } const n = Boolean(e.json); const r = resolveGatewayService(); let i = false; let a; const o = resolveGatewayRestartIntentOptions(e); const { explicit: s, fallback: c } = await resolveGatewayConfigPorts(); let l = await resolveGatewayLifecycleContext(r, t).catch(async (e) => { if (hasCommandProcessCleanupError(e)) throw e; if (t) throw e; return { port: c, env: process.env }; }); let u = t ? l.port : s ?? l.port; let d = await readActiveGatewayLockPort().catch(() => void 0) ?? u; const f = postRestartHealthAttempts(); const p = f * 500; const m = Math.round(p / 1e3); let h; return runServiceRestart({ serviceNoun: "Gateway", service: r, renderStartHints: renderGatewayServiceStartHints, opts: { ...e, ...o ? { restartIntent: o } : {} }, checkTokenDrift: true, expectedPort: s, beforeServiceMutation: () => assertGatewayServiceMutationAllowed("restart the gateway"), restartOwnedProcess: t ? void 0 : async () => { const e = readGatewayOwnerLease(); if (!e || e.state === "dead" || e.mode !== "foreground") return null; assertGatewayServiceFallbackAllowed("foreground owner restart"); if (e.state !== "live") throw new Error(`Cannot verify foreground Gateway owner pid ${e.pid} on ${e.host}`); d = e.port; if (!(await waitForGatewayHealthyListener({ port: e.port, env: process.env, attempts: f, delayMs: 500, signal: getAsyncWorkSignal() })).healthy) throw new Error(`Foreground Gateway owner pid ${e.pid} is still starting or unhealthy on port ${e.port}; it was left running`); const t = await signalGatewayRestart(e.port, { restartIntent: o, enforceRestartConfig: true, processLabel: "foreground", auditSource: "cli", ownerLease: e, env: process.env }); if (!t) throw new Error(`Foreground Gateway owner pid ${e.pid} no longer listens on port ${e.port}`); i = true; a = t.previousLockIdentity; h = resolveRestartListenerHealthWait(o); return t; }, repairLoadedService: t ? void 0 : async ({ json: e, stdout: t, warn: n, state: i, issues: a }) => { const o = await repairLoadedGatewayServiceForStart({ action: "restart", service: r, json: e, stdout: t, warn: n, state: i, issues: a }); l = await resolveGatewayLifecycleContext(r); u = s ?? l.port; return o; }, onNotLoaded: async () => { assertGatewayServiceFallbackAllowed("unmanaged restart"); if (t) return null; const e = resolveGatewayServiceMutationError("restart the gateway"); if (process.platform === "darwin" && !e) { const e = await recoverInstalledLaunchAgent({ result: "restarted" }); if (e) { appendGatewayLifecycleAudit({ action: "restart", source: "cli", mode: "launchd-bootstrap" }); return e; } } const n = await restartUnmanaged(d, o, !e); if (n) { i = true; if (isGatewaySignalRestartResult(n) && n.previousLockIdentity) { a = n.previousLockIdentity; h = resolveRestartListenerHealthWait(o); } return n; } if (e) throw e; return null; }, postRestartCheck: async ({ warnings: e, fail: o, stdout: s, warn: c, activationAccepted: g, preserveDefinition: _ }) => { if (_) { t = true; u = l.port; } let v = g; const reportHealthFailure = (t, r) => { if (n) { e.push(...t, ...r); return; } for (const e of t) defaultRuntime.log(theme.warn(e)); for (const e of r) defaultRuntime.log(theme.muted(e)); }; if (i) { const e = await waitForGatewayHealthyListener({ port: d, env: process.env, attempts: h?.attempts ?? f, delayMs: 500, signal: getAsyncWorkSignal(), ...a ? { previousLockIdentity: a, waitIndefinitelyForPreviousOwner: h?.waitIndefinitelyForPreviousOwner ?? false } : {} }); if (e.healthy) return; const t = renderGatewayPortHealthDiagnostics(e); const n = h?.timeoutSeconds ?? m; reportHealthFailure([`Timed out after ${n}s waiting for gateway port ${d} to become healthy.`], t); o(`Gateway restart timed out after ${n}s waiting for health checks.`, [formatCliCommand("openclaw gateway status --deep"), formatCliCommand("openclaw doctor")], v ? "restart-health-failed" : void 0); throw new Error("unreachable after gateway restart health failure"); } const waitForHealthy = async () => await waitForGatewayHealthyRestart({ service: r, port: u, attempts: f, delayMs: 500, ...process.platform === "win32" ? { timeoutMs: p } : {}, env: l.env, ...l.env.OPENCLAW_UPDATE_IN_PROGRESS !== "1" ? { requirePluginHealth: false } : {}, supervisorKeepsAlive: process.platform === "darwin", signal: getAsyncWorkSignal() }); let y = await waitForHealthy(); if (!y.healthy && y.staleGatewayPids.length > 0) { const i = `Found stale gateway process(es): ${y.staleGatewayPids.join(", ")}.`; e.push(i); if (!n) { defaultRuntime.log(theme.warn(i)); defaultRuntime.log(theme.muted("Stopping stale process(es) and retrying restart...")); } const a = await terminateStaleGatewayPids(y.staleGatewayPids, { env: l.env, assertCurrent: assertGatewayServiceUpdateCurrent }); const o = readGatewayOwnerLease({ env: l.env }); if (a.length > 0 && (!o || o.state === "dead")) { const e = await r.restart({ preserveDefinition: t, env: process.env, stdout: s, warn: c, onMutation: createGatewayLifecycleMutationAudit({ action: "restart" }) }); if (e.outcome === "scheduled") return e; v = true; } y = await waitForHealthy(); } if (y.healthy) return; const b = renderRestartDiagnostics(y); const x = formatGatewayRestartFailure({ health: y, port: u, defaultTimeoutSeconds: m }); const S = y.waitOutcome !== "still-starting" && y.runtime.status === "running" && y.portUsage.status === "free" ? `Gateway process is running but port ${u} is still free (startup hang/crash loop or very slow VM startup).` : null; reportHealthFailure([x.statusLine, ...S ? [S] : []], b); o(x.failMessage, [formatCliCommand("openclaw gateway status --deep"), formatCliCommand("openclaw doctor")], y.waitOutcome === "still-starting" ? l.env.OPENCLAW_UPDATE_IN_PROGRESS === "1" ? "restart-health-failed" : "still-starting" : v ? "restart-health-failed" : void 0); throw new Error("unreachable after gateway restart failure"); } }); } //#endregion export { runDaemonRestart, runDaemonStart, runDaemonStop, runDaemonUninstall };