@xzzpig/pi-subagents 0.14.0 → 0.15.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 (198) hide show
  1. package/CHANGELOG.md +233 -0
  2. package/README.md +6 -5
  3. package/agents/evidence-auditor.md +34 -0
  4. package/agents/researcher.md +23 -13
  5. package/agents/reviewer.md +3 -2
  6. package/docs/agents.md +56 -15
  7. package/docs/configuration.md +92 -14
  8. package/docs/extension-api.md +132 -19
  9. package/docs/missions.md +10 -2
  10. package/docs/models.md +11 -22
  11. package/docs/observability.md +63 -11
  12. package/docs/standalone-background.md +59 -0
  13. package/docs/tool-reference.md +42 -23
  14. package/docs/watchdog.md +39 -10
  15. package/docs/workflows.md +58 -19
  16. package/index.ts +5 -2
  17. package/inspector-runner.mjs +2 -2
  18. package/node_modules/@xzzpig/pi-components/dist/src/transcript.d.ts +13 -3
  19. package/node_modules/@xzzpig/pi-components/dist/src/transcript.js +18 -6
  20. package/node_modules/@xzzpig/pi-components/src/transcript.ts +26 -6
  21. package/package.json +9 -4
  22. package/prompts/parallel-review.md +1 -1
  23. package/runner-peer-loader.mjs +24 -0
  24. package/runner-peer-preload.mjs +36 -0
  25. package/skills/pi-subagents/SKILL.md +34 -22
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +3 -2
  27. package/skills/pi-subagents/references/execution-controls.md +27 -8
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +3 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +17 -13
  31. package/skills/pi-subagents/references/review-and-validation.md +3 -3
  32. package/src/agents/advertised-agent-prompt.ts +94 -0
  33. package/src/agents/agent-management.ts +71 -59
  34. package/src/agents/agent-serializer.ts +6 -3
  35. package/src/agents/agents.ts +198 -72
  36. package/src/agents/builtin-names.ts +1 -0
  37. package/src/agents/chain-serializer.ts +5 -0
  38. package/src/agents/runtime-agent-registry.ts +7 -6
  39. package/src/api/delegation.ts +4 -0
  40. package/src/api/preflight.ts +110 -71
  41. package/src/api/required-child-extensions.ts +6 -0
  42. package/src/api/shared-types.ts +3 -1
  43. package/src/api/workflow-resources.ts +6 -0
  44. package/src/extension/config.ts +14 -37
  45. package/src/extension/fanout-child.ts +68 -5
  46. package/src/extension/herdr-pi-bridge.ts +164 -0
  47. package/src/extension/index.ts +141 -51
  48. package/src/extension/public-execution.ts +7 -6
  49. package/src/extension/rpc.ts +8 -21
  50. package/src/extension/schemas.ts +86 -84
  51. package/src/extension/tool-description.ts +32 -79
  52. package/src/inspectors/actions.ts +148 -0
  53. package/src/inspectors/ghostty/actions.ts +74 -0
  54. package/src/inspectors/ghostty/plugin.ts +17 -0
  55. package/src/inspectors/herdr/actions.ts +99 -179
  56. package/src/inspectors/herdr/plugin.ts +20 -0
  57. package/src/inspectors/herdr/project-panes.ts +4 -1
  58. package/src/inspectors/{herdr/inspector-runner.ts → inspector-runner.ts} +12 -12
  59. package/src/inspectors/plugins.ts +8 -0
  60. package/src/inspectors/{herdr/session-roots-codec.ts → session-roots-codec.ts} +3 -14
  61. package/src/inspectors/types.ts +51 -0
  62. package/src/integrations/pi-web-session-liveness.ts +73 -0
  63. package/src/intercom/intercom-bridge.ts +50 -8
  64. package/src/intercom/native-supervisor-channel.ts +142 -115
  65. package/src/intercom/supervisor-ui.ts +3 -2
  66. package/src/missions/workflow-state.ts +37 -16
  67. package/src/policy/authority.ts +4 -0
  68. package/src/profiles/profiles.ts +12 -6
  69. package/src/runs/background/active-async-capacity.ts +22 -18
  70. package/src/runs/background/active-run-index.ts +17 -1
  71. package/src/runs/background/async-execution.ts +359 -176
  72. package/src/runs/background/async-job-tracker.ts +41 -7
  73. package/src/runs/background/async-resume.ts +19 -12
  74. package/src/runs/background/async-retention.ts +20 -0
  75. package/src/runs/background/async-status-snapshot.ts +10 -12
  76. package/src/runs/background/async-status.ts +32 -13
  77. package/src/runs/background/auto-drain.ts +59 -35
  78. package/src/runs/background/binary-bootstrap.ts +38 -0
  79. package/src/runs/background/chain-append.ts +1 -1
  80. package/src/runs/background/chain-root-attachment.ts +22 -33
  81. package/src/runs/background/control-channel.ts +78 -44
  82. package/src/runs/background/fleet-view.ts +30 -2
  83. package/src/runs/background/notify.ts +193 -19
  84. package/src/runs/background/owned-process-tree.ts +35 -8
  85. package/src/runs/background/process-terminal.ts +23 -23
  86. package/src/runs/background/result-files.ts +8 -4
  87. package/src/runs/background/result-watcher.ts +19 -2
  88. package/src/runs/background/retained-nested-route-tracker.ts +96 -0
  89. package/src/runs/background/run-child-session.ts +118 -41
  90. package/src/runs/background/run-status.ts +78 -5
  91. package/src/runs/background/runner-aliases.ts +22 -5
  92. package/src/runs/background/runner-child-launch.ts +93 -0
  93. package/src/runs/background/runner-child-sessions.ts +5 -4
  94. package/src/runs/background/runner-http-dispatcher.ts +119 -0
  95. package/src/runs/background/scheduled-runs.ts +51 -18
  96. package/src/runs/background/stale-run-reconciler.ts +38 -12
  97. package/src/runs/background/steering.ts +20 -2
  98. package/src/runs/background/subagent-runner.ts +766 -432
  99. package/src/runs/background/subagent-wait.ts +179 -28
  100. package/src/runs/background/wait-completions.ts +79 -27
  101. package/src/runs/background/wait-subscriptions.ts +9 -3
  102. package/src/runs/background/wait-tool.ts +5 -3
  103. package/src/runs/foreground/async-steering-action.ts +37 -7
  104. package/src/runs/foreground/async-stop-action.ts +93 -3
  105. package/src/runs/foreground/execution.ts +174 -194
  106. package/src/runs/foreground/foreground-history.ts +5 -2
  107. package/src/runs/foreground/prompt-audit.ts +12 -6
  108. package/src/runs/foreground/subagent-executor.ts +896 -397
  109. package/src/runs/foreground/workflow-detach-reconcile.ts +10 -5
  110. package/src/runs/foreground/workflow-foreground-steering.ts +57 -2
  111. package/src/runs/shared/acceptance.ts +54 -14
  112. package/src/runs/shared/agent-contract.ts +1 -1
  113. package/src/runs/shared/async-status-projection.ts +172 -78
  114. package/src/runs/shared/capability-ceiling.ts +2 -0
  115. package/src/runs/shared/child-hooks.ts +167 -3
  116. package/src/runs/shared/child-launch-plan.ts +15 -3
  117. package/src/runs/shared/child-launch.ts +44 -16
  118. package/src/runs/shared/child-lifecycle.ts +6 -3
  119. package/src/runs/shared/child-runtime-config.ts +8 -1
  120. package/src/runs/shared/child-session.ts +130 -24
  121. package/src/runs/shared/child-tool-plan.ts +145 -14
  122. package/src/runs/shared/completion-evidence.ts +2 -2
  123. package/src/runs/shared/completion-guard.ts +6 -3
  124. package/src/runs/shared/dynamic-fanout.ts +2 -2
  125. package/src/runs/shared/effective-system-prompt.ts +33 -0
  126. package/src/runs/shared/external-cli-contract.ts +11 -1
  127. package/src/runs/shared/external-cli-preflight.ts +6 -2
  128. package/src/runs/shared/external-cli-runner.ts +9 -7
  129. package/src/runs/shared/herdr-connection.ts +134 -0
  130. package/src/runs/shared/herdr-external-adapters.ts +169 -0
  131. package/src/runs/shared/herdr-machine.ts +279 -0
  132. package/src/runs/shared/herdr-pi-protocol.ts +59 -0
  133. package/src/runs/shared/herdr-placed-run.ts +263 -0
  134. package/src/runs/shared/host-step-status.ts +11 -11
  135. package/src/runs/shared/llm-intent-arbiter.ts +40 -21
  136. package/src/runs/shared/model-resolution-diagnostic.ts +76 -0
  137. package/src/runs/shared/{model-fallback.ts → model-resolution.ts} +34 -218
  138. package/src/runs/shared/model-scope.ts +1 -1
  139. package/src/runs/shared/nested-events.ts +19 -10
  140. package/src/runs/shared/orca-progress-tabs.ts +7 -1
  141. package/src/runs/shared/parallel-handoff.ts +57 -12
  142. package/src/runs/shared/parallel-utils.ts +10 -4
  143. package/src/runs/shared/pi-spawn.ts +10 -0
  144. package/src/runs/shared/readonly-drain-observation.ts +42 -0
  145. package/src/runs/shared/run-fanout-budget.ts +8 -8
  146. package/src/runs/shared/runtime-acknowledged-extensions.ts +3 -3
  147. package/src/runs/shared/subagent-prompt-runtime.ts +23 -5
  148. package/src/runs/shared/task-intent.ts +46 -13
  149. package/src/runs/shared/workflow-async-child-guidance.ts +18 -0
  150. package/src/runs/shared/worktree-cleanup-plan.ts +6 -3
  151. package/src/runs/shared/worktree-setup-command.ts +213 -0
  152. package/src/runs/shared/worktree.ts +437 -214
  153. package/src/shared/child-cache-retention.ts +43 -0
  154. package/src/shared/fork-context.ts +15 -72
  155. package/src/shared/launch-contract.ts +70 -8
  156. package/src/shared/model-response-aliases.ts +13 -0
  157. package/src/shared/opencode-session-headers.ts +30 -0
  158. package/src/shared/pruned-fork.ts +1 -1
  159. package/src/shared/required-child-extensions.ts +81 -0
  160. package/src/shared/settings.ts +5 -2
  161. package/src/shared/shortcuts.ts +0 -4
  162. package/src/shared/types.ts +163 -90
  163. package/src/shared/utils.ts +10 -2
  164. package/src/shared/watch-strategy.ts +2 -0
  165. package/src/shared/workflow-child-permit.ts +18 -13
  166. package/src/slash/delegation-adapters.ts +3 -1
  167. package/src/slash/delegation-request.ts +14 -0
  168. package/src/slash/slash-commands.ts +2 -7
  169. package/src/slash/subagents-admin.ts +31 -14
  170. package/src/tui/fleet-status.ts +165 -20
  171. package/src/tui/fleet.ts +30 -19
  172. package/src/tui/render.ts +210 -50
  173. package/src/watchdog/child-status.ts +28 -28
  174. package/src/watchdog/lsp-diagnostics.ts +1 -1
  175. package/src/watchdog/model-selection.ts +21 -1
  176. package/src/watchdog/permission-arbiter.ts +5 -2
  177. package/src/watchdog/register-child.ts +10 -2
  178. package/src/watchdog/register-main.ts +39 -35
  179. package/src/watchdog/render.ts +1 -1
  180. package/src/watchdog/review.ts +122 -74
  181. package/src/watchdog/rules.ts +1 -1
  182. package/src/watchdog/runtime.ts +100 -27
  183. package/src/watchdog/scope.ts +1 -1
  184. package/src/watchdog/settings.ts +3 -0
  185. package/src/watchdog/tool-actions.ts +13 -12
  186. package/src/watchdog/turn-delta.ts +23 -0
  187. package/src/watchdog/types.ts +5 -3
  188. package/src/watchdog/warning-format.ts +1 -1
  189. package/src/workflows/chat-progress.ts +3 -3
  190. package/src/workflows/scripted-workflow.ts +349 -26
  191. package/src/workflows/workflow-checklist.ts +17 -20
  192. package/src/workflows/workflow-child-summary.ts +57 -8
  193. package/src/workflows/workflow-preflight.ts +19 -19
  194. package/src/workflows/workflow-receipt.ts +24 -6
  195. package/src/workflows/workflow-resources.ts +108 -22
  196. package/src/workflows/workflow-settlement.ts +3 -0
  197. package/src/runs/shared/model-exclusions.ts +0 -373
  198. /package/src/inspectors/{herdr/shell-command.ts → shell-command.ts} +0 -0
