@maheidem/pi-delegate 0.1.5 → 0.2.1

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,22 @@ 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";
30
+ import type { FeedEvent } from "./transcript-feed.ts";
29
31
 
30
32
  export interface RunnerConfig {
31
33
  maxResultBytes: number;
32
34
  inactivityTimeoutMs: number;
33
35
  hardTimeoutMs: number;
34
36
  killGraceMs: number;
37
+ /** R2: grace for the killed child's final handoff answer (default 90 s). */
38
+ handoffGraceMs?: number;
39
+ /** Bounded wait for a child to answer the mandatory-handoff enforcement
40
+ * prompt (default 60 s) — independent of the hard timeout, so a child
41
+ * that goes silent after settling can never dangle the run for hours. */
42
+ handoffEnforceTimeoutMs?: number;
43
+ /** R1: watchdog budget while a tool call is in flight (default: hard). */
44
+ stuckToolTimeoutMs?: number;
35
45
  updateThrottleMs: number;
36
46
  maxRecordBytes?: number;
37
47
  malformedThreshold?: number;
@@ -73,16 +83,31 @@ export interface RunnerSpawnRequest {
73
83
  projectTrusted: boolean;
74
84
  /** Registered tool names in the parent process (for role ceiling preflight). */
75
85
  registeredTools: readonly string[];
86
+ /** R3: prior run whose child session this run resumes ("--session <file>"). */
87
+ resumeOf?: string;
88
+ /** R3: child session file to re-enter (resume mode); new runs use --session-dir. */
89
+ sessionPath?: string;
90
+ /** R3: directory the child's session file is persisted to (new runs). */
91
+ sessionDir?: string;
76
92
  }
77
93
 
78
94
  export function buildChildArgs(
79
95
  req: RunnerSpawnRequest,
80
96
  role: DelegateRole,
81
97
  ): { args: string[]; env: NodeJS.ProcessEnv; promptId: string } {
82
- const toolList = role.tools.join(",");
98
+ // The mandatory structured-handoff tool is always in the child's
99
+ // ceiling; the delegate extension registers it in child mode.
100
+ const toolList = [...role.tools, "handoff"].join(",");
101
+ // R3: the child's session is DURABLE. New runs persist it under the run
102
+ // store (--session-dir); resumed runs re-enter the prior session file
103
+ // directly (--session <file>) so a killed run can be continued in the
104
+ // same context instead of a cold re-explained child.
105
+ const sessionArgs = req.sessionPath
106
+ ? ["--session", req.sessionPath]
107
+ : ["--session-dir", req.sessionDir ?? ".pi-sessions"];
83
108
  const args: string[] = [
84
109
  "--mode", "rpc",
85
- "--no-session",
110
+ ...sessionArgs,
86
111
  "--model", req.parentModel,
87
112
  ];
88
113
  if (req.thinkingLevel) args.push("--thinking", req.thinkingLevel);
@@ -99,9 +124,13 @@ export function buildChildArgs(
99
124
  return { args, env, promptId: `delegate:${req.runId}:prompt` };
100
125
  }
101
126
 
102
- function buildPromptMessage(runId: string, role: string, task: string): string {
127
+ function buildPromptMessage(runId: string, role: string, task: string, resumeOf?: string): string {
128
+ const resumeNote = resumeOf
129
+ ? `You are RESUMING the child session of run ${resumeOf} (its earlier turns are in your context). Continue from where that run left off.\n`
130
+ : "";
103
131
  return (
104
132
  `[delegated child run · id=${runId} · role=${role}]\n` +
133
+ resumeNote +
105
134
  `This task came from a parent Pi session. Work only on this task.\n` +
106
135
  `Do not delegate or attempt to contact the parent during execution.\n` +
107
136
  `Follow the role output contract exactly.\n\n` +
@@ -109,6 +138,26 @@ function buildPromptMessage(runId: string, role: string, task: string): string {
109
138
  );
110
139
  }
111
140
 
141
+ /** R2: the bounded termination-notice prompt a timed-out child must answer
142
+ * through the handoff TOOL (deterministic capture), with a free-text
143
+ * fallback only if the tool path is unavailable in an older child. */
144
+ export function buildHandoffPrompt(runId: string): string {
145
+ return (
146
+ `[delegate ${runId} · termination notice]\n` +
147
+ `You are being terminated NOW. Call the handoff tool IMMEDIATELY with outcome "partial":\n` +
148
+ `- summary: what you completed so far\n` +
149
+ `- changes: every file you created/modified so far\n` +
150
+ `- verification: last test/typecheck state (or not_run)\n` +
151
+ `- remaining: precise next steps for a successor\n` +
152
+ `Do not start new work. If the handoff tool is unavailable, reply in plain text with those four sections.`
153
+ );
154
+ }
155
+
156
+ /** R4: provider-error artifacts produced by our own abort, not the provider. */
157
+ export function isAbortArtifactErrorMessage(message: string): boolean {
158
+ return /this operation was aborted|request was aborted|operation aborted/i.test(message);
159
+ }
160
+
112
161
  /**
113
162
  * UTF-8-safe bounded handoff: deterministic 75% head / 25% tail split with
114
163
  * an omission marker so both the outcome and trailing risks survive
@@ -156,6 +205,8 @@ function displaySafeArgValue(value: unknown, limit = 80): string {
156
205
  interface AssistantFinal {
157
206
  text: string;
158
207
  stopReason?: string;
208
+ /** R4: provider errorMessage captured from the final message_end, verbatim. */
209
+ errorMessage?: string;
159
210
  usage: DelegateUsage;
160
211
  }
161
212
 
@@ -190,6 +241,25 @@ export class DelegateRunner {
190
241
  private promptAccepted = false;
191
242
  private settled = false;
192
243
  private lastAssistant: AssistantFinal | null = null;
244
+ /** R1: toolCallIds with a start but no matching end yet. */
245
+ private openToolCalls = new Set<string>();
246
+ /** Feed: toolCallId → start ms (for end-event durations). */
247
+ private toolStartedAt = new Map<string, number>();
248
+ /** Feed: toolCallId → tool name. */
249
+ private toolNames = new Map<string, string>();
250
+ /** Feed: toolCallId → the start event's arg detail (path/command). */
251
+ private toolDetails = new Map<string, string>();
252
+ /** R2: handoff negotiation phase after a timeout cancel. */
253
+ private handoffPhase: "none" | "await-settle" | "await-handoff" = "none";
254
+ /** Structured handoff captured from the child's `handoff` tool call. */
255
+ private structuredHandoff: HandoffSubmission | null = null;
256
+ /** Bounded enforcement prompts when the child settled without submitting. */
257
+ private handoffEnforceAttempts = 0;
258
+ private static readonly HANDOFF_ENFORCE_MAX = 2;
259
+ private handoffEnforceTimer: NodeJS.Timeout | null = null;
260
+ private handoffGraceTimer: NodeJS.Timeout | null = null;
261
+ private handoffSettleTimer: NodeJS.Timeout | null = null;
262
+ private killEscalateTimer: NodeJS.Timeout | null = null;
193
263
  private usage: DelegateUsage = { ...EMPTY_USAGE };
194
264
  private turns = 0;
195
265
  private exitCode: number | null = null;
@@ -256,6 +326,12 @@ export class DelegateRunner {
256
326
  const { args, env } = buildChildArgs(this.req, role);
257
327
  const launchArgs = [...invocation.args, ...args];
258
328
 
329
+ // R6: worktree checkpoint at run start (BEFORE spawn — no sync work
330
+ // may sit between spawn and stream wiring; a fast-exiting child
331
+ // would otherwise win the race to close stdin). Post-death
332
+ // inspection becomes `git diff <gitBase>` instead of re-reading.
333
+ const gitBase = gitCheckpoint(this.req.cwd);
334
+
259
335
  let child: childProcess.ChildProcess;
260
336
  try {
261
337
  child = childProcess.spawn(invocation.command, launchArgs, {
@@ -275,7 +351,14 @@ export class DelegateRunner {
275
351
  this.child = child;
276
352
  this.startedAt = new Date().toISOString();
277
353
  this.startedAtMs = Date.now();
278
- this.updateMetadata({ state: "starting", pid: child.pid, startedAt: this.startedAt });
354
+ this.updateMetadata({
355
+ state: "starting",
356
+ pid: child.pid,
357
+ startedAt: this.startedAt,
358
+ ...(this.req.resumeOf ? { resumeOf: this.req.resumeOf } : {}),
359
+ ...(this.req.sessionPath ? { sessionPath: this.req.sessionPath } : {}),
360
+ ...(gitBase ? gitBase : {}),
361
+ });
279
362
 
280
363
  // Wire streams BEFORE the prompt; stdout records are captured raw first.
281
364
  child.stdout?.on("data", (chunk: Buffer) => this.onStdout(chunk));
@@ -319,8 +402,13 @@ export class DelegateRunner {
319
402
  this.hardTimer = setTimeout(() => this.cancel("timed_out_hard"), this.cfg.hardTimeoutMs);
320
403
  this.hardTimer.unref();
321
404
 
405
+ // A fast-exiting child closes stdin before/as the prompt is written;
406
+ // the resulting EPIPE must never escape as an unhandled stream error
407
+ // (the exit handler already finalizes the run).
408
+ child.stdin?.on("error", () => {});
409
+
322
410
  // Send the single prompt over RPC stdin.
323
- const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task);
411
+ const promptMessage = buildPromptMessage(this.runId, role.name, this.req.task, this.req.resumeOf);
324
412
  const promptRecord = JSON.stringify({ id: this.promptId, type: "prompt", message: promptMessage });
325
413
  try {
326
414
  child.stdin?.write(`${promptRecord}\n`);
@@ -340,19 +428,33 @@ export class DelegateRunner {
340
428
 
341
429
  private onStdout(chunk: Buffer): void {
342
430
  this.noteActivity();
431
+ this.lastStreamActivityMs = Date.now();
343
432
  const records = this.parser.feed(chunk);
344
433
  for (const record of records) this.handleRecord(record);
345
434
  }
346
435
 
436
+ /** R2: last stdout timestamp — the settle wait re-arms while the child
437
+ * is still streaming its post-abort message instead of killing it. */
438
+ private lastStreamActivityMs = 0;
439
+ private cancelRequestedAtMs: number | null = null;
440
+
347
441
 
348
442
  private noteActivity(): void {
349
443
  this.armInactivity();
350
444
  }
351
445
 
446
+ /** R1: in-flight tool calls count as activity — the watchdog switches to
447
+ * the (much longer) stuck-tool budget while a tool call is open, so a
448
+ * legitimate long-running tool (test matrix, benchmark, soak) is never
449
+ * idle-killed mid-execution. A genuinely hung child with NO open tool
450
+ * still hits the normal inactivity budget. */
352
451
  private armInactivity(): void {
353
452
  if (this.finalizing || !this.child) return;
354
453
  if (this.inactivityTimer) clearTimeout(this.inactivityTimer);
355
- this.inactivityTimer = setTimeout(() => this.cancel("timed_out_idle"), this.cfg.inactivityTimeoutMs);
454
+ const budget = this.openToolCalls.size > 0
455
+ ? this.cfg.stuckToolTimeoutMs ?? this.cfg.hardTimeoutMs
456
+ : this.cfg.inactivityTimeoutMs;
457
+ this.inactivityTimer = setTimeout(() => this.cancel("timed_out_idle"), budget);
356
458
  this.inactivityTimer.unref();
357
459
  }
358
460
 
@@ -405,16 +507,90 @@ export class DelegateRunner {
405
507
  case "message_end": {
406
508
  const message = (record.parsed as { message?: unknown }).message;
407
509
  this.ingestMessage(message, cls.stopReason);
510
+ const m = message as { role?: string; stopReason?: string; errorMessage?: string; content?: Array<{ type?: string; text?: string }> } | null;
511
+ if (m?.role === "assistant") {
512
+ if (m.stopReason === "error") {
513
+ this.emitEvent({
514
+ atMs: Date.now(),
515
+ kind: "provider_error",
516
+ detail: (m.errorMessage ?? "").trim() || "provider error (no message)",
517
+ });
518
+ } else {
519
+ const text = (m.content ?? []).find((b) => b?.type === "text" && b.text?.trim())?.text ?? "";
520
+ if (text.trim()) {
521
+ this.emitEvent({
522
+ atMs: Date.now(),
523
+ kind: "assistant",
524
+ detail: text.split("\n").filter(Boolean)[0] ?? "",
525
+ });
526
+ }
527
+ }
528
+ }
408
529
  break;
409
530
  }
410
531
  case "tool_event":
532
+ // R1: track open tool calls (start/end pairs by toolCallId).
533
+ if (cls.id) {
534
+ if (cls.phase === "start") {
535
+ this.openToolCalls.add(cls.id);
536
+ this.toolStartedAt.set(cls.id, Date.now());
537
+ if (cls.toolName) this.toolNames.set(cls.id, cls.toolName);
538
+ this.toolDetails.set(cls.id, feedDetailFor(cls.toolName ?? "", cls.args));
539
+ } else if (cls.phase === "end") {
540
+ this.openToolCalls.delete(cls.id);
541
+ this.toolStartedAt.delete(cls.id);
542
+ this.toolNames.delete(cls.id);
543
+ this.toolDetails.delete(cls.id);
544
+ }
545
+ // a tool event resets the watchdog to the right budget
546
+ this.armInactivity();
547
+ }
411
548
  if (cls.phase === "start" && cls.toolName) {
412
549
  this.pushAction(describeToolAction(cls.toolName, cls.args));
413
550
  this.pushUpdate(`tool:${cls.toolName}`);
551
+ this.emitEvent({
552
+ atMs: Date.now(),
553
+ kind: "tool_start",
554
+ tool: cls.toolName,
555
+ detail: feedDetailFor(cls.toolName, cls.args),
556
+ });
557
+ }
558
+ if (cls.phase === "end" && cls.toolName && cls.id) {
559
+ const started = this.toolStartedAt.get(cls.id);
560
+ // Echo the start's arg detail (path/command); bash keeps
561
+ // its output head — file-content heads are noise.
562
+ const argDetail = this.toolDetails.get(cls.id) ?? "";
563
+ const head = cls.result?.textHead ?? "";
564
+ const detail =
565
+ cls.toolName === "bash" && head ? head.slice(0, 70) : (argDetail || head.slice(0, 70) || "done");
566
+ this.emitEvent({
567
+ atMs: Date.now(),
568
+ kind: "tool_end",
569
+ tool: cls.toolName,
570
+ detail,
571
+ isError: cls.result?.isError === true,
572
+ ...(started ? { durationMs: Date.now() - started } : {}),
573
+ });
574
+ }
575
+ // Structured handoff: the child's mandatory final report rides
576
+ // on the handoff tool result details — capture it verbatim
577
+ // (re-validated; a stale/malformed payload is ignored).
578
+ if (cls.phase === "end" && cls.toolName === "handoff") {
579
+ const candidate = (cls.result?.details as { delegateHandoff?: unknown } | undefined)?.delegateHandoff;
580
+ const validation = validateHandoffSubmission(candidate);
581
+ if (validation.ok) {
582
+ this.structuredHandoff = validation.value ?? null;
583
+ this.emitEvent({
584
+ atMs: Date.now(),
585
+ kind: "handoff",
586
+ detail: `handoff submitted (${validation.value?.outcome ?? "?"})`,
587
+ });
588
+ }
414
589
  }
415
590
  break;
416
591
  case "agent_settled":
417
592
  this.settled = true;
593
+ this.emitEvent({ atMs: Date.now(), kind: "settled", detail: "agent settled" });
418
594
  this.finalizeSettled();
419
595
  break;
420
596
  case "agent_end":
@@ -452,17 +628,27 @@ export class DelegateRunner {
452
628
  .join("\n\n");
453
629
  const reason =
454
630
  typeof m.stopReason === "string" ? m.stopReason : stopReason;
631
+ // R4: the provider's own error text rides on message_end.errorMessage —
632
+ // capture it verbatim (e.g. "Codex error: The usage limit has been
633
+ // reached", or abort artifacts like "This operation was aborted").
634
+ const errorMessage = typeof m.errorMessage === "string" ? m.errorMessage : undefined;
455
635
  this.lastAssistant = {
456
636
  text,
457
637
  stopReason: reason,
638
+ ...(errorMessage ? { errorMessage } : {}),
458
639
  usage: { ...this.usage },
459
640
  };
460
641
  }
461
642
 
462
643
  /**
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.
644
+ * R2 — timeout cancellation with a graceful handoff attempt:
645
+ * 1. RPC `abort` (ends the in-flight tool/turn, exactly as before);
646
+ * 2. wait (bounded, 5 s) for the child to settle;
647
+ * 3. send the termination-notice prompt; wait `handoffGraceMs`;
648
+ * 4. capture the child's final answer as `partialHandoff`;
649
+ * 5. SIGTERM → killGrace → SIGKILL (the old path, as fallback).
650
+ * A user/parent `cancelled` keeps the OLD fast path (2 s → SIGTERM):
651
+ * the caller asked to stop, not to negotiate.
466
652
  */
467
653
  cancel(state: RunTerminalState): void {
468
654
  if (this.finalizing) return;
@@ -471,6 +657,7 @@ export class DelegateRunner {
471
657
  const byUser = state === "cancelled";
472
658
  if (byUser) this.cancelledByUser = true;
473
659
  this.cancelRequested = state;
660
+ this.cancelRequestedAtMs = Date.now();
474
661
  const child = this.child;
475
662
  if (!child) {
476
663
  this.finish(state);
@@ -483,7 +670,43 @@ export class DelegateRunner {
483
670
  // fall through to signals
484
671
  }
485
672
  }
486
- setTimeout(() => {
673
+ if (byUser) {
674
+ // Fast path (unchanged): 2 s → SIGTERM → grace → SIGKILL.
675
+ this.startKillEscalation(2000);
676
+ return;
677
+ }
678
+ // Timeout path: negotiate a partial handoff, bounded at every step.
679
+ this.handoffPhase = "await-settle";
680
+ this.armHandoffSettleWait(this.startedAtMs ? Date.now() : Date.now());
681
+ }
682
+
683
+ /**
684
+ * R2: wait (bounded) for the child to settle after the abort. A real
685
+ * child often keeps streaming its interrupted turn for several seconds
686
+ * after the abort (observed: ≥5 s of message_update deltas) — while it
687
+ * is still producing output we re-arm instead of killing mid-sentence.
688
+ */
689
+ private armHandoffSettleWait(_startedAt: number): void {
690
+ const stepMs = 5000;
691
+ const capMs = 45_000;
692
+ this.handoffSettleTimer = setTimeout(() => {
693
+ if (this.finalizing || this.handoffPhase !== "await-settle") return;
694
+ const quiet = Date.now() - this.lastStreamActivityMs;
695
+ if (quiet < 3000 && Date.now() - (this.cancelRequestedAtMs ?? Date.now()) < capMs) {
696
+ this.armHandoffSettleWait(_startedAt);
697
+ return;
698
+ }
699
+ // Child never settled after the abort — no negotiation possible.
700
+ this.handoffPhase = "none";
701
+ this.startKillEscalation(0);
702
+ }, stepMs);
703
+ this.handoffSettleTimer.unref();
704
+ }
705
+
706
+ /** SIGTERM → killGrace → SIGKILL escalation (one shared implementation). */
707
+ private startKillEscalation(delayMs: number): void {
708
+ if (this.finalizing) return;
709
+ this.killEscalateTimer = setTimeout(() => {
487
710
  if (this.finalizing || !this.child?.kill) return;
488
711
  try {
489
712
  this.child.kill("SIGTERM");
@@ -498,13 +721,63 @@ export class DelegateRunner {
498
721
  // ignore
499
722
  }
500
723
  }, 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.
724
+ }, delayMs);
725
+ this.killEscalateTimer.unref();
726
+ }
727
+
728
+ /** R2: the child settled after our abort — offer it the handoff prompt. */
729
+ private beginHandoffPrompt(): void {
730
+ this.handoffPhase = "await-handoff";
731
+ try {
732
+ this.child?.stdin?.write(
733
+ `${JSON.stringify({ id: `${this.runId}:handoff`, type: "prompt", message: buildHandoffPrompt(this.runId) })}\n`,
734
+ );
735
+ } catch {
736
+ // child gone — fall back to the kill path
737
+ this.handoffPhase = "none";
738
+ this.startKillEscalation(0);
739
+ return;
740
+ }
741
+ const grace = this.cfg.handoffGraceMs ?? 90_000;
742
+ this.handoffGraceTimer = setTimeout(() => {
743
+ // Grace exhausted — finalize with whatever we already captured.
744
+ this.handoffPhase = "none";
745
+ if (!this.finalizing) {
746
+ this.startKillEscalation(0);
747
+ if (this.cancelRequested) this.finish(this.cancelRequested, undefined, this.partialHandoffExtra());
748
+ }
749
+ }, grace);
750
+ this.handoffGraceTimer.unref();
751
+ }
752
+
753
+ /** R2: build the partial-handoff `extra`. The structured submission
754
+ * (from the handoff tool) wins; free text is the fallback. */
755
+ private partialHandoffExtra(): { handoff?: string; truncated?: boolean; partialHandoff?: string } | undefined {
756
+ if (this.structuredHandoff) {
757
+ return { partialHandoff: renderHandoff(this.structuredHandoff, { partial: true }) };
758
+ }
759
+ const text = this.lastAssistant?.text?.trim();
760
+ if (!text) return undefined;
761
+ const { text: bounded, truncated } = truncateHandoff(text, this.cfg.maxResultBytes);
762
+ return { partialHandoff: bounded, truncated };
504
763
  }
505
764
 
506
765
  private finalizeSettled(): void {
507
766
  if (this.finalizing) return;
767
+ // R2: a timeout cancellation negotiates a partial handoff BEFORE it
768
+ // finalizes. Settles arriving during the negotiation belong to the
769
+ // handoff exchange, not to the run outcome.
770
+ if (this.cancelRequested && this.handoffPhase === "await-settle") {
771
+ this.beginHandoffPrompt();
772
+ return;
773
+ }
774
+ if (this.cancelRequested && this.handoffPhase === "await-handoff") {
775
+ // The child answered the termination-notice prompt — finalize with
776
+ // whatever it wrote as the partial handoff.
777
+ this.handoffPhase = "none";
778
+ this.finish(this.cancelRequested, undefined, this.partialHandoffExtra());
779
+ return;
780
+ }
508
781
  // A cancellation is already finalizing via the exit path (§9.7) — an
509
782
  // aborted turn legitimately has no final text and must not overwrite
510
783
  // the cancellation with E_NO_HANDOFF.
@@ -516,21 +789,102 @@ export class DelegateRunner {
516
789
  return;
517
790
  }
518
791
  if (final?.stopReason === "error") {
792
+ // R4 — precise provider-error diagnosis. The provider's own text
793
+ // rides on message_end.errorMessage; quote it verbatim. Abort
794
+ // artifacts (our own watchdog abort surfacing as stop=error) are
795
+ // classified as killed-by-watchdog, not blamed on the provider.
796
+ // The stderr tail is NEVER presented as the cause — it is routinely
797
+ // unrelated noise (e.g. model-discovery notices about user config).
798
+ const providerMessage = final.errorMessage?.trim();
799
+ if (providerMessage && !isAbortArtifactErrorMessage(providerMessage)) {
800
+ this.finish("failed", {
801
+ code: "E_PROVIDER_ERROR",
802
+ message: `Provider error: ${providerMessage}`,
803
+ });
804
+ return;
805
+ }
806
+ if (providerMessage) {
807
+ this.finish("failed", {
808
+ code: "E_CHILD_MODEL",
809
+ message: `Child aborted mid-request (${providerMessage}); typically a watchdog/timeout kill landing mid-generation, not a provider fault.`,
810
+ });
811
+ return;
812
+ }
519
813
  this.finish("failed", {
520
814
  code: "E_CHILD_MODEL",
521
- message: `Child model stopped with an error (stderr tail: ${this.stderrTail()})`,
815
+ message: `Child model stopped with an error (no provider message on the final message; unrelated stderr tail: ${this.stderrTail()})`,
522
816
  });
523
817
  return;
524
818
  }
819
+ // Protocol enforcement: the child MUST submit the structured handoff
820
+ // via the handoff tool. A settle without it is re-prompted (bounded);
821
+ // after the budget is spent the free-text ending is accepted with a
822
+ // diagnostic note (older children without the tool still finish).
823
+ if (
824
+ !this.structuredHandoff &&
825
+ this.handoffEnforceAttempts < DelegateRunner.HANDOFF_ENFORCE_MAX &&
826
+ final?.text.trim()
827
+ ) {
828
+ this.handoffEnforceAttempts += 1;
829
+ let written = false;
830
+ try {
831
+ this.child?.stdin?.write(
832
+ `${JSON.stringify({
833
+ id: `${this.runId}:handoff-required`,
834
+ type: "prompt",
835
+ message:
836
+ `[delegate ${this.runId} · handoff required]\n` +
837
+ `Your run ended WITHOUT the mandatory handoff tool call. Call the handoff tool NOW with your structured result ` +
838
+ `(outcome, summary, changes, verification, remaining, risks). Do not write free text; the run does not complete without it.`,
839
+ })}\n`,
840
+ );
841
+ written = true;
842
+ } catch {
843
+ // child gone — finalize on what we have
844
+ }
845
+ if (written) {
846
+ // DEADLOCK GUARD: the child already finished its work; if it
847
+ // never answers the enforcement prompt (older child, hung
848
+ // model), finalize with the free-text fallback after a SHORT
849
+ // bound — never the remaining hard budget.
850
+ if (this.handoffEnforceTimer) clearTimeout(this.handoffEnforceTimer);
851
+ this.handoffEnforceTimer = setTimeout(() => {
852
+ if (this.finalizing) return;
853
+ this.handoffPhase = "none";
854
+ this.finalizeFreeTextFallback();
855
+ }, this.cfg.handoffEnforceTimeoutMs ?? 60_000);
856
+ this.handoffEnforceTimer.unref();
857
+ return; // wait for the enforcement turn to settle
858
+ }
859
+ }
525
860
  if (!final || !final.text.trim()) {
861
+ if (this.structuredHandoff) {
862
+ // Tool submitted but the child never wrote a closing message:
863
+ // the structured submission IS the handoff.
864
+ this.finish("succeeded", undefined, {
865
+ handoff: renderHandoff(this.structuredHandoff),
866
+ truncated: false,
867
+ stopReason: final?.stopReason,
868
+ usage: { ...this.usage, turns: this.turns },
869
+ });
870
+ return;
871
+ }
526
872
  this.finish("failed", {
527
873
  code: "E_NO_HANDOFF",
528
874
  message: "Child settled without a final assistant text message.",
529
875
  });
530
876
  return;
531
877
  }
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 } });
878
+ if (this.structuredHandoff) {
879
+ this.finish("succeeded", undefined, {
880
+ handoff: renderHandoff(this.structuredHandoff),
881
+ truncated: false,
882
+ stopReason: final.stopReason,
883
+ usage: { ...final.usage, turns: this.turns },
884
+ });
885
+ } else {
886
+ this.finalizeFreeTextFallback();
887
+ }
534
888
  // End stdin and wait briefly for clean exit; if the RPC host remains
535
889
  // alive, SIGTERM then SIGKILL. This never turns success into failure.
536
890
  if (child) {
@@ -558,6 +912,28 @@ export class DelegateRunner {
558
912
  }
559
913
  }
560
914
 
915
+ /**
916
+ * Free-text fallback finalization: the child's own closing message
917
+ * becomes the handoff (bounded), with a diagnostic note that the
918
+ * structured protocol was not satisfied.
919
+ */
920
+ private finalizeFreeTextFallback(): void {
921
+ if (this.finalizing) return;
922
+ const final = this.lastAssistant;
923
+ if (!final || !final.text.trim()) {
924
+ this.finish("failed", {
925
+ code: "E_NO_HANDOFF",
926
+ message: "Child settled without a final assistant text message.",
927
+ });
928
+ return;
929
+ }
930
+ if (this.handoffEnforceAttempts > 0) {
931
+ this.diagnosticNotes.push("child settled without the handoff tool; free-text handoff accepted after enforcement retries");
932
+ }
933
+ const { text: handoff, truncated } = truncateHandoff(final.text, this.cfg.maxResultBytes);
934
+ this.finish("succeeded", undefined, { handoff, truncated, stopReason: final.stopReason, usage: { ...final.usage, turns: this.turns } });
935
+ }
936
+
561
937
  private finalizeOnExit(): void {
562
938
  // Flush any incomplete final record into the capture.
563
939
  try {
@@ -599,7 +975,7 @@ export class DelegateRunner {
599
975
  }
600
976
  }
601
977
 
602
- private finish(state: RunTerminalState, error?: DelegateError, extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage }): void {
978
+ private finish(state: RunTerminalState, error?: DelegateError, extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage; partialHandoff?: string }): void {
603
979
  if (this.finalizing) return;
604
980
  this.finalizing = true;
605
981
  const finishedAt = new Date().toISOString();
@@ -624,6 +1000,20 @@ export class DelegateRunner {
624
1000
  metadataPatch.outputBytes = Buffer.byteLength(extra.handoff, "utf8");
625
1001
  }
626
1002
  if (extra?.stopReason) metadataPatch.stopReason = extra.stopReason;
1003
+ // Structured handoff (from the child's handoff tool call).
1004
+ if (this.structuredHandoff) metadataPatch.handoffData = this.structuredHandoff;
1005
+ // R2: partial handoff from a killed child — first-class receipt field.
1006
+ if (extra?.partialHandoff !== undefined) {
1007
+ metadataPatch.partialHandoff = extra.partialHandoff;
1008
+ }
1009
+ // R3: locate + record the child's durable session file (new runs).
1010
+ if (!this.req.sessionPath) {
1011
+ const sessionPath = this.locateChildSession();
1012
+ if (sessionPath) metadataPatch.sessionPath = sessionPath;
1013
+ }
1014
+ // R6: post-run worktree delta (bounded).
1015
+ const gitDelta = gitDeltaSince(this.req.cwd);
1016
+ if (gitDelta) metadataPatch.gitDelta = gitDelta;
627
1017
  if (effectiveError) {
628
1018
  metadataPatch.errorCode = effectiveError.code;
629
1019
  metadataPatch.errorMessage = effectiveError.message;
@@ -664,10 +1054,15 @@ export class DelegateRunner {
664
1054
  private synthesizedTerminalError(state: RunTerminalState): DelegateError | undefined {
665
1055
  switch (state) {
666
1056
  case "timed_out_idle":
667
- return {
668
- code: "E_TIMEOUT_IDLE",
669
- message: `no child activity for ${formatDuration(this.cfg.inactivityTimeoutMs)} (inactivity watchdog)`,
670
- };
1057
+ return this.openToolCalls.size > 0
1058
+ ? {
1059
+ code: "E_TIMEOUT_IDLE",
1060
+ 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)`,
1061
+ }
1062
+ : {
1063
+ code: "E_TIMEOUT_IDLE",
1064
+ message: `no child activity for ${formatDuration(this.cfg.inactivityTimeoutMs)} (inactivity watchdog)`,
1065
+ };
671
1066
  case "timed_out_hard":
672
1067
  return {
673
1068
  code: "E_TIMEOUT_HARD",
@@ -685,7 +1080,7 @@ export class DelegateRunner {
685
1080
 
686
1081
  private outcome(
687
1082
  state: RunTerminalState,
688
- extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage },
1083
+ extra?: { handoff?: string; truncated?: boolean; stopReason?: string; usage?: DelegateUsage; partialHandoff?: string },
689
1084
  error?: DelegateError,
690
1085
  ): RunnerOutcome {
691
1086
  const finishedAt = new Date().toISOString();
@@ -694,6 +1089,7 @@ export class DelegateRunner {
694
1089
  runId: this.runId,
695
1090
  state,
696
1091
  handoff: state === "succeeded" ? extra?.handoff ?? "" : "",
1092
+ partialHandoff: state !== "succeeded" ? extra?.partialHandoff : undefined,
697
1093
  outputBytes: Buffer.byteLength(extra?.handoff ?? "", "utf8"),
698
1094
  outputTruncated: extra?.truncated ?? false,
699
1095
  startedAt: this.startedAt,
@@ -726,6 +1122,25 @@ export class DelegateRunner {
726
1122
  if (this.lastActions.length > 10) this.lastActions.shift();
727
1123
  }
728
1124
 
1125
+ /** Names of tools currently in flight (for live views). */
1126
+ private openToolNames(): string[] {
1127
+ const names = new Set<string>();
1128
+ for (const id of this.openToolCalls) {
1129
+ const name = this.toolNames.get(id);
1130
+ if (name) names.add(name);
1131
+ }
1132
+ return [...names];
1133
+ }
1134
+
1135
+ /** Live feed fan-out (unthrottled; views bound what they keep). */
1136
+ private emitEvent(event: FeedEvent): void {
1137
+ try {
1138
+ this.hooks.onEvent?.(event);
1139
+ } catch {
1140
+ // feed failures never affect the run
1141
+ }
1142
+ }
1143
+
729
1144
  private pushUpdate(phase: "starting" | "running" | `tool:${string}` | "finalizing"): void {
730
1145
  if (!this.hooks.onUpdate) return;
731
1146
  const now = Date.now();
@@ -735,6 +1150,8 @@ export class DelegateRunner {
735
1150
  runId: this.runId,
736
1151
  role: this.req.role.name,
737
1152
  phase,
1153
+ model: this.req.parentModel,
1154
+ openTools: this.openToolNames(),
738
1155
  elapsedMs: this.startedAtMs ? now - this.startedAtMs : 0,
739
1156
  lastActions: this.lastActions.slice(-5),
740
1157
  usage: { ...this.usage, turns: this.turns },
@@ -772,6 +1189,30 @@ export class DelegateRunner {
772
1189
  }, 250);
773
1190
  }
774
1191
 
1192
+ /**
1193
+ * R3: find the child's durable session file. New runs spawn with
1194
+ * `--session-dir <runsDir>/sessions`; pi names the file itself, so we
1195
+ * take the newest session file in that directory written during this
1196
+ * run's lifetime. Best-effort: absent when pi did not persist one.
1197
+ */
1198
+ private locateChildSession(): string | undefined {
1199
+ const dir = this.req.sessionDir;
1200
+ if (!dir || !this.startedAtMs) return undefined;
1201
+ try {
1202
+ const names = fs.readdirSync(dir).filter((n) => n.endsWith(".jsonl"));
1203
+ let best: { name: string; mtime: number } | null = null;
1204
+ for (const name of names) {
1205
+ const st = fs.statSync(path.join(dir, name));
1206
+ if (st.mtimeMs >= this.startedAtMs - 2_000 && (!best || st.mtimeMs > best.mtime)) {
1207
+ best = { name, mtime: st.mtimeMs };
1208
+ }
1209
+ }
1210
+ return best ? path.join(dir, best.name) : undefined;
1211
+ } catch {
1212
+ return undefined;
1213
+ }
1214
+ }
1215
+
775
1216
  private cleanup(): void {
776
1217
  // NOTE: reap timers intentionally survive cleanup — they must run to
777
1218
  // completion to guarantee the child is killed (short-lived refs).
@@ -779,6 +1220,10 @@ export class DelegateRunner {
779
1220
  if (this.hardTimer) clearTimeout(this.hardTimer);
780
1221
  if (this.killGraceTimer) clearTimeout(this.killGraceTimer);
781
1222
  if (this.settleExitTimer) clearTimeout(this.settleExitTimer);
1223
+ if (this.handoffGraceTimer) clearTimeout(this.handoffGraceTimer);
1224
+ if (this.handoffSettleTimer) clearTimeout(this.handoffSettleTimer);
1225
+ if (this.handoffEnforceTimer) clearTimeout(this.handoffEnforceTimer);
1226
+ if (this.killEscalateTimer) clearTimeout(this.killEscalateTimer);
782
1227
  this.inactivityTimer = null;
783
1228
  this.hardTimer = null;
784
1229
  this.killGraceTimer = null;
@@ -805,6 +1250,73 @@ export class DelegateRunner {
805
1250
  }
806
1251
 
807
1252
 
1253
+ // ── R6: git worktree checkpoints (bounded, best-effort, non-fatal) ─────────
1254
+
1255
+ function gitExec(cwd: string, args: string[]): string | null {
1256
+ try {
1257
+ const out = childProcess.execFileSync("git", args, {
1258
+ cwd,
1259
+ encoding: "utf8",
1260
+ timeout: 3000,
1261
+ stdio: ["ignore", "pipe", "ignore"],
1262
+ maxBuffer: 512 * 1024,
1263
+ });
1264
+ return out.trim();
1265
+ } catch {
1266
+ return null;
1267
+ }
1268
+ }
1269
+
1270
+ function isGitWorktree(cwd: string): boolean {
1271
+ return gitExec(cwd, ["rev-parse", "--is-inside-work-tree"]) === "true";
1272
+ }
1273
+
1274
+ /** Snapshot HEAD + bounded dirty status at run start. */
1275
+ export function gitCheckpoint(cwd: string): { gitBase: string; gitStatus?: string } | null {
1276
+ if (!isGitWorktree(cwd)) return null;
1277
+ const head = gitExec(cwd, ["rev-parse", "HEAD"]);
1278
+ if (!head) return null;
1279
+ const status = gitExec(cwd, ["status", "--porcelain"]);
1280
+ const bounded = status ? status.split("\n").slice(0, 40).join("\n").slice(0, 2000) : "";
1281
+ return { gitBase: head, ...(bounded ? { gitStatus: bounded } : {}) };
1282
+ }
1283
+
1284
+ /**
1285
+ * Bounded post-run worktree delta at finalization: `git diff --stat HEAD`
1286
+ * plus untracked files (a killed child's brand-new files are exactly the
1287
+ * evidence that matters — `diff HEAD` alone would hide them).
1288
+ */
1289
+ export function gitDeltaSince(cwd: string, _since?: string): string | null {
1290
+ if (!isGitWorktree(cwd)) return null;
1291
+ const parts: string[] = [];
1292
+ const diff = gitExec(cwd, ["diff", "--stat", "HEAD"]);
1293
+ if (diff) parts.push(diff);
1294
+ const untracked = gitExec(cwd, ["ls-files", "--others", "--exclude-standard"]);
1295
+ if (untracked) {
1296
+ parts.push(
1297
+ untracked
1298
+ .split("\n")
1299
+ .slice(0, 40)
1300
+ .map((f) => `untracked: ${f}`)
1301
+ .join("\n"),
1302
+ );
1303
+ }
1304
+ if (parts.length === 0) return null;
1305
+ return parts.join("\n").slice(0, 4000);
1306
+ }
1307
+
1308
+ /** Feed detail for a tool start: command/path head (display-safe). */
1309
+ function feedDetailFor(toolName: string, args?: Record<string, unknown>): string {
1310
+ const a = (key: string): string => {
1311
+ const v = args?.[key];
1312
+ return typeof v === "string" ? v : "";
1313
+ };
1314
+ const v = a("command") || a("path") || a("pattern") || a("query");
1315
+ if (v) return v.replace(/\s+/g, " ").slice(0, 90);
1316
+ if (toolName === "handoff") return "structured submission";
1317
+ return "";
1318
+ }
1319
+
808
1320
  /**
809
1321
  * Display-safe one-liner for a child tool call (never fed to the model).
810
1322
  * Keeps at most ~100 visible chars; args are user-visible command/path