UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

383 lines (382 loc) • 11.4 kB
import { opendirSync, readFileSync } from "node:fs"; import { spawn, spawnSync } from "node:child_process"; //#region packages/agent-core/src/harness/env/kill-tree.ts const DEFAULT_GRACE_MS = 3e3; const MAX_GRACE_MS = 6e4; const TASKKILL_COMPLETION_TIMEOUT_MS = 3e3; const UNIX_PROCESS_TREE_TIMEOUT_MS = 500; const MAX_UNIX_PROCESS_TREE_PIDS = 4096; const MAX_UNIX_PROCESS_TREE_DEPTH = 128; /** * Best-effort process-tree termination with graceful shutdown. * - Windows: use taskkill /T to include descendants. Sends SIGTERM-equivalent * first (without /F), then force-kills if taskkill refuses or the process * survives the grace period. * - Unix: send SIGTERM to the process group when ownership is known, wait the * grace period, then SIGKILL. Linux attached children are enumerated and * signaled descendants-first because their process group belongs to the gateway. * * Group kill (`process.kill(-pid, ...)`) is only used when the PID is verified * as its own process group leader, unless `detached: true` is explicitly passed. * This prevents accidentally signaling the gateway's process group when the * child shares its parent's group. * * - `detached: false`: skip group kill unconditionally. * - `detached: true`: use group kill unconditionally (trust caller). * - `detached` omitted: use group kill only when PID is the group leader. * * `exited()` verifies that every retained escalation target is gone: the group, * every captured Linux attached-tree identity, or otherwise the root. True latches, * clears the grace timer, and prevents later `force()` calls from signaling recycled numbers. */ function killProcessTree(e, t) { if (!Number.isFinite(e) || e <= 0) return; if (process.platform === "win32") { if (t?.force === true) { signalProcessTreeWindowsAndWait(e, "SIGKILL"); return; } killProcessTreeWindows(e, normalizeGraceMs(t?.graceMs)); return; } const n = t?.detached === true || t?.detached !== false && isProcessGroupLeader(e); const r = t?.detached === false && !n && process.platform === "linux"; const i = r ? collectUnixProcessTree(e) : void 0; if (r && !i) { signalProcessTreeUnix(e, t?.force === true ? "SIGKILL" : "SIGTERM", false); return; } let a = false; const force = () => { if (a) return; a = true; const t = i?.filter(verifiedProcessInstanceAlive) ?? []; if (!(n ? isProcessAlive(-e) : r ? t.length > 0 : isProcessAlive(e))) return; signalProcessTreeUnix(e, "SIGKILL", n, i ? t : void 0); }; if (t?.force === true) { if (i) force(); else signalProcessTreeUnix(e, "SIGKILL", n); return; } signalProcessTreeUnix(e, "SIGTERM", n, i); const o = normalizeGraceMs(t?.graceMs); const s = setTimeout(force, o); if (!r) s.unref(); let c = false; const exited = () => { c ||= n ? !isProcessAlive(-e) : i ? !i.some(capturedProcessInstanceMayBeAlive) : !isProcessAlive(e); if (c) { a = true; clearTimeout(s); } return c; }; return { force: () => { clearTimeout(s); force(); }, exited }; } function signalProcessTree(e, t, n) { if (!Number.isFinite(e) || e <= 0) { n?.onComplete?.(); return; } if (process.platform === "win32") { signalProcessTreeWindowsAndWait(e, t).then(n?.onComplete); return; } const r = n?.detached === true || n?.detached !== false && isProcessGroupLeader(e); signalProcessTreeUnix(e, t, r, n?.detached === false && !r && process.platform === "linux" ? collectUnixProcessTree(e) : void 0); n?.onComplete?.(); } /** Capture the group selected by signalProcessTree while its leader still exists. */ function readUnixProcessGroupMembers(e) { if (process.platform === "win32" || !isProcessGroupLeader(e)) return [e]; const t = readPsOutput(["-axo", "pid=,pgid="]); const n = /* @__PURE__ */ new Set([e]); for (const r of t?.split("\n") ?? []) { const [t, i] = r.trim().split(/\s+/); const a = parseProcessGroupId(t); if (a && parseProcessGroupId(i) === e) n.add(a); } return [...n]; } /** Signals every process group and process still owned by one forkpty session. */ function signalPtySessionTree(e, t) { if (!Number.isFinite(e) || e <= 0) return; if (process.platform === "win32") { signalProcessTreeWindowsAndWait(e, t); return; } const n = process.platform === "darwin" ? readDarwinPtyTty(e) : void 0; if (process.platform === "darwin" && !n) { signalUnixTarget(-e, t); return; } const r = readProcessSessionMembers(e, n); if (!r) { signalUnixTarget(-e, t); return; } const signalMembers = (n) => { const r = new Set(n.map((e) => e.pgid)); r.delete(e); for (const e of r) signalUnixTarget(-e, t); for (const r of n) if (r.pid !== e) signalUnixTarget(r.pid, t); }; signalMembers(r); const i = readProcessSessionMembers(e, n); if (i) signalMembers(i); signalUnixTarget(-e, t); signalUnixTarget(e, t); } function normalizeGraceMs(e) { if (typeof e !== "number" || !Number.isFinite(e)) return DEFAULT_GRACE_MS; return Math.max(0, Math.min(MAX_GRACE_MS, Math.floor(e))); } function isProcessAlive(e) { try { process.kill(e, 0); } catch (e) { if ((typeof e === "object" && e !== null && "code" in e ? e.code : void 0) !== "EPERM") return false; } if (e < 0 || process.platform !== "linux") return true; try { const t = readFileSync(`/proc/${e}/status`, "utf8"); return !(t.match(/^State:\s+(\S)/m)?.[1] === "Z" && /^Threads:[ \t]+1[ \t]*$/m.test(t)); } catch { return true; } } function parseProcessGroupId(e) { if (typeof e !== "string" || !/^\d+$/.test(e.trim())) return; const t = Number(e.trim()); return Number.isSafeInteger(t) && t > 0 ? t : void 0; } function readPsOutput(e) { try { const t = spawnSync("ps", e, { encoding: "utf8", timeout: 500 }); return t.error || t.status !== 0 ? void 0 : t.stdout; } catch { return; } } function readProcStatFields(e) { try { const t = readFileSync(`/proc/${e}/stat`, "utf8"); const n = t.lastIndexOf(")"); if (n < 0) return; return t.slice(n + 1).trim().split(/\s+/); } catch { return; } } function readDarwinPtyTty(e) { const t = readPsOutput([ "-p", String(e), "-o", "tty=" ])?.trim(); return t && t !== "?" && t !== "??" ? t : void 0; } function readProcessSessionMembers(e, t) { const n = t ?? String(e); const r = readPsOutput(t ? [ "-t", t, "-o", "pid=,pgid=" ] : process.platform === "linux" ? [ "-s", n, "-o", "pid=,pgid=,sid=" ] : ["-axo", "pid=,pgid=,sid="]); if (r === void 0) return; const i = []; for (const e of r.split("\n")) { const [r, a, o] = e.trim().split(/\s+/); const s = parseProcessGroupId(r); const c = parseProcessGroupId(a); if (s && c && (t || o === n)) i.push({ pid: s, pgid: c }); } return i; } /** Fail closed to direct-PID signaling when group ownership cannot be proved. */ function isProcessGroupLeader(e) { return ((process.platform === "linux" ? parseProcessGroupId(readProcStatFields(e)?.[2]) : void 0) ?? parseProcessGroupId(readPsOutput([ "-p", String(e), "-o", "pgid=" ]))) === e; } function parsePositivePids(e) { if (typeof e !== "string") return []; return e.trim().split(/\s+/u).map((e) => Number(e)).filter((e) => Number.isSafeInteger(e) && e > 0); } function readUnixProcessIdentity(e, t) { return readUnixProcessInstance(e, t)?.identity; } /** Capture identity and parent together so a recycled child PID cannot authorize a foreign tree. */ function readUnixProcessInstance(e, t) { if (t !== void 0 && Date.now() >= t) return; if (process.platform !== "linux") return; const n = readProcStatFields(e); const r = Number(n?.[1]); const i = n?.[19]; if (!i || !/^\d+$/u.test(i) || !Number.isSafeInteger(r)) return; return { identity: `${e}:${i}`, ppid: r }; } /** Missing identities are never eligible for an attached-tree signal. */ function verifiedProcessInstanceAlive(e) { if (!e.identity || !isProcessAlive(e.pid)) return false; return readUnixProcessIdentity(e.pid) === e.identity; } /** Completion needs proof: an existing PID whose identity is unreadable may still be the captured instance. */ function capturedProcessInstanceMayBeAlive(e) { if (!e.identity || !isProcessAlive(e.pid)) return false; const t = readUnixProcessIdentity(e.pid); return t === void 0 || t === e.identity; } function* readUnixProcessChildren(e, t) { let n; try { n = opendirSync(`/proc/${e}/task`); while (t()) { const t = n.readSync(); if (!t) return; const r = parseProcessGroupId(t.name); if (!r) continue; try { yield* parsePositivePids(readFileSync(`/proc/${e}/task/${r}/children`, "utf8")); } catch {} } } catch {} finally { try { n?.closeSync(); } catch {} } } /** Capture verified descendants before their parents; an unverified subtree is omitted. */ function collectUnixProcessTree(e) { if (process.platform !== "linux") return; const t = []; const n = /* @__PURE__ */ new Set([e]); let r = 0; const i = Date.now() + UNIX_PROCESS_TREE_TIMEOUT_MS; const a = readUnixProcessIdentity(e, i); if (!a || Date.now() >= i) return; const withinBounds = (e) => Date.now() < i && e <= MAX_UNIX_PROCESS_TREE_DEPTH; const hasCapacity = () => n.size < MAX_UNIX_PROCESS_TREE_PIDS; const visit = (e, a, o) => { if (!withinBounds(o) || !hasCapacity()) return; if (readUnixProcessIdentity(e, i) !== a) return; const s = readUnixProcessChildren(e, () => withinBounds(o) && hasCapacity() && r++ < MAX_UNIX_PROCESS_TREE_PIDS && readUnixProcessIdentity(e, i) === a); for (const r of s) { if (!withinBounds(o + 1) || !hasCapacity()) return; if (n.has(r) || r === process.pid) continue; n.add(r); const a = readUnixProcessInstance(r, i); if (!a || a.ppid !== e || !withinBounds(o + 1)) continue; visit(r, a.identity, o + 1); t.push({ pid: r, identity: a.identity }); } }; visit(e, a, 0); return [...t, { pid: e, identity: a }]; } function signalProcessTreeUnix(e, t, n, r) { if (n) { signalUnixTarget(-e, t); return; } const i = r ?? [{ pid: e }]; for (const e of i) { if (r && !verifiedProcessInstanceAlive(e)) continue; signalUnixTarget(e.pid, t); } } function signalUnixTarget(e, t) { try { process.kill(e, t); } catch {} } function runTaskkill(e, t) { return new Promise((n) => { let r = false; const finish = (e) => { if (r) return; r = true; clearTimeout(i); t?.(e); n(); }; const i = setTimeout(() => finish(null), TASKKILL_COMPLETION_TIMEOUT_MS); i.unref?.(); try { const t = spawn("taskkill", e, { stdio: "ignore", detached: true, windowsHide: true }); t.once("error", () => finish(null)); t.once("close", (e) => finish(e)); } catch { finish(null); } }); } function killProcessTreeWindows(e, t) { let n = false; let r; const forceKill = () => { if (n) return; n = true; if (r !== void 0) { clearTimeout(r); r = void 0; } if (!isProcessAlive(e)) return; signalProcessTreeWindowsAndWait(e, "SIGKILL"); }; signalProcessTreeWindowsAndWait(e, "SIGTERM", (e) => { if (e !== null && e !== 0) forceKill(); }); r = setTimeout(forceKill, t); r.unref(); } function signalProcessTreeWindowsAndWait(e, t, n) { return runTaskkill(t === "SIGKILL" ? [ "/F", "/T", "/PID", String(e) ] : [ "/T", "/PID", String(e) ], n); } //#endregion export { signalPtySessionTree as i, readUnixProcessGroupMembers as n, signalProcessTree as r, killProcessTree as t };