@maheidem/pi-delegate 0.1.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.
package/runner.ts ADDED
@@ -0,0 +1,771 @@
1
+ /**
2
+ * delegate — child process + RPC lifecycle for one foreground run.
3
+ *
4
+ * Owns exactly one child `pi` process per run (FR-007, POL-007): owned,
5
+ * tracked, killable; never detached or unref'd. The task travels over RPC
6
+ * stdin, never argv (POL-004). The full stdout capture and stderr stay on
7
+ * disk; only a bounded handoff + diagnostics return to the caller
8
+ * (FR-013/FR-014).
9
+ */
10
+
11
+ import * as childProcess from "node:child_process";
12
+ import * as fs from "node:fs";
13
+ import * as path from "node:path";
14
+ import type {
15
+ DelegateDisplayItem,
16
+ DelegateError,
17
+ DelegateErrorCode,
18
+ DelegateRole,
19
+ DelegateUsage,
20
+ RunState,
21
+ RunTerminalState,
22
+ RunHooks,
23
+ RunnerOutcome,
24
+ } from "./types.ts";
25
+ import { EMPTY_USAGE } from "./types.ts";
26
+ import { classifyRpcRecord, RpcJsonlParser, type RpcRecord } from "./rpc-jsonl.ts";
27
+ import { appendTranscriptRecord, updateRunMetadata, type OpenedRun } from "./run-store.ts";
28
+
29
+ export interface RunnerConfig {
30
+ maxResultBytes: number;
31
+ inactivityTimeoutMs: number;
32
+ hardTimeoutMs: number;
33
+ killGraceMs: number;
34
+ updateThrottleMs: number;
35
+ maxRecordBytes?: number;
36
+ malformedThreshold?: number;
37
+ }
38
+
39
+ export type PiInvocationResolver = (piPath?: string) => {
40
+ command: string;
41
+ args: string[];
42
+ };
43
+
44
+ /**
45
+ * Robust Pi executable resolution (official example pattern, §9.4):
46
+ * 1. current Pi script path (argv[1]) exists → node/bun + that script;
47
+ * 2. compiled executable → execPath directly;
48
+ * 3. otherwise `pi` on PATH.
49
+ */
50
+ export function resolvePiInvocation(piPath?: string): { command: string; args: string[] } {
51
+ const explicit = piPath && fs.existsSync(piPath) ? piPath : undefined;
52
+ const argv1 = process.argv[1];
53
+ const scriptPath = explicit ?? (argv1 && fs.existsSync(argv1) ? argv1 : undefined);
54
+ if (scriptPath) {
55
+ return { command: process.execPath, args: [scriptPath] };
56
+ }
57
+ const base = path.basename(process.execPath).toLowerCase();
58
+ if (base.startsWith("pi") || (process.platform === "darwin" && base === "pi")) {
59
+ return { command: process.execPath, args: [] };
60
+ }
61
+ return { command: "pi", args: [] };
62
+ }
63
+
64
+ export interface RunnerSpawnRequest {
65
+ agentDir: string;
66
+ role: DelegateRole;
67
+ task: string;
68
+ runId: string;
69
+ parentModel: string;
70
+ thinkingLevel?: string;
71
+ cwd: string;
72
+ projectTrusted: boolean;
73
+ /** Registered tool names in the parent process (for role ceiling preflight). */
74
+ registeredTools: readonly string[];
75
+ }
76
+
77
+ export function buildChildArgs(
78
+ req: RunnerSpawnRequest,
79
+ role: DelegateRole,
80
+ ): { args: string[]; env: NodeJS.ProcessEnv; promptId: string } {
81
+ const toolList = role.tools.join(",");
82
+ const args: string[] = [
83
+ "--mode", "rpc",
84
+ "--no-session",
85
+ "--model", req.parentModel,
86
+ ];
87
+ if (req.thinkingLevel) args.push("--thinking", req.thinkingLevel);
88
+ args.push("--tools", toolList);
89
+ args.push("--no-skills", "--no-prompt-templates", "--no-themes");
90
+ args.push("--append-system-prompt", role.promptPath);
91
+ args.push(req.projectTrusted ? "--approve" : "--no-approve");
92
+ const env: NodeJS.ProcessEnv = {
93
+ ...process.env,
94
+ PI_DELEGATE_CHILD: "1",
95
+ PI_DELEGATE_RUN_ID: req.runId,
96
+ PI_DELEGATE_PARENT_PID: String(process.pid),
97
+ };
98
+ return { args, env, promptId: `delegate:${req.runId}:prompt` };
99
+ }
100
+
101
+ function buildPromptMessage(runId: string, role: string, task: string): string {
102
+ return (
103
+ `[delegated child run · id=${runId} · role=${role}]\n` +
104
+ `This task came from a parent Pi session. Work only on this task.\n` +
105
+ `Do not delegate or attempt to contact the parent during execution.\n` +
106
+ `Follow the role output contract exactly.\n\n` +
107
+ `<delegated-task>\n${task}\n</delegated-task>`
108
+ );
109
+ }
110
+
111
+ /**
112
+ * UTF-8-safe bounded handoff: deterministic 75% head / 25% tail split with
113
+ * an omission marker so both the outcome and trailing risks survive
114
+ * (NFR-004, §9.10).
115
+ */
116
+ export function truncateHandoff(text: string, maxBytes: number): { text: string; truncated: boolean } {
117
+ const buf = Buffer.from(text, "utf8");
118
+ if (buf.length <= maxBytes) return { text, truncated: false };
119
+ if (maxBytes < 64) {
120
+ // Extremely small budget: safe head-only cut.
121
+ const head = safeHead(buf, maxBytes);
122
+ return { text: `${head}\n… [delegate: truncated]`, truncated: true };
123
+ }
124
+ const headBytes = Math.floor(maxBytes * 0.75);
125
+ const tailBytes = Math.floor(maxBytes * 0.25);
126
+ const marker = "\n… [delegate: output truncated — middle omitted] …\n";
127
+ const markerBytes = Buffer.byteLength(marker, "utf8");
128
+ const head = safeHead(buf, headBytes);
129
+ const tail = safeTail(buf, tailBytes - markerBytes - head.length);
130
+ return { text: `${head}${marker}${tail}`, truncated: true };
131
+ }
132
+
133
+ function safeHead(buf: Buffer, maxBytes: number): string {
134
+ let end = Math.min(maxBytes, buf.length);
135
+ while (end > 0 && (buf[end] & 0xc0) === 0x80) end--; // back off continuation bytes
136
+ return buf.subarray(0, end).toString("utf8");
137
+ }
138
+
139
+ function safeTail(buf: Buffer, maxBytes: number): string {
140
+ if (maxBytes <= 0) return "";
141
+ let start = Math.max(0, buf.length - maxBytes);
142
+ while (start < buf.length && (buf[start] & 0xc0) === 0x80) start++; // skip continuation bytes
143
+ return buf.subarray(start).toString("utf8");
144
+ }
145
+
146
+ function displaySafeArgValue(value: unknown, limit = 80): string {
147
+ try {
148
+ const text = typeof value === "string" ? value : JSON.stringify(value);
149
+ return (text ?? "").slice(0, limit);
150
+ } catch {
151
+ return "?";
152
+ }
153
+ }
154
+
155
+ interface AssistantFinal {
156
+ text: string;
157
+ stopReason?: string;
158
+ usage: DelegateUsage;
159
+ }
160
+
161
+ function aggregateUsage(acc: DelegateUsage, usage: unknown): void {
162
+ if (!usage || typeof usage !== "object") return;
163
+ const u = usage as Record<string, unknown>;
164
+ const num = (v: unknown): number => (typeof v === "number" && Number.isFinite(v) ? v : 0);
165
+ acc.input += num(u.input);
166
+ acc.output += num(u.output);
167
+ acc.cacheRead += num(u.cacheRead);
168
+ acc.cacheWrite += num(u.cacheWrite);
169
+ acc.contextTokens = num(u.totalTokens) || acc.contextTokens;
170
+ const cost = u.cost as Record<string, unknown> | undefined;
171
+ const total =
172
+ typeof cost?.total === "number" ? num(cost.total) :
173
+ num(u.cost) || 0;
174
+ acc.cost = Math.max(acc.cost, total);
175
+ }
176
+
177
+ export class DelegateRunner {
178
+ private child: childProcess.ChildProcess | null = null;
179
+ private readonly opened: OpenedRun;
180
+ private readonly req: RunnerSpawnRequest;
181
+ private readonly cfg: RunnerConfig;
182
+ private readonly resolveInvocation: PiInvocationResolver;
183
+ private readonly hooks: RunHooks;
184
+
185
+ private parser: RpcJsonlParser;
186
+ private finalizing = false;
187
+ private cancelRequested: RunTerminalState | null = null;
188
+ private cancelledByUser = false;
189
+ private promptAccepted = false;
190
+ private settled = false;
191
+ private lastAssistant: AssistantFinal | null = null;
192
+ private usage: DelegateUsage = { ...EMPTY_USAGE };
193
+ private turns = 0;
194
+ private exitCode: number | null = null;
195
+ private startedAt = "";
196
+ private startedAtMs = 0;
197
+ private inactivityTimer: NodeJS.Timeout | null = null;
198
+ private hardTimer: NodeJS.Timeout | null = null;
199
+ private killGraceTimer: NodeJS.Timeout | null = null;
200
+ private settleExitTimer: NodeJS.Timeout | null = null;
201
+ private reapEscalateTimer: NodeJS.Timeout | null = null;
202
+ private reapKillTimer: NodeJS.Timeout | null = null;
203
+ private childReaped = false;
204
+ private finalError: DelegateError | null = null;
205
+ private lastUpdateSent = 0;
206
+ private lastActions: string[] = [];
207
+ private diagnosticNotes: string[] = [];
208
+ private readonly listeners: Array<{ remove: () => void }> = [];
209
+ private transcriptSeq = 0;
210
+ private readonly promptId: string;
211
+
212
+ constructor(opened: OpenedRun, req: RunnerSpawnRequest, cfg: RunnerConfig, hooks: RunHooks = {}, resolveInvocation?: PiInvocationResolver) {
213
+ this.opened = opened;
214
+ this.req = req;
215
+ this.cfg = cfg;
216
+ this.hooks = hooks;
217
+ this.resolveInvocation = resolveInvocation ?? resolvePiInvocation;
218
+ this.promptId = `delegate:${opened.metadata.runId}:prompt`;
219
+ this.parser = new RpcJsonlParser({
220
+ maxRecordBytes: cfg.maxRecordBytes,
221
+ malformedThreshold: cfg.malformedThreshold,
222
+ });
223
+ }
224
+
225
+ get runId(): string {
226
+ return this.opened.metadata.runId;
227
+ }
228
+
229
+ get childPid(): number | undefined {
230
+ return this.child?.pid;
231
+ }
232
+
233
+ /** Spawn and drive the run to a terminal state. */
234
+ async run(): Promise<RunnerOutcome> {
235
+ const { metadata, paths, stdout, stderr } = this.opened;
236
+ const role = this.req.role;
237
+
238
+ // Preflight: research role requires a Firecrawl-capable path.
239
+ if (role.name === "research") {
240
+ const hasFirecrawl =
241
+ this.req.registeredTools.some((t) =>
242
+ t === "mcp__firecrawl" || (t.startsWith("mcp__") && /firecrawl/i.test(t)),
243
+ ) ||
244
+ this.req.registeredTools.includes("mcp");
245
+ if (!hasFirecrawl) {
246
+ this.finish("failed", {
247
+ code: "E_RESEARCH_TOOLS",
248
+ message: "No Firecrawl-capable research tool path is available in this parent session.",
249
+ });
250
+ return this.outcome("failed");
251
+ }
252
+ }
253
+
254
+ const invocation = this.resolveInvocation();
255
+ const { args, env } = buildChildArgs(this.req, role);
256
+ const launchArgs = [...invocation.args, ...args];
257
+
258
+ let child: childProcess.ChildProcess;
259
+ try {
260
+ child = childProcess.spawn(invocation.command, launchArgs, {
261
+ cwd: this.req.cwd,
262
+ env,
263
+ stdio: ["pipe", "pipe", "pipe"],
264
+ shell: false,
265
+ detached: false,
266
+ });
267
+ } catch (error) {
268
+ this.finish("failed", {
269
+ code: "E_SPAWN",
270
+ message: `Could not start child Pi process: ${(error as Error).message}`,
271
+ });
272
+ return this.outcome("failed");
273
+ }
274
+ this.child = child;
275
+ this.startedAt = new Date().toISOString();
276
+ this.startedAtMs = Date.now();
277
+ this.updateMetadata({ state: "starting", pid: child.pid, startedAt: this.startedAt });
278
+
279
+ // Wire streams BEFORE the prompt; stdout records are captured raw first.
280
+ child.stdout?.on("data", (chunk: Buffer) => this.onStdout(chunk));
281
+ this.listeners.push({ remove: () => child.stdout?.off("data", () => {}) });
282
+
283
+ const onStderr = (chunk: Buffer) => {
284
+ try {
285
+ const fd = (stderr as unknown as { fd: number | null }).fd;
286
+ if (typeof fd === "number") fs.appendFileSync(fd, chunk);
287
+ else stderr.write(chunk);
288
+ } catch {
289
+ // ignore
290
+ }
291
+ this.noteActivity();
292
+ };
293
+ child.stderr?.on("data", onStderr);
294
+
295
+ child.on("error", (error) => {
296
+ if (!this.finalizing) {
297
+ this.finish("failed", {
298
+ code: "E_SPAWN",
299
+ message: `Child process error: ${error.message}`,
300
+ });
301
+ }
302
+ });
303
+
304
+ child.on("exit", (code, signal) => {
305
+ this.exitCode = code ?? (signal ? 1 : 0);
306
+ this.finalizeOnExit();
307
+ });
308
+
309
+ // AbortSignal from the tool call.
310
+ if (this.hooks.abortSignal) {
311
+ const onAbort = () => this.cancel(this.hooks.abortSignal?.reason === "abort" ? "cancelled" : "cancelled");
312
+ if (this.hooks.abortSignal.aborted) onAbort();
313
+ else this.hooks.abortSignal.addEventListener("abort", onAbort, { once: true });
314
+ }
315
+
316
+ // Timers: inactivity (reset by activity) + hard (from spawn).
317
+ this.armInactivity();
318
+ this.hardTimer = setTimeout(() => this.cancel("timed_out_hard"), this.cfg.hardTimeoutMs);
319
+ this.hardTimer.unref();
320
+
321
+ // Send the single prompt over RPC stdin.
322
+ const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task);
323
+ const promptRecord = JSON.stringify({ id: this.promptId, type: "prompt", message: promptMessage });
324
+ try {
325
+ child.stdin?.write(`${promptRecord}\n`);
326
+ } catch (error) {
327
+ this.finish("failed", {
328
+ code: "E_RPC_PROMPT_REJECTED",
329
+ message: `Could not write prompt to child stdin: ${(error as Error).message}`,
330
+ });
331
+ }
332
+
333
+ return await new Promise<RunnerOutcome>((resolve) => {
334
+ this.settledResolver = resolve;
335
+ });
336
+ }
337
+
338
+ private settledResolver: ((outcome: RunnerOutcome) => void) | null = null;
339
+
340
+ private onStdout(chunk: Buffer): void {
341
+ this.noteActivity();
342
+ const records = this.parser.feed(chunk);
343
+ for (const record of records) this.handleRecord(record);
344
+ }
345
+
346
+
347
+ private noteActivity(): void {
348
+ this.armInactivity();
349
+ }
350
+
351
+ private armInactivity(): void {
352
+ if (this.finalizing || !this.child) return;
353
+ if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
354
+ this.inactivityTimer = setTimeout(() => this.cancel("timed_out_idle"), this.cfg.inactivityTimeoutMs);
355
+ this.inactivityTimer.unref();
356
+ }
357
+
358
+ private handleRecord(record: RpcRecord): void {
359
+ // Persist raw record losslessly BEFORE semantic processing.
360
+ try {
361
+ appendTranscriptRecord(
362
+ this.opened.stdout,
363
+ this.transcriptSeq++,
364
+ new Date().toISOString(),
365
+ record.raw,
366
+ );
367
+ } catch {
368
+ // capture failure is a warning, not a run failure
369
+ }
370
+ if (this.parser.oversized) {
371
+ this.finish("failed", {
372
+ code: "E_RPC_PROTOCOL",
373
+ message: "Child emitted an RPC record above the maximum size.",
374
+ });
375
+ return;
376
+ }
377
+ if (this.parser.exceededMalformedThreshold) {
378
+ this.finish("failed", {
379
+ code: "E_RPC_PROTOCOL",
380
+ message: `Child RPC stream exceeded the malformed-record threshold (${this.parser.malformedRecords} malformed records).`,
381
+ });
382
+ return;
383
+ }
384
+ if (record.malformed) {
385
+ this.diagnosticNotes.push(`malformed RPC record captured (index ${this.parser.malformedRecords})`);
386
+ return;
387
+ }
388
+ const cls = classifyRpcRecord(record);
389
+ switch (cls.kind) {
390
+ case "prompt_response":
391
+ if (cls.id === this.promptId || cls.id === "") {
392
+ if (cls.ok) {
393
+ this.promptAccepted = true;
394
+ this.updateMetadata({ state: "running" });
395
+ this.pushUpdate("running");
396
+ } else {
397
+ this.finish("failed", {
398
+ code: "E_RPC_PROMPT_REJECTED",
399
+ message: "Child rejected the prompt command.",
400
+ });
401
+ }
402
+ }
403
+ break;
404
+ case "message_end": {
405
+ const message = (record.parsed as { message?: unknown }).message;
406
+ this.ingestMessage(message, cls.stopReason);
407
+ break;
408
+ }
409
+ case "tool_event":
410
+ if (cls.phase === "start" && cls.toolName) {
411
+ this.pushAction(`tool ${cls.toolName}`);
412
+ this.pushUpdate(`tool:${cls.toolName}`);
413
+ }
414
+ break;
415
+ case "agent_settled":
416
+ this.settled = true;
417
+ this.finalizeSettled();
418
+ break;
419
+ case "agent_end":
420
+ // NOT a completion signal: retries/compaction may follow.
421
+ break;
422
+ case "extension_ui_request":
423
+ // Auto-cancel to prevent headless deadlock.
424
+ try {
425
+ this.child?.stdin?.write(
426
+ `${JSON.stringify({ type: "extension_ui_response", id: cls.id, cancelled: true })}\n`,
427
+ );
428
+ } catch {
429
+ // ignore
430
+ }
431
+ break;
432
+ case "extension_error":
433
+ this.diagnosticNotes.push("child extension_error observed");
434
+ break;
435
+ default:
436
+ // Unknown valid events are persisted (already) and ignored.
437
+ break;
438
+ }
439
+ }
440
+
441
+ private ingestMessage(message: unknown, stopReason?: string): void {
442
+ if (!message || typeof message !== "object") return;
443
+ const m = message as Record<string, unknown>;
444
+ if (m.role !== "assistant") return;
445
+ this.turns += 1;
446
+ if (m.usage) aggregateUsage(this.usage, m.usage);
447
+ const blocks = Array.isArray(m.content) ? (m.content as Array<Record<string, unknown>>) : [];
448
+ const text = blocks
449
+ .filter((b) => b?.type === "text" && typeof b.text === "string")
450
+ .map((b) => b.text as string)
451
+ .join("\n\n");
452
+ const reason =
453
+ typeof m.stopReason === "string" ? m.stopReason : stopReason;
454
+ this.lastAssistant = {
455
+ text,
456
+ stopReason: reason,
457
+ usage: { ...this.usage },
458
+ };
459
+ }
460
+
461
+ /**
462
+ * One idempotent cancel path (§9.11): mark → RPC abort → 2 s → SIGTERM →
463
+ * grace (5 s default via killGraceMs) → SIGKILL. Finalizes metadata once
464
+ * and removes all listeners/timers.
465
+ */
466
+ cancel(state: RunTerminalState): void {
467
+ if (this.finalizing) return;
468
+ // §9.7 — the FIRST cancellation wins; later cancels are no-ops.
469
+ if (this.cancelRequested) return;
470
+ const byUser = state === "cancelled";
471
+ if (byUser) this.cancelledByUser = true;
472
+ this.cancelRequested = state;
473
+ const child = this.child;
474
+ if (!child) {
475
+ this.finish(state);
476
+ return;
477
+ }
478
+ if (child.stdin?.writable) {
479
+ try {
480
+ child.stdin.write(`${JSON.stringify({ type: "abort" })}\n`);
481
+ } catch {
482
+ // fall through to signals
483
+ }
484
+ }
485
+ setTimeout(() => {
486
+ if (this.finalizing || !this.child?.kill) return;
487
+ try {
488
+ this.child.kill("SIGTERM");
489
+ } catch {
490
+ // ignore
491
+ }
492
+ this.killGraceTimer = setTimeout(() => {
493
+ if (this.finalizing || !this.child?.kill) return;
494
+ try {
495
+ this.child.kill("SIGKILL");
496
+ } catch {
497
+ // ignore
498
+ }
499
+ }, this.cfg.killGraceMs);
500
+ }, 2000);
501
+ // If the child never exits, the kill path above plus the exit handler
502
+ // covers it; the hard timer is already armed as a last backstop.
503
+ }
504
+
505
+ private finalizeSettled(): void {
506
+ if (this.finalizing) return;
507
+ // A cancellation is already finalizing via the exit path (§9.7) — an
508
+ // aborted turn legitimately has no final text and must not overwrite
509
+ // the cancellation with E_NO_HANDOFF.
510
+ if (this.cancelRequested) return;
511
+ const child = this.child;
512
+ const final = this.lastAssistant;
513
+ if (final?.stopReason === "aborted") {
514
+ this.finish("cancelled");
515
+ return;
516
+ }
517
+ if (final?.stopReason === "error") {
518
+ this.finish("failed", {
519
+ code: "E_CHILD_MODEL",
520
+ message: `Child model stopped with an error (stderr tail: ${this.stderrTail()})`,
521
+ });
522
+ return;
523
+ }
524
+ if (!final || !final.text.trim()) {
525
+ this.finish("failed", {
526
+ code: "E_NO_HANDOFF",
527
+ message: "Child settled without a final assistant text message.",
528
+ });
529
+ return;
530
+ }
531
+ const { text: handoff, truncated } = truncateHandoff(final.text, this.cfg.maxResultBytes);
532
+ this.finish("succeeded", undefined, { handoff, truncated, stopReason: final.stopReason, usage: { ...final.usage, turns: this.turns } });
533
+ // End stdin and wait briefly for clean exit; if the RPC host remains
534
+ // alive, SIGTERM then SIGKILL. This never turns success into failure.
535
+ if (child) {
536
+ try {
537
+ child.stdin?.end();
538
+ } catch {
539
+ // ignore
540
+ }
541
+ this.settleExitTimer = setTimeout(() => {
542
+ if (this.finalizing || !this.child?.kill) return;
543
+ try {
544
+ this.child.kill("SIGTERM");
545
+ } catch {
546
+ // ignore
547
+ }
548
+ this.killGraceTimer = setTimeout(() => {
549
+ if (this.finalizing || !this.child?.kill) return;
550
+ try {
551
+ this.child.kill("SIGKILL");
552
+ } catch {
553
+ // ignore
554
+ }
555
+ }, this.cfg.killGraceMs);
556
+ }, 1500);
557
+ }
558
+ }
559
+
560
+ private finalizeOnExit(): void {
561
+ // Flush any incomplete final record into the capture.
562
+ try {
563
+ for (const record of this.parser.close()) {
564
+ appendTranscriptRecord(this.opened.stdout, this.transcriptSeq++, new Date().toISOString(), record.raw);
565
+ }
566
+ } catch {
567
+ // ignore
568
+ }
569
+ if (this.finalizing) {
570
+ this.cleanup();
571
+ return;
572
+ }
573
+ if (this.cancelRequested) {
574
+ this.finish(this.cancelRequested);
575
+ return;
576
+ }
577
+ if (!this.settled && !this.promptAccepted) {
578
+ this.finish("crashed", {
579
+ code: "E_CHILD_EXIT",
580
+ message: `Child exited before accepting the prompt (exit ${this.exitCode}). ${this.stderrTail()}`,
581
+ });
582
+ return;
583
+ }
584
+ if (!this.settled) {
585
+ this.finish("crashed", {
586
+ code: "E_CHILD_EXIT",
587
+ message: `Child exited before settling (exit ${this.exitCode}). ${this.stderrTail()}`,
588
+ });
589
+ }
590
+ }
591
+
592
+ private stderrTail(limit = 400): string {
593
+ try {
594
+ const buf = fs.readFileSync(this.opened.paths.stderrPath);
595
+ return buf.length === 0 ? "" : buf.subarray(-limit).toString("utf8").trim().slice(-300);
596
+ } catch {
597
+ return "";
598
+ }
599
+ }
600
+
601
+ private finish(state: RunTerminalState, error?: DelegateError, extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage }): void {
602
+ if (this.finalizing) return;
603
+ this.finalizing = true;
604
+ const finishedAt = new Date().toISOString();
605
+ const durationMs = this.startedAtMs ? Date.now() - this.startedAtMs : 0;
606
+ this.finalError = error ?? this.finalError;
607
+ const usage = { ...(extra?.usage ?? this.usage), turns: this.turns };
608
+ const metadataPatch: Record<string, unknown> = {
609
+ state,
610
+ finishedAt,
611
+ exitCode: this.exitCode ?? undefined,
612
+ usage,
613
+ outputTruncated: extra?.truncated ?? false,
614
+ };
615
+ if (extra?.handoff !== undefined) {
616
+ metadataPatch.finalHandoff = extra.handoff;
617
+ metadataPatch.outputBytes = Buffer.byteLength(extra.handoff, "utf8");
618
+ }
619
+ if (extra?.stopReason) metadataPatch.stopReason = extra.stopReason;
620
+ if (error) {
621
+ metadataPatch.errorCode = error.code;
622
+ metadataPatch.errorMessage = error.message;
623
+ }
624
+ if (this.diagnosticNotes.length > 0) {
625
+ metadataPatch.errorMessage = metadataPatch.errorMessage
626
+ ? `${metadataPatch.errorMessage} [${this.diagnosticNotes.slice(-3).join("; ")}]`
627
+ : `[${this.diagnosticNotes.slice(-3).join("; ")}]`;
628
+ }
629
+ try {
630
+ updateRunMetadata(this.req.agentDir, this.runId, () => metadataPatch);
631
+ } catch {
632
+ // metadata write failure is diagnostic-only at finalization
633
+ }
634
+ try {
635
+ this.opened.stdout.end();
636
+ this.opened.stderr.end();
637
+ } catch {
638
+ // ignore
639
+ }
640
+ // §9 — every finalization MUST reap the child exactly once. Protocol
641
+ // failures finalize without an exit event; without this the child
642
+ // would orphan and keep parent pipes open.
643
+ this.reapChild();
644
+ this.cleanup();
645
+
646
+ const outcome = this.outcome(state, extra, error);
647
+ const resolver = this.settledResolver;
648
+ this.settledResolver = null;
649
+ resolver?.(outcome);
650
+ }
651
+
652
+ private outcome(
653
+ state: RunTerminalState,
654
+ extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage },
655
+ error?: DelegateError,
656
+ ): RunnerOutcome {
657
+ const finishedAt = new Date().toISOString();
658
+ const err = error ?? this.finalError ?? undefined;
659
+ return {
660
+ runId: this.runId,
661
+ state,
662
+ handoff: state === "succeeded" ? extra?.handoff ?? "" : "",
663
+ outputBytes: Buffer.byteLength(extra?.handoff ?? "", "utf8"),
664
+ outputTruncated: extra?.truncated ?? false,
665
+ startedAt: this.startedAt,
666
+ finishedAt,
667
+ durationMs: this.startedAtMs ? Date.now() - this.startedAtMs : 0,
668
+ exitCode: this.exitCode ?? undefined,
669
+ stopReason: extra?.stopReason,
670
+ usage: { ...(extra?.usage ?? this.usage), turns: this.turns },
671
+ displayItems: this.lastActions.slice(-5).map((a) => ({
672
+ type: "text" as const,
673
+ text: a,
674
+ })),
675
+ error: err,
676
+ transcriptPath: this.opened.paths.transcriptPath,
677
+ stderrPath: this.opened.paths.stderrPath,
678
+ lastActions: this.lastActions.slice(-5),
679
+ };
680
+ }
681
+
682
+ private updateMetadata(patch: Record<string, unknown>): void {
683
+ try {
684
+ updateRunMetadata(this.req.agentDir, this.runId, () => patch);
685
+ } catch {
686
+ // transition metadata failure is diagnostic-only
687
+ }
688
+ }
689
+
690
+ private pushAction(action: string): void {
691
+ this.lastActions.push(action);
692
+ if (this.lastActions.length > 10) this.lastActions.shift();
693
+ }
694
+
695
+ private pushUpdate(phase: "starting" | "running" | `tool:${string}` | "finalizing"): void {
696
+ if (!this.hooks.onUpdate) return;
697
+ const now = Date.now();
698
+ if (now - this.lastUpdateSent < this.cfg.updateThrottleMs) return;
699
+ this.lastUpdateSent = now;
700
+ this.hooks.onUpdate({
701
+ runId: this.runId,
702
+ role: this.req.role.name,
703
+ phase,
704
+ elapsedMs: this.startedAtMs ? now - this.startedAtMs : 0,
705
+ lastActions: this.lastActions.slice(-5),
706
+ usage: { ...this.usage, turns: this.turns },
707
+ });
708
+ }
709
+
710
+ /**
711
+ * Guaranteed one-shot reaping: RPC abort, then SIGTERM, then SIGKILL
712
+ * after the grace window. Never orphans the child; failures are
713
+ * swallowed (reaping must never change the run outcome).
714
+ */
715
+ private reapChild(): void {
716
+ const child = this.child;
717
+ if (!child || this.childReaped || child.exitCode !== null || child.signalCode) return;
718
+ this.childReaped = true;
719
+ try {
720
+ if (child.stdin?.writable) child.stdin.write(`${JSON.stringify({ type: "abort" })}\n`);
721
+ child.stdin?.end();
722
+ } catch {
723
+ // ignore
724
+ }
725
+ this.reapEscalateTimer = setTimeout(() => {
726
+ try {
727
+ child.kill("SIGTERM");
728
+ } catch {
729
+ // ignore
730
+ }
731
+ this.reapKillTimer = setTimeout(() => {
732
+ try {
733
+ child.kill("SIGKILL");
734
+ } catch {
735
+ // ignore
736
+ }
737
+ }, this.cfg.killGraceMs);
738
+ }, 250);
739
+ }
740
+
741
+ private cleanup(): void {
742
+ // NOTE: reap timers intentionally survive cleanup — they must run to
743
+ // completion to guarantee the child is killed (short-lived refs).
744
+ if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
745
+ if (this.hardTimer) clearTimeout(this.hardTimer);
746
+ if (this.killGraceTimer) clearTimeout(this.killGraceTimer);
747
+ if (this.settleExitTimer) clearTimeout(this.settleExitTimer);
748
+ this.inactivityTimer = null;
749
+ this.hardTimer = null;
750
+ this.killGraceTimer = null;
751
+ this.settleExitTimer = null;
752
+ for (const { remove } of this.listeners) {
753
+ try {
754
+ remove();
755
+ } catch {
756
+ // ignore
757
+ }
758
+ }
759
+ this.listeners.length = 0;
760
+ const child = this.child;
761
+ if (child) {
762
+ try {
763
+ child.stdout?.removeAllListeners();
764
+ child.stderr?.removeAllListeners();
765
+ child.removeAllListeners();
766
+ } catch {
767
+ // ignore
768
+ }
769
+ }
770
+ }
771
+ }