@xzzpig/pi-subagents 0.7.0 → 0.9.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 (234) hide show
  1. package/CHANGELOG.md +456 -4
  2. package/README.md +3 -3
  3. package/agents/claude-code-writer.md +15 -0
  4. package/agents/claude-code.md +15 -0
  5. package/agents/codex-exec-writer.md +15 -0
  6. package/agents/codex-exec.md +15 -0
  7. package/agents/cursor-agent-writer.md +14 -0
  8. package/agents/cursor-agent.md +14 -0
  9. package/agents/reviewer.md +13 -3
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +154 -42
  12. package/docs/configuration.md +85 -26
  13. package/docs/extension-api.md +81 -16
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +75 -11
  16. package/docs/observability.md +34 -21
  17. package/docs/tool-reference.md +142 -18
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +148 -4
  20. package/index.ts +10 -1
  21. package/install.mjs +1 -1
  22. package/package.json +7 -6
  23. package/prompts/council.md +19 -7
  24. package/prompts/parallel-review.md +5 -1
  25. package/prompts/review-loop.md +11 -7
  26. package/skills/council-mode/SKILL.md +44 -215
  27. package/skills/council-mode/references/pass-contracts.md +150 -0
  28. package/skills/pi-subagents/SKILL.md +90 -32
  29. package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
  30. package/skills/pi-subagents/references/execution-controls.md +104 -19
  31. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  32. package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
  33. package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
  34. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  35. package/src/agents/agent-management.ts +471 -114
  36. package/src/agents/agent-refinements.ts +4 -4
  37. package/src/agents/agent-serializer.ts +16 -4
  38. package/src/agents/agents.ts +1076 -351
  39. package/src/agents/builtin-names.ts +6 -0
  40. package/src/agents/runtime-agent-events.ts +70 -0
  41. package/src/agents/runtime-agent-registry.ts +31 -20
  42. package/src/api/agents.ts +10 -5
  43. package/src/api/background-work.ts +12 -3
  44. package/src/api/capability-ceiling.ts +0 -1
  45. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  46. package/src/api/delegation.ts +0 -7
  47. package/src/api/external-job-provider.ts +10 -1
  48. package/src/api/external-runs.ts +67 -4
  49. package/src/api/preflight.ts +97 -34
  50. package/src/api/project-panes.ts +2 -0
  51. package/src/api/shared-types.ts +6 -0
  52. package/src/extension/config.ts +90 -0
  53. package/src/extension/doctor.ts +15 -13
  54. package/src/extension/fanout-child.ts +17 -16
  55. package/src/extension/index.ts +139 -41
  56. package/src/extension/public-execution.ts +113 -22
  57. package/src/extension/rpc.ts +182 -13
  58. package/src/extension/schemas.ts +63 -21
  59. package/src/extension/tool-description.ts +48 -23
  60. package/src/extension/tool-result.ts +19 -0
  61. package/src/inspectors/herdr/actions.ts +2 -1
  62. package/src/inspectors/herdr/client.ts +3 -3
  63. package/src/inspectors/herdr/focus.ts +55 -0
  64. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  65. package/src/inspectors/herdr/project-panes.ts +228 -44
  66. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  67. package/src/integrations/herdr-status.ts +75 -5
  68. package/src/intercom/native-supervisor-channel.ts +138 -60
  69. package/src/intercom/result-intercom.ts +2 -0
  70. package/src/intercom/supervisor-ui.ts +243 -0
  71. package/src/profiles/profiles.ts +5 -6
  72. package/src/runs/background/active-async-capacity.ts +103 -18
  73. package/src/runs/background/async-execution.ts +492 -125
  74. package/src/runs/background/async-job-tracker.ts +127 -28
  75. package/src/runs/background/async-resume.ts +67 -29
  76. package/src/runs/background/async-retention.ts +21 -4
  77. package/src/runs/background/async-status-snapshot.ts +23 -261
  78. package/src/runs/background/async-status.ts +199 -14
  79. package/src/runs/background/auto-drain.ts +1 -1
  80. package/src/runs/background/chain-append.ts +8 -3
  81. package/src/runs/background/chain-root-attachment.ts +79 -8
  82. package/src/runs/background/control-channel.ts +101 -214
  83. package/src/runs/background/fleet-view.ts +38 -22
  84. package/src/runs/background/inspect-rpc.ts +8 -8
  85. package/src/runs/background/notify.ts +295 -8
  86. package/src/runs/background/process-terminal.ts +16 -0
  87. package/src/runs/background/result-delivery-ownership.ts +45 -0
  88. package/src/runs/background/result-files.ts +28 -14
  89. package/src/runs/background/result-watcher.ts +43 -19
  90. package/src/runs/background/resume-guidance.ts +2 -2
  91. package/src/runs/background/retained-children.ts +1 -1
  92. package/src/runs/background/run-child-session.ts +613 -0
  93. package/src/runs/background/run-status.ts +99 -18
  94. package/src/runs/background/runner-aliases.ts +125 -0
  95. package/src/runs/background/runner-child-sessions.ts +31 -0
  96. package/src/runs/background/scheduled-runs.ts +174 -18
  97. package/src/runs/background/stale-run-reconciler.ts +13 -4
  98. package/src/runs/background/steering.ts +8 -15
  99. package/src/runs/background/subagent-runner.ts +959 -1159
  100. package/src/runs/background/subagent-wait.ts +86 -31
  101. package/src/runs/background/terminal-run-index.ts +1 -1
  102. package/src/runs/background/wait-completions.ts +45 -2
  103. package/src/runs/background/wait-config.ts +23 -9
  104. package/src/runs/background/wait-tool.ts +27 -19
  105. package/src/runs/foreground/async-steering-action.ts +3 -19
  106. package/src/runs/foreground/async-stop-action.ts +23 -2
  107. package/src/runs/foreground/execution.ts +585 -481
  108. package/src/runs/foreground/foreground-control.ts +13 -0
  109. package/src/runs/foreground/foreground-history.ts +26 -3
  110. package/src/runs/foreground/subagent-executor.ts +1549 -410
  111. package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
  112. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  113. package/src/runs/shared/abort-recovery.ts +119 -0
  114. package/src/runs/shared/acceptance.ts +147 -39
  115. package/src/runs/shared/agent-contract.ts +1 -1
  116. package/src/runs/shared/async-status-projection.ts +565 -0
  117. package/src/runs/shared/background-process-options.ts +9 -0
  118. package/src/runs/shared/capability-ceiling.ts +2 -2
  119. package/src/runs/shared/child-hooks.ts +25 -0
  120. package/src/runs/shared/child-identity.ts +62 -0
  121. package/src/runs/shared/child-launch-plan.ts +151 -0
  122. package/src/runs/shared/child-launch.ts +314 -0
  123. package/src/runs/shared/child-lifecycle.ts +25 -0
  124. package/src/runs/shared/child-runtime-config.ts +126 -0
  125. package/src/runs/shared/child-session.ts +342 -0
  126. package/src/runs/shared/child-tool-plan.ts +540 -0
  127. package/src/runs/shared/claude-code-adapter.ts +133 -0
  128. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  129. package/src/runs/shared/completion-evidence.ts +89 -0
  130. package/src/runs/shared/completion-guard.ts +57 -6
  131. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  132. package/src/runs/shared/dynamic-fanout.ts +4 -4
  133. package/src/runs/shared/extension-bindings.ts +78 -0
  134. package/src/runs/shared/external-cli-contract.ts +167 -0
  135. package/src/runs/shared/external-cli-preflight.ts +138 -0
  136. package/src/runs/shared/external-cli-runner.ts +349 -54
  137. package/src/runs/shared/external-job-bridge.ts +53 -37
  138. package/src/runs/shared/external-job-runner.ts +126 -23
  139. package/src/runs/shared/fast-mode-extension.ts +10 -0
  140. package/src/runs/shared/host-step-status.ts +231 -0
  141. package/src/runs/shared/lane-metadata.ts +126 -0
  142. package/src/runs/shared/launch-cwd.ts +16 -0
  143. package/src/runs/shared/long-running-guard.ts +2 -1
  144. package/src/runs/shared/mcp-config-sources.ts +422 -0
  145. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  146. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  147. package/src/runs/shared/model-exclusions.ts +141 -10
  148. package/src/runs/shared/model-fallback.ts +187 -33
  149. package/src/runs/shared/model-scope.ts +106 -39
  150. package/src/runs/shared/mutation-evidence.ts +199 -0
  151. package/src/runs/shared/nested-events.ts +38 -48
  152. package/src/runs/shared/nested-path.ts +0 -14
  153. package/src/runs/shared/nested-render.ts +9 -5
  154. package/src/runs/shared/orca-progress-tabs.ts +83 -16
  155. package/src/runs/shared/parallel-handoff.ts +423 -7
  156. package/src/runs/shared/parallel-utils.ts +28 -5
  157. package/src/runs/shared/permissions.ts +1 -14
  158. package/src/runs/shared/pi-spawn.ts +69 -35
  159. package/src/runs/shared/process-signal.ts +16 -0
  160. package/src/runs/shared/run-fanout-budget.ts +0 -13
  161. package/src/runs/shared/run-history.ts +21 -1
  162. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  163. package/src/runs/shared/single-output.ts +89 -22
  164. package/src/runs/shared/structured-output.ts +61 -7
  165. package/src/runs/shared/subagent-control.ts +6 -2
  166. package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
  167. package/src/runs/shared/task-intent.ts +21 -7
  168. package/src/runs/shared/tool-availability.ts +18 -64
  169. package/src/runs/shared/tool-budget.ts +0 -14
  170. package/src/runs/shared/tool-timeout.ts +1 -1
  171. package/src/runs/shared/workflow-graph.ts +16 -0
  172. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  173. package/src/runs/shared/worktree.ts +571 -62
  174. package/src/shared/atomic-json.ts +3 -1
  175. package/src/shared/child-session-name.ts +46 -0
  176. package/src/shared/extension-context.ts +24 -0
  177. package/src/shared/fork-context.ts +21 -12
  178. package/src/shared/fork-session-cwd.ts +27 -0
  179. package/src/shared/formatters.ts +18 -3
  180. package/src/shared/jsonl-writer.ts +11 -0
  181. package/src/shared/launch-contract.ts +20 -6
  182. package/src/shared/pruned-fork.ts +450 -0
  183. package/src/shared/session-file-trust.ts +19 -0
  184. package/src/shared/session-tokens.ts +14 -3
  185. package/src/shared/settings.ts +21 -102
  186. package/src/shared/shortcuts.ts +17 -0
  187. package/src/shared/thinking-ceiling.ts +46 -0
  188. package/src/shared/types.ts +644 -75
  189. package/src/shared/utils.ts +60 -93
  190. package/src/shared/workflow-child-permit.ts +207 -0
  191. package/src/slash/delegation-adapters.ts +1 -9
  192. package/src/slash/delegation-request.ts +0 -4
  193. package/src/slash/prompt-template-bridge.ts +37 -1
  194. package/src/slash/slash-bridge.ts +1 -2
  195. package/src/slash/slash-commands.ts +383 -116
  196. package/src/slash/slash-live-state.ts +22 -11
  197. package/src/slash/subagents-admin.ts +29 -12
  198. package/src/tui/fleet-native-transcript.ts +4 -0
  199. package/src/tui/fleet-status.ts +278 -90
  200. package/src/tui/fleet-transcript.ts +11 -5
  201. package/src/tui/fleet.ts +54 -28
  202. package/src/tui/render-helpers.ts +31 -0
  203. package/src/tui/render.ts +1433 -166
  204. package/src/watchdog/change-signature.ts +40 -1
  205. package/src/watchdog/child-status.ts +54 -34
  206. package/src/watchdog/diff-tool.ts +77 -0
  207. package/src/watchdog/emission-guard.ts +5 -3
  208. package/src/watchdog/guidance.ts +20 -0
  209. package/src/watchdog/permission-arbiter.ts +59 -52
  210. package/src/watchdog/register-child.ts +28 -25
  211. package/src/watchdog/register-main.ts +10 -9
  212. package/src/watchdog/render.ts +4 -5
  213. package/src/watchdog/review.ts +15 -4
  214. package/src/watchdog/rules.ts +70 -0
  215. package/src/watchdog/runtime.ts +75 -92
  216. package/src/watchdog/scope.ts +0 -11
  217. package/src/watchdog/settings.ts +48 -104
  218. package/src/watchdog/turn-delta.ts +1 -1
  219. package/src/watchdog/types.ts +18 -32
  220. package/src/watchdog/warning-format.ts +0 -1
  221. package/src/workflows/chat-progress.ts +7 -3
  222. package/src/workflows/host-command.ts +235 -0
  223. package/src/workflows/scripted-workflow.ts +1142 -69
  224. package/src/workflows/workflow-checklist.ts +439 -0
  225. package/src/workflows/workflow-child-summary.ts +121 -0
  226. package/src/workflows/workflow-preflight.ts +297 -0
  227. package/src/workflows/workflow-receipt.ts +232 -6
  228. package/src/workflows/workflow-resources.ts +150 -0
  229. package/src/workflows/workflow-settlement.ts +246 -0
  230. package/src/runs/shared/child-protocol.ts +0 -401
  231. package/src/runs/shared/pi-args.ts +0 -858
  232. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  233. package/src/runs/shared/turn-budget.ts +0 -98
  234. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -2,7 +2,7 @@ import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
