UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,233 lines (1,232 loc) • 36.6 kB
import { a as resolveWindowsSystem32Path, r as resolveWindowsCmdExePath, t as buildCmdExeCommandLine } from "./windows-cmd-helpers-Dg8JAn1e.mjs"; import fs, { fstatSync, writeSync } from "node:fs"; import path from "node:path"; import { randomUUID } from "node:crypto"; import { constants as constants$1, tmpdir } from "node:os"; import { isMainThread } from "node:worker_threads"; import { spawn, spawnSync } from "node:child_process"; import { Socket } from "node:net"; import { Writable } from "node:stream"; //#region scripts/lib/managed-cleanup-handoff.mts const HANDOFF_ENV = "OPENCLAW_MANAGED_CLEANUP_PARENT"; const MAX_FRAME_BYTES = 1024; function readParent() { const e = process.env[HANDOFF_ENV]; if (!isMainThread || process.platform === "win32" || !e) return; const [t, n, r, i] = e.split(":"); const a = Number(t); const o = Number(n); if (i !== void 0 || a !== process.ppid || !Number.isSafeInteger(o) || o < 3 || typeof r !== "string" || !/^[0-9a-f-]{36}$/u.test(r)) return; try { if (fstatSync(o).isSocket()) return { fd: o, pid: a, token: r }; } catch {} } function hasManagedCleanupParent() { return client !== void 0 || readParent() !== void 0; } let client; var ManagedCleanupCancelled = class extends Error { constructor(e) { super("Managed cleanup parent is already cancelling"); this.code = "ABORT_ERR"; this.signal = e; } }; function cleanupClient() { if (client) return client; const e = readParent(); if (!e) return; delete process.env[HANDOFF_ENV]; return client = createCleanupClient(e); } function createCleanupClient(e) { const t = new Socket({ fd: e.fd, readable: true, writable: true }); let n = false; let r = false; let i = 0; let a = false; let o; let s = ""; let c = Promise.resolve(); let l = 0; let u; const fail = (e) => { o ??= e; u?.reject(o); u = void 0; t.destroy(); }; const markFailed = () => { if (!a) { a = true; if (n && !t.destroyed) t.write(`failed ${e.token}\n`); } }; t.unref(); t.setEncoding("utf8"); t.on("error", fail); t.on("end", () => fail(/* @__PURE__ */ new Error("Managed cleanup parent closed its control channel"))); t.on("close", () => { if (u) fail(/* @__PURE__ */ new Error("Managed cleanup parent closed before acknowledging ownership")); }); t.on("data", (t) => { s += t; if (Buffer.byteLength(s) > MAX_FRAME_BYTES) { fail(/* @__PURE__ */ new Error("Managed cleanup parent sent an invalid acknowledgement")); return; } let r; while ((r = s.indexOf("\n")) !== -1) { const t = s.slice(0, r); s = s.slice(r + 1); const i = [ "SIGINT", "SIGTERM", "SIGHUP" ].find((n) => t === `stopping ${n} ${e.token}`); if (i) { fail(new ManagedCleanupCancelled(i)); return; } if (!u || t !== `${u.kind === "claim" ? "owned" : "released"} ${e.token}`) { fail(/* @__PURE__ */ new Error("Managed cleanup parent sent an invalid acknowledgement")); return; } n = u.kind === "claim"; const { resolve: a } = u; u = void 0; a(); } }); if (process.versions.bun) { c = new Promise((e, n) => { t.once("connect", e); t.once("error", n); t.once("close", () => n(/* @__PURE__ */ new Error("Managed cleanup channel closed before opening"))); }); c.catch(fail); t.connect({ fd: e.fd }); } process.once("exit", () => { if ((n || u?.kind === "claim") && i === 0 && !a && !o) try { writeSync(e.fd, `finished ${e.token}\n`); } catch {} }); const request = (n) => { if (o) return Promise.reject(o); if (a) return Promise.reject(Object.assign(/* @__PURE__ */ new Error("Managed cleanup ownership contains unjoined work"), { code: "EPROCESSGROUP_CLEANUP_FAILED", processTreeState: "indeterminate" })); return new Promise((r, i) => { u = { kind: n, resolve: r, reject: i }; t.write(`${n} ${e.token}\n`); }); }; const serialize = (e) => { const t = c.then(e); c = t.catch(() => {}); return t; }; const ensureOwned = () => n && !o && !a ? Promise.resolve() : request("claim"); const waitForAcknowledgement = async (e, n) => { l++; t.ref(); let abort; try { await new Promise((t, r) => { e.then(t, r); if (n) { abort = () => r(Object.assign(/* @__PURE__ */ new Error("Managed command aborted"), { code: "ABORT_ERR" })); n.addEventListener("abort", abort, { once: true }); if (n.aborted) abort(); } }); } finally { if (abort) n?.removeEventListener("abort", abort); if (--l === 0) t.unref(); } }; return { markFailed, async claim() { r = true; await waitForAcknowledgement(serialize(ensureOwned)); return true; }, async acquire(e) { e?.throwIfAborted(); i++; let t = false; const release = (e, o = false) => { if (t) return Promise.resolve(); t = true; i--; if (!e) { markFailed(); return Promise.resolve(); } const s = serialize(() => i === 0 && !r && n && !a ? request("release") : Promise.resolve()); s.catch(fail); return o ? waitForAcknowledgement(s) : s; }; try { await waitForAcknowledgement(serialize(() => i > 0 || r ? ensureOwned() : Promise.resolve()), e); } catch (e) { release(true); throw e; } return release; } }; } /** Call only after installing the implementation's lifetime cancellation owner. */ function claimManagedCleanup() { return cleanupClient()?.claim() ?? Promise.resolve(false); } function acquireManagedCleanup(e) { return cleanupClient()?.acquire(e); } function failManagedCleanup() { client?.markFailed(); } /** Each descriptor belongs to exactly the ChildProcess passed to attach. */ function prepareManagedCleanupHandoff(e, t, n) { delete t[HANDOFF_ENV]; if (n === "win32") return { stdio: e, attach: (e) => void 0 }; const r = Array.isArray(e) ? [...e] : [ e, e, e ]; const i = Math.max(3, r.length); const a = randomUUID(); while (r.length < i) r.push(r.length < 3 ? "pipe" : "ignore"); r.push("pipe"); t[HANDOFF_ENV] = `${process.pid}:${i}:${a}`; return { stdio: r, attach(e) { if (!e.pid) return; const t = e.stdio[i]; if (!(t instanceof Socket)) return; let n = false; let r = false; let o = false; let s = false; let c; let l; let u = ""; const d = /* @__PURE__ */ new Set(); const f = /* @__PURE__ */ new Set(); const fail = (e) => { l ??= e; for (const e of d) e(l); }; t.unref(); t.setEncoding("utf8"); t.on("error", (e) => { if (n && !o || u.length > 0) fail(e); }); const finishChannel = () => { if (s) return; s = true; if (u.length > 0 || n && !o) fail(/* @__PURE__ */ new Error("Managed cleanup owner lost its control channel before relinquishing ownership")); }; t.on("end", finishChannel); t.on("close", finishChannel); e.once("exit", () => { if (!r) t.destroy(); }); t.on("data", (e) => { u += e; if (Buffer.byteLength(u) > MAX_FRAME_BYTES) { fail(/* @__PURE__ */ new Error("Managed cleanup owner sent an oversized handoff")); return; } let i; while ((i = u.indexOf("\n")) !== -1) { const e = u.slice(0, i); u = u.slice(i + 1); if (e === `claim ${a}` && !n && !o && !l) { if (c) t.end(`stopping ${c} ${a}\n`); else { n = true; r = true; t.write(`owned ${a}\n`); } } else if (e === `finished ${a}` && !o && (n || r || c)) o = true; else if (e === `release ${a}` && n && !o && !l) { n = false; t.write(`released ${a}\n`); for (const e of f) e(); } else if (e === `failed ${a}` && n && !o) fail(/* @__PURE__ */ new Error("Managed cleanup owner reported unjoined work")); else fail(/* @__PURE__ */ new Error("Managed cleanup owner sent an invalid handoff")); } }); return { stop(e) { c ??= e; }, delegated: () => n, failure: () => l, settled: () => !r || s, waitForOwnerSettlement: (t) => new Promise((r, i) => { if (l) { i(l); return; } if (!n || e.exitCode !== null || e.signalCode !== null) { r(true); return; } const cleanup = () => { clearTimeout(a); e.off("exit", onExit); e.off("error", onError); d.delete(onError); f.delete(onExit); }; const onExit = () => { cleanup(); r(true); }; const onError = (e) => { cleanup(); i(e); }; const a = setTimeout(() => { cleanup(); r(false); }, Math.max(0, t - Date.now())); e.once("exit", onExit); e.once("error", onError); d.add(onError); f.add(onExit); }), close: () => t.destroy() }; } }; } //#endregion //#region scripts/lib/vitest-resource-ownership.mts const OWNER_DIRECTORY = ".vitest-resource-owner"; const ID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/; function readReceipt(e) { const t = fs.openSync(e, "r"); try { const e = Buffer.alloc(128); return e.subarray(0, fs.readSync(t, e)).toString("utf8"); } finally { fs.closeSync(t); } } function resourceOwner(e, t) { const n = path.join(e, OWNER_DIRECTORY); const r = path.join(n, "owner"); const i = path.join(n, "claims"); const verifyOwner = () => { if (readReceipt(r) !== t) throw new Error(`Vitest resource owner changed: ${e}`); }; return { root: e, claim() { verifyOwner(); const e = randomUUID(); const n = path.join(i, e); fs.mkdirSync(n); return () => { verifyOwner(); fs.writeFileSync(path.join(n, "released"), `${t}:${e}`, { flag: "wx" }); }; }, assertReleased() { verifyOwner(); for (const e of fs.readdirSync(i)) { const n = path.join(i, e, "released"); try { if (ID_PATTERN.test(e) && readReceipt(n) === `${t}:${e}`) continue; } catch {} throw new Error(`Unreleased Vitest resource claim: ${path.join(i, e)}`); } } }; } /** Discover only explicit containing owners, including canonical TMP symlinks. */ function findVitestResourceOwner(e = tmpdir()) { let t = path.resolve(e); while (true) { try { t = fs.realpathSync(t); fs.lstatSync(path.join(t, OWNER_DIRECTORY)); } catch (e) { if (e.code !== "ENOENT") throw e; const n = path.dirname(t); if (n === t) return; t = n; continue; } const e = readReceipt(path.join(t, OWNER_DIRECTORY, "owner")); if (!ID_PATTERN.test(e)) throw new Error(`Invalid Vitest resource owner: ${t}`); return resourceOwner(t, e); } } //#endregion //#region scripts/lib/windows-taskkill.mjs /** * @param {NodeJS.ProcessEnv} [env] * @returns {string} */ function resolveWindowsTaskkillPath(e = process.env) { return resolveWindowsSystem32Path("taskkill.exe", e); } //#endregion //#region scripts/lib/managed-child-process.mts const FORWARDED_SIGNALS = [ "SIGINT", "SIGTERM", "SIGHUP" ]; const FORCE_KILL_DELAY_MS = 5e3; const PROCESS_GROUP_DRAIN_TIMEOUT_MS = 5e3; const PROCESS_GROUP_POLL_MS = 25; const TASKKILL_TIMEOUT_MS = 1e4; const managedChildren = /* @__PURE__ */ new Set(); const signalHandlers = /* @__PURE__ */ new Map(); const windowsJobs = /* @__PURE__ */ new WeakMap(); const windowsTerminations = /* @__PURE__ */ new WeakMap(); const cleanupHandoffs = /* @__PURE__ */ new WeakMap(); /** Resolve platform code before spawning so callers can attach listeners synchronously. */ function loadManagedChildSpawner(e = process.platform) { if (e !== "win32") return spawn; return import("./managed-windows-job-DuwYGPhs.mjs").then(({ spawnWindowsJobChild: e }) => { function spawnManagedChild(t, n, r) { const i = e(t, n, r); if (!i) return spawn(t, n, r); windowsJobs.set(i.child, i.job); return i.child; } return spawnManagedChild; }); } function observeWindowsTree(e) { const t = windowsJobs.get(e); if (!t) return windowsTerminations.get(e) ?? { processTreeState: "indeterminate" }; try { const e = t.inspect(); return { processTreeState: e.length === 0 ? "terminated" : "indeterminate", survivingPids: e }; } catch (e) { return { processTreeState: "indeterminate", error: e instanceof Error ? e : new Error(String(e)) }; } } /** Nested command failures retain their owner's inputs until process cleanup is verified. */ function hasUnjoinedWork(e) { const t = [e]; const n = /* @__PURE__ */ new Set(); for (const e of t) { if (!e || typeof e !== "object" || n.has(e)) continue; n.add(e); if ("processTreeState" in e && e.processTreeState !== "terminated") return true; if ("errors" in e && Array.isArray(e.errors)) for (const n of e.errors) t.push(n); if ("cause" in e) t.push(e.cause); if ("error" in e) t.push(e.error); } return false; } /** Return the conventional shell exit code for a signal. */ function signalExitCode(e) { const t = signalNumberFor(e); return t ? 128 + t : 1; } function terminateManagedChild(e, t = "SIGTERM", { deadlineAt: n, onChildSignalError: r, onProcessGroupSignalError: i, platform: a = process.platform, processGroupFallback: o = "always", runTaskkill: s = spawnSync, taskkillTimeoutMs: c = TASKKILL_TIMEOUT_MS, useProcessGroup: l = a !== "win32", useWindowsTaskkill: u = true } = {}) { if (!e.pid) { try { const n = e.kill(t); if (a !== "win32") return { processTreeState: n === false ? "terminated" : "signaled" }; } catch (e) { r?.(e); } return a === "win32" ? { processTreeState: "indeterminate" } : void 0; } const d = a === "win32" ? windowsJobs.get(e) : void 0; d?.beginStop(); let f = false; try { if (a !== "win32" && l) { process.kill(-e.pid, t); return { processTreeState: "signaled" }; } } catch (t) { if (isExitedDarwinGroup(e, a, t, n)) return { processTreeState: "terminated" }; f = isMissingProcessError(t); if (!f) i?.(t); if (o === "never" || o === "nonmissing" && f) return f ? { processTreeState: "terminated" } : void 0; } if (a !== "win32" || !u) { const n = l && !f ? "indeterminate" : "terminated"; try { return { processTreeState: e.kill(t) === false ? n : "signaled" }; } catch (e) { r?.(e); return isMissingProcessError(e) ? { processTreeState: n } : void 0; } } if (e.exitCode != null || e.signalCode != null) { if (d) try { d.stop(); } catch (e) { r?.(e); } return observeWindowsTree(e); } const p = resolveWindowsTaskkillPath(); const m = [ "/PID", String(e.pid), "/T" ]; if (t === "SIGKILL") m.push("/F"); const h = c === null ? { stdio: [ "ignore", "pipe", "pipe" ] } : { killSignal: "SIGKILL", stdio: [ "ignore", "pipe", "pipe" ], timeout: c }; const g = s(p, m, h); const _ = [g]; if ((g?.error || g?.status !== 0) && t !== "SIGKILL" && !hasManagedChildExited(e)) _.push(s(p, [...m, "/F"], h)); if (d && observeWindowsTree(e).processTreeState !== "terminated") try { d.stop(); } catch (e) { r?.(e); } if (_.some((e) => !e?.error && e?.status === 0)) { windowsTerminations.set(e, { processTreeState: "terminated" }); return d ? observeWindowsTree(e) : { processTreeState: "terminated" }; } try { if (!hasManagedChildExited(e)) e.kill(t); } catch (e) { r?.(e); } const v = _.map((e) => ({ status: e?.status ?? null, signal: e?.signal ?? null, stdout: e?.stdout?.toString() ?? "", stderr: e?.stderr?.toString() ?? "", error: e?.error?.message })); const y = d ? observeWindowsTree(e) : { processTreeState: "indeterminate" }; const b = { ...y, error: Object.assign(createManagedCommandCleanupError(`Windows taskkill failed: ${JSON.stringify(v)}`, e, a, "indeterminate", y.error), { taskkill: v, survivingPids: y.survivingPids }) }; windowsTerminations.set(e, b); return b; } function hasManagedChildExited(e) { if (e.exitCode != null || e.signalCode != null) return true; if (e.pid) try { process.kill(e.pid, 0); } catch (e) { return isMissingProcessError(e); } return false; } function inspectManagedProcessGroup(e, { deadlineAt: t, errorPolicy: n, inspectLeaderWhenNoGroup: r = false, platform: i = process.platform, useProcessGroup: a = i !== "win32" }) { if (i === "win32" && !r) return observeWindowsTree(e).processTreeState === "terminated" ? "dead" : "indeterminate"; if (!a) return r && e.pid && e.exitCode === null && e.signalCode === null ? "live" : "dead"; const { pid: o } = e; if (typeof o !== "number" || !Number.isSafeInteger(o) || o <= 1 || o > 2147483647) return "indeterminate"; try { process.kill(-o, 0); if (i === "linux" && (e.exitCode != null || e.signalCode != null)) { if (isZombieProcessGroup(o, i, t)) return "dead"; process.kill(-o, 0); } return "live"; } catch (r) { if (isMissingProcessError(r)) return "dead"; if (isExitedDarwinGroup(e, i, r, t)) return "dead"; return n === "alive-on-eperm" && hasProcessErrorCode(r, "EPERM") ? "live" : "indeterminate"; } } function isExitedDarwinGroup(e, t, n, r) { if (t !== "darwin" || !hasProcessErrorCode(n, "EPERM") || !e.pid || e.exitCode == null && e.signalCode == null) return false; if (isZombieProcessGroup(e.pid, t, r)) return true; try { process.kill(-e.pid, 0); } catch (e) { return isMissingProcessError(e); } return false; } function isZombieProcessGroup(e, t, n) { const r = n === void 0 ? PROCESS_GROUP_DRAIN_TIMEOUT_MS : Math.min(PROCESS_GROUP_DRAIN_TIMEOUT_MS, Math.floor(n - Date.now())); if (r <= 0) return false; const i = spawnSync("ps", [ ...t === "darwin" ? ["-g", String(e)] : [ "-s", String(e), "-L" ], "-o", "pgid=,state=" ], { encoding: "utf8", stdio: [ "ignore", "pipe", "ignore" ], timeout: r, killSignal: "SIGKILL" }); const a = new RegExp(`^\\s*${e}\\s+${t === "darwin" ? "Z[+<>AELNSsVWX]*" : "Z"}\\s*$`, "u"); return !i.error && i.status === 0 && i.stdout.trim().split("\n").every((e) => a.test(e)); } async function waitForManagedProcessGroupExit(e, t, { clampPollToDeadline: n = false, pollIntervalMs: r = PROCESS_GROUP_POLL_MS, signal: i, ...a }) { const o = Math.min(Date.now() + t, a.deadlineAt ?? Infinity); const s = { ...a, deadlineAt: o }; while (Date.now() < o) { if (i?.aborted) return false; if (inspectManagedProcessGroup(e, s) === "dead") return true; const t = o - Date.now(); if (t <= 0) break; const a = n ? Math.min(r, t) : r; await new Promise((e) => { const finish = () => { clearTimeout(t); i?.removeEventListener("abort", finish); e(); }; const t = setTimeout(finish, a); i?.addEventListener("abort", finish, { once: true }); if (i?.aborted) finish(); }); } return !i?.aborted && inspectManagedProcessGroup(e, s) === "dead"; } /** Run a child command while forwarding termination signals to its process group. */ async function runManagedCommand({ waitForCleanupRelease: e = false, ...t }) { const n = { ...t, args: t.args?.slice(), cwd: path.resolve(t.cwd ?? process.cwd()), env: { ...t.env ?? process.env }, stdio: Array.isArray(t.stdio) ? [...t.stdio] : t.stdio }; if (!hasManagedCleanupParent()) return runOwnedManagedCommand(n); n.signal?.throwIfAborted(); let r; let i = false; let a = false; const o = new AbortController(); const rememberSignal = (e) => { r ??= e; if (!i || a) n.onSignal?.(e); if (!i) o.abort(); }; installSignalHandlers(); managedChildren.add(rememberSignal); let s; let c = true; let l; const u = n.signal ? AbortSignal.any([n.signal, o.signal]) : o.signal; try { s = await acquireManagedCleanup(u); n.signal?.throwIfAborted(); l = { status: r ? signalExitCode(r) : await runOwnedManagedCommand({ ...n, signal: u, onReady(e) { i = true; n.onReady?.(e); } }) }; } catch (e) { c = !hasUnjoinedWork(e); l = { error: e }; } a = true; try { const t = s?.(c, e); if (e) await t; } finally { managedChildren.delete(rememberSignal); removeSignalHandlersIfIdle(); } if ("error" in l) { const { error: e } = l; if (e instanceof ManagedCleanupCancelled) { if (!r) n.onSignal?.(e.signal); return signalExitCode(r ?? e.signal); } if (r && !n.signal?.aborted && hasProcessErrorCode(e, "ABORT_ERR")) return signalExitCode(r); throw e; } return r ? signalExitCode(r) : l.status; } async function runOwnedManagedCommand(e) { const { memoryLimitBytes: t } = e; if (t !== void 0) { if (!Number.isSafeInteger(t) || t <= 0) throw new Error("Managed command memory limit must be a positive integer"); if ((e.platform ?? process.platform) === "linux") { if (Array.isArray(e.stdio) && (e.stdio.length > 3 || e.stdio.includes("ipc"))) throw new Error("Linux memory-limited commands do not support IPC or extra stdio descriptors"); const t = { ...e, args: e.args?.slice(), cwd: path.resolve(e.cwd ?? process.cwd()), env: { ...e.env ?? process.env }, stdio: Array.isArray(e.stdio) ? [...e.stdio] : e.stdio }; const { runLinuxMemoryCommand: n } = await import("./managed-memory-B7yPouGT.mjs"); const r = t.env; const i = findVitestResourceOwner(r.TMPDIR || r.TMP || r.TEMP || tmpdir())?.claim(); let a = true; let o = false; let s; const rememberSignal = (e) => { s ??= e; if (!o) t.onSignal?.(e); }; installSignalHandlers(); managedChildren.add(rememberSignal); try { const e = await n(t, async (e) => { o = true; try { return await runManagedCommandInner(e, false); } finally { o = false; } }); if (s) return signalExitCode(s); if (t.signal?.aborted) throw Object.assign(/* @__PURE__ */ new Error("Managed command aborted"), { code: "ABORT_ERR" }); return e; } catch (e) { a = !hasUnjoinedWork(e); throw e; } finally { try { if (a) i?.(); } finally { managedChildren.delete(rememberSignal); removeSignalHandlersIfIdle(); } } } throw new Error("Semantic checks require verified kernel memory containment. Run this command through Crabbox or a memory-limited Linux VM; native containment is not qualified on this platform."); } return await runManagedCommandInner(e); } async function runManagedCommandInner({ stdio: e = "inherit", platform: t = process.platform, memoryLimitBytes: n, onMemoryScope: r, timeoutMs: i, timeoutKillGraceMs: a, signalKillGraceMs: o, timeoutForceKillOnLeaderExit: s = false, requireProcessTreeExit: c = false, runTaskkill: l = spawnSync, onReady: u, onTimeout: d, signal: f, abortKillGraceMs: p, cleanupDrainTimeoutMs: m, onSignal: h, ...g }, _ = true) { if (t === "win32" && c) throw Object.assign(/* @__PURE__ */ new Error("Strict managed process-tree verification is not supported on Windows"), { code: "EPROCESS_TREE_VERIFICATION_UNSUPPORTED" }); f?.throwIfAborted(); const v = e === "inherit" ? [ "inherit", "inherit", "inherit" ] : Array.isArray(e) ? [...e] : e; const y = [process.stdout, process.stderr].map((e, n) => { if (t !== "win32" && !e.isTTY && Array.isArray(v) && v[n + 1] === "inherit") { v[n + 1] = "pipe"; return e; } }); const b = { ...g.env ?? process.env }; const x = prepareManagedCleanupHandoff(v, b, t); const S = createManagedCommandSpawnSpec({ ...g, args: g.args?.slice(), cwd: g.cwd ?? process.cwd(), env: b, stdio: x.stdio, platform: t }); const C = loadManagedChildSpawner(t); const w = typeof C === "function" ? C : await C; f?.throwIfAborted(); let T = _ ? findVitestResourceOwner(b.TMPDIR || b.TMP || b.TEMP || tmpdir())?.claim() : void 0; const releaseOwnership = () => { T?.(); T = void 0; }; installSignalHandlers(); let E; const D = d ? Date.now() : 0; try { E = w(S.command, S.args, S.options); } catch (e) { removeSignalHandlersIfIdle(); releaseOwnership(); throw e; } let O = false; E.once("close", () => { O = true; clearTimeout(F); }); const k = x.attach(E); if (k) cleanupHandoffs.set(E, k); const A = c || windowsJobs.has(E); const j = new Set([E.stdout, E.stderr].filter((e) => e != null)); const M = [...j].map((e) => { const onClose = () => { j.delete(e); }; e.once("close", onClose); return () => e.off("close", onClose); }); let N = null; const observeExit = (e, t) => { N = { code: e, signal: t, elapsedMs: Date.now() - D }; }; const P = d ? [E.stdout, E.stderr].map((e) => { if (!e) return null; let t = 0; let n = null; const observeData = (e) => { t += Buffer.byteLength(e); n = Date.now() - D; }; e.on("data", observeData); return { snapshot: () => ({ bytes: t, lastDataElapsedMs: n, closed: !j.has(e) }), remove: () => e.off("data", observeData) }; }) : []; if (d) E.once("exit", observeExit); let F; let I; const L = new AbortController(); let R; const z = { signal: L.signal, getRequest: () => R }; let B; let V; const H = new Promise((e) => { V = e; }); const finalize = (e, n, r = false) => { if (e && !R) { R = { signal: e, forceKillDelayMs: n, forceKillOnLeaderExit: r }; L.abort(); } return I ??= finalizeManagedChild(E, e, { platform: t, runTaskkill: l, forceKillDelayMs: n, forceKillOnLeaderExit: r, drainTimeoutMs: m, areOutputPipesClosed: () => j.size === 0, isChildClosed: () => O, onTerminated: releaseOwnership, stopControl: z }).then(() => void 0, (e) => ({ type: "failed", error: e })); }; const stop = (e, ...t) => { B ??= e; clearTimeout(F); const n = finalize(...t); V(B); return n; }; const forwardSignal = (e) => { h?.(e); stop({ type: "signal", signal: e }, e, o); }; const abort = () => { stop({ type: "aborted" }, "SIGTERM", p); }; managedChildren.add(forwardSignal); try { E.once("error", (e) => { clearTimeout(F); if (windowsJobs.has(E)) stop({ type: "failed", error: e }, "SIGKILL"); else V({ type: "failed", error: e }); }); E.once(A ? "exit" : "close", (e, t) => { V({ type: "completed", exit: t ?? e ?? 1 }); }); if (i !== void 0) F = setTimeout(() => { try { d?.({ elapsedMs: Date.now() - D, exit: N, stdout: P[0]?.snapshot() ?? null, stderr: P[1]?.snapshot() ?? null }); } catch {} stop({ type: "timeout" }, "SIGTERM", a, s); }, i); f?.addEventListener("abort", abort, { once: true }); if (f?.aborted) abort(); try { for (const [e, t] of y.entries()) if (t) (e === 0 ? E.stdout : E.stderr).pipe(new Writable({ write(e, n, r) { t.write(e, n, r); } })); u?.(E); } catch (e) { const t = await stop({ type: "failed", error: e }, "SIGTERM"); if (t && t.error !== e) throw createManagedCommandSetupCleanupError(e, t.error); throw e; } let e = await H; if (e.type === "completed" && (A || k?.delegated() || k?.failure())) finalize(typeof e.exit === "string" ? e.exit : void 0); e = (I ? await I : void 0) ?? B ?? e; if (e.type === "completed" && !A && !B && !I) releaseOwnership(); if (e.type === "failed") throw e.error; if (e.type === "timeout") throw Object.assign(/* @__PURE__ */ new Error(`Managed command timed out after ${i}ms`), { code: "ETIMEDOUT" }); if (e.type === "aborted") throw Object.assign(/* @__PURE__ */ new Error("Managed command aborted"), { code: "ABORT_ERR" }); if (e.type === "signal") return signalExitCode(e.signal); return typeof e.exit === "string" ? signalExitCode(e.exit) : e.exit; } finally { k?.close(); cleanupHandoffs.delete(E); for (const e of M) e(); E.off("exit", observeExit); for (const e of P) e?.remove(); clearTimeout(F); f?.removeEventListener("abort", abort); managedChildren.delete(forwardSignal); removeSignalHandlersIfIdle(); if (!E.pid) releaseOwnership(); } } async function finalizeManagedChild(e, t, { platform: n, runTaskkill: r, forceKillDelayMs: i = FORCE_KILL_DELAY_MS, forceKillOnLeaderExit: a = false, drainTimeoutMs: o = PROCESS_GROUP_DRAIN_TIMEOUT_MS, retainOutputOnFailure: s = false, areOutputPipesClosed: c, isChildClosed: l = () => true, onTerminated: u = () => {}, stopControl: d }) { let f = t; let p = a; const m = Date.now(); const h = f ? i : 0; const g = m + Math.floor(o / 2); let _ = m + h; let v = _ + o; let y = !f || n === "win32"; const b = []; const recordSignalError = (e) => { if (!isMissingProcessError(e)) b.push(e); }; const x = { deadlineAt: f ? m : m + o, platform: n, runTaskkill: r, onChildSignalError: recordSignalError, onProcessGroupSignalError: recordSignalError }; const S = windowsJobs.get(e); const C = !f && S !== void 0; const w = c ?? (() => [e.stdout, e.stderr].every((e) => !e || e.closed)); let T = false; const E = []; let D; let O = false; let k = false; const A = cleanupHandoffs.get(e); let j = false; let M; const interruptNaturalDrain = () => { const t = d?.getRequest(); if (!t || f || k) return; f = t.signal; A?.stop(f); p = t.forceKillOnLeaderExit; _ = Math.min(Date.now() + (t.forceKillDelayMs ?? FORCE_KILL_DELAY_MS), g); y = false; O = true; D = terminateManagedChild(e, f, { ...x, deadlineAt: Date.now() }); }; const N = !f && n !== "win32" ? d?.signal : void 0; N?.addEventListener("abort", interruptNaturalDrain, { once: true }); try { if (f) A?.stop(f); if (N?.aborted) interruptNaturalDrain(); if (C && !w()) await new Promise((t) => { const finish = () => { clearTimeout(n); e.off("close", finish); t(); }; const n = setTimeout(finish, Math.max(0, m + o / 2 - Date.now())); e.once("close", finish); }); const t = !f && (n === "win32" ? inspectManagedProcessGroup(e, { deadlineAt: m + o, errorPolicy: "indeterminate", platform: n }) === "dead" : await waitForManagedProcessGroupExit(e, Math.floor(o / 2), { deadlineAt: g, clampPollToDeadline: true, errorPolicy: "indeterminate", platform: n, signal: N })); if (!O) { k = !f && !t; D = t ? { processTreeState: "terminated" } : terminateManagedChild(e, f ?? "SIGKILL", x); } if (n === "win32" && D?.processTreeState !== "terminated" && !S) throw createManagedCommandCleanupError("Windows taskkill could not verify managed process tree exit", e, n, "indeterminate", D?.error); if (n === "win32" && !C) { _ = Date.now() + h; v = _ + o; } let r = "indeterminate"; let i; let a; let c = false; while (true) { if (f && A?.delegated() && !j) { j = true; let t = false; try { t = await A.waitForOwnerSettlement(v); } catch (e) { M = e; } const r = e.exitCode !== null || e.signalCode !== null; if (!t && !r) { if (!s) { for (const t of e.stdio) t?.destroy(); if (e.connected) e.disconnect(); } else { for (const t of e.stdio) if (t instanceof Socket) t.unref(); e.channel?.unref(); } A.close(); e.unref(); throw createManagedCommandCleanupError(M ? "Managed cleanup owner lost control while retaining live custody" : "Managed cleanup owner did not relinquish live custody before the cancellation deadline", e, n, "indeterminate", M); } } const t = e.exitCode !== null || e.signalCode !== null; const o = y ? v : p && t ? Math.min(_, Date.now()) : _; if (n === "win32") { const t = observeWindowsTree(e); i = t.survivingPids; a = t.error; r = t.processTreeState === "terminated" ? "dead" : "indeterminate"; if (!c && r !== "dead") { c = true; process.emitWarning(Object.assign(createManagedCommandCleanupError(`Windows process tree unresolved: ${JSON.stringify({ survivingPids: i ?? null, observationError: t.error?.message })}`, e, n, "indeterminate", D?.error ?? t.error), { survivingPids: i })); } } else r = inspectManagedProcessGroup(e, { deadlineAt: o, errorPolicy: "indeterminate", platform: n }); if (r === "dead" && t && l() && w() && A?.settled() !== false) { T = true; if (!f && n !== "win32" && D?.processTreeState !== "terminated") { const t = [D?.error, ...b].filter((e) => e !== void 0); throw createManagedCommandCleanupError("Managed command exited while its process group remained active", e, n, "terminated", t.length > 0 ? new AggregateError(t, "Managed process termination failed") : void 0); } break; } const u = Date.now(); if (!y && (u >= _ || p && t)) { y = true; if (r !== "dead") terminateManagedChild(e, "SIGKILL", { ...x, deadlineAt: v }); } if (u >= v) break; await new Promise((e) => { setTimeout(e, Math.min(PROCESS_GROUP_POLL_MS, (y ? v : _) - u)); }); } if (!T) { if (!s) { e.stdout?.destroy(); e.stderr?.destroy(); } throw Object.assign(createManagedCommandCleanupError(`Managed command cleanup could not verify child, process group, and output closure${n === "win32" ? `: ${JSON.stringify({ survivingPids: i ?? null })}` : ""}`, e, n, r === "live" ? "live" : "indeterminate", new AggregateError([ D?.error, a, ...b ].filter((e) => e !== void 0), "Managed process termination or observation failed")), { survivingPids: i }); } const u = A?.failure() ?? M; if (u) { T = false; throw createManagedCommandCleanupError("Managed cleanup ownership handoff failed", e, n, "indeterminate", u); } } catch (e) { E.push(e); } finally { N?.removeEventListener("abort", interruptNaturalDrain); } if (S) { const t = T ? void 0 : observeWindowsTree(e); if (!T && !hasUnjoinedWork(E[0])) E[0] = Object.assign(createManagedCommandCleanupError("Windows Job finalization remains unverified", e, n, "indeterminate", E[0]), { survivingPids: t?.survivingPids }); if (t?.error) E.push(t.error); const r = { ...t, processTreeState: T ? "terminated" : "indeterminate", ...E.length ? { error: new AggregateError(E, "Managed command finalization failed") } : {} }; windowsTerminations.set(e, r); try { S.close(); windowsJobs.delete(e); } catch (t) { T = false; E.push(createManagedCommandCleanupError("Windows Job handle closure failed", e, n, "indeterminate", t)); r.processTreeState = "indeterminate"; r.error = new AggregateError(E, "Windows Job finalization failed"); } } if (T) u(); if (E.length === 1) throw E[0]; if (E.length > 1) throw new AggregateError(E, "Managed command finalization failed"); } function createManagedCommandSetupCleanupError(e, t) { return new AggregateError([e, t], "Managed command setup failed and its process tree could not be cleaned up", { cause: t }); } function createManagedCommandCleanupError(e, t, n, r, i) { const a = n !== "win32" && t.pid !== void 0 && Number.isSafeInteger(t.pid) && t.pid > 1 ? t.pid : void 0; return Object.assign(new Error(e, { cause: i }), { code: "EPROCESSGROUP_CLEANUP_FAILED", ...n === "win32" ? { manualRecoveryRequired: true } : {}, ...a === void 0 ? {} : { processGroupId: a }, processTreeState: r }); } function installSignalHandlers() { for (const e of FORWARDED_SIGNALS) { if (signalHandlers.has(e)) continue; const handler = () => forwardSignalToManagedChildren(e); signalHandlers.set(e, handler); process.on(e, handler); } } function removeSignalHandlersIfIdle() { if (managedChildren.size > 0) return; for (const [e, t] of signalHandlers) process.off(e, t); signalHandlers.clear(); } function forwardSignalToManagedChildren(e) { for (const t of managedChildren) t(e); } function createManagedCommandSpawnSpec(e) { const { cwd: t, env: n, stdio: r = "inherit", platform: i = process.platform } = e; const { args: a, command: o, ...s } = createManagedCommandInvocation(e); return { args: a, command: o, options: { cwd: t, env: n, stdio: r, ...s, detached: i !== "win32" } }; } function createManagedCommandInvocation({ bin: e, args: t = [], env: n, platform: r = process.platform, shell: i = r === "win32", windowsVerbatimArguments: a, comSpec: o }) { if (r === "win32" && i && t.length > 0) return { args: [ "/d", "/s", "/c", buildCmdExeCommandLine(e, t) ], command: o ?? resolveWindowsCmdExePath(n ?? process.env), shell: false, windowsVerbatimArguments: true }; return { args: t, command: e, shell: i, windowsVerbatimArguments: a }; } function signalNumberFor(e) { switch (e) { case "SIGHUP": return 1; case "SIGINT": return 2; case "SIGTERM": return 15; default: return constants$1.signals?.[e] ?? 0; } } function isMissingProcessError(e) { return hasProcessErrorCode(e, "ESRCH"); } function hasProcessErrorCode(e, t) { return Boolean(e && typeof e === "object" && "code" in e && e.code === t); } //#endregion export { ManagedCleanupCancelled as a, runManagedCommand as i, hasUnjoinedWork as n, claimManagedCleanup as o, loadManagedChildSpawner as r, failManagedCleanup as s, finalizeManagedChild as t };