@@ -145,6 +145,7 @@ import * as Effect from "effect/Effect";
145145import * as Equal from "effect/Equal";
146146import * as Exit from "effect/Exit";
147147import * as Fiber from "effect/Fiber";
148+ import * as Schedule from "effect/Schedule";
148149import * as FileSystem from "effect/FileSystem";
149150import * as Layer from "effect/Layer";
150151import * as Option from "effect/Option";
@@ -358,6 +359,8 @@ const CLAUDE_STOP_CONFIRM_TIMEOUT_MS = 10_000;
358359const CLAUDE_STDERR_TAIL_LENGTH = 2_048;
359360// The process group is killed on exit, so its stderr closes promptly.
360361const CLAUDE_STDERR_DRAIN_TIMEOUT = Duration.seconds(1);
362+ // How often the CLI's process tree is recorded when no agent scope will stop what it leaves.
363+ const CLAUDE_DESCENDANT_POLL = "1 second";
361364// Claude Code's refusal of bypassPermissions as root, which it explains only on stderr.
362365const CLAUDE_ROOT_REFUSAL =
363366 "--dangerously-skip-permissions cannot be used with root/sudo privileges for security reasons";
@@ -437,12 +440,12 @@ function killClaudeDescendant(row: ClaudeProcessRow) {
437440
438441function claudeDescendants(
439442 rows: ReadonlyArray<ClaudeProcessRow>,
440- rootPid: number,
443+ rootPids: ReadonlyArray< number> ,
441444): ReadonlyArray<ClaudeProcessRow> {
442445 const children = Map.groupBy(rows, (row) => row.ppid);
443446 const found: Array<ClaudeProcessRow> = [];
444- const seen = new Set<number>([rootPid] );
445- const pending = [rootPid ];
447+ const seen = new Set<number>(rootPids );
448+ const pending = [...rootPids ];
446449 for (let parent = pending.pop(); parent !== undefined; parent = pending.pop()) {
447450 for (const child of children.get(parent) ?? []) {
448451 if (seen.has(child.pid)) continue;
@@ -1231,18 +1234,34 @@ export const layerQueryRunner: Layer.Layer<
12311234 Effect.map((result) => (result.code === 0 ? parseClaudeProcessTable(result.stdout) : [])),
12321235 Effect.orElseSucceed(() => []),
12331236 );
1234- // A job that left the CLI's group escapes the group kill and is re-parented once the CLI
1235- // exits, so it is found while the CLI runs and stopped after it exits, if still the same process.
1236- const stopAfterExit = Effect.fn("ClaudeAgentSdkQueryRunner.stopAfterExit")(function* (
1237- descendants: ReadonlyArray<ClaudeProcessRow>,
1238- exited: Promise<void>,
1239- ) {
1240- yield* Effect.promise(() => exited);
1241- const running = new Set((yield* readProcessTable).map((row) => `${row.pid} ${row.started}`));
1242- for (const row of descendants) {
1243- if (running.has(`${row.pid} ${row.started}`)) killClaudeDescendant(row);
1244- }
1245- });
1237+ // Without an agent scope, a job that left the CLI's group escapes the group kill and is
1238+ // re-parented once the CLI exits. So the CLI's tree is recorded while it runs, and what is
1239+ // still the same process (pid and start time) is stopped after it exits.
1240+ const trackDescendants = (cliPid: number) => {
1241+ const tracked = new Map<string, ClaudeProcessRow>();
1242+ const identity = (row: ClaudeProcessRow) => `${row.pid} ${row.started}`;
1243+ // After exit the CLI's pid may belong to an unrelated process, so only tracked jobs are roots.
1244+ const refresh = Effect.fn("ClaudeAgentSdkQueryRunner.trackDescendants")(function* (
1245+ cliRunning: boolean,
1246+ ) {
1247+ const rows = yield* readProcessTable;
1248+ const running = new Set(rows.map(identity));
1249+ const roots = [
1250+ ...(cliRunning ? [cliPid] : []),
1251+ ...[...tracked.values()].flatMap((row) => (running.has(identity(row)) ? [row.pid] : [])),
1252+ ];
1253+ for (const row of claudeDescendants(rows, roots)) tracked.set(identity(row), row);
1254+ return running;
1255+ });
1256+ const stop = refresh(false).pipe(
1257+ Effect.map((running) => {
1258+ for (const row of tracked.values()) {
1259+ if (running.has(identity(row))) killClaudeDescendant(row);
1260+ }
1261+ }),
1262+ );
1263+ return { refresh: refresh(true).pipe(Effect.asVoid), stop };
1264+ };
12461265
12471266 return ClaudeAgentSdkQueryRunner.of({
12481267 allocateSessionId: random.uuidV4(),
@@ -1307,7 +1326,7 @@ export const layerQueryRunner: Layer.Layer<
13071326 if (answered) return;
13081327 stderrTail = (stderrTail + text).slice(-CLAUDE_STDERR_TAIL_LENGTH);
13091328 };
1310- let cliPid: number | undefined ;
1329+ let refreshDescendants: Effect.Effect<void> = Effect.void ;
13111330 const spawnProcess =
13121331 options.spawnClaudeCodeProcess ??
13131332 ((spawnOptions: ClaudeSpawnOptions) => {
@@ -1321,7 +1340,16 @@ export const layerQueryRunner: Layer.Layer<
13211340 appendStderr,
13221341 stderrDone,
13231342 );
1324- cliPid = child.pid;
1343+ if (unit === undefined && child.pid !== undefined) {
1344+ const tracker = trackDescendants(child.pid);
1345+ const polling = runFork(
1346+ tracker.refresh.pipe(Effect.repeat(Schedule.spaced(CLAUDE_DESCENDANT_POLL))),
1347+ );
1348+ child.once("exit", () =>
1349+ runFork(Fiber.interrupt(polling).pipe(Effect.andThen(tracker.stop))),
1350+ );
1351+ refreshDescendants = tracker.refresh;
1352+ }
13251353 return child;
13261354 }
13271355 const child = NodeChildProcess.spawn(spawnOptions.command, spawnOptions.args, {
@@ -1617,16 +1645,8 @@ export const layerQueryRunner: Layer.Layer<
16171645 }),
16181646 ),
16191647 ),
1620- close: Effect.gen(function* () {
1621- const descendants =
1622- cliPid === undefined || processExited
1623- ? []
1624- : claudeDescendants(yield* readProcessTable, cliPid);
1625- const exited = processExit;
1626- if (descendants.length > 0 && exited !== undefined) {
1627- runFork(stopAfterExit(descendants, exited));
1628- }
1629- }).pipe(
1648+ // A job started since the last poll is recorded before the CLI is told to exit.
1649+ close: Effect.suspend(() => (processExited ? Effect.void : refreshDescendants)).pipe(
16301650 Effect.andThen(Queue.shutdown(promptQueue)),
16311651 Effect.andThen(closeClaudeQuery(queryRuntime)),
16321652 Effect.tap(() =>
0 commit comments