UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

433 lines (432 loc) • 15.2 kB
import { i as withNodeRuntimePath } from "./node-runtime-env-ncloLK-i.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { t as killProcessTree } from "./kill-tree-DlMFq2XA.mjs"; import { a as markOpenClawExecEnv } from "./openclaw-exec-env-BPYcT7Dr.mjs"; import { t as sleep } from "./sleep-CkI3nkiJ.mjs"; import { n as mergeProcessEnv } from "./process-env-DVJdcOcM.mjs"; import { n as getProcessInstanceStartTime, t as getFileLockProcessStartTime } from "./pid-alive-D899x-ak.mjs"; import { t as BrokerChild } from "./child-CJvs_oct.mjs"; import { n as isChildProcessTreeAlive, s as scheduleAdoptedChildZombieReapAfterExit } from "./child-process-tree-BHY5y2g3.mjs"; import { t as getSpawnBroker } from "./context-Btn9lVDh.mjs"; import { r as recordChildProcessSpawn } from "./spawn-diagnostics-DBVI9KzR.mjs"; import { i as hasCommandProcessCleanupError, t as CommandProcessCleanupError } from "./exec-result-DJMhztYN.mjs"; import { n as assertAppContainerSpawnSupported } from "./windows-appcontainer-spawn-DAwxp_r9.mjs"; import { r as resolveSafeChildProcessInvocation } from "./windows-command-BgNYMnai.mjs"; import process from "node:process"; import path from "node:path"; import { AsyncLocalStorage } from "node:async_hooks"; import { stripVTControlCharacters } from "node:util"; import { once } from "node:events"; import { execa } from "execa"; //#region src/process/spawn-broker/execa-protocol.ts const decoder = new TextDecoder(); const commonEscapes = /* @__PURE__ */ new Map([ [" ", " "], ["\n", "\n"], ["\b", "\\b"], ["\f", "\\f"], ["\r", "\\r"], [" ", "\\t"] ]); function renderOutput(e) { let t = typeof e === "string" ? e : decoder.decode(e); if (t.endsWith("\n")) t = t.slice(0, t.endsWith("\r\n") ? -2 : -1); return stripVTControlCharacters(t).replace(/[\p{Separator}\p{Other}]/gu, (e) => { const t = commonEscapes.get(e); if (t !== void 0) return t; const n = e.codePointAt(0); const r = n.toString(16); return n <= 65535 ? `\\u${r.padStart(4, "0")}` : `\\U${r}`; }); } function decodeExecaMessage(e, t) { return e.messageOutputs ? [e.message, ...e.messageOutputs.map((e) => renderOutput(t[e]))].join("\n\n") : e.message; } function restoreError(e, t) { const n = new Error(decodeExecaMessage(e, t), { cause: e.cause ? restoreError(e.cause, t) : void 0 }); return Object.assign(n, { name: e.name, code: e.code }); } /** Failed reject:false results are still Errors, as they are with local execa. */ function restoreExecaResult(e) { const { error: t, ...n } = e; const r = { ...n, stdout: n.stdout, stderr: n.stderr, shortMessage: n.shortMessage, code: n.code }; if (t) { const e = restoreError(t, r); return Object.assign(e, r, { cause: e.cause }); } return { ...r, cause: void 0 }; } //#endregion //#region src/process/exec-spawn.ts function isOutputOption(e) { return e === void 0 || e === "pipe" || e === "ignore" || e === "inherit" || typeof e === "object" && e !== null && "file" in e && typeof e.file === "string" && Object.keys(e).length === 1; } /** Unsupported native descriptors and independent-lifetime commands remain explicit local paths. */ function brokerExecaOptions(e) { if (e.ipc || e.cleanup === false || typeof e.stdin === "number") return; if (e.stdout === "inherit" || e.stderr === "inherit" || e.stdio === "inherit" || typeof e.stdout === "number" || typeof e.stderr === "number") return; if (e.stdio && typeof e.stdio !== "string" && e.stdio.some((e, t) => typeof e === "number" || t > 0 && e === "inherit")) return; if (e.cwd !== void 0 && typeof e.cwd !== "string" || e.input !== void 0 && typeof e.input !== "string" && !(e.input instanceof Uint8Array) || e.stdin !== void 0 && e.stdin !== "pipe" && e.stdin !== "ignore" && e.stdin !== "inherit" || !isOutputOption(e.stdout) || !isOutputOption(e.stderr) || e.shell !== void 0 && e.shell !== false) throw new TypeError("Unsupported spawn broker execa stream or invocation options"); if (Array.isArray(e.stdio) && (e.stdio.length !== 3 || ![ "pipe", "ignore", "inherit" ].includes(String(e.stdio[0])) || !isOutputOption(e.stdio[1]) || !isOutputOption(e.stdio[2]))) throw new TypeError("Unsupported spawn broker execa stdio"); const { cancelSignal: t, ...n } = e; return n; } function spawnBrokerCommand(e, t, n, r) { const i = e.spawnExeca(t, r); const a = i.child; const o = a.waitForClose(); const onAbort = () => { a.killed = true; i.cancel(); }; n.cancelSignal?.addEventListener("abort", onAbort, { once: true }); if (n.cancelSignal?.aborted) onAbort(); const s = i.result.then(async (e) => { if (e.timedOut) a.killed = true; await o; const t = restoreExecaResult(e); if (t instanceof Error && (n.reject !== false || t.code === "ERR_SPAWN_BROKER_UNAVAILABLE")) throw t; return t; }).finally(() => n.cancelSignal?.removeEventListener("abort", onAbort)); s.catch(() => {}); once(a, "spawn").then(() => { setImmediate(() => { for (const e of [a.stdout, a.stderr]) if (e?.readableFlowing === null) e.resume(); }); }, () => {}); const c = { nodeChildProcess: a, get pid() { return a.pid; }, get stdin() { return a.stdin; }, get stdout() { return a.stdout; }, get stderr() { return a.stderr; }, kill: (e) => a.kill(e ?? n.killSignal) }; const l = Object.assign(s, c); return Object.defineProperties(l, Object.getOwnPropertyDescriptors(c)); } const COMMAND_PROCESS_TREE_KILL_GRACE_MS = 300; /** * Post-SIGKILL teardown and orphan reaping, not cooperative grace. macOS reports * EPERM, not ESRCH, while only unreaped zombies remain, and loaded hosts have * exceeded 300 ms. Polling ends at extinction, so only surviving groups wait. */ const COMMAND_PROCESS_GROUP_EXIT_CONFIRMATION_MS = 1e4; /** The single owner for confirming that a force-killed command group is gone. */ async function waitForCommandProcessGroupExit(e, t) { const n = performance.now() + COMMAND_PROCESS_GROUP_EXIT_CONFIRMATION_MS; while (isChildProcessTreeAlive({ pid: e })) { if (!t()) return "replaced"; const r = n - performance.now(); if (r <= 0) return isChildProcessTreeAlive({ pid: e }) ? "alive" : "exited"; await sleep(Math.min(25, r)); } return "exited"; } const commandAdmissions = /* @__PURE__ */ new WeakMap(); /** Remote PID and pipes arrive together before admission or stream subscription. */ async function waitForCommandSpawn(e) { if (e.nodeChildProcess instanceof BrokerChild) try { await e.nodeChildProcess.ready(); } catch { await e; } await commandAdmissions.get(e.nodeChildProcess); } const commandProcessScope = new AsyncLocalStorage(); function resolveCommandProcessSignal(e) { const t = commandProcessScope.getStore()?.signal; return t && e ? AbortSignal.any([t, e]) : t ?? e; } /** Cleanup helpers must outlive cancellation of the commands they are settling. */ function runOutsideCommandProcessScope(e) { return commandProcessScope.exit(e); } /** Join the command owner's cleanup separately from its bounded caller result. */ function retainCommandProcessCleanup(e) { const t = commandProcessScope.getStore(); if (!t) return; const n = e.then((e) => { if (e === "uncertain") t.failure ??= { error: new CommandProcessCleanupError() }; }, (e) => { t.failure ??= { error: e }; }); t.cleanups.add(n); n.then(() => t.cleanups.delete(n)); } /** Terminal command deadlines stop and join children before the caller permits rollback. */ async function withCommandProcessScope(e, t, n) { const r = commandProcessScope.getStore(); const i = new AbortController(); const a = resolveCommandProcessSignal(t); const o = { signal: a ? AbortSignal.any([a, i.signal]) : i.signal, children: /* @__PURE__ */ new Set(), cleanups: /* @__PURE__ */ new Set(), custody: n ?? r?.custody }; const stop = () => { i.abort(); for (const e of o.children) try { e.stop(); } catch (e) { o.failure ??= { error: e }; } }; let s; const settle = () => s ??= settleCommands(); async function settleCommands() { stop(); await Promise.all([...o.children].map(async (e) => { try { await e.settle(); } catch (e) { o.failure ??= { error: e }; } })); while (o.cleanups.size > 0) await Promise.all(o.cleanups); } const c = { stop, async settle() { await settle(); if (o.failure) throw new CommandProcessCleanupError({ cause: o.failure.error }); } }; r?.children.add(c); const l = commandProcessScope.run(o, async () => { let t; try { t = { result: await e(stop) }; } catch (e) { t = { error: e }; if (r && hasCommandProcessCleanupError(e)) r.failure ??= { error: e }; } await settle(); if (o.failure) { const e = "error" in t ? t.error === o.failure.error ? t.error : new AggregateError([t.error, o.failure.error], "Command and cleanup failed", { cause: t.error }) : o.failure.error; throw new CommandProcessCleanupError({ cause: e }); } if ("error" in t) throw t.error; return t.result; }); l.then(() => r?.children.delete(c), (e) => { if (r && hasCommandProcessCleanupError(e)) r.failure ??= { error: e }; r?.children.delete(c); }); return await l; } function retainCommandProcess(e, t, n) { let r; let i = null; let a = false; let o = false; let s = false; let c = false; const settleCustody = () => { if (!n || s || c) return; try { n.settled(); c = true; } catch (e) { s = true; throw e; } }; const l = t.nodeChildProcess; let u = l.exitCode != null || l.signalCode != null; const onExit = () => { u = true; }; l.once("exit", onExit); const d = l instanceof BrokerChild ? l.waitForClose() : void 0; const stop = () => { if (a || r === void 0 || process.platform === "win32") return; a = true; if (l.exitCode !== null || l.signalCode !== null) { if (!isChildProcessTreeAlive({ pid: r })) { o = true; return; } const e = getFileLockProcessStartTime(r); if (e !== null && e !== i) throw new CommandProcessCleanupError(); } killProcessTree(r, { detached: true, force: true }); scheduleAdoptedChildZombieReapAfterExit(l, true); }; const initialize = () => { r = t.pid; if (r !== void 0) try { if (process.platform !== "win32") i = getFileLockProcessStartTime(r); n?.spawned({ pid: r, startedAt: getProcessInstanceStartTime(r) }); if (e.signal.aborted) stop(); } catch (t) { e.failure ??= { error: t }; stop(); throw t; } }; let f; let p; if (l instanceof BrokerChild && t.pid === void 0) p = l.ready().then(initialize); else try { initialize(); p = Promise.resolve(); } catch (e) { f = { error: e }; p = Promise.reject(toErrorObject(e, "Command process custody admission failed")); } commandAdmissions.set(l, p); const m = Promise.resolve(t).then(() => void 0, () => void 0).then(async () => { await d; l.removeListener("exit", onExit); }); const h = p.catch((t) => { if (!(l instanceof BrokerChild && l.notStarted)) e.failure ??= { error: t }; }); const g = { stop, async settle() { await h; await m; if (o) { settleCustody(); return; } if (r === void 0) { if (l instanceof BrokerChild && !l.notStarted) throw new CommandProcessCleanupError(); settleCustody(); return; } if (process.platform === "win32") { if (!u) throw new CommandProcessCleanupError(); settleCustody(); return; } const e = r; if (await waitForCommandProcessGroupExit(e, () => { const t = getFileLockProcessStartTime(e); return t === null || t === i; }) !== "exited") throw new CommandProcessCleanupError(); settleCustody(); } }; e.children.add(g); m.then(() => { if (r === void 0 && (!(l instanceof BrokerChild) || l.notStarted) || r !== void 0 && process.platform !== "win32" && !isChildProcessTreeAlive({ pid: r })) try { settleCustody(); e.children.delete(g); } catch (t) { e.failure ??= { error: t }; } }); if (f) throw f.error; } function shouldSpawnWithShell(e) { return false; } function commandCreatesChildPipes(e) { if ((e.ipc ?? (e.node === true || e.ipcInput !== void 0 || e.gracefulCancel === true)) || e.input !== void 0 || e.inputFile !== void 0) return true; const t = typeof e.stdio === "string" || e.stdio === void 0 ? [ e.stdio, e.stdio, e.stdio ] : e.stdio; return [ e.stdin ?? t[0], e.stdout ?? t[1], e.stderr ?? t[2], ...t.slice(3).filter((e) => e !== void 0) ].some((e) => e !== "ignore" && e !== "inherit" && !(typeof e === "number" && e >= 0)); } function spawnCommandWithInvocation(e, t = {}) { if (process.platform === "win32" && commandCreatesChildPipes(t)) assertAppContainerSpawnSupported(); const n = commandProcessScope.getStore(); if (n?.signal.aborted) throw new Error("Command process scope is closed"); const { baseEnv: r, env: i, windowsVerbatimArguments: a, cancelSignal: o, executionTimeoutMs: s, inheritScopeCancellation: c = true, ...l } = t; const u = resolveCommandEnv({ argv: e, baseEnv: r, env: i }); const d = resolveSafeChildProcessInvocation({ argv: e, cwd: l.cwd, env: u, windowsVerbatimArguments: a }); const f = { ...l, cancelSignal: c ? resolveCommandProcessSignal(o) : o, ...n ? { killDescendants: true } : {}, env: u, extendEnv: false, shell: false, windowsHide: d.windowsHide, windowsVerbatimArguments: d.windowsVerbatimArguments }; const p = getSpawnBroker(); const m = p ? brokerExecaOptions(f) : void 0; if (m && s !== void 0) m.executionDeadlineMs = s + 1e3; const h = n?.custody?.reserve([d.command, ...d.args]); const g = p && m ? spawnBrokerCommand(p, [d.command, ...d.args], f, m) : execa(d.command, d.args, f); const _ = e[0] === "nice" && e[1] === "-n" && e[2] === "10" && e[3] === "git"; recordChildProcessSpawn(_ ? "git" : d.command, g.nodeChildProcess, void 0, _ ? e.slice(4) : d.args); if (n) retainCommandProcess(n, g, h); return { child: g, invocation: d }; } /** Spawn through the canonical argv, environment, and Windows safety boundary. */ function spawnCommand(e, t = {}) { return spawnCommandWithInvocation(e, t).child; } function resolveCommandEnv(e) { const t = e.baseEnv ?? process.env; const n = e.platform ?? process.platform; const r = path.basename(e.argv[0] ?? ""); const i = r === "npm" || r === "npm.cmd" || r === "npm.exe" || (r === "node" || r === "node.exe") && (e.argv[1] ?? "").includes("npm-cli.js"); const a = e.argv[0] ?? ""; const o = n === "win32" ? path.win32 : path.posix; const s = o.isAbsolute(a) && /^(?:node|node\.exe)$/iu.test(o.basename(a)) && /^(?:npm-cli\.js|npx-cli\.js|pnpm\.(?:cjs|js))$/iu.test(o.basename(e.argv[1] ?? "")); const c = mergeProcessEnv([t, e.env], n); const l = s ? withNodeRuntimePath(c, a, n) : c; if (i) { l.NPM_CONFIG_FUND ??= "false"; l.npm_config_fund ??= "false"; } return markOpenClawExecEnv(l); } //#endregion export { retainCommandProcessCleanup as a, spawnCommand as c, waitForCommandSpawn as d, withCommandProcessScope as f, resolveCommandProcessSignal as i, spawnCommandWithInvocation as l, COMMAND_PROCESS_TREE_KILL_GRACE_MS as n, runOutsideCommandProcessScope as o, resolveCommandEnv as r, shouldSpawnWithShell as s, COMMAND_PROCESS_GROUP_EXIT_CONFIRMATION_MS as t, waitForCommandProcessGroupExit as u };