UNPKG

@sema-agent/core

Version:

Stateless, task-oriented AI agent core

277 lines (276 loc) • 8.92 kB
import { spawn } from "node:child_process"; import { inheritedHostEnv } from "../../core/secret-env.js"; import { processGroupReadingIn, readProcessTable, sameProcessMark } from "../../core/process-table.js"; import { existsSync } from "node:fs"; import { join } from "node:path"; const DEFAULT_GRACE_MS = 3000; const MAX_GRACE_MS = 60_000; import { shutdownDebug } from "../../core/shutdown-debug.js"; export { shutdownDebug }; export function killProcessTree(pid, opts) { if (!Number.isFinite(pid) || pid <= 0) { return; } shutdownDebug("killProcessTree", { pid, force: opts?.force === true, detached: opts?.detached !== false, graceMs: opts?.graceMs }); if (process.platform === "win32") { if (opts?.force === true) { signalProcessTreeWindows(pid, "SIGKILL"); return; } const graceMs = normalizeGraceMs(opts?.graceMs); killProcessTreeWindows(pid, graceMs, undefined); return; } const useGroupKill = opts?.detached !== false; if (opts?.force === true) { signalProcessTreeUnix(pid, "SIGKILL", useGroupKill); return; } const graceMs = normalizeGraceMs(opts?.graceMs); const term = signalProcessTreeUnix(pid, "SIGTERM", useGroupKill); setTimeout(() => { const rediscovered = enumerateDescendantsSync(pid); const verifiedCarriedForward = new Map(); for (const [p, originalEtime] of term.descendants) { const currentEtime = rediscovered.etimeOf.get(p); if (currentEtime !== undefined && verifyStillSameProcess(originalEtime, currentEtime)) { verifiedCarriedForward.set(p, currentEtime); } } const leaderNow = rediscovered.etimeOf.get(pid); const bothMarks = term.leaderMark !== undefined && leaderNow !== undefined; const sameLeader = bothMarks && verifyStillSameProcess(term.leaderMark, leaderNow); const walkIsOurs = sameLeader || (term.leaderMark === undefined && anchorSaysRunning(opts?.stillRunning)); const knownDescendants = new Map([...verifiedCarriedForward, ...(walkIsOurs ? rediscovered.descendants : [])]); killEach(knownDescendants.keys(), "SIGKILL"); if (bothMarks && !sameLeader) return; if (escalationCancelled(opts?.stillRunning)) { if (useGroupKill && groupMayRun(rediscovered, pid)) { try { process.kill(-pid, "SIGKILL"); } catch { } } return; } const stillAlive = useGroupKill ? groupMayRun(rediscovered, pid) || isProcessAlive(pid) : isProcessAlive(pid); if (!stillAlive) { return; } if (useGroupKill) { try { process.kill(-pid, "SIGKILL"); return; } catch { } } try { process.kill(pid, "SIGKILL"); } catch { } }, graceMs).unref(); } function anchorSaysRunning(stillRunning) { if (stillRunning === undefined) return false; try { return stillRunning() === true; } catch { return false; } } function escalationCancelled(stillRunning) { if (stillRunning === undefined) return false; try { return !stillRunning(); } catch { return false; } } export function signalProcessTree(pid, signal, opts) { if (!Number.isFinite(pid) || pid <= 0) { return; } if (process.platform === "win32") { signalProcessTreeWindows(pid, signal); return; } signalProcessTreeUnix(pid, signal, opts?.detached !== false); } function normalizeGraceMs(value) { if (typeof value !== "number" || !Number.isFinite(value)) { return DEFAULT_GRACE_MS; } return Math.max(0, Math.min(MAX_GRACE_MS, Math.floor(value))); } function isProcessAlive(pid) { try { process.kill(pid, 0); return true; } catch { return false; } } function signalProcessTreeUnix(pid, signal, useGroupKill) { const snapshot = enumerateDescendantsSync(pid); const descendants = snapshot.descendants; const leaderMark = snapshot.etimeOf.get(pid); if (useGroupKill) { try { process.kill(-pid, signal); } catch { try { process.kill(pid, signal); } catch { } } killEach(descendants.keys(), signal); return { descendants, leaderMark }; } try { process.kill(pid, signal); } catch { } killEach(descendants.keys(), signal); return { descendants, leaderMark }; } function killEach(pids, signal) { for (const pid of pids) { try { process.kill(pid, signal); } catch { } } } const PS_ENUMERATION_TIMEOUT_MS = 500; const UNREAD_TABLE = Object.freeze({ unreadable: "no process table reader on win32" }); const emptySnapshot = (table) => ({ descendants: new Map(), etimeOf: new Map(), table }); function enumerateDescendantsSync(rootPid) { if (process.platform === "win32") return emptySnapshot(UNREAD_TABLE); const table = readProcessTable(PS_ENUMERATION_TIMEOUT_MS); if ("unreadable" in table) return emptySnapshot(table); const childrenOf = new Map(); const etimeOf = new Map(); for (const row of table.values()) { const p = row.pid; const pp = row.ppid; etimeOf.set(p, row.mark); const list = childrenOf.get(pp); if (list) list.push(p); else childrenOf.set(pp, [p]); } const seen = new Set(); const queue = [rootPid]; while (queue.length > 0) { const cur = queue.shift(); for (const kid of childrenOf.get(cur) ?? []) { if (kid <= 1 || kid === rootPid || seen.has(kid)) continue; seen.add(kid); queue.push(kid); } } const descendants = new Map(); for (const p of seen) { const et = etimeOf.get(p); if (et !== undefined) descendants.set(p, et); } return { descendants, etimeOf, table }; } function verifyStillSameProcess(originalMark, currentMark) { return sameProcessMark(originalMark, currentMark); } function groupMayRun(snapshot, pgid) { const reading = processGroupReadingIn(snapshot.table, pgid); return reading === "running_member" || reading === "unreadable"; } function runTaskkill(args) { try { const child = spawn("taskkill", args, { env: inheritedHostEnv("scrub"), stdio: "ignore", detached: true, windowsHide: true, }); child.on("error", () => { }); } catch { } } function killProcessTreeWindows(pid, graceMs, stillRunning) { signalProcessTreeWindows(pid, "SIGTERM"); setTimeout(() => { if (escalationCancelled(stillRunning)) { return; } if (!isProcessAlive(pid)) { return; } signalProcessTreeWindows(pid, "SIGKILL"); }, graceMs).unref(); } function signalProcessTreeWindows(pid, signal) { if (signal === "SIGKILL") { const bash = gitBashPath(); if (bash) { const fired = tryMsysGroupKill(bash, pid); if (fired) { setTimeout(() => runTaskkill(["/F", "/T", "/PID", String(pid)]), 1200).unref(); return; } } runTaskkill(["/F", "/T", "/PID", String(pid)]); return; } runTaskkill(["/T", "/PID", String(pid)]); } function gitBashPath() { const candidates = [ process.env.SEMA_GIT_BASH, join(process.env["ProgramFiles"] ?? "C:\\Program Files", "Git", "bin", "bash.exe"), join(process.env["ProgramFiles(x86)"] ?? "C:\\Program Files (x86)", "Git", "bin", "bash.exe"), ]; for (const c of candidates) { try { if (c && existsSync(c)) return c; } catch { } } return undefined; } function tryMsysGroupKill(bashPath, pid) { const script = `kids=$(powershell.exe -NoProfile -Command "Get-CimInstance Win32_Process -Filter 'ParentProcessId=${pid}' | Select-Object -ExpandProperty ProcessId" 2>/dev/null | tr -d "\\r"); ` + `for w in ${pid} $kids; do ` + `g=$(ps -W | awk -v w="$w" '$4==w {print $3; exit}'); ` + `[ -n "$g" ] && [ "$g" != "0" ] && kill -9 -"$g" 2>/dev/null; ` + `done; exit 0`; try { const child = spawn(bashPath, ["-c", script], { env: inheritedHostEnv("scrub"), stdio: "ignore", detached: true, windowsHide: true }); child.on("error", () => { }); return true; } catch { return false; } }