UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

522 lines (521 loc) • 17.7 kB
import { c as resolveLauncherStopTimeoutMs, o as RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS } from "./gateway-shutdown-budget-cDAYhBVI.mjs"; import { c as resolveOpenClawCliRespawn } from "./cli-invocation-ZSPsKRWa.mjs"; import { i as withNodeRuntimePath, t as nodeRuntimePathEntries } from "./node-runtime-env-ncloLK-i.mjs"; import { c as isUpdateCommandArgv, i as consumeRootOptionToken } from "./cli-root-options-xlQx6o4R.mjs"; import { r as isForegroundGatewayRunArgv } from "./gateway-run-argv-DfcBAs2-.mjs"; import { n as nodeRuntimeFailure, t as detectCurrentSqliteCapabilities } from "./node-sqlite-rcZh3Q1F.mjs"; import { t as createRuntimeProcessScriptFile } from "./runtime-process-scripts.generated-DGDjiipU.mjs"; import { lstatSync, readFileSync, readdirSync, realpathSync, statSync } from "node:fs"; import { fileURLToPath } from "node:url"; import path from "node:path"; import os from "node:os"; import { spawn, spawnSync } from "node:child_process"; //#region node-runtime-recovery.mjs const isNativeHookRelayInvocation = (e) => e[2] === "hooks" && e[3] === "relay"; const isForegroundGmailRunInvocation = (e) => { const t = e.slice(2); const n = []; for (let e = 0; e < t.length && n.length < 3; e += 1) { const r = consumeRootOptionToken(t, e); if (r > 0) e += r - 1; else if (!t[e] || t[e].startsWith("-")) break; else n.push(t[e]); } return n.join(" ") === "webhooks gmail run"; }; const respawnSignals = process.platform === "win32" ? [ "SIGTERM", "SIGINT", "SIGBREAK" ] : [ "SIGTERM", "SIGINT", "SIGHUP", "SIGQUIT" ]; const respawnSignalForceKillGraceMs = RESPAWN_SIGNAL_FORCE_KILL_GRACE_MS; /** * Startup-only bootstrap cannot depend on dist or installed packages, so this * mirrors formatErrorStackWithMessage * (packages/normalization-core/src/error-coercion.ts): Bun can materialize * `stack` during garbage collection with a bare header that drops the message. */ function formatRespawnErrorDetail(e) { const t = typeof e.name === "string" && e.name ? e.name : "Error"; const n = typeof e.message === "string" ? e.message : ""; const r = typeof e.stack === "string" ? e.stack : ""; if (!r || !n || r.includes(n)) return r || n || t; const i = `${t}: ${n}`; const a = r.indexOf("\n"); const o = a < 0 ? r : r.slice(0, a); return o === t ? i + r.slice(o.length) : `${i}\n${r}`; } /** Resolve true only after the replacement and its stdio close; the caller must return. */ const runRespawnedChild = ({ command: e, args: t, env: n }) => { const r = resolveLauncherStopTimeoutMs({ platform: process.platform, foreground: isForegroundGatewayRunArgv(process.argv), update: isUpdateCommandArgv(process.argv) }) - respawnSignalForceKillGraceMs; const i = process.stdin.isTTY || process.stdout.isTTY; const a = spawn(e, t, { stdio: [ "inherit", "inherit", "inherit", "ipc" ], env: n, windowsHide: !i }); const o = /* @__PURE__ */ new Map(); let s = null; let c = null; let l = null; let u = false; let d = false; const clearEscalation = () => { if (s) { clearTimeout(s); s = null; } if (c) { clearTimeout(c); c = null; } }; const detach = () => { clearEscalation(); for (const [e, t] of o) process.off(e, t); o.clear(); }; const forceKillChild = () => { try { a.kill(process.platform === "win32" ? "SIGTERM" : "SIGKILL"); } catch {} }; const requestChildTermination = () => { try { a.kill("SIGTERM"); } catch {} c = setTimeout(() => { u = true; forceKillChild(); }, respawnSignalForceKillGraceMs); c.unref?.(); }; const scheduleParentExit = (e) => { l ??= e; if (s) return; s = setTimeout(() => { requestChildTermination(); }, r); s.unref?.(); }; for (const e of respawnSignals) { const listener = () => { if (d) return; try { a.kill(e); } catch {} scheduleParentExit(e); }; try { process.on(e, listener); o.set(e, listener); } catch {} } return new Promise((e) => { let t = false; a.once("error", (e) => { t = true; process.stderr.write(`[openclaw] Failed to respawn launcher: ${e instanceof Error ? formatRespawnErrorDetail(e) : String(e)}\n`); }); a.once("exit", () => { d = true; clearEscalation(); }); a.once("close", (n, r) => { detach(); const i = r && os.constants.signals[r]; const a = !u && r === l ? r === "SIGINT" ? 130 : r === "SIGTERM" ? 143 : void 0 : void 0; process.exitCode = t ? 1 : r ? process.platform === "win32" ? a ?? 1 : i ? 128 + i : 1 : n ?? 1; if (!t && r && process.platform !== "win32") process.kill(process.pid, r); e(true); }); }); }; function readSmallFile(e, t = "utf8") { const n = resolveRecoveryPath(e); if (!n) return null; try { const e = statSync(n); return e.isFile() && e.size <= 65536 ? readFileSync(n, t) : null; } catch { return null; } } const WINDOWS_SERVICE_CODEPAGE_LABELS = { 437: "cp437", 720: "cp720", 737: "cp737", 775: "cp775", 850: "cp850", 852: "cp852", 855: "cp855", 857: "cp857", 858: "cp858", 860: "cp860", 861: "cp861", 862: "cp862", 863: "cp863", 865: "cp865", 866: "ibm866", 869: "cp869", 874: "windows-874", 932: "shift_jis", 936: "gbk", 949: "euc-kr", 950: "big5", 1200: "utf-16le", 1201: "utf-16be", 1250: "windows-1250", 1251: "windows-1251", 1252: "windows-1252", 1253: "windows-1253", 1254: "windows-1254", 1255: "windows-1255", 1256: "windows-1256", 1257: "windows-1257", 1258: "windows-1258", 28591: "iso-8859-1", 28592: "iso-8859-2", 28593: "iso-8859-3", 28594: "iso-8859-4", 28595: "iso-8859-5", 28596: "iso-8859-6", 28597: "iso-8859-7", 28598: "iso-8859-8", 28599: "iso-8859-9", 28600: "iso-8859-10", 28603: "iso-8859-13", 28604: "iso-8859-14", 28605: "iso-8859-15", 28606: "iso-8859-16", 38598: "iso-8859-8-i", 54936: "gb18030", 65001: "utf-8" }; function readWindowsServiceScript(e) { let t = readSmallFile(e, null); if (!t) return null; let n = 65001; if (t[0] === 255 && t[1] === 254) n = 1200; else if (t[0] === 254 && t[1] === 255) n = 1201; else { if (t[0] === 239 && t[1] === 187 && t[2] === 191) t = t.subarray(3); let e = t.indexOf(10); const r = /^@chcp (\d+) >nul\s*$/.exec(t.subarray(0, e < 0 ? t.length : e).toString("latin1")); if (r) { n = Number(r[1]); t = t.subarray(e < 0 ? t.length : e + 1); e = t.indexOf(10); } const i = /^@rem openclaw-launcher-encoding=(\S+)\s*$/.exec(t.subarray(0, e < 0 ? t.length : e).toString("latin1")); if (i) { if (!r) { const e = i[1].toLowerCase(); const t = /^cp(\d+)$/.exec(e); n = t ? Number(t[1]) : Number(Object.entries(WINDOWS_SERVICE_CODEPAGE_LABELS).find(([, t]) => t === e)?.[0]); } t = t.subarray(e < 0 ? t.length : e + 1); } } const r = WINDOWS_SERVICE_CODEPAGE_LABELS[n]; try { if (r && n !== 850 && n !== 949) return new TextDecoder(r, { fatal: true }).decode(t); } catch {} process.stderr.write(`openclaw: service script uses code page ${Number.isFinite(n) ? n : "unknown"}; not decodable here\n`); return null; } function realNodePath(e) { try { return realpathSync(e); } catch { return null; } } function isPathWithin(e, t) { const n = path.relative(t, e); return n !== ".." && !n.startsWith(`..${path.sep}`) && !path.isAbsolute(n); } function resolveRecoveryPath(e, t, { allowMissing: n = false, allowCwd: r = false, trustedRoot: i } = {}) { const a = e?.trim().replace(/^~(?=$|[\\/])/, () => t ?? "~"); if (!a || !path.isAbsolute(a)) return null; const o = /^(?:[a-zA-Z]:[\\/]|\\\\)/.test(a) ? path.win32 : path; const s = o.resolve(a); const c = realNodePath(process.cwd()) ?? process.cwd(); const l = !r && c !== "/"; const u = i && path.isAbsolute(i) && isPathWithin(s, i); const excluded = (e) => l && isPathWithin(e, c) && !(u && isPathWithin(e, i)); if (excluded(s)) return null; if (l) for (let e = o.dirname(s);;) { if (u && !isPathWithin(e, i)) break; const t = realNodePath(e); if (t && excluded(t)) return null; const n = o.dirname(e); if (n === e) break; e = n; } let d = s; const f = []; for (;;) { const e = realNodePath(d); if (e) { const t = o.resolve(e, ...f); return path.isAbsolute(t) && !excluded(t) ? t : null; } if (!n) return null; try { lstatSync(d); return null; } catch (e) { if (e?.code !== "ENOENT") return null; } const t = o.dirname(d); if (t === d) return null; f.unshift(o.basename(d)); d = t; } } function isUsableNode(e, { allowCwd: t = false, trustedRoot: n, env: r = process.env, acceptVersion: i } = {}) { const a = resolveRecoveryPath(e, void 0, { allowCwd: t, trustedRoot: n }); if (!a || !/^node(?:\.exe)?$/i.test(path.basename(a))) return false; const o = { NODE_NO_WARNINGS: "1" }; for (const [e, t] of Object.entries(r)) if (/^(SystemRoot|WINDIR|TEMP|TMP|TMPDIR)$/i.test(e)) o[e] = t; let s; try { s = createRuntimeProcessScriptFile("daemonRuntimeProbe"); const e = spawnSync(a, [fileURLToPath(s.url), "node"], { encoding: "utf8", env: o, timeout: 5e3, killSignal: "SIGKILL", maxBuffer: 65536, windowsHide: true, stdio: [ "ignore", "pipe", "pipe" ] }); const t = JSON.parse(e.stdout); return e.status === 0 && !t.bunVersion && !nodeRuntimeFailure(t.nodeVersion, t.sqliteProbe) && (!i || i(t.nodeVersion)); } catch { return false; } finally { s?.dispose(); } } function windowsServiceNode(e) { for (const t of e.split(/\r?\n/)) { const e = t.trimStart().replace(/^@/, ""); let n = ""; let r = false; for (let t = 0; t < e.length; t += 1) { const i = e[t]; if (i === "\\" && e[t + 1] === "\"") { n += "\""; t += 1; } else if (i === "\"") r = !r; else if (/\s/.test(i) && !r) break; else n += i; } n = n.replace(/\^!/g, "!").replace(/%%/g, "%"); if (!r && path.win32.isAbsolute(n) && /^node\.exe$/i.test(path.win32.basename(n))) return n; } return null; } function managedServiceNode(e, t) { let n = t.OPENCLAW_PROFILE?.trim(); const r = process.argv.slice(2); for (let e = 0; e < r.length;) { const t = consumeRootOptionToken(r, e); if (!t) break; if (r[e] === "--dev") n = "dev"; else if (r[e] === "--profile") n = r[e + 1]; else if (r[e].startsWith("--profile=")) n = r[e].slice(10); e += t; } const i = n && n.toLowerCase() !== "default" ? n : ""; let a; if (process.platform === "darwin") { if (!e) return null; const n = t.OPENCLAW_LAUNCHD_LABEL?.trim() || `ai.openclaw.${i || "gateway"}`; if (!/^[A-Za-z0-9._-]+$/.test(n)) return null; const r = [...(readSmallFile(path.join(e, "Library", "LaunchAgents", `${n}.plist`))?.match(/<key>ProgramArguments<\/key>\s*<array>([\s\S]*?)<\/array>/)?.[1] || "").matchAll(/<string>([^<]*)<\/string>/g)].map(([, e]) => e.replace(/&(amp|lt|gt|quot|apos);/g, (e, t) => ({ amp: "&", lt: "<", gt: ">", quot: "\"", apos: "'" })[t])); const o = r[0] === "/bin/sh" ? 1 : 0; a = r[r[o]?.endsWith(`${n}-env-wrapper.sh`) && r[o + 1]?.endsWith(`${n}.env`) ? o + 2 : 0]; } else if (process.platform === "linux") { if (!e) return null; const n = t.OPENCLAW_SYSTEMD_UNIT?.trim() || `openclaw-gateway${i ? `-${i}` : ""}`; if (!/^[A-Za-z0-9._@-]+$/.test(n)) return null; const r = n.endsWith(".service") ? n : `${n}.service`; const o = (readSmallFile(path.join(e, ".config", "systemd", "user", r))?.split(/^\s*\[Service\]\s*$/m)[1]?.split(/^\s*\[/m)[0])?.match(/^\s*ExecStart=\s*(?:"((?:[^"\\]|\\.)*)"|(\S+))/m); a = (o?.[1] ?? o?.[2])?.replace(/\\(.)/g, "$1"); } else if (process.platform === "win32") { const n = t.OPENCLAW_TASK_SCRIPT_NAME?.trim() || "gateway.cmd"; if (/[/\\]|\.\./.test(n)) return null; const r = resolveRecoveryPath(t.OPENCLAW_STATE_DIR?.trim() || e && path.join(e, `.openclaw${i ? `-${i}` : ""}`), e); const o = readWindowsServiceScript(resolveRecoveryPath(t.OPENCLAW_TASK_SCRIPT?.trim() || r && path.join(r, n), e)); a = o && windowsServiceNode(o); } return a && path.isAbsolute(a) && /^node(?:\.exe)?$/i.test(path.basename(a)) ? a : null; } function directoryNames(e) { const t = resolveRecoveryPath(e); if (!t) return []; try { return readdirSync(t).toSorted().slice(0, 256); } catch { return []; } } function resolveNvmDefault(e) { let t = readSmallFile(path.join(e, "alias", "default"))?.trim(); for (let n = 0; t && n < 8; n += 1) { if (/^v?\d+(?:\.\d+){0,2}$/.test(t) || ["node", "stable"].includes(t)) { const n = t.replace(/^v/, ""); const r = directoryNames(path.join(e, "versions", "node")).filter((e) => /^v\d+\.\d+\.\d+$/.test(e)).filter((e) => ["node", "stable"].includes(t) || e === `v${n}` || e.startsWith(`v${n}.`)).toSorted((e, t) => t.localeCompare(e, "en", { numeric: true }))[0]; return r ? path.join(e, "versions", "node", r, "bin", "node") : null; } if (t === "lts/*") t = directoryNames(path.join(e, "alias", "lts")).map((t) => readSmallFile(path.join(e, "alias", "lts", t))?.trim()).filter((e) => e && /^v?\d+\.\d+\.\d+$/.test(e)).toSorted((e, t) => t.localeCompare(e, "en", { numeric: true }))[0]; else if (/^(?:lts\/)?[A-Za-z0-9_-]+$/.test(t)) t = readSmallFile(path.join(e, "alias", t))?.trim(); else return null; } return null; } function* availableNodeCandidates(e, t) { yield [managedServiceNode(e, t), "managed Gateway service"]; const n = process.platform === "win32" ? Object.keys(t).find((e) => e.toUpperCase() === "PATH") || "PATH" : "PATH"; const r = process.platform === "win32" ? "node.exe" : "node"; for (const e of nodeRuntimePathEntries(t[n])) if (path.isAbsolute(e)) yield [path.join(e, r), "PATH"]; for (const n of /* @__PURE__ */ new Set([t.NVM_DIR, e && path.join(e, ".nvm")])) { const t = resolveRecoveryPath(n, e); if (t) yield [resolveNvmDefault(t), "nvm default"]; } for (const n of /* @__PURE__ */ new Set([ t.FNM_DIR, e && path.join(e, ".fnm"), e && path.join(e, ".local", "share", "fnm"), ...process.platform === "darwin" && e ? [path.join(e, "Library", "Application Support", "fnm")] : [] ])) { const t = resolveRecoveryPath(n, e); if (t) yield [path.join(t, "aliases", "default", ...process.platform === "win32" ? [] : ["bin"], r), "fnm default"]; } for (const n of /* @__PURE__ */ new Set([t.VOLTA_HOME, e && path.join(e, ".volta")])) { const t = resolveRecoveryPath(n, e); if (!t) continue; try { const e = JSON.parse(readSmallFile(path.join(t, "tools", "user", "platform.json")))?.node?.runtime; if (typeof e === "string" && /^\d+\.\d+\.\d+$/.test(e)) yield [path.join(t, "tools", "image", "node", e, ...process.platform === "win32" ? [] : ["bin"], r), "Volta default"]; } catch {} } for (const e of [26, 24]) for (const t of ["/opt/homebrew", "/usr/local"]) if (process.platform === "darwin" || process.platform === "linux") yield [path.join(t, "opt", `node@${e}`, "bin", "node"), `Homebrew node@${e}`]; } /** Select a verified runtime without respawning; callers own target admission and activation. */ async function findUsableNodeRuntime({ homeDir: e, allowInstall: t = false, env: n = process.env, acceptVersion: r, nodeVersion: i, installCommand: a } = {}) { const o = n.HOME?.trim() || n.USERPROFILE?.trim(); let s; if (!o || /^~(?=$|[\\/])/.test(o)) try { s = os.userInfo().homedir; } catch {} const c = resolveRecoveryPath(o || s, s, { allowMissing: true, allowCwd: true }); const l = resolveRecoveryPath(e ?? (n.OPENCLAW_HOME?.trim() || c), c, { allowMissing: true, allowCwd: true }); const u = l && path.join(l, ".openclaw"); const d = u && resolveRecoveryPath(u, void 0, { allowMissing: true, trustedRoot: u }); const { resolveUpdatedNodeRuntime: f } = await import("./node-runtime-update-DTNrNE5w.mjs"); let p = d ? await f(d, { allowInstall: false, env: n, acceptVersion: r, installCommand: a }) : null; let m = "cached OpenClaw runtime"; const h = realNodePath(process.execPath); if (!p) { const e = /* @__PURE__ */ new Set([h]); for (const [t, i] of availableNodeCandidates(c, n)) { const a = i === "PATH" ? realNodePath(t) : null; const o = Boolean(a && realNodePath(path.dirname(t)) === path.dirname(a)); const s = resolveRecoveryPath(t, void 0, { allowCwd: o }); if (!s || e.has(s)) continue; e.add(s); if (isUsableNode(s, { allowCwd: o, env: n, acceptVersion: r })) { p = s; m = i; break; } } } if (!p && t && d) { p = await f(d, { env: n, acceptVersion: r, nodeVersion: i, installCommand: a }); m = "private OpenClaw runtime"; } return p ? { nodePath: p, reason: m } : null; } /** * Recover only at CLI startup, before reading config or state. A true result * means the replacement completed and exitCode is recorded: do not resume startup. */ async function recoverNodeRuntime({ homeDir: e, allowInstall: t = false, env: n = process.env } = {}) { if (process.versions.bun || n.OPENCLAW_NODE_UPDATE_RESPAWNED === "1" || !process.argv[1] || isForegroundGmailRunInvocation(process.argv) || process.platform !== "win32" && isNativeHookRelayInvocation(process.argv) || !nodeRuntimeFailure(process.versions.node, await detectCurrentSqliteCapabilities())) return false; const r = await findUsableNodeRuntime({ homeDir: e, allowInstall: t, env: n }); const i = r?.nodePath; const a = r?.reason; if (!i) return false; process.stderr.write(`openclaw: Retrying with ${JSON.stringify(i)} (${a}; current Node failed runtime admission).\n`); return await runRespawnedChild(resolveOpenClawCliRespawn({ execPath: i, env: { ...withNodeRuntimePath(n, i), OPENCLAW_NODE_UPDATE_RESPAWNED: "1" } })); } //#endregion export { recoverNodeRuntime as a, isUsableNode as i, isForegroundGmailRunInvocation as n, resolveRecoveryPath as o, isNativeHookRelayInvocation as r, runRespawnedChild as s, findUsableNodeRuntime as t };