@@ -2,12 +2,14 @@ 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 { getArtifactPaths, getArtifactsDir } from "../../shared/artifacts.ts";
6
+ import { readFleetTranscript } from "../../tui/fleet-transcript.ts";
5
7
  import { formatAsyncRunList, formatAsyncRunOutputPath, formatAsyncRunProgressLabel, formatWorkflowStageLine, listAsyncRuns } from "./async-status.ts";
6
8
  import { formatAsyncResultTranscript, formatAsyncRunTranscript, formatNestedRunTranscript, inspectSubagentFleet } from "./fleet-view.ts";
7
9
  import { formatNestedRunStatusLines } from "../shared/nested-render.ts";
8
10
  import { formatModelThinking } from "../../shared/formatters.ts";
9
11
  import { formatActivityLabel } from "../../shared/status-format.ts";
10
- import { DIRS, type AsyncStatus, type Details, type ForegroundResumeRun, type NestedRunSummary, type SteeringStatus, type SubagentState } from "../../shared/types.ts";
12
+ import { DIRS, type AsyncStatus, type Details, type ForegroundRunControl, type ForegroundResumeRun, type NestedRunSummary, type SteeringStatus, type SubagentState } from "../../shared/types.ts";
11
13
  import { inspectActiveAsyncCapacityOwner, type ActiveAsyncCapacityInspection } from "./active-async-capacity.ts";
12
14
  import { readStatus } from "../../shared/utils.ts";
13
15
  import { resolveSubagentIntercomTarget } from "../../intercom/intercom-bridge.ts";
@@ -30,6 +32,7 @@ import { getExternalJobProvider } from "../../api/external-job-provider.ts";
30
32
  import { formatTimeoutRecoveryLines } from "../shared/mutation-evidence.ts";
31
33
  import { formatWorkflowChecklistText, projectWorkflowChecklist } from "../../workflows/workflow-checklist.ts";
32
34
  import { validHostStepNodes } from "../shared/host-step-status.ts";
35
+ import { workflowAsyncChildSteeringGuidance } from "../shared/workflow-async-child-guidance.ts";
33
36
 
34
37
  interface RunStatusParams {
35
38
  action?: string;
@@ -88,6 +91,7 @@ function formatRunLifecycleDebug(input: { status: AsyncStatus; asyncDir: string;
88
91
  `Run: ${status.runId}`,
89
92
  `Dir: ${asyncDir}`,
90
93
  `Status file: ${path.join(asyncDir, "status.json")}`,
94
+ status.workflowReceiptPath ? `Workflow receipt: ${status.workflowReceiptPath}` : undefined,
91
95
  `Process terminal file: ${path.join(asyncDir, "process-terminal.json")}`,
92
96
  `Session: ${status.sessionId ?? "unknown"}`,
93
97
  `State: ${status.state}`,
@@ -241,6 +245,54 @@ function formatRememberedForegroundStatus(run: ForegroundResumeRun): string {
241
245
  return lines.join("\n");
242
246
  }
243
247
 
248
+ /** Request-only snapshot of the same artifact used by Fleet; no session or output fallback. */
249
+ function formatLiveForegroundTranscript(control: ForegroundRunControl, state: SubagentState, options: { index?: number; lines?: number }): string {
250
+ if (!state.currentSessionId || control.sessionId !== state.currentSessionId) {
251
+ throw new Error(`Foreground run '${control.runId}' is not owned by the current session.`);
252
+ }
253
+ if (options.index !== undefined && (!Number.isInteger(options.index) || options.index < 0)) {
254
+ throw new Error("Transcript index must be a non-negative integer.");
255
+ }
256
+ const children = control.activeChildren
257
+ ? [...control.activeChildren.values()]
258
+ : control.currentAgent ? [{ index: control.currentIndex ?? 0, agent: control.currentAgent, sessionName: control.sessionName }] : [];
259
+ const header = [`Run: ${control.runId}`, "State: live foreground"];
260
+ if (children.length === 0) return `${header.map((line) => safeTerminalText(line)).join("\n")}\nTranscript unavailable: no active foreground child.`;
261
+ if (options.index === undefined && children.length > 1) {
262
+ throw new Error(`Transcript view requires index for foreground run '${control.runId}'. Active child indexes: ${children.map((child) => child.index).join(", ")}.`);
263
+ }
264
+ const child = options.index === undefined ? children[0]! : children.find((child) => child.index === options.index);
265
+ if (!child) throw new Error(`Transcript index ${options.index} is not an active foreground child of '${control.runId}'.`);
266
+ const root = getArtifactsDir(state.parentSessionFile ?? null, control.cwd ?? state.baseCwd, state.artifactDirPreference);
267
+ const transcriptPath = getArtifactPaths(root, control.runId, child.agent, child.index).transcriptPath;
268
+ const transcript = readFleetTranscript(transcriptPath, { trustedRoots: [root] });
269
+ const lineLimit = Number.isFinite(options.lines) ? Math.max(1, Math.min(500, Math.trunc(options.lines!))) : 80;
270
+ const allLines = transcript.events.flatMap((event) => {
271
+ const text = event.kind === "tool"
272
+ ? [`Tool: ${event.name} (${event.status})`, event.argsPayload ?? event.args, event.output ?? event.error].filter(Boolean).join("\n")
273
+ : event.kind === "notice" ? event.text : `${event.kind === "assistant" ? "Assistant" : "Supervisor"}: ${event.text}`;
274
+ return text.split(/\r?\n/);
275
+ });
276
+ let body = allLines.slice(-lineLimit).join("\n");
277
+ let truncated = transcript.truncated || allLines.length > lineLimit
278
+ || transcript.events.some((event) => event.kind === "tool" && event.outputTruncated)
279
+ || body.includes("… message truncated");
280
+ const maxOutputBytes = 32 * 1024;
281
+ const bytes = Buffer.from(body);
282
+ if (bytes.length > maxOutputBytes) {
283
+ // Skip UTF-8 continuation bytes at the beginning of the bounded tail.
284
+ let start = bytes.length - maxOutputBytes;
285
+ while ((bytes[start]! & 0xc0) === 0x80) start++;
286
+ body = bytes.subarray(start).toString("utf-8");
287
+ truncated = true;
288
+ }
289
+ header.push(`Child: ${child.index} (${child.sessionName?.trim() || child.agent})`, `Transcript: ${transcriptPath}`);
290
+ if (transcript.warning) header.push(`Transcript warning: ${transcript.warning}`);
291
+ header.push(`Live transcript tail${truncated ? " (tail truncated)" : ""}:`);
292
+ if (!body) header.push("Transcript unavailable: no readable activity in the bounded artifact tail yet.");
293
+ return [...header.map((line) => safeTerminalText(line)), body].filter(Boolean).join("\n");
294
+ }
295
+
244
296
  function formatRememberedForegroundTranscript(run: ForegroundResumeRun, options: { index?: number; lines?: number }): string {
245
297
  let index = options.index;
246
298
  if (index !== undefined && !Number.isInteger(index)) throw new Error("Transcript index must be an integer.");
@@ -313,6 +365,12 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
313
365
  return inspectSubagentFleet(params, { asyncDirRoot, resultsDir, kill: deps.kill, now: deps.now, state: deps.state, childSafe: Boolean(deps.nested) });
314
366
  }
315
367
  if (!params.id && !params.runId && !params.dir) {
368
+ if (params.view === "transcript" && deps.state?.currentSessionId) {
369
+ const controls = [...deps.state.foregroundControls.values()].filter((control) => control.sessionId === currentSessionId);
370
+ const foreground = controls.find((control) => control.runId === deps.state?.lastForegroundControlId)
371
+ ?? controls.sort((left, right) => right.updatedAt - left.updatedAt)[0];
372
+ if (foreground) return inspectSubagentStatus({ ...params, id: foreground.runId }, deps);
373
+ }
316
374
  if (deps.nested) {
317
375
  return {
318
376
  content: [{ type: "text", text: "Child-safe subagent status requires an id when no foreground run is active." }],
@@ -353,6 +411,13 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
353
411
  } else if (!params.dir && requestedId) {
354
412
  const resolved = resolveSubagentRunId(requestedId, { asyncDirRoot, resultsDir, state: deps.state, nested: deps.nested });
355
413
  if (resolved?.kind === "foreground") {
414
+ const control = deps.state?.foregroundControls.get(resolved.id);
415
+ if (control && deps.state && params.view === "transcript") {
416
+ return {
417
+ content: [{ type: "text", text: formatLiveForegroundTranscript(control, deps.state, params) }],
418
+ details: { mode: "management", results: [] },
419
+ };
420
+ }
356
421
  const run = deps.state?.foregroundRuns?.get(resolved.id);
357
422
  if (run) {
358
423
  try {
@@ -423,7 +488,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
423
488
  const capacity = inspectActiveAsyncCapacityOwner({ runId: diskStatus.runId, sessionId: diskStatus.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: deps.abandonedSlotReleaseAfterMs });
424
489
  return {
425
490
  content: [{ type: "text", text: formatRunLifecycleDebug({ status: diskStatus, asyncDir, sidecarProcessTerminal: sidecar, overlayProcessTerminal: overlay, capacity }) }],
426
- details: { mode: "single", results: [], ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
491
+ details: { mode: "single", results: [], ...(diskStatus.workflowReceiptPath ? { workflowReceiptPath: diskStatus.workflowReceiptPath } : {}), ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
427
492
  };
428
493
  }
429
494
  if (params.view === "transcript") {
@@ -450,7 +515,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
450
515
  const capacity = inspectActiveAsyncCapacityOwner({ runId: status.runId, sessionId: status.sessionId, asyncDir }, { rootDir: deps.activeCapacityRoot, liveWorkflowRunIds: new Set(deps.state?.workflowControllers?.keys() ?? []), abandonedSlotReleaseAfterMs: deps.abandonedSlotReleaseAfterMs });
451
516
  return {
452
517
  content: [{ type: "text", text: formatRunLifecycleDebug({ status, asyncDir, sidecarProcessTerminal: sidecar, overlayProcessTerminal: overlay, capacity }) }],
453
- details: { mode: "single", results: [], ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
518
+ details: { mode: "single", results: [], ...(status.workflowReceiptPath ? { workflowReceiptPath: status.workflowReceiptPath } : {}), ...((sidecar ?? overlay) ? { lifecycleStatus: { processTerminal: sidecar ?? overlay } } : {}) },
454
519
  };
455
520
  }
456
521
  if (params.view === "transcript") {
@@ -560,6 +625,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
560
625
  const display = runStatusStepDisplayName(step);
561
626
  const phase = step.phase ? `[${step.phase}] ` : "";
562
627
  lines.push(`${stepLineLabel(status, index)}: ${phase}${display} ${step.status}${modelText}${stepActivityText ? `, ${stepActivityText}` : ""}${steeringSuffix}${acceptanceText}${budgetText}${errorText}`);
628
+ if (status.mode === "workflow" && step.runId) lines.push(` Child run: ${step.runId}`);
563
629
  const structuredOutputPreview = step.structuredOutput === undefined ? undefined : formatWorkflowJsonPreview(step.structuredOutput, 4_000);
564
630
  if (structuredOutputPreview !== undefined) lines.push(` Structured output: ${structuredOutputPreview}`);
565
631
  if (step.structuredOutputPath) lines.push(` Structured output path: ${step.structuredOutputPath}`);
@@ -624,8 +690,10 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
624
690
  lines.push(`Steer live foreground child: subagent({ action: "steer", id: "${control.runId}", index: ${index}, message: "..." })`);
625
691
  }
626
692
  }
693
+ lines.push(...workflowAsyncChildSteeringGuidance(status, deps.state));
627
694
  }
628
695
  if (nestedWarning) lines.push(`Warning: ${nestedWarning}`);
696
+ if (status.workflowReceiptPath) lines.push(`Workflow receipt: ${status.workflowReceiptPath}`);
629
697
  if (status.sessionFile) lines.push(`Session: ${status.sessionFile}`);
630
698
  const allExternal = (status.steps?.length ?? 0) > 0 && status.steps!.every((step) => step.runner?.type === "external-cli" || step.runner?.type === "external-job");
631
699
  if (status.state === "running" && !allExternal && status.mode !== "workflow") lines.push(`Steer running child: subagent({ action: "steer", id: "${status.runId}", message: "..." })`);
@@ -639,7 +707,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
639
707
 
640
708
  const workflowChildren = parseWorkflowChildSummary(status.workflowChildren);
641
709
  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 } } : {}) } };
710
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(status.workflowReceiptPath ? { workflowReceiptPath: status.workflowReceiptPath } : {}), ...(status.preflight ? { preflight: status.preflight } : {}), ...(status.workflow?.preflightWarnings?.length ? { preflightWarnings: status.workflow.preflightWarnings } : {}), ...(workflowChildren ? { workflowChildren } : {}), ...(runFanoutBudget ? { runFanoutBudget } : {}), ...(processTerminal ? { lifecycleStatus: { processTerminal } } : {}) } };
643
711
  }
644
712
  }
645
713
 
@@ -680,6 +748,11 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
680
748
  const runId = data.runId ?? data.id ?? resolvedId;
681
749
  const lines = [`Run: ${runId}`, data.toolCallId ? `Tool call: ${data.toolCallId}` : undefined, `State: ${status}`, `Result: ${resultPath}`].filter((line): line is string => Boolean(line));
682
750
  if (data.parallelHandoff?.path) lines.push(`Parallel handoff: ${data.parallelHandoff.path}`);
751
+ const receipt = (data as Record<string, unknown>).workflowReceipt;
752
+ const receiptPath = receipt && typeof receipt === "object" && !Array.isArray(receipt)
753
+ ? (receipt as Record<string, unknown>).path : undefined;
754
+ const workflowReceiptPath = typeof receiptPath === "string" && receiptPath ? receiptPath : undefined;
755
+ if (workflowReceiptPath) lines.push(`Workflow receipt: ${workflowReceiptPath}`);
683
756
  const children = Array.isArray(data.results) ? data.results : data.agent ? [{ agent: data.agent, sessionFile: data.sessionFile }] : [];
684
757
  lines.push(...formatTimeoutRecoveryLines(data.timeoutRecovery, " "));
685
758
  for (const [index, child] of children.entries()) {
@@ -694,7 +767,7 @@ export function inspectSubagentStatus(params: RunStatusParams, deps: RunStatusDe
694
767
  if (data.summary) lines.push("", data.summary);
695
768
  const workflowChildren = parseWorkflowChildSummary((data as unknown as Record<string, unknown>).workflowChildren);
696
769
  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 } : {}) } };
770
+ return { content: [{ type: "text", text: lines.join("\n") }], details: { mode: "single", results: [], ...(workflowReceiptPath ? { workflowReceiptPath } : {}), ...(workflowChildren ? { workflowChildren } : {}) } };
698
771
  } catch (error) {
699
772
  const message = error instanceof Error ? error.message : String(error);
700
773
  return {
@@ -7,8 +7,7 @@
7
7
  * this extension and are not installed next to it. pi's own extension loader
8
8
  * aliases those specifiers to the copies shipped inside the installed pi
9
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.
10
+ * through `JITI_ALIAS`, so child sessions and hooks retain host API identity.
12
11
  */
13
12
  import * as fs from "node:fs";
14
13
  import * as path from "node:path";
@@ -19,6 +18,7 @@ export const JITI_ALIAS_ENV = "JITI_ALIAS";
19
18
  export const HOST_PEER_ALIASES: ReadonlyArray<{ specifier: string; pkg: string; subpath: string }> = [
20
19
  { specifier: "@earendil-works/pi-coding-agent", pkg: "@earendil-works/pi-coding-agent", subpath: "." },
21
20
  { specifier: "@earendil-works/pi-agent-core", pkg: "@earendil-works/pi-agent-core", subpath: "." },
21
+ { specifier: "@earendil-works/pi-agent-core/node", pkg: "@earendil-works/pi-agent-core", subpath: "./node" },
22
22
  { specifier: "@earendil-works/pi-tui", pkg: "@earendil-works/pi-tui", subpath: "." },
23
23
  { specifier: "@earendil-works/pi-ai", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
24
24
  { specifier: "@earendil-works/pi-ai/compat", pkg: "@earendil-works/pi-ai", subpath: "./compat" },
@@ -29,8 +29,15 @@ export const HOST_PEER_ALIASES: ReadonlyArray<{ specifier: string; pkg: string;
29
29
  { specifier: "typebox/value", pkg: "typebox", subpath: "./value" },
30
30
  ];
31
31
 
32
+ /** Public Pi manifests introduce chord in 0.85.0 (absent through 0.84.4). */
33
+ const CHORD_PEER_ALIASES = [
34
+ { specifier: "@earendil-works/chord", pkg: "@earendil-works/chord", subpath: "." },
35
+ { specifier: "@earendil-works/chord/context", pkg: "@earendil-works/chord", subpath: "./context" },
36
+ ];
37
+
32
38
  interface PackageManifest {
33
39
  name?: unknown;
40
+ version?: unknown;
34
41
  main?: unknown;
35
42
  exports?: unknown;
36
43
  }
@@ -95,7 +102,11 @@ export function resolvePackageSubpath(packageDir: string, subpath: string): stri
95
102
 
96
103
  /** Find `pkg` as the pi package itself, one of its dependencies, or a sibling in a hoisted install. */
97
104
  export function findHostPeerPackageDir(piPackageRoot: string, pkg: string): string | undefined {
98
- if (readManifest(piPackageRoot)?.name === pkg) return piPackageRoot;
105
+ return findPeerPackageDir(piPackageRoot, pkg, readManifest(piPackageRoot)?.name);
106
+ }
107
+
108
+ function findPeerPackageDir(piPackageRoot: string, pkg: string, hostName: unknown): string | undefined {
109
+ if (hostName === pkg) return piPackageRoot;
99
110
  const candidates = [path.join(piPackageRoot, "node_modules", pkg)];
100
111
  let dir = piPackageRoot;
101
112
  for (;;) {
@@ -115,8 +126,14 @@ export function findHostPeerPackageDir(piPackageRoot: string, pkg: string): stri
115
126
  export function resolveHostPeerAliases(piPackageRoot: string): { aliases: Record<string, string>; missing: string[] } {
116
127
  const aliases: Record<string, string> = {};
117
128
  const missing: string[] = [];
118
- for (const { specifier, pkg, subpath } of HOST_PEER_ALIASES) {
119
- const packageDir = findHostPeerPackageDir(piPackageRoot, pkg);
129
+ const hostManifest = readManifest(piPackageRoot);
130
+ // Only known stable pre-chord versions may omit it. Unknown/prerelease
131
+ // hosts retain the required aliases, rather than hiding a broken install.
132
+ const stableVersion = typeof hostManifest?.version === "string" ? /^0\.(\d+)\.\d+$/.exec(hostManifest.version) : null;
133
+ const isPreChord = stableVersion !== null && Number(stableVersion[1]) < 85;
134
+ const required = [...HOST_PEER_ALIASES, ...(isPreChord ? [] : CHORD_PEER_ALIASES)];
135
+ for (const { specifier, pkg, subpath } of required) {
136
+ const packageDir = findPeerPackageDir(piPackageRoot, pkg, hostManifest?.name);
120
137
  const target = packageDir ? resolvePackageSubpath(packageDir, subpath) : undefined;
121
138
  if (target && fs.existsSync(target)) aliases[specifier] = target;
122
139
  else missing.push(specifier);
@@ -0,0 +1,93 @@
1
+ /** Native runner construction, separate from its executable entrypoint and attempt loop. */
2
+ import * as path from "node:path";
3
+ import { buildInProcessChildLaunch, type BuildInProcessChildLaunchInput, type InheritedChildRuntime } from "../shared/child-launch.ts";
4
+ import { deriveForkPromptCacheKey } from "../shared/child-tool-plan.ts";
5
+ import { normalizeExtensionBindings } from "../shared/extension-bindings.ts";
6
+ import type { RunnerSubagentStep } from "../shared/parallel-utils.ts";
7
+ import { formatAcceptancePrompt } from "../shared/acceptance.ts";
8
+ import { isAgentContract } from "../shared/agent-contract.ts";
9
+
10
+ export interface RunnerChildLaunchContext {
11
+ cwd: string;
12
+ id: string;
13
+ flatIndex: number;
14
+ artifactsDir?: string;
15
+ childIntercomTarget?: string;
16
+ orchestratorIntercomTarget?: string;
17
+ nestedRoute?: BuildInProcessChildLaunchInput["nestedRoute"];
18
+ runFanoutBudget?: BuildInProcessChildLaunchInput["runFanoutBudget"];
19
+ capabilityCeiling?: BuildInProcessChildLaunchInput["capabilityCeiling"];
20
+ inheritedChildRuntime?: InheritedChildRuntime;
21
+ hostAvailableBuiltins?: readonly string[];
22
+ }
23
+
24
+ export function buildRunnerChildLaunch(step: RunnerSubagentStep, ctx: RunnerChildLaunchContext, attempt: {
25
+ model?: string;
26
+ sessionEnabled: boolean;
27
+ sessionDir?: string;
28
+ sessionName?: string;
29
+ structuredOutput?: BuildInProcessChildLaunchInput["structuredOutput"];
30
+ childWatchdog?: BuildInProcessChildLaunchInput["childWatchdog"];
31
+ watchdogStatus: NonNullable<BuildInProcessChildLaunchInput["watchdogStatus"]>;
32
+ }) {
33
+ // Resource-backed system instructions survive SDK split-turn compaction verbatim.
34
+ const acceptancePrompt = step.effectiveAcceptance
35
+ ? formatAcceptancePrompt(step.effectiveAcceptance, { reportOptional: isAgentContract(step.agentContract), structuredOutput: Boolean(step.structuredOutput?.acceptanceReportPath) })
36
+ : "";
37
+ return buildInProcessChildLaunch({
38
+ machine: step.machine,
39
+ remoteSkillNames: step.skills,
40
+ remoteReads: step.remoteReads,
41
+ parentSessionId: step.parentSessionId,
42
+ forkCacheKey: step.context === "fork" ? deriveForkPromptCacheKey(step.parentSessionId) : undefined,
43
+ sessionEnabled: attempt.sessionEnabled,
44
+ sessionDir: attempt.sessionDir,
45
+ sessionFile: step.sessionFile,
46
+ model: attempt.model,
47
+ inheritProjectContext: step.inheritProjectContext,
48
+ inheritGlobalContext: step.inheritGlobalContext,
49
+ inheritSkills: step.inheritSkills,
50
+ requireReadTool: Boolean(step.skills?.length),
51
+ tools: step.tools,
52
+ excludeTools: step.excludeTools,
53
+ allowNestedSubagents: step.allowNestedSubagents,
54
+ extensions: step.extensions,
55
+ subagentOnlyExtensions: step.subagentOnlyExtensions,
56
+ requiredExtensions: step.requiredExtensions,
57
+ fast: step.fast,
58
+ systemPrompt: acceptancePrompt ? `${step.systemPrompt ?? ""}\n${acceptancePrompt}` : step.systemPrompt ?? "",
59
+ systemPromptMode: step.systemPromptMode,
60
+ mcpDirectTools: step.mcpDirectTools,
61
+ extensionBindings: normalizeExtensionBindings(step.extensionBindings)?.value,
62
+ capabilityCeiling: step.capabilityCeiling ?? ctx.capabilityCeiling,
63
+ cwd: step.cwd ?? ctx.cwd,
64
+ intercomSessionName: ctx.childIntercomTarget,
65
+ sessionName: attempt.sessionName,
66
+ orchestratorIntercomTarget: ctx.orchestratorIntercomTarget,
67
+ runId: ctx.id,
68
+ childAgentName: step.agent,
69
+ childIndex: ctx.flatIndex,
70
+ nestedRoute: ctx.nestedRoute,
71
+ runFanoutBudget: ctx.runFanoutBudget ? {
72
+ ...ctx.runFanoutBudget,
73
+ ...(step.runFanoutPath ? { parentPath: `${ctx.runFanoutBudget.parentPath ? `${ctx.runFanoutBudget.parentPath}/` : ""}${step.runFanoutPath}` } : {}),
74
+ } : undefined,
75
+ structuredOutput: attempt.structuredOutput,
76
+ toolBudget: step.toolBudget,
77
+ permissionRules: step.permissionRules,
78
+ sandbox: step.sandbox,
79
+ permissionProfile: step.permissionProfile,
80
+ permissionAuditPath: step.permissionRules && ctx.artifactsDir
81
+ ? path.join(ctx.artifactsDir, "permission-audit", `${ctx.id}-${ctx.flatIndex}.jsonl`) : undefined,
82
+ childWatchdog: attempt.childWatchdog,
83
+ // registerChildWatchdog returns before reading the sink when unconfigured.
84
+ ...(attempt.childWatchdog ? { watchdogStatus: attempt.watchdogStatus } : {}),
85
+ waitToolEnabled: step.waitToolEnabled,
86
+ waitToolDefaultTimeoutMs: step.waitToolDefaultTimeoutMs,
87
+ thinkingCeiling: step.thinkingCeiling,
88
+ maxSubagentDepth: step.maxSubagentDepth,
89
+ inherited: ctx.inheritedChildRuntime,
90
+ hostAvailableBuiltins: ctx.hostAvailableBuiltins,
91
+ host: "runner",
92
+ });
93
+ }
@@ -5,11 +5,12 @@
5
5
  * the parent aliases that specifier (and the other host peer packages) to the
6
6
  * installed pi package through `JITI_ALIAS` when it spawns the runner, see
7
7
  * `runner-aliases.ts`. Tests replace the factory with a scripted one by
8
- * naming a module in the runner config.
8
+ * naming a module in the runner config. The binary bootstrap supplies its
9
+ * embedded SDK through the default factory's existing loader option instead.
9
10
  */
10
11
  import * as path from "node:path";
11
12
  import { pathToFileURL } from "node:url";
12
- import { createDefaultChildSessionFactory, type ChildSessionFactory } from "../shared/child-session.ts";
13
+ import { createPlacementChildSessionFactory, type ChildSessionFactory, type DefaultChildSessionFactoryOptions } from "../shared/child-session.ts";
13
14
 
14
15
  export interface RunnerChildSessionConfig {
15
16
  /** Test seam: module whose default export is a `ChildSessionFactory`, or a function returning one. */
@@ -20,8 +21,8 @@ function isChildSessionFactory(value: unknown): value is ChildSessionFactory {
20
21
  return Boolean(value) && typeof value === "object" && typeof (value as ChildSessionFactory).create === "function" && typeof (value as ChildSessionFactory).dispose === "function";
21
22
  }
22
23
 
23
- export async function loadRunnerChildSessionFactory(config: RunnerChildSessionConfig): Promise<ChildSessionFactory> {
24
- if (!config.childSessionFactoryModule) return createDefaultChildSessionFactory();
24
+ export async function loadRunnerChildSessionFactory(config: RunnerChildSessionConfig, options?: DefaultChildSessionFactoryOptions): Promise<ChildSessionFactory> {
25
+ if (!config.childSessionFactoryModule) return createPlacementChildSessionFactory(options);
25
26
  const loaded = await import(pathToFileURL(path.resolve(config.childSessionFactoryModule)).href) as { default?: unknown };
26
27
  const candidate = typeof loaded.default === "function" ? (loaded.default as () => unknown)() : loaded.default;
27
28
  if (!isChildSessionFactory(candidate)) {
@@ -0,0 +1,119 @@
1
+ import { EventEmitter } from "node:events";
2
+ import * as fs from "node:fs";
3
+ import { createRequire } from "node:module";
4
+ import * as path from "node:path";
5
+ import { getConfigDirName } from "../../shared/utils.ts";
6
+
7
+ /** Pi's default undici header/body idle timeout. */
8
+ export const DEFAULT_HTTP_IDLE_TIMEOUT_MS = 300_000;
9
+
10
+ export interface HttpIdleTimeoutResolution {
11
+ timeoutMs: number;
12
+ source: "project" | "global" | "default";
13
+ warning?: string;
14
+ }
15
+
16
+ /**
17
+ * Mirrors pi-coding-agent's `parseHttpIdleTimeoutMs`: numbers (or numeric
18
+ * strings) are floored, `"disabled"` means 0, anything else is invalid.
19
+ */
20
+ export function parseHttpIdleTimeoutMs(value: unknown): number | undefined {
21
+ if (typeof value === "string") {
22
+ const trimmed = value.trim();
23
+ if (trimmed.toLowerCase() === "disabled") return 0;
24
+ if (trimmed.length === 0) return undefined;
25
+ return parseHttpIdleTimeoutMs(Number(trimmed));
26
+ }
27
+ if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return undefined;
28
+ return Math.floor(value);
29
+ }
30
+
31
+ function readSetting(file: string): { present: boolean; value?: unknown; error?: string } {
32
+ let raw: string;
33
+ try {
34
+ raw = fs.readFileSync(file, "utf8");
35
+ } catch (error) {
36
+ if ((error as NodeJS.ErrnoException).code === "ENOENT") return { present: false };
37
+ return { present: false, error: `cannot read ${file}: ${error instanceof Error ? error.message : String(error)}` };
38
+ }
39
+ try {
40
+ const parsed = JSON.parse(raw) as unknown;
41
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return { present: false };
42
+ if (!Object.hasOwn(parsed, "httpIdleTimeoutMs")) return { present: false };
43
+ return { present: true, value: (parsed as Record<string, unknown>).httpIdleTimeoutMs };
44
+ } catch (error) {
45
+ return { present: false, error: `cannot parse ${file}: ${error instanceof Error ? error.message : String(error)}` };
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Resolves Pi's `httpIdleTimeoutMs` the way the host does: the project
51
+ * `.pi/settings.json` overrides the global `<agentDir>/settings.json`, and an
52
+ * unset value falls back to 300 000 ms. Detached runners install their own
53
+ * undici dispatcher before pi-coding-agent is loaded, so they cannot borrow
54
+ * Pi's SettingsManager and must read the setting themselves.
55
+ */
56
+ export function resolveHttpIdleTimeoutMs(options: { agentDir: string; cwd: string }): HttpIdleTimeoutResolution {
57
+ const candidates: Array<{ source: "project" | "global"; file: string }> = [
58
+ { source: "project", file: path.join(options.cwd, getConfigDirName(), "settings.json") },
59
+ { source: "global", file: path.join(options.agentDir, "settings.json") },
60
+ ];
61
+ const warnings: string[] = [];
62
+ for (const candidate of candidates) {
63
+ const read = readSetting(candidate.file);
64
+ if (read.error) {
65
+ warnings.push(read.error);
66
+ continue;
67
+ }
68
+ if (!read.present) continue;
69
+ const timeoutMs = parseHttpIdleTimeoutMs(read.value);
70
+ if (timeoutMs === undefined) {
71
+ // Pi rejects the merged value outright; a malformed override must not
72
+ // silently fall through to a different scope's setting.
73
+ warnings.push(`invalid httpIdleTimeoutMs in ${candidate.file}: ${String(read.value)}`);
74
+ return { timeoutMs: DEFAULT_HTTP_IDLE_TIMEOUT_MS, source: "default", warning: warnings.join("; ") };
75
+ }
76
+ return { timeoutMs, source: candidate.source, ...(warnings.length ? { warning: warnings.join("; ") } : {}) };
77
+ }
78
+ return { timeoutMs: DEFAULT_HTTP_IDLE_TIMEOUT_MS, source: "default", ...(warnings.length ? { warning: warnings.join("; ") } : {}) };
79
+ }
80
+
81
+ /** Dispatcher options shared by the runner and its regression test. */
82
+ export function runnerHttpDispatcherOptions(timeoutMs: number): {
83
+ allowH2: false;
84
+ proxyTunnel: true;
85
+ headersTimeout: number;
86
+ bodyTimeout: number;
87
+ } {
88
+ return {
89
+ allowH2: false,
90
+ // Keep HTTP origins on CONNECT tunnels, matching Pi's dispatcher.
91
+ proxyTunnel: true,
92
+ headersTimeout: timeoutMs,
93
+ bodyTimeout: timeoutMs,
94
+ };
95
+ }
96
+
97
+ /**
98
+ * Installs the runner's proxy-aware undici dispatcher as the process global and
99
+ * routes global fetch through it, with header/body idle clocks taken from Pi's
100
+ * `httpIdleTimeoutMs`. Detached runners skip Pi's CLI dispatcher setup: the Node
101
+ * entrypoint never runs it, and the binary bootstrap runs inside the extension
102
+ * factory, before Pi applies the setting to its own dispatcher. Best effort: a
103
+ * failure logs and leaves the existing dispatcher in place.
104
+ */
105
+ export function installRunnerHttpDispatcher(options: { agentDir: string; cwd: string }): void {
106
+ try {
107
+ // SAFETY: require loads the pinned direct dependency described by these types.
108
+ const undici = createRequire(import.meta.url)("undici") as typeof import("undici");
109
+ const idle = resolveHttpIdleTimeoutMs(options);
110
+ if (idle.warning) console.error(`[pi-subagents] httpIdleTimeoutMs: ${idle.warning}; using ${idle.timeoutMs}ms`);
111
+ const dispatcher = new undici.EnvHttpProxyAgent(runnerHttpDispatcherOptions(idle.timeoutMs));
112
+ // Fetch rejects stream errors; the listener prevents an unhandled EventEmitter error.
113
+ EventEmitter.prototype.on.call(dispatcher, "error", () => {});
114
+ undici.setGlobalDispatcher(dispatcher);
115
+ undici.install();
116
+ } catch (error) {
117
+ console.error(`[pi-subagents] proxy-aware HTTP dispatcher not installed: ${error instanceof Error ? error.message : String(error)}`);
118
+ }
119
+ }