@xzzpig/pi-subagents 0.19.0 → 0.21.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.
Files changed (153) hide show
  1. package/CHANGELOG.md +214 -0
  2. package/README.md +1 -1
  3. package/agents/oracle.md +8 -19
  4. package/agents/researcher.md +0 -3
  5. package/agents/reviewer.md +17 -61
  6. package/agents/scout.md +1 -4
  7. package/agents/worker.md +8 -25
  8. package/docs/agents.md +86 -11
  9. package/docs/configuration.md +68 -7
  10. package/docs/extension-api.md +37 -12
  11. package/docs/fork-extensions.md +1 -0
  12. package/docs/missions.md +48 -17
  13. package/docs/models.md +7 -3
  14. package/docs/observability.md +18 -8
  15. package/docs/tool-reference.md +138 -80
  16. package/docs/watchdog.md +8 -6
  17. package/docs/workflows.md +18 -9
  18. package/index.ts +5 -0
  19. package/package.json +5 -3
  20. package/prompts/council.md +1 -1
  21. package/skills/pi-subagents/SKILL.md +1 -1
  22. package/skills/pi-subagents/references/constraints-and-recipes.md +1 -1
  23. package/skills/pi-subagents/references/execution-controls.md +16 -16
  24. package/skills/pi-subagents/references/management-authoring-rpc.md +16 -12
  25. package/skills/pi-subagents/references/prompting-and-roles.md +3 -3
  26. package/src/agents/advertised-agent-prompt.ts +9 -1
  27. package/src/agents/agent-management.ts +4 -0
  28. package/src/agents/agent-memory.ts +3 -3
  29. package/src/agents/agent-scope.ts +4 -0
  30. package/src/agents/agent-serializer.ts +8 -1
  31. package/src/agents/agents.ts +224 -122
  32. package/src/api/preflight.ts +50 -5
  33. package/src/extension/config.ts +24 -2
  34. package/src/extension/context-injection.ts +6 -1
  35. package/src/extension/control-notices.ts +1 -9
  36. package/src/extension/declaration-pinning.ts +164 -0
  37. package/src/extension/doctor.ts +7 -10
  38. package/src/extension/fanout-child.ts +7 -8
  39. package/src/extension/index.ts +134 -145
  40. package/src/extension/public-execution.ts +3 -0
  41. package/src/extension/reply-workflow-script.ts +21 -12
  42. package/src/extension/rpc.ts +12 -7
  43. package/src/extension/schemas.ts +39 -33
  44. package/src/extension/subagent-guide.ts +86 -6
  45. package/src/extension/subagent-options.ts +47 -0
  46. package/src/extension/tool-activation.ts +3 -2
  47. package/src/extension/tool-description.ts +51 -68
  48. package/src/inspectors/actions.ts +37 -11
  49. package/src/inspectors/plugins.ts +3 -2
  50. package/src/inspectors/tmux/actions.ts +204 -0
  51. package/src/inspectors/tmux/client.ts +85 -0
  52. package/src/inspectors/tmux/plugin.ts +21 -0
  53. package/src/integrations/herdr-status.ts +18 -49
  54. package/src/integrations/program-status.ts +215 -0
  55. package/src/intercom/native-supervisor-channel.ts +77 -4
  56. package/src/intercom/result-intercom.ts +3 -2
  57. package/src/intercom/supervisor-ui.ts +2 -174
  58. package/src/missions/goal-driver.ts +44 -31
  59. package/src/missions/store.ts +35 -6
  60. package/src/profiles/profiles.ts +29 -23
  61. package/src/runs/background/active-async-capacity.ts +58 -8
  62. package/src/runs/background/async-execution.ts +231 -44
  63. package/src/runs/background/async-job-tracker.ts +12 -4
  64. package/src/runs/background/async-resume.ts +5 -2
  65. package/src/runs/background/await-async-run.ts +18 -11
  66. package/src/runs/background/binary-bootstrap.ts +2 -1
  67. package/src/runs/background/calendar-schedule.ts +90 -0
  68. package/src/runs/background/chain-root-attachment.ts +9 -5
  69. package/src/runs/background/control-channel.ts +43 -0
  70. package/src/runs/background/fleet-view.ts +5 -5
  71. package/src/runs/background/notify.ts +185 -12
  72. package/src/runs/background/result-files.ts +116 -5
  73. package/src/runs/background/result-watcher.ts +99 -66
  74. package/src/runs/background/resume-guidance.ts +2 -2
  75. package/src/runs/background/run-child-session.ts +29 -8
  76. package/src/runs/background/run-id-resolver.ts +8 -5
  77. package/src/runs/background/run-status.ts +21 -16
  78. package/src/runs/background/runner-aliases.ts +7 -4
  79. package/src/runs/background/runner-child-launch.ts +1 -0
  80. package/src/runs/background/runner-http-dispatcher.ts +3 -0
  81. package/src/runs/background/scheduled-runs.ts +282 -72
  82. package/src/runs/background/stale-run-reconciler.ts +13 -2
  83. package/src/runs/background/subagent-runner-bootstrap.ts +4 -1
  84. package/src/runs/background/subagent-runner.ts +75 -16
  85. package/src/runs/background/subagent-wait.ts +38 -19
  86. package/src/runs/background/terminal-run-index.ts +46 -1
  87. package/src/runs/background/wait-completions.ts +1 -0
  88. package/src/runs/background/wait-tool.ts +33 -23
  89. package/src/runs/background/workflow-terminal-proof.ts +39 -22
  90. package/src/runs/foreground/async-stop-action.ts +48 -22
  91. package/src/runs/foreground/command-action.ts +41 -0
  92. package/src/runs/foreground/execution.ts +109 -58
  93. package/src/runs/foreground/foreground-history.ts +1 -0
  94. package/src/runs/foreground/subagent-executor.ts +270 -89
  95. package/src/runs/shared/child-commands.ts +229 -0
  96. package/src/runs/shared/child-hooks.ts +4 -3
  97. package/src/runs/shared/child-launch.ts +3 -0
  98. package/src/runs/shared/child-session.ts +131 -40
  99. package/src/runs/shared/child-tool-plan.ts +14 -27
  100. package/src/runs/shared/claude-code-adapter.ts +157 -2
  101. package/src/runs/shared/dynamic-fanout.ts +2 -2
  102. package/src/runs/shared/external-cli-preflight.ts +54 -6
  103. package/src/runs/shared/external-cli-runner.ts +5 -1
  104. package/src/runs/shared/fork-command-result.ts +10 -0
  105. package/src/runs/shared/herdr-placed-run.ts +5 -4
  106. package/src/runs/shared/mcp-direct-tool-allowlist.ts +8 -5
  107. package/src/runs/shared/model-resolution-diagnostic.ts +25 -0
  108. package/src/runs/shared/model-resolution.ts +39 -2
  109. package/src/runs/shared/nested-events.ts +5 -0
  110. package/src/runs/shared/parallel-handoff.ts +56 -8
  111. package/src/runs/shared/parallel-utils.ts +4 -0
  112. package/src/runs/shared/partial-output.ts +48 -0
  113. package/src/runs/shared/run-history.ts +87 -0
  114. package/src/runs/shared/runner-launcher.ts +25 -0
  115. package/src/runs/shared/single-output.ts +53 -0
  116. package/src/runs/shared/structured-output.ts +14 -7
  117. package/src/runs/shared/subagent-control.ts +33 -18
  118. package/src/runs/shared/subagent-prompt-runtime.ts +59 -30
  119. package/src/runs/shared/workflow-async-child-guidance.ts +1 -1
  120. package/src/runs/shared/worktree-cleanup-apply.ts +160 -0
  121. package/src/runs/shared/worktree-cleanup-plan.ts +41 -19
  122. package/src/runs/shared/worktree-lock.ts +29 -0
  123. package/src/runs/shared/worktree.ts +12 -1
  124. package/src/shared/atomic-json.ts +4 -2
  125. package/src/shared/edit-distance.ts +33 -0
  126. package/src/shared/file-lease.ts +74 -0
  127. package/src/shared/formatters.ts +1 -5
  128. package/src/shared/model-info.ts +22 -0
  129. package/src/shared/package-version.ts +17 -0
  130. package/src/shared/parent-wake.ts +79 -0
  131. package/src/shared/pruned-fork.ts +7 -1
  132. package/src/shared/required-child-extensions.ts +39 -5
  133. package/src/shared/runtime-module-path.ts +19 -0
  134. package/src/shared/settings-file-lease.ts +36 -0
  135. package/src/shared/types.ts +42 -3
  136. package/src/shared/utils.ts +8 -6
  137. package/src/slash/slash-commands.ts +3 -3
  138. package/src/slash/subagent-cost.ts +9 -5
  139. package/src/slash/subagents-admin.ts +2 -1
  140. package/src/tui/fleet-native-transcript.ts +2 -0
  141. package/src/tui/fleet-transcript.ts +12 -3
  142. package/src/tui/fleet.ts +11 -8
  143. package/src/tui/render.ts +28 -20
  144. package/src/tui/subagent-messages.ts +305 -0
  145. package/src/watchdog/diff-tool.ts +2 -2
  146. package/src/watchdog/register-main.ts +2 -22
  147. package/src/watchdog/render.ts +2 -24
  148. package/src/watchdog/runtime.ts +6 -4
  149. package/src/watchdog/settings.ts +18 -13
  150. package/src/watchdog/tool-actions.ts +2 -2
  151. package/src/workflows/scripted-workflow.ts +20 -6
  152. package/src/workflows/workflow-receipt.ts +2 -2
  153. package/src/workflows/workflow-resources.ts +18 -4
