@maheidem/pi-delegate 0.1.5 → 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
@@ -26,12 +26,21 @@ 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
28
  import { formatDuration } from "./config.ts";
29
+ import { renderHandoff, validateHandoffSubmission, type HandoffSubmission } from "./handoff.ts";
29
30
 
30
31
  export interface RunnerConfig {
31
32
  maxResultBytes: number;
32
33
  inactivityTimeoutMs: number;
33
34
  hardTimeoutMs: number;
34
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;
35
44
  updateThrottleMs: number;
36
45
  maxRecordBytes?: number;
37
46
  malformedThreshold?: number;
@@ -73,16 +82,31 @@ export interface RunnerSpawnRequest {
73
82
  projectTrusted: boolean;
74
83
  /** Registered tool names in the parent process (for role ceiling preflight). */
75
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;
76
91
  }
77
92
 
78
93
  export function buildChildArgs(
79
94
  req: RunnerSpawnRequest,
80
95
  role: DelegateRole,
81
96
  ): { args: string[]; env: NodeJS.ProcessEnv; promptId: string } {
82
- 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"];
83
107
  const args: string[] = [
84
108
  "--mode", "rpc",
85
- "--no-session",
109
+ ...sessionArgs,
86
110
  "--model", req.parentModel,
87
111
  ];
88
112
  if (req.thinkingLevel) args.push("--thinking", req.thinkingLevel);
@@ -99,9 +123,13 @@ export function buildChildArgs(
99
123
  return { args, env, promptId: `delegate:${req.runId}:prompt` };
100
124
  }
101
125
 
102
- 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
+ : "";
103
130
  return (
104
131
  `[delegated child run · id=${runId} · role=${role}]\n` +
132
+ resumeNote +
105
133
  `This task came from a parent Pi session. Work only on this task.\n` +
106
134
  `Do not delegate or attempt to contact the parent during execution.\n` +
107
135
  `Follow the role output contract exactly.\n\n` +
@@ -109,6 +137,26 @@ function buildPromptMessage(runId: string, role: string, task: string): string {
109
137
  );
110
138
  }
111
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
+
112
160
  /**
113
161
  * UTF-8-safe bounded handoff: deterministic 75% head / 25% tail split with
114
162
  * an omission marker so both the outcome and trailing risks survive
@@ -156,6 +204,8 @@ function displaySafeArgValue(value: unknown, limit = 80): string {
156
204
  interface AssistantFinal {
157
205
  text: string;
158
206
  stopReason?: string;
207
+ /** R4: provider errorMessage captured from the final message_end, verbatim. */
208
+ errorMessage?: string;
159
209
  usage: DelegateUsage;
160
210
  }
161
211
 
@@ -190,6 +240,19 @@ export class DelegateRunner {
190
240
  private promptAccepted = false;
191
241
  private settled = false;
192
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;
193
256
  private usage: DelegateUsage = { ...EMPTY_USAGE };
194
257
  private turns = 0;
195
258
  private exitCode: number | null = null;
@@ -256,6 +319,12 @@ export class DelegateRunner {
256
319
  const { args, env } = buildChildArgs(this.req, role);
257
320
  const launchArgs = [...invocation.args, ...args];
258
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
+
259
328
  let child: childProcess.ChildProcess;
260
329
  try {
261
330
  child = childProcess.spawn(invocation.command, launchArgs, {
@@ -275,7 +344,14 @@ export class DelegateRunner {
275
344
  this.child = child;
276
345
  this.startedAt = new Date().toISOString();
277
346
  this.startedAtMs = Date.now();
278
- 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
+ });
279
355
 
280
356
  // Wire streams BEFORE the prompt; stdout records are captured raw first.
281
357
  child.stdout?.on("data", (chunk: Buffer) => this.onStdout(chunk));
@@ -319,8 +395,13 @@ export class DelegateRunner {
319
395
  this.hardTimer = setTimeout(() => this.cancel("timed_out_hard"), this.cfg.hardTimeoutMs);
320
396
  this.hardTimer.unref();
321
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
+
322
403
  // Send the single prompt over RPC stdin.
323
- const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task);
404
+ const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task, this.req.resumeOf);
324
405
  const promptRecord = JSON.stringify({ id: this.promptId, type: "prompt", message: promptMessage });
325
406
  try {
326
407
  child.stdin?.write(`${promptRecord}\n`);
@@ -340,19 +421,33 @@ export class DelegateRunner {
340
421
 
341
422
  private onStdout(chunk: Buffer): void {
342
423
  this.noteActivity();
424
+ this.lastStreamActivityMs = Date.now();
343
425
  const records = this.parser.feed(chunk);
344
426
  for (const record of records) this.handleRecord(record);
345
427
  }
346
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
+
347
434
 
348
435
  private noteActivity(): void {
349
436
  this.armInactivity();
350
437
  }
351
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. */
352
444
  private armInactivity(): void {
353
445
  if (this.finalizing || !this.child) return;
354
446
  if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
355
- 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);
356
451
  this.inactivityTimer.unref();
357
452
  }
358
453
 
@@ -408,10 +503,25 @@ export class DelegateRunner {
408
503
  break;
409
504
  }
410
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
+ }
411
513
  if (cls.phase === "start" && cls.toolName) {
412
514
  this.pushAction(describeToolAction(cls.toolName, cls.args));
413
515
  this.pushUpdate(`tool:${cls.toolName}`);
414
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
+ }
415
525
  break;
416
526
  case "agent_settled":
417
527
  this.settled = true;
@@ -452,17 +562,27 @@ export class DelegateRunner {
452
562
  .join("\n\n");
453
563
  const reason =
454
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;
455
569
  this.lastAssistant = {
456
570
  text,
457
571
  stopReason: reason,
572
+ ...(errorMessage ? { errorMessage } : {}),
458
573
  usage: { ...this.usage },
459
574
  };
460
575
  }
461
576
 
462
577
  /**
463
- * One idempotent cancel path (§9.11): mark → RPC abort → 2 s → SIGTERM →
464
- * grace (5 s default via killGraceMs) → SIGKILL. Finalizes metadata once
465
- * 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.
466
586
  */
467
587
  cancel(state: RunTerminalState): void {
468
588
  if (this.finalizing) return;
@@ -471,6 +591,7 @@ export class DelegateRunner {
471
591
  const byUser = state === "cancelled";
472
592
  if (byUser) this.cancelledByUser = true;
473
593
  this.cancelRequested = state;
594
+ this.cancelRequestedAtMs = Date.now();
474
595
  const child = this.child;
475
596
  if (!child) {
476
597
  this.finish(state);
@@ -483,7 +604,43 @@ export class DelegateRunner {
483
604
  // fall through to signals
484
605
  }
485
606
  }
486
- 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(() => {
487
644
  if (this.finalizing || !this.child?.kill) return;
488
645
  try {
489
646
  this.child.kill("SIGTERM");
@@ -498,13 +655,63 @@ export class DelegateRunner {
498
655
  // ignore
499
656
  }
500
657
  }, this.cfg.killGraceMs);
501
- }, 2000);
502
- // If the child never exits, the kill path above plus the exit handler
503
- // 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 };
504
697
  }
505
698
 
506
699
  private finalizeSettled(): void {
507
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
+ }
508
715
  // A cancellation is already finalizing via the exit path (§9.7) — an
509
716
  // aborted turn legitimately has no final text and must not overwrite
510
717
  // the cancellation with E_NO_HANDOFF.
@@ -516,21 +723,102 @@ export class DelegateRunner {
516
723
  return;
517
724
  }
518
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
+ }
519
747
  this.finish("failed", {
520
748
  code: "E_CHILD_MODEL",
521
- 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()})`,
522
750
  });
523
751
  return;
524
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
+ }
525
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
+ }
526
806
  this.finish("failed", {
527
807
  code: "E_NO_HANDOFF",
528
808
  message: "Child settled without a final assistant text message.",
529
809
  });
530
810
  return;
531
811
  }
532
- const { text: handoff, truncated } = truncateHandoff(final.text, this.cfg.maxResultBytes);
533
- 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
+ }
534
822
  // End stdin and wait briefly for clean exit; if the RPC host remains
535
823
  // alive, SIGTERM then SIGKILL. This never turns success into failure.
536
824
  if (child) {
@@ -558,6 +846,28 @@ export class DelegateRunner {
558
846
  }
559
847
  }
560
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
+
561
871
  private finalizeOnExit(): void {
562
872
  // Flush any incomplete final record into the capture.
563
873
  try {
@@ -599,7 +909,7 @@ export class DelegateRunner {
599
909
  }
600
910
  }
601
911
 
602
- 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 {
603
913
  if (this.finalizing) return;
604
914
  this.finalizing = true;
605
915
  const finishedAt = new Date().toISOString();
@@ -624,6 +934,20 @@ export class DelegateRunner {
624
934
  metadataPatch.outputBytes = Buffer.byteLength(extra.handoff, "utf8");
625
935
  }
626
936
  if (extra?.stopReason) metadataPatch.stopReason = extra.stopReason;
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;
627
951
  if (effectiveError) {
628
952
  metadataPatch.errorCode = effectiveError.code;
629
953
  metadataPatch.errorMessage = effectiveError.message;
@@ -664,10 +988,15 @@ export class DelegateRunner {
664
988
  private synthesizedTerminalError(state: RunTerminalState): DelegateError | undefined {
665
989
  switch (state) {
666
990
  case "timed_out_idle":
667
- return {
668
- code: "E_TIMEOUT_IDLE",
669
- message: `no child activity for ${formatDuration(this.cfg.inactivityTimeoutMs)} (inactivity watchdog)`,
670
- };
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
+ };
671
1000
  case "timed_out_hard":
672
1001
  return {
673
1002
  code: "E_TIMEOUT_HARD",
@@ -685,7 +1014,7 @@ export class DelegateRunner {
685
1014
 
686
1015
  private outcome(
687
1016
  state: RunTerminalState,
688
- extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage },
1017
+ extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage; partialHandoff?: string },
689
1018
  error?: DelegateError,
690
1019
  ): RunnerOutcome {
691
1020
  const finishedAt = new Date().toISOString();
@@ -694,6 +1023,7 @@ export class DelegateRunner {
694
1023
  runId: this.runId,
695
1024
  state,
696
1025
  handoff: state === "succeeded" ? extra?.handoff ?? "" : "",
1026
+ partialHandoff: state !== "succeeded" ? extra?.partialHandoff : undefined,
697
1027
  outputBytes: Buffer.byteLength(extra?.handoff ?? "", "utf8"),
698
1028
  outputTruncated: extra?.truncated ?? false,
699
1029
  startedAt: this.startedAt,
@@ -735,6 +1065,7 @@ export class DelegateRunner {
735
1065
  runId: this.runId,
736
1066
  role: this.req.role.name,
737
1067
  phase,
1068
+ model: this.req.parentModel,
738
1069
  elapsedMs: this.startedAtMs ? now - this.startedAtMs : 0,
739
1070
  lastActions: this.lastActions.slice(-5),
740
1071
  usage: { ...this.usage, turns: this.turns },
@@ -772,6 +1103,30 @@ export class DelegateRunner {
772
1103
  }, 250);
773
1104
  }
774
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
+
775
1130
  private cleanup(): void {
776
1131
  // NOTE: reap timers intentionally survive cleanup — they must run to
777
1132
  // completion to guarantee the child is killed (short-lived refs).
@@ -779,6 +1134,10 @@ export class DelegateRunner {
779
1134
  if (this.hardTimer) clearTimeout(this.hardTimer);
780
1135
  if (this.killGraceTimer) clearTimeout(this.killGraceTimer);
781
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);
782
1141
  this.inactivityTimer = null;
783
1142
  this.hardTimer = null;
784
1143
  this.killGraceTimer = null;
@@ -805,6 +1164,61 @@ export class DelegateRunner {
805
1164
  }
806
1165
 
807
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
+
808
1222
  /**
809
1223
  * Display-safe one-liner for a child tool call (never fed to the model).
810
1224
  * Keeps at most ~100 visible chars; args are user-visible command/path