Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
perf: start-up reads use their indexes, and a turn's stop walks only its own process tree
Absterrg02ad248897c33
diff --git a/scripts/bench-start-scans.ts b/scripts/bench-start-scans.tsnew file mode 100644index 0000000000..6c47fb934e--- /dev/null+++ b/scripts/bench-start-scans.ts@@ -0,0 +1,113 @@+// Synthetic local data only. Never import config before isolating data.+// node --experimental-strip-types scripts/bench-start-scans.ts [baseline-ref=main] [messages=200000]+// Times the start-up reads of messages.db and one capture of an engine's process tree, at the baseline ref and at+// this checkout, on the same data, and fails when the two disagree.+import { deepStrictEqual } from "node:assert";+import { execFileSync } from "node:child_process";+import { mkdtempSync, readdirSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { fileURLToPath } from "node:url";++const ROOT = fileURLToPath(new URL("..", import.meta.url));+const ref = process.argv[2] ?? "main";+const total = Number(process.argv[3] ?? 200_000);+const directory = mkdtempSync(join(tmpdir(), "omb-start-scans-bench-"));+process.env.HOME = directory;+process.env.USERPROFILE = directory;+process.env.OMB_DATA_DIR = join(directory, "data");++const baselineFiles = ["message-db", "procs"].map((name) => ({ name, path: join(ROOT, "server", `${name}.bench-baseline.ts`) }));+for (const { name, path } of baselineFiles) writeFileSync(path, execFileSync("git", ["show", `${ref}:server/${name}.ts`], { cwd: ROOT }));++type MessageDb = typeof import("../server/message-db.ts");+type Procs = typeof import("../server/procs.ts");+const median = (values: number[]) => [...values].sort((a, b) => a - b)[Math.floor(values.length / 2)]!;+const round = (value: number) => Number(value.toFixed(2));++/** Wall and CPU time of `runs` calls; CPU is what the server's one thread spends, whatever else the machine runs. */+function measure<T>(run: () => T, runs: number): { result: T; wallMs: number; cpuMs: number } {+ const wall: number[] = [], cpu: number[] = [];+ let result!: T;+ for (let i = 0; i < runs; i++) {+ const startCpu = process.cpuUsage(), start = performance.now();+ result = run();+ wall.push(performance.now() - start);+ const used = process.cpuUsage(startCpu);+ cpu.push((used.user + used.system) / 1000);+ }+ return { result, wallMs: round(median(wall)), cpuMs: round(median(cpu)) };+}++try {+ const baselineDb = await import(join(ROOT, "server", "message-db.bench-baseline.ts")) as MessageDb;+ const tools = ["your_computer", "computer_ask", "ask_peer"];+ const filler = (n: number) => "Synthetic history for start-up measurement. ".repeat(Math.ceil(n / 45)).slice(0, n);+ const threads: string[] = [];+ const at0 = Date.now() - 30 * 86_400_000;+ let seeded = 0;+ for (let thread = 0; seeded < total; thread++) {+ const threadId = `thread-${thread}`;+ threads.push(threadId);+ const rows: Array<Record<string, unknown>> = [];+ for (let turn = 0; rows.length < 1_000 && seeded + rows.length < total; turn++) {+ const at = at0 + (thread * 1_000 + turn) * 60_000, turnId = `${threadId}-turn-${turn}`;+ rows.push({ id: `${turnId}-ask`, role: "user", kind: "text", text: `Handle item ${turn}. ${filler(160)}`, at, sendId: `${turnId}-send` });+ for (let call = 0; call < 3; call++) {+ rows.push({ id: `${turnId}-call-${call}`, role: "bot", kind: "activity", at: at + 1_000 * (call + 1), turnId,+ tool: { name: call ? "Bash" : "Read", ok: true, input: JSON.stringify({ command: filler(400) }), output: filler(1_500) } });+ }+ if (turn % 40 === 0) {+ rows.push({ id: `${turnId}-card`, role: "bot", kind: "options", at: at + 4_500, turnId,+ card: { title: "Allow?", subtitle: "", options: ["Yes", "No"], requestType: "question", tool: tools[turn % tools.length], requestId: `${turnId}-request` } });+ }+ rows.push({ id: `${turnId}-reply`, role: "bot", kind: "text", text: `Done. ${filler(600)}`, at: at + 5_000, turnId, turnTerminal: true, turnCompletedAt: at + 5_500 });+ rows.push({ id: `${turnId}-digest`, role: "bot", kind: "digest", text: filler(200), at: at + 6_000, turnId, turnSucceeded: true });+ }+ let parentId: string | null = null;+ for (const row of rows) { row.parentId = parentId; parentId = row.id as string; }+ baselineDb.importThread(threadId, rows as never, parentId);+ seeded += rows.length;+ }+ baselineDb.closeMessageDb();++ const reads = (db: MessageDb) => ({+ optionCards: () => [db.optionCardsForTools(["your_computer"]), db.optionCardsForTools(["computer_ask"]), db.optionCardsForTools(["ask_peer"])],+ threadStamps: () => [db.latestMessageAts(threads), db.latestMessageAts(threads, true)].map((stamps) => [...stamps].sort(([a], [b]) => a.localeCompare(b))),+ });+ const before = reads(baselineDb);+ const baselineRuns = { optionCards: measure(before.optionCards, 7), threadStamps: measure(before.threadStamps, 7) };+ baselineDb.closeMessageDb();++ const currentDb = await import("../server/message-db.ts");+ const firstOpen = measure(() => currentDb.latestMessageAts([threads[0]!]), 1);+ const after = reads(currentDb);+ const currentRuns = { optionCards: measure(after.optionCards, 7), threadStamps: measure(after.threadStamps, 7) };+ currentDb.closeMessageDb();+ for (const read of ["optionCards", "threadStamps"] as const) {+ deepStrictEqual(currentRuns[read].result, baselineRuns[read].result);+ console.log(JSON.stringify({ read, messages: seeded, threads: threads.length,+ before: { wallMs: baselineRuns[read].wallMs, cpuMs: baselineRuns[read].cpuMs },+ after: { wallMs: currentRuns[read].wallMs, cpuMs: currentRuns[read].cpuMs } }));+ }+ console.log(JSON.stringify({ read: "first open after the upgrade (index build, once)", wallMs: firstOpen.wallMs, cpuMs: firstOpen.cpuMs }));++ if (process.platform === "linux") {+ const processes = readdirSync("/proc").filter((entry) => /^\d+$/.test(entry)).length;+ const capture = async (procs: Procs) => {+ const child = procs.spawnCli("sh", ["-c", "sleep 60 & sleep 60 & wait"], { stdio: "pipe" });+ await new Promise((resolve) => setTimeout(resolve, 200));+ const timed = measure(() => procs.captureCliTree(child), 25);+ await procs.killCliTree(child, 1_000);+ return timed;+ };+ const baselineProcs = await import(join(ROOT, "server", "procs.bench-baseline.ts")) as Procs;+ const captureBefore = await capture(baselineProcs);+ const captureAfter = await capture(await import("../server/procs.ts"));+ console.log(JSON.stringify({ read: "engine process tree capture", processesOnMachine: processes,+ before: { wallMs: captureBefore.wallMs, cpuMs: captureBefore.cpuMs }, after: { wallMs: captureAfter.wallMs, cpuMs: captureAfter.cpuMs } }));+ }+} finally {+ for (const { path } of baselineFiles) rmSync(path, { force: true });+ rmSync(directory, { recursive: true, force: true });+}diff --git a/server/kill-tree-linux.test.ts b/server/kill-tree-linux.test.tsindex 7d5f274890..31add74b47 100644--- a/server/kill-tree-linux.test.ts+++ b/server/kill-tree-linux.test.ts@@ -2,14 +2,22 @@ import type { ChildProcess } from "node:child_process";import { EventEmitter } from "node:events";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-const mocks = vi.hoisted(() => ({ spawn: vi.fn(), readdir: vi.fn(), read: vi.fn() }));+const mocks = vi.hoisted(() => ({ spawn: vi.fn(), readdir: vi.fn(), read: vi.fn(), exists: vi.fn() }));vi.mock("node:child_process", async (original) => ({ ...await original<typeof import("node:child_process")>(), spawn: mocks.spawn }));-vi.mock("node:fs", async (original) => ({ ...await original<typeof import("node:fs")>(), readdirSync: mocks.readdir, readFileSync: mocks.read }));+vi.mock("node:fs", async (original) => ({ ...await original<typeof import("node:fs")>(), readdirSync: mocks.readdir, readFileSync: mocks.read, existsSync: mocks.exists }));import { captureCliTree, killCliTree, spawnCli } from "./procs.ts";let processes: Map<number, string>;let denied: Set<number>;+/** What a children file lists instead of the true children, as when Linux skips one. */+let listed: Map<number, string>;+let hiddenTasks: Set<number>;+/** Threads beyond each process's main one, and what each thread's children file reads. */+let threads: Map<number, string[]>;+let threadChildren: Map<string, string>;+let goneThreads: Set<number>;+let onTaskList: (pid: number) => void;let signal: ReturnType<typeof vi.fn>;function stat(pid: number, parent: number, start: string, state = "S"): string {@@ -21,6 +29,10 @@ function stat(pid: number, parent: number, start: string, state = "S"): string {return `${pid} (helper with ) in name) ${fields.join(" ")}`;}+function parentOf(value: string): string {+ return value.slice(value.lastIndexOf(")") + 2).split(" ")[1];+}+function root(): ChildProcess {const child = Object.assign(new EventEmitter(), {pid: 10001, exitCode: null, signalCode: null,@@ -33,12 +45,41 @@ function root(): ChildProcess {beforeEach(() => {processes = new Map([[10001, stat(10001, 9000, "10")], [10002, stat(10002, 10001, "11")], [10003, stat(10003, 10002, "12")]]);denied = new Set();- mocks.readdir.mockImplementation(() => [...processes.keys()].map(String));+ listed = new Map();+ hiddenTasks = new Set();+ threads = new Map();+ threadChildren = new Map();+ goneThreads = new Set();+ onTaskList = () => {};+ const gone = () => Object.assign(new Error("gone"), { code: "ENOENT" });+ mocks.readdir.mockImplementation((path: string) => {+ if (path === "/proc") return [...processes.keys()].map(String);+ const pid = Number(/^\/proc\/(\d+)\/task$/.exec(path)?.[1]);+ onTaskList(pid);+ if (!processes.has(pid) || hiddenTasks.has(pid)) throw gone();+ return [String(pid), ...threads.get(pid) ?? []];+ });mocks.read.mockImplementation((path: string) => {+ const thread = /^\/proc\/(\d+)\/task\/(\d+)\/stat$/.exec(path);+ if (thread) {+ if (goneThreads.has(Number(thread[2]))) throw gone();+ const value = processes.get(Number(thread[1]));+ if (!value) throw gone();+ return value;+ }+ const children = /^\/proc\/(\d+)\/task\/(\d+)\/children$/.exec(path);+ if (children) {+ if (!processes.has(Number(children[1]))) throw gone();+ const ofThread = threadChildren.get(`${children[1]}/${children[2]}`);+ if (ofThread !== undefined) return ofThread;+ const instead = listed.get(Number(children[1]));+ if (instead !== undefined) return instead;+ return [...processes].filter(([, value]) => parentOf(value) === children[1]).map(([pid]) => `${pid} `).join("");+ }const pid = Number(/^\/proc\/(\d+)\/stat$/.exec(path)?.[1]);if (denied.has(pid)) throw Object.assign(new Error("denied"), { code: "EPERM" });const value = processes.get(pid);- if (!value) throw Object.assign(new Error("gone"), { code: "ENOENT" });+ if (!value) throw gone();return value;});signal = vi.fn((pid: number, value: number | string) => {@@ -50,7 +91,9 @@ beforeEach(() => {});afterEach(() => { vi.unstubAllGlobals(); vi.clearAllMocks(); });-describe("Linux CLI descendants", () => {+describe.each([["children files", true], ["a read of every process", false]])("Linux CLI descendants, found through %s", (_, childrenFiles) => {+ beforeEach(() => { mocks.exists.mockImplementation((path: string) => childrenFiles && /^\/proc\/self\/task\/\d+\/children$/.test(path)); });+it("retains detached descendant identities across protocol exit and reparenting", async () => {const child = root();captureCliTree(child);@@ -125,3 +168,81 @@ describe("Linux CLI descendants", () => {expect(signal).not.toHaveBeenCalledWith(10003, "SIGKILL");});});++describe("Linux CLI descendants through children files that may be incomplete", () => {+ beforeEach(() => { mocks.exists.mockReturnValue(true); });+ const detach = (child: ChildProcess) => {+ processes.delete(10001);+ for (const [pid, value] of processes) processes.set(pid, stat(pid, 1, value.slice(value.lastIndexOf(" ") + 1)));+ Object.assign(child, { exitCode: 0 });+ };+ const terminated = () => signal.mock.calls.filter(([pid, value]) => pid > 0 && value === "SIGTERM").map(([pid]) => pid);++ it("reads every process when a child listed beside a skipped one has been reaped", async () => {+ processes.set(10003, stat(10003, 10001, "12"));+ listed.set(10001, "10009 10002 ");+ const child = root();+ captureCliTree(child);+ detach(child);++ await expect(killCliTree(child, 0)).resolves.toBe(true);+ expect(terminated().sort()).toEqual([10002, 10003]);+ });++ it("reads every process when a live parent's thread list is hidden", async () => {+ hiddenTasks.add(10001);+ const child = root();+ captureCliTree(child);+ detach(child);++ await expect(killCliTree(child, 0)).resolves.toBe(true);+ expect(terminated()).toEqual([10003, 10002]);+ });++ it("keeps a descendant it found when the root exits before the walk is done", async () => {+ const child = root();+ onTaskList = (pid) => {+ if (pid !== 10002) return;+ processes.delete(10001);+ processes.set(10002, stat(10002, 1, "11"));+ hiddenTasks.add(10002);+ };+ captureCliTree(child);+ onTaskList = () => {};+ Object.assign(child, { exitCode: 0 });++ await expect(killCliTree(child, 0)).resolves.toBe(true);+ expect(terminated()).toEqual([10003, 10002]);+ });++ it("reads every process when a thread exits after handing its child to a thread already read", async () => {+ threads.set(10001, ["20001"]);+ threadChildren.set("10001/10001", "");+ threadChildren.set("10001/20001", "");+ goneThreads.add(20001);+ const child = root();+ captureCliTree(child);+ detach(child);++ await expect(killCliTree(child, 0)).resolves.toBe(true);+ expect(terminated()).toEqual([10003, 10002]);+ });++ it("never adopts the children of a process that took a parent's PID during the walk", async () => {+ processes.delete(10003);+ const child = root();+ onTaskList = (pid) => {+ if (pid !== 10002) return;+ processes.set(10002, stat(10002, 1, "99"));+ processes.set(10005, stat(10005, 10002, "15"));+ };+ captureCliTree(child);+ onTaskList = () => {};+ processes.delete(10001);+ Object.assign(child, { exitCode: 0 });++ await expect(killCliTree(child, 0)).resolves.toBe(true);+ expect(signal).not.toHaveBeenCalledWith(10005, expect.anything());+ expect(signal).not.toHaveBeenCalledWith(10002, expect.anything());+ });+});diff --git a/server/message-db.test.ts b/server/message-db.test.tsindex 45b85d7421..50e4ef5c60 100644--- a/server/message-db.test.ts+++ b/server/message-db.test.ts@@ -13,7 +13,9 @@ import { closeMessageDb,insertNotificationLog,lastRowAt,liveAppRows,+ latestMessageAts,latestPersonLineAts,+ optionCardsForTools,logNotification,openRescueMessages,latestSaidByBot,@@ -495,7 +497,7 @@ describe("messages_thread_at", () => {"AND (json_extract(m.json, '$.from.botId') IS NULL OR json_extract(m.json, '$.from.botId') = ?)" +") WHERE rn = 1 ORDER BY at DESC LIMIT ?",);- const ats = planOf("SELECT thread_id, MAX(at) AS at FROM messages WHERE thread_id IN (?, ?) GROUP BY thread_id");+ const ats = planOf("SELECT value AS thread_id, (SELECT MAX(at) FROM messages WHERE thread_id = value ) AS at FROM json_each(?)");expect(said).toContain("messages_thread_at");expect(ats).toContain("messages_thread_at");} finally {@@ -504,6 +506,38 @@ describe("messages_thread_at", () => {});});+describe("start-up reads on their indexes", () => {+ beforeEach(() => {+ closeMessageDb();+ rmSync(DATA_DIR, { recursive: true, force: true });+ mkdirSync(DATA_DIR, { recursive: true });+ });++ it("orders a thread by its newest person line or finished reply, at the turn's completion when it has one", () => {+ insertMessage("chat", msg("asked", "Plan the week.", { at: 10 }));+ insertMessage("chat", msg("working", "Looking.", { at: 20, role: "bot", turnId: "turn-1" }));+ insertMessage("chat", msg("done", "Here it is.", { at: 30, role: "bot", turnId: "turn-1", turnTerminal: true, turnCompletedAt: 45 }));+ insertMessage("chat", { ...msg("tool", "", { at: 60, role: "bot", turnId: "turn-1" }), kind: "activity" });+ insertMessage("peer", msg("handoff", "Take this over.", { at: 70, peerAsk: { botId: "teammate", name: "Teammate" } }));+ insertMessage("peer", msg("note", "No turn.", { at: 50, role: "bot" }));+ insertMessage("quiet", { ...msg("only-tool", "", { at: 80, role: "bot" }), kind: "activity" });+ expect(Object.fromEntries(latestMessageAts(["chat", "peer", "quiet", "empty"], true))).toEqual({ chat: 45, peer: 50 });+ expect(Object.fromEntries(latestMessageAts(["chat", "peer", "quiet", "empty"]))).toEqual({ chat: 60, peer: 70, quiet: 80 });+ });++ it("finds the option cards naming a tool, oldest first, among every other kind of row", () => {+ const card = (id: string, tool: string, at: number): Message => ({ ...msg(id, "", { at, role: "bot" }), kind: "options", card: { title: "Allow?", subtitle: "", options: ["Yes"], requestType: "question", tool } as Message["card"] });+ insertMessage("b", card("second", "your_computer", 20));+ insertMessage("a", card("first", "your_computer", 10));+ insertMessage("a", card("other", "ask_peer", 30));+ insertMessage("a", { ...msg("call", "", { at: 40, role: "bot" }), kind: "activity", tool: { name: "your_computer", ok: true } as Message["tool"] });+ insertMessage("a", msg("said", "your_computer", { at: 50 }));+ expect(optionCardsForTools(["your_computer"])).toEqual([{ threadId: "b", messageId: "second" }, { threadId: "a", messageId: "first" }]);+ expect(optionCardsForTools(["your_computer", "ask_peer"]).map((row) => row.messageId)).toEqual(["second", "first", "other"]);+ expect(optionCardsForTools([])).toEqual([]);+ });+});+describe("describeMissingFts5", () => {it("turns SQLite's bare module error into one that names the fix", () => {const described = describeMissingFts5(new Error("no such module: fts5"));diff --git a/server/message-db.ts b/server/message-db.tsindex 0c50f4d0e3..c507daafb4 100644--- a/server/message-db.ts+++ b/server/message-db.ts@@ -22,6 +22,10 @@ const DB_FILE = () => join(DATA_DIR, "messages.db");const WORK_KINDS = "kind IN ('activity', 'digest', 'options')";const CARD_KINDS = "kind IN ('secret', 'signin', 'connector')";const FAILED_CALL = "kind = 'activity' AND instr(json, '\"ok\":false') > 0";+/** The rows that order the thread list and the time each one counts at. SQLite uses messages_thread_order only for a+ * statement whose WHERE and MAX repeat these texts exactly. */+const ORDERING_ROW = "((role = 'user' AND json_extract(json, '$.peerAsk') IS NULL) OR (role = 'bot' AND kind = 'text' AND (json_extract(json, '$.turnTerminal') = 1 OR json_extract(json, '$.turnId') IS NULL)))";+const ORDERING_AT = "COALESCE(json_extract(json, '$.turnCompletedAt'), at)";let handle: DatabaseSync | null = null;let handlePath: string | null = null;@@ -60,6 +64,7 @@ function open(): DatabaseSync {-- open, including a database that already has messages.CREATE INDEX IF NOT EXISTS messages_thread_at ON messages(thread_id, at);-- Partial, so no other query's plan can move onto them: only a statement that repeats the WHERE may use one.+ CREATE INDEX IF NOT EXISTS messages_thread_order ON messages(thread_id, ${ORDERING_AT}) WHERE ${ORDERING_ROW};CREATE INDEX IF NOT EXISTS messages_work_at ON messages(kind, at) WHERE ${WORK_KINDS};CREATE INDEX IF NOT EXISTS messages_cards_at ON messages(kind, at) WHERE ${CARD_KINDS};CREATE INDEX IF NOT EXISTS messages_failed_at ON messages(at) WHERE ${FAILED_CALL};@@ -616,7 +621,7 @@ export function lastRowAt(threadId: string): number | undefined {export function latestMessageAts(threadIds: readonly string[], forOrdering = false): Map<string, number> {return forOrdering- ? newestAts(threadIds, "AND ((role = 'user' AND json_extract(json, '$.peerAsk') IS NULL) OR (role = 'bot' AND kind = 'text' AND (json_extract(json, '$.turnTerminal') = 1 OR json_extract(json, '$.turnId') IS NULL)))", "COALESCE(json_extract(json, '$.turnCompletedAt'), at)")+ ? newestAts(threadIds, `AND ${ORDERING_ROW}`, ORDERING_AT, "INDEXED BY messages_thread_order"): newestAts(threadIds, "");}@@ -625,19 +630,15 @@ export function latestPersonLineAts(threadIds: readonly string[]): Map<string, n"AND json_extract(json, '$.peerAsk') IS NULL AND json_extract(json, '$.relayed') IS NULL");}-function newestAts(threadIds: readonly string[], where: string, at = "at"): Map<string, number> {+/** One MAX per thread, so SQLite reads the newest entry of an index on (thread_id, value) instead of every row. */+function newestAts(threadIds: readonly string[], where: string, at = "at", index = ""): Map<string, number> {const ids = [...new Set(threadIds.filter((id) => id.length > 0))];const out = new Map<string, number>();- const chunk = 400;- for (let i = 0; i < ids.length; i += chunk) {- const slice = ids.slice(i, i + chunk);- const placeholders = slice.map(() => "?").join(", ");- const rows = db()- .prepare(`SELECT thread_id, MAX(${at}) AS at FROM messages WHERE thread_id IN (${placeholders}) ${where} GROUP BY thread_id`)- .all(...slice) as Array<{ thread_id: string; at: number }>;- for (const row of rows) {- if (typeof row.at === "number" && Number.isFinite(row.at)) out.set(row.thread_id, row.at);- }+ if (ids.length === 0) return out;+ const rows = prepared(`SELECT value AS thread_id, (SELECT MAX(${at}) FROM messages ${index} WHERE thread_id = value ${where}) AS at FROM json_each(?)`)+ .all(JSON.stringify(ids)) as Array<{ thread_id: string; at: number | null }>;+ for (const row of rows) {+ if (typeof row.at === "number" && Number.isFinite(row.at)) out.set(row.thread_id, row.at);}return out;}@@ -665,7 +666,7 @@ export function deleteThreads(threadIds: readonly string[], beforeCommit?: () =>export function optionCardsForTools(tools: readonly string[]): Array<{ threadId: string; messageId: string }> {if (tools.length === 0) return [];const rows = db()- .prepare(`SELECT thread_id, id FROM messages WHERE kind = 'options' AND json_extract(json, '$.card.tool') IN (${tools.map(() => "?").join(", ")}) ORDER BY rowid`)+ .prepare(`SELECT thread_id, id FROM messages INDEXED BY messages_work_at WHERE ${WORK_KINDS} AND kind = 'options' AND json_extract(json, '$.card.tool') IN (${tools.map(() => "?").join(", ")}) ORDER BY rowid`).all(...tools) as Array<{ thread_id: string; id: string }>;return rows.map((row) => ({ threadId: row.thread_id, messageId: row.id }));}diff --git a/server/procs.ts b/server/procs.tsindex 065602ee76..9034f797ab 100644--- a/server/procs.ts+++ b/server/procs.ts@@ -55,10 +55,10 @@ 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>>();-function linuxProcess(pid: number): LinuxProcess | null {+function linuxProcess(pid: number, file = `/proc/${pid}/stat`): LinuxProcess | null {let stat: string;try {- stat = readFileSync(`/proc/${pid}/stat`, "utf8");+ stat = readFileSync(file, "utf8");} catch (error) {if (["ENOENT", "ESRCH"].includes((error as NodeJS.ErrnoException).code ?? "")) return null;throw error;@@ -71,6 +71,34 @@ function linuxProcess(pid: number): LinuxProcess | null {return { pid, parent, start, state };}+/** /proc/<pid>/task/<tid>/children needs CONFIG_PROC_CHILDREN (CONFIG_CHECKPOINT_RESTORE before Linux 4.2); a kernel built without it, or gVisor, has no such file. */+function linuxChildrenFiles(): boolean {+ return existsSync(`/proc/self/task/${process.pid}/children`);+}++/** Every thread's children, or null when the list may miss one: Linux hides /proc/<pid>/task once the main thread has+ * exited while others run, and a thread that exits hands its children to a sibling thread, after which its own+ * children file reads empty. */+function linuxChildren(pid: number): number[] | null {+ let tasks: string[];+ try { tasks = readdirSync(`/proc/${pid}/task`); } catch { return null; }+ if (tasks.length === 0) return null;+ const children: number[] = [];+ for (const task of tasks) {+ let listed: string;+ try { listed = readFileSync(`/proc/${pid}/task/${task}/children`, "utf8"); } catch { return null; }+ let thread: LinuxProcess | null;+ try { thread = linuxProcess(pid, `/proc/${pid}/task/${task}/stat`); } catch { return null; }+ if (!thread || thread.state === "Z" || thread.state === "X") return null;+ for (const entry of listed.split(" ")) if (/^\d+$/.test(entry)) children.push(Number(entry));+ }+ return children;+}++function isLinuxProcess(pid: number, start: string): boolean {+ try { return linuxProcess(pid)?.start === start; } catch { return false; }+}+/** 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;@@ -79,6 +107,32 @@ export function captureCliTree(child: ChildProcess): void {tree = new Map();linuxTrees.set(child, tree);}+ if (!linuxChildrenFiles() || !addLinuxDescendants(tree)) addLinuxDescendantsFromEveryProcess(tree);+}++/** False when the walk may have missed a descendant; those it confirmed stay in the tree. A children file can skip a+ * live child while a sibling listed before it is reaped (docs.kernel.org/filesystems/proc.html,+ * "/proc/<pid>/task/<tid>/children"), and that sibling is then gone or reparented when its stat is read. */+function addLinuxDescendants(tree: Map<number, string>): boolean {+ const queue = [...tree].filter(([pid, start]) => isLinuxProcess(pid, start));+ for (let next = 0; next < queue.length; next += 1) {+ const [parent, parentStart] = queue[next];+ const children = linuxChildren(parent);+ if (!children || !isLinuxProcess(parent, parentStart)) return false;+ for (const pid of children) {+ if (pid === process.pid) continue;+ let current: LinuxProcess | null;+ try { current = linuxProcess(pid); } catch { return false; }+ if (!current || current.parent !== parent) return false;+ if (tree.get(pid) === current.start) continue;+ tree.set(pid, current.start);+ queue.push([pid, current.start]);+ }+ }+ return true;+}++function addLinuxDescendantsFromEveryProcess(tree: Map<number, string>): void {const snapshot = new Map<number, LinuxProcess>();let entries: string[];try { entries = readdirSync("/proc"); } catch { return; }