Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
fix(procs): stop CLI descendants that left the process group on macOS, and execCli's on timeout
Krishna Dobhal5e5ae9e305b2
diff --git a/server/kill-tree-escaped.test.ts b/server/kill-tree-escaped.test.tsnew file mode 100644index 0000000000..ac4e39089d--- /dev/null+++ b/server/kill-tree-escaped.test.ts@@ -0,0 +1,34 @@+import { mkdtempSync, readFileSync, rmSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, describe, expect, it } from "vitest";+import { execCli } from "./procs.ts";++const posix = process.platform === "linux" || process.platform === "darwin";+let dir: string | undefined;+let grandchild: number | undefined;++afterEach(() => {+ if (grandchild) try { process.kill(grandchild, "SIGKILL"); } catch {}+ if (dir) rmSync(dir, { recursive: true, force: true });+ dir = grandchild = undefined;+});++const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };++describe.runIf(posix)("execCli timeout", () => {+ it("stops a SIGTERM-ignoring grandchild that left the process group", async () => {+ dir = mkdtempSync(join(tmpdir(), "omb-escaped-"));+ const pidFile = join(dir, "pid");+ const sleeper = "process.on('SIGTERM',()=>{});setInterval(()=>{},1000)";+ const wrapper = `process.on('SIGTERM',()=>{});`+ + `const c=require('child_process').spawn(process.execPath,['-e',${JSON.stringify(sleeper)}],{detached:true,stdio:'ignore'});`+ + `require('fs').writeFileSync(${JSON.stringify(pidFile)},String(c.pid));setInterval(()=>{},1000)`;+ const done = new Promise<Error | null>((resolve) => execCli(process.execPath, ["-e", wrapper], { timeout: 1_500 }, (err) => resolve(err)));+ await done;+ grandchild = Number(readFileSync(pidFile, "utf8"));+ const deadline = Date.now() + 3_000;+ while (alive(grandchild) && Date.now() < deadline) await new Promise((resolve) => setTimeout(resolve, 50));+ expect(alive(grandchild)).toBe(false);+ }, 15_000);+});diff --git a/server/procs.ts b/server/procs.tsindex c0dbdd5f09..f5e25e81c7 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -4,6 +4,7 @@import {spawn,execFile,+ execFileSync,type ChildProcess,type ChildProcessByStdio,type ExecFileOptions,@@ -62,7 +63,27 @@ const stopping = new WeakMap<ChildProcess, Promise<boolean>>();type LinuxProcess = { pid: number; parent: number; start: string; state: string };const linuxTrees = new WeakMap<ChildProcess, Map<number, string>>();+const PS_ROW = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/;++/** macOS has no /proc: `ps` gives the same pid, parent, state and start time (`lstart`, the identity that survives PID reuse). */+function psProcesses(pid?: number): Map<number, LinuxProcess> {+ const rows = new Map<number, LinuxProcess>();+ let out: string;+ try {+ out = execFileSync("/bin/ps", [...(pid ? ["-p", String(pid)] : ["-A"]), "-o", "pid=,ppid=,stat=,lstart="], { encoding: "utf8", timeout: 2_000, windowsHide: true });+ } catch (error) {+ if (pid && (error as { status?: number }).status === 1) return rows;+ throw error;+ }+ for (const line of out.split(/\r?\n/)) {+ const match = PS_ROW.exec(line);+ if (match) rows.set(Number(match[1]), { pid: Number(match[1]), parent: Number(match[2]), state: match[3][0], start: match[4] });+ }+ return rows;+}+function linuxProcess(pid: number, file = `/proc/${pid}/stat`): LinuxProcess | null {+ if (process.platform === "darwin") return psProcesses(pid).get(pid) ?? null;let stat: string;try {stat = readFileSync(file, "utf8");@@ -108,13 +129,16 @@ function isLinuxProcess(pid: number, start: string): boolean {/** Linux sandbox helpers can leave the CLI's process group and reparent during a protocol interrupt. */export function captureCliTree(child: ChildProcess): void {- if (process.platform !== "linux" || !cliGroups.has(child) || !child.pid) return;+ if ((process.platform !== "linux" && process.platform !== "darwin") || !child.pid) return;let tree = linuxTrees.get(child);+ if (!tree && !cliGroups.has(child)) return;if (!tree) {tree = new Map();linuxTrees.set(child, tree);}- if (!linuxChildrenFiles() || !addLinuxDescendants(tree)) addLinuxDescendantsFromEveryProcess(tree);+ if (process.platform === "darwin" || !linuxChildrenFiles() || !addLinuxDescendants(tree)) {+ try { addDescendantsFromEveryProcess(tree); } catch {}+ }}/** False when the walk may have missed a descendant; those it confirmed stay in the tree. A children file can skip a@@ -139,17 +163,20 @@ function addLinuxDescendants(tree: Map<number, string>): boolean {return true;}-function addLinuxDescendantsFromEveryProcess(tree: Map<number, string>): void {- const snapshot = new Map<number, LinuxProcess>();- let entries: string[];- try { entries = readdirSync("/proc"); } catch { return; }- for (const entry of entries) {- if (!/^\d+$/.test(entry)) continue;- const pid = Number(entry);- try {- const current = linuxProcess(pid);- if (current) snapshot.set(pid, current);- } catch {}+function addDescendantsFromEveryProcess(tree: Map<number, string>): void {+ let snapshot = new Map<number, LinuxProcess>();+ if (process.platform === "darwin") snapshot = psProcesses();+ else {+ let entries: string[];+ try { entries = readdirSync("/proc"); } catch { return; }+ for (const entry of entries) {+ if (!/^\d+$/.test(entry)) continue;+ const pid = Number(entry);+ try {+ const current = linuxProcess(pid);+ if (current) snapshot.set(pid, current);+ } catch {}+ }}const parents = new Set([...tree].filter(([pid, start]) => snapshot.get(pid)?.start === start).map(([pid]) => pid));let discovered: boolean;@@ -366,7 +393,7 @@ export function spawnCli(// The broker token minted for this process dies with it.if (boxed?.token) child.once("exit", boxed.release);if (process.platform !== "win32") cliGroups.add(child);- if (process.platform === "linux" && child.pid) {+ if ((process.platform === "linux" || process.platform === "darwin") && child.pid) {const tree = new Map<number, string>();try {const root = linuxProcess(child.pid);@@ -452,10 +479,16 @@ export function execCli(cb(err ?? (timedOut ? cutOffError(cli, opts.timeout) : null), stdout, stderr);});// Node (24) calls back only once the child exits, and a CLI wrapper that traps SIGTERM outlives the timeout's signal.- // Only the child is stopped: execFile starts no process group, so a grandchild that ignores SIGTERM can outlive it.+ // execFile starts no process group: the child's descendants are tracked and signalled one by one.// When its timeout fires after the child exited but before Node saw the exit, Node (24) drops the output and still// reports success; this timer is queued just after Node's, so it marks that run as timed out.if (opts.timeout) {+ if (child.pid && (process.platform === "linux" || process.platform === "darwin")) {+ try {+ const root = linuxProcess(child.pid);+ if (root) linuxTrees.set(child, new Map([[root.pid, root.start]]));+ } catch {}+ }escalate = setTimeout(() => void killCliTree(child, 0), opts.timeout + EXEC_KILL_GRACE_MS);escalate.unref?.();deadline = setTimeout(() => {