@zew1me/pi-subagents 0.0.0-stage → 0.1.0-alpha.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,845 @@
1
+ import { execFile, execFileSync, spawn } from "node:child_process";
2
+ import type { ChildProcessWithoutNullStreams } from "node:child_process";
3
+ import { StringDecoder } from "node:string_decoder";
4
+ import { extractTextContent, appendBoundedTail } from "./helpers.ts";
5
+ import type { ContextMode, ThinkingLevel } from "./helpers.ts";
6
+
7
+ const MAX_JSONL_LINE_BYTES = 16 * 1024 * 1024;
8
+ const MAX_TRANSCRIPT_CHARS = 120_000;
9
+ const MAX_STDERR_CHARS = 64_000;
10
+ const REQUEST_TIMEOUT_MS = 30_000;
11
+ const FORCE_KILL_DELAY_MS = 3_000;
12
+ const TERMINAL_CLEANUP_TIMEOUT_MS = 10_000;
13
+
14
+ function processListInvocation(): { command: string; args: string[]; timeout: number } {
15
+ return process.platform === "win32"
16
+ ? {
17
+ command: "powershell.exe",
18
+ args: [
19
+ "-NoProfile",
20
+ "-NonInteractive",
21
+ "-Command",
22
+ "Get-CimInstance Win32_Process | ForEach-Object { '{0} {1}' -f $_.ProcessId,$_.ParentProcessId }",
23
+ ],
24
+ timeout: 3_000,
25
+ }
26
+ : { command: "ps", args: ["-axo", "pid=,ppid="], timeout: 1_000 };
27
+ }
28
+
29
+ function parseProcessTree(rootPid: number, output: string): number[] {
30
+ const children = new Map<number, number[]>();
31
+ for (const line of output.split("\n")) {
32
+ const match = /^(\d+)\s+(\d+)$/.exec(line.trim());
33
+ if (!match) continue;
34
+ const pid = Number(match[1]);
35
+ const ppid = Number(match[2]);
36
+ const siblings = children.get(ppid) ?? [];
37
+ siblings.push(pid);
38
+ children.set(ppid, siblings);
39
+ }
40
+ const result: number[] = [];
41
+ const visit = (pid: number) => {
42
+ for (const child of children.get(pid) ?? []) visit(child);
43
+ result.push(pid);
44
+ };
45
+ visit(rootPid);
46
+ return result;
47
+ }
48
+
49
+ function processTreePids(rootPid: number): number[] {
50
+ try {
51
+ const invocation = processListInvocation();
52
+ const output = execFileSync(invocation.command, invocation.args, {
53
+ encoding: "utf8",
54
+ timeout: invocation.timeout,
55
+ });
56
+ return parseProcessTree(rootPid, output);
57
+ } catch {
58
+ return [rootPid];
59
+ }
60
+ }
61
+
62
+ type TreeWatcher = { rootPid: number; onResult: (pids: number[]) => void };
63
+
64
+ const treeWatchers = new Set<TreeWatcher>();
65
+ let treeSampleTimer: NodeJS.Timeout | undefined;
66
+ let treeSampleInFlight = false;
67
+
68
+ function sampleWatchedTrees(): void {
69
+ if (treeSampleInFlight || treeWatchers.size === 0) return;
70
+ treeSampleInFlight = true;
71
+ const invocation = processListInvocation();
72
+ execFile(
73
+ invocation.command,
74
+ invocation.args,
75
+ {
76
+ encoding: "utf8",
77
+ timeout: invocation.timeout,
78
+ },
79
+ (error, stdout) => {
80
+ treeSampleInFlight = false;
81
+ for (const watcher of treeWatchers) {
82
+ watcher.onResult(error ? [watcher.rootPid] : parseProcessTree(watcher.rootPid, stdout));
83
+ }
84
+ },
85
+ );
86
+ }
87
+
88
+ function watchProcessTree(rootPid: number, onResult: (pids: number[]) => void): () => void {
89
+ const watcher = { rootPid, onResult };
90
+ treeWatchers.add(watcher);
91
+ sampleWatchedTrees();
92
+ if (!treeSampleTimer) {
93
+ treeSampleTimer = setInterval(sampleWatchedTrees, process.platform === "win32" ? 2_000 : 250);
94
+ treeSampleTimer.unref();
95
+ }
96
+ return () => {
97
+ treeWatchers.delete(watcher);
98
+ if (treeWatchers.size === 0 && treeSampleTimer) {
99
+ clearInterval(treeSampleTimer);
100
+ treeSampleTimer = undefined;
101
+ }
102
+ };
103
+ }
104
+
105
+ export type ChildState = "starting" | "running" | "idle" | "interrupting" | "stopped" | "failed";
106
+
107
+ export type ChildLaunchOptions = {
108
+ id: string;
109
+ name: string;
110
+ task: string;
111
+ model: string;
112
+ effort: ThinkingLevel;
113
+ contextSummary: string;
114
+ contextMode?: ContextMode;
115
+ cwd: string;
116
+ command: string;
117
+ args: string[];
118
+ env: NodeJS.ProcessEnv;
119
+ ownsProcessGroup?: boolean;
120
+ classification: "explicit" | "classified" | "fallback";
121
+ classificationRationale?: string;
122
+ };
123
+
124
+ export type ChildSessionStats = {
125
+ tokens: {
126
+ input: number;
127
+ output: number;
128
+ cacheRead: number;
129
+ cacheWrite: number;
130
+ total: number;
131
+ };
132
+ cost: number;
133
+ contextUsage?: {
134
+ tokens: number | null;
135
+ contextWindow: number;
136
+ percent: number | null;
137
+ };
138
+ };
139
+
140
+ function displayString(value: unknown, fallback: string): string {
141
+ return typeof value === "string" ? value : fallback;
142
+ }
143
+
144
+ function finiteNumber(value: unknown, fallback = 0): number {
145
+ return typeof value === "number" && Number.isFinite(value) ? value : fallback;
146
+ }
147
+
148
+ export function parseSessionStats(value: unknown): ChildSessionStats | undefined {
149
+ if (!value || typeof value !== "object" || Array.isArray(value)) return undefined;
150
+ const input = value as Record<string, unknown>;
151
+ if (!input.tokens || typeof input.tokens !== "object" || Array.isArray(input.tokens)) return undefined;
152
+ const rawTokens = input.tokens as Record<string, unknown>;
153
+ const tokens = {
154
+ input: finiteNumber(rawTokens.input),
155
+ output: finiteNumber(rawTokens.output),
156
+ cacheRead: finiteNumber(rawTokens.cacheRead),
157
+ cacheWrite: finiteNumber(rawTokens.cacheWrite),
158
+ total: finiteNumber(rawTokens.total),
159
+ };
160
+ if (tokens.total === 0) tokens.total = tokens.input + tokens.output + tokens.cacheRead + tokens.cacheWrite;
161
+ let contextUsage: ChildSessionStats["contextUsage"];
162
+ if (input.contextUsage && typeof input.contextUsage === "object" && !Array.isArray(input.contextUsage)) {
163
+ const rawContext = input.contextUsage as Record<string, unknown>;
164
+ const contextWindow = finiteNumber(rawContext.contextWindow);
165
+ if (contextWindow > 0) {
166
+ contextUsage = {
167
+ tokens: rawContext.tokens === null ? null : finiteNumber(rawContext.tokens),
168
+ contextWindow,
169
+ percent: rawContext.percent === null ? null : finiteNumber(rawContext.percent),
170
+ };
171
+ }
172
+ }
173
+ return {
174
+ tokens,
175
+ cost: finiteNumber(input.cost),
176
+ ...(contextUsage ? { contextUsage } : {}),
177
+ };
178
+ }
179
+
180
+ export type ChildSnapshot = {
181
+ id: string;
182
+ name: string;
183
+ task: string;
184
+ state: ChildState;
185
+ model: string;
186
+ effort: ThinkingLevel;
187
+ contextMode: ContextMode;
188
+ classification: ChildLaunchOptions["classification"];
189
+ classificationRationale?: string;
190
+ pid?: number;
191
+ startedAt: number;
192
+ updatedAt: number;
193
+ turns: number;
194
+ toolCalls: number;
195
+ currentTool?: { name: string; argsPreview: string; startedAt: number };
196
+ pendingMessages: number;
197
+ compactions: number;
198
+ stats?: ChildSessionStats;
199
+ sessionFile?: string;
200
+ lastAssistantText?: string;
201
+ transcriptTail: string;
202
+ stderr?: string;
203
+ error?: string;
204
+ };
205
+
206
+ export function buildKickoffPrompt(task: string, contextSummary: string): string {
207
+ const compacted = contextSummary.trim();
208
+ return compacted
209
+ ? [
210
+ "Task-targeted compacted context from the requesting session:",
211
+ "<context>",
212
+ compacted,
213
+ "</context>",
214
+ "",
215
+ "Task:",
216
+ task,
217
+ ].join("\n")
218
+ : `Task:\n${task}`;
219
+ }
220
+
221
+ type PendingRequest = {
222
+ command: string;
223
+ resolve: (value: Record<string, unknown>) => void;
224
+ reject: (error: Error) => void;
225
+ timer: NodeJS.Timeout;
226
+ };
227
+
228
+ export class ManagedSubagent {
229
+ readonly id: string;
230
+ readonly name: string;
231
+ readonly task: string;
232
+ readonly model: string;
233
+ readonly effort: ThinkingLevel;
234
+ readonly classification: ChildLaunchOptions["classification"];
235
+ readonly classificationRationale: string | undefined;
236
+ readonly startedAt = Date.now();
237
+
238
+ private readonly proc: ChildProcessWithoutNullStreams;
239
+ private state: ChildState = "starting";
240
+ private updatedAt = Date.now();
241
+ private transcript = "";
242
+ private stderr = "";
243
+ private error: string | undefined;
244
+ private lastAssistantText: string | undefined;
245
+ private sessionFile: string | undefined;
246
+ private pendingMessages = 0;
247
+ private turns = 0;
248
+ private toolCalls = 0;
249
+ private activeTools = new Map<string, NonNullable<ChildSnapshot["currentTool"]>>();
250
+ private compactions = 0;
251
+ private stats: ChildSessionStats | undefined;
252
+ private requestSequence = 0;
253
+ private pending = new Map<string, PendingRequest>();
254
+ private stdoutBytes = 0;
255
+ private stdoutLine = "";
256
+ private stoppedIntentionally = false;
257
+ private terminationStarted = false;
258
+ private killTimer: NodeJS.Timeout | undefined;
259
+ private terminalCleanupTimer: NodeJS.Timeout | undefined;
260
+ private stopTreeMonitor: (() => void) | undefined;
261
+ private terminationPoll: NodeJS.Timeout | undefined;
262
+ private terminationPids: number[] = [];
263
+ private windowsKillersInFlight = 0;
264
+ private terminationDone: Promise<void> = Promise.resolve();
265
+ private resolveTermination: (() => void) | undefined;
266
+ private controlTail: Promise<void> = Promise.resolve();
267
+ private readonly options: ChildLaunchOptions;
268
+
269
+ constructor(options: ChildLaunchOptions) {
270
+ this.options = options;
271
+ this.id = options.id;
272
+ this.name = options.name;
273
+ this.task = options.task;
274
+ this.model = options.model;
275
+ this.effort = options.effort;
276
+ this.classification = options.classification;
277
+ this.classificationRationale = options.classificationRationale;
278
+ this.proc = spawn(options.command, options.args, {
279
+ cwd: options.cwd,
280
+ env: options.env,
281
+ shell: false,
282
+ stdio: ["pipe", "pipe", "pipe"],
283
+ // Root children own a Unix process group for whole-tree cleanup. Nested
284
+ // children stay in that group so a root crash cannot orphan their groups.
285
+ detached: process.platform !== "win32" && options.ownsProcessGroup !== false,
286
+ });
287
+ // spawn() has copied the environment; do not retain runtime credentials in
288
+ // the long-lived management object.
289
+ delete options.env.PI_SIMPLE_SUBAGENT_API_KEY;
290
+ delete options.env.PI_SIMPLE_SUBAGENT_AUTH_PROVIDER;
291
+ this.attachStreams();
292
+ const childPid = this.proc.pid;
293
+ if (childPid) {
294
+ this.stopTreeMonitor = watchProcessTree(childPid, (current) => {
295
+ // Keep only the latest verified tree during normal operation. Once
296
+ // termination begins, freeze it for completion tracking; force-kill uses
297
+ // the Unix process group or a freshly verified descendant tree instead.
298
+ if (!this.terminationStarted) this.terminationPids = current;
299
+ });
300
+ }
301
+ }
302
+
303
+ async start(): Promise<void> {
304
+ await this.request({ type: "prompt", message: buildKickoffPrompt(this.task, this.options.contextSummary) });
305
+ if (this.state === "starting") this.state = "running";
306
+ this.touch();
307
+ }
308
+
309
+ steer(message: string): Promise<void> {
310
+ return this.serializeControl(async () => {
311
+ this.assertControllable();
312
+ if (this.state === "running" || this.state === "interrupting") {
313
+ await this.request({ type: "steer", message });
314
+ } else {
315
+ await this.request({ type: "prompt", message });
316
+ this.state = "running";
317
+ }
318
+ this.touch();
319
+ });
320
+ }
321
+
322
+ followUp(message: string): Promise<void> {
323
+ return this.serializeControl(async () => {
324
+ this.assertControllable();
325
+ if (this.state === "running" || this.state === "interrupting") {
326
+ await this.request({ type: "follow_up", message });
327
+ } else {
328
+ await this.request({ type: "prompt", message });
329
+ this.state = "running";
330
+ }
331
+ this.touch();
332
+ });
333
+ }
334
+
335
+ interrupt(): Promise<void> {
336
+ return this.serializeControl(async () => {
337
+ this.assertControllable();
338
+ if (this.state === "idle") return;
339
+ const previousState = this.state;
340
+ this.state = "interrupting";
341
+ this.touch();
342
+ try {
343
+ await this.request({ type: "abort" });
344
+ // RPC abort is also valid while the session is already settling, in
345
+ // which case no later agent_settled event is guaranteed.
346
+ this.finishInterrupt();
347
+ } catch (error) {
348
+ this.restoreInterrupt(previousState);
349
+ throw error;
350
+ } finally {
351
+ this.touch();
352
+ }
353
+ });
354
+ }
355
+
356
+ refresh(): Promise<void> {
357
+ return this.serializeControl(async () => {
358
+ if (this.state === "stopped" || this.state === "failed") return;
359
+ try {
360
+ const response = await this.request({ type: "get_state" }, 3_000);
361
+ const data = response.data as Record<string, unknown> | undefined;
362
+ if (data) {
363
+ this.pendingMessages =
364
+ typeof data.pendingMessageCount === "number" ? data.pendingMessageCount : this.pendingMessages;
365
+ this.sessionFile = typeof data.sessionFile === "string" ? data.sessionFile : this.sessionFile;
366
+ if (data.isStreaming === true) this.state = "running";
367
+ else if (this.state !== "starting") this.state = "idle";
368
+ }
369
+ } catch {
370
+ // Cached state remains useful if a refresh races process shutdown.
371
+ }
372
+ try {
373
+ const response = await this.request({ type: "get_session_stats" }, 3_000);
374
+ const parsed = parseSessionStats(response.data);
375
+ if (parsed) this.stats = parsed;
376
+ } catch {
377
+ // Older/custom RPC implementations may not expose stats.
378
+ }
379
+ this.touch();
380
+ });
381
+ }
382
+
383
+ waitForIdle(timeoutMs: number, signal?: AbortSignal): Promise<boolean> {
384
+ if (this.isSettled()) return Promise.resolve(true);
385
+ return new Promise((resolve, reject) => {
386
+ let done = false;
387
+ const finish = (settled: boolean) => {
388
+ if (done) return;
389
+ done = true;
390
+ clearInterval(poll);
391
+ clearTimeout(timeout);
392
+ signal?.removeEventListener("abort", onAbort);
393
+ resolve(settled);
394
+ };
395
+ const onAbort = () => {
396
+ if (done) return;
397
+ done = true;
398
+ clearInterval(poll);
399
+ clearTimeout(timeout);
400
+ signal?.removeEventListener("abort", onAbort);
401
+ const error = new Error("Subagent wait was aborted; the child is still running.");
402
+ error.name = "AbortError";
403
+ reject(error);
404
+ };
405
+ const poll = setInterval(() => {
406
+ if (this.isSettled()) finish(true);
407
+ }, 50);
408
+ const timeout = setTimeout(() => {
409
+ finish(this.isSettled());
410
+ }, timeoutMs);
411
+ if (signal?.aborted) onAbort();
412
+ else signal?.addEventListener("abort", onAbort, { once: true });
413
+ });
414
+ }
415
+
416
+ stop(): Promise<void> {
417
+ if (this.state !== "stopped") {
418
+ // Stop is intentionally not queued behind steering/status RPC. It is the
419
+ // authoritative escape hatch and must terminate even if a request hangs.
420
+ this.stoppedIntentionally = true;
421
+ this.state = "stopped";
422
+ this.touch();
423
+ this.rejectPending(new Error(`Subagent ${this.id} was stopped.`));
424
+ this.terminateProcess();
425
+ }
426
+ return this.terminationDone;
427
+ }
428
+
429
+ isAlive(): boolean {
430
+ return this.proc.exitCode === null && this.proc.signalCode === null;
431
+ }
432
+
433
+ snapshot(): ChildSnapshot {
434
+ const currentTool = [...this.activeTools.values()].sort((left, right) => right.startedAt - left.startedAt)[0];
435
+ return {
436
+ id: this.id,
437
+ name: this.name,
438
+ task: this.task,
439
+ state: this.state,
440
+ model: this.model,
441
+ effort: this.effort,
442
+ contextMode: this.options.contextMode ?? "task_compacted",
443
+ classification: this.classification,
444
+ ...(this.classificationRationale ? { classificationRationale: this.classificationRationale } : {}),
445
+ ...(this.proc.pid ? { pid: this.proc.pid } : {}),
446
+ startedAt: this.startedAt,
447
+ updatedAt: this.updatedAt,
448
+ turns: this.turns,
449
+ toolCalls: this.toolCalls,
450
+ ...(currentTool ? { currentTool: { ...currentTool } } : {}),
451
+ pendingMessages: this.pendingMessages,
452
+ compactions: this.compactions,
453
+ ...(this.stats ? { stats: this.stats } : {}),
454
+ ...(this.sessionFile ? { sessionFile: this.sessionFile } : {}),
455
+ ...(this.lastAssistantText ? { lastAssistantText: this.lastAssistantText } : {}),
456
+ transcriptTail: this.transcript,
457
+ ...(this.stderr.trim() ? { stderr: this.stderr.trim() } : {}),
458
+ ...(this.error ? { error: this.error } : {}),
459
+ };
460
+ }
461
+
462
+ private serializeControl<T>(operation: () => Promise<T>): Promise<T> {
463
+ const run = this.controlTail.then(operation, operation);
464
+ this.controlTail = run.then(
465
+ () => undefined,
466
+ () => undefined,
467
+ );
468
+ return run;
469
+ }
470
+
471
+ private isSettled(): boolean {
472
+ return this.state === "failed" || this.state === "stopped" || (this.state === "idle" && this.pendingMessages === 0);
473
+ }
474
+
475
+ private finishInterrupt(): void {
476
+ if (this.state === "interrupting") this.state = "idle";
477
+ }
478
+
479
+ private restoreInterrupt(previousState: ChildState): void {
480
+ if (this.state === "interrupting") this.state = previousState;
481
+ }
482
+
483
+ private assertControllable(): void {
484
+ if (this.state === "stopped" || this.state === "failed") {
485
+ throw new Error(`Subagent ${this.id} is ${this.state} and cannot accept messages.`);
486
+ }
487
+ }
488
+
489
+ private touch(): void {
490
+ this.updatedAt = Date.now();
491
+ }
492
+
493
+ private appendTranscript(text: string): void {
494
+ this.transcript = appendBoundedTail(this.transcript, text, MAX_TRANSCRIPT_CHARS);
495
+ this.touch();
496
+ }
497
+
498
+ // Deliberately a hand-built Promise rather than an `async` function:
499
+ // - The response arrives later via the stdout line handler (matched by request id), and failure can also arrive via
500
+ // the timeout timer, the stdin write callback, or child exit. Those are event/callback sources with no awaitable
501
+ // form, so `new Promise` is the bridge; `async`/`await` would only wrap the same executor in another promise.
502
+ // - The pending entry (resolve/reject/timer) must be registered synchronously, before the write is issued, so a
503
+ // fast response or a synchronous write error always finds it. Request ids stay ordered by call order for the same
504
+ // reason.
505
+ // - Precondition failures use `Promise.reject` so every failure, synchronous or not, surfaces as a rejection and
506
+ // callers never need a separate try/catch for a synchronous throw.
507
+ private request(command: Record<string, unknown>, timeoutMs = REQUEST_TIMEOUT_MS): Promise<Record<string, unknown>> {
508
+ const commandName = String(command.type);
509
+ if (this.proc.stdin.destroyed || this.proc.exitCode !== null) {
510
+ return Promise.reject(this.rpcFailure("write failure", commandName, "the child process is not running"));
511
+ }
512
+ const id = `${this.id}-${String(++this.requestSequence)}`;
513
+ return new Promise((resolve, reject) => {
514
+ const timer = setTimeout(() => {
515
+ this.pending.delete(id);
516
+ reject(this.rpcFailure("timeout", commandName, `no response after ${String(timeoutMs)}ms`));
517
+ }, timeoutMs);
518
+ timer.unref();
519
+ this.pending.set(id, { command: commandName, resolve, reject, timer });
520
+ const onWrite = (error?: Error | null) => {
521
+ if (!error) return;
522
+ const pending = this.pending.get(id);
523
+ if (!pending) return;
524
+ clearTimeout(pending.timer);
525
+ this.pending.delete(id);
526
+ pending.reject(this.rpcFailure("write failure", pending.command, error.message));
527
+ };
528
+ try {
529
+ this.proc.stdin.write(`${JSON.stringify({ id, ...command })}\n`, onWrite);
530
+ } catch (error) {
531
+ onWrite(error instanceof Error ? error : new Error(String(error)));
532
+ }
533
+ });
534
+ }
535
+
536
+ private childDiagnostics(code = this.proc.exitCode, signal = this.proc.signalCode): string {
537
+ const stderr = this.stderr.trim();
538
+ return [
539
+ `child=${this.id}`,
540
+ `pid=${String(this.proc.pid ?? "unknown")}`,
541
+ `model=${this.model}`,
542
+ // A signal-terminated child has a null exit code but is not still running.
543
+ `exitCode=${String(code ?? (signal ? "none" : "pending"))}`,
544
+ `signal=${signal ?? "none"}`,
545
+ ...(stderr ? [`stderr=${JSON.stringify(stderr.slice(-4_000))}`] : []),
546
+ ].join(", ");
547
+ }
548
+
549
+ private rpcFailure(kind: string, command: string, detail: string): Error {
550
+ return new Error(`Subagent RPC ${kind} for ${JSON.stringify(command)}: ${detail} (${this.childDiagnostics()}).`);
551
+ }
552
+
553
+ private processCloseFailure(code: number | null, signal: NodeJS.Signals | null): Error {
554
+ return new Error(`Subagent process closed unexpectedly (${this.childDiagnostics(code, signal)}).`);
555
+ }
556
+
557
+ private attachStreams(): void {
558
+ const decoder = new StringDecoder("utf8");
559
+ let stdoutRejected = false;
560
+ const rejectOversizedOutput = () => {
561
+ stdoutRejected = true;
562
+ this.stdoutLine = "";
563
+ this.stdoutBytes = 0;
564
+ this.proc.stdout.destroy();
565
+ this.fail("Child RPC output exceeded the 16 MiB JSONL line limit.");
566
+ this.terminateProcess();
567
+ };
568
+ this.proc.stdout.on("data", (chunk: Buffer) => {
569
+ if (stdoutRejected) return;
570
+ const text = decoder.write(chunk);
571
+ let start = 0;
572
+ for (;;) {
573
+ const newline = text.indexOf("\n", start);
574
+ if (newline === -1) break;
575
+ const segment = text.slice(start, newline);
576
+ if (this.stdoutBytes + Buffer.byteLength(segment) > MAX_JSONL_LINE_BYTES) {
577
+ rejectOversizedOutput();
578
+ return;
579
+ }
580
+ const combined = this.stdoutLine + segment;
581
+ const line = combined.endsWith("\r") ? combined.slice(0, -1) : combined;
582
+ this.stdoutLine = "";
583
+ this.stdoutBytes = 0;
584
+ if (line) this.handleLine(line);
585
+ start = newline + 1;
586
+ }
587
+ const remainder = text.slice(start);
588
+ this.stdoutLine += remainder;
589
+ this.stdoutBytes += Buffer.byteLength(remainder);
590
+ if (this.stdoutBytes > MAX_JSONL_LINE_BYTES) rejectOversizedOutput();
591
+ });
592
+ this.proc.stdout.on("end", () => {
593
+ if (stdoutRejected) return;
594
+ const final = this.stdoutLine + decoder.end();
595
+ if (final.trim()) this.handleLine(final.endsWith("\r") ? final.slice(0, -1) : final);
596
+ });
597
+ this.proc.stderr.on("data", (chunk: Buffer) => {
598
+ this.stderr = appendBoundedTail(this.stderr, chunk.toString("utf8"), MAX_STDERR_CHARS);
599
+ this.touch();
600
+ });
601
+ this.proc.on("error", (error) => {
602
+ this.fail(`Subagent process error: ${error.message} (${this.childDiagnostics()}).`);
603
+ });
604
+ this.proc.on("close", (code, signal) => {
605
+ this.stopTreeMonitor?.();
606
+ this.stopTreeMonitor = undefined;
607
+ const closeError = this.processCloseFailure(code, signal);
608
+ if (this.stoppedIntentionally) this.state = "stopped";
609
+ else {
610
+ if (this.state !== "failed") this.fail(closeError.message);
611
+ // The root may have crashed while tools or recursively-created children
612
+ // were still alive. Sweep the process tree observed during its lifetime.
613
+ this.terminateProcess();
614
+ }
615
+ this.rejectPending(this.error ? new Error(this.error) : closeError);
616
+ this.touch();
617
+ });
618
+ this.proc.stdin.on("error", () => {
619
+ // Pending requests and process close report actionable errors.
620
+ });
621
+ }
622
+
623
+ // RPC lines may be responses, UI requests, or asynchronous session events.
624
+ // eslint-disable-next-line sonarjs/cognitive-complexity
625
+ private handleLine(line: string): void {
626
+ let parsed: unknown;
627
+ try {
628
+ parsed = JSON.parse(line);
629
+ } catch {
630
+ this.appendTranscript(`\n[rpc parse error] ${line.slice(0, 500)}\n`);
631
+ return;
632
+ }
633
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
634
+ this.appendTranscript(`\n[rpc protocol error] expected an object\n`);
635
+ return;
636
+ }
637
+ const event = parsed as Record<string, unknown>;
638
+ if (event.type === "response" && typeof event.id === "string") {
639
+ const pending = this.pending.get(event.id);
640
+ if (!pending) return;
641
+ clearTimeout(pending.timer);
642
+ this.pending.delete(event.id);
643
+ if (event.success === false)
644
+ pending.reject(new Error(typeof event.error === "string" ? event.error : `${pending.command} failed.`));
645
+ else pending.resolve(event);
646
+ return;
647
+ }
648
+ if (event.type === "extension_ui_request" && typeof event.id === "string") {
649
+ const method = event.method;
650
+ if (method === "select" || method === "confirm" || method === "input" || method === "editor") {
651
+ this.proc.stdin.write(`${JSON.stringify({ type: "extension_ui_response", id: event.id, cancelled: true })}\n`);
652
+ this.appendTranscript(`\n[extension dialog cancelled: ${method}]\n`);
653
+ }
654
+ return;
655
+ }
656
+ this.handleEvent(event);
657
+ }
658
+
659
+ // Keep the wire protocol's event variants visible in one exhaustive dispatcher.
660
+ // eslint-disable-next-line sonarjs/cognitive-complexity
661
+ private handleEvent(event: Record<string, unknown>): void {
662
+ switch (event.type) {
663
+ case "agent_start":
664
+ this.state = "running";
665
+ break;
666
+ case "agent_settled":
667
+ this.activeTools.clear();
668
+ if (this.state !== "failed" && this.state !== "stopped") this.state = "idle";
669
+ break;
670
+ case "turn_end":
671
+ this.turns++;
672
+ break;
673
+ case "queue_update": {
674
+ const steering = Array.isArray(event.steering) ? event.steering.length : 0;
675
+ const followUp = Array.isArray(event.followUp) ? event.followUp.length : 0;
676
+ this.pendingMessages = steering + followUp;
677
+ break;
678
+ }
679
+ case "message_update": {
680
+ const delta = event.assistantMessageEvent as Record<string, unknown> | undefined;
681
+ if (delta?.type === "text_delta" && typeof delta.delta === "string") this.appendTranscript(delta.delta);
682
+ break;
683
+ }
684
+ case "message_end": {
685
+ const message = event.message as Record<string, unknown> | undefined;
686
+ if (message?.role === "assistant") {
687
+ const text = extractTextContent(message.content);
688
+ if (text) this.lastAssistantText = appendBoundedTail("", text, MAX_TRANSCRIPT_CHARS);
689
+ if (message.stopReason === "error") {
690
+ this.fail(
691
+ typeof message.errorMessage === "string" ? message.errorMessage : "Child model returned an error.",
692
+ );
693
+ this.terminateProcess();
694
+ } else if (message.stopReason === "length" && !text.trim()) {
695
+ this.fail("Child model exhausted its output token limit without producing text.");
696
+ this.terminateProcess();
697
+ }
698
+ }
699
+ break;
700
+ }
701
+ case "tool_execution_start": {
702
+ const name = displayString(event.toolName, "tool");
703
+ const argsPreview = JSON.stringify(event.args ?? {}).slice(0, 500);
704
+ const startedAt = Date.now();
705
+ const key =
706
+ typeof event.toolCallId === "string"
707
+ ? event.toolCallId
708
+ : `${name}:${String(startedAt)}:${String(this.toolCalls)}`;
709
+ this.toolCalls++;
710
+ this.activeTools.set(key, { name, argsPreview, startedAt });
711
+ this.appendTranscript(`\n→ ${name} ${argsPreview}\n`);
712
+ break;
713
+ }
714
+ case "tool_execution_end": {
715
+ if (typeof event.toolCallId === "string") this.activeTools.delete(event.toolCallId);
716
+ else {
717
+ const name = displayString(event.toolName, "tool");
718
+ for (const [key, tool] of this.activeTools) {
719
+ if (tool.name === name) this.activeTools.delete(key);
720
+ }
721
+ }
722
+ this.appendTranscript(
723
+ `\n← ${displayString(event.toolName, "tool")}${event.isError === true ? " (error)" : ""}\n`,
724
+ );
725
+ break;
726
+ }
727
+ case "compaction_end":
728
+ if (event.aborted !== true && event.result) this.compactions++;
729
+ break;
730
+ case "extension_error":
731
+ this.appendTranscript(`\n[extension error] ${displayString(event.error, "unknown")}\n`);
732
+ break;
733
+ }
734
+ this.touch();
735
+ }
736
+
737
+ private fail(message: string): void {
738
+ this.state = "failed";
739
+ this.error = message;
740
+ this.touch();
741
+ }
742
+
743
+ private terminateProcess(): void {
744
+ if (this.terminationStarted) return;
745
+ const pid = this.proc.pid;
746
+ if (!pid) return;
747
+ this.terminationStarted = true;
748
+ this.stopTreeMonitor?.();
749
+ this.stopTreeMonitor = undefined;
750
+ this.terminationDone = new Promise((resolve) => {
751
+ this.resolveTermination = resolve;
752
+ });
753
+ this.signalProcessTree("SIGTERM", false);
754
+ const finish = () => {
755
+ if (this.terminationPoll) clearInterval(this.terminationPoll);
756
+ if (this.killTimer) clearTimeout(this.killTimer);
757
+ if (this.terminalCleanupTimer) clearTimeout(this.terminalCleanupTimer);
758
+ this.terminationPoll = undefined;
759
+ this.killTimer = undefined;
760
+ this.terminalCleanupTimer = undefined;
761
+ this.resolveTermination?.();
762
+ this.resolveTermination = undefined;
763
+ };
764
+ this.terminationPoll = setInterval(() => {
765
+ const treeDead = this.terminationPids.every((target) => !this.pidIsAlive(target));
766
+ // SIGTERM can exit the root before the tree snapshot sees a resistant
767
+ // descendant. Keep escalation armed while our owned Unix group exists,
768
+ // even when every sampled PID is gone. Windows has no owned Unix group.
769
+ const ownsGroup = process.platform !== "win32" && this.options.ownsProcessGroup !== false;
770
+ const groupDead = !ownsGroup || !this.pidIsAlive(-pid);
771
+ const windowsDone = process.platform !== "win32" || this.windowsKillersInFlight === 0;
772
+ if (treeDead && groupDead && windowsDone) finish();
773
+ }, 50);
774
+ this.killTimer = setTimeout(() => {
775
+ this.signalProcessTree("SIGKILL", true);
776
+ // Keep polling after escalation until every tracked process is gone and
777
+ // asynchronous Windows taskkill commands have settled. This final bound
778
+ // prevents shutdown from waiting forever on an unkillable process.
779
+ this.terminalCleanupTimer = setTimeout(finish, TERMINAL_CLEANUP_TIMEOUT_MS);
780
+ }, FORCE_KILL_DELAY_MS);
781
+ }
782
+
783
+ private pidIsAlive(pid: number): boolean {
784
+ try {
785
+ process.kill(pid, 0);
786
+ return true;
787
+ } catch (error) {
788
+ // Only ESRCH proves absence. Permission/inspection failures must not
789
+ // cancel escalation; the existing terminal deadline still bounds cleanup.
790
+ return (error as NodeJS.ErrnoException).code !== "ESRCH";
791
+ }
792
+ }
793
+
794
+ private signalProcessTree(signal: NodeJS.Signals, force: boolean): void {
795
+ const pid = this.proc.pid;
796
+ if (!pid) return;
797
+ if (process.platform === "win32") {
798
+ const currentTree = processTreePids(pid);
799
+ this.terminationPids = [...new Set([...this.terminationPids, ...currentTree])];
800
+ // A cached PID may have been reused after SIGTERM. taskkill only targets
801
+ // the root and descendants whose ancestry was verified in this sample.
802
+ for (const target of currentTree) {
803
+ this.windowsKillersInFlight++;
804
+ let settled = false;
805
+ const settle = () => {
806
+ if (settled) return;
807
+ settled = true;
808
+ this.windowsKillersInFlight = Math.max(0, this.windowsKillersInFlight - 1);
809
+ };
810
+ const killer = spawn("taskkill", ["/PID", String(target), "/T", ...(force ? ["/F"] : [])], { stdio: "ignore" });
811
+ killer.on("close", settle);
812
+ killer.on("error", settle);
813
+ killer.unref();
814
+ }
815
+ return;
816
+ }
817
+ if (this.options.ownsProcessGroup !== false) {
818
+ try {
819
+ process.kill(-pid, signal);
820
+ } catch {
821
+ // The group may already be gone; known nested groups are handled below.
822
+ }
823
+ }
824
+ const currentTree = processTreePids(pid);
825
+ if (!force) this.terminationPids = [...new Set([...this.terminationPids, ...currentTree])];
826
+ // The owned process group catches descendants that were reparented when the
827
+ // root exited. Individually signal only freshly verified descendants so a
828
+ // stale cached numeric PID can never receive SIGKILL.
829
+ for (const target of currentTree) {
830
+ try {
831
+ process.kill(target, signal);
832
+ } catch {
833
+ // Continue best-effort through the rest of the tree.
834
+ }
835
+ }
836
+ }
837
+
838
+ private rejectPending(error: Error): void {
839
+ for (const request of this.pending.values()) {
840
+ clearTimeout(request.timer);
841
+ request.reject(error);
842
+ }
843
+ this.pending.clear();
844
+ }
845
+ }