3
  import type { AgentToolResult } from "@earendil-works/pi-agent-core";
4
4
  import { safeTerminalText } from "../../shared/display-text.ts";
5
- import { formatAsyncRunList, formatAsyncRunOutputPath, formatAsyncRunProgressLabel, listAsyncRuns } from "./async-status.ts";
5
+ import { formatAsyncRunList, formatAsyncRunOutputPath, formatAsyncRunProgressLabel, formatWorkflowStageLine, listAsyncRuns } from "./async-status.ts";
6
6
  import { formatAsyncResultTranscript, formatAsyncRunTranscript, formatNestedRunTranscript, inspectSubagentFleet } from "./fleet-view.ts";
7
7
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
8
8
  import { formatModelThinking } from "../../shared/formatters.ts";
@@ -11,6 +11,7 @@ import { DIRS, type AsyncStatus, type Details, type ForegroundResumeRun, type Ne
11
11
  import { inspectActiveAsyncCapacityOwner, type ActiveAsyncCapacityInspection } from "./active-async-capacity.ts";
12
12
  import { readStatus } from "../../shared/utils.ts";
13
13
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
14
+ import { normalizeExternalCliRunnerStatus } from "../shared/external-cli-contract.ts";
14
15
  import { resolveSubagentResultStatus } from "../../intercom/result-intercom.ts";
15
16
  import { readProcessTerminal, sanitizeProcessTerminal } from "./process-terminal.ts";
16
17
  import { formatWaitSubscriptions } from "./wait-subscriptions.ts";
@@ -21,7 +22,14 @@ import { reconcileAsyncRun, reconcileNestedAsyncDescendants } from "./stale-run-
21
22
  import { attachRootChildrenToSteps, findNestedRouteForRootId, projectNestedRegistryForRoot, type NestedRunResolutionScope } from "../shared/nested-events.ts";
22
23
  import { readMissionBinding } from "../../missions/lifecycle.ts";
23
24
  import { formatWorkflowJsonPreview } from "../../workflows/scripted-workflow.ts";
25
+ import { parseWorkflowChildSummary } from "../../workflows/workflow-child-summary.ts";
26
+ import { formatWorkflowPreflightPlanSummary, formatWorkflowPreflightWarningSummary } from "../../workflows/workflow-preflight.ts";
24
27
  import { formatRunFanoutBudget, getRunFanoutBudgetSnapshot, readRunFanoutBudgetDescriptor } from "../shared/run-fanout-budget.ts";
28
+ import { workflowGraphStageNodes } from "../shared/workflow-graph.ts";
29
+ import { getExternalJobProvider } from "../../api/external-job-provider.ts";
30
+ import { formatTimeoutRecoveryLines } from "../shared/mutation-evidence.ts";
31
+ import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
32
+ import { validHostStepNodes } from "../shared/host-step-status.ts";
25
33
 
26
34
  interface RunStatusParams {
27
35
  action?: string;
@@ -61,13 +69,14 @@ function formatCapacityOwner(inspect: ActiveAsyncCapacityInspection): string[] {
61
69
  }
62
70
 
63
71
  function formatWorkflowDebug(status: AsyncStatus): string[] {
64
- if (status.mode !== "workflow" && !status.parentWorkflowRunId && !status.workflowKey) return [];
72
+ if (status.mode !== "workflow" && !status.parentWorkflowRunId && !status.workflowKey && !status.lane) return [];
65
73
  const lines = [
66
74
  status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
67
75
  status.mode === "workflow" ? `Workflow children: ${(status.steps ?? []).length}` : undefined,
76
+ status.lane ? `Lane: ${status.lane.key}${status.lane.mode ? ` (${status.lane.mode})` : ""}` : undefined,
68
77
  ].filter((line): line is string => line !== undefined);
69
78
  for (const [index, step] of (status.steps ?? []).entries()) {
70
- lines.push(` ${index + 1}. key ${step.workflowKey ?? "n/a"} · ${step.agent} · ${step.status} · async ${step.async === undefined ? "unknown" : step.async ? "yes" : "no"}${step.runId ? ` · run ${step.runId}` : ""}`);
79
+ lines.push(` ${index + 1}. key ${step.workflowKey ?? "n/a"} · ${runStatusStepDisplayName(step)} · ${step.status} · async ${step.async === undefined ? "unknown" : step.async ? "yes" : "no"}${step.runId ? ` · run ${step.runId}` : ""}${step.lane ? ` · lane ${step.lane.key}` : ""}${step.worktreePath ? ` · worktree ${step.worktreePath} · branch ${step.branch ?? "unknown"}${step.provider ? ` · provider ${step.provider}` : ""}` : ""}`);
71
80
  }
72
81
  return lines;
73
82
  }
@@ -85,6 +94,7 @@ function formatRunLifecycleDebug(input: { status: AsyncStatus; asyncDir: string;
85
94
  `Mode: ${status.mode}`,
86
95
  status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}` : undefined,
87
96
  status.workflowKey ? `Workflow key: ${status.workflowKey}` : undefined,
97
+ status.lane ? `Lane: ${status.lane.key}${status.lane.mode ? ` (${status.lane.mode})` : ""}` : undefined,
88
98
  `Status process terminal: ${formatProcessTerminal(overlayProcessTerminal)}`,
89
99
  `Sidecar process terminal: ${formatProcessTerminal(sidecarProcessTerminal)}`,
90
100
  ...formatCapacityOwner(capacity),
@@ -102,6 +112,7 @@ interface RunStatusDeps {
102
112
  nested?: NestedRunResolutionScope;
103
113
  sessionRoots?: string[];
104
114
  activeCapacityRoot?: string;
115
+ abandonedSlotReleaseAfterMs?: number | false;
105
116
  }
106
117
 
107
118
  function hasExistingSessionFile(value: unknown): value is string {
@@ -119,7 +130,7 @@ function formatResumeGuidance(runId: string | undefined, children: Array<{ agent
119
130
  const resumableWorkflowChildren = workflowChildren.filter(({ child }) => !(child.status === "paused" && child.activityState === "needs_attention"));
120
131
  if (workflowChildren.length > 0) {
121
132
  return [
122
- ...supervisorDetachedWorkflowChildren.map(({ child }) => `Recovery workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: reply to the supervisor request first, then wait with subagent_wait({ id: "${child.runId}" }). Use subagent({ action: "status", id: "${child.runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`),
133
+ ...supervisorDetachedWorkflowChildren.map(({ child }) => `Recovery workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: reply to the supervisor request first, then wait with bg_wait({ id: "${child.runId}" }). Use subagent({ action: "status", id: "${child.runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`),
123
134
  ...resumableWorkflowChildren.map(({ child }) => `Revive workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: subagent({ action: "resume", id: "${child.runId}", message: "..." })`),
124
135
  ].join("\n");
125
136
  }
@@ -148,7 +159,12 @@ function stepLineLabel(status: AsyncStatus, index: number): string {
148
159
  return `Step ${index + 1}`;
149
160
  }
150
161
 
162
+ function runStatusStepDisplayName(step: { agent: string; sessionName?: string; label?: string }): string {
163
+ return step.sessionName?.trim() || (step.label ? `${step.label} (${step.agent})` : step.agent);
164
+ }
165
+
151
166
  function nestedRunDisplayName(run: NestedRunSummary): string {
167
+ if (run.sessionName?.trim()) return run.sessionName.trim();
152
168
  if (run.agent) return run.agent;
153
169
  if (run.agents?.length) return run.agents.join(", ");
154
170
  return run.id;
@@ -161,6 +177,14 @@ function formatSteeringSummary(input: { steering?: SteeringStatus }): string | u
161
177
  return `${steering.requested} requested, ${steering.scheduled} scheduled, ${steering.pending} pending, ${steering.delivered} delivered, ${steering.failed} failed, ${steering.recovered} recovered${lateAcknowledgments ? `, ${lateAcknowledgments} late acknowledged` : ""}`;
162
178
  }
163
179
 
180
+ function externalJobFollowUpSupported(provider: string): boolean {
181
+ try {
182
+ return typeof getExternalJobProvider(provider)?.followUp === "function";
183
+ } catch {
184
+ return false;
185
+ }
186
+ }
187
+
164
188
  function rememberedForegroundChildOutput(child: ForegroundResumeRun["children"][number]): string {
165
189
  const outputPath = child.artifactPaths?.outputPath ?? child.savedOutputPath;
166
190
  if (outputPath && fs.existsSync(outputPath)) {
@@ -185,7 +209,7 @@ function formatRememberedForegroundStatus(run: ForegroundResumeRun): string {
185
209
  for (const child of run.children) {
186
210
  const output = rememberedForegroundChildOutput(child).trim().split(/\r?\n/).find((line) => line.trim());
187
211
  const parts = [
188
- `${child.index + 1}. ${child.agent} ${child.status}`,
212
+ `${child.index + 1}. ${child.sessionName?.trim() || child.agent} ${child.status}`,
189
213
  child.exitCode !== undefined ? `exit ${child.exitCode}` : undefined,
190
214
  child.detachedReason ? `detached: ${child.detachedReason}` : undefined,
191
215
  child.acceptance ? `acceptance: ${child.acceptance.status}` : undefined,
@@ -206,7 +230,7 @@ function formatRememberedForegroundStatus(run: ForegroundResumeRun): string {
206
230
  const detached = run.children.some((child) => child.status === "detached");
207
231
  const resumable = run.children.find((child) => hasExistingSessionFile(child.sessionFile));
208
232
  if (detached) {
209
- lines.push(`Recovery: reply to the supervisor request first, then wait with subagent_wait({ id: "${run.runId}" }); do not resume or launch a replacement while any child remains detached.`);
233
+ lines.push(`Recovery: reply to the supervisor request first, then wait with bg_wait({ id: "${run.runId}" }); do not resume or launch a replacement while any child remains detached.`);
210
234
  } else if (resumable) {
211
235
  lines.push(run.children.length === 1
212
236
  ? `Revive: subagent({ action: "resume", id: "${run.runId}", message: "..." })`
@@ -229,7 +253,7 @@ function formatRememberedForegroundTranscript(run: ForegroundResumeRun, options:
229
253
  const lines = [
230
254
  `Run: ${run.runId}`,
231
255
  `State: ${child.status}`,
232
- `Child: ${index} (${child.agent})`,
256
+ `Child: ${index} (${child.sessionName?.trim() || child.agent})`,
233
257
  child.sessionFile ? `Session: ${child.sessionFile}` : undefined,
234
258
  child.transcriptPath ? `Transcript: ${child.transcriptPath}` : undefined,
235
259
  child.artifactPaths?.outputPath ? `Output: ${child.artifactPaths.outputPath}` : undefined,
@@ -265,7 +289,7 @@ function formatNestedExactStatus(rootRunId: string, run: NestedRunSummary): stri
265
289
  for (const [index, step] of run.steps.entries()) {
266
290
  const activity = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
267
291
  const budget = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "";
268
- lines.push(` ${index + 1}. ${step.agent} ${step.status}${activity ? `, ${activity}` : ""}${budget}${step.error ? `, error: ${step.error}` : ""}`);
292
+ lines.push(` ${index + 1}. ${step.sessionName?.trim() || step.agent} ${step.status}${activity ? `, ${activity}` : ""}${budget}${step.error ? `, error: ${step.error}` : ""}`);
269
293
  lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true }));
270
294
  }
271
295
  }
@@ -396,7 +420,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
396
420
  if (!status && diskStatus?.displayDismissedAt !== undefined) {
397
421
  if (params.action === "debug.run") {
398
422
  const { sidecar, overlay } = debugProcessTerminal(asyncDir, diskStatus);
399
- const capacity = inspectActiveAsyncCapacityOwner({ runId: diskStatus.runId, sessionId: diskStatus.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []) });
423
+ const capacity = inspectActiveAsyncCapacityOwner({ runId: diskStatus.runId, sessionId: diskStatus.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: deps.abandonedSlotReleaseAfterMs });
400
424
  return {
401
425
  content: [{ type: "text", text: formatRunLifecycleDebug({ status: diskStatus, asyncDir, sidecarProcessTerminal: sidecar, overlayProcessTerminal: overlay, capacity }) }],
402
426
  details: { mode: "single", results: [], ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
@@ -423,7 +447,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
423
447
  if (status) {
424
448
  if (params.action === "debug.run") {
425
449
  const { sidecar, overlay } = debugProcessTerminal(asyncDir, status);
426
- const capacity = inspectActiveAsyncCapacityOwner({ runId: status.runId, sessionId: status.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []) });
450
+ const capacity = inspectActiveAsyncCapacityOwner({ runId: status.runId, sessionId: status.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: deps.abandonedSlotReleaseAfterMs });
427
451
  return {
428
452
  content: [{ type: "text", text: formatRunLifecycleDebug({ status, asyncDir, sidecarProcessTerminal: sidecar, overlayProcessTerminal: overlay, capacity }) }],
429
453
  details: { mode: "single", results: [], ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
@@ -461,6 +485,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
461
485
  currentStep: status.currentStep,
462
486
  chainStepCount: status.chainStepCount,
463
487
  parallelGroups: status.parallelGroups,
488
+ workflowGraph: status.workflowGraph,
464
489
  steps: (status.steps ?? []).map((step, index) => ({ index, agent: step.agent, status: step.status })),
465
490
  });
466
491
  const started = new Date(status.startedAt).toISOString();
@@ -492,11 +517,21 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
492
517
  statusActivityText ? `Activity: ${statusActivityText}` : undefined,
493
518
  steeringText ? `Steering: ${steeringText}` : undefined,
494
519
  `Mode: ${status.mode}`,
520
+ ...(status.preflight ? [formatWorkflowPreflightPlanSummary(status.preflight)] : []),
521
+ ...(status.workflow?.preflightWarnings?.length ? [formatWorkflowPreflightWarningSummary(status.workflow.preflightWarnings)] : []),
495
522
  runFanoutBudget ? formatRunFanoutBudget(runFanoutBudget) : undefined,
496
523
  status.parentWorkflowRunId ? `Workflow parent: ${status.parentWorkflowRunId}${status.workflowKey ? ` (${status.workflowKey})` : ""}` : undefined,
497
524
  status.mode === "workflow" && workflowReturnPreview !== undefined ? `Return: ${workflowReturnPreview}` : undefined,
498
525
  status.mode === "workflow" && workflowEmitPreview !== undefined ? `Latest emit: ${workflowEmitPreview}` : undefined,
499
526
  `Progress: ${progressLabel}`,
527
+ ...(status.mode === "workflow" ? formatWorkflowChecklistText(projectWorkflowChecklist({
528
+ graph: status.workflowGraph,
529
+ steps: status.steps,
530
+ hostSteps: validHostStepNodes(status.workflowGraph),
531
+ preflight: status.preflight,
532
+ trace: status.workflow?.trace,
533
+ now: status.lastUpdate ?? status.endedAt ?? Date.now(),
534
+ }), "", { includeItems: false }) : []),
500
535
  status.pendingAppends ? `Pending appends: ${status.pendingAppends}` : undefined,
501
536
  `Started: ${started}`,
502
537
  `Updated: ${updated}`,
@@ -510,9 +545,9 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
510
545
  const liveWorkflowControls = status.mode === "workflow" && deps.state?.currentSessionId === status.sessionId && deps.state?.workflowControllers?.has(status.runId)
511
546
  ? [...(deps.state?.foregroundControls.values() ?? [])].filter((control) => control.parentWorkflowRunId === status.runId
512
547
  && control.sessionId === status.sessionId
513
- && Boolean(control.workflowSteeringDir && fs.existsSync(control.workflowSteeringDir))
514
548
  && (control.activeChildren?.size ?? 0) > 0)
515
549
  : [];
550
+ let hasExternalJobFollowUpHint = false;
516
551
  for (const [index, step] of (status.steps ?? []).entries()) {
517
552
  const stepActivityText = step.status === "running" ? formatActivityLabel(step.lastActivityAt, step.activityState) : undefined;
518
553
  const modelThinking = formatModelThinking(step.model, step.thinking);
@@ -522,19 +557,47 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
522
557
  const errorText = step.error ? `, error: ${step.error}` : "";
523
558
  const acceptanceText = step.acceptance?.status ? `, acceptance: ${step.acceptance.status}` : "";
524
559
  const budgetText = step.turnBudget ? `, turn budget: ${step.turnBudget.turnCount}/${step.turnBudget.maxTurns}+${step.turnBudget.graceTurns} (${step.turnBudget.outcome})` : "";
525
- const display = step.label ? `${step.label} (${step.agent})` : step.agent;
560
+ const display = runStatusStepDisplayName(step);
526
561
  const phase = step.phase ? `[${step.phase}] ` : "";
527
562
  lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText}`);
563
+ const structuredOutputPreview = step.structuredOutput === undefined ? undefined : formatWorkflowJsonPreview(step.structuredOutput, 4_000);
564
+ if (structuredOutputPreview !== undefined) lines.push(` Structured output: ${structuredOutputPreview}`);
565
+ if (step.structuredOutputPath) lines.push(` Structured output path: ${step.structuredOutputPath}`);
566
+ lines.push(...formatTimeoutRecoveryLines(step.timeoutRecovery, " "));
528
567
  if (step.runner?.type === "external-cli") {
529
- lines.push(` Runner: external-cli (${step.runner.command}${step.runner.args.length ? ` ${step.runner.args.join(" ")}` : ""})`);
568
+ const runner = normalizeExternalCliRunnerStatus(step.runner);
569
+ if (runner) {
570
+ lines.push(` Runner: external-cli (${runner.command}${runner.args.length ? ` ${runner.args.join(" ")}` : ""})`);
571
+ lines.push(` Adapter: ${runner.adapter.id} v${runner.adapter.version} (${runner.adapter.executionMode})`);
572
+ if (runner.safety) {
573
+ if ("approvalPolicy" in runner.safety) lines.push(` Safety: ${"access" in runner.safety ? `access=${runner.safety.access}, ` : ""}sandbox=${runner.safety.sandbox}, approval=${runner.safety.approvalPolicy}, ephemeral=${runner.safety.ephemeral}`);
574
+ else if ("mode" in runner.safety) lines.push(` Safety: access=${runner.safety.access}, auth=${runner.safety.authentication}, mode=${runner.safety.mode}, sandbox=${runner.safety.sandbox}, workspaceTrust=${runner.safety.workspaceTrust}, sessionReuse=${runner.safety.sessionReuse}`);
575
+ else if ("authentication" in runner.safety) lines.push(` Safety: access=${runner.safety.access}, auth=${runner.safety.authentication}, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, settingsTrust=${runner.safety.userSettingsTrust}, persistence=${runner.safety.sessionPersistence}`);
576
+ else lines.push(` Safety: access=read-only, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, persistence=${runner.safety.sessionPersistence}`);
577
+ }
578
+ lines.push(` Capabilities: stop=${runner.capabilities.stop}, steer=false, resume=false, structuredOutput=false, toolEvents=false, supervisor=unsupported, forkContext=false, extensionBindings=false`);
579
+ lines.push(` Unsupported steer: ${runner.unsupportedReasons.steer}`);
580
+ lines.push(` Unsupported resume: ${runner.nonResumableReason}`);
581
+ lines.push(` Unsupported supervisor: ${runner.unsupportedReasons.supervisor}`);
582
+ lines.push(` Context handoff: fresh only (${runner.unsupportedReasons.forkContext})`);
583
+ } else {
584
+ lines.push(" Runner: external-cli (invalid persisted runner metadata)");
585
+ }
530
586
  if (step.externalProcess?.pid !== undefined) lines.push(` Process: ${step.externalProcess.pid}`);
531
- if (step.externalProcess) lines.push(` Stdout: ${step.externalProcess.stdoutPath}`, ` Stderr: ${step.externalProcess.stderrPath}`);
587
+ if (step.externalProcess) {
588
+ lines.push(` Stdout: ${step.externalProcess.stdoutPath}`, ` Stderr: ${step.externalProcess.stderrPath}`);
589
+ if (step.externalProcess.finalOutputPath) lines.push(` Final output: ${step.externalProcess.finalOutputPath}`);
590
+ }
532
591
  } else if (step.runner?.type === "external-job") {
533
592
  lines.push(` Runner: external-job (${step.runner.provider})`);
534
593
  if (step.externalJob?.providerJobId) lines.push(` Provider job: ${step.externalJob.providerJobId}`);
535
594
  if (step.externalJob?.state) lines.push(` Provider state: ${step.externalJob.state}`);
536
595
  if (step.externalJob?.conversationUrl) lines.push(` Conversation: ${step.externalJob.conversationUrl}`);
537
596
  if (step.externalJob?.resultArtifactPath) lines.push(` Result artifact: ${step.externalJob.resultArtifactPath}`);
597
+ if ((step.status === "complete" || step.status === "completed") && step.externalJob?.state === "completed" && step.externalJob.providerJobId && externalJobFollowUpSupported(step.runner.provider)) {
598
+ hasExternalJobFollowUpHint = true;
599
+ lines.push(` Follow-up: subagent({ action: "resume", id: "${status.runId}", index: ${index}, message: "..." })`);
600
+ }
538
601
  }
539
602
  lines.push(...formatNestedRunStatusLines(step.children, { indent: " ", commandHints: true, maxLines: 20 }));
540
603
  const stepOutputPath = path.join(asyncDir, `output-${index}.log`);
@@ -546,6 +609,11 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
546
609
  lines.push(" Steer: unavailable; external runners do not accept live messages.");
547
610
  }
548
611
  }
612
+ const loadedWorkflowKeys = new Set((status.steps ?? []).flatMap((step) => step.workflowKey ? [step.workflowKey] : []));
613
+ const graphStages = status.mode === "workflow" ? workflowGraphStageNodes(status.workflowGraph) : [];
614
+ for (const [index, node] of graphStages.entries()) {
615
+ if (!loadedWorkflowKeys.has(node.id)) lines.push(` ${formatWorkflowStageLine(node, index, graphStages.length)}`);
616
+ }
549
617
  const attached = new Set((status.steps ?? []).flatMap((step) => step.children?.map((child) => child.id) ?? []));
550
618
  const unattached = nestedChildren.filter((child) => !attached.has(child.id));
551
619
  lines.push(...formatNestedRunStatusLines(unattached, { indent: "", commandHints: true, maxLines: 20 }));
@@ -563,13 +631,15 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
563
631
  if (status.state === "running" && !allExternal && status.mode !== "workflow") lines.push(`Steer running child: subagent({ action: "steer", id: "${status.runId}", message: "..." })`);
564
632
  if (status.state !== "running") {
565
633
  lines.push(allExternal
566
- ? "Resume: unavailable; external runners do not persist Pi sessions."
634
+ ? hasExternalJobFollowUpHint ? "Resume: use the external-job follow-up hint above." : "Resume: unavailable; external runners do not persist Pi sessions."
567
635
  : formatResumeGuidance(status.runId, status.steps ?? [], status.sessionFile, { stopped: status.state === "stopped" || status.stopped === true }));
568
636
  }
569
637
  if (fs.existsSync(logPath)) lines.push(`Log: ${logPath}`);
570
638
  if (fs.existsSync(eventsPath)) lines.push(`Events: ${eventsPath}`);
571
639
 
572
- return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(runFanoutBudget ? { runFanoutBudget } : {}), ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
640
+ const workflowChildren = parseWorkflowChildSummary(status.workflowChildren);
641
+ if (workflowChildren && workflowChildren.workflowRunId !== status.runId) throw new Error("workflowChildren.workflowRunId does not match async status runId.");
642
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(status.preflight ? { preflight: status.preflight } : {}), ...(status.workflow?.preflightWarnings?.length ? { preflightWarnings: status.workflow.preflightWarnings } : {}), ...(workflowChildren ? { workflowChildren } : {}), ...(runFanoutBudget ? { runFanoutBudget } : {}), ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
573
643
  }
574
644
  }
575
645
 
@@ -583,7 +653,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
583
653
  }
584
654
  try {
585
655
  const raw = fs.readFileSync(resultPath, "utf-8");
586
- const data = JSON.parse(raw) as { id?: string; runId?: string; toolCallId?: string; agent?: string; success?: boolean; summary?: string; output?: string; exitCode?: number; state?: string; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; processSignal?: string | null; sessionFile?: string; parallelHandoff?: { path?: string }; results?: Array<{ agent?: string; runId?: string; workflowKey?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; interrupted?: boolean; processSignal?: string | null }> };
656
+ const data = JSON.parse(raw) as { id?: string; runId?: string; toolCallId?: string; agent?: string; success?: boolean; summary?: string; output?: string; exitCode?: number; state?: string; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; processSignal?: string | null; sessionFile?: string; timeoutRecovery?: unknown; parallelHandoff?: { path?: string }; results?: Array<{ agent?: string; sessionName?: string; runId?: string; workflowKey?: string; output?: string; summary?: string; sessionFile?: string; state?: string; success?: boolean; exitCode?: number | null; stopped?: boolean; timedOut?: boolean; turnBudgetExceeded?: boolean; interrupted?: boolean; processSignal?: string | null; timeoutRecovery?: unknown }> };
587
657
  if (params.view === "transcript") {
588
658
  try {
589
659
  return { content: [{ type: "text", text: formatAsyncResultTranscript(data, resultPath, { index: params.index, lines: params.lines }) }], details: { mode: "single", results: [] } };
@@ -611,9 +681,20 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
611
681
  const lines = [`Run: ${runId}`, data.toolCallId ? `Tool call: ${data.toolCallId}` : undefined, `State: ${status}`, `Result: ${resultPath}`].filter((line): line is string => Boolean(line));
612
682
  if (data.parallelHandoff?.path) lines.push(`Parallel handoff: ${data.parallelHandoff.path}`);
613
683
  const children = Array.isArray(data.results) ? data.results : data.agent ? [{ agent: data.agent, sessionFile: data.sessionFile }] : [];
684
+ lines.push(...formatTimeoutRecoveryLines(data.timeoutRecovery, " "));
685
+ for (const [index, child] of children.entries()) {
686
+ const structuredOutput = (child as { structuredOutput?: unknown }).structuredOutput;
687
+ const structuredOutputPreview = structuredOutput === undefined ? undefined : formatWorkflowJsonPreview(structuredOutput, 4_000);
688
+ if (structuredOutputPreview !== undefined) lines.push(` Structured output${children.length > 1 ? ` (${index + 1})` : ""}: ${structuredOutputPreview}`);
689
+ const structuredOutputPath = (child as { structuredOutputPath?: unknown }).structuredOutputPath;
690
+ if (typeof structuredOutputPath === "string" && structuredOutputPath.trim()) lines.push(` Structured output path${children.length > 1 ? ` (${index + 1})` : ""}: ${structuredOutputPath}`);
691
+ lines.push(...formatTimeoutRecoveryLines(child.timeoutRecovery, " "));
692
+ }
614
693
  lines.push(formatResumeGuidance(runId, children, data.sessionFile, { stopped: status === "stopped" }));
615
694
  if (data.summary) lines.push("", data.summary);
616
- return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [] } };
695
+ const workflowChildren = parseWorkflowChildSummary((data as unknown as Record<string, unknown>).workflowChildren);
696
+ if (workflowChildren && workflowChildren.workflowRunId !== runId) throw new Error("workflowChildren.workflowRunId does not match the result run id.");
697
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(workflowChildren ? { workflowChildren } : {}) } };
617
698
  } catch (error) {
618
699
  const message = error instanceof Error ? error.message : String(error);
619
700
  return {
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Module aliases for the detached async runner.
3
+ *
4
+ * The runner is a plain Node process started through jiti. The child hooks it
5
+ * loads import pi's host packages (`@earendil-works/pi-coding-agent`,
6
+ * `pi-agent-core`, `pi-ai`, `pi-tui`, `typebox`), which are peer packages of
7
+ * this extension and are not installed next to it. pi's own extension loader
8
+ * aliases those specifiers to the copies shipped inside the installed pi
9
+ * package; the parent computes the same map and hands it to the runner
10
+ * through `JITI_ALIAS`, so the runner's child sessions and hooks share one
11
+ * copy of every host package.
12
+ */
13
+ import * as fs from "node:fs";
14
+ import * as path from "node:path";
15
+
16
+ export const JITI_ALIAS_ENV = "JITI_ALIAS";
17
+
18
+ /** Specifiers the runner's import graph may use, with the package and export subpath each resolves to. */
19
+ export const HOST_PEER_ALIASES: ReadonlyArray<{ specifier: string; pkg: string; subpath: string }> = [
20
+ { specifier: "@earendil-works/pi-coding-agent", pkg: "@earendil-works/pi-coding-agent", subpath: "." },
21
+ { specifier: "@earendil-works/pi-agent-core", pkg: "@earendil-works/pi-agent-core", subpath: "." },
22
+ { specifier: "@earendil-works/pi-tui", pkg: "@earendil-works/pi-tui", subpath: "." },
23
+ { specifier: "@earendil-works/pi-ai", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
24
+ { specifier: "@earendil-works/pi-ai/compat", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
25
+ { specifier: "@earendil-works/pi-ai/oauth", pkg: "@earendil-works/pi-ai", subpath: "./oauth" },
26
+ { specifier: "@earendil-works/pi-ai/providers/all", pkg: "@earendil-works/pi-ai", subpath: "./providers/all" },
27
+ { specifier: "typebox", pkg: "typebox", subpath: "." },
28
+ { specifier: "typebox/compile", pkg: "typebox", subpath: "./compile" },
29
+ { specifier: "typebox/value", pkg: "typebox", subpath: "./value" },
30
+ ];
31
+
32
+ interface PackageManifest {
33
+ name?: unknown;
34
+ main?: unknown;
35
+ exports?: unknown;
36
+ }
37
+
38
+ function readManifest(packageDir: string): PackageManifest | undefined {
39
+ try {
40
+ return JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf-8")) as PackageManifest;
41
+ } catch {
42
+ return undefined;
43
+ }
44
+ }
45
+
46
+ /** Pick the import target of one exports entry (string, conditions object, or array of those). */
47
+ function exportTarget(entry: unknown): string | undefined {
48
+ if (typeof entry === "string") return entry;
49
+ if (Array.isArray(entry)) {
50
+ for (const candidate of entry) {
51
+ const target = exportTarget(candidate);
52
+ if (target) return target;
53
+ }
54
+ return undefined;
55
+ }
56
+ if (entry && typeof entry === "object") {
57
+ const conditions = entry as Record<string, unknown>;
58
+ for (const condition of ["import", "node", "default"]) {
59
+ if (condition in conditions) {
60
+ const target = exportTarget(conditions[condition]);
61
+ if (target) return target;
62
+ }
63
+ }
64
+ }
65
+ return undefined;
66
+ }
67
+
68
+ /** Resolve `subpath` of the package at `packageDir` through its `exports` map (with `*` patterns) or `main`. */
69
+ export function resolvePackageSubpath(packageDir: string, subpath: string): string | undefined {
70
+ const manifest = readManifest(packageDir);
71
+ if (!manifest) return undefined;
72
+ const exportsField = manifest.exports;
73
+ if (exportsField !== undefined) {
74
+ const map: Record<string, unknown> = typeof exportsField === "string" || Array.isArray(exportsField) || (exportsField && typeof exportsField === "object" && !Object.keys(exportsField as object).some((key) => key.startsWith(".")))
75
+ ? { ".": exportsField }
76
+ : exportsField as Record<string, unknown>;
77
+ const exact = exportTarget(map[subpath]);
78
+ if (exact) return path.resolve(packageDir, exact);
79
+ for (const [pattern, entry] of Object.entries(map)) {
80
+ const star = pattern.indexOf("*");
81
+ if (star === -1) continue;
82
+ const prefix = pattern.slice(0, star);
83
+ const suffix = pattern.slice(star + 1);
84
+ if (!subpath.startsWith(prefix) || !subpath.endsWith(suffix) || subpath.length < prefix.length + suffix.length) continue;
85
+ const target = exportTarget(entry);
86
+ if (!target) continue;
87
+ const wildcard = subpath.slice(prefix.length, subpath.length - suffix.length);
88
+ return path.resolve(packageDir, target.replace("*", wildcard));
89
+ }
90
+ return undefined;
91
+ }
92
+ if (subpath !== ".") return undefined;
93
+ return path.resolve(packageDir, typeof manifest.main === "string" && manifest.main.trim() ? manifest.main : "index.js");
94
+ }
95
+
96
+ /** Find `pkg` as the pi package itself, one of its dependencies, or a sibling in a hoisted install. */
97
+ export function findHostPeerPackageDir(piPackageRoot: string, pkg: string): string | undefined {
98
+ if (readManifest(piPackageRoot)?.name === pkg) return piPackageRoot;
99
+ const candidates = [path.join(piPackageRoot, "node_modules", pkg)];
100
+ let dir = piPackageRoot;
101
+ for (;;) {
102
+ const parent = path.dirname(dir);
103
+ if (parent === dir) break;
104
+ if (path.basename(parent) === "node_modules" || path.basename(path.dirname(parent)) === "node_modules") {
105
+ const modulesRoot = path.basename(parent) === "node_modules" ? parent : path.dirname(parent);
106
+ candidates.push(path.join(modulesRoot, pkg));
107
+ }
108
+ candidates.push(path.join(parent, "node_modules", pkg));
109
+ dir = parent;
110
+ }
111
+ return candidates.find((candidate) => readManifest(candidate)?.name === pkg);
112
+ }
113
+
114
+ /** The alias map the runner needs, or the specifiers that could not be resolved. */
115
+ export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record<string, string>; missing: string[] } {
116
+ const aliases: Record<string, string> = {};
117
+ const missing: string[] = [];
118
+ for (const { specifier, pkg, subpath } of HOST_PEER_ALIASES) {
119
+ const packageDir = findHostPeerPackageDir(piPackageRoot, pkg);
120
+ const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : undefined;
121
+ if (target && fs.existsSync(target)) aliases[specifier] = target;
122
+ else missing.push(specifier);
123
+ }
124
+ return { aliases, missing };
125
+ }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * Child session factory for the detached async runner.
3
+ *
4
+ * The runner imports `@earendil-works/pi-coding-agent` like the parent does;
5
+ * the parent aliases that specifier (and the other host peer packages) to the
6
+ * installed pi package through `JITI_ALIAS` when it spawns the runner, see
7
+ * `runner-aliases.ts`. Tests replace the factory with a scripted one by
8
+ * naming a module in the runner config.
9
+ */
10
+ import * as path from "node:path";
11
+ import { pathToFileURL } from "node:url";
12
+ import { createDefaultChildSessionFactory, type ChildSessionFactory } from "../shared/child-session.ts";
13
+
14
+ export interface RunnerChildSessionConfig {
15
+ /** Test seam: module whose default export is a `ChildSessionFactory`, or a function returning one. */
16
+ childSessionFactoryModule?: string;
17
+ }
18
+
19
+ function isChildSessionFactory(value: unknown): value is ChildSessionFactory {
20
+ return Boolean(value) && typeof value === "object" && typeof (value as ChildSessionFactory).create === "function" && typeof (value as ChildSessionFactory).dispose === "function";
21
+ }
22
+
23
+ export async function loadRunnerChildSessionFactory(config: RunnerChildSessionConfig): Promise<ChildSessionFactory> {
24
+ if (!config.childSessionFactoryModule) return createDefaultChildSessionFactory();
25
+ const loaded = await import(pathToFileURL(path.resolve(config.childSessionFactoryModule)).href) as { default?: unknown };
26
+ const candidate = typeof loaded.default === "function" ? (loaded.default as () => unknown)() : loaded.default;
27
+ if (!isChildSessionFactory(candidate)) {
28
+ throw new Error(`Child session factory module '${config.childSessionFactoryModule}' must default-export a ChildSessionFactory or a function returning one.`);
29
+ }
30
+ return candidate;
31
+ }