@@ -1,3 +1,4 @@
1
+ import { withHandoffWriteLock, withRepositoryWorktreeLock } from "./worktree-lock.ts";
1
2
  import * as fs from "node:fs";
2
3
  import * as path from "node:path";
3
4
  import { writeAtomicJson } from "../../shared/atomic-json.ts";
@@ -20,7 +21,7 @@ import type {
20
21
  WorktreeSetupProgress,
21
22
  WorktreeCleanupIntent,
22
23
  } from "./worktree.ts";
23
- import { cleanupWorktrees } from "./worktree.ts";
24
+ import { cleanupWorktrees, withWorktreeTransaction } from "./worktree.ts";
24
25
  import { assertWorkflowLaneKey, normalizeWorkflowLaneMetadata } from "./lane-metadata.ts";
25
26
 
26
27
  export interface ParallelHandoffResult {
@@ -159,6 +160,26 @@ function pathInside(root: string, candidate: string): boolean {
159
160
  return relative === "" || (relative !== ".." && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative));
160
161
  }
161
162
 
163
+ export async function protectRetainedWorktreeForResume(manifestPath: string, runId: string, childIndex: number, signal?: AbortSignal): Promise<string> {
164
+ const original = readParallelHandoffManifest(manifestPath);
165
+ const group = original?.groups.find((item) => item.children.some((child) => child.index === childIndex));
166
+ if (!group) throw new Error("Retained worktree handoff disappeared before resume admission.");
167
+ return withWorktreeTransaction(() => withRepositoryWorktreeLock(group.repoRoot, () => withHandoffWriteLock(manifestPath, () => {
168
+ signal?.throwIfAborted();
169
+ const cwd = resolveRetainedWorktreeCwd(manifestPath, runId, childIndex);
170
+ if (!cwd) throw new Error("Retained worktree ownership disappeared before resume admission.");
171
+ const manifest = readParallelHandoffManifest(manifestPath)!;
172
+ const currentGroup = manifest.groups.find((item) => item.children.some((child) => child.index === childIndex))!;
173
+ const child = currentGroup.children.find((item) => item.index === childIndex)!;
174
+ const task = currentGroup.cleanup.tasks.find((item) => item.index === child.taskIndex)!;
175
+ task.preserved = true;
176
+ task.reason = "retained child resume requires managed worktree cwd";
177
+ manifest.updatedAt = Date.now();
178
+ writeAtomicJson(manifestPath, manifest);
179
+ return cwd;
180
+ }), { signal }));
181
+ }
182
+
162
183
  export function resolveRetainedWorktreeCwd(manifestPath: string, runId: string, childIndex: number): string | undefined {
163
184
  const manifest = readParallelHandoffManifest(manifestPath);
164
185
  if (!manifest) return undefined;
@@ -405,7 +426,7 @@ function firstRepositoryRoot(manifest: ParallelHandoffManifest): string | undefi
405
426
 
406
427
  function formatCleanupCommand(manifestPath: string, manifest: ParallelHandoffManifest): string | undefined {
407
428
  const repoRoot = firstRepositoryRoot(manifest);
408
- return repoRoot ? `subagent({ action: "worktree.cleanup", repo: ${JSON.stringify(repoRoot)}, handoffPath: ${JSON.stringify(manifestPath)}, mode: "plan" })` : undefined;
429
+ return repoRoot ? `subagent({ action: "worktree.cleanup", options: { repo: ${JSON.stringify(repoRoot)}, handoffPath: ${JSON.stringify(manifestPath)}, mode: "plan" } })` : undefined;
409
430
  }
410
431
 
411
432
  export function formatStoredParallelHandoffCleanup(manifestPath: string, manifest?: ParallelHandoffManifest): string {
@@ -417,7 +438,7 @@ export function formatStoredParallelHandoffCleanup(manifestPath: string, manifes
417
438
  stored = undefined;
418
439
  }
419
440
  }
420
- if (!stored) return ["Cleanup eligibility: unknown", "Reason: lane manifest is missing or invalid; removal is not safe.", `Plan command: subagent({ action: "worktree.cleanup", handoffPath: ${JSON.stringify(manifestPath)}, mode: "plan" })`].join("\n");
441
+ if (!stored) return ["Cleanup eligibility: unknown", "Reason: lane manifest is missing or invalid; removal is not safe.", `Plan command: subagent({ action: "worktree.cleanup", options: { handoffPath: ${JSON.stringify(manifestPath)}, mode: "plan" } })`].join("\n");
421
442
  const eligibility = trustedStoredCleanupEligibility(stored);
422
443
  const lines = [`Cleanup eligibility: ${eligibility.state}`];
423
444
  if (eligibility.state === "terminal-blocked") lines.push(`Reason: ${eligibility.reason}`);
@@ -434,7 +455,11 @@ export interface ParallelHandoffEvidenceResult {
434
455
  text: string;
435
456
  }
436
457
 
437
- export function recordParallelHandoffMerge(input: { manifestPath: string; laneId: string; merge: unknown; now?: number }): ParallelHandoffEvidenceResult {
458
+ export function recordParallelHandoffMerge(...args: Parameters<typeof recordParallelHandoffMergeUnlocked>): ReturnType<typeof recordParallelHandoffMergeUnlocked> {
459
+ return withHandoffWriteLock(args[0].manifestPath, () => recordParallelHandoffMergeUnlocked(...args));
460
+ }
461
+
462
+ function recordParallelHandoffMergeUnlocked(input: { manifestPath: string; laneId: string; merge: unknown; now?: number }): ParallelHandoffEvidenceResult {
438
463
  const manifest = readParallelHandoffManifest(input.manifestPath);
439
464
  if (!manifest) throw new Error(`Parallel handoff manifest not found: ${input.manifestPath}`);
440
465
  validateManifestForLaneEvidence(manifest, boundedString(input.laneId, "laneId", MAX_SUPERSESSION_ID_LENGTH));
@@ -452,7 +477,11 @@ export function recordParallelHandoffMerge(input: { manifestPath: string; laneId
452
477
  return { manifest: updated, reference: referenceFor(input.manifestPath, updated), text: formatStoredParallelHandoffCleanup(input.manifestPath, updated) };
453
478
  }
454
479
 
455
- export function recordParallelHandoffSupersession(input: { manifestPath: string; laneId: string; supersession: unknown; now?: number }): ParallelHandoffEvidenceResult {
480
+ export function recordParallelHandoffSupersession(...args: Parameters<typeof recordParallelHandoffSupersessionUnlocked>): ReturnType<typeof recordParallelHandoffSupersessionUnlocked> {
481
+ return withHandoffWriteLock(args[0].manifestPath, () => recordParallelHandoffSupersessionUnlocked(...args));
482
+ }
483
+
484
+ function recordParallelHandoffSupersessionUnlocked(input: { manifestPath: string; laneId: string; supersession: unknown; now?: number }): ParallelHandoffEvidenceResult {
456
485
  const manifest = readParallelHandoffManifest(input.manifestPath);
457
486
  if (!manifest) throw new Error(`Parallel handoff manifest not found: ${input.manifestPath}`);
458
487
  const laneId = boundedString(input.laneId, "laneId", MAX_SUPERSESSION_ID_LENGTH);
@@ -494,7 +523,11 @@ function missingDiff(input: { manifestPath: string; stepIndex: number; taskIndex
494
523
  };
495
524
  }
496
525
 
497
- export function writeParallelHandoffGroup(input: {
526
+ export function writeParallelHandoffGroup(...args: Parameters<typeof writeParallelHandoffGroupUnlocked>): ReturnType<typeof writeParallelHandoffGroupUnlocked> {
527
+ return withHandoffWriteLock(args[0].manifestPath, () => writeParallelHandoffGroupUnlocked(...args));
528
+ }
529
+
530
+ function writeParallelHandoffGroupUnlocked(input: {
498
531
  manifestPath: string;
499
532
  runId: string;
500
533
  mode: "single" | "parallel" | "chain";
@@ -577,6 +610,7 @@ export function writeParallelHandoffGroup(input: {
577
610
  branch: worktree.branch,
578
611
  ...(worktree.provider ? { provider: worktree.provider } : {}),
579
612
  ...(worktree.naming ? { naming: worktree.naming } : {}),
613
+ ...(worktree.recordedBaseDir ? { recordedBaseDir: worktree.recordedBaseDir } : {}),
580
614
  worktreeRemoved: false,
581
615
  branchRemoved: false,
582
616
  preserved: true,
@@ -584,6 +618,15 @@ export function writeParallelHandoffGroup(input: {
584
618
  })),
585
619
  },
586
620
  };
621
+ for (const task of group.cleanup.tasks) {
622
+ const previous = existing?.groups.flatMap((item) => item.cleanup.tasks).find((item) => item.path === task.path && item.branch === task.branch);
623
+ if (previous?.worktreeRemoved) task.worktreeRemoved = true;
624
+ if (previous?.branchRemoved) task.branchRemoved = true;
625
+ if (!task.worktreeRemoved && previous?.reason?.includes("retained child resume")) {
626
+ task.preserved = true;
627
+ task.reason = previous.reason;
628
+ }
629
+ }
587
630
  const groups = existing?.groups.filter((candidate) => candidate.stepIndex !== input.stepIndex) ?? [];
588
631
  groups.push(group);
589
632
  groups.sort((left, right) => left.stepIndex - right.stepIndex);
@@ -664,7 +707,7 @@ export function writeWorktreeSetupHandoff(input: Omit<Parameters<typeof writePar
664
707
  const task = cleanup?.tasks.find((candidate) => candidate.index === worktree.index);
665
708
  return task ? { ...task, reason: task.reason && diagnostic(task.reason), errors: task.errors?.map(diagnostic) } : {
666
709
  index: worktree.index, path: worktree.path, branch: worktree.branch,
667
- provider: worktree.provider, naming: worktree.naming,
710
+ provider: worktree.provider, naming: worktree.naming, recordedBaseDir: worktree.recordedBaseDir,
668
711
  worktreeRemoved: false, branchRemoved: false, preserved: true,
669
712
  reason: "setup pending durable handoff capture",
670
713
  };
@@ -681,7 +724,11 @@ export function formatParallelHandoffError(error: unknown): string {
681
724
  return `Worktree handoff unavailable: ${error instanceof Error ? error.message : String(error)}`;
682
725
  }
683
726
 
684
- export function discardPreservedWorktrees(
727
+ export function discardPreservedWorktrees(...args: Parameters<typeof discardPreservedWorktreesUnlocked>): ReturnType<typeof discardPreservedWorktreesUnlocked> {
728
+ return withHandoffWriteLock(args[0], () => discardPreservedWorktreesUnlocked(...args));
729
+ }
730
+
731
+ function discardPreservedWorktreesUnlocked(
685
732
  manifestPath: string,
686
733
  authorization: Extract<WorktreeCleanupIntent, { kind: "discard" }>["authorization"],
687
734
  ): { manifest: ParallelHandoffManifest; text: string } {
@@ -702,6 +749,7 @@ export function discardPreservedWorktrees(
702
749
  branch: task.branch,
703
750
  ...(task.provider ? { provider: task.provider } : {}),
704
751
  ...(task.naming ? { naming: task.naming } : {}),
752
+ ...(task.recordedBaseDir ? { recordedBaseDir: task.recordedBaseDir } : {}),
705
753
  index: task.index,
706
754
  nodeModulesLinked: false,
707
755
  syntheticPaths: [],
@@ -3,6 +3,8 @@ export type ResolvedRunnerConfig = import("../../shared/types.ts").AgentRunnerCo
3
3
  export interface RunnerSubagentStep {
4
4
  /** Session id of the direct parent session for permission-system ask forwarding. */
5
5
  parentSessionId?: string;
6
+ /** Parent session file, recorded as the new child session's `parentSession` header. */
7
+ parentSessionFile?: string;
6
8
  /** Resolved opt-in rules for native Pi child tool calls. */
7
9
  permissionRules?: import("./permissions.ts").PermissionRules;
8
10
  /** Parent-authoritative trust state for profile-aware project config merging. */
@@ -44,6 +46,8 @@ export interface RunnerSubagentStep {
44
46
  contextLimit?: number;
45
47
  fast?: boolean;
46
48
  thinking?: string;
49
+ /** Trailing Claude Code argv for an explicit model/thinking request. */
50
+ claudeCodeOverrideArgs?: string[];
47
51
  thinkingCeiling?: import("../../shared/model-info.ts").ThinkingLevel;
48
52
  requestedModel?: string;
49
53
  /** The primary model is inherited from the parent session and should not be verified against the child-reported active registry model. */
@@ -0,0 +1,48 @@
1
+ /**
2
+ * Unfinished assistant text recovered when a child ends abnormally.
3
+ *
4
+ * Final output is built from completed `message_end` messages, so text that was
5
+ * still streaming when a child timed out or its session threw is otherwise lost.
6
+ * The tracker keeps one in-memory reference to the latest unfinished assistant
7
+ * message. Nothing is persisted.
8
+ */
9
+ import type { ChildSessionEvent } from "./child-session.ts";
10
+ import { extractTextFromContent } from "../../shared/utils.ts";
11
+
12
+ export type PartialOutputCause = "timeout" | "child error";
13
+
14
+ export interface PartialOutputTracker {
15
+ observe(event: ChildSessionEvent): void;
16
+ /** Latest unfinished assistant text that is newer than the last completed reply. */
17
+ text(): string | undefined;
18
+ }
19
+
20
+ function isAssistant(message: unknown): boolean {
21
+ return !!message && typeof message === "object" && (message as { role?: unknown }).role === "assistant";
22
+ }
23
+
24
+ function isErroredAssistant(message: unknown): boolean {
25
+ const { stopReason, errorMessage } = message as { stopReason?: unknown; errorMessage?: unknown };
26
+ return stopReason === "error" || (typeof errorMessage === "string" && errorMessage.length > 0);
27
+ }
28
+
29
+ export function createPartialOutputTracker(): PartialOutputTracker {
30
+ // Only a reference is kept per event; text is extracted once, when a child ends abnormally.
31
+ let latest: { content?: unknown } | undefined;
32
+ return {
33
+ observe(event) {
34
+ if ((event.type !== "message_update" && event.type !== "message_end") || !isAssistant(event.message)) return;
35
+ // A completed reply, including a tool-only one, is already part of the final output.
36
+ // A provider-error message is skipped there, so its text is the newest unfinished text.
37
+ latest = event.type === "message_update" || isErroredAssistant(event.message) ? event.message as { content?: unknown } : undefined;
38
+ },
39
+ text() {
40
+ const text = extractTextFromContent(latest?.content);
41
+ return text.trim() ? text : undefined;
42
+ },
43
+ };
44
+ }
45
+
46
+ export function formatPartialOutput(text: string, cause: PartialOutputCause): string {
47
+ return `Partial output before ${cause}:\n${text}`;
48
+ }
@@ -133,6 +133,93 @@ function appendPrivateHistoryLine(historyPath: string, line: string): void {
133
133
  }
134
134
  }
135
135
 
136
+ function backgroundRunHistoryTask(steps: readonly unknown[], resultMode: string): string {
137
+ const step = steps.length === 1 && typeof steps[0] === "object" && steps[0] !== null
138
+ ? (steps[0] as { task?: unknown; launchBindingTask?: unknown })
139
+ : undefined;
140
+ if (step) {
141
+ const task = typeof step.launchBindingTask === "string" && step.launchBindingTask ? step.launchBindingTask : step.task;
142
+ if (typeof task === "string" && task) return task;
143
+ }
144
+ return resultMode || "run";
145
+ }
146
+
147
+ export interface BackgroundRunHistoryEntry {
148
+ agent: string;
149
+ task: string;
150
+ exitCode: number;
151
+ durationMs: number;
152
+ terminal: Pick<NonNullable<Parameters<typeof recordRun>[4]>, "stopped" | "interrupted" | "timedOut" | "processSignal">;
153
+ }
154
+
155
+ const TERMINAL_STEP_STATUSES = new Set(["complete", "completed"]);
156
+ /** Steps that reached THEIR OWN terminal state — run-wide flags must not relabel them. */
157
+ const SELF_TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "rejected"]);
158
+
159
+ /**
160
+ * Census rows for one finished background run. Single-step runs keep the exact
161
+ * foreground shape (agent + task text). Multi-step runs record ONE ROW PER CHILD
162
+ * STEP so `loadRunsForAgent(agent)` sees every child — a composite-only row would
163
+ * stay invisible to per-agent lookups. Per-step prompts are never hashed:
164
+ * multi-step rows hash the mode label only.
165
+ *
166
+ * Fidelity rules:
167
+ * - a row is recorded only for children that actually LAUNCHED (a child
168
+ * session was dispatched). Status alone cannot decide this: `stopRunner()`,
169
+ * `timeoutRunner()`, fail-fast skips, and usage-budget skips all relabel
170
+ * never-launched steps to terminal statuses (`stopped`, `failed`+`timedOut,
171
+ * `failed`+`skipped) before the run ends — the runner therefore threads an
172
+ * explicit `launched` fact per step. `pending` and `launched: false` steps
173
+ * get no row — unrun agents must not accumulate attempts or failures;
174
+ * - run-level terminal flags (stopped/interrupted/timedOut) apply only to steps
175
+ * that did not reach a terminal state of their own — a child that completed
176
+ * or failed BEFORE a sibling was interrupted keeps its own outcome, because
177
+ * recordRun() lets those flags override the exit code;
178
+ * - self-terminal steps carry their own timedOut/stopped flags instead.
179
+ */
180
+ export function planBackgroundRunHistory(input: {
181
+ steps: readonly unknown[];
182
+ resultMode: string;
183
+ statusSteps: ReadonlyArray<{ agent?: unknown; status?: unknown; durationMs?: number; timedOut?: boolean; stopped?: boolean; launched?: boolean }>;
184
+ stepResults?: ReadonlyArray<{ processSignal?: unknown } | undefined>;
185
+ runDurationMs: number;
186
+ stopped?: boolean;
187
+ interrupted?: boolean;
188
+ timedOut?: boolean;
189
+ }): BackgroundRunHistoryEntry[] {
190
+ const runTerminal: BackgroundRunHistoryEntry["terminal"] = {
191
+ ...(input.stopped ? { stopped: true } : {}),
192
+ ...(input.interrupted ? { interrupted: true } : {}),
193
+ ...(input.timedOut ? { timedOut: true } : {}),
194
+ };
195
+ const task = backgroundRunHistoryTask(input.steps, input.resultMode);
196
+ const rows: BackgroundRunHistoryEntry[] = [];
197
+ for (const [index, step] of input.statusSteps.entries()) {
198
+ if (typeof step.agent !== "string" || !step.agent) continue;
199
+ // `launched === false` marks steps the runner never dispatched a child
200
+ // session for, regardless of the status they were later relabeled to.
201
+ if (step.status === "pending" || step.launched === false) continue;
202
+ const succeeded = typeof step.status === "string" && TERMINAL_STEP_STATUSES.has(step.status);
203
+ const ownTerminal: BackgroundRunHistoryEntry["terminal"] = {
204
+ ...(step.timedOut === true ? { timedOut: true } : {}),
205
+ ...(step.stopped === true ? { stopped: true } : {}),
206
+ };
207
+ // A step that reached its own terminal state (completed, or failed/rejected
208
+ // before a sibling was interrupted) keeps its own outcome; run-wide flags
209
+ // would relabel it in recordRun().
210
+ const terminal = typeof step.status === "string" && SELF_TERMINAL_STEP_STATUSES.has(step.status) ? ownTerminal : { ...runTerminal, ...ownTerminal };
211
+ const processSignal = input.stepResults?.[index]?.processSignal;
212
+ rows.push({
213
+ agent: step.agent,
214
+ task,
215
+ exitCode: succeeded ? 0 : 1,
216
+ durationMs: typeof step.durationMs === "number" ? step.durationMs : input.runDurationMs,
217
+ terminal: processSignal === undefined ? terminal : { ...terminal, processSignal: typeof processSignal === "string" ? processSignal : null },
218
+ });
219
+ }
220
+ return rows;
221
+ }
222
+
136
223
  export function recordRun(
137
224
  agent: string,
138
225
  task: string,
@@ -0,0 +1,25 @@
1
+ import type { AgentConfig } from "../../agents/agents.ts";
2
+ import type { RunnerLauncher } from "../../shared/types.ts";
3
+
4
+ /** Own-property lookup, so an inherited object key can never select a command. */
5
+ export function lookupRunnerLauncher(runnerLaunchers: Record<string, string[]> | undefined, name: string): RunnerLauncher | undefined {
6
+ const argv = runnerLaunchers && Object.hasOwn(runnerLaunchers, name) ? runnerLaunchers[name] : undefined;
7
+ return argv ? { name, argv: [...argv] } : undefined;
8
+ }
9
+
10
+ /** A launcher wraps the local Pi background runner, so it cannot combine with machine placement or an external runner. */
11
+ export function runnerLauncherPlacementError(agent: Pick<AgentConfig, "name" | "launcher" | "runner">, machine: string | undefined): string | undefined {
12
+ if (agent.launcher === undefined) return undefined;
13
+ const runnerType = agent.runner?.type === "external-cli" || agent.runner?.type === "external-job" ? agent.runner.type : undefined;
14
+ if (!machine && !runnerType) return undefined;
15
+ return `Agent '${agent.name}' uses launcher '${agent.launcher}', which wraps the local Pi background runner, so it cannot run ${machine ? `on machine '${machine}'` : `with runner.type='${runnerType}'`}.`;
16
+ }
17
+
18
+ /** The launcher an agent launch runs under, or the reason it cannot launch. */
19
+ export function resolveAgentRunnerLauncher(agent: Pick<AgentConfig, "name" | "launcher" | "runner">, runnerLaunchers: Record<string, string[]> | undefined, machine: string | undefined): { launcher?: RunnerLauncher; error?: string } {
20
+ if (agent.launcher === undefined) return {};
21
+ const placementError = runnerLauncherPlacementError(agent, machine);
22
+ if (placementError) return { error: placementError };
23
+ const launcher = lookupRunnerLauncher(runnerLaunchers, agent.launcher);
24
+ return launcher ? { launcher } : { error: `Agent '${agent.name}' uses launcher '${agent.launcher}', which is not defined in runnerLaunchers in the user subagent config.` };
25
+ }
@@ -174,6 +174,59 @@ export function formatSavedOutputReference(savedPath: string, fullOutput: string
174
174
  };
175
175
  }
176
176
 
177
+ const INLINE_OUTPUT_HEAD_CHARS = 2_000;
178
+ /** Larger files are not read to check a cap; the output then stays whole. */
179
+ const MAX_FULL_OUTPUT_FILE_BYTES = 50 * 1024 * 1024;
180
+ /** The line finalizeSingleOutput appends when inline output was also saved to an explicit output file. */
181
+ const SAVED_OUTPUT_LINE = /\n\nOutput saved to: (.+) \([^()\n]*\)\. Read this file if needed\.$/;
182
+
183
+ function readFullOutputFile(filePath: string): string | undefined {
184
+ try {
185
+ const stat = fs.statSync(filePath);
186
+ if (!stat.isFile() || stat.size > MAX_FULL_OUTPUT_FILE_BYTES) return undefined;
187
+ return fs.readFileSync(filePath, "utf-8");
188
+ } catch {
189
+ return undefined;
190
+ }
191
+ }
192
+
193
+ /**
194
+ * Keeps at most INLINE_OUTPUT_HEAD_CHARS of a child's output inline and points to the file holding all of it.
195
+ * Files come only from run records, never from the child's text: a trailing `Output saved to:` line is kept as the
196
+ * pointer only when it names the run's recorded saved-output path, and that recorded path is what gets read.
197
+ * Output stays whole when it is short or no readable file contains it, so no text is lost.
198
+ */
199
+ export function capInlineOutput(output: string, files: { artifactPath?: string; savedPath?: string }): string {
200
+ const match = files.savedPath ? output.match(SAVED_OUTPUT_LINE) : null;
201
+ const savedLine = match && files.savedPath && match[1] === path.resolve(files.savedPath) ? match : undefined;
202
+ const body = savedLine ? output.slice(0, savedLine.index) : output;
203
+ const filePath = savedLine ? files.savedPath : files.artifactPath;
204
+ if (body.length <= INLINE_OUTPUT_HEAD_CHARS || !filePath) return output;
205
+ const fullOutput = readFullOutputFile(filePath);
206
+ if (fullOutput === undefined || !fullOutput.includes(body)) return output;
207
+ const lineEnd = body.lastIndexOf("\n", INLINE_OUTPUT_HEAD_CHARS);
208
+ let end = lineEnd >= INLINE_OUTPUT_HEAD_CHARS - 200 ? lineEnd : INLINE_OUTPUT_HEAD_CHARS;
209
+ if (/[\uD800-\uDBFF]/.test(body[end - 1] ?? "")) end -= 1;
210
+ if (savedLine) return `${body.slice(0, end)}\n…${output.slice(body.length)}`;
211
+ const reference = formatSavedOutputReference(filePath, fullOutput);
212
+ return `${body.slice(0, end)}\n…\nFull output: ${reference.path} (${formatByteSize(reference.bytes)}, ${reference.lines} ${reference.lines === 1 ? "line" : "lines"}). Read it if needed.`;
213
+ }
214
+
215
+ /** Applies capInlineOutput to each `agent:\noutput` section of a run summary whose child output is long. */
216
+ export function capSummaryOutputs(summary: string, results: ReadonlyArray<{ agent?: unknown; output?: unknown; artifactPaths?: { outputPath?: unknown }; artifactOutputSaveFailed?: unknown; savedOutputPath?: unknown }> | undefined): string {
217
+ let capped = summary;
218
+ for (const result of results ?? []) {
219
+ if (typeof result.agent !== "string" || typeof result.output !== "string" || result.output.length <= INLINE_OUTPUT_HEAD_CHARS) continue;
220
+ const artifactPath = result.artifactOutputSaveFailed === true || typeof result.artifactPaths?.outputPath !== "string" ? undefined : result.artifactPaths.outputPath;
221
+ const savedPath = typeof result.savedOutputPath === "string" && result.savedOutputPath ? result.savedOutputPath : undefined;
222
+ const section = `${result.agent}:\n${result.output}`;
223
+ const index = capped.indexOf(section);
224
+ if (index < 0) continue;
225
+ capped = `${capped.slice(0, index)}${result.agent}:\n${capInlineOutput(result.output, { artifactPath, savedPath })}${capped.slice(index + section.length)}`;
226
+ }
227
+ return capped;
228
+ }
229
+
177
230
  export function validateFileOnlyOutputMode(outputMode: OutputMode | undefined, outputPath: string | undefined, context: string): string | undefined {
178
231
  if (outputMode === "file-only" && !outputPath) {
179
232
  return `${context} sets outputMode: "file-only" but does not configure an output file. Set output to a path or use outputMode: "inline".`;
@@ -5,6 +5,7 @@ import * as path from "node:path";
5
5
  import { pathToFileURL } from "node:url";
6
6
  import type { Message } from "@earendil-works/pi-ai";
7
7
  import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
8
+ import { resolveInstalledPiPackageRoot, resolvePiPackageRoot } from "./pi-spawn.ts";
8
9
  import type { JsonSchemaObject } from "../../shared/types.ts";
9
10
  import type { ResolvedAcceptanceReportMode } from "./acceptance.ts";
10
11
 
@@ -175,17 +176,23 @@ async function importCompile(): Promise<CompileJsonSchema> {
175
176
  } catch (error) {
176
177
  failures.push(`direct import failed: ${error instanceof Error ? error.message : String(error)}`);
177
178
  }
178
- const packageRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV];
179
- if (packageRoot) {
179
+ // Pi's extension loader imports this compiled file natively, so the lazy import above misses
180
+ // Pi's host-package aliases when TypeBox is installed only in Pi's own tree.
181
+ const envRoot = process.env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]?.trim() || undefined;
182
+ if (!envRoot) failures.push(`${PI_CODING_AGENT_PACKAGE_ROOT_ENV} is not set`);
183
+ const roots = new Map<string, string>();
184
+ for (const [label, root] of [[PI_CODING_AGENT_PACKAGE_ROOT_ENV, envRoot], ["running Pi package root", resolvePiPackageRoot()], ["installed Pi package root", resolveInstalledPiPackageRoot()]] as const) {
185
+ if (root && !roots.has(root)) roots.set(root, label);
186
+ }
187
+ if (roots.size === 0) failures.push("no Pi package root found");
188
+ for (const [root, label] of roots) {
180
189
  try {
181
- const compile = await resolveCompileFromPackageRoot(packageRoot);
190
+ const compile = await resolveCompileFromPackageRoot(root);
182
191
  if (compile) return compile;
183
- failures.push("Pi package root typebox/compile did not export a Compile function");
192
+ failures.push(`${label} ${root}: typebox/compile did not export a Compile function`);
184
193
  } catch (error) {
185
- failures.push(`Pi package root import failed: ${error instanceof Error ? error.message : String(error)}`);
194
+ failures.push(`${label} ${root}: ${error instanceof Error ? error.message : String(error)}`);
186
195
  }
187
- } else {
188
- failures.push(`${PI_CODING_AGENT_PACKAGE_ROOT_ENV} is not set`);
189
196
  }
190
197
  throw new Error(`Cannot load typebox/compile for structured output validation (${failures.join("; ")})`);
191
198
  }
@@ -190,7 +190,8 @@ export function shouldNotifyControlEvent(config: ResolvedControlConfig, event: C
190
190
  export function controlNotificationKey(event: ControlEvent, childIntercomTarget?: string): string {
191
191
  const childKey = childIntercomTarget ?? (event.index !== undefined ? `${event.runId}:${event.index}` : event.runId);
192
192
  const contextHash = createHash("sha256").update(formatControlNudge(event)).digest("hex").slice(0, 8);
193
- return `${childKey}:${event.type}:${event.reason ?? "idle"}:${contextHash}`;
193
+ const callKey = event.reason === "tool_open_threshold" && event.toolCallId ? `:${event.toolCallId}` : "";
194
+ return `${childKey}:${event.type}:${event.reason ?? "idle"}${callKey}:${contextHash}`;
194
195
  }
195
196
 
196
197
  export function claimControlNotification(config: ResolvedControlConfig, event: ControlEvent, seenKeys: Set<string>, childIntercomTarget?: string): boolean {
@@ -226,44 +227,58 @@ export function formatControlNudge(event: ControlEvent): string {
226
227
  export function formatControlNoticeMessage(event: ControlEvent, childIntercomTarget?: string): string {
227
228
  const runTarget = event.runId;
228
229
  const nudgeMessage = formatControlNudge(event);
229
- const steerCommand = `subagent({ action: "steer", id: "${runTarget}", ${event.index !== undefined ? `index: ${event.index}, ` : ""}message: ${JSON.stringify(nudgeMessage)} })`;
230
+ const steerCommand = `subagent({ action: "steer", id: "${runTarget}", message: ${JSON.stringify(nudgeMessage)}${event.index !== undefined ? `, options: { index: ${event.index} }` : ""} })`;
230
231
  const nestedResumeCommand = `subagent({ action: "resume", id: "${runTarget}", message: ${JSON.stringify(nudgeMessage)} })`;
232
+ const facts = formatLongRunningFacts(event);
233
+ const head = (title: string) => [
234
+ `${title}: ${event.agent}`,
235
+ `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
236
+ `Signal: ${event.message}`,
237
+ facts ? `Facts: ${facts}` : undefined,
238
+ ];
239
+ const status = `Status: subagent({ action: "status", id: "${runTarget}" })`;
240
+ const lines = (items: Array<string | undefined>) => items.filter((line): line is string => Boolean(line)).join("\n");
231
241
  if (event.type === "active_long_running") {
232
- const facts = formatLongRunningFacts(event);
233
- return [
234
- `Subagent active but long-running: ${event.agent}`,
235
- `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
236
- `Signal: ${event.message}`,
237
- facts ? `Facts: ${facts}` : undefined,
242
+ return lines([
243
+ ...head("Subagent active but long-running"),
238
244
  "Hint: Inspect status first. Use steer for a top-level live async child, routed resume for a live nested child, or resume to revive a paused/completed/failed child.",
239
245
  `Top-level live async nudge: ${steerCommand}`,
240
246
  `Routed live nested nudge: ${nestedResumeCommand}`,
241
247
  childIntercomTarget ? `Direct intercom target: ${childIntercomTarget}` : undefined,
242
- `Status: subagent({ action: "status", id: "${runTarget}" })`,
248
+ status,
243
249
  `Interrupt: subagent({ action: "interrupt", id: "${runTarget}" })`,
244
- ].filter((line): line is string => Boolean(line)).join("\n");
250
+ ]);
251
+ }
252
+
253
+ if (event.reason === "tool_open_threshold" && event.currentTool === "bash") {
254
+ const command = (label: string, action: string) => `${label}: subagent(${JSON.stringify({ action, id: runTarget, options: { ...(event.index !== undefined ? { index: event.index } : {}), toolCallId: event.toolCallId } })})`;
255
+ return lines([
256
+ ...head("Subagent needs attention"),
257
+ "Hint: Inspect the running command and recent output before nudging. A queued steer does not cancel an in-flight bash call. A dev server or watch command may intentionally never return. Elapsed time alone does not prove the command is stuck.",
258
+ "Recovery: For a local Pi child explicitly granted subagent_command, yield a needed persistent command or cancel the exact incorrect command, then steer the child. Query command.status to confirm the result. If command controls are unavailable, inspect partial changes and interruption scope before interrupt/resume; interrupt is run-scoped and may affect siblings.",
259
+ ...(event.toolCallId ? [command("Command", "command.status"), command("Yield", "command.yield"), command("Cancel", "command.cancel")] : []),
260
+ status,
261
+ `Transcript: subagent({ action: "status", id: "${runTarget}", options: { view: "transcript"${event.index !== undefined ? `, index: ${event.index}` : ""} } })`,
262
+ ]);
245
263
  }
246
264
 
247
265
  const supervisorHint = event.reason === "supervisor_request"
248
266
  ? "Supervisor request: reply to the pending request. If subagent_supervisor pending is empty, check intercom pending because an external intercom tool may own the request."
249
267
  : undefined;
250
- const facts = formatLongRunningFacts(event);
251
- return [
252
- `Subagent needs attention: ${event.agent}`,
253
- `Run: ${runTarget}${event.index !== undefined ? ` step ${event.index + 1}` : ""}`,
254
- `Signal: ${event.message}`,
255
- facts ? `Facts: ${facts}` : undefined,
268
+ return lines([
269
+ ...head("Subagent needs attention"),
256
270
  event.recentFailureSummary ? `Recent failures: ${event.recentFailureSummary}` : undefined,
257
271
  supervisorHint,
258
272
  "Hint: Inspect status first unless the run is clearly blocked. Use steer for a top-level live async child, routed resume for a live nested child, or resume to revive a paused/completed/failed child.",
259
273
  `Top-level live async nudge: ${steerCommand}`,
260
274
  `Routed live nested nudge: ${nestedResumeCommand}`,
261
275
  childIntercomTarget ? `Direct intercom target: ${childIntercomTarget}` : undefined,
262
- `Status: subagent({ action: "status", id: "${runTarget}" })`,
276
+ status,
263
277
  `Interrupt: subagent({ action: "interrupt", id: "${runTarget}" })`,
264
- ].filter((line): line is string => Boolean(line)).join("\n");
278
+ ]);
265
279
  }
266
280
 
281
+
267
282
  export function formatControlIntercomMessage(event: ControlEvent, childIntercomTarget?: string): string {
268
283
  const statusLabel = event.type === "active_long_running"
269
284
  ? "subagent active but long-running"