Skip to content

A personal assistant that lives on your desktop, remembers what matters, and can use your Mac for you.

TypeScript

feat(daemon): bounded agent shutdown through the process tree

Marcelitoa8863e11db11
diff --git a/.github/workflows/windows.yml b/.github/workflows/windows.yml
index fd80c24..9b6a7aa 100644
--- a/.github/workflows/windows.yml
+++ b/.github/workflows/windows.yml
@@ -96,5 +96,5 @@ jobs:
# These portable adapter tests and real-addon refusal tests stay together.
- name: App-channel tests
- run: pnpm exec vitest run packages/daemon/test/windows-stop.test.ts packages/daemon/test/windows-app-channel.test.ts packages/daemon/test/app-channel-platform.test.ts packages/daemon/test/app-channel.test.ts packages/daemon/test/app-channel-fd.test.ts packages/daemon/test/windows-app-channel-addon.test.ts
+ run: pnpm exec vitest run packages/daemon/test/windows-stop.test.ts packages/daemon/test/windows-app-channel.test.ts packages/daemon/test/app-channel-platform.test.ts packages/daemon/test/app-channel.test.ts packages/daemon/test/app-channel-fd.test.ts packages/daemon/test/windows-app-channel-addon.test.ts packages/daemon/test/process-tree.test.ts packages/daemon/test/supervisor.test.ts
diff --git a/packages/daemon/src/process-tree.ts b/packages/daemon/src/process-tree.ts
new file mode 100644
index 0000000..bb3a7ef
--- /dev/null
+++ b/packages/daemon/src/process-tree.ts
@@ -0,0 +1,69 @@
+import { type ChildProcess, spawn } from "node:child_process";
+
+/** Windows tree enumeration can take several seconds even for a small console process. */
+export const WINDOWS_TASKKILL_TIMEOUT_MS = 10_000;
+
+export interface ProcessTreeTerminationOptions {
+ platform?: NodeJS.Platform;
+ /** Confirms immediately before escalation that this is still the supervisor-owned child. */
+ isCurrent?: () => boolean;
+ /** Maximum time allowed for taskkill itself. */
+ commandTimeoutMs?: number;
+ /** Test seam for the taskkill process only. */
+ spawnTaskkill?: (
+ command: string,
+ args: readonly string[],
+ options: { windowsHide: boolean; stdio: "ignore" },
+ ) => ChildProcess;
+}
+
+/**
+ * Escalates termination for one supervisor-owned child.
+ *
+ * Windows taskkill is necessarily PID-based. The ownership check narrows, but cannot
+ * eliminate, the race where Windows reuses a PID between the check and taskkill.
+ */
+export function terminateProcessTree(
+ child: ChildProcess,
+ force: boolean,
+ options: ProcessTreeTerminationOptions = {},
+): Promise<boolean> {
+ if (options.isCurrent && !options.isCurrent()) return Promise.resolve(false);
+ if ((options.platform ?? process.platform) !== "win32") {
+ return Promise.resolve(child.kill(force ? "SIGKILL" : "SIGTERM"));
+ }
+
+ const pid = child.pid;
+ if (!Number.isSafeInteger(pid) || (pid ?? 0) <= 0) {
+ return Promise.reject(
+ new Error("Cannot terminate Windows process tree without a strictly positive process id"),
+ );
+ }
+ // Recheck after validation so a stale asynchronous escalation never reaches taskkill.
+ if (options.isCurrent && !options.isCurrent()) return Promise.resolve(false);
+
+ const args = ["/PID", String(pid), ...(force ? ["/F"] : []), "/T"];
+ const spawnTaskkill = options.spawnTaskkill ?? spawn;
+ return new Promise<boolean>((resolve, reject) => {
+ let settled = false;
+ const taskkill = spawnTaskkill("taskkill.exe", args, { windowsHide: true, stdio: "ignore" });
+ const finish = (error?: Error) => {
+ if (settled) return;
+ settled = true;
+ clearTimeout(timer);
+ if (error) reject(error);
+ else resolve(true);
+ };
+ const timer = setTimeout(() => {
+ taskkill.kill();
+ finish(new Error(`taskkill timed out while terminating process tree ${pid}`));
+ }, options.commandTimeoutMs ?? WINDOWS_TASKKILL_TIMEOUT_MS);
+ taskkill.once("error", (error) =>
+ finish(new Error(`taskkill failed for process tree ${pid}: ${error.message}`)),
+ );
+ taskkill.once("close", (code) => {
+ if (code === 0) finish();
+ else finish(new Error(`taskkill failed for process tree ${pid} with exit code ${code}`));
+ });
+ });
+}
diff --git a/packages/daemon/src/supervisor.ts b/packages/daemon/src/supervisor.ts
index 320cc67..bf26761 100644
--- a/packages/daemon/src/supervisor.ts
+++ b/packages/daemon/src/supervisor.ts
@@ -3,6 +3,7 @@ import { existsSync, mkdirSync, readFileSync } from "node:fs";
import { join } from "node:path";
import { encodeRecord, JsonlDecoder } from "./jsonl.ts";
import { writePrivateFile } from "./private-file.ts";
+import { terminateProcessTree, WINDOWS_TASKKILL_TIMEOUT_MS } from "./process-tree.ts";
import type { OsUser } from "./vps.ts";
/** A record the agent wrote to stdout that is not a command response. */
@@ -47,8 +48,16 @@ export interface SupervisorOptions {
requestTimeoutMs?: number;
/** Deadline for the agent to answer its first `get_state`. Default 60s. */
startTimeoutMs?: number;
- /** Grace period after closing stdin before SIGTERM. Default 5s. */
+ /** Grace period after closing stdin before the first process-tree escalation. Default 5s. */
stopTimeoutMs?: number;
+ /** Lifecycle platform override; tests pair this with a termination override. */
+ platform?: NodeJS.Platform;
+ /** Time between soft and forced escalation. Default 12s on Windows, 2s on Unix. */
+ hardStopTimeoutMs?: number;
+ /** Time after forced escalation before shutdown rejects. Default 12s on Windows, 2s on Unix. */
+ terminationFailureTimeoutMs?: number;
+ /** Process-tree termination override, primarily for deterministic lifecycle tests. */
+ terminateProcessTree?: typeof terminateProcessTree;
log?: (line: string) => void;
}
@@ -196,11 +205,13 @@ export class AgentSupervisor {
const child = this.child;
if (!child || this.stopping) return;
this.restarting = true;
- const closed = new Promise<void>((resolve) => this.closeWaiters.push(resolve));
- child.stdin?.end();
- const term = setTimeout(() => child.kill("SIGTERM"), this.options.stopTimeoutMs ?? 5000);
- await closed;
- clearTimeout(term);
+ try {
+ await this.closeChild(child);
+ } catch (error) {
+ // The old process is still running: never spawn a second engine over it.
+ this.restarting = false;
+ throw error;
+ }
// Stopped while the old process was closing: nothing is started again.
if (this.stopping) {
this.setState("stopped");
@@ -220,13 +231,64 @@ export class AgentSupervisor {
this.setState("stopped");
return;
}
- const closed = new Promise<void>((resolve) => this.closeWaiters.push(resolve));
- child.stdin?.end();
- const term = setTimeout(() => child.kill("SIGTERM"), this.options.stopTimeoutMs ?? 5000);
- const kill = setTimeout(() => child.kill("SIGKILL"), (this.options.stopTimeoutMs ?? 5000) + 2000);
- await closed;
- clearTimeout(term);
- clearTimeout(kill);
+ await this.closeChild(child);
+ }
+
+ /**
+ * Closes stdin, then escalates through the process tree: soft after the grace period, forced
+ * after the hard window. Rejects when the child is still the current one after the failure
+ * window, instead of waiting for a process that did not terminate.
+ */
+ private closeChild(child: ChildProcess): Promise<void> {
+ const gracefulMs = this.options.stopTimeoutMs ?? 5000;
+ const platform = this.options.platform ?? process.platform;
+ // Leave two seconds for the child's close event after taskkill's own deadline.
+ const stageMs = platform === "win32" ? WINDOWS_TASKKILL_TIMEOUT_MS + 2000 : 2000;
+ const hardMs = this.options.hardStopTimeoutMs ?? stageMs;
+ const failureMs = this.options.terminationFailureTimeoutMs ?? stageMs;
+ const terminate = this.options.terminateProcessTree ?? terminateProcessTree;
+ return new Promise<void>((resolve, reject) => {
+ let settled = false;
+ const errors: string[] = [];
+ const timers: NodeJS.Timeout[] = [];
+ const finish = (error?: Error) => {
+ if (settled) return;
+ settled = true;
+ for (const timer of timers) clearTimeout(timer);
+ const index = this.closeWaiters.indexOf(onClose);
+ if (index >= 0) this.closeWaiters.splice(index, 1);
+ if (error) reject(error);
+ else resolve();
+ };
+ const onClose = () => finish();
+ const escalate = (force: boolean) => {
+ if (this.child !== child) return;
+ void terminate(child, force, { platform, isCurrent: () => this.child === child }).catch(
+ (error: Error) => {
+ errors.push(error.message);
+ this.log(error.message);
+ },
+ );
+ };
+ this.closeWaiters.push(onClose);
+ child.stdin?.end();
+ timers.push(setTimeout(() => escalate(false), gracefulMs));
+ timers.push(setTimeout(() => escalate(true), gracefulMs + hardMs));
+ timers.push(
+ setTimeout(
+ () => {
+ if (this.child !== child) return finish();
+ const detail = errors.length > 0 ? `: ${errors.join("; ")}` : "";
+ finish(
+ new Error(
+ `Failed to stop agent process ${child.pid ?? "without a PID"} after bounded termination${detail}`,
+ ),
+ );
+ },
+ gracefulMs + hardMs + failureMs,
+ ),
+ );
+ });
}
private initialize(): Promise<void> {
diff --git a/packages/daemon/test/process-tree.test.ts b/packages/daemon/test/process-tree.test.ts
new file mode 100644
index 0000000..bc11935
--- /dev/null
+++ b/packages/daemon/test/process-tree.test.ts
@@ -0,0 +1,121 @@
+import type { ChildProcess } from "node:child_process";
+import { EventEmitter } from "node:events";
+import { describe, expect, it, vi } from "vitest";
+import { terminateProcessTree } from "../src/process-tree.ts";
+
+function taskkillProcess(code = 0): ChildProcess {
+ const process = new EventEmitter() as ChildProcess;
+ process.kill = vi.fn(() => true);
+ queueMicrotask(() => process.emit("close", code, null));
+ return process;
+}
+
+describe("terminateProcessTree", () => {
+ it("uses bounded Windows tree termination and adds force only for hard escalation", async () => {
+ const calls: { command: string; args: readonly string[]; windowsHide?: boolean }[] = [];
+ const spawnTaskkill = vi.fn(
+ (command: string, args: readonly string[], options: { windowsHide?: boolean }) => {
+ calls.push({ command, args, windowsHide: options.windowsHide });
+ return taskkillProcess();
+ },
+ );
+ const child = { pid: 321 } as ChildProcess;
+
+ await terminateProcessTree(child, false, { platform: "win32", spawnTaskkill });
+ await terminateProcessTree(child, true, { platform: "win32", spawnTaskkill });
+
+ expect(calls).toEqual([
+ { command: "taskkill.exe", args: ["/PID", "321", "/T"], windowsHide: true },
+ { command: "taskkill.exe", args: ["/PID", "321", "/F", "/T"], windowsHide: true },
+ ]);
+ });
+
+ it.each([undefined, 0, -1, 1.5, Number.NaN])("never invokes taskkill for invalid pid %s", async (pid) => {
+ const spawnTaskkill = vi.fn(() => taskkillProcess());
+ await expect(
+ terminateProcessTree({ pid } as ChildProcess, false, { platform: "win32", spawnTaskkill }),
+ ).rejects.toThrow(/positive process id/i);
+ expect(spawnTaskkill).not.toHaveBeenCalled();
+ });
+
+ it("rechecks ownership immediately before taskkill and skips a stale child", async () => {
+ const spawnTaskkill = vi.fn(() => taskkillProcess());
+ const ownership = [true, false];
+ await expect(
+ terminateProcessTree({ pid: 321 } as ChildProcess, false, {
+ platform: "win32",
+ spawnTaskkill,
+ isCurrent: () => ownership.shift() ?? false,
+ }),
+ ).resolves.toBe(false);
+ expect(spawnTaskkill).not.toHaveBeenCalled();
+ });
+
+ it("allows a Windows tree command to finish after six seconds without timing out", async () => {
+ vi.useFakeTimers();
+ try {
+ const taskkill = new EventEmitter() as ChildProcess;
+ taskkill.kill = vi.fn(() => true);
+ const result = terminateProcessTree({ pid: 321 } as ChildProcess, true, {
+ platform: "win32",
+ spawnTaskkill: () => {
+ setTimeout(() => taskkill.emit("close", 0, null), 6500);
+ return taskkill;
+ },
+ }).then(
+ (value) => ({ value }),
+ (error) => ({ error: String(error) }),
+ );
+ await vi.advanceTimersByTimeAsync(6500);
+ expect(await result).toEqual({ value: true });
+ expect(taskkill.kill).not.toHaveBeenCalled();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("still bounds the default Windows taskkill command at ten seconds", async () => {
+ vi.useFakeTimers();
+ try {
+ const taskkill = new EventEmitter() as ChildProcess;
+ taskkill.kill = vi.fn(() => true);
+ let failure: string | undefined;
+ const result = terminateProcessTree({ pid: 321 } as ChildProcess, false, {
+ platform: "win32",
+ spawnTaskkill: () => taskkill,
+ }).catch((error) => {
+ failure = String(error);
+ });
+ await vi.advanceTimersByTimeAsync(9999);
+ expect(failure).toBeUndefined();
+ expect(taskkill.kill).not.toHaveBeenCalled();
+ await vi.advanceTimersByTimeAsync(1);
+ await result;
+ expect(failure).toMatch(/taskkill timed out/i);
+ expect(taskkill.kill).toHaveBeenCalledOnce();
+ } finally {
+ vi.useRealTimers();
+ }
+ });
+
+ it("bounds a hung taskkill command", async () => {
+ const taskkill = new EventEmitter() as ChildProcess;
+ taskkill.kill = vi.fn(() => true);
+ await expect(
+ terminateProcessTree({ pid: 321 } as ChildProcess, false, {
+ platform: "win32",
+ commandTimeoutMs: 1,
+ spawnTaskkill: () => taskkill,
+ }),
+ ).rejects.toThrow(/taskkill timed out/i);
+ expect(taskkill.kill).toHaveBeenCalledOnce();
+ });
+
+ it.each(["linux", "darwin"] as const)("keeps the existing %s signal path", async (platform) => {
+ const kill = vi.fn(() => true);
+ const child = { pid: 321, kill } as unknown as ChildProcess;
+ await expect(terminateProcessTree(child, false, { platform })).resolves.toBe(true);
+ await expect(terminateProcessTree(child, true, { platform })).resolves.toBe(true);
+ expect(kill.mock.calls).toEqual([["SIGTERM"], ["SIGKILL"]]);
+ });
+});
diff --git a/packages/daemon/test/supervisor.test.ts b/packages/daemon/test/supervisor.test.ts
index 86b07da..40d7146 100644
--- a/packages/daemon/test/supervisor.test.ts
+++ b/packages/daemon/test/supervisor.test.ts
@@ -1,6 +1,6 @@
import { readFileSync } from "node:fs";
import { join } from "node:path";
-import { afterEach, describe, expect, it } from "vitest";
+import { afterEach, describe, expect, it, vi } from "vitest";
import type { AgentSupervisor } from "../src/supervisor.ts";
import { fakeSupervisor, tempDir, waitFor } from "./helpers.ts";
@@ -14,6 +14,31 @@ function track<T extends { supervisor: AgentSupervisor }>(value: T): T {
return value;
}
+const STUBBORN_AGENT = `
+process.on("SIGTERM", () => {});
+process.stdin.setEncoding("utf8");
+let buffer = "";
+process.stdin.on("data", (chunk) => {
+ buffer += chunk;
+ for (;;) {
+ const newline = buffer.indexOf("\\n");
+ if (newline < 0) break;
+ const line = buffer.slice(0, newline);
+ buffer = buffer.slice(newline + 1);
+ if (!line) continue;
+ const record = JSON.parse(line);
+ if (record.type === "get_state") {
+ process.stdout.write(JSON.stringify({
+ type: "response", id: record.id, command: "get_state", success: true,
+ data: { sessionId: "stubborn" }
+ }) + "\\n");
+ }
+ }
+});
+process.stdin.on("end", () => process.stdin.resume());
+setInterval(() => {}, 1000);
+`;
+
describe("AgentSupervisor", () => {
it("spawns the agent in RPC mode with the session dir and extra args", async () => {
const argsFile = join(tempDir(), "argv.json");
@@ -243,4 +268,153 @@ describe("AgentSupervisor", () => {
expect(supervisor.state).toBe("stopped");
await expect(supervisor.request({ type: "get_state" })).rejects.toThrow(/not ready/i);
});
+
+ it("closes a cooperative agent within the production grace without escalation", async () => {
+ const escalations: boolean[] = [];
+ const { supervisor } = track(
+ fakeSupervisor({
+ // Keep the production grace: OS scheduling under suite load is not a 10ms contract.
+ terminateProcessTree: async (_child, force) => {
+ escalations.push(force);
+ return false;
+ },
+ }),
+ );
+ await supervisor.start();
+ await supervisor.stop();
+ expect(escalations).toEqual([]);
+ expect(supervisor.state).toBe("stopped");
+ expect(supervisor.pid).toBeUndefined();
+ });
+
+ it.each([
+ ["win32", 12000],
+ ["linux", 2000],
+ ["darwin", 2000],
+ ] as const)(
+ "coordinates default %s escalation windows without changing Unix timing",
+ async (platform, windowMs) => {
+ const escalations: boolean[] = [];
+ const { supervisor } = track(
+ fakeSupervisor({
+ platform,
+ command: process.execPath,
+ args: ["-e", STUBBORN_AGENT, "--"],
+ stopTimeoutMs: 1,
+ terminateProcessTree: async (child, force) => {
+ escalations.push(force);
+ if (force) child.kill("SIGKILL");
+ return true;
+ },
+ }),
+ );
+ await supervisor.start();
+ vi.useFakeTimers();
+ const stopped = supervisor.stop();
+ void stopped.catch(() => {});
+ try {
+ await vi.advanceTimersByTimeAsync(1);
+ expect(escalations).toEqual([false]);
+ await vi.advanceTimersByTimeAsync(windowMs - 1);
+ expect(escalations).toEqual([false]);
+ await vi.advanceTimersByTimeAsync(1);
+ expect(escalations).toEqual([false, true]);
+ await stopped;
+ expect(supervisor.state).toBe("stopped");
+ expect(supervisor.pid).toBeUndefined();
+ } finally {
+ vi.useRealTimers();
+ const pid = supervisor.pid;
+ // Only a positive PID is the owned fixture; a throw here would hide the test's own failure.
+ if (pid !== undefined && pid > 0) {
+ process.kill(pid, "SIGKILL");
+ await waitFor(() => supervisor.state === "stopped");
+ }
+ }
+ },
+ );
+
+ it("keeps both Windows default stages bounded without rejecting before taskkill can finish", async () => {
+ const escalations: boolean[] = [];
+ const { supervisor } = track(
+ fakeSupervisor({
+ platform: "win32",
+ command: process.execPath,
+ args: ["-e", STUBBORN_AGENT, "--"],
+ stopTimeoutMs: 1,
+ terminateProcessTree: async (_child, force) => {
+ escalations.push(force);
+ return false;
+ },
+ }),
+ );
+ await supervisor.start();
+ const pid = supervisor.pid;
+ const sessionId = supervisor.sessionId;
+ vi.useFakeTimers();
+ let failure: Error | undefined;
+ const stopped = supervisor.stop().catch((error) => {
+ failure = error;
+ });
+ try {
+ await vi.advanceTimersByTimeAsync(24000);
+ expect(failure).toBeUndefined();
+ expect(escalations).toEqual([false, true]);
+ await vi.advanceTimersByTimeAsync(1);
+ await stopped;
+ expect(failure?.message).toBe(`Failed to stop agent process ${pid} after bounded termination`);
+ expect(supervisor.pid).toBe(pid);
+ expect(supervisor.sessionId).toBe(sessionId);
+ } finally {
+ vi.useRealTimers();
+ // Only the current positive PID is the owned fixture; a throw here would hide the test's own failure.
+ if (pid && pid > 0 && supervisor.pid === pid) {
+ process.kill(pid, "SIGKILL");
+ await waitFor(() => supervisor.state === "stopped");
+ }
+ }
+ });
+
+ it("rejects stop actionably when bounded soft and hard termination do not close the child", async () => {
+ const escalations: boolean[] = [];
+ const { supervisor } = fakeSupervisor({
+ command: process.execPath,
+ args: ["-e", STUBBORN_AGENT, "--"],
+ stopTimeoutMs: 10,
+ hardStopTimeoutMs: 10,
+ terminationFailureTimeoutMs: 10,
+ terminateProcessTree: async (_child, force) => {
+ escalations.push(force);
+ return false;
+ },
+ });
+ await supervisor.start();
+ const pid = supervisor.pid;
+ await expect(supervisor.stop()).rejects.toThrow(/failed to stop agent process/i);
+ expect(escalations).toEqual([false, true]);
+ expect(supervisor.pid).toBe(pid);
+ if (!pid || pid <= 0) throw new Error("Missing owned test child PID");
+ process.kill(pid, "SIGKILL");
+ await waitFor(() => supervisor.state === "stopped");
+ });
+
+ it("rejects restart actionably instead of spawning over a child that did not terminate", async () => {
+ const { supervisor } = fakeSupervisor({
+ command: process.execPath,
+ args: ["-e", STUBBORN_AGENT, "--"],
+ stopTimeoutMs: 10,
+ hardStopTimeoutMs: 10,
+ terminationFailureTimeoutMs: 10,
+ terminateProcessTree: async () => false,
+ });
+ await supervisor.start();
+ const pid = supervisor.pid;
+ await expect(supervisor.restart()).rejects.toThrow(/failed to stop agent process/i);
+ expect(supervisor.pid).toBe(pid);
+ if (!pid || pid <= 0) throw new Error("Missing owned test child PID");
+ const stopped = supervisor.stop();
+ process.kill(pid, "SIGKILL");
+ await stopped;
+ expect(supervisor.state).toBe("stopped");
+ });
});