@maheidem/pi-delegate 0.1.4 → 0.2.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 CHANGED
@@ -25,12 +25,22 @@ import type {
25
25
  import { EMPTY_USAGE } from "./types.ts";
26
26
  import { classifyRpcRecord, RpcJsonlParser, type RpcRecord } from "./rpc-jsonl.ts";
27
27
  import { appendTranscriptRecord, updateRunMetadata, type OpenedRun } from "./run-store.ts";
28
+ import { formatDuration } from "./config.ts";
29
+ import { renderHandoff, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
28
30
 
29
31
  export interface RunnerConfig {
30
32
  maxResultBytes: number;
31
33
  inactivityTimeoutMs: number;
32
34
  hardTimeoutMs: number;
33
35
  killGraceMs: number;
36
+ /** R2: grace for the killed child's final handoff answer (default 90 s). */
37
+ handoffGraceMs?: number;
38
+ /** Bounded wait for a child to answer the mandatory-handoff enforcement
39
+ * prompt (default 60 s) — independent of the hard timeout, so a child
40
+ * that goes silent after settling can never dangle the run for hours. */
41
+ handoffEnforceTimeoutMs?: number;
42
+ /** R1: watchdog budget while a tool call is in flight (default: hard). */
43
+ stuckToolTimeoutMs?: number;
34
44
  updateThrottleMs: number;
35
45
  maxRecordBytes?: number;
36
46
  malformedThreshold?: number;
@@ -72,16 +82,31 @@ export interface RunnerSpawnRequest {
72
82
  projectTrusted: boolean;
73
83
  /** Registered tool names in the parent process (for role ceiling preflight). */
74
84
  registeredTools: readonly string[];
85
+ /** R3: prior run whose child session this run resumes ("--session <file>"). */
86
+ resumeOf?: string;
87
+ /** R3: child session file to re-enter (resume mode); new runs use --session-dir. */
88
+ sessionPath?: string;
89
+ /** R3: directory the child's session file is persisted to (new runs). */
90
+ sessionDir?: string;
75
91
  }
76
92
 
77
93
  export function buildChildArgs(
78
94
  req: RunnerSpawnRequest,
79
95
  role: DelegateRole,
80
96
  ): { args: string[]; env: NodeJS.ProcessEnv; promptId: string } {
81
- const toolList = role.tools.join(",");
97
+ // The mandatory structured-handoff tool is always in the child's
98
+ // ceiling; the delegate extension registers it in child mode.
99
+ const toolList = [...role.tools, "handoff"].join(",");
100
+ // R3: the child's session is DURABLE. New runs persist it under the run
101
+ // store (--session-dir); resumed runs re-enter the prior session file
102
+ // directly (--session <file>) so a killed run can be continued in the
103
+ // same context instead of a cold re-explained child.
104
+ const sessionArgs = req.sessionPath
105
+ ? ["--session", req.sessionPath]
106
+ : ["--session-dir", req.sessionDir ?? ".pi-sessions"];
82
107
  const args: string[] = [
83
108
  "--mode", "rpc",
84
- "--no-session",
109
+ ...sessionArgs,
85
110
  "--model", req.parentModel,
86
111
  ];
87
112
  if (req.thinkingLevel) args.push("--thinking", req.thinkingLevel);
@@ -98,9 +123,13 @@ export function buildChildArgs(
98
123
  return { args, env, promptId: `delegate:${req.runId}:prompt` };
99
124
  }
100
125
 
101
- function buildPromptMessage(runId: string, role: string, task: string): string {
126
+ function buildPromptMessage(runId: string, role: string, task: string, resumeOf?: string): string {
127
+ const resumeNote = resumeOf
128
+ ? `You are RESUMING the child session of run ${resumeOf} (its earlier turns are in your context). Continue from where that run left off.\n`
129
+ : "";
102
130
  return (
103
131
  `[delegated child run · id=${runId} · role=${role}]\n` +
132
+ resumeNote +
104
133
  `This task came from a parent Pi session. Work only on this task.\n` +
105
134
  `Do not delegate or attempt to contact the parent during execution.\n` +
106
135
  `Follow the role output contract exactly.\n\n` +
@@ -108,6 +137,26 @@ function buildPromptMessage(runId: string, role: string, task: string): string {
108
137
  );
109
138
  }
110
139
 
140
+ /** R2: the bounded termination-notice prompt a timed-out child must answer
141
+ * through the handoff TOOL (deterministic capture), with a free-text
142
+ * fallback only if the tool path is unavailable in an older child. */
143
+ export function buildHandoffPrompt(runId: string): string {
144
+ return (
145
+ `[delegate ${runId} · termination notice]\n` +
146
+ `You are being terminated NOW. Call the handoff tool IMMEDIATELY with outcome "partial":\n` +
147
+ `- summary: what you completed so far\n` +
148
+ `- changes: every file you created/modified so far\n` +
149
+ `- verification: last test/typecheck state (or not_run)\n` +
150
+ `- remaining: precise next steps for a successor\n` +
151
+ `Do not start new work. If the handoff tool is unavailable, reply in plain text with those four sections.`
152
+ );
153
+ }
154
+
155
+ /** R4: provider-error artifacts produced by our own abort, not the provider. */
156
+ export function isAbortArtifactErrorMessage(message: string): boolean {
157
+ return /this operation was aborted|request was aborted|operation aborted/i.test(message);
158
+ }
159
+
111
160
  /**
112
161
  * UTF-8-safe bounded handoff: deterministic 75% head / 25% tail split with
113
162
  * an omission marker so both the outcome and trailing risks survive
@@ -155,6 +204,8 @@ function displaySafeArgValue(value: unknown, limit = 80): string {
155
204
  interface AssistantFinal {
156
205
  text: string;
157
206
  stopReason?: string;
207
+ /** R4: provider errorMessage captured from the final message_end, verbatim. */
208
+ errorMessage?: string;
158
209
  usage: DelegateUsage;
159
210
  }
160
211
 
@@ -189,6 +240,19 @@ export class DelegateRunner {
189
240
  private promptAccepted = false;
190
241
  private settled = false;
191
242
  private lastAssistant: AssistantFinal | null = null;
243
+ /** R1: toolCallIds with a start but no matching end yet. */
244
+ private openToolCalls = new Set<string>();
245
+ /** R2: handoff negotiation phase after a timeout cancel. */
246
+ private handoffPhase: "none" | "await-settle" | "await-handoff" = "none";
247
+ /** Structured handoff captured from the child's `handoff` tool call. */
248
+ private structuredHandoff: HandoffSubmission | null = null;
249
+ /** Bounded enforcement prompts when the child settled without submitting. */
250
+ private handoffEnforceAttempts = 0;
251
+ private static readonly HANDOFF_ENFORCE_MAX = 2;
252
+ private handoffEnforceTimer: NodeJS.Timeout | null = null;
253
+ private handoffGraceTimer: NodeJS.Timeout | null = null;
254
+ private handoffSettleTimer: NodeJS.Timeout | null = null;
255
+ private killEscalateTimer: NodeJS.Timeout | null = null;
192
256
  private usage: DelegateUsage = { ...EMPTY_USAGE };
193
257
  private turns = 0;
194
258
  private exitCode: number | null = null;
@@ -255,6 +319,12 @@ export class DelegateRunner {
255
319
  const { args, env } = buildChildArgs(this.req, role);
256
320
  const launchArgs = [...invocation.args, ...args];
257
321
 
322
+ // R6: worktree checkpoint at run start (BEFORE spawn — no sync work
323
+ // may sit between spawn and stream wiring; a fast-exiting child
324
+ // would otherwise win the race to close stdin). Post-death
325
+ // inspection becomes `git diff <gitBase>` instead of re-reading.
326
+ const gitBase = gitCheckpoint(this.req.cwd);
327
+
258
328
  let child: childProcess.ChildProcess;
259
329
  try {
260
330
  child = childProcess.spawn(invocation.command, launchArgs, {
@@ -274,7 +344,14 @@ export class DelegateRunner {
274
344
  this.child = child;
275
345
  this.startedAt = new Date().toISOString();
276
346
  this.startedAtMs = Date.now();
277
- this.updateMetadata({ state: "starting", pid: child.pid, startedAt: this.startedAt });
347
+ this.updateMetadata({
348
+ state: "starting",
349
+ pid: child.pid,
350
+ startedAt: this.startedAt,
351
+ ...(this.req.resumeOf ? { resumeOf: this.req.resumeOf } : {}),
352
+ ...(this.req.sessionPath ? { sessionPath: this.req.sessionPath } : {}),
353
+ ...(gitBase ? gitBase : {}),
354
+ });
278
355
 
279
356
  // Wire streams BEFORE the prompt; stdout records are captured raw first.
280
357
  child.stdout?.on("data", (chunk: Buffer) => this.onStdout(chunk));
@@ -318,8 +395,13 @@ export class DelegateRunner {
318
395
  this.hardTimer = setTimeout(() => this.cancel("timed_out_hard"), this.cfg.hardTimeoutMs);
319
396
  this.hardTimer.unref();
320
397
 
398
+ // A fast-exiting child closes stdin before/as the prompt is written;
399
+ // the resulting EPIPE must never escape as an unhandled stream error
400
+ // (the exit handler already finalizes the run).
401
+ child.stdin?.on("error", () => {});
402
+
321
403
  // Send the single prompt over RPC stdin.
322
- const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task);
404
+ const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task, this.req.resumeOf);
323
405
  const promptRecord = JSON.stringify({ id: this.promptId, type: "prompt", message: promptMessage });
324
406
  try {
325
407
  child.stdin?.write(`${promptRecord}\n`);
@@ -339,19 +421,33 @@ export class DelegateRunner {
339
421
 
340
422
  private onStdout(chunk: Buffer): void {
341
423
  this.noteActivity();
424
+ this.lastStreamActivityMs = Date.now();
342
425
  const records = this.parser.feed(chunk);
343
426
  for (const record of records) this.handleRecord(record);
344
427
  }
345
428
 
429
+ /** R2: last stdout timestamp — the settle wait re-arms while the child
430
+ * is still streaming its post-abort message instead of killing it. */
431
+ private lastStreamActivityMs = 0;
432
+ private cancelRequestedAtMs: number | null = null;
433
+
346
434
 
347
435
  private noteActivity(): void {
348
436
  this.armInactivity();
349
437
  }
350
438
 
439
+ /** R1: in-flight tool calls count as activity — the watchdog switches to
440
+ * the (much longer) stuck-tool budget while a tool call is open, so a
441
+ * legitimate long-running tool (test matrix, benchmark, soak) is never
442
+ * idle-killed mid-execution. A genuinely hung child with NO open tool
443
+ * still hits the normal inactivity budget. */
351
444
  private armInactivity(): void {
352
445
  if (this.finalizing || !this.child) return;
353
446
  if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
354
- this.inactivityTimer = setTimeout(() => this.cancel("timed_out_idle"), this.cfg.inactivityTimeoutMs);
447
+ const budget = this.openToolCalls.size > 0
448
+ ? this.cfg.stuckToolTimeoutMs ?? this.cfg.hardTimeoutMs
449
+ : this.cfg.inactivityTimeoutMs;
450
+ this.inactivityTimer = setTimeout(() => this.cancel("timed_out_idle"), budget);
355
451
  this.inactivityTimer.unref();
356
452
  }
357
453
 
@@ -407,10 +503,25 @@ export class DelegateRunner {
407
503
  break;
408
504
  }
409
505
  case "tool_event":
506
+ // R1: track open tool calls (start/end pairs by toolCallId).
507
+ if (cls.id) {
508
+ if (cls.phase === "start") this.openToolCalls.add(cls.id);
509
+ else if (cls.phase === "end") this.openToolCalls.delete(cls.id);
510
+ // a tool event resets the watchdog to the right budget
511
+ this.armInactivity();
512
+ }
410
513
  if (cls.phase === "start" && cls.toolName) {
411
514
  this.pushAction(describeToolAction(cls.toolName, cls.args));
412
515
  this.pushUpdate(`tool:${cls.toolName}`);
413
516
  }
517
+ // Structured handoff: the child's mandatory final report rides
518
+ // on the handoff tool result details — capture it verbatim
519
+ // (re-validated; a stale/malformed payload is ignored).
520
+ if (cls.phase === "end" && cls.toolName === "handoff") {
521
+ const candidate = (cls.result?.details as { delegateHandoff?: unknown } | undefined)?.delegateHandoff;
522
+ const validation = validateHandoffSubmission(candidate);
523
+ if (validation.ok) this.structuredHandoff = validation.value ?? null;
524
+ }
414
525
  break;
415
526
  case "agent_settled":
416
527
  this.settled = true;
@@ -451,17 +562,27 @@ export class DelegateRunner {
451
562
  .join("\n\n");
452
563
  const reason =
453
564
  typeof m.stopReason === "string" ? m.stopReason : stopReason;
565
+ // R4: the provider's own error text rides on message_end.errorMessage —
566
+ // capture it verbatim (e.g. "Codex error: The usage limit has been
567
+ // reached", or abort artifacts like "This operation was aborted").
568
+ const errorMessage = typeof m.errorMessage === "string" ? m.errorMessage : undefined;
454
569
  this.lastAssistant = {
455
570
  text,
456
571
  stopReason: reason,
572
+ ...(errorMessage ? { errorMessage } : {}),
457
573
  usage: { ...this.usage },
458
574
  };
459
575
  }
460
576
 
461
577
  /**
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.
578
+ * R2 — timeout cancellation with a graceful handoff attempt:
579
+ * 1. RPC `abort` (ends the in-flight tool/turn, exactly as before);
580
+ * 2. wait (bounded, 5 s) for the child to settle;
581
+ * 3. send the termination-notice prompt; wait `handoffGraceMs`;
582
+ * 4. capture the child's final answer as `partialHandoff`;
583
+ * 5. SIGTERM → killGrace → SIGKILL (the old path, as fallback).
584
+ * A user/parent `cancelled` keeps the OLD fast path (2 s → SIGTERM):
585
+ * the caller asked to stop, not to negotiate.
465
586
  */
466
587
  cancel(state: RunTerminalState): void {
467
588
  if (this.finalizing) return;
@@ -470,6 +591,7 @@ export class DelegateRunner {
470
591
  const byUser = state === "cancelled";
471
592
  if (byUser) this.cancelledByUser = true;
472
593
  this.cancelRequested = state;
594
+ this.cancelRequestedAtMs = Date.now();
473
595
  const child = this.child;
474
596
  if (!child) {
475
597
  this.finish(state);
@@ -482,7 +604,43 @@ export class DelegateRunner {
482
604
  // fall through to signals
483
605
  }
484
606
  }
485
- setTimeout(() => {
607
+ if (byUser) {
608
+ // Fast path (unchanged): 2 s → SIGTERM → grace → SIGKILL.
609
+ this.startKillEscalation(2000);
610
+ return;
611
+ }
612
+ // Timeout path: negotiate a partial handoff, bounded at every step.
613
+ this.handoffPhase = "await-settle";
614
+ this.armHandoffSettleWait(this.startedAtMs ? Date.now() : Date.now());
615
+ }
616
+
617
+ /**
618
+ * R2: wait (bounded) for the child to settle after the abort. A real
619
+ * child often keeps streaming its interrupted turn for several seconds
620
+ * after the abort (observed: ≥5 s of message_update deltas) — while it
621
+ * is still producing output we re-arm instead of killing mid-sentence.
622
+ */
623
+ private armHandoffSettleWait(_startedAt: number): void {
624
+ const stepMs = 5000;
625
+ const capMs = 45_000;
626
+ this.handoffSettleTimer = setTimeout(() => {
627
+ if (this.finalizing || this.handoffPhase !== "await-settle") return;
628
+ const quiet = Date.now() - this.lastStreamActivityMs;
629
+ if (quiet < 3000 && Date.now() - (this.cancelRequestedAtMs ?? Date.now()) < capMs) {
630
+ this.armHandoffSettleWait(_startedAt);
631
+ return;
632
+ }
633
+ // Child never settled after the abort — no negotiation possible.
634
+ this.handoffPhase = "none";
635
+ this.startKillEscalation(0);
636
+ }, stepMs);
637
+ this.handoffSettleTimer.unref();
638
+ }
639
+
640
+ /** SIGTERM → killGrace → SIGKILL escalation (one shared implementation). */
641
+ private startKillEscalation(delayMs: number): void {
642
+ if (this.finalizing) return;
643
+ this.killEscalateTimer = setTimeout(() => {
486
644
  if (this.finalizing || !this.child?.kill) return;
487
645
  try {
488
646
  this.child.kill("SIGTERM");
@@ -497,13 +655,63 @@ export class DelegateRunner {
497
655
  // ignore
498
656
  }
499
657
  }, 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.
658
+ }, delayMs);
659
+ this.killEscalateTimer.unref();
660
+ }
661
+
662
+ /** R2: the child settled after our abort — offer it the handoff prompt. */
663
+ private beginHandoffPrompt(): void {
664
+ this.handoffPhase = "await-handoff";
665
+ try {
666
+ this.child?.stdin?.write(
667
+ `${JSON.stringify({ id: `${this.runId}:handoff`, type: "prompt", message: buildHandoffPrompt(this.runId) })}\n`,
668
+ );
669
+ } catch {
670
+ // child gone — fall back to the kill path
671
+ this.handoffPhase = "none";
672
+ this.startKillEscalation(0);
673
+ return;
674
+ }
675
+ const grace = this.cfg.handoffGraceMs ?? 90_000;
676
+ this.handoffGraceTimer = setTimeout(() => {
677
+ // Grace exhausted — finalize with whatever we already captured.
678
+ this.handoffPhase = "none";
679
+ if (!this.finalizing) {
680
+ this.startKillEscalation(0);
681
+ if (this.cancelRequested) this.finish(this.cancelRequested, undefined, this.partialHandoffExtra());
682
+ }
683
+ }, grace);
684
+ this.handoffGraceTimer.unref();
685
+ }
686
+
687
+ /** R2: build the partial-handoff `extra`. The structured submission
688
+ * (from the handoff tool) wins; free text is the fallback. */
689
+ private partialHandoffExtra(): { handoff?: string; truncated?: boolean; partialHandoff?: string } | undefined {
690
+ if (this.structuredHandoff) {
691
+ return { partialHandoff: renderHandoff(this.structuredHandoff, { partial: true }) };
692
+ }
693
+ const text = this.lastAssistant?.text?.trim();
694
+ if (!text) return undefined;
695
+ const { text: bounded, truncated } = truncateHandoff(text, this.cfg.maxResultBytes);
696
+ return { partialHandoff: bounded, truncated };
503
697
  }
504
698
 
505
699
  private finalizeSettled(): void {
506
700
  if (this.finalizing) return;
701
+ // R2: a timeout cancellation negotiates a partial handoff BEFORE it
702
+ // finalizes. Settles arriving during the negotiation belong to the
703
+ // handoff exchange, not to the run outcome.
704
+ if (this.cancelRequested && this.handoffPhase === "await-settle") {
705
+ this.beginHandoffPrompt();
706
+ return;
707
+ }
708
+ if (this.cancelRequested && this.handoffPhase === "await-handoff") {
709
+ // The child answered the termination-notice prompt — finalize with
710
+ // whatever it wrote as the partial handoff.
711
+ this.handoffPhase = "none";
712
+ this.finish(this.cancelRequested, undefined, this.partialHandoffExtra());
713
+ return;
714
+ }
507
715
  // A cancellation is already finalizing via the exit path (§9.7) — an
508
716
  // aborted turn legitimately has no final text and must not overwrite
509
717
  // the cancellation with E_NO_HANDOFF.
@@ -515,21 +723,102 @@ export class DelegateRunner {
515
723
  return;
516
724
  }
517
725
  if (final?.stopReason === "error") {
726
+ // R4 — precise provider-error diagnosis. The provider's own text
727
+ // rides on message_end.errorMessage; quote it verbatim. Abort
728
+ // artifacts (our own watchdog abort surfacing as stop=error) are
729
+ // classified as killed-by-watchdog, not blamed on the provider.
730
+ // The stderr tail is NEVER presented as the cause — it is routinely
731
+ // unrelated noise (e.g. model-discovery notices about user config).
732
+ const providerMessage = final.errorMessage?.trim();
733
+ if (providerMessage && !isAbortArtifactErrorMessage(providerMessage)) {
734
+ this.finish("failed", {
735
+ code: "E_PROVIDER_ERROR",
736
+ message: `Provider error: ${providerMessage}`,
737
+ });
738
+ return;
739
+ }
740
+ if (providerMessage) {
741
+ this.finish("failed", {
742
+ code: "E_CHILD_MODEL",
743
+ message: `Child aborted mid-request (${providerMessage}); typically a watchdog/timeout kill landing mid-generation, not a provider fault.`,
744
+ });
745
+ return;
746
+ }
518
747
  this.finish("failed", {
519
748
  code: "E_CHILD_MODEL",
520
- message: `Child model stopped with an error (stderr tail: ${this.stderrTail()})`,
749
+ message: `Child model stopped with an error (no provider message on the final message; unrelated stderr tail: ${this.stderrTail()})`,
521
750
  });
522
751
  return;
523
752
  }
753
+ // Protocol enforcement: the child MUST submit the structured handoff
754
+ // via the handoff tool. A settle without it is re-prompted (bounded);
755
+ // after the budget is spent the free-text ending is accepted with a
756
+ // diagnostic note (older children without the tool still finish).
757
+ if (
758
+ !this.structuredHandoff &&
759
+ this.handoffEnforceAttempts < DelegateRunner.HANDOFF_ENFORCE_MAX &&
760
+ final?.text.trim()
761
+ ) {
762
+ this.handoffEnforceAttempts += 1;
763
+ let written = false;
764
+ try {
765
+ this.child?.stdin?.write(
766
+ `${JSON.stringify({
767
+ id: `${this.runId}:handoff-required`,
768
+ type: "prompt",
769
+ message:
770
+ `[delegate ${this.runId} · handoff required]\n` +
771
+ `Your run ended WITHOUT the mandatory handoff tool call. Call the handoff tool NOW with your structured result ` +
772
+ `(outcome, summary, changes, verification, remaining, risks). Do not write free text; the run does not complete without it.`,
773
+ })}\n`,
774
+ );
775
+ written = true;
776
+ } catch {
777
+ // child gone — finalize on what we have
778
+ }
779
+ if (written) {
780
+ // DEADLOCK GUARD: the child already finished its work; if it
781
+ // never answers the enforcement prompt (older child, hung
782
+ // model), finalize with the free-text fallback after a SHORT
783
+ // bound — never the remaining hard budget.
784
+ if (this.handoffEnforceTimer) clearTimeout(this.handoffEnforceTimer);
785
+ this.handoffEnforceTimer = setTimeout(() => {
786
+ if (this.finalizing) return;
787
+ this.handoffPhase = "none";
788
+ this.finalizeFreeTextFallback();
789
+ }, this.cfg.handoffEnforceTimeoutMs ?? 60_000);
790
+ this.handoffEnforceTimer.unref();
791
+ return; // wait for the enforcement turn to settle
792
+ }
793
+ }
524
794
  if (!final || !final.text.trim()) {
795
+ if (this.structuredHandoff) {
796
+ // Tool submitted but the child never wrote a closing message:
797
+ // the structured submission IS the handoff.
798
+ this.finish("succeeded", undefined, {
799
+ handoff: renderHandoff(this.structuredHandoff),
800
+ truncated: false,
801
+ stopReason: final?.stopReason,
802
+ usage: { ...this.usage, turns: this.turns },
803
+ });
804
+ return;
805
+ }
525
806
  this.finish("failed", {
526
807
  code: "E_NO_HANDOFF",
527
808
  message: "Child settled without a final assistant text message.",
528
809
  });
529
810
  return;
530
811
  }
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 } });
812
+ if (this.structuredHandoff) {
813
+ this.finish("succeeded", undefined, {
814
+ handoff: renderHandoff(this.structuredHandoff),
815
+ truncated: false,
816
+ stopReason: final.stopReason,
817
+ usage: { ...final.usage, turns: this.turns },
818
+ });
819
+ } else {
820
+ this.finalizeFreeTextFallback();
821
+ }
533
822
  // End stdin and wait briefly for clean exit; if the RPC host remains
534
823
  // alive, SIGTERM then SIGKILL. This never turns success into failure.
535
824
  if (child) {
@@ -557,6 +846,28 @@ export class DelegateRunner {
557
846
  }
558
847
  }
559
848
 
849
+ /**
850
+ * Free-text fallback finalization: the child's own closing message
851
+ * becomes the handoff (bounded), with a diagnostic note that the
852
+ * structured protocol was not satisfied.
853
+ */
854
+ private finalizeFreeTextFallback(): void {
855
+ if (this.finalizing) return;
856
+ const final = this.lastAssistant;
857
+ if (!final || !final.text.trim()) {
858
+ this.finish("failed", {
859
+ code: "E_NO_HANDOFF",
860
+ message: "Child settled without a final assistant text message.",
861
+ });
862
+ return;
863
+ }
864
+ if (this.handoffEnforceAttempts > 0) {
865
+ this.diagnosticNotes.push("child settled without the handoff tool; free-text handoff accepted after enforcement retries");
866
+ }
867
+ const { text: handoff, truncated } = truncateHandoff(final.text, this.cfg.maxResultBytes);
868
+ this.finish("succeeded", undefined, { handoff, truncated, stopReason: final.stopReason, usage: { ...final.usage, turns: this.turns } });
869
+ }
870
+
560
871
  private finalizeOnExit(): void {
561
872
  // Flush any incomplete final record into the capture.
562
873
  try {
@@ -598,12 +909,18 @@ export class DelegateRunner {
598
909
  }
599
910
  }
600
911
 
601
- private finish(state: RunTerminalState, error?: DelegateError, extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage }): void {
912
+ private finish(state: RunTerminalState, error?: DelegateError, extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage; partialHandoff?: string }): void {
602
913
  if (this.finalizing) return;
603
914
  this.finalizing = true;
604
915
  const finishedAt = new Date().toISOString();
605
916
  const durationMs = this.startedAtMs ? Date.now() - this.startedAtMs : 0;
606
- this.finalError = error ?? this.finalError;
917
+ // P3: timeout/cancel terminal states are reached without an explicit
918
+ // error (timers and user cancels funnel through finish() bare).
919
+ // Synthesize a specific payload so the tool text never degrades to
920
+ // "unknown failure" — the header shows the state; the error line must
921
+ // agree. Flows into both the metadata and the reported outcome.
922
+ const effectiveError = error ?? this.synthesizedTerminalError(state);
923
+ this.finalError = effectiveError ?? this.finalError;
607
924
  const usage = { ...(extra?.usage ?? this.usage), turns: this.turns };
608
925
  const metadataPatch: Record<string, unknown> = {
609
926
  state,
@@ -617,9 +934,23 @@ export class DelegateRunner {
617
934
  metadataPatch.outputBytes = Buffer.byteLength(extra.handoff, "utf8");
618
935
  }
619
936
  if (extra?.stopReason) metadataPatch.stopReason = extra.stopReason;
620
- if (error) {
621
- metadataPatch.errorCode = error.code;
622
- metadataPatch.errorMessage = error.message;
937
+ // Structured handoff (from the child's handoff tool call).
938
+ if (this.structuredHandoff) metadataPatch.handoffData = this.structuredHandoff;
939
+ // R2: partial handoff from a killed child — first-class receipt field.
940
+ if (extra?.partialHandoff !== undefined) {
941
+ metadataPatch.partialHandoff = extra.partialHandoff;
942
+ }
943
+ // R3: locate + record the child's durable session file (new runs).
944
+ if (!this.req.sessionPath) {
945
+ const sessionPath = this.locateChildSession();
946
+ if (sessionPath) metadataPatch.sessionPath = sessionPath;
947
+ }
948
+ // R6: post-run worktree delta (bounded).
949
+ const gitDelta = gitDeltaSince(this.req.cwd);
950
+ if (gitDelta) metadataPatch.gitDelta = gitDelta;
951
+ if (effectiveError) {
952
+ metadataPatch.errorCode = effectiveError.code;
953
+ metadataPatch.errorMessage = effectiveError.message;
623
954
  }
624
955
  if (this.diagnosticNotes.length > 0) {
625
956
  metadataPatch.errorMessage = metadataPatch.errorMessage
@@ -643,15 +974,47 @@ export class DelegateRunner {
643
974
  this.reapChild();
644
975
  this.cleanup();
645
976
 
646
- const outcome = this.outcome(state, extra, error);
977
+ const outcome = this.outcome(state, extra, effectiveError);
647
978
  const resolver = this.settledResolver;
648
979
  this.settledResolver = null;
649
980
  resolver?.(outcome);
650
981
  }
651
982
 
983
+ /**
984
+ * P3: specific error payloads for the terminal states reached without an
985
+ * explicit error. `succeeded`/`failed` already carry their error at the
986
+ * call site (or legitimately have none) and are unaffected.
987
+ */
988
+ private synthesizedTerminalError(state: RunTerminalState): DelegateError | undefined {
989
+ switch (state) {
990
+ case "timed_out_idle":
991
+ return this.openToolCalls.size > 0
992
+ ? {
993
+ code: "E_TIMEOUT_IDLE",
994
+ message: `in-flight tool call exceeded the stuck-tool budget of ${formatDuration(this.cfg.stuckToolTimeoutMs ?? this.cfg.hardTimeoutMs)} (${this.openToolCalls.size} tool call(s) still open)`,
995
+ }
996
+ : {
997
+ code: "E_TIMEOUT_IDLE",
998
+ message: `no child activity for ${formatDuration(this.cfg.inactivityTimeoutMs)} (inactivity watchdog)`,
999
+ };
1000
+ case "timed_out_hard":
1001
+ return {
1002
+ code: "E_TIMEOUT_HARD",
1003
+ message: `hard timeout of ${formatDuration(this.cfg.hardTimeoutMs)} reached (wall-clock cap)`,
1004
+ };
1005
+ case "cancelled":
1006
+ return {
1007
+ code: "E_CANCELLED",
1008
+ message: this.cancelledByUser ? "cancelled by user" : "aborted (parent session abort)",
1009
+ };
1010
+ default:
1011
+ return undefined;
1012
+ }
1013
+ }
1014
+
652
1015
  private outcome(
653
1016
  state: RunTerminalState,
654
- extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage },
1017
+ extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage; partialHandoff?: string },
655
1018
  error?: DelegateError,
656
1019
  ): RunnerOutcome {
657
1020
  const finishedAt = new Date().toISOString();
@@ -660,6 +1023,7 @@ export class DelegateRunner {
660
1023
  runId: this.runId,
661
1024
  state,
662
1025
  handoff: state === "succeeded" ? extra?.handoff ?? "" : "",
1026
+ partialHandoff: state !== "succeeded" ? extra?.partialHandoff : undefined,
663
1027
  outputBytes: Buffer.byteLength(extra?.handoff ?? "", "utf8"),
664
1028
  outputTruncated: extra?.truncated ?? false,
665
1029
  startedAt: this.startedAt,
@@ -701,6 +1065,7 @@ export class DelegateRunner {
701
1065
  runId: this.runId,
702
1066
  role: this.req.role.name,
703
1067
  phase,
1068
+ model: this.req.parentModel,
704
1069
  elapsedMs: this.startedAtMs ? now - this.startedAtMs : 0,
705
1070
  lastActions: this.lastActions.slice(-5),
706
1071
  usage: { ...this.usage, turns: this.turns },
@@ -738,6 +1103,30 @@ export class DelegateRunner {
738
1103
  }, 250);
739
1104
  }
740
1105
 
1106
+ /**
1107
+ * R3: find the child's durable session file. New runs spawn with
1108
+ * `--session-dir <runsDir>/sessions`; pi names the file itself, so we
1109
+ * take the newest session file in that directory written during this
1110
+ * run's lifetime. Best-effort: absent when pi did not persist one.
1111
+ */
1112
+ private locateChildSession(): string | undefined {
1113
+ const dir = this.req.sessionDir;
1114
+ if (!dir || !this.startedAtMs) return undefined;
1115
+ try {
1116
+ const names = fs.readdirSync(dir).filter((n) => n.endsWith(".jsonl"));
1117
+ let best: { name: string; mtime: number } | null = null;
1118
+ for (const name of names) {
1119
+ const st = fs.statSync(path.join(dir, name));
1120
+ if (st.mtimeMs >= this.startedAtMs - 2_000 && (!best || st.mtimeMs > best.mtime)) {
1121
+ best = { name, mtime: st.mtimeMs };
1122
+ }
1123
+ }
1124
+ return best ? path.join(dir, best.name) : undefined;
1125
+ } catch {
1126
+ return undefined;
1127
+ }
1128
+ }
1129
+
741
1130
  private cleanup(): void {
742
1131
  // NOTE: reap timers intentionally survive cleanup — they must run to
743
1132
  // completion to guarantee the child is killed (short-lived refs).
@@ -745,6 +1134,10 @@ export class DelegateRunner {
745
1134
  if (this.hardTimer) clearTimeout(this.hardTimer);
746
1135
  if (this.killGraceTimer) clearTimeout(this.killGraceTimer);
747
1136
  if (this.settleExitTimer) clearTimeout(this.settleExitTimer);
1137
+ if (this.handoffGraceTimer) clearTimeout(this.handoffGraceTimer);
1138
+ if (this.handoffSettleTimer) clearTimeout(this.handoffSettleTimer);
1139
+ if (this.handoffEnforceTimer) clearTimeout(this.handoffEnforceTimer);
1140
+ if (this.killEscalateTimer) clearTimeout(this.killEscalateTimer);
748
1141
  this.inactivityTimer = null;
749
1142
  this.hardTimer = null;
750
1143
  this.killGraceTimer = null;
@@ -771,6 +1164,61 @@ export class DelegateRunner {
771
1164
  }
772
1165
 
773
1166
 
1167
+ // ── R6: git worktree checkpoints (bounded, best-effort, non-fatal) ─────────
1168
+
1169
+ function gitExec(cwd: string, args: string[]): string | null {
1170
+ try {
1171
+ const out = childProcess.execFileSync("git", args, {
1172
+ cwd,
1173
+ encoding: "utf8",
1174
+ timeout: 3000,
1175
+ stdio: ["ignore", "pipe", "ignore"],
1176
+ maxBuffer: 512 * 1024,
1177
+ });
1178
+ return out.trim();
1179
+ } catch {
1180
+ return null;
1181
+ }
1182
+ }
1183
+
1184
+ function isGitWorktree(cwd: string): boolean {
1185
+ return gitExec(cwd, ["rev-parse", "--is-inside-work-tree"]) === "true";
1186
+ }
1187
+
1188
+ /** Snapshot HEAD + bounded dirty status at run start. */
1189
+ export function gitCheckpoint(cwd: string): { gitBase: string; gitStatus?: string } | null {
1190
+ if (!isGitWorktree(cwd)) return null;
1191
+ const head = gitExec(cwd, ["rev-parse", "HEAD"]);
1192
+ if (!head) return null;
1193
+ const status = gitExec(cwd, ["status", "--porcelain"]);
1194
+ const bounded = status ? status.split("\n").slice(0, 40).join("\n").slice(0, 2000) : "";
1195
+ return { gitBase: head, ...(bounded ? { gitStatus: bounded } : {}) };
1196
+ }
1197
+
1198
+ /**
1199
+ * Bounded post-run worktree delta at finalization: `git diff --stat HEAD`
1200
+ * plus untracked files (a killed child's brand-new files are exactly the
1201
+ * evidence that matters — `diff HEAD` alone would hide them).
1202
+ */
1203
+ export function gitDeltaSince(cwd: string, _since?: string): string | null {
1204
+ if (!isGitWorktree(cwd)) return null;
1205
+ const parts: string[] = [];
1206
+ const diff = gitExec(cwd, ["diff", "--stat", "HEAD"]);
1207
+ if (diff) parts.push(diff);
1208
+ const untracked = gitExec(cwd, ["ls-files", "--others", "--exclude-standard"]);
1209
+ if (untracked) {
1210
+ parts.push(
1211
+ untracked
1212
+ .split("\n")
1213
+ .slice(0, 40)
1214
+ .map((f) => `untracked: ${f}`)
1215
+ .join("\n"),
1216
+ );
1217
+ }
1218
+ if (parts.length === 0) return null;
1219
+ return parts.join("\n").slice(0, 4000);
1220
+ }
1221
+
774
1222
  /**
775
1223
  * Display-safe one-liner for a child tool call (never fed to the model).
776
1224
  * Keeps at most ~100 visible chars; args are user-visible command/path