UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

758 lines (757 loc) • 31.4 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { D as parseStrictPositiveInteger, T as parseStrictInteger } from "./number-coercion-D6u-4YD8.mjs"; import { d as resolveGatewayLaunchAgentLabel, n as GATEWAY_SERVICE_KIND, r as GATEWAY_SERVICE_MARKER } from "./constants-BZisy3jr.mjs"; import "./utils-C8YECn2Q.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { a as isPidDefinitelyDead, i as isPidAlive, t as getFileLockProcessStartTime } from "./pid-alive-D899x-ak.mjs"; import { i as hasCommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { i as ServiceInspectionError } from "./service-inspection-error-BKgh5HDJ.mjs"; import { t as resolveServiceManagerEnv } from "./service-process-env-03_YbuSP.mjs"; import { t as createManagedHandoffLeaseStore } from "./update-managed-service-handoff-lease-CLrAwep3.mjs"; import { r as readGatewayOwnerLease } from "./gateway-owner-lease-I0ETcEQK.mjs"; import { r as getSelfAndAncestorPidsSync, t as cleanStaleGatewayProcessesSync } from "./restart-stale-pids-GhDopwa0.mjs"; import { t as resolveDaemonHomeDir } from "./paths-CNsU_DAo.mjs"; import { c as withGatewayServiceInstallationRecovery, i as assertGatewayServiceUpdateCurrent, o as isUpdateOwnedGatewayServiceCommand } from "./service-update-authority-wlK0pAdP.mjs"; import { n as normalizeWindowsPathSeparators, r as writeFormattedLines, t as formatLine } from "./output-D4pCmbg2.mjs"; import { l as readLockPayloadSync, u as resolveGatewayLockPaths } from "./gateway-lock-IYOwJQai.mjs"; import { a as writeGatewayServiceRestartIntentSync, r as prepareGatewayRestartIntentLegacyProcess, s as GatewayRestartPreparationError } from "./restart-intent-D5xKHHxG.mjs"; import { t as mergeGatewayServiceEnv } from "./service-env-merge-994N__ny.mjs"; import { t as resolveUpdateInstallRoot } from "./update-install-root-U1Z-3dbz.mjs"; import { n as resolveLaunchAgentLabel, t as assertValidLaunchAgentLabel } from "./launchd-label-DdmmL_TH.mjs"; import { n as probePortUsage } from "./ports-probe-DVN9Sc3E.mjs"; import { b as isLaunchctlNotLoaded, c as resolveLaunchAgentPlistPathForLabel, d as assertNoSystemLaunchDaemonOwnership, l as rewriteLaunchAgentPlistForRestart, m as isSystemLaunchDaemonOwnershipError, n as readExistingLaunchAgentPlist, r as removeBootedOutLaunchAgentPlist, s as resolveLaunchAgentPlistPath, t as captureLaunchAgentInstallFiles, u as writeLaunchAgentPlist, v as execLaunchctl, y as formatLaunchctlResultDetail } from "./launchd-service-files-BgSRMq9s.mjs"; import { s as readLaunchAgentProgramArgumentsFromFile } from "./launchd-plist-wGTZ-pik.mjs"; import { a as isLaunchctlAlreadyLoaded, f as readLaunchAgentProgramArguments, g as resolveLaunchAgentGuiDomain, h as resolveLaunchAgentGatewayContext, l as parseLaunchctlJob, o as isUnsupportedGuiDomain, p as readLaunchAgentRuntime, r as isLaunchAgentEnabled, t as bootstrapLaunchAgentOrThrow, u as probeLaunchAgentState } from "./launchd-runtime-DS9pQoDc.mjs"; import { r as resolveServiceProcessMembershipBlock, t as inspectServiceProcessMembershipSync } from "./service-process-membership-B9vnW59t.mjs"; import { r as formatPortDiagnostics } from "./ports-format-BBqs9qRU.mjs"; import { n as inspectPortUsage } from "./ports-inspect-DjJ_TGZf.mjs"; import { n as scheduleDetachedLaunchdRestartHandoff, t as scheduleDetachedLaunchdMaintenancePark } from "./launchd-restart-handoff-C8Iy_8IG.mjs"; import { t as createGatewayLifecycleMutationReporter } from "./service-mutation-DD9C-blM.mjs"; import path from "node:path"; import fs from "node:fs/promises"; import { isDeepStrictEqual } from "node:util"; import { spawnSync } from "node:child_process"; //#region src/daemon/launchd-current-service.ts /** Detects native launchd membership, including children reparented after ancestor exit. */ /** Environment hints for launchd identity; inherited markers do not prove ancestry. */ function isCurrentProcessLaunchdServiceLabel(e, t = process.env) { return [ t.LAUNCH_JOB_LABEL, t.LAUNCH_JOB_NAME, t.XPC_SERVICE_NAME ].some((t) => normalizeOptionalString(t) === e) || normalizeOptionalString(t.OPENCLAW_LAUNCHD_LABEL) === e && normalizeOptionalString(t.OPENCLAW_SERVICE_MARKER) === "openclaw" && Boolean(normalizeOptionalString(t.OPENCLAW_SERVICE_KIND)); } /** A completed parent walk alone cannot exclude reparented members of a launchd job. */ async function isCurrentProcessInsideLaunchdService(e) { const t = await probeLaunchAgentState(`${resolveLaunchAgentGuiDomain()}/${e}`); if (t.state === "running" && t.runtime.pid !== void 0) { const e = getSelfAndAncestorPidsSync(); if (e.has(t.runtime.pid)) return true; const n = resolveServiceProcessMembershipBlock(inspectServiceProcessMembershipSync(t.runtime.pid, "darwin"), e.has(1), "darwin"); if (n === "inside-gateway-service") return true; if (n) throw new ServiceInspectionError(n); return false; } if (t.state === "unknown" || t.state === "running") throw new ServiceInspectionError("service-membership-unverified"); return false; } //#endregion //#region src/daemon/launchd-install.ts /** Transactional LaunchAgent installation, staging, rollback, and removal. */ async function uninstallLaunchAgent({ env: e, stdout: t }) { await assertExternalLaunchAgentMutation(e, "uninstall"); const n = resolveLaunchAgentGuiDomain(); const r = resolveLaunchAgentLabel(e); const i = resolveLaunchAgentPlistPath(e); if ((await probeLaunchAgentState(`${n}/${r}`)).state !== "not-loaded") await bootoutLaunchAgent(`${n}/${r}`); try { await fs.lstat(i); } catch (e) { if (e.code !== "ENOENT") throw createLaunchAgentRemovalError(e); t.write(`LaunchAgent not found at ${i}\n`); return; } const a = normalizeWindowsPathSeparators(resolveDaemonHomeDir(e)); const o = path.posix.join(a, ".Trash"); const s = path.join(o, `${r}-${Date.now()}.plist`); try { const { trashed: e } = await removeBootedOutLaunchAgentPlist(i, s); t.write(`${e ? formatLine("Moved LaunchAgent to Trash", s) : formatLine("Removed LaunchAgent", i)}\n`); } catch (e) { if (e.code === "ENOENT") try { await fs.lstat(i); } catch (e) { if (e.code === "ENOENT") { t.write(`LaunchAgent not found at ${i}\n`); return; } throw createLaunchAgentRemovalError(e); } throw createLaunchAgentRemovalError(e); } } function createLaunchAgentRemovalError(e) { const t = e.code; return /* @__PURE__ */ new Error(`LaunchAgent removal failed${t ? ` (${t})` : ""}. Check permissions and retry.`); } async function assertExternalLaunchAgentMutation(e, t) { const n = process.env.OPENCLAW_LAUNCHD_LABEL?.trim(); const r = /* @__PURE__ */ new Set([resolveLaunchAgentLabel(e), ...n ? [assertValidLaunchAgentLabel(n)] : []]); for (const n of r) if (await isCurrentProcessInsideLaunchdService(n)) throw new Error(`Refusing to ${t} LaunchAgent ${resolveLaunchAgentLabel(e)} from inside ${n}; run this command from an external shell.`); } async function stageLaunchAgent(e) { const { plistPath: t, stdoutPath: n } = await writeLaunchAgentPlist(e); writeFormattedLines(e.stdout, [{ label: "Staged LaunchAgent", value: t }, { label: "Logs", value: n }]); return { plistPath: t }; } async function bootoutLaunchAgent(e) { assertGatewayServiceUpdateCurrent(); const t = await execLaunchctl(["bootout", e]); assertGatewayServiceUpdateCurrent(); if (t.code !== 0 && !isLaunchctlNotLoaded(t)) throw new Error(`launchctl bootout failed: ${formatLaunchctlResultDetail(t)}`); } async function installLaunchAgent(e) { const t = resolveLaunchAgentPlistPath(e.env); const n = resolveLaunchAgentLabel(e.env); const r = resolveLaunchAgentGuiDomain(); const i = `${r}/${n}`; const { publication: a, loaded: o, restoreLoaded: s, enabled: c } = await withGatewayServiceInstallationRecovery(async () => { await assertExternalLaunchAgentMutation(e.env, "install"); const n = e.definitionTransaction ? { kind: "transaction", hooks: e.definitionTransaction } : { kind: "local", files: await captureLaunchAgentInstallFiles(e.env) }; const r = n.kind === "local" ? n.files.originals.get(t).snapshot : await readExistingLaunchAgentPlist(t); const a = e.preserveAutoStart ? await isLaunchAgentEnabled({ env: e.env }) : void 0; const o = await probeLaunchAgentState(i); if (o.state === "unknown") throw new Error(`launchctl print could not determine whether ${i} is loaded: ${o.detail ?? "unknown error"}`); const s = o.state !== "not-loaded"; const c = s && r !== null; if (s && !c) e.warn?.(`LaunchAgent ${i} plist is missing; replacing the registration without a previous definition to restore.`); return { publication: n, loaded: s, restoreLoaded: c, enabled: a }; }, async () => false); const bootstrap = (t, n) => bootstrapLaunchAgentOrThrow({ domain: r, serviceTarget: i, plistPath: t, actionHint: n, retryPendingTeardown: true, assertCurrent: assertGatewayServiceUpdateCurrent, preserveAutoStart: e.preserveAutoStart, preservedEnabled: c }); let l = false; const install = async () => { const t = await writeLaunchAgentPlist(e, a.kind === "local" ? a.files : void 0); await (a.kind === "local" ? a.files.assertCurrent() : a.hooks.beforeWrite()); await assertNoSystemLaunchDaemonOwnership(n); assertGatewayServiceUpdateCurrent(); l = true; if (o) await bootoutLaunchAgent(i); await bootstrap(t.plistPath, "openclaw gateway install --force"); assertGatewayServiceUpdateCurrent(); return t; }; const { plistPath: u, stdoutPath: d } = a.kind === "transaction" ? await install() : await withGatewayServiceInstallationRecovery(install, async () => { const e = a.files; if (l) { await e.assertCurrent(); const t = await probeLaunchAgentState(i); if (t.state === "unknown") throw new Error(`launchctl print could not determine whether ${i} is loaded during LaunchAgent rollback: ${t.detail ?? "unknown error"}`); if (t.state !== "not-loaded") { await e.assertCurrent(); await bootoutLaunchAgent(i); } } const r = await e.restore(); if (l && s) { await e.assertCurrent(); await assertNoSystemLaunchDaemonOwnership(n); await bootstrap(t, "openclaw gateway start"); } return r || l; }); writeFormattedLines(e.stdout, [{ label: "Installed LaunchAgent", value: u }, { label: "Logs", value: d }]); return { plistPath: u }; } //#endregion //#region src/daemon/launchd-lifecycle.ts const LAUNCHCTL_PROTECTED_PID_TIMEOUT_MS = 2e3; function readLaunchAgentPidForCleanupSync(e) { const t = spawnSync("launchctl", ["print", e], { env: resolveServiceManagerEnv(), encoding: "utf8", timeout: LAUNCHCTL_PROTECTED_PID_TIMEOUT_MS }); const n = { stdout: t.stdout ?? "", stderr: t.error?.message ?? t.stderr ?? "", code: t.error ? 1 : t.status ?? 1 }; if (n.code !== 0) throw new Error(`launchctl print failed: ${formatLaunchctlResultDetail(n)}`); const r = parseLaunchctlJob(n.stdout || n.stderr || "", e).runtime.pid; if (r === void 0) throw new Error("launchctl print did not report a running pid"); return r; } async function repairLaunchAgentBootstrap(e) { const t = e.env ?? process.env; const n = resolveLaunchAgentGuiDomain(); const r = resolveLaunchAgentLabel(t); const i = resolveLaunchAgentPlistPath(t); const a = `${n}/${r}`; try { await assertNoSystemLaunchDaemonOwnership(r); } catch (e) { if (!isSystemLaunchDaemonOwnershipError(e)) throw e; return { ok: false, status: e.ownership.status === "unverifiable" ? "system-launchdaemon-unverifiable" : "system-launchdaemon-conflict", detail: e.message }; } const o = e.warn ?? ((e) => console.warn(formatLine("Warning", e))); await rewriteLaunchAgentPlistForRestart({ env: t, label: r, plistPath: i, warn: o }); try { if (await bootstrapLaunchAgentOrThrow({ domain: n, serviceTarget: a, plistPath: i, actionHint: "openclaw gateway start", deadline: e.deadline }) === "bootstrapped") return { ok: true, status: "repaired" }; } catch (e) { if (hasCommandProcessCleanupError(e)) throw e; const t = e instanceof Error ? e.cause : void 0; if (!t || typeof t !== "object" || !("stderr" in t) || typeof t.stderr !== "string" || !("stdout" in t) || typeof t.stdout !== "string" || !("code" in t) || typeof t.code !== "number" || !("termination" in t)) throw e; const r = (t.stderr || t.stdout).trim(); if (isUnsupportedGuiDomain(r)) return { ok: false, status: "gui-session-unavailable", detail: r, domain: n }; if (t.termination !== "exit" || !isLaunchctlAlreadyLoaded({ code: t.code, termination: "exit", stderr: t.stderr, stdout: t.stdout })) return { ok: false, status: "bootstrap-failed", detail: r || void 0 }; } if ((await readLaunchAgentRuntime(t, { timeoutMs: e.deadline?.remainingMs() })).status === "running") return { ok: true, status: "already-loaded" }; const s = await execLaunchctl(["kickstart", a], e.deadline); if (s.code !== 0) return { ok: false, status: "kickstart-failed", detail: (s.stderr || s.stdout).trim() || void 0 }; return { ok: true, status: "already-loaded" }; } function writeLaunchAgentActionLine(e, t, n) { try { e.write(`${formatLine(t, n)}\n`); } catch (e) { if (e?.code !== "EPIPE") throw e; } } async function ensureLaunchAgentLoadedAfterFailure(e) { e.assertCurrent?.(); const t = await execLaunchctl(["print", e.serviceTarget], e.deadline); e.assertCurrent?.(); if (t.code === 0) return { loaded: true }; try { await bootstrapLaunchAgentOrThrow({ ...e, actionHint: "openclaw gateway start" }); return { loaded: true }; } catch (e) { if (hasCommandProcessCleanupError(e)) throw e; return { loaded: false, detail: e instanceof Error ? e.message : String(e) }; } } async function rethrowLaunchAgentActivationFailure(e, t) { if (hasCommandProcessCleanupError(t)) throw t; const n = await ensureLaunchAgentLoadedAfterFailure(e); const r = t instanceof Error ? t.message : String(t); throw new Error(n.loaded ? `${r}\nLaunchAgent ${e.serviceTarget} is loaded; launchd can retry its KeepAlive job. Run openclaw gateway status --deep to inspect startup.` : [ r, `LaunchAgent ${e.serviceTarget} is not loaded and could not be restored: ${n.detail}`, "The gateway is down and launchd has no job left to respawn it.", `Fix: run \`openclaw gateway start\`, or \`launchctl bootstrap ${e.domain} ${e.plistPath}\`.` ].join("\n"), { cause: t }); } async function needsLaunchAgentBootstrap(e, t, n, r) { if (e.code === 0 || isLaunchctlNotLoaded(e)) return e.code !== 0; n?.(); const i = await probeLaunchAgentState(t, r?.remainingMs()); n?.(); return i.state === "not-loaded"; } async function prepareLaunchAgentActivation(e, t) { const { assertCurrent: n, preserveAutoStart: r, preserveDefinition: i, onRestartAttempted: a, deadline: o } = e; const s = e.env ?? process.env; const c = resolveLaunchAgentGuiDomain(); const l = resolveLaunchAgentLabel(s); const u = resolveLaunchAgentPlistPath(s); const d = `${c}/${l}`; const f = createGatewayLifecycleMutationReporter(e.onMutation); await assertNoSystemLaunchDaemonOwnership(l); const p = { domain: c, serviceTarget: d, plistPath: u, onMutation: f, assertCurrent: n, preserveAutoStart: r, retryPendingTeardown: i, deadline: o }; const load = (e = {}) => bootstrapLaunchAgentOrThrow({ ...p, actionHint: `openclaw gateway ${t}`, ...e }); return { serviceEnv: s, label: l, plistPath: u, serviceTarget: d, reportMutation: f, async enable() { if (r) return false; n?.(); const e = await execLaunchctl(["enable", d], o); if (e.code === 0) f("enable"); return e.code === 0; }, bootstrap: load, async kickstart(e) { n?.(); if (t === "restart") a?.(); let r = await execLaunchctl([ "kickstart", ...t === "restart" ? ["-k"] : [], d ], o); if (t === "restart" && r.code === 0) { f("kickstart"); return; } if (await needsLaunchAgentBootstrap(r, d, n, o)) { await load({ skipEnable: e }); if (t === "restart" && !i) return; n?.(); r = await execLaunchctl(["kickstart", d], o); } if (r.code !== 0) throw new Error(`launchctl kickstart failed: ${r.stderr || r.stdout}`.trim()); if (t === "restart") f("kickstart"); }, rethrow: (e, t = i) => rethrowLaunchAgentActivationFailure({ ...p, retryPendingTeardown: t }, e) }; } async function startLaunchAgent(e) { const { stdout: t } = e; const n = await prepareLaunchAgentActivation(e, "start"); const r = await n.enable(); try { await n.kickstart(r); } catch (e) { await n.rethrow(e); } n.reportMutation("kickstart"); writeLaunchAgentActionLine(t, "Started LaunchAgent", n.serviceTarget); } async function restartLaunchAgent(e) { const { preserveDefinition: t, stdout: n, warn: r, assertCurrent: i } = e; const a = await prepareLaunchAgentActivation(e, "restart"); const { serviceEnv: o, label: s, plistPath: c, serviceTarget: l, reportMutation: u } = a; const d = await isCurrentProcessInsideLaunchdService(s); try { if (!d) { const { env: t, port: n, probeHosts: r } = await resolveLaunchAgentGatewayContext(o); if (n !== null) { assertGatewayServiceUpdateCurrent(); cleanStaleGatewayProcessesSync(n, { env: t, assertCurrent: assertGatewayServiceUpdateCurrent, resolveProtectedPid: () => { const e = readLaunchAgentPidForCleanupSync(l); assertGatewayServiceUpdateCurrent(); return e; } }); const i = await inspectPortUsage(n, { probeHosts: r }).catch(() => null); if (i?.status === "busy") { const t = (await readLaunchAgentRuntime(o, { timeoutMs: e.deadline?.remainingMs() })).pid; if (!(t !== void 0 && i.listeners.length > 0 && i.listeners.every((e) => e.pid === t))) throw new Error([`gateway port ${n} is busy but is not verifiably owned by LaunchAgent ${s}`, ...formatPortDiagnostics(i)].join("\n")); } } } } catch (e) { if (t) await a.rethrow(e); throw e; } const f = !t && await rewriteLaunchAgentPlistForRestart({ env: o, label: s, plistPath: c, stdout: n, warn: r }); if (d) { if (isUpdateOwnedGatewayServiceCommand()) throw new Error("UPDATE_NATIVE_AUTHORITY: update-owned native restart requires an external executor, not a detached service handoff."); const e = scheduleDetachedLaunchdRestartHandoff({ env: o, mode: f ? "reload" : "kickstart", waitForPid: process.pid }); if (!e.ok) throw new Error(`launchd restart handoff failed: ${e.error}`); if (!await e.value) throw new Error("launchd restart handoff failed: helper failed to spawn"); u(f ? "handoff-reload" : "handoff-kickstart"); writeLaunchAgentActionLine(n, "Scheduled LaunchAgent restart", l); return { outcome: "scheduled" }; } try { await a.enable(); if (f) { i?.(); const t = await execLaunchctl(["bootout", l], e.deadline); if (t.code !== 0 && !isLaunchctlNotLoaded(t)) throw new Error(`launchctl bootout failed: ${formatLaunchctlResultDetail(t)}`); if (t.code === 0) u("bootout"); await a.bootstrap({ retryPendingTeardown: true }); } else await a.kickstart(); } catch (e) { await a.rethrow(e, t || f); } writeLaunchAgentActionLine(n, "Restarted LaunchAgent", l); return { outcome: "completed" }; } //#endregion //#region src/daemon/launchd-stop.ts const LAUNCH_AGENT_STOP_PORT_RELEASE_TIMEOUT_MS = 330 * 1e3; const LAUNCH_AGENT_STOP_PORT_RELEASE_POLL_MS = 100; const LAUNCH_AGENT_STOP_TIMEOUT_MS = (330 + 10) * 1e3; function launchAgentStopError(e, t) { return /* @__PURE__ */ new Error(`${t}. Run \`launchctl bootout ${e}\` from an external terminal in the service owner's logged-in macOS GUI session.`); } function verifyLaunchAgentStopProbe(e, t) { if (t.state === "unknown") throw launchAgentStopError(e, `launchctl print could not verify LaunchAgent stop: ${t.detail ?? "unknown error"}`); if (t.state !== "running") return; if (t.runtime.pid === void 0) throw launchAgentStopError(e, "launchctl print reported a running job without a PID"); return t.runtime.pid; } async function waitForLaunchAgentUnloaded(e, t, n, r) { const i = new Set(t); const a = performance.now() + LAUNCH_AGENT_STOP_TIMEOUT_MS; let o = false; for (;;) { const t = await probeLaunchAgentState(e, 5e3); n?.(); const s = verifyLaunchAgentStopProbe(e, t); if (s !== void 0) i.add(s); const c = [...i].filter((e) => !isPidDefinitelyDead(e)); if (t.state === "not-loaded" && c.length === 0) return; if (t.state === "not-loaded" && !o) { o = true; r?.(c); } if (performance.now() >= a) throw launchAgentStopError(e, `LaunchAgent stop did not complete: ${e} is ${t.state === "not-loaded" ? "unloaded" : "still loaded"}${c.length ? `; PID ${c.join(", ")} is still alive` : ""}`); await sleep(Math.min(100, Math.max(0, a - performance.now()))); } } async function waitForGatewayPortRelease(e, t) { const n = performance.now() + LAUNCH_AGENT_STOP_PORT_RELEASE_TIMEOUT_MS; while (performance.now() < n) { await sleep(Math.min(LAUNCH_AGENT_STOP_PORT_RELEASE_POLL_MS, n - performance.now())); if (await probePortUsage(e, t) === "free") return true; } return false; } async function assertGatewayPortReleasedAfterStop(e, t) { const { env: n, port: r, probeHosts: i } = await resolveLaunchAgentGatewayContext(e); if (r === null) return; await t(); assertGatewayServiceUpdateCurrent(); cleanStaleGatewayProcessesSync(r, { env: n, assertCurrent: assertGatewayServiceUpdateCurrent }); const a = await inspectPortUsage(r, { probeHosts: i }).catch(() => null); if (a?.status !== "busy") return; if (await waitForGatewayPortRelease(r, i)) return; throw new Error([`gateway port ${r} is still busy after LaunchAgent stop`, ...formatPortDiagnostics(a)].join("\n")); } async function stopLaunchAgent({ stdout: e, env: t, disable: n, onMutation: r, assertCurrent: i, updateHandoff: a }) { const o = t ?? process.env; const s = resolveLaunchAgentGuiDomain(); const c = resolveLaunchAgentLabel(o); const l = `${s}/${c}`; const u = createGatewayLifecycleMutationReporter(r); const d = isUpdateOwnedGatewayServiceCommand(); let f = o; const assertNativeCurrent = () => { i?.(); assertGatewayServiceUpdateCurrent(); }; const p = await isCurrentProcessInsideLaunchdService(c); const assertStopCurrent = async () => { assertNativeCurrent(); const e = d && a ? createManagedHandoffLeaseStore().read(resolveUpdateInstallRoot(a.root)) : void 0; const t = e?.kind === "current" && (e.lease.helper.pid !== e.lease.executor.pid || e.lease.helper.startIdentity !== e.lease.executor.startIdentity); if (p || t || d && f.OPENCLAW_UPDATE_RUN_HANDOFF === "1") { if (!(d && a && await (await import("./update-managed-service-handoff-current-CraS00WL.mjs")).isCurrentManagedServiceUpdateHandoffProcess({ ...a, env: f }))) throw launchAgentStopError(l, `Refusing to stop LaunchAgent ${c} from inside the same launchd service`); } assertNativeCurrent(); }; await assertStopCurrent(); const m = verifyLaunchAgentStopProbe(l, await probeLaunchAgentState(l, 5e3)); const h = new Set(m === void 0 ? [] : [m]); let g; let _ = assertNativeCurrent; let v; try { if (d) { const e = await readLaunchAgentProgramArguments(o, { requireEffective: true }); assertNativeCurrent(); if (!e) throw new GatewayRestartPreparationError("service-command"); f = mergeGatewayServiceEnv(o, e); await assertStopCurrent(); const t = readGatewayOwnerLease({ env: f, current: true }); const n = t ? void 0 : resolveGatewayLockPaths(f).stateLockPath; const r = n ? readLockPayloadSync(n, true) : void 0; const i = await prepareGatewayRestartIntentLegacyProcess({ env: f, command: e, runtimePid: m, readRuntime: () => readLaunchAgentRuntime(o), assertCurrent: assertNativeCurrent }); const a = await probeLaunchAgentState(l, 5e3); await assertStopCurrent(); if (verifyLaunchAgentStopProbe(l, a) !== m) throw new GatewayRestartPreparationError("serving-owner"); const assertIntentCurrent = () => { assertNativeCurrent(); if (i && (!r || !n || !isPidAlive(i.pid) || getFileLockProcessStartTime(i.pid, f) !== i.startTime || !isPidAlive(r.pid) || getFileLockProcessStartTime(r.pid, f) !== r.startTime || !isDeepStrictEqual(r, readLockPayloadSync(n, true)))) throw new GatewayRestartPreparationError("serving-owner"); const e = readGatewayOwnerLease({ env: f, current: true }); if (e?.owner !== t?.owner || e?.pid !== t?.pid || e?.startedAt !== t?.startedAt || e?.state !== t?.state) throw new GatewayRestartPreparationError("serving-owner"); }; _ = assertIntentCurrent; writeGatewayServiceRestartIntentSync({ env: f, service: { kind: "launchd", name: c }, nativePid: m, nativeStopped: a.state !== "running", legacyProcess: i, reason: "update.run", assertCurrent: assertIntentCurrent, onRecorded: (e) => { g = e; } }); const s = t?.pid ?? r?.pid; if (s !== void 0) h.add(s); } if (n) { await assertStopCurrent(); _(); const e = await execLaunchctl(["disable", l]); if (e.code === 0) u("disable"); else v = `launchctl disable failed; used bootout fallback without persisting disable: ${formatLaunchctlResultDetail(e)}`; } await assertStopCurrent(); _(); const e = await execLaunchctl(["bootout", l], LAUNCH_AGENT_STOP_TIMEOUT_MS); if (e.code !== 0 && !isLaunchctlNotLoaded(e)) throw launchAgentStopError(l, `launchctl bootout failed: ${formatLaunchctlResultDetail(e)}`); } catch (e) { g?.(); throw e; } u(n ? "disable-bootout" : "bootout"); await waitForLaunchAgentUnloaded(l, [...h], i, (t) => { e.write(`${formatLine("Warning", `Waiting for Gateway PID ${t.join(", ")} to exit and release its databases before continuing.`)}\n`); }); if (v) e.write(`${formatLine("Warning", v)}\n`); await assertGatewayPortReleasedAfterStop(o, assertStopCurrent); i?.(); e.write(`${formatLine(v ? "Stopped LaunchAgent (degraded)" : "Stopped LaunchAgent", l)}\n`); } async function parkCurrentLaunchAgentForMaintenance() { const e = process.env; const t = resolveLaunchAgentGuiDomain(); const n = resolveLaunchAgentLabel(e); if (!await isCurrentProcessInsideLaunchdService(n)) return false; const r = `${t}/${n}`; const i = await execLaunchctl(["disable", r]); if (i.code !== 0) throw new Error(`launchctl disable failed while parking ${r}: ${formatLaunchctlResultDetail(i)}`); const a = scheduleDetachedLaunchdMaintenancePark({ env: e, waitForPid: process.pid }); const o = !a.ok ? a.error : await a.value ? void 0 : "helper failed to spawn"; if (o) { const e = await execLaunchctl(["enable", r]); const t = e.code === 0 ? "restored launchd enable state" : `launchctl enable rollback failed: ${formatLaunchctlResultDetail(e)}`; throw new Error(`launchd maintenance park handoff failed: ${o}; ${t}`); } return true; } //#endregion //#region src/daemon/launchd-update-jobs.ts const OPENCLAW_UPDATE_LAUNCHD_LABEL_PREFIX = "ai.openclaw.update."; const MANUAL_UPDATE_LAUNCHD_LABEL_PATTERN = /^ai\.openclaw\.manual-update\.\d+$/; const OPENCLAW_PROFILE_UPDATE_LAUNCHD_LABEL_PATTERN = /^ai\.openclaw\.[A-Za-z0-9._-]+\.update\.[A-Za-z0-9._-]+$/; const OPENCLAW_DIRECT_CLI_NAMES = /* @__PURE__ */ new Set(["openclaw", "openclaw.mjs"]); const OPENCLAW_NODE_RUNTIME_NAMES = /* @__PURE__ */ new Set([ "bun", "bun.exe", "node", "node.exe" ]); function normalizeOpenClawUpdateLaunchdLabelCandidate(e) { if (typeof e !== "string") return null; const t = e.trim(); if (t.startsWith(OPENCLAW_UPDATE_LAUNCHD_LABEL_PREFIX) || MANUAL_UPDATE_LAUNCHD_LABEL_PATTERN.test(t)) return { label: t, requiresMetadata: false }; return OPENCLAW_PROFILE_UPDATE_LAUNCHD_LABEL_PATTERN.test(t) ? { label: t, requiresMetadata: true } : null; } function isCurrentGatewayLaunchdLabel(e, t) { if (e === resolveGatewayLaunchAgentLabel(t.OPENCLAW_PROFILE)) return true; if (t.OPENCLAW_SERVICE_MARKER?.trim() !== "openclaw" || t.OPENCLAW_SERVICE_KIND?.trim() !== "gateway") return false; const n = t.OPENCLAW_LAUNCHD_LABEL?.trim(); return Boolean(n && e === n); } function resolveCurrentOpenClawUpdateLaunchdJobLabel(e = process.env) { for (const t of [ e.LAUNCH_JOB_LABEL, e.LAUNCH_JOB_NAME, e.XPC_SERVICE_NAME, e.OPENCLAW_LAUNCHD_LABEL ]) { const n = normalizeOpenClawUpdateLaunchdLabelCandidate(t); if (n && !isCurrentGatewayLaunchdLabel(n.label, e)) return n; } return null; } function parseLaunchctlListOpenClawUpdateJobCandidates(e) { const t = []; for (const n of e.split(/\r?\n/)) { const e = n.trim(); if (!e) continue; const [r, i, ...a] = e.split(/\s+/); const o = normalizeOpenClawUpdateLaunchdLabelCandidate(a.join(" ")); if (!o) continue; const s = r === "-" ? void 0 : parseStrictPositiveInteger(r ?? ""); const c = parseStrictInteger(i ?? ""); t.push({ label: o.label, requiresMetadata: o.requiresMetadata, ...s !== void 0 ? { pid: s } : {}, ...c !== void 0 ? { lastExitStatus: c } : {} }); } return t.toSorted((e, t) => e.label.localeCompare(t.label)); } function hasOpenClawUpdateLaunchdMarker(e) { return e?.OPENCLAW_UPDATE_RUN_HANDOFF?.trim() === "1"; } function isOpenClawUpdateProgramArguments(e) { if (!Array.isArray(e) || e.length === 0) return false; const t = e.findIndex((e) => e.trim() === "update"); if (t < 0 || !e.slice(t + 1).includes("--yes")) return false; const n = path.basename(e[0] ?? "").toLowerCase(); return (t === 1 ? OPENCLAW_DIRECT_CLI_NAMES.has(n) : t === 2 && OPENCLAW_NODE_RUNTIME_NAMES.has(n) && path.basename(e[1] ?? "").toLowerCase() === "openclaw.mjs") && !e.some((e) => e.trim() === "gateway"); } async function isLaunchdJobConfirmedOpenClawUpdater(e) { const t = resolveLaunchAgentPlistPathForLabel(e.env, e.label); const n = await readLaunchAgentProgramArgumentsFromFile(t); return hasOpenClawUpdateLaunchdMarker(n?.environment) || isOpenClawUpdateProgramArguments(n?.programArguments); } async function findStaleOpenClawUpdateLaunchdJobs(e = process.env) { if (process.platform !== "darwin") return []; const t = await execLaunchctl(["list"]); if (t.code !== 0) return []; const n = []; for (const { requiresMetadata: r, ...i } of parseLaunchctlListOpenClawUpdateJobCandidates(t.stdout)) { if (isCurrentGatewayLaunchdLabel(i.label, e)) continue; if (r && !await isLaunchdJobConfirmedOpenClawUpdater({ label: i.label, env: e })) continue; n.push(i); } return n; } async function disableCurrentOpenClawUpdateLaunchdJob(e = process.env) { const t = resolveCurrentOpenClawUpdateLaunchdJobLabel(e); if (!t || process.platform !== "darwin") return false; const n = isCurrentProcessLaunchdServiceLabel(t.label, e); if (t.requiresMetadata && !(n && hasOpenClawUpdateLaunchdMarker(e) || await isLaunchdJobConfirmedOpenClawUpdater({ label: t.label, env: e }))) return false; const r = `${resolveLaunchAgentGuiDomain()}/${assertValidLaunchAgentLabel(t.label)}`; return (await execLaunchctl(["disable", r])).code === 0; } //#endregion export { repairLaunchAgentBootstrap as a, installLaunchAgent as c, stopLaunchAgent as i, stageLaunchAgent as l, findStaleOpenClawUpdateLaunchdJobs as n, restartLaunchAgent as o, parkCurrentLaunchAgentForMaintenance as r, startLaunchAgent as s, disableCurrentOpenClawUpdateLaunchdJob as t, uninstallLaunchAgent as u };