Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

fix(procs): stop process trees when their owner goes, and browsers when processes run out (#6181)

Milind Soniecae16bd85b0
diff --git a/electron/main.mjs b/electron/main.mjs
index 6fe3c43d1c..8403495a3b 100644
--- a/electron/main.mjs
+++ b/electron/main.mjs
@@ -290,7 +290,7 @@ const managedDesktopRelay = createManagedDesktopRelay();
const includedX = createDesktopIncludedX({ account: () => cloudAccount, server: () => serverProc, log: slog }), includedPages = createDesktopIncludedPages({ account: () => cloudAccount, server: () => serverProc, log: slog }), phoneLinkFact = createPhoneLinkFact({ retired: () => companionTunnelRetired(secureCredentialState?.read() ?? secureCredentials), server: () => (serverReady ? serverProc : null), log: slog }), phonePushAccess = createPhonePushAccessSync({ server: () => (serverReady ? serverProc : null), credentials: () => secureCredentialState?.read() ?? secureCredentials, controlPlane: () => resolveCompanionControlPlaneURL({ isPackaged: app.isPackaged, environment: process.env }), log: slog });
const cloudPower = createCloudPowerGate({ power: () => cloudAccount?.power() ?? null, wanted: () => Boolean(cloudSync?.running() || computerSharing?.lendingToCloud()) });
const utilityServerExits = new WeakMap(), systemProxy = createSystemProxyCache(); // A Mac app opened from Finder never gets the shell's proxy.
-const UTILITY_SERVER_STOP_TIMEOUT_MS = 6_500;
+const UTILITY_SERVER_STOP_TIMEOUT_MS = 9_500; // the server's shutdown deadline (8 s, server/graceful-shutdown.ts) and its 1 s log flush
const trustedApprovalMode = createTrustedApprovalModeCoordinator({ randomId: randomUUID, t: (...args) => nativeT(...args) });
const desktopMutationToken = randomBytes(32).toString("base64url");
const desktopLaunchId = randomUUID();
diff --git a/server/bot-box/env.test.ts b/server/bot-box/env.test.ts
index f862e646da..95d26c23ff 100644
--- a/server/bot-box/env.test.ts
+++ b/server/bot-box/env.test.ts
@@ -35,7 +35,7 @@ const SERVER_ONLY_OMB: ReadonlySet<string> = new Set([
"OMB_CREDENTIAL_STORE", "OMB_CUSTOM_DECIDER_KEY", "OMB_CUSTOM_IMAGE_KEY", "OMB_CUSTOM_LIVE_ENDPOINT", "OMB_CUSTOM_LIVE_MODEL", "OMB_DATA_DIR", "OMB_DECISION_RETENTION_DAYS",
"OMB_DEEPSEEK_API_KEY", "OMB_DESKTOP_LAUNCH_ID", "OMB_DESKTOP_PARENT", "OMB_DEVS_STATUS_MS",
"OMB_DEV_TRUST_LOCAL_BROWSER", "OMB_DISABLE_ANNOUNCEMENTS", "OMB_DISABLE_MODEL_CATALOG_FETCH", "OMB_DISABLE_MODEL_MANIFEST_FETCH", "OMB_DUCKDB_DIR", "OMB_DUCKDB_MAX_TEMP_SIZE",
- "OMB_DUCKDB_MEMORY_LIMIT", "OMB_ELEVENLABS_API", "OMB_ENTERPRISE_DIR", "OMB_ENVIRONMENT_LABEL", "OMB_EOF",
+ "OMB_DUCKDB_MEMORY_LIMIT", "OMB_ELEVENLABS_API", "OMB_ENGINE_TAG", "OMB_ENTERPRISE_DIR", "OMB_ENVIRONMENT_LABEL", "OMB_EOF",
"OMB_FIRST_REPLY_NOTICE_MS", "OMB_FISH_AUDIO_API", "OMB_FISH_AUDIO_API_KEY", "OMB_FISH_LIVE_AGENT_ID", "OMB_FISH_LIVE_URL", "OMB_FLEET_SOCKET", "OMB_GATE_",
"OMB_GEMINI_API_KEY", "OMB_GEMINI_IMAGE_KEY", "OMB_GEMINI_LIVE_MODEL", "OMB_GEMINI_LIVE_URL", "OMB_GEMINI_TTS_API", "OMB_GOAL_WAIT_MAX_MS",
"OMB_GREENFERENCE_API_KEY", "OMB_GROQ_API_KEY", "OMB_HELPER_INSTANCE", "OMB_HELPER_MODEL", "OMB_HOOKS", "OMB_HOOK_",
diff --git a/server/browser-engine.test.ts b/server/browser-engine.test.ts
index 2fe440061a..b633eee30a 100644
--- a/server/browser-engine.test.ts
+++ b/server/browser-engine.test.ts
@@ -361,7 +361,7 @@ describe("a browser daemon that will not close (#2603)", () => {
process.exit(0);
}, 200));
setInterval(() => {}, 1000);`;
- async function engine(options: { close: (pids: { daemon: number; browser: number; helper: number }) => number | Promise<number>; via?: "symlink" | "resolved" | "unreaped"; daemon?: string }) {
+ async function engine(options: { close: (pids: { daemon: number; browser: number; helper: number }) => number | Promise<number>; via?: "symlink" | "resolved" | "unreaped"; daemon?: string; listFails?: boolean }) {
const actual = await vi.importActual<typeof import("node:child_process")>("node:child_process");
const home = mkdtempSync(join(tmpdir(), "omb-browser-hung-"));
scratch.push(home);
@@ -394,6 +394,7 @@ describe("a browser daemon that will not close (#2603)", () => {
writeFileSync(browserDaemonFile(env, ".pid"), String(daemon));
const running = new Set(["work"]);
vi.mocked(spawn).mockImplementation(((binary: string, args: readonly string[], spawnOptions: object) => {
+ if (args[0] === "session" && options.listFails) throw Object.assign(new Error("spawn EAGAIN"), { code: "EAGAIN" });
if (args[0] === "session") return lifecycleChild(args, { sessions: [...running] });
if (args[0] !== "close") return actual.spawn(binary, args, spawnOptions);
const child = Object.assign(new EventEmitter(), { stdout: new EventEmitter(), kill: () => true });
@@ -414,6 +415,28 @@ describe("a browser daemon that will not close (#2603)", () => {
expect(existsSync(profile)).toBe(false);
});
+ it.skipIf(!posix)("stops the daemon by its pid file when agent-browser cannot even start to list its browsers (out of processes)", async () => {
+ let closes = 0;
+ const { actual, binaryPath, env, pids } = await engine({ close: () => { closes += 1; return 0; }, listFails: true, daemon: SAVING_DAEMON });
+ expect(await closeBrowserSession(binaryPath, env, 1_000)).toBe(true);
+ expect(closes).toBe(0);
+ // TERM to the daemon first, so it still saves its sign-ins from its browser.
+ expect(readFileSync(join(env.HOME, "browser.pid.saved"), "utf8")).toBe("saved");
+ for (const pid of Object.values(pids)) expect(gone(actual, pid), String(pid)).toBe(true);
+ });
+
+ it.skipIf(!posix)("never stops a stranger the pid file names when the list cannot be read", async () => {
+ const { actual, binaryPath, env } = await engine({ close: () => 1, listFails: true });
+ const stranger = actual.spawn("sleep", ["30"], { stdio: "ignore" });
+ try {
+ writeFileSync(browserDaemonFile(env, ".pid"), String(stranger.pid));
+ expect(await closeBrowserSession(binaryPath, env, 500)).toBe(false);
+ expect(alive(stranger.pid!)).toBe(true);
+ } finally {
+ stranger.kill("SIGKILL");
+ }
+ });
+
it.skipIf(!posix)("lets a daemon that will not close save its sign-ins from its browser before anything else is stopped", async () => {
const { actual, binaryPath, env, pids } = await engine({ close: () => 1, daemon: SAVING_DAEMON });
expect(await closeBrowserSession(binaryPath, env, 1_000)).toBe(true);
diff --git a/server/browser-engine.ts b/server/browser-engine.ts
index 59f717228f..d04688f605 100644
--- a/server/browser-engine.ts
+++ b/server/browser-engine.ts
@@ -142,15 +142,17 @@ async function closeOnce(binaryPath: string, env: NodeJS.ProcessEnv, session: st
const closeEnv = daemonControlEnv(env);
if (!closeEnv) return false;
const deadline = Date.now() + timeoutMs;
- // `close` to a stopped session starts a daemon only to stop it again and leaves its .config file behind.
- const running = await runningBrowserSessions(binaryPath, closeEnv, deadline);
- if (!running) return false;
- if (!running.includes(session)) return true;
const pidFile = browserDaemonFile(env, ".pid");
const daemonPid = () => { try { return readFileSync(pidFile, "utf8").trim(); } catch { return null; } };
+ // `close` to a stopped session starts a daemon only to stop it again and leaves its .config file behind.
+ const running = await runningBrowserSessions(binaryPath, closeEnv, deadline);
+ if (running && !running.includes(session)) return true;
const closing = daemonPid();
// Read first: once the daemon exits, its Chrome is re-parented and can no longer be found under it.
const tree = closing === null ? null : await browserProcessTree(binaryPath, Number(closing), session).catch(() => null);
+ // The list could not be read: on a box out of processes, every agent-browser command fails to start, so the daemon
+ // the pid file names (checked to be this session's own, from /proc where there is one) is stopped directly.
+ if (!running) return tree ? stopBrowserProcesses(tree) : false;
if ((await runBrowserCommand(binaryPath, closeEnv, ["close"], deadline)).ok) {
// Native close answers before the daemon exits, and Chrome's helper processes can outlive the answer.
while (Date.now() < deadline) {
diff --git a/server/browser-lifecycle-cleanup.test.ts b/server/browser-lifecycle-cleanup.test.ts
index 213aad66d3..a98b7416ca 100644
--- a/server/browser-lifecycle-cleanup.test.ts
+++ b/server/browser-lifecycle-cleanup.test.ts
@@ -289,6 +289,17 @@ describe("closing this data dir's browsers nothing uses", () => {
expect(closed()).toEqual([]);
});
+ it("still closes by pid file when agent-browser cannot list its browsers (it cannot start once the box is out of processes)", async () => {
+ home(["bot-a", "bot-b", "someone-elses"]);
+ vi.mocked(runningBrowserSessionNames).mockResolvedValue(null);
+ const { value, closeIdle, closed } = sweep({ live: ["bot-a"], idle: async () => true });
+ await value.sweep();
+ expect(closeIdle.mock.calls).toEqual([["bot-a"]]);
+ expect(closed()).toEqual(["/engine/agent-browser bot-b"]);
+ await value.closeAll(1_000);
+ expect(closed()).toEqual(["/engine/agent-browser bot-b", "/engine/agent-browser bot-a", "/engine/agent-browser bot-b"]);
+ });
+
it("asks the engine nothing while no daemon has a pid file, or there is no engine", async () => {
home([]);
writeFileSync(join(process.env.XDG_RUNTIME_DIR!, "agent-browser", "dashboard.pid"), "0");
diff --git a/server/browser-lifecycle-cleanup.ts b/server/browser-lifecycle-cleanup.ts
index 233e84aac4..b16f9874e6 100644
--- a/server/browser-lifecycle-cleanup.ts
+++ b/server/browser-lifecycle-cleanup.ts
@@ -384,10 +384,13 @@ export function browserIdleMs(cfg: { browserEngine?: { idleTimeoutMinutes?: numb
return (cfg.browserEngine?.idleTimeoutMinutes ?? (cloudHome ? CLOUD_HOME_BROWSER_IDLE_MINUTES : DEFAULT_BROWSER_IDLE_MINUTES)) * 60_000;
}
-/** agent-browser writes one `<session>.pid` per daemon, so with none there is nothing to ask about. */
-function daemonsMayRun(env: NodeJS.ProcessEnv): boolean {
- try { return readdirSync(dirname(browserDaemonFile({ ...env, AGENT_BROWSER_SESSION: "" }, ".pid"))).some((name) => name.endsWith(".pid") && name !== "dashboard.pid"); }
- catch { return false; }
+/** The sessions agent-browser has written a `<session>.pid` for (one per daemon, removed when it exits). */
+function daemonPidFiles(env: NodeJS.ProcessEnv): string[] {
+ try {
+ return readdirSync(dirname(browserDaemonFile({ ...env, AGENT_BROWSER_SESSION: "" }, ".pid")))
+ .filter((name) => name.endsWith(".pid") && name !== "dashboard.pid").map((name) => name.slice(0, -".pid".length))
+ .filter((session) => /^[A-Za-z0-9_.-]{1,96}$/.test(session));
+ } catch { return []; }
}
/** agent-browser detaches each daemon and its Chrome, so they outlive a crashed or killed server. A browser attached to the
@@ -433,10 +436,13 @@ export class BrowserSweep {
return this.#pass;
}
+ /** Null when no daemon runs. When agent-browser cannot list them (it cannot start once the box is out of processes),
+ * the sessions with a pid file: closing one then stops its daemon by that file (closeBrowserSession). */
async #owned(binaryPath: string, timeoutMs?: number): Promise<string[] | null> {
const env = browserRuntimeEnv({});
- if (!daemonsMayRun(env)) return null;
- return (await runningBrowserSessionNames(binaryPath, env, timeoutMs))?.filter((session) => this.#owns(session)) ?? null;
+ const files = daemonPidFiles(env);
+ if (!files.length) return null;
+ return ((await runningBrowserSessionNames(binaryPath, env, timeoutMs)) ?? files).filter((session) => this.#owns(session));
}
async #sweep(boot: boolean): Promise<void> {
diff --git a/server/checkpoints-perf.test.ts b/server/checkpoints-perf.test.ts
index e1265b5644..0ed7dfb888 100644
--- a/server/checkpoints-perf.test.ts
+++ b/server/checkpoints-perf.test.ts
@@ -44,6 +44,13 @@ vi.mock("node:child_process", async (importOriginal) => {
return { ...actual, execFile };
});
+// Checkpoints start git in a process group of their own; here every git run goes through the execFile above instead.
+vi.mock("./group-exec.ts", async (importOriginal) => {
+ const actual = await importOriginal<typeof import("./group-exec.ts")>();
+ const { execFile } = await import("node:child_process");
+ return { ...actual, execFileInGroup: (file: string, args: string[], options: object, callback: (...rest: unknown[]) => void) => execFile(file, args, options, callback) };
+});
+
const scratchDirs: string[] = [];
afterAll(async () => {
for (const dir of scratchDirs) await removeTempDir(dir);
diff --git a/server/checkpoints.ts b/server/checkpoints.ts
index 042542ca59..5ddb2442ad 100644
--- a/server/checkpoints.ts
+++ b/server/checkpoints.ts
@@ -15,6 +15,7 @@ import { homedir } from "node:os";
import { isAbsolute, join, parse, resolve } from "node:path";
import { DATA_DIR } from "./config.ts";
+import { execFileInGroup } from "./group-exec.ts";
export const CHECKPOINTS_DIR = join(DATA_DIR, "checkpoints");
@@ -198,7 +199,7 @@ function gitEnv(shadow: string, cwd: string): NodeJS.ProcessEnv {
return env;
}
-/** execFile reports its own timeout as a killed child; a `signal` cancellation arrives as an AbortError instead. */
+/** A timeout reports a killed child; a `signal` cancellation also stops the child, and is told apart by the signal. */
function gitFailure(command: string, err: Error & { killed?: boolean }, stderr: string, signal?: AbortSignal): Error {
if (err.killed && err.name !== "AbortError" && !signal?.aborted) {
return new GitTimeoutError(`git ${command} timed out after ${GIT_TIMEOUT_MS / 1000} s`);
@@ -209,10 +210,11 @@ function gitFailure(command: string, err: Error & { killed?: boolean }, stderr:
function runGit(args: string[], cwd: string, env: NodeJS.ProcessEnv, signal?: AbortSignal, input?: string): Promise<string> {
return new Promise((resolvePromise, rejectPromise) => {
signal?.throwIfAborted();
- const child = execFile(
+ // Its own group: a timeout or a stop also ends what git started (hooks are off, but pack and gc helpers run).
+ const child = execFileInGroup(
"git",
args,
- { cwd, env, signal, windowsHide: true, encoding: "utf8", timeout: GIT_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 },
+ { cwd, env, signal, encoding: "utf8", timeout: GIT_TIMEOUT_MS, maxBuffer: 16 * 1024 * 1024 },
(err, stdout, stderr) => {
if (err) rejectPromise(gitFailure(args[0]!, err, stderr, signal));
else resolvePromise(stdout);
diff --git a/server/container-computer.ts b/server/container-computer.ts
index 809bb68493..a17628a272 100644
--- a/server/container-computer.ts
+++ b/server/container-computer.ts
@@ -1,11 +1,10 @@
// Cua-backed Local VM: OMB owns only the sandbox boundary; desktop automation is Cua Driver's (`cua-driver mcp` in the container).
-import { execFile } from "node:child_process";
+import { execFileInGroupAsync } from "./group-exec.ts";
import { createHash, randomBytes } from "node:crypto";
import { lstatSync } from "node:fs";
import { chmod, mkdir, mkdtemp, rm, writeFile } from "node:fs/promises";
import { tmpdir } from "node:os";
import { join, resolve } from "node:path";
-import { promisify } from "node:util";
import { augmentedPath, resolveCliSpawn } from "./env-path.ts";
import { workspacePreparationDockerfile } from "./container-workspace.ts";
@@ -35,7 +34,8 @@ import {
} from "./container-isolation.ts";
import { SPAWNED_PROXIES } from "./proxy-paths.ts";
-const run = promisify(execFile);
+// Its own group: a timeout also ends the docker CLI plugins and credential helpers it started.
+const run = execFileInGroupAsync;
const SCREENSHOT_STATUS_TTL_MS = 10_000;
export type CommandRunner = (
diff --git a/server/drivers/acp/core.ts b/server/drivers/acp/core.ts
index c8aca341d8..17728519c4 100644
--- a/server/drivers/acp/core.ts
+++ b/server/drivers/acp/core.ts
@@ -19,7 +19,7 @@ import { DeviceAuthController, deviceAuthInstanceSurface, type DeviceSignIn } fr
import { AcpBrowserAuth, acpBrowserAuthInstanceSurface, type AcpBrowserSignInSpec } from "./browser-auth.ts";
import { deletePromptSplitReceipt, promptHalves, readPromptSplitReceipt, splitSessionPrompt, writePromptSplitReceipt } from "../prompt-split.ts";
import type { PromptSplitReceipt } from "../prompt-split.ts";
-import { describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts";
+import { describeSpawnFailure, execCli, killCliTree, sharedBoxScope, spawnCli } from "../../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../../engine-stop.ts";
import { runAcpOneShot } from "./background-text.ts";
import { acpCapabilities } from "./capabilities.ts";
import { acpNativeLogMessage } from "./tool-log.ts";
@@ -387,11 +387,14 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
const sessions = new Map<string, AcpSession>();
// Retain every closing Qwen child until its tree is gone: closing drops the pool entry, not its native writer lease.
const retiring = new Map<string, Set<ReturnType<typeof spawnCli>>>();
+ // Other agents get 5 s to leave on their own after EOF, as before, then their tree is stopped; no turn waits for them,
+ // dispose does.
+ const leaving = new Set<ReturnType<typeof spawnCli>>();
const retireChild = async (threadId: string, child: ReturnType<typeof spawnCli>): Promise<boolean> => {
let children = retiring.get(threadId);
if (!children) retiring.set(threadId, children = new Set());
children.add(child);
- const stopped = await killCliTree(child);
+ const stopped = await stopEngineTree(child, 0, 5_000);
if (stopped) {
children.delete(child);
if (!children.size && retiring.get(threadId) === children) retiring.delete(threadId);
@@ -419,17 +422,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
return;
}
host.draining = true;
- // EOF is no guaranteed exit: Qwen is tracked before another turn can resume its history.
- try {
- session.child.stdin.end();
- } catch {}
+ // EOF is no guaranteed exit: Qwen is tracked before another turn can resume its history.
if (support.restartOnMcpChange) void retireChild(threadId, session.child);
- else {
- const kill = setTimeout(() => {
- void killCliTree(session.child);
- }, 5_000);
- kill.unref?.();
- }
+ else void (leaving.add(session.child), stopEngineTree(session.child, 5_000, 5_000).then((stopped) => stopped && leaving.delete(session.child)));
};
// A session that ignores session/cancel goes on working, and EOF on stdin does not stop it either. Only a confirmed
// session/close or the end of its process stops it, and ending a shared process ends the other sessions' turns too.
@@ -1653,10 +1648,9 @@ export function createAcpDriver(support: AcpSupport): ProviderDriver<AcpConfig>
closeSession(threadId, "dispose");
settle(threadId, session, true, "cancelled");
}
- for (const [threadId, children] of retiring) {
- for (const child of children) void retireChild(threadId, child);
- }
listeners.clear();
+ // Engines lead sessions of their own, so nothing stops them once this server exits.
+ await stopEngineTrees([...disposingSessions.map(([, session]) => session.child), ...[...retiring.values()].flatMap((children) => [...children]), ...leaving]);
},
};
},
diff --git a/server/drivers/acp/deepseek.ts b/server/drivers/acp/deepseek.ts
index 4c9e663c5a..bfd0f81dfe 100644
--- a/server/drivers/acp/deepseek.ts
+++ b/server/drivers/acp/deepseek.ts
@@ -30,7 +30,7 @@ import { parse as parseYaml } from "yaml";
import type { ModelCatalog } from "../../contracts.ts";
import { harnessHome } from "../../env-path.ts";
-import { resolveCli, spawnCli } from "../../procs.ts";
+import { killCliTree, resolveCli, spawnCli } from "../../procs.ts";
import { createAcpDriver, type AcpSupport } from "./core.ts";
import { acpVariantOption } from "./config-options.ts";
@@ -214,16 +214,8 @@ export function fetchDeepSeekCatalog(
try {
child.stdin?.end();
} catch {}
- try {
- if (child.kill()) {
- const hardKill = setTimeout(() => {
- try {
- child.kill("SIGKILL");
- } catch {}
- }, 1_000);
- hardKill.unref?.();
- }
- } catch {}
+ // dsh's own children (its MCP servers) go too: spawnCli started it in a group of its own.
+ void killCliTree(child, 1_000);
if ("catalog" in outcome) resolve(outcome.catalog);
else reject(outcome.error);
};
diff --git a/server/drivers/acp/hermes.ts b/server/drivers/acp/hermes.ts
index 5fc13c0f23..5cd354cb32 100644
--- a/server/drivers/acp/hermes.ts
+++ b/server/drivers/acp/hermes.ts
@@ -8,7 +8,7 @@ import { parse as parseYaml } from "yaml";
import type { ModelCatalog } from "../../contracts.ts";
import { findCliCandidates, harnessHome, resolveCliSpawn, splitCliString, whichWin } from "../../env-path.ts";
-import { resolveCli, spawnCli } from "../../procs.ts";
+import { killCliTree, resolveCli, spawnCli } from "../../procs.ts";
import { decodeInjectId, hostApiKey, INJECT_SEP, localHost, mergeLocalInject } from "../local-inject.ts";
import { createAcpDriver, type AcpSupport } from "./core.ts";
@@ -288,31 +288,19 @@ export async function fetchHermesAcpModels(
}
let settled = false;
let timer: ReturnType<typeof setTimeout> | undefined;
- let hardKillTimer: ReturnType<typeof setTimeout> | undefined;
const done = (out: { id: string; label: string; custom: true }[]) => {
if (settled) return;
settled = true;
if (timer) clearTimeout(timer);
- try {
- if (child.kill()) {
- hardKillTimer = setTimeout(() => {
- try {
- child.kill("SIGKILL");
- } catch {}
- }, 1_000);
- hardKillTimer.unref?.();
- }
- } catch {}
+ // Hermes' own children (its MCP servers) go too: spawnCli started it in a group of its own.
+ void killCliTree(child, 1_000);
resolve(out);
};
timer = setTimeout(() => done([]), hermesAcpModelsTimeoutMs(env));
child.once("error", () => done([]));
// A child that already exited makes stdin emit EPIPE, and an unhandled stream 'error' crashes the server.
child.stdin?.on("error", () => done([]));
- child.once("close", () => {
- if (hardKillTimer) clearTimeout(hardKillTimer);
- done([]);
- });
+ child.once("close", () => done([]));
let buf = "";
let id = 0;
diff --git a/server/drivers/claude.test.ts b/server/drivers/claude.test.ts
index d18db8e8ea..0436f4aeff 100644
--- a/server/drivers/claude.test.ts
+++ b/server/drivers/claude.test.ts
@@ -3693,6 +3693,30 @@ describe("ClaudeDriver turns (fake CLI)", () => {
expect(close.contractChanged).toContain("mcpServers:-agents");
}, 20_000);
+ it.skipIf(process.platform === "win32")("stops a warm engine's whole tree before dispose returns: a server that exits leaves nothing running", async () => {
+ const marker = join(scratch, "background.pid");
+ const saved = { bash: process.env.FAKE_CLAUDE_RUN_BASH, calls: process.env.FAKE_CLAUDE_TOOL_CALLS };
+ // A tool call leaves a process behind in the engine's group, as a dev server or an MCP server does.
+ process.env.FAKE_CLAUDE_RUN_BASH = "1";
+ process.env.FAKE_CLAUDE_TOOL_CALLS = JSON.stringify([{ name: "Bash", input: { command: `"${process.execPath}" -e "setTimeout(() => {}, 60000)" >/dev/null 2>&1 & echo $! > "${marker}"` } }]);
+ const alive = (value: number) => { try { process.kill(value, 0); return true; } catch { return false; } };
+ let left = 0;
+ try {
+ await create();
+ await instance.adapter.sendTurn({ threadId: "t-dispose-tree", text: "one" });
+ await recorder.until((e) => e.type === "turn.completed");
+ left = Number(readFileSync(marker, "utf8").trim());
+ expect(alive(left)).toBe(true);
+ await instance.dispose();
+ expect(alive(left)).toBe(false);
+ } finally {
+ if (left && alive(left)) process.kill(left, "SIGKILL");
+ for (const [key, value] of [["FAKE_CLAUDE_RUN_BASH", saved.bash], ["FAKE_CLAUDE_TOOL_CALLS", saved.calls]] as const) {
+ if (value === undefined) delete process.env[key]; else process.env[key] = value;
+ }
+ }
+ }, 20_000);
+
it("closes an idle session after the configured window", async () => {
// Ten seconds is the floor; poll the native log for the close instead of sleeping past it.
process.env.OMB_CLAUDE_SESSION_IDLE_MIN_MS = "10000";
diff --git a/server/drivers/claude.ts b/server/drivers/claude.ts
index ecd034448e..57e6211578 100644
--- a/server/drivers/claude.ts
+++ b/server/drivers/claude.ts
@@ -10,7 +10,7 @@ import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts";
import { openStartupModelCatalog, unconfirmedModelCatalog, writeStartupModelCache } from "../startup-model-catalog.ts";
import { writeFileAtomicIfChanged } from "../atomic.ts";
import { augmentedPath, findCliCandidates } from "../env-path.ts"; import { BASH_MAX_TIMEOUT_MS } from "../system-prompt.ts";
-import { brokerSocketPath, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts";
+import { brokerSocketPath, describeSpawnFailure, execCli, killCliTree, spawnCli } from "../procs.ts"; import { stopEngineTree, stopEngineTrees } from "../engine-stop.ts";
import { cliToLaunch, cliVersionProbe } from "../cli-version-probe.ts";
import { claudeAuthStatus } from "./claude-auth-status.ts";
import { projectMcpServers } from "./claude-project-mcp.ts";
@@ -925,10 +925,7 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
try {
s.child.stdin.end();
} catch {}
- const kill = setTimeout(() => {
- stopSession(s);
- }, 5_000);
- kill.unref?.();
+ setTimeout(() => stopSession(s), 5_000).unref?.();
};
const armIdle = (threadId: string) => {
const s = sessions.get(threadId);
@@ -1235,7 +1232,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
}
return { turnId };
}
- if (live) closeSession(threadId, turn.sessionReset ? "context reset" : "spawn contract changed", turn.sessionReset ? undefined : spawnContractDiff(live.argsKey, argsKey));
+ // The old process and its tree end before the new one starts, so two never share the session.
+ if (live) { closeSession(threadId, turn.sessionReset ? "context reset" : "spawn contract changed", turn.sessionReset ? undefined : spawnContractDiff(live.argsKey, argsKey)); await stopEngineTree(live.child); }
// A new process gets the stable half only; the volatile half rides its first message, so a relaunch reuses the cached prefix.
const halves = promptHalves(turn);
const launchSystem = halves.stable ?? turn.system;
@@ -2078,6 +2076,8 @@ export const ClaudeDriver: ProviderDriver<ClaudeConfig> = {
for (const { stop } of active.values()) stop();
for (const threadId of Array.from(sessions.keys())) closeSession(threadId, "dispose");
listeners.clear();
+ // Engines lead sessions of their own, so nothing stops them once this server exits.
+ await stopEngineTrees(Array.from(sessions.values(), (s) => s.child));
}
},
};
diff --git a/server/engine-records.test.ts b/server/engine-records.test.ts
new file mode 100644
index 0000000000..8e0c157eae
--- /dev/null
+++ b/server/engine-records.test.ts
@@ -0,0 +1,224 @@
+import { execFileSync, spawn, type ChildProcess } from "node:child_process";
+import { existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { ENGINE_RUNS_DIR, ENGINE_TAG_ENV, engineRunTag, leftBehind, markEngineRunClean, resetEngineRecordsForTest, startEngineRecords, type Listed } from "./engine-records.ts";
+import { killCliTree, spawnCli } from "./procs.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+const posix = process.platform !== "win32";
+const folders: string[] = [];
+const started: ChildProcess[] = [];
+const strays: number[] = [];
+
+afterEach(async () => {
+ resetEngineRecordsForTest();
+ for (const child of started.splice(0)) { try { process.kill(-child.pid!, "SIGKILL"); } catch {} }
+ for (const pid of strays.splice(0)) { try { process.kill(pid, "SIGKILL"); } catch {} }
+ for (const folder of folders.splice(0)) await removeTempDir(folder);
+});
+
+function dataDir(): string {
+ const dir = mkdtempSync(join(tmpdir(), "omb-engine-records-"));
+ folders.push(dir);
+ return dir;
+}
+
+const startOf = (pid: number) => process.platform === "linux"
+ ? (() => { const stat = readFileSync(`/proc/${pid}/stat`, "utf8"); return stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19]; })()
+ : execFileSync("/bin/ps", ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", env: { ...process.env, LC_ALL: "C" } }).trim();
+const running = (pid: number) => {
+ try { return !execFileSync("ps", ["-o", "stat=", "-p", String(pid)], { encoding: "utf8" }).trim().startsWith("Z"); } catch { return false; }
+};
+/** The test process plays both servers, so the next one may not skip what started after it (startEngineRecords' cutoff). */
+const sweep = (dir: string) => startEngineRecords(dir, () => {}, null);
+
+/** An engine of an earlier server run: a session leader whose child outlives it in the background, as an MCP server does.
+ * Both are node: macOS shows no environment of its own system programs (/bin/sleep), as it does of an engine's. */
+async function leftover(dir: string, tag: string, server: { pid: number; start: string | null; boot?: string }, env: NodeJS.ProcessEnv = { [ENGINE_TAG_ENV]: tag }) {
+ const pids = join(dir, `pids-${tag}`);
+ const wait = `"${process.execPath}" -e "setTimeout(() => {}, 60000)"`;
+ const engine = spawn("/bin/sh", ["-c", `${wait} & echo $! > "$0"; exec ${wait}`, pids], { detached: true, stdio: "ignore", env: { PATH: process.env.PATH, ...env } });
+ started.push(engine);
+ await vi.waitFor(() => expect(existsSync(pids) && readFileSync(pids, "utf8").trim()).toBeTruthy());
+ const run = join(dir, ENGINE_RUNS_DIR, tag);
+ mkdirSync(run, { recursive: true });
+ writeFileSync(join(run, "server.json"), JSON.stringify(server));
+ writeFileSync(join(run, `${engine.pid}.json`), JSON.stringify({ pid: engine.pid, start: startOf(engine.pid!) }));
+ return { engine: engine.pid!, child: Number(readFileSync(pids, "utf8").trim()), run };
+}
+
+const DEAD_SERVER = { pid: 999_999_999, start: "gone" };
+
+describe.skipIf(!posix)("engines an earlier server of this data folder left", () => {
+ it("stops them and what they started, then forgets that run", async () => {
+ const dir = dataDir();
+ const left = await leftover(dir, "a".repeat(32), DEAD_SERVER);
+ const info = vi.spyOn(console, "info").mockImplementation(() => {});
+ await startEngineRecords(dir, console.info, null);
+ info.mockRestore();
+ expect(running(left.engine)).toBe(false);
+ expect(running(left.child)).toBe(false);
+ expect(existsSync(left.run)).toBe(false);
+ });
+
+ it("stops a recorded engine by its start time even when its environment cannot be read", async () => {
+ const dir = dataDir();
+ const left = await leftover(dir, "b".repeat(32), DEAD_SERVER, {});
+ await sweep(dir);
+ expect(running(left.engine)).toBe(false);
+ // Its child carries no tag: it is left alone.
+ expect(running(left.child)).toBe(true);
+ });
+
+ it("leaves alone a run whose server still runs, a process that only took a recorded number, and a run it cannot judge", async () => {
+ const dir = dataDir();
+ const server = spawn("sleep", ["60"], { detached: true, stdio: "ignore" });
+ started.push(server);
+ const live = await leftover(dir, "c".repeat(32), { pid: server.pid!, start: startOf(server.pid!) });
+ const stranger = spawn("sleep", ["60"], { detached: true, stdio: "ignore" });
+ started.push(stranger);
+ const run = join(dir, ENGINE_RUNS_DIR, "d".repeat(32));
+ mkdirSync(run, { recursive: true });
+ writeFileSync(join(run, "server.json"), JSON.stringify(DEAD_SERVER));
+ writeFileSync(join(run, `${stranger.pid}.json`), JSON.stringify({ pid: stranger.pid, start: "an earlier process" }));
+ const unjudged = join(dir, ENGINE_RUNS_DIR, "e".repeat(32));
+ mkdirSync(unjudged, { recursive: true });
+ await sweep(dir);
+ expect(running(live.engine)).toBe(true);
+ expect(running(live.child)).toBe(true);
+ expect(running(stranger.pid!)).toBe(true);
+ expect(existsSync(live.run)).toBe(true);
+ expect(existsSync(unjudged)).toBe(true);
+ });
+
+ it("stops nothing of a run from another boot (a pid and start tick mean nothing across a reboot) and forgets it", async () => {
+ const dir = dataDir();
+ const left = await leftover(dir, "f".repeat(32), { ...DEAD_SERVER, boot: "an-earlier-boot" });
+ await sweep(dir);
+ expect(running(left.engine)).toBe(true);
+ expect(running(left.child)).toBe(true);
+ expect(existsSync(left.run)).toBe(false);
+ });
+
+ it("tags and records what this server starts, and forgets a record once its whole tree is stopped", async () => {
+ const dir = dataDir();
+ await sweep(dir);
+ const tag = engineRunTag()!;
+ expect(tag).toMatch(/^[0-9a-f]{32}$/);
+ const child = spawnCli("/bin/sh", ["-c", `echo "$${ENGINE_TAG_ENV}"; exec sleep 60`], { stdio: ["pipe", "pipe", "pipe"] });
+ started.push(child);
+ let said = "";
+ child.stdout.on("data", (chunk) => { said += chunk; });
+ await vi.waitFor(() => expect(said.trim()).toBe(tag));
+ const records = join(dir, ENGINE_RUNS_DIR, tag);
+ expect(readdirSync(records)).toContain(`${child.pid}.json`);
+ expect(await killCliTree(child, 500)).toBe(true);
+ await vi.waitFor(() => expect(readdirSync(records)).not.toContain(`${child.pid}.json`));
+ });
+});
+
+/** An engine this server starts with spawnCli: a background child in its own group (as an MCP server), and a daemon that
+ * leaves for a session of its own (as an adb server, tmux or a dev server a bot starts on purpose). Both inherit the tag.
+ * The daemon detaches as daemons do: a starter puts it in a new session and exits, so it is no longer below the engine.
+ * (On Linux killCliTree stops every process still below the engine, whatever its session: sandbox helpers leave the
+ * engine's group, procs.ts captureCliTree.) */
+const ENGINE = `
+const { spawn } = require("node:child_process");
+const wait = ["-e", "setTimeout(() => {}, 60000)"];
+const child = spawn(process.execPath, wait, { stdio: "ignore" });
+const daemonize = "const d = require('node:child_process').spawn(process.execPath, " + JSON.stringify(wait) + ", { stdio: 'ignore', detached: true }); d.unref(); console.log(d.pid);";
+const starter = spawn(process.execPath, ["-e", daemonize], { stdio: ["ignore", "pipe", "ignore"] });
+let said = "";
+starter.stdout.on("data", (chunk) => { said += chunk; });
+starter.on("close", () => require("node:fs").writeFileSync(process.argv[2], JSON.stringify({ child: child.pid, daemon: Number(said.trim()) })));
+setInterval(() => {}, 60000);
+`;
+
+describe.skipIf(!posix)("a daemon an engine started in a session of its own", () => {
+ async function serverWithEngine(dir: string) {
+ await sweep(dir);
+ const tag = engineRunTag()!;
+ const script = join(dir, "engine.cjs");
+ const pids = join(dir, `engine-${tag}.json`);
+ writeFileSync(script, ENGINE);
+ const engine = spawnCli("/bin/sh", ["-c", `exec "${process.execPath}" "$0" "$1"`, script, pids], { stdio: ["pipe", "pipe", "pipe"] });
+ started.push(engine);
+ await vi.waitFor(() => expect(existsSync(pids)).toBe(true));
+ const { child, daemon } = JSON.parse(readFileSync(pids, "utf8")) as { child: number; daemon: number };
+ strays.push(child, daemon);
+ const run = join(dir, ENGINE_RUNS_DIR, tag);
+ return { tag, engine, child, daemon, run };
+ }
+ /** The server is gone: its process no longer runs (the test process keeps running, so its record says so). */
+ const serverDied = (run: string) => {
+ const server = JSON.parse(readFileSync(join(run, "server.json"), "utf8")) as Record<string, unknown>;
+ writeFileSync(join(run, "server.json"), JSON.stringify({ ...server, pid: 999_999_999 }));
+ resetEngineRecordsForTest();
+ };
+
+ it("survives a clean restart: the server stopped its engine itself and the next start sweeps nothing", async () => {
+ const dir = dataDir();
+ const first = await serverWithEngine(dir);
+ // As dispose does at shutdown: the engine's whole group, not what left it.
+ expect(await killCliTree(first.engine, 1_000)).toBe(true);
+ expect(running(first.child)).toBe(false);
+ expect(markEngineRunClean()).toBe(true);
+ serverDied(first.run);
+ await sweep(dir);
+ expect(running(first.daemon)).toBe(true);
+ expect(existsSync(first.run)).toBe(false);
+ });
+
+ it("is not marked clean while an engine of the run still runs", async () => {
+ const dir = dataDir();
+ const first = await serverWithEngine(dir);
+ expect(markEngineRunClean()).toBe(false);
+ expect(existsSync(join(first.run, "clean"))).toBe(false);
+ });
+
+ it("survives an unclean one, while the engine and the child still in its group are stopped", async () => {
+ const dir = dataDir();
+ const first = await serverWithEngine(dir);
+ serverDied(first.run);
+ await sweep(dir);
+ expect(running(first.engine.pid!)).toBe(false);
+ expect(running(first.child)).toBe(false);
+ expect(running(first.daemon)).toBe(true);
+ expect(existsSync(first.run)).toBe(false);
+ });
+});
+
+describe("what of an earlier run is still running", () => {
+ const tag = "a".repeat(32);
+ /** A start as the system shows it: the start tick on Linux, ps's lstart elsewhere. */
+ const at = (second: number) => process.platform === "linux" ? String(second) : new Date(2026, 10, 16, 10, 0, second).toString();
+ const env = (value = tag) => new Map([[ENGINE_TAG_ENV, value]]);
+ const row = (pid: number, extra: Partial<Listed> = {}): Listed => ({ pid, start: at(1), zombie: false, pgid: pid, sid: pid, env: env(), ...extra });
+ const self = { pid: 1_000, tag: "b".repeat(32), start: at(30) };
+ const leaders = new Map([[10, { start: at(1), at: null }]]);
+
+ it("takes a recorded leader and the tagged processes in its group or session, and nothing in a session of its own", () => {
+ const table = [
+ row(10),
+ row(11, { pgid: 10, sid: 10 }),
+ row(12, { pgid: 12, sid: 10 }),
+ row(13),
+ row(14, { pgid: 10, sid: 10, env: env("c".repeat(32)) }),
+ row(15, { pgid: 10, sid: 10, env: null }),
+ ];
+ expect(leftBehind(table, tag, leaders, self).sort()).toEqual([10, 11, 12]);
+ });
+
+ it("still takes a gone leader's group, but not the group of another process that now has that number", () => {
+ expect(leftBehind([row(11, { pgid: 10, sid: 10 })], tag, leaders, self)).toEqual([11]);
+ expect(leftBehind([row(10, { start: at(3), env: null }), row(11, { pgid: 10, sid: 10, start: at(4) })], tag, leaders, self)).toEqual([]);
+ });
+
+ it("never takes what started after this server, nor what carries this server's own tag", () => {
+ expect(leftBehind([row(10, { start: at(40) }), row(11, { pgid: 10, sid: 10, start: at(41) })], tag, new Map([[10, { start: at(40), at: null }]]), self)).toEqual([]);
+ expect(leftBehind([row(11, { pgid: 10, sid: 10, env: env(self.tag) })], tag, leaders, self)).toEqual([]);
+ });
+});
diff --git a/server/engine-records.ts b/server/engine-records.ts
new file mode 100644
index 0000000000..f9a3809b2a
--- /dev/null
+++ b/server/engine-records.ts
@@ -0,0 +1,285 @@
+// Engines and the other CLIs spawnCli starts lead POSIX sessions of their own (procs.ts), so nothing signals them when the
+// server dies: a server that is killed, or restarts in place in its container (server-launcher.ts), leaves them running.
+// Each server run writes down what it starts under <data>/engine-runs/<run tag>/. A server that shuts down cleanly has
+// stopped its engines itself and marks its run clean: nothing of it is ever swept. After an unclean death, the next server
+// of the same data folder stops what that run left, and only that: a recorded leader that is still the same process (same
+// boot, same start time), and processes carrying the run's random tag (spawnCli puts it in the environment, and children
+// inherit it) that are still in a recorded leader's process group or session. A daemon an engine started that left for a
+// session of its own (an adb server, tmux, pm2, a dev server, a browser) carries the tag too, and is never touched; nothing
+// is ever found by name. agent-browser daemons and their Chromes are left to the browser sweep, which closes them so they
+// save their sign-ins. Windows: off (engines there are not detached).
+import { randomBytes } from "node:crypto";
+import { execFile, execFileSync, type ChildProcess } from "node:child_process";
+import { existsSync, mkdirSync, readdirSync, readFileSync, readlinkSync, rmSync, writeFileSync } from "node:fs";
+import { join } from "node:path";
+
+export const ENGINE_TAG_ENV = "OMB_ENGINE_TAG";
+/** In the data folder; this machine's own, never backed up or moved. */
+export const ENGINE_RUNS_DIR = "engine-runs";
+const TAG = /^[0-9a-f]{32}$/;
+/** Written by a server whose shutdown finished: it stopped its own engines, and what they left on purpose stays. */
+const CLEAN = "clean";
+
+/** `start`: the kernel's start tick on Linux, ps's lstart elsewhere; `at`: when spawn returned (ms), where no start was read. */
+type Leader = { start: string | null; at: number | null };
+type ServerRecord = { pid?: unknown; start?: unknown; boot?: unknown; ns?: unknown };
+/** `sid` only where the system shows it (Linux); macOS's ps prints no session id. */
+export type Listed = { pid: number; start: string; zombie: boolean; pgid: number; sid: number | null; env: Map<string, string> | null };
+
+let run: { dir: string; tag: string } | null = null;
+
+/** The tag spawnCli adds to a child's environment, or null before startEngineRecords (tests, other processes). */
+export function engineRunTag(): string | null {
+ return run?.tag ?? null;
+}
+
+const PS = process.platform === "darwin" ? "/bin/ps" : "ps";
+
+function psText(args: string[]): Promise<string | null> {
+ return new Promise((done) => {
+ execFile(PS, args, { encoding: "utf8", timeout: 10_000, maxBuffer: 64 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" } }, (error, stdout) => done(error ? null : stdout));
+ });
+}
+
+function linuxStat(pid: number | string): string[] | null {
+ try {
+ const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
+ return stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ } catch { return null; }
+}
+
+function environment(entries: string[]): Map<string, string> {
+ return new Map(entries.flatMap((entry) => {
+ const at = entry.indexOf("=");
+ return at > 0 ? [[entry.slice(0, at), entry.slice(at + 1)] as const] : [];
+ }));
+}
+
+/** Every process with its start time, group, session and, where the system shows it to this user, its environment. */
+async function processes(): Promise<Listed[] | null> {
+ if (process.platform === "linux") {
+ let names: string[];
+ try { names = readdirSync("/proc"); } catch { return null; }
+ return names.filter((name) => /^\d+$/.test(name)).flatMap((name) => {
+ const fields = linuxStat(name);
+ if (!fields) return [];
+ let env: Map<string, string> | null = null;
+ try { env = environment(readFileSync(`/proc/${name}/environ`, "utf8").split("\0")); } catch {}
+ return [{ pid: Number(name), start: fields[19] ?? "", zombie: fields[0] === "Z" || fields[0] === "X", pgid: Number(fields[2]), sid: Number(fields[3]), env }];
+ });
+ }
+ // macOS: `ps -E` appends the environment, space separated, for this user's processes; lstart is five words.
+ const listing = await psText(["-A", "-E", "-ww", "-o", "pid=,stat=,pgid=,lstart=,command="]);
+ if (listing === null) return null;
+ return listing.split("\n").flatMap((line) => {
+ const [pid, stat, pgid, ...rest] = line.trim().split(/\s+/);
+ if (!pid || !/^\d+$/.test(pid) || !pgid || !/^\d+$/.test(pgid)) return [];
+ return [{ pid: Number(pid), start: rest.slice(0, 5).join(" "), zombie: stat?.startsWith("Z") === true, pgid: Number(pgid), sid: null, env: environment(rest.slice(5)) }];
+ });
+}
+
+function startOf(pid: number): string | null {
+ if (process.platform === "linux") return linuxStat(pid)?.[19] ?? null;
+ try { return execFileSync(PS, ["-o", "lstart=", "-p", String(pid)], { encoding: "utf8", timeout: 5_000, stdio: ["ignore", "pipe", "ignore"], env: { ...process.env, LC_ALL: "C" } }).trim() || null; }
+ catch { return null; }
+}
+
+/** Random per boot (Linux boot_id, macOS kern.bootsessionuuid): a pid and its start tick mean nothing across a reboot, as a
+ * restarted VM with its volume restored has. */
+function bootId(): string | null {
+ try {
+ if (process.platform === "linux") return readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim() || null;
+ if (process.platform === "darwin") return execFileSync("/usr/sbin/sysctl", ["-n", "kern.bootsessionuuid"], { encoding: "utf8", timeout: 5_000, stdio: ["ignore", "pipe", "ignore"] }).trim() || null;
+ } catch {}
+ return null;
+}
+
+/** A container's processes live in a pid namespace of their own; one container cannot see or signal another's. */
+function pidNamespace(): string | null {
+ if (process.platform !== "linux") return null;
+ try { return readlinkSync("/proc/self/ns/pid"); } catch { return null; }
+}
+
+function exists(pid: number): boolean {
+ try { process.kill(pid, 0); return true; } catch (error) { return (error as NodeJS.ErrnoException).code === "EPERM"; }
+}
+
+/** One process from two readings: the start tick (Linux) or lstart string, or on macOS within 2 s of when spawn returned. */
+function sameStart(leader: Leader, listed: string): boolean {
+ if (leader.start) return leader.start === listed;
+ if (leader.at === null) return false;
+ const seen = Date.parse(listed);
+ return Number.isFinite(seen) && Math.abs(seen - leader.at) < 2_000;
+}
+
+/** Started before this server: nothing this server starts can be an earlier run's. Unknown on either side counts as before. */
+function startedBefore(listed: string, self: string | null): boolean {
+ if (!self || !listed) return true;
+ if (process.platform === "linux") return Number(listed) < Number(self);
+ const [a, b] = [Date.parse(listed), Date.parse(self)];
+ return !Number.isFinite(a) || !Number.isFinite(b) || a < b;
+}
+
+export interface SweepSelf { pid: number; tag: string | null; start: string | null }
+
+/** What of an earlier, dead run `tag` with `leaders` is still running in `table`: see the note at the top. */
+export function leftBehind(table: readonly Listed[], tag: string, leaders: ReadonlyMap<number, Leader>, self: SweepSelf): number[] {
+ const byPid = new Map(table.map((entry) => [entry.pid, entry]));
+ // A group or session id is a recorded leader's only while that pid is not some other process: the system gives no new
+ // process a number that still names a group or session, so with the leader gone, the id is still its.
+ const leadersGroup = (id: number | null) => {
+ const leader = id === null ? undefined : leaders.get(id);
+ if (!leader) return false;
+ const holder = byPid.get(id!);
+ return !holder || sameStart(leader, holder.start);
+ };
+ return table.filter((entry) => {
+ if (entry.zombie || entry.pid === self.pid || entry.pid <= 1) return false;
+ const tagged = entry.env?.get(ENGINE_TAG_ENV);
+ if ((self.tag && tagged === self.tag) || entry.env?.get("AGENT_BROWSER_DAEMON") === "1" || !startedBefore(entry.start, self.start)) return false;
+ const leader = leaders.get(entry.pid);
+ if (leader && sameStart(leader, entry.start)) return true;
+ return tagged === tag && (leadersGroup(entry.pgid) || leadersGroup(entry.sid));
+ }).map((entry) => entry.pid);
+}
+
+/** Starts recording for this server and stops what earlier servers of `dataDir` left. Resolves once that sweep is done. It
+ * runs alongside the server's own start: what this server starts carries its own tag, and nothing that started after this
+ * server (`cutoff`, its own start unless a test plays both servers in one process) is ever taken for an earlier run's. */
+export async function startEngineRecords(dataDir: string, log: (line: string) => void = console.info, cutoff?: string | null): Promise<void> {
+ if (process.platform === "win32" || run) return;
+ const root = join(dataDir, ENGINE_RUNS_DIR);
+ const tag = randomBytes(16).toString("hex");
+ const dir = join(root, tag);
+ const start = startOf(process.pid);
+ const self = { pid: process.pid, tag, start: cutoff === undefined ? start : cutoff, boot: bootId(), ns: pidNamespace() };
+ try {
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
+ writeFileSync(join(dir, "server.json"), JSON.stringify({ pid: self.pid, start, boot: self.boot, ns: self.ns }), { mode: 0o600 });
+ } catch (error) {
+ log(`engine records: could not write ${dir} (${error instanceof Error ? error.message : String(error)}); engines left by this server are not stopped at the next start`);
+ return;
+ }
+ run = { dir, tag };
+ let earlier: string[];
+ try { earlier = readdirSync(root).filter((name) => name !== tag && TAG.test(name)); } catch { return; }
+ for (const other of earlier) await sweepRun(join(root, other), other, self, log).catch((error) => log(`engine records: ${other}: ${error instanceof Error ? error.message : String(error)}`));
+}
+
+/** Whether an earlier run's server still runs: "gone" from another boot or another container (none of its processes is
+ * here), "dead" on this boot, "unknown" when that cannot be told (its folder is then left alone). */
+function serverState(server: ServerRecord, self: { pid: number; boot: string | null; ns: string | null }): "alive" | "dead" | "gone" | "unknown" {
+ if (!Number.isInteger(server.pid) || (server.pid as number) <= 0) return "unknown";
+ if (typeof server.boot === "string" && self.boot && server.boot !== self.boot) return "gone";
+ // This server holds the data folder's lease, so that container's server has ended, and its processes with it.
+ if (typeof server.ns === "string" && self.ns && server.ns !== self.ns) return "gone";
+ const pid = server.pid as number;
+ if (pid === self.pid || !exists(pid)) return "dead";
+ if (typeof server.start !== "string" || !server.start) return "unknown";
+ const now = startOf(pid);
+ return now === null ? "unknown" : now === server.start ? "alive" : "dead";
+}
+
+async function sweepRun(dir: string, tag: string, self: SweepSelf & { boot: string | null; ns: string | null }, log: (line: string) => void): Promise<void> {
+ const forgetRun = () => rmSync(dir, { recursive: true, force: true });
+ if (existsSync(join(dir, CLEAN))) return forgetRun();
+ let server: ServerRecord;
+ try { server = JSON.parse(readFileSync(join(dir, "server.json"), "utf8")) as ServerRecord; } catch { return; }
+ const state = serverState(server, self);
+ if (state === "gone") return forgetRun();
+ // Never another live server's: the data folder's lease allows one, but its records are its own while it runs.
+ if (state !== "dead") return;
+ const leaders = new Map<number, Leader>();
+ try {
+ for (const name of readdirSync(dir)) {
+ if (!/^\d+\.json$/.test(name)) continue;
+ try {
+ const record = JSON.parse(readFileSync(join(dir, name), "utf8")) as { pid?: unknown; start?: unknown; at?: unknown };
+ if (!Number.isInteger(record.pid)) continue;
+ const start = typeof record.start === "string" && record.start ? record.start : null;
+ const at = typeof record.at === "number" && Number.isFinite(record.at) ? record.at : null;
+ if (start || at !== null) leaders.set(record.pid as number, { start, at });
+ } catch {}
+ }
+ } catch { return; }
+ const theirs = async (): Promise<number[] | null> => {
+ const table = await processes();
+ return table && leftBehind(table, tag, leaders, self);
+ };
+ let left = await theirs();
+ if (left === null) return;
+ if (left.length) {
+ log(`Stopping ${left.length} process${left.length === 1 ? "" : "es"} an earlier OpenMausBot server of this data folder started and left running.`);
+ signal(left, "SIGTERM");
+ for (const until = Date.now() + 1_500; Date.now() < until && left.length; ) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ left = await theirs() ?? left;
+ }
+ // Read again right before: only processes still that run's are killed.
+ signal(left, "SIGKILL");
+ for (const until = Date.now() + 1_000; Date.now() < until && left.length; ) {
+ await new Promise((resolve) => setTimeout(resolve, 100));
+ left = await theirs() ?? left;
+ }
+ }
+ if (left.length) log(`engine records: ${left.length} process(es) of an earlier server did not stop`);
+ else forgetRun();
+}
+
+function signal(pids: number[], value: NodeJS.Signals): void {
+ for (const pid of pids) {
+ try { process.kill(pid, value); } catch {}
+ }
+}
+
+/** Writes down a child spawnCli started in a session of its own; the record goes once the child and its group have gone. */
+export function recordEngine(child: ChildProcess, start: string | null): void {
+ const pid = child.pid;
+ if (!run || !pid) return;
+ const file = join(run.dir, `${pid}.json`);
+ try { writeFileSync(file, JSON.stringify({ pid, start, at: Date.now() }), { mode: 0o600 }); } catch { return; }
+ child.once("exit", () => {
+ // Its group can outlive it (an MCP server it started); then the record stays for the next start's sweep.
+ try { process.kill(-pid, 0); } catch (error) {
+ if ((error as NodeJS.ErrnoException).code === "ESRCH") forget(file);
+ }
+ });
+ stoppedFiles.set(child, file);
+}
+
+const stoppedFiles = new WeakMap<ChildProcess, string>();
+
+function forget(file: string): void {
+ try { rmSync(file, { force: true }); } catch {}
+}
+
+/** killCliTree confirmed the whole tree gone. */
+export function engineStopped(child: ChildProcess): void {
+ const file = stoppedFiles.get(child);
+ if (file) forget(file);
+}
+
+/** At a graceful exit: when nothing this run recorded still runs (its engines' groups are all gone), the run is marked
+ * clean and the next start sweeps nothing of it. What its engines started in sessions of their own stays running. */
+export function markEngineRunClean(): boolean {
+ if (!run) return false;
+ try {
+ for (const name of readdirSync(run.dir)) {
+ if (!/^\d+\.json$/.test(name)) continue;
+ try {
+ process.kill(-Number(name.slice(0, -".json".length)), 0);
+ return false;
+ } catch (error) {
+ if ((error as NodeJS.ErrnoException).code !== "ESRCH") return false;
+ }
+ forget(join(run.dir, name));
+ }
+ writeFileSync(join(run.dir, CLEAN), "", { mode: 0o600 });
+ return true;
+ } catch { return false; }
+}
+
+/** For tests: forget this process's run. */
+export function resetEngineRecordsForTest(): void {
+ run = null;
+}
diff --git a/server/engine-stop.ts b/server/engine-stop.ts
new file mode 100644
index 0000000000..7167950ca1
--- /dev/null
+++ b/server/engine-stop.ts
@@ -0,0 +1,21 @@
+import type { ChildProcess } from "node:child_process";
+import { killCliTree, waitForExit } from "./procs.ts";
+
+/** How long an engine gets to leave on its own after its input ends, and after SIGTERM, before it is killed. */
+export const ENGINE_EOF_GRACE_MS = 500;
+export const ENGINE_TERM_GRACE_MS = 1_500;
+
+/** Ends an engine as a close does (end of its input), then stops whatever of its tree is left: the MCP servers and
+ * tools it started lead no group of their own and stay behind otherwise. True once the whole tree is gone; at most
+ * eofGraceMs + termGraceMs + 1 s. */
+export async function stopEngineTree(child: ChildProcess, eofGraceMs = ENGINE_EOF_GRACE_MS, termGraceMs = ENGINE_TERM_GRACE_MS): Promise<boolean> {
+ try { child.stdin?.end(); } catch {}
+ if (eofGraceMs > 0) await waitForExit(child, eofGraceMs);
+ return killCliTree(child, termGraceMs).catch(() => false);
+}
+
+/** Stops every distinct tree at once; resolves when all are confirmed gone or past their deadlines. */
+export async function stopEngineTrees(children: Iterable<ChildProcess>, eofGraceMs?: number): Promise<boolean> {
+ const results = await Promise.all([...new Set(children)].map((child) => stopEngineTree(child, eofGraceMs)));
+ return results.every(Boolean);
+}
diff --git a/server/graceful-shutdown.ts b/server/graceful-shutdown.ts
index c47054f171..3c0c0fa264 100644
--- a/server/graceful-shutdown.ts
+++ b/server/graceful-shutdown.ts
@@ -4,11 +4,16 @@ export interface GracefulShutdownOptions {
timeoutMs?: number;
}
+/** Above the engines' kill path (engine-stop.ts: 0.5 s after end of input, 1.5 s after SIGTERM, 1 s after SIGKILL) and the
+ * browsers' close (4 s, then their process trees): engines lead sessions of their own and nothing else stops them. Below the
+ * desktop app's wait for the server (electron/main.mjs) and Docker's default 10 s stop timeout, with the 1 s log flush. */
+export const SHUTDOWN_DEADLINE_MS = 8_000;
+
/** A wedged provider cannot keep the child alive, and a normal stop clears browser capabilities so no turn bearer outlives it. */
export function createGracefulShutdown({
cleanup,
exit,
- timeoutMs = 6_000,
+ timeoutMs = SHUTDOWN_DEADLINE_MS,
}: GracefulShutdownOptions): () => void {
let started = false;
return () => {
diff --git a/server/group-exec.test.ts b/server/group-exec.test.ts
new file mode 100644
index 0000000000..48d2792d1f
--- /dev/null
+++ b/server/group-exec.test.ts
@@ -0,0 +1,60 @@
+import { spawn } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { execFileInGroup, execFileInGroupAsync, OWN_GROUP, stopGroup } from "./group-exec.ts";
+import { removeTempDir } from "./testing/cleanup.ts";
+
+const posix = process.platform !== "win32";
+const folders: string[] = [];
+afterEach(async () => { for (const folder of folders.splice(0)) await removeTempDir(folder); });
+
+const alive = (pid: number) => { try { process.kill(pid, 0); return true; } catch { return false; } };
+/** A shell that starts a background child (as git starts git-remote-https) and writes its pid. */
+function script(): { file: string; args: string[] } {
+ const dir = mkdtempSync(join(tmpdir(), "omb-group-exec-"));
+ folders.push(dir);
+ return { file: "/bin/sh", args: ["-c", `sleep 30 & echo $! > "$0"; wait`, join(dir, "child.pid")] };
+}
+const childOf = async (path: string) => {
+ await vi.waitFor(() => expect(existsSync(path) && readFileSync(path, "utf8").trim()).toBeTruthy());
+ return Number(readFileSync(path, "utf8").trim());
+};
+
+describe.skipIf(!posix)("a child in a group of its own", () => {
+ it("stops what it started too when its timeout passes, and reports the run killed", async () => {
+ const { file, args } = script();
+ const done = execFileInGroupAsync(file, args, { timeout: 300 });
+ const child = await childOf(args[2]!);
+ await expect(done).rejects.toMatchObject({ killed: true });
+ await vi.waitFor(() => expect(alive(child)).toBe(false));
+ });
+
+ it("stops the whole group when its signal aborts", async () => {
+ const { file, args } = script();
+ const abort = new AbortController();
+ const result = new Promise<{ killed?: boolean } | null>((resolve) => { execFileInGroup(file, args, { signal: abort.signal }, (error) => resolve(error)); });
+ const child = await childOf(args[2]!);
+ abort.abort();
+ expect(await result).toMatchObject({ killed: true });
+ await vi.waitFor(() => expect(alive(child)).toBe(false));
+ });
+
+ it("answers as execFile does when the command finishes", async () => {
+ await expect(execFileInGroupAsync("/bin/sh", ["-c", "echo out; echo err >&2"])).resolves.toEqual({ stdout: "out\n", stderr: "err\n" });
+ await expect(execFileInGroupAsync("/bin/sh", ["-c", "exit 3"])).rejects.toMatchObject({ code: 3 });
+ });
+
+ it("stopGroup ends a spawned child's group, and does nothing once the child has exited", async () => {
+ const { file, args } = script();
+ const shell = spawn(file, args, { stdio: "ignore", ...OWN_GROUP });
+ const child = await childOf(args[2]!);
+ const exited = new Promise((resolve) => shell.once("exit", resolve));
+ stopGroup(shell, 100);
+ await exited;
+ await vi.waitFor(() => expect(alive(child)).toBe(false));
+ expect(() => stopGroup(shell)).not.toThrow();
+ });
+});
diff --git a/server/group-exec.ts b/server/group-exec.ts
new file mode 100644
index 0000000000..4ad05c492d
--- /dev/null
+++ b/server/group-exec.ts
@@ -0,0 +1,97 @@
+// A child started in a process group of its own (POSIX), so a timeout or a stop reaches what it started too: git's remote
+// helpers, docker's CLI plugins, ffmpeg's workers, ssh's ProxyCommand. Signalling the child alone orphans them. Windows has
+// no process groups: taskkill /T walks the tree there.
+import { execFile, spawn, type ChildProcess, type SpawnOptions } from "node:child_process";
+
+/** Spawn options: a group of its own on POSIX; no console window on Windows. */
+export const OWN_GROUP = { windowsHide: true, detached: process.platform !== "win32" } as const;
+
+const KILL_GRACE_MS = 2_000;
+
+function groupSignal(pid: number, signal: NodeJS.Signals): boolean {
+ try {
+ process.kill(-pid, signal);
+ return true;
+ } catch { return false; }
+}
+
+/** SIGTERM to the child's group now and SIGKILL to what is left of it after `graceMs`. Only while the child has not been
+ * seen to exit, or within the grace: a group outlives its leader only while a member runs, and the system gives no new
+ * process that number while it does. */
+export function stopGroup(child: ChildProcess, graceMs = KILL_GRACE_MS): void {
+ const pid = child.pid;
+ if ((child.exitCode ?? null) !== null || (child.signalCode ?? null) !== null) return;
+ if (pid && process.platform === "win32") {
+ execFile("taskkill", ["/PID", String(pid), "/T", "/F"], { windowsHide: true }, () => {});
+ return;
+ }
+ // No pid (it never started) or no group of its own: the child alone.
+ if (!pid || !groupSignal(pid, "SIGTERM")) {
+ try { child.kill("SIGTERM"); } catch {}
+ return;
+ }
+ const hard = setTimeout(() => groupSignal(pid, "SIGKILL"), graceMs);
+ hard.unref?.();
+}
+
+type ExecError = Error & { code?: number | string | null; signal?: NodeJS.Signals | null; killed?: boolean; cmd?: string; stdout?: string; stderr?: string };
+type GroupExecOptions = Pick<SpawnOptions, "cwd" | "env" | "uid" | "gid"> & { timeout?: number; maxBuffer?: number; signal?: AbortSignal; encoding?: "utf8"; input?: never };
+
+/** execFile in a group of its own (execFile itself drops `detached`): `timeout` and `signal` stop the whole group (SIGTERM,
+ * then SIGKILL), and its errors are shaped as execFile's: `code` is the exit code (or the spawn error's), `killed` is true
+ * for a run it stopped, and output past `maxBuffer` (1 MiB) stops it. Output is UTF-8 text. */
+export function execFileInGroup(
+ file: string,
+ args: readonly string[],
+ options: GroupExecOptions,
+ callback: (error: ExecError | null, stdout: string, stderr: string) => void,
+): ChildProcess {
+ const { timeout, signal, maxBuffer = 1024 * 1024, encoding: _encoding, ...rest } = options;
+ const cmd = [file, ...args].join(" ");
+ let stdout = "", stderr = "", stopped = false, overflow = false, finished = false;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const stop = () => {
+ if (stopped) return;
+ stopped = true;
+ stopGroup(child);
+ };
+ const finish = (error: ExecError | null) => {
+ if (finished) return;
+ finished = true;
+ clearTimeout(timer);
+ signal?.removeEventListener("abort", stop);
+ callback(error ? Object.assign(error, { cmd, stdout, stderr, ...(stopped ? { killed: true } : {}) }) : null, stdout, stderr);
+ };
+ const child = spawn(file, args, { ...rest, ...OWN_GROUP, stdio: ["pipe", "pipe", "pipe"] });
+ const take = (which: "stdout" | "stderr") => (chunk: string) => {
+ if (which === "stdout") stdout += chunk; else stderr += chunk;
+ if (!overflow && stdout.length + stderr.length > maxBuffer) { overflow = true; stop(); }
+ };
+ child.stdout!.setEncoding("utf8").on("data", take("stdout"));
+ child.stderr!.setEncoding("utf8").on("data", take("stderr"));
+ // A child that exits before reading its input must not surface as an unhandled EPIPE.
+ child.stdin!.on("error", () => {});
+ child.once("error", (error) => finish(error));
+ child.once("close", (code, exitSignal) => {
+ if (overflow) return finish(Object.assign(new RangeError(`${file} wrote more than ${maxBuffer} bytes`), { code: "ERR_CHILD_PROCESS_STDIO_MAXBUFFER" }));
+ if (code === 0 && !exitSignal) return finish(null);
+ finish(Object.assign(new Error(`Command failed: ${cmd}\n${stderr}`), { code, signal: exitSignal }));
+ });
+ if (timeout) {
+ timer = setTimeout(stop, timeout);
+ timer.unref?.();
+ }
+ if (signal?.aborted) stop();
+ else signal?.addEventListener("abort", stop, { once: true });
+ return child;
+}
+
+/** execFileInGroup as a promise, shaped as `promisify(execFile)`'s: rejects with `code`, `killed`, `stdout` and `stderr`. */
+export function execFileInGroupAsync(file: string, args: readonly string[], options: GroupExecOptions = {}): Promise<{ stdout: string; stderr: string }> {
+ return new Promise((resolve, reject) => {
+ execFileInGroup(file, args, options, (error, stdout, stderr) => {
+ if (error) reject(Object.assign(error, { stdout, stderr }));
+ else resolve({ stdout, stderr });
+ });
+ });
+}
diff --git a/server/index.ts b/server/index.ts
index 58e47e39b9..d74c019e6a 100644
--- a/server/index.ts
+++ b/server/index.ts
@@ -524,7 +524,7 @@ import {
isTurnEventQuarantined, TURN_ENDED_REFUSAL,
} from "./turn-dispatch-guard.ts";
import { createGracefulShutdown } from "./graceful-shutdown.ts";
-import { acquireDataDirLeaseForProcess } from "./data-dir-lease.ts";
+import { acquireDataDirLeaseForProcess } from "./data-dir-lease.ts"; import { markEngineRunClean, startEngineRecords } from "./engine-records.ts";
import { createWorkspaceAccess, describeEdition, editionForSettings, editionStatus, entitled, hostedWorkspaceConfiguration, hostedWorkspaceConfigured, licenseWarning, sharedWorkspaceFullAccessConfigured, loadEnterpriseLayer, workspaceMembership, type WorkspaceAccess } from "./enterprise.ts";
import { environmentDescriptor, loadEnvironmentId, OWNER_LENDING, serverVersion } from "./environment.ts"; import { dataFormatAtStart } from "./data-format.ts";
import { WorkspaceBackupMaintenance } from "./workspace-backup-maintenance.ts";
@@ -663,7 +663,7 @@ const STATIC_DIR = process.env.OMB_STATIC_DIR || null;
dataFormatAtStart("check", DATA_DIR, serverVersion()); ensureDirs();
// Acquire before any durable identity, sessions, config or Store state is loaded.
-const dataDirLease = acquireDataDirLeaseForProcess(DATA_DIR);
+const dataDirLease = acquireDataDirLeaseForProcess(DATA_DIR); void startEngineRecords(DATA_DIR); // stops what an earlier server left
let dataDirLeaseReleaseAttempted = false;
function releaseDataDirLeaseAtExit(): void {
if (dataDirLeaseReleaseAttempted) return;
@@ -15422,7 +15422,7 @@ const gracefulShutdown = createGracefulShutdown({
}
flushLaterSaves(); closeMessageDb();
mcpOAuth.dispose();
- releaseDataDirLeaseAtExit();
+ markEngineRunClean(); releaseDataDirLeaseAtExit(); // before the lease: the next server must not sweep this run
process.exit(restartRequested && exitCode === 0 ? RESTART_EXIT_CODE : exitCode);
};
// Streamed text and lines queued after the cleanup flush reach disk before exit; the deadline already elapsed, so the wait is short.
diff --git a/server/lent-clone.ts b/server/lent-clone.ts
index 816e42a970..34782aa22c 100644
--- a/server/lent-clone.ts
+++ b/server/lent-clone.ts
@@ -9,6 +9,7 @@ import { homedir } from "node:os";
import { join } from "node:path";
import { z } from "zod";
import { writeFileAtomic } from "./atomic.ts";
+import { OWN_GROUP, stopGroup } from "./group-exec.ts";
import { botBox } from "./bot-box/box.ts";
export const lentGit = z.object({
@@ -43,10 +44,11 @@ export function runGit(args: string[], timeoutMs = CLONE_MS): Promise<void> {
return new Promise((resolve, reject) => {
// The address is always https://github.com/<owner>/<name>.git (lentGit's repo), never one a computer sent.
const run = gitInvocation(args);
- const child = spawn("git", run.args, { stdio: ["ignore", "ignore", "pipe"], env: run.env });
+ // Its own group, so a timeout also ends git-remote-https and any credential helper it started.
+ const child = spawn("git", run.args, { stdio: ["ignore", "ignore", "pipe"], env: run.env, ...OWN_GROUP });
let error = "";
child.stderr.on("data", (chunk) => { if (error.length < 4_000) error += chunk; });
- const timer = setTimeout(() => child.kill("SIGKILL"), timeoutMs);
+ const timer = setTimeout(() => stopGroup(child, 0), timeoutMs);
child.once("error", (cause) => { clearTimeout(timer); reject(cause); });
child.once("close", (code) => { clearTimeout(timer); if (code === 0) resolve(); else reject(new Error(error.trim().split("\n").at(-1) || `git exited ${code}`)); });
});
diff --git a/server/mcp-gate-lifetime.test.ts b/server/mcp-gate-lifetime.test.ts
new file mode 100644
index 0000000000..adfd2f6807
--- /dev/null
+++ b/server/mcp-gate-lifetime.test.ts
@@ -0,0 +1,91 @@
+import { spawn, type ChildProcessWithoutNullStreams } from "node:child_process";
+import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+import { afterEach, beforeEach, describe, expect, it } from "vitest";
+
+const GATE = join(dirname(fileURLToPath(import.meta.url)), "mcp-gate.ts");
+
+/** A server behind a launcher, as `npx <package>` runs one: the launcher passes no signal on, and the server ignores the
+ * end of its input. */
+const SERVER = `
+const { writeFileSync } = require("node:fs");
+writeFileSync(process.env.PID_FILE, String(process.pid));
+process.stdin.resume();
+if (process.env.IGNORES_TERM === "1") process.on("SIGTERM", () => {});
+setInterval(() => {}, 60_000);
+`;
+
+const alive = (pid: number): boolean => {
+ try { process.kill(pid, 0); return true; } catch { return false; }
+};
+
+async function until(check: () => boolean, ms: number): Promise<boolean> {
+ const deadline = Date.now() + ms;
+ while (Date.now() < deadline) {
+ if (check()) return true;
+ await new Promise((resolve) => setTimeout(resolve, 50));
+ }
+ return check();
+}
+
+describe.skipIf(process.platform === "win32")("mcp-gate and the processes it started", () => {
+ let scratch: string;
+ let gate: ChildProcessWithoutNullStreams | undefined;
+ let serverPid = 0;
+
+ const start = async (env: Record<string, string> = {}) => {
+ const server = join(scratch, "server.cjs");
+ const pidFile = join(scratch, "server.pid");
+ writeFileSync(server, SERVER);
+ gate = spawn(process.execPath, ["--experimental-strip-types", "--no-warnings", GATE], {
+ stdio: ["pipe", "pipe", "pipe"],
+ env: {
+ ...process.env,
+ OMB_GATE_NAME: "notes",
+ OMB_GATE_SPILL_DIR: join(scratch, "spill"),
+ OMB_GATE_UPSTREAM: JSON.stringify({
+ command: "/bin/sh",
+ args: ["-c", `"${process.execPath}" "${server}"; exit 0`],
+ env: { PID_FILE: pidFile, ...env },
+ }),
+ },
+ }) as ChildProcessWithoutNullStreams;
+ expect(await until(() => existsSync(pidFile), 20_000)).toBe(true);
+ serverPid = Number(readFileSync(pidFile, "utf8"));
+ expect(alive(serverPid)).toBe(true);
+ };
+ const exited = () => gate!.exitCode !== null || gate!.signalCode !== null;
+
+ beforeEach(() => { scratch = mkdtempSync(join(tmpdir(), "omb-gate-life-")); });
+ afterEach(() => {
+ gate?.kill("SIGKILL");
+ if (serverPid) try { process.kill(serverPid, "SIGKILL"); } catch {}
+ serverPid = 0;
+ rmSync(scratch, { recursive: true, force: true });
+ });
+
+ it("stops the server behind a launcher within the deadline after its input ends", async () => {
+ await start();
+ gate!.stdin.end();
+ await new Promise((resolve) => setTimeout(resolve, 2_000));
+ expect(exited()).toBe(false);
+ expect(await until(exited, 8_000)).toBe(true);
+ expect(await until(() => !alive(serverPid), 2_000)).toBe(true);
+ }, 40_000);
+
+ it("stops the whole tree on SIGTERM, not only the launcher", async () => {
+ await start();
+ gate!.kill("SIGTERM");
+ expect(await until(exited, 5_000)).toBe(true);
+ expect(await until(() => !alive(serverPid), 2_000)).toBe(true);
+ }, 40_000);
+
+ it("kills a server that ignores SIGTERM", async () => {
+ await start({ IGNORES_TERM: "1" });
+ gate!.kill("SIGTERM");
+ expect(await until(exited, 6_000)).toBe(true);
+ expect(await until(() => !alive(serverPid), 2_000)).toBe(true);
+ }, 40_000);
+});
diff --git a/server/mcp-gate.ts b/server/mcp-gate.ts
index 282e2473e9..67aec2ac80 100644
--- a/server/mcp-gate.ts
+++ b/server/mcp-gate.ts
@@ -12,6 +12,7 @@ import { directoryCallTarget, isDirectoryTool } from "./mcp-directory.ts";
import { QUERY_TOOL, QUERY_TOOL_NAME, ResultStore, answerQuery, describeShape, exampleQuery } from "./mcp-shape.ts";
import { fitToolList } from "./mcp-tool-schema.ts";
import { DEFAULT_RESULT_BUDGET, type HeldResult, trimResultText, trimStructured } from "./mcp-trim.ts";
+import { descendantsOf, signalTree, stopTree, type TreeProcess } from "./proc-descendants.ts";
import { killCliTree } from "./procs.ts";
import { toolSchemaProfileFromEnv } from "./tool-schema-profile.ts";
import { capToolListResult, toolLimitFromEnv } from "./tool-count-limit.ts";
@@ -234,22 +235,41 @@ const child = spawn(resolved.command, resolved.args, {
...(process.platform === "win32" ? { windowsHide: true } : {}),
});
-// The real server must not outlive a killed gate, and on Windows only taskkill /T reaps a tree.
-let reaping = false;
-const reapChild = () => {
- if (reaping) return;
- reaping = true;
- void killCliTree(child);
+// The real server must not outlive its gate: a launcher (npx, a shell) does not pass a signal on to what it started, so
+// each process below the gate is signalled itself. On Windows only taskkill /T reaps a tree.
+const END_OF_INPUT_GRACE_MS = 5_000;
+const TREE_STOP_GRACE_MS = 1_500;
+const tree: TreeProcess[] = [];
+const captureTree = () => {
+ if (!child.pid) return;
+ const seen = new Set(tree.map((one) => `${one.pid}:${one.start}`));
+ for (const one of descendantsOf(child.pid)) {
+ if (!seen.has(`${one.pid}:${one.start}`)) tree.push(one);
+ }
};
-process.on("SIGTERM", () => {
- reapChild();
- process.exit(0);
-});
-process.on("SIGINT", () => {
- reapChild();
- process.exit(0);
+let stopping: Promise<void> | undefined;
+const stopUpstream = (): Promise<void> => stopping ??= (async () => {
+ captureTree();
+ if (process.platform === "win32") {
+ await killCliTree(child, TREE_STOP_GRACE_MS);
+ return;
+ }
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM");
+ await stopTree(tree, TREE_STOP_GRACE_MS);
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGKILL");
+})();
+const leave = (code: number) => void stopUpstream().finally(() => process.exit(code));
+process.on("SIGTERM", () => leave(0));
+process.on("SIGINT", () => leave(0));
+process.on("exit", () => {
+ if (stopping) return;
+ if (process.platform === "win32") void killCliTree(child);
+ else {
+ captureTree();
+ if (child.exitCode === null && child.signalCode === null) child.kill("SIGTERM");
+ signalTree(tree, "SIGTERM");
+ }
});
-process.on("exit", reapChild);
child.on("error", (error) => {
process.stderr.write(`mcp-gate(${NAME}): could not start ${resolved.command}: ${String(error)}\n`);
@@ -327,7 +347,11 @@ createInterface({ input: process.stdin }).on("line", (line) => {
}
child.stdin.write(`${line}\n`);
});
-process.stdin.on("end", () => child.stdin.end());
+process.stdin.on("end", () => {
+ child.stdin.end();
+ captureTree();
+ setTimeout(() => leave(0), END_OF_INPUT_GRACE_MS);
+});
createInterface({ input: child.stdout }).on("line", (line) => {
if (!line.trim()) return;
@@ -399,4 +423,4 @@ createInterface({ input: child.stdout }).on("line", (line) => {
process.stdout.write(`${JSON.stringify(message)}\n`);
});
-child.on("exit", (code, signal) => process.exit(code ?? (signal ? 1 : 0)));
+child.on("exit", (code, signal) => leave(code ?? (signal ? 1 : 0)));
diff --git a/server/move-freeze.ts b/server/move-freeze.ts
index 5f722194fb..7b8d7b0035 100644
--- a/server/move-freeze.ts
+++ b/server/move-freeze.ts
@@ -37,7 +37,7 @@ const READS = new Set(["GET", "HEAD", "OPTIONS"]);
/** What a frozen copy keeps once its workspace is deleted: the marker, this server's identity, Files, downloaded tools
* and caches, and its own runtime files. Everything else, credentials included, is the person's workspace. */
const DEVICE_STATE = new Set(["moved.json", "environment-id", "sync", "tools", "cache", ".cache", "tmp", ".tmp", "dist-native", "tunnel-runtime",
- ".openmausbot-server-child", "openmausbot-server.lease"]);
+ ".openmausbot-server-child", "openmausbot-server.lease", "engine-runs"]);
const kept = (name: string) => DEVICE_STATE.has(name) || name.startsWith("openmausbot-server.lease.");
export type MoveFreeze = ReturnType<typeof createMoveFreeze>;
diff --git a/server/proc-descendants.ts b/server/proc-descendants.ts
new file mode 100644
index 0000000000..3f51bdfc92
--- /dev/null
+++ b/server/proc-descendants.ts
@@ -0,0 +1,87 @@
+import { execFileSync } from "node:child_process";
+import { readdirSync, readFileSync } from "node:fs";
+
+/** `start` tells a process from a later one that reuses its pid: the kernel's start tick on Linux, ps's lstart elsewhere. */
+export interface TreeProcess {
+ pid: number;
+ start: string;
+}
+
+type Row = TreeProcess & { parent: number; gone: boolean };
+
+function linuxRows(): Row[] {
+ const rows: Row[] = [];
+ let entries: string[];
+ try { entries = readdirSync("/proc"); } catch { return rows; }
+ for (const entry of entries) {
+ if (!/^\d+$/.test(entry)) continue;
+ try {
+ const stat = readFileSync(`/proc/${entry}/stat`, "utf8");
+ const fields = stat.slice(stat.lastIndexOf(")") + 2).split(" ");
+ rows.push({ pid: Number(entry), parent: Number(fields[1]), start: fields[19] ?? "", gone: fields[0] === "Z" || fields[0] === "X" });
+ } catch {}
+ }
+ return rows;
+}
+
+/** macOS keeps ps at /bin/ps, and the C locale keeps lstart in one fixed form. */
+function psRows(): Row[] {
+ let listing: string;
+ try {
+ listing = execFileSync(process.platform === "darwin" ? "/bin/ps" : "ps", ["-A", "-o", "pid=,ppid=,stat=,lstart="],
+ { encoding: "utf8", timeout: 2_000, maxBuffer: 8 * 1024 * 1024, env: { ...process.env, LC_ALL: "C" }, stdio: ["ignore", "pipe", "ignore"] });
+ } catch { return []; }
+ const rows: Row[] = [];
+ for (const line of listing.split("\n")) {
+ const match = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.+?)\s*$/.exec(line);
+ if (match) rows.push({ pid: Number(match[1]), parent: Number(match[2]), start: match[4]!, gone: match[3]!.startsWith("Z") });
+ }
+ return rows;
+}
+
+function rows(platform: NodeJS.Platform): Row[] {
+ return platform === "linux" ? linuxRows() : platform === "win32" ? [] : psRows();
+}
+
+/** The live processes below `root`, parents before their children. Empty on Windows, where taskkill /T walks the tree. */
+export function descendantsOf(root: number, platform: NodeJS.Platform = process.platform): TreeProcess[] {
+ const all = rows(platform);
+ const found: TreeProcess[] = [];
+ const parents = [root];
+ for (let next = 0; next < parents.length; next += 1) {
+ for (const row of all) {
+ if (row.parent !== parents[next] || row.pid === process.pid || row.pid <= 1 || parents.includes(row.pid)) continue;
+ parents.push(row.pid);
+ if (!row.gone) found.push({ pid: row.pid, start: row.start });
+ }
+ }
+ return found;
+}
+
+/** Those of `tree` still running as the same process. */
+export function stillRunning(tree: readonly TreeProcess[], platform: NodeJS.Platform = process.platform): TreeProcess[] {
+ if (!tree.length) return [];
+ const now = new Map(rows(platform).filter((row) => !row.gone).map((row) => [row.pid, row.start]));
+ return tree.filter((one) => now.get(one.pid) === one.start);
+}
+
+export function signalTree(tree: readonly TreeProcess[], signal: NodeJS.Signals): void {
+ for (const one of [...tree].reverse()) {
+ if (one.pid <= 1 || one.pid === process.pid) continue;
+ try { process.kill(one.pid, signal); } catch {}
+ }
+}
+
+/** SIGTERM to every process of `tree`, SIGKILL to those still there after `graceMs`. Resolves once none is left or the kill was sent. */
+export async function stopTree(tree: readonly TreeProcess[], graceMs: number, platform: NodeJS.Platform = process.platform): Promise<void> {
+ let left = stillRunning(tree, platform);
+ if (!left.length) return;
+ signalTree(left, "SIGTERM");
+ const deadline = Date.now() + graceMs;
+ while (Date.now() < deadline) {
+ await new Promise((resolve) => setTimeout(resolve, platform === "linux" ? 50 : 250));
+ left = stillRunning(left, platform);
+ if (!left.length) return;
+ }
+ signalTree(left, "SIGKILL");
+}
diff --git a/server/procs.ts b/server/procs.ts
index 9034f797ab..e0e1be7d0d 100644
--- a/server/procs.ts
+++ b/server/procs.ts
@@ -16,6 +16,7 @@ import { botBox, type WrappedSpawn } from "./bot-box/box.ts";
import type { BoxRequest } from "./bot-box/plan.ts";
import { homeProgramsDistrusted, serverMayRunFrom, serverPath } from "./bot-box/program-trust.ts";
import { engineMemory } from "./engine-memory.ts";
+import { ENGINE_TAG_ENV, engineRunTag, engineStopped, recordEngine } from "./engine-records.ts";
import { engineHomes } from "./engine-homes/engine-homes.ts";
import type { HomedSpawn } from "./engine-homes/layout.ts";
import { resolveCliSpawn, type ResolvedSpawn } from "./env-path.ts";
@@ -286,9 +287,12 @@ export function spawnCli(
const { box: _box, engineHome: _engineHome, botWork, ...spawnOpts } = boxed ? options : outsideBoxOptions(resolved.command, options);
// The box's extra descriptors (its seccomp filter) follow stdio; only a plain three-entry stdio can take them.
const stdio = boxed?.extraFds.length && Array.isArray(spawnOpts.stdio) && spawnOpts.stdio.length === 3 ? [...spawnOpts.stdio, ...boxed.extraFds] : spawnOpts.stdio;
+ // A server that restarts in place stops what an earlier one left by this tag (engine-records.ts).
+ const tag = process.platform === "win32" ? null : engineRunTag();
const start = () => spawn(boxed?.command ?? resolved.command, boxed?.args ?? resolved.args, {
...spawnOpts,
...(boxed ? { env: boxed.env, stdio } : {}),
+ ...(tag ? { env: { ...(boxed?.env ?? spawnOpts.env ?? process.env), [ENGINE_TAG_ENV]: tag } } : {}),
// POSIX: own group so kill(-pid) reaps child MCP servers; Windows: taskkill /T does it.
...(process.platform === "win32" ? { windowsHide: true } : { detached: true }),
}) as ChildProcessByStdio<Writable, Readable, Readable>;
@@ -310,6 +314,7 @@ export function spawnCli(
} catch {}
linuxTrees.set(child, tree);
}
+ if (process.platform !== "win32") recordEngine(child, child.pid ? linuxTrees.get(child)?.get(child.pid) ?? null : null);
if (process.platform !== "win32" && owner === "bot") {
rememberEngineSession(child);
engineMemory.track(child);
@@ -458,7 +463,7 @@ export function killCliTree(child: ChildProcess, timeoutMs = 5_000): Promise<boo
const run = stopCliTree(child, pid, Number.isFinite(timeoutMs) ? Math.max(0, timeoutMs) : 5_000);
stopping.set(child, run);
// Remember success, so a delayed caller cannot signal a reused PID/group.
- void run.then((stopped) => { if (!stopped) stopping.delete(child); });
+ void run.then((stopped) => { if (!stopped) stopping.delete(child); else engineStopped(child); });
return run;
}
diff --git a/server/turn-video.ts b/server/turn-video.ts
index 6d860e8b91..0a1d21e73a 100644
--- a/server/turn-video.ts
+++ b/server/turn-video.ts
@@ -6,6 +6,7 @@ import { tmpdir } from "node:os";
import { join } from "node:path";
import type { TurnImageInput, TurnVideoInput } from "./contracts.ts";
+import { OWN_GROUP, stopGroup } from "./group-exec.ts";
export const VIDEO_SAMPLE_FRAME_COUNT = 4;
const FFPROBE_TIMEOUT_MS = 10_000;
@@ -23,14 +24,14 @@ const VIDEO_READER: Record<TurnVideoInput["mime"], readonly string[]> = {
function run(command: string, args: readonly string[], timeoutMs: number): Promise<string> {
return new Promise((resolvePromise, reject) => {
- const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], windowsHide: true });
+ const child = spawn(command, args, { stdio: ["ignore", "pipe", "pipe"], ...OWN_GROUP });
let stdout = "";
let stderr = "";
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
- child.kill();
+ stopGroup(child);
reject(new Error(`${command} timed out`));
}, timeoutMs);
child.stdout.on("data", (chunk: Buffer) => { stdout += chunk; });
diff --git a/server/vps-computer.ts b/server/vps-computer.ts
index 83e819fa82..1b8d2d15f1 100644
--- a/server/vps-computer.ts
+++ b/server/vps-computer.ts
@@ -2,7 +2,7 @@
import { createHash, randomBytes } from "node:crypto";
import { spawn } from "node:child_process";
import { createConnection, createServer, type AddressInfo } from "node:net";
-
+import { OWN_GROUP, stopGroup } from "./group-exec.ts";
import {
BASE_IMAGE,
CUA_DRIVER_VERSION,
@@ -226,7 +226,7 @@ function stopDesktopTunnel(botId: string, expected?: DesktopTunnel): boolean {
if (pending) {
pending.start.cancelled = true;
const child = pending.start.child;
- if (child?.exitCode === null && !child.killed) child.kill("SIGTERM");
+ if (child) stopGroup(child);
pendingDesktopTunnels.delete(botId);
}
}
@@ -234,7 +234,7 @@ function stopDesktopTunnel(botId: string, expected?: DesktopTunnel): boolean {
if (!tunnel || desktopTunnels.get(botId) !== tunnel) return false;
desktopTunnels.delete(botId);
clearTimeout(tunnel.expiry);
- if (tunnel.child.exitCode === null && !tunnel.child.killed) tunnel.child.kill("SIGTERM");
+ stopGroup(tunnel.child);
return true;
}
@@ -1112,7 +1112,7 @@ async function startDesktopTunnel(cfg: AppConfig, botId: string, alias: string,
shell: false,
env: { ...process.env, PATH: ssh.path },
stdio: ["ignore", "ignore", "pipe"],
- windowsHide: true,
+ ...OWN_GROUP, // with ssh's ProxyCommand, if any, so a stop reaches it
});
start.child = child;
let failure: string | null = null;
@@ -1140,7 +1140,7 @@ async function startDesktopTunnel(cfg: AppConfig, botId: string, alias: string,
}
const ready = !failure && await loopbackAnswers(localPort);
if (start.cancelled || failure || !ready) {
- if (child.exitCode === null && !child.killed) child.kill("SIGTERM");
+ stopGroup(child);
assertOpen();
const detail = failure || stderr.trim() || "the SSH port forward did not become ready";
throw Object.assign(new Error(`Could not open the VPS live desktop: ${detail}`), { status: 502 });
diff --git a/server/workspace-backup.ts b/server/workspace-backup.ts
index c565a29a5d..2884a41d92 100644
--- a/server/workspace-backup.ts
+++ b/server/workspace-backup.ts
@@ -45,6 +45,8 @@ const EXCLUDED = new Set([
"claude-user-skills",
// The bot box's live sockets and seccomp filter (bot-box/box.ts), made again each time the server starts.
"box",
+ // The processes this machine's servers started (engine-records.ts), stopped by its next start.
+ "engine-runs",
// A Team Cloud's engine homes (engine-homes/layout.ts): CLI login homes, each audience's own transcripts and the held
// folder, which no admin reads.
"engine-homes",