@@ -146,6 +146,7 @@ import * as Effect from "effect/Effect";
146146import * as Equal from "effect/Equal";
147147import * as Exit from "effect/Exit";
148148import * as Fiber from "effect/Fiber";
149+ import * as Schedule from "effect/Schedule";
149150import * as FileSystem from "effect/FileSystem";
150151import * as Layer from "effect/Layer";
151152import * as Option from "effect/Option";
@@ -178,6 +179,7 @@ import {
178179} from "../../claudeModelOptions.ts";
179180import * as ServerConfig from "../../config.ts";
180181import * as PortScanner from "../../preview/PortScanner.ts";
182+ import * as ProcessRunner from "../../processRunner.ts";
181183import * as ServerSettings from "../../serverSettings.ts";
182184import { expandHomePath } from "@t3tools/provider-core/server/pathExpansion";
183185import { spawnAndCollect } from "@t3tools/provider-core/server/snapshotProbe";
@@ -360,6 +362,8 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
360362const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
361363// The process group is killed on exit, so its stderr closes promptly.
362364const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
365+ // How often the CLI's process tree is recorded when no agent scope will stop what it leaves.
366+ const CLAUDE_DESCENDANT_POLL = "1 second";
363367// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
364368const CLAUDE_ROOT_REFUSAL =
365369 "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
@@ -379,7 +383,7 @@ export function spawnClaudeProcessGroup(
379383 onExit?: () => void,
380384 onStderr: (text: string) => void = () => {},
381385 onStderrClose: () => void = () => {},
382- ): ClaudeSpawnedProcess {
386+ ): ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid"> {
383387 const child = NodeChildProcess.spawn(
384388 "/bin/sh",
385389 ["-c", CLAUDE_GROUP_WATCH_SCRIPT, "t3-claude", options.command, ...options.args],
@@ -400,7 +404,60 @@ export function spawnClaudeProcessGroup(
400404 onExit?.();
401405 });
402406 // Node's typings make stdin and stdout nullable once stdio has a fourth entry; both are pipes.
403- return child as ClaudeSpawnedProcess;
407+ return child as ClaudeSpawnedProcess & Pick<NodeChildProcess.ChildProcess, "pid">;
408+ }
409+
410+ interface ClaudeProcessRow {
411+ readonly pid: number;
412+ readonly ppid: number;
413+ readonly pgid: number;
414+ readonly started: string;
415+ }
416+
417+ /** Parses `ps -A -o pid=,ppid=,pgid=,lstart=`; pid plus start time tells a process from a reused pid. */
418+ function parseClaudeProcessTable(table: string): ReadonlyArray<ClaudeProcessRow> {
419+ return table.split("\n").flatMap((line) => {
420+ const [pid, ppid, pgid, ...started] = line.trim().split(/\s+/);
421+ const row = {
422+ pid: Number(pid),
423+ ppid: Number(ppid),
424+ pgid: Number(pgid),
425+ started: started.join(" "),
426+ };
427+ return Number.isSafeInteger(row.pid) &&
428+ Number.isSafeInteger(row.ppid) &&
429+ Number.isSafeInteger(row.pgid) &&
430+ row.started
431+ ? [row]
432+ : [];
433+ });
434+ }
435+
436+ // A job leading its own group takes the processes it started since with it.
437+ function killClaudeDescendant(row: ClaudeProcessRow) {
438+ try {
439+ if (row.pgid === row.pid) signalProcessGroup(row.pid, "SIGKILL");
440+ else process.kill(row.pid, "SIGKILL");
441+ } catch {}
442+ }
443+
444+ function claudeDescendants(
445+ rows: ReadonlyArray<ClaudeProcessRow>,
446+ rootPids: ReadonlyArray<number>,
447+ ): ReadonlyArray<ClaudeProcessRow> {
448+ const children = Map.groupBy(rows, (row) => row.ppid);
449+ const found: Array<ClaudeProcessRow> = [];
450+ const seen = new Set<number>(rootPids);
451+ const pending = [...rootPids];
452+ for (let parent = pending.pop(); parent !== undefined; parent = pending.pop()) {
453+ for (const child of children.get(parent) ?? []) {
454+ if (seen.has(child.pid)) continue;
455+ seen.add(child.pid);
456+ found.push(child);
457+ pending.push(child.pid);
458+ }
459+ }
460+ return found;
404461}
405462
406463export const ClaudeProviderCapabilitiesV2 = {
@@ -1195,6 +1252,41 @@ export const layerQueryRunner: Layer.Layer<
11951252 const runFork = Effect.runForkWith(yield* Effect.context<never>());
11961253 const hostEnvironment = yield* HostProcess.Environment;
11971254 const portDiscovery = yield* PortScanner.PortDiscovery;
1255+ const processRunner = yield* ProcessRunner.make();
1256+ const readProcessTable = processRunner
1257+ .run({ command: "ps", args: ["-A", "-o", "pid=,ppid=,pgid=,lstart="], timeout: "5 seconds" })
1258+ .pipe(
1259+ Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])),
1260+ Effect.orElseSucceed(() => []),
1261+ );
1262+ // Without an agent scope, a job that left the CLI's group escapes the group kill and is
1263+ // re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is
1264+ // still the same process (pid and start time) is stopped after it exits.
1265+ const trackDescendants = (cliPid: number) => {
1266+ const tracked = new Map<string, ClaudeProcessRow>();
1267+ const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;
1268+ // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.
1269+ const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")(function* (
1270+ cliRunning: boolean,
1271+ ) {
1272+ const rows = yield* readProcessTable;
1273+ const running = new Set(rows.map(identity));
1274+ const roots = [
1275+ ...(cliRunning ? [cliPid] : []),
1276+ ...[...tracked.values()].flatMap((row) => (running.has(identity(row)) ? [row.pid] : [])),
1277+ ];
1278+ for (const row of claudeDescendants(rows, roots)) tracked.set(identity(row), row);
1279+ return running;
1280+ });
1281+ const stop = refresh(false).pipe(
1282+ Effect.map((running) => {
1283+ for (const row of tracked.values()) {
1284+ if (running.has(identity(row))) killClaudeDescendant(row);
1285+ }
1286+ }),
1287+ );
1288+ return { refresh: refresh(true).pipe(Effect.asVoid), stop };
1289+ };
11981290
11991291 return ClaudeAgentSdkQueryRunner.of({
12001292 allocateSessionId: random.uuidV4(),
@@ -1259,14 +1351,31 @@ export const layerQueryRunner: Layer.Layer<
12591351 if (answered) return;
12601352 stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
12611353 };
1354+ let refreshDescendants: Effect.Effect<void> = Effect.void;
12621355 const spawnProcess =
12631356 options.spawnClaudeCodeProcess ??
12641357 ((spawnOptions: ClaudeSpawnOptions) => {
12651358 if (platform !== "win32") {
12661359 // Node can report "exit" before it has read the stderr the CLI wrote.
12671360 let stderrDone = () => {};
12681361 stderrClosed = new Promise((resolve) => (stderrDone = resolve));
1269- return spawnClaudeProcessGroup(spawnOptions, stopScope, appendStderr, stderrDone);
1362+ const child = spawnClaudeProcessGroup(
1363+ spawnOptions,
1364+ stopScope,
1365+ appendStderr,
1366+ stderrDone,
1367+ );
1368+ if (unit === undefined && child.pid !== undefined) {
1369+ const tracker = trackDescendants(child.pid);
1370+ const polling = runFork(
1371+ tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
1372+ );
1373+ child.once("exit", () =>
1374+ runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
1375+ );
1376+ refreshDescendants = tracker.refresh;
1377+ }
1378+ return child;
12701379 }
12711380 const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, {
12721381 cwd: spawnOptions.cwd,
@@ -1573,7 +1682,9 @@ export const layerQueryRunner: Layer.Layer<
15731682 }),
15741683 ),
15751684 ),
1576- close: Queue.shutdown(promptQueue).pipe(
1685+ // A job started since the last poll is recorded before the CLI is told to exit.
1686+ close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
1687+ Effect.andThen(Queue.shutdown(promptQueue)),
15771688 Effect.andThen(closeClaudeQuery(queryRuntime)),
15781689 Effect.tap(() =>
15791690 logProtocolEvent({
0 commit comments