@xzzpig/pi-subagents 0.8.0 → 0.10.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 (221) hide show
  1. package/CHANGELOG.md +477 -0
  2. package/README.md +2 -2
  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 +1 -1
  10. package/agents/scout.md +1 -1
  11. package/docs/agents.md +195 -39
  12. package/docs/configuration.md +81 -22
  13. package/docs/extension-api.md +69 -14
  14. package/docs/missions.md +2 -0
  15. package/docs/models.md +32 -9
  16. package/docs/observability.md +22 -20
  17. package/docs/tool-reference.md +123 -14
  18. package/docs/watchdog.md +92 -114
  19. package/docs/workflows.md +142 -4
  20. package/install.mjs +1 -1
  21. package/package.json +7 -6
  22. package/prompts/review-loop.md +2 -2
  23. package/skills/council-mode/SKILL.md +48 -243
  24. package/skills/council-mode/references/pass-contracts.md +150 -0
  25. package/skills/pi-subagents/SKILL.md +89 -35
  26. package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
  27. package/skills/pi-subagents/references/execution-controls.md +91 -15
  28. package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
  29. package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
  30. package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
  31. package/skills/pi-subagents/references/review-and-validation.md +73 -0
  32. package/src/agents/agent-management.ts +384 -115
  33. package/src/agents/agent-refinements.ts +4 -4
  34. package/src/agents/agent-serializer.ts +14 -2
  35. package/src/agents/agents.ts +935 -372
  36. package/src/agents/builtin-names.ts +6 -0
  37. package/src/agents/runtime-agent-events.ts +70 -0
  38. package/src/agents/runtime-agent-registry.ts +42 -21
  39. package/src/api/agents.ts +10 -5
  40. package/src/api/background-work.ts +12 -3
  41. package/src/api/capability-ceiling.ts +0 -1
  42. package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
  43. package/src/api/delegation.ts +0 -7
  44. package/src/api/external-runs.ts +67 -4
  45. package/src/api/preflight.ts +77 -21
  46. package/src/api/shared-types.ts +6 -0
  47. package/src/extension/config.ts +90 -0
  48. package/src/extension/doctor.ts +5 -13
  49. package/src/extension/fanout-child.ts +14 -14
  50. package/src/extension/index.ts +115 -37
  51. package/src/extension/public-execution.ts +103 -15
  52. package/src/extension/rpc.ts +120 -25
  53. package/src/extension/schemas.ts +65 -29
  54. package/src/extension/tool-description.ts +48 -26
  55. package/src/inspectors/herdr/actions.ts +2 -1
  56. package/src/inspectors/herdr/inspector-runner.ts +21 -23
  57. package/src/inspectors/herdr/session-roots-codec.ts +42 -0
  58. package/src/integrations/herdr-status.ts +51 -3
  59. package/src/intercom/native-supervisor-channel.ts +138 -60
  60. package/src/intercom/result-intercom.ts +7 -0
  61. package/src/intercom/supervisor-ui.ts +243 -0
  62. package/src/profiles/profiles.ts +5 -6
  63. package/src/runs/background/active-async-capacity.ts +103 -18
  64. package/src/runs/background/async-execution.ts +417 -133
  65. package/src/runs/background/async-job-tracker.ts +95 -15
  66. package/src/runs/background/async-resume.ts +60 -28
  67. package/src/runs/background/async-retention.ts +20 -3
  68. package/src/runs/background/async-status-snapshot.ts +23 -261
  69. package/src/runs/background/async-status.ts +204 -14
  70. package/src/runs/background/auto-drain.ts +1 -1
  71. package/src/runs/background/chain-append.ts +8 -3
  72. package/src/runs/background/chain-root-attachment.ts +74 -8
  73. package/src/runs/background/control-channel.ts +4 -205
  74. package/src/runs/background/fleet-view.ts +38 -22
  75. package/src/runs/background/inspect-rpc.ts +8 -8
  76. package/src/runs/background/notify.ts +238 -12
  77. package/src/runs/background/process-terminal.ts +16 -0
  78. package/src/runs/background/result-delivery-ownership.ts +45 -0
  79. package/src/runs/background/result-files.ts +28 -14
  80. package/src/runs/background/result-watcher.ts +39 -16
  81. package/src/runs/background/resume-guidance.ts +2 -2
  82. package/src/runs/background/retained-children.ts +1 -1
  83. package/src/runs/background/run-child-session.ts +613 -0
  84. package/src/runs/background/run-status.ts +84 -17
  85. package/src/runs/background/runner-aliases.ts +125 -0
  86. package/src/runs/background/runner-child-sessions.ts +31 -0
  87. package/src/runs/background/scheduled-runs.ts +174 -18
  88. package/src/runs/background/stale-run-reconciler.ts +10 -4
  89. package/src/runs/background/steering.ts +8 -15
  90. package/src/runs/background/subagent-runner.ts +718 -1161
  91. package/src/runs/background/subagent-wait.ts +86 -31
  92. package/src/runs/background/terminal-run-index.ts +1 -1
  93. package/src/runs/background/wait-completions.ts +43 -2
  94. package/src/runs/background/wait-config.ts +23 -9
  95. package/src/runs/background/wait-tool.ts +26 -19
  96. package/src/runs/foreground/async-steering-action.ts +3 -19
  97. package/src/runs/foreground/execution.ts +489 -499
  98. package/src/runs/foreground/foreground-control.ts +13 -0
  99. package/src/runs/foreground/foreground-history.ts +23 -1
  100. package/src/runs/foreground/subagent-executor.ts +1223 -402
  101. package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
  102. package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
  103. package/src/runs/shared/abort-recovery.ts +119 -0
  104. package/src/runs/shared/acceptance.ts +138 -36
  105. package/src/runs/shared/async-status-projection.ts +565 -0
  106. package/src/runs/shared/background-process-options.ts +9 -0
  107. package/src/runs/shared/capability-ceiling.ts +2 -2
  108. package/src/runs/shared/child-hooks.ts +25 -0
  109. package/src/runs/shared/child-identity.ts +32 -6
  110. package/src/runs/shared/child-launch-plan.ts +151 -0
  111. package/src/runs/shared/child-launch.ts +364 -0
  112. package/src/runs/shared/child-lifecycle.ts +25 -0
  113. package/src/runs/shared/child-runtime-config.ts +126 -0
  114. package/src/runs/shared/child-session.ts +366 -0
  115. package/src/runs/shared/child-tool-plan.ts +632 -0
  116. package/src/runs/shared/claude-code-adapter.ts +133 -0
  117. package/src/runs/shared/codex-exec-adapter.ts +129 -0
  118. package/src/runs/shared/completion-evidence.ts +89 -0
  119. package/src/runs/shared/completion-guard.ts +6 -5
  120. package/src/runs/shared/cursor-agent-adapter.ts +114 -0
  121. package/src/runs/shared/dynamic-fanout.ts +3 -3
  122. package/src/runs/shared/external-cli-contract.ts +167 -0
  123. package/src/runs/shared/external-cli-preflight.ts +138 -0
  124. package/src/runs/shared/external-cli-runner.ts +348 -55
  125. package/src/runs/shared/fast-mode-extension.ts +5 -5
  126. package/src/runs/shared/host-step-status.ts +231 -0
  127. package/src/runs/shared/lane-metadata.ts +126 -0
  128. package/src/runs/shared/launch-cwd.ts +16 -0
  129. package/src/runs/shared/long-running-guard.ts +2 -1
  130. package/src/runs/shared/mcp-config-sources.ts +422 -0
  131. package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
  132. package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
  133. package/src/runs/shared/model-exclusions.ts +139 -9
  134. package/src/runs/shared/model-fallback.ts +146 -14
  135. package/src/runs/shared/mutation-evidence.ts +57 -3
  136. package/src/runs/shared/nested-events.ts +99 -77
  137. package/src/runs/shared/nested-path.ts +0 -14
  138. package/src/runs/shared/nested-render.ts +9 -5
  139. package/src/runs/shared/orca-progress-tabs.ts +12 -7
  140. package/src/runs/shared/parallel-handoff.ts +423 -7
  141. package/src/runs/shared/parallel-utils.ts +20 -7
  142. package/src/runs/shared/permissions.ts +1 -14
  143. package/src/runs/shared/pi-spawn.ts +69 -35
  144. package/src/runs/shared/process-signal.ts +16 -0
  145. package/src/runs/shared/run-fanout-budget.ts +0 -13
  146. package/src/runs/shared/run-history.ts +21 -1
  147. package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
  148. package/src/runs/shared/sandbox-profile-guard.ts +85 -0
  149. package/src/runs/shared/sandbox-startup-diagnostics.ts +54 -0
  150. package/src/runs/shared/single-output.ts +89 -22
  151. package/src/runs/shared/structured-output.ts +49 -9
  152. package/src/runs/shared/subagent-control.ts +6 -2
  153. package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
  154. package/src/runs/shared/task-intent.ts +21 -7
  155. package/src/runs/shared/tool-availability.ts +18 -62
  156. package/src/runs/shared/tool-budget.ts +0 -14
  157. package/src/runs/shared/tool-timeout.ts +1 -1
  158. package/src/runs/shared/workflow-graph.ts +16 -0
  159. package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
  160. package/src/runs/shared/worktree.ts +571 -62
  161. package/src/shared/atomic-json.ts +3 -1
  162. package/src/shared/child-session-name.ts +46 -0
  163. package/src/shared/extension-context.ts +24 -0
  164. package/src/shared/fork-context.ts +21 -12
  165. package/src/shared/fork-session-cwd.ts +27 -0
  166. package/src/shared/formatters.ts +18 -3
  167. package/src/shared/jsonl-writer.ts +11 -0
  168. package/src/shared/launch-contract.ts +11 -1
  169. package/src/shared/pruned-fork.ts +450 -0
  170. package/src/shared/sandbox-profile.ts +23 -0
  171. package/src/shared/session-file-trust.ts +19 -0
  172. package/src/shared/session-tokens.ts +14 -3
  173. package/src/shared/settings.ts +19 -105
  174. package/src/shared/shortcuts.ts +17 -0
  175. package/src/shared/thinking-ceiling.ts +0 -6
  176. package/src/shared/types.ts +545 -70
  177. package/src/shared/utils.ts +60 -93
  178. package/src/shared/workflow-child-permit.ts +207 -0
  179. package/src/slash/delegation-adapters.ts +1 -9
  180. package/src/slash/delegation-request.ts +0 -4
  181. package/src/slash/prompt-template-bridge.ts +37 -1
  182. package/src/slash/slash-bridge.ts +1 -2
  183. package/src/slash/slash-commands.ts +383 -116
  184. package/src/slash/slash-live-state.ts +22 -11
  185. package/src/slash/subagents-admin.ts +29 -12
  186. package/src/tui/fleet-native-transcript.ts +4 -0
  187. package/src/tui/fleet-status.ts +217 -82
  188. package/src/tui/fleet-transcript.ts +11 -5
  189. package/src/tui/fleet.ts +54 -28
  190. package/src/tui/render-helpers.ts +31 -0
  191. package/src/tui/render.ts +1429 -163
  192. package/src/watchdog/change-signature.ts +40 -1
  193. package/src/watchdog/child-status.ts +54 -34
  194. package/src/watchdog/diff-tool.ts +77 -0
  195. package/src/watchdog/emission-guard.ts +5 -3
  196. package/src/watchdog/guidance.ts +20 -0
  197. package/src/watchdog/register-child.ts +28 -25
  198. package/src/watchdog/register-main.ts +10 -9
  199. package/src/watchdog/render.ts +4 -5
  200. package/src/watchdog/review.ts +15 -4
  201. package/src/watchdog/rules.ts +70 -0
  202. package/src/watchdog/runtime.ts +75 -92
  203. package/src/watchdog/scope.ts +0 -11
  204. package/src/watchdog/settings.ts +48 -104
  205. package/src/watchdog/turn-delta.ts +1 -1
  206. package/src/watchdog/types.ts +18 -32
  207. package/src/watchdog/warning-format.ts +0 -1
  208. package/src/workflows/chat-progress.ts +7 -3
  209. package/src/workflows/host-command.ts +235 -0
  210. package/src/workflows/scripted-workflow.ts +988 -59
  211. package/src/workflows/workflow-checklist.ts +439 -0
  212. package/src/workflows/workflow-child-summary.ts +121 -0
  213. package/src/workflows/workflow-preflight.ts +297 -0
  214. package/src/workflows/workflow-receipt.ts +232 -6
  215. package/src/workflows/workflow-resources.ts +150 -0
  216. package/src/workflows/workflow-settlement.ts +246 -0
  217. package/src/runs/shared/child-protocol.ts +0 -401
  218. package/src/runs/shared/pi-args.ts +0 -935
  219. package/src/runs/shared/subagent-startup-retry.ts +0 -116
  220. package/src/runs/shared/turn-budget.ts +0 -98
  221. package/src/shared/post-exit-stdio-guard.ts +0 -85
@@ -1,6 +1,7 @@
1
1
  import * as fs from "node:fs";
2
- import { resultFilePath } from "./result-files.ts";
3
- import type { AcceptanceLedger, AsyncStatus, CostSummary, ModelAttempt } from "../../shared/types.ts";
2
+ import * as path from "node:path";
3
+ import { resultFilePath, resultPayloadPathForSessionRun } from "./result-files.ts";
4
+ import type { AcceptanceLedger, ArtifactPaths, AsyncStatus, CostSummary, EffectsProjection, ExecutionProjection, ModelAttempt, Usage } from "../../shared/types.ts";
4
5
  import { readStatus } from "../../shared/utils.ts";
5
6
 
6
7
  export interface ImportedAsyncRoot {
@@ -12,6 +13,8 @@ export interface ImportedAsyncRoot {
12
13
 
13
14
  export interface ImportedAsyncRootResult {
14
15
  agent: string;
16
+ /** Human-readable display name for the child session, when derived at launch. */
17
+ sessionName?: string;
15
18
  output: string;
16
19
  success: boolean;
17
20
  exitCode: number;
@@ -23,12 +26,19 @@ export interface ImportedAsyncRootResult {
23
26
  modelAttempts?: ModelAttempt[];
24
27
  contextOverflow?: boolean;
25
28
  totalCost?: CostSummary;
29
+ usage?: Usage;
26
30
  structuredOutput?: unknown;
27
31
  structuredOutputPath?: string;
28
32
  structuredOutputSchemaPath?: string;
29
33
  acceptance?: AcceptanceLedger;
34
+ artifactPaths?: ArtifactPaths;
35
+ outputSaveError?: string;
36
+ transcriptPath?: string;
37
+ transcriptError?: string;
30
38
  timedOut?: boolean;
31
39
  stopped?: boolean;
40
+ execution?: ExecutionProjection;
41
+ effects?: EffectsProjection;
32
42
  }
33
43
 
34
44
  interface AsyncResultFile {
@@ -40,11 +50,14 @@ interface AsyncResultFile {
40
50
  stopped?: boolean;
41
51
  results?: Array<{
42
52
  agent?: string;
53
+ sessionName?: string;
43
54
  output?: string;
44
55
  error?: string;
45
56
  success?: boolean;
46
57
  timedOut?: boolean;
47
58
  stopped?: boolean;
59
+ execution?: ExecutionProjection;
60
+ effects?: EffectsProjection;
48
61
  sessionFile?: string;
49
62
  intercomTarget?: string;
50
63
  model?: string;
@@ -52,15 +65,37 @@ interface AsyncResultFile {
52
65
  modelAttempts?: ModelAttempt[];
53
66
  contextOverflow?: boolean;
54
67
  totalCost?: CostSummary;
68
+ usage?: Usage;
55
69
  structuredOutput?: unknown;
56
70
  structuredOutputPath?: string;
57
71
  structuredOutputSchemaPath?: string;
58
72
  acceptance?: AcceptanceLedger;
73
+ artifactPaths?: ArtifactPaths;
74
+ outputSaveError?: string;
75
+ transcriptPath?: string;
76
+ transcriptError?: string;
59
77
  }>;
60
78
  }
61
79
 
62
- const TERMINAL_STATES = new Set(["complete", "failed", "paused", "stopped"]);
63
- const TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "paused", "stopped"]);
80
+ const TERMINAL_STATES = new Set(["complete", "failed", "partial", "paused", "stopped"]);
81
+ const TERMINAL_STEP_STATUSES = new Set(["complete", "completed", "failed", "partial", "paused", "stopped"]);
82
+
83
+ function usageFromAttempts(attempts: ModelAttempt[] | undefined): Usage | undefined {
84
+ if (!attempts?.length) return undefined;
85
+ const usage: Usage = { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, cost: 0, turns: 0 };
86
+ for (const attempt of attempts) {
87
+ if (!attempt.usage) continue;
88
+ usage.input += attempt.usage.input;
89
+ usage.output += attempt.usage.output;
90
+ usage.cacheRead += attempt.usage.cacheRead;
91
+ usage.cacheWrite += attempt.usage.cacheWrite;
92
+ usage.cost += attempt.usage.cost;
93
+ usage.turns += attempt.usage.turns;
94
+ }
95
+ return usage.input !== 0 || usage.output !== 0 || usage.cacheRead !== 0 || usage.cacheWrite !== 0 || usage.cost !== 0 || usage.turns !== 0
96
+ ? usage
97
+ : undefined;
98
+ }
64
99
 
65
100
  function readResultFile(resultPath: string): AsyncResultFile | undefined {
66
101
  try {
@@ -73,6 +108,13 @@ function readResultFile(resultPath: string): AsyncResultFile | undefined {
73
108
  }
74
109
  }
75
110
 
111
+ function readImportedResultFile(root: ImportedAsyncRoot, status: AsyncStatus | null): AsyncResultFile | undefined {
112
+ const direct = readResultFile(root.resultPath);
113
+ if (direct || !status?.sessionId) return direct;
114
+ const indexedPath = resultPayloadPathForSessionRun(path.dirname(root.resultPath), status.sessionId, root.runId);
115
+ return indexedPath ? readResultFile(indexedPath) : undefined;
116
+ }
117
+
76
118
  function selectedStatusStep(status: AsyncStatus | null, index: number): NonNullable<AsyncStatus["steps"]>[number] | undefined {
77
119
  return status?.steps?.[index];
78
120
  }
@@ -84,12 +126,12 @@ function isTerminalStatus(status: AsyncStatus | null, index: number): boolean {
84
126
  return TERMINAL_STATES.has(status.state);
85
127
  }
86
128
 
87
- function resultState(result: AsyncResultFile | undefined, child: NonNullable<AsyncResultFile["results"]>[number] | undefined): "complete" | "failed" | "paused" | "stopped" | undefined {
129
+ function resultState(result: AsyncResultFile | undefined, child: NonNullable<AsyncResultFile["results"]>[number] | undefined): "complete" | "failed" | "partial" | "paused" | "stopped" | undefined {
88
130
  if (!result) return undefined;
89
131
  if (child?.stopped === true) return "stopped";
90
132
  if (child?.success === true) return "complete";
91
- if (child?.success === false) return result.state === "stopped" ? "stopped" : result.state === "paused" ? "paused" : "failed";
92
- if (result.state === "complete" || result.state === "failed" || result.state === "paused" || result.state === "stopped") return result.state;
133
+ if (child?.success === false) return result.state === "stopped" ? "stopped" : result.state === "paused" ? "paused" : result.state === "partial" ? "partial" : "failed";
134
+ if (result.state === "complete" || result.state === "failed" || result.state === "partial" || result.state === "paused" || result.state === "stopped") return result.state;
93
135
  if (result.success === true) return "complete";
94
136
  if (result.success === false) return "failed";
95
137
  return undefined;
@@ -100,6 +142,11 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
100
142
  const timedOut = step?.timedOut === true || status.timedOut === true;
101
143
  const stopped = step?.stopped === true || status.stopped === true || status.state === "stopped";
102
144
  const message = step?.error ?? status.error ?? (stopped ? "Subagent stopped by user." : `Attached async root ${root.runId} ended without a result file at ${root.resultPath}.`);
145
+ const partialStatus = status.state === "partial" || step?.status === "partial";
146
+ const execution = step?.execution ?? (partialStatus
147
+ ? { status: "partial" as const, success: false, exitCode: 1, error: message }
148
+ : undefined);
149
+ const usage = usageFromAttempts(step?.modelAttempts);
103
150
  return {
104
151
  agent,
105
152
  output: message,
@@ -108,21 +155,27 @@ function outputFromTerminalStatus(root: ImportedAsyncRoot, status: AsyncStatus,
108
155
  error: message,
109
156
  ...(timedOut ? { timedOut: true } : {}),
110
157
  ...(stopped ? { stopped: true } : {}),
158
+ ...(step?.sessionName ? { sessionName: step.sessionName } : {}),
111
159
  ...(step?.sessionFile ?? status.sessionFile ? { sessionFile: step?.sessionFile ?? status.sessionFile } : {}),
112
160
  ...(step?.model ? { model: step.model } : {}),
113
161
  ...(step?.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
114
162
  ...(step?.modelAttempts ? { modelAttempts: step.modelAttempts } : {}),
115
163
  ...(step?.contextOverflow ? { contextOverflow: true } : {}),
116
164
  ...(step?.totalCost ? { totalCost: step.totalCost } : {}),
165
+ ...(usage ? { usage } : {}),
117
166
  ...(step?.structuredOutput !== undefined ? { structuredOutput: step.structuredOutput } : {}),
118
167
  ...(step?.structuredOutputPath ? { structuredOutputPath: step.structuredOutputPath } : {}),
119
168
  ...(step?.structuredOutputSchemaPath ? { structuredOutputSchemaPath: step.structuredOutputSchemaPath } : {}),
120
169
  ...(step?.acceptance ? { acceptance: step.acceptance } : {}),
170
+ ...(execution ? { execution } : {}),
171
+ ...(step?.effects ? { effects: step.effects } : {}),
172
+ ...(step?.transcriptPath ? { transcriptPath: step.transcriptPath } : {}),
121
173
  };
122
174
  }
123
175
 
124
176
  function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null, message: string): ImportedAsyncRootResult {
125
177
  const step = selectedStatusStep(status, root.index);
178
+ const usage = usageFromAttempts(step?.modelAttempts);
126
179
  return {
127
180
  agent: step?.agent ?? status?.steps?.[root.index]?.agent ?? "subagent",
128
181
  output: message,
@@ -130,12 +183,15 @@ function outputFromTimeout(root: ImportedAsyncRoot, status: AsyncStatus | null,
130
183
  exitCode: 1,
131
184
  error: message,
132
185
  timedOut: true,
186
+ ...(step?.sessionName ? { sessionName: step.sessionName } : {}),
133
187
  ...(step?.sessionFile ?? status?.sessionFile ? { sessionFile: step?.sessionFile ?? status?.sessionFile } : {}),
134
188
  ...(step?.model ? { model: step.model } : {}),
135
189
  ...(step?.attemptedModels ? { attemptedModels: step.attemptedModels } : {}),
136
190
  ...(step?.modelAttempts ? { modelAttempts: step.modelAttempts } : {}),
137
191
  ...(step?.contextOverflow ? { contextOverflow: true } : {}),
138
192
  ...(step?.totalCost ? { totalCost: step.totalCost } : {}),
193
+ ...(usage ? { usage } : {}),
194
+ ...(step?.transcriptPath ? { transcriptPath: step.transcriptPath } : {}),
139
195
  };
140
196
  }
141
197
 
@@ -149,6 +205,8 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
149
205
  const stopped = child?.stopped === true || step?.stopped === true || result.stopped === true || status?.stopped === true || state === "stopped";
150
206
  const success = state === "complete" && !timedOut && !stopped;
151
207
  const error = child?.error ?? (success ? undefined : stopped ? "Subagent stopped by user." : result.error ?? result.summary ?? status?.error ?? `Attached async root ${root.runId} did not complete successfully.`);
208
+ const execution = state ? { status: state === "complete" ? "completed" as const : state, success, exitCode: success ? 0 : 1, ...(error ? { error } : {}) } : undefined;
209
+ const usage = child?.usage ?? usageFromAttempts(step?.modelAttempts);
152
210
  return {
153
211
  agent,
154
212
  output: success ? output : (output || error || ""),
@@ -157,6 +215,7 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
157
215
  ...(error ? { error } : {}),
158
216
  ...(timedOut ? { timedOut: true } : {}),
159
217
  ...(stopped ? { stopped: true } : {}),
218
+ ...(child?.sessionName ?? step?.sessionName ? { sessionName: child?.sessionName ?? step?.sessionName } : {}),
160
219
  ...(child?.sessionFile ?? step?.sessionFile ?? status?.sessionFile ? { sessionFile: child?.sessionFile ?? step?.sessionFile ?? status?.sessionFile } : {}),
161
220
  ...(child?.intercomTarget ? { intercomTarget: child.intercomTarget } : {}),
162
221
  ...(child?.model ?? step?.model ? { model: child?.model ?? step?.model } : {}),
@@ -164,10 +223,17 @@ function buildImportedResult(root: ImportedAsyncRoot, status: AsyncStatus | null
164
223
  ...(child?.modelAttempts ?? step?.modelAttempts ? { modelAttempts: child?.modelAttempts ?? step?.modelAttempts } : {}),
165
224
  ...(child?.contextOverflow || step?.contextOverflow ? { contextOverflow: true } : {}),
166
225
  ...(child?.totalCost ?? step?.totalCost ? { totalCost: child?.totalCost ?? step?.totalCost } : {}),
226
+ ...(usage ? { usage } : {}),
167
227
  ...(child?.structuredOutput !== undefined ? { structuredOutput: child.structuredOutput } : step?.structuredOutput !== undefined ? { structuredOutput: step.structuredOutput } : {}),
168
228
  ...(child?.structuredOutputPath ?? step?.structuredOutputPath ? { structuredOutputPath: child?.structuredOutputPath ?? step?.structuredOutputPath } : {}),
169
229
  ...(child?.structuredOutputSchemaPath ?? step?.structuredOutputSchemaPath ? { structuredOutputSchemaPath: child?.structuredOutputSchemaPath ?? step?.structuredOutputSchemaPath } : {}),
170
230
  ...(child?.acceptance ?? step?.acceptance ? { acceptance: child?.acceptance ?? step?.acceptance } : {}),
231
+ ...(child?.artifactPaths ? { artifactPaths: child.artifactPaths } : {}),
232
+ ...(child?.outputSaveError ? { outputSaveError: child.outputSaveError } : {}),
233
+ ...(child?.transcriptPath ?? step?.transcriptPath ? { transcriptPath: child?.transcriptPath ?? step?.transcriptPath } : {}),
234
+ ...(child?.transcriptError ? { transcriptError: child.transcriptError } : {}),
235
+ ...(execution ? { execution } : {}),
236
+ ...(child?.effects ?? step?.effects ? { effects: child?.effects ?? step?.effects } : {}),
171
237
  };
172
238
  }
173
239
 
@@ -182,7 +248,7 @@ export async function waitForImportedAsyncRoot(
182
248
  for (;;) {
183
249
  const status = readStatus(root.asyncDir);
184
250
  if (options.shouldAbort?.()) return outputFromTimeout(root, status, options.timeoutMessage ?? "Subagent timed out.");
185
- const result = readResultFile(root.resultPath);
251
+ const result = readImportedResultFile(root, status);
186
252
  if (result) return buildImportedResult(root, status, result);
187
253
  if (isTerminalStatus(status, root.index)) {
188
254
  terminalSince ??= now();
@@ -1,8 +1,9 @@
1
1
  /**
2
2
  * Cross-OS control channel for async subagent runs.
3
3
  *
4
- * Background runs are detached OS processes. The original control path delivered
5
- * an interrupt with `process.kill(pid, SIGUSR2|SIGBREAK)`, but Windows cannot
4
+ * Background runs use a detached runner process. Unix detaches it from the parent process.
5
+ * The original control path delivered an interrupt with
6
+ * `process.kill(pid, SIGUSR2|SIGBREAK)`, but Windows cannot
6
7
  * deliver those signals cross-process via `process.kill` and throws `ENOSYS`,
7
8
  * which left async runs uninterruptible (no stop, no live steer) on Windows.
8
9
  *
@@ -73,33 +74,10 @@ export interface SteerRequest {
73
74
  source?: string;
74
75
  }
75
76
 
76
- export interface SteerCapability {
77
- type: "steer-capability";
78
- protocolVersion: 1;
79
- index: number;
80
- pid: number;
81
- readyAt: number;
82
- supported: boolean;
83
- }
84
-
85
- export interface SteerAck {
86
- type: "steer-ack";
87
- protocolVersion: 1;
88
- requestId: string;
89
- index: number;
90
- ts: number;
91
- state: "delivered" | "queued" | "failed";
92
- deliveryStatus?: SteerDeliveryStatus;
93
- message: string;
94
- }
95
-
96
77
  const STEER_REQUESTS_DIR = "steer-requests";
97
78
  const STOP_REQUESTS_DIR = "stop-requests";
98
79
  const REVIVAL_BRIEFS_DIR = "revival-briefs";
99
80
  export const MAX_STEER_QUEUE_SIZE = 20;
100
- const STEER_TARGETS_DIR = "steer-targets";
101
- const STEER_CAPABILITIES_DIR = "steer-capabilities";
102
- const STEER_ACKS_DIR = "steer-acks";
103
81
  const STEER_INBOX_CLOSED_FILE = "steer-inbox-closed.json";
104
82
  const MAX_STEER_MESSAGE_BYTES = 128 * 1024;
105
83
  const MAX_STEER_REQUEST_ID_LENGTH = 256;
@@ -142,35 +120,6 @@ export function closeSteerInbox(asyncDir: string, state: string, write: (filePat
142
120
  write(steerInboxClosedPath(asyncDir), { version: 1, closedAt: Date.now(), state });
143
121
  }
144
122
 
145
- /** Per-child inbox consumed by the child prompt runtime inside the Pi process. */
146
- export function stepSteerInboxDir(asyncDir: string, index: number): string {
147
- assertChildIndex(index);
148
- return path.join(controlInboxDir(asyncDir), STEER_TARGETS_DIR, String(index));
149
- }
150
-
151
- export function steerCapabilitiesDir(asyncDir: string): string {
152
- return path.join(controlInboxDir(asyncDir), STEER_CAPABILITIES_DIR);
153
- }
154
-
155
- export function steerCapabilityPath(asyncDir: string, index: number): string {
156
- assertChildIndex(index);
157
- return path.join(steerCapabilitiesDir(asyncDir), `${index}.json`);
158
- }
159
-
160
- export function steerAcksDir(asyncDir: string, index: number): string {
161
- assertChildIndex(index);
162
- return path.join(controlInboxDir(asyncDir), STEER_ACKS_DIR, String(index));
163
- }
164
-
165
- function steerAckFileName(requestId: string): string {
166
- return `${Buffer.from(requestId).toString("base64url")}.json`;
167
- }
168
-
169
- export function steerAckPathFromDir(dir: string, requestId: string): string {
170
- if (!/^[^\s]+$/.test(requestId) || requestId.length > 256) throw new Error("steer acknowledgment requestId is invalid.");
171
- return path.join(dir, steerAckFileName(requestId));
172
- }
173
-
174
123
  function assertChildIndex(index: number): void {
175
124
  if (!Number.isInteger(index) || index < 0 || index > 1_000_000) throw new Error("child index must be a non-negative integer.");
176
125
  }
@@ -228,45 +177,6 @@ export function writeSteerRequestToExistingDir(dir: string, request: SteerReques
228
177
  return requestPath;
229
178
  }
230
179
 
231
- export function writeSteerCapabilityAt(filePath: string, capability: Omit<SteerCapability, "type" | "protocolVersion">): string {
232
- assertChildIndex(capability.index);
233
- if (!Number.isInteger(capability.pid) || capability.pid <= 0) throw new Error("steer capability pid must be a positive integer.");
234
- if (!Number.isFinite(capability.readyAt) || capability.readyAt <= 0) throw new Error("steer capability readyAt must be a finite timestamp.");
235
- const record: SteerCapability = { type: "steer-capability", protocolVersion: 1, ...capability };
236
- writeAtomicJson(filePath, record);
237
- return filePath;
238
- }
239
-
240
- export function writeSteerCapability(asyncDir: string, capability: Omit<SteerCapability, "type" | "protocolVersion">): string {
241
- return writeSteerCapabilityAt(steerCapabilityPath(asyncDir, capability.index), capability);
242
- }
243
-
244
- function steerAckWritePath(filePath: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
245
- const parsed = path.parse(filePath);
246
- const stateOrder = ack.state === "queued" ? "0" : ack.state === "delivered" ? "1" : "2";
247
- const timestamp = String(Math.trunc(ack.ts)).padStart(13, "0");
248
- for (let suffix = 0; suffix < 1_000; suffix += 1) {
249
- const candidate = path.join(parsed.dir, `${parsed.name}-${timestamp}-${stateOrder}-${ack.state}${suffix === 0 ? "" : `-${suffix}`}${parsed.ext}`);
250
- if (!fs.existsSync(candidate)) return candidate;
251
- }
252
- throw new Error("steer acknowledgment queue is full.");
253
- }
254
-
255
- export function writeSteerAckAt(filePath: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
256
- assertChildIndex(ack.index);
257
- if (!/^[^\s]+$/.test(ack.requestId) || ack.requestId.length > 256) throw new Error("steer acknowledgment requestId is invalid.");
258
- if (!Number.isFinite(ack.ts) || ack.ts <= 0) throw new Error("steer acknowledgment ts must be a finite timestamp.");
259
- if (!ack.message.trim() || ack.message.length > 1000) throw new Error("steer acknowledgment message is invalid.");
260
- const record: SteerAck = { type: "steer-ack", protocolVersion: 1, ...ack, message: ack.message.trim() };
261
- const ackPath = steerAckWritePath(filePath, ack);
262
- writeAtomicJson(ackPath, record);
263
- return ackPath;
264
- }
265
-
266
- export function writeSteerAck(asyncDir: string, ack: Omit<SteerAck, "type" | "protocolVersion">): string {
267
- return writeSteerAckAt(path.join(steerAcksDir(asyncDir, ack.index), steerAckFileName(ack.requestId)), ack);
268
- }
269
-
270
180
  /**
271
181
  * Parent side: drop a portable interrupt request the runner's inbox watcher will
272
182
  * pick up regardless of OS. Written atomically (temp + rename), dir auto-created.
@@ -349,97 +259,6 @@ export function requestAsyncSteer(
349
259
  return requestPath;
350
260
  }
351
261
 
352
- export function enqueueStepSteer(asyncDir: string, index: number, request: SteerRequest): string {
353
- assertChildIndex(index);
354
- const { targetIndexes: _targetIndexes, ...singleTargetRequest } = request;
355
- return writeSteerRequestToDir(stepSteerInboxDir(asyncDir, index), { ...singleTargetRequest, targetIndex: index, type: "steer" });
356
- }
357
-
358
- function parseSteerCapability(raw: unknown): SteerCapability | undefined {
359
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
360
- const input = raw as Partial<SteerCapability>;
361
- if (input.type !== "steer-capability" || input.protocolVersion !== 1) return undefined;
362
- const { index, pid, readyAt, supported } = input;
363
- if (typeof index !== "number" || !Number.isInteger(index) || index < 0 || index > 1_000_000) return undefined;
364
- if (typeof pid !== "number" || typeof readyAt !== "number" || !Number.isInteger(pid) || pid <= 0 || !Number.isFinite(readyAt) || readyAt <= 0 || typeof supported !== "boolean") return undefined;
365
- return { type: "steer-capability", protocolVersion: 1, index, pid, readyAt, supported };
366
- }
367
-
368
- function parseSteerAck(raw: unknown): SteerAck | undefined {
369
- if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
370
- const input = raw as Partial<SteerAck>;
371
- if (input.type !== "steer-ack" || input.protocolVersion !== 1 || typeof input.requestId !== "string" || !/^[^\s]+$/.test(input.requestId) || input.requestId.length > 256) return undefined;
372
- const { index, ts, state, message } = input;
373
- if (typeof index !== "number" || typeof ts !== "number" || !Number.isInteger(index) || index < 0 || index > 1_000_000 || !Number.isFinite(ts) || ts <= 0) return undefined;
374
- if (state !== "delivered" && state !== "queued" && state !== "failed") return undefined;
375
- if (input.deliveryStatus !== undefined && input.deliveryStatus !== "delivered" && input.deliveryStatus !== "queued") return undefined;
376
- if (typeof message !== "string" || !message.trim() || message.length > 1000) return undefined;
377
- return { type: "steer-ack", protocolVersion: 1, requestId: input.requestId, index, ts, state, ...(input.deliveryStatus ? { deliveryStatus: input.deliveryStatus } : {}), message: message.trim() };
378
- }
379
-
380
- export function readSteerCapability(asyncDir: string, index: number): SteerCapability | undefined {
381
- try {
382
- return parseSteerCapability(JSON.parse(fs.readFileSync(steerCapabilityPath(asyncDir, index), "utf-8")));
383
- } catch {
384
- return undefined;
385
- }
386
- }
387
-
388
- export function consumeSteerCapabilities(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync"> = fs): SteerCapability[] {
389
- const dir = steerCapabilitiesDir(asyncDir);
390
- if (!fsImpl.existsSync(dir)) return [];
391
- const capabilities: SteerCapability[] = [];
392
- for (const entry of fsImpl.readdirSync(dir).filter((name) => /^\d+\.json$/.test(name)).sort()) {
393
- try {
394
- const capability = parseSteerCapability(JSON.parse(fsImpl.readFileSync(path.join(dir, entry), "utf-8")));
395
- if (capability) capabilities.push(capability);
396
- } catch {
397
- // A partially written or malformed capability is ignored until a valid one arrives.
398
- }
399
- }
400
- return capabilities;
401
- }
402
-
403
- export function consumeSteerAckFromDir(
404
- dir: string,
405
- requestId: string,
406
- fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync" | "rmSync"> = fs,
407
- ): SteerAck | undefined {
408
- if (!fsImpl.existsSync(dir)) return undefined;
409
- let entries: string[];
410
- try { entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort(); } catch { return undefined; }
411
- for (const entry of entries) {
412
- const target = path.join(dir, entry);
413
- let ack: SteerAck | undefined;
414
- try { ack = parseSteerAck(JSON.parse(fsImpl.readFileSync(target, "utf-8"))); } catch { ack = undefined; }
415
- if (ack?.requestId !== requestId) continue;
416
- try { fsImpl.rmSync(target, { force: true }); } catch { return undefined; }
417
- return ack;
418
- }
419
- return undefined;
420
- }
421
-
422
- export function consumeSteerAcks(asyncDir: string, fsImpl: Pick<typeof fs, "existsSync" | "readdirSync" | "readFileSync" | "rmSync"> = fs): SteerAck[] {
423
- const root = path.join(controlInboxDir(asyncDir), STEER_ACKS_DIR);
424
- if (!fsImpl.existsSync(root)) return [];
425
- const acks: SteerAck[] = [];
426
- let indexNames: string[];
427
- try { indexNames = fsImpl.readdirSync(root).filter((name) => /^\d+$/.test(name)); } catch { return []; }
428
- for (const indexName of indexNames) {
429
- const dir = path.join(root, indexName);
430
- let entries: string[];
431
- try { entries = fsImpl.readdirSync(dir).filter((name) => name.endsWith(".json")).sort(); } catch { continue; }
432
- for (const entry of entries) {
433
- const target = path.join(dir, entry);
434
- let ack: SteerAck | undefined;
435
- try { ack = parseSteerAck(JSON.parse(fsImpl.readFileSync(target, "utf-8"))); } catch { ack = undefined; }
436
- try { fsImpl.rmSync(target, { force: true }); } catch { continue; }
437
- if (ack) acks.push(ack);
438
- }
439
- }
440
- return acks;
441
- }
442
-
443
262
  function parseSteerRequest(raw: unknown): SteerRequest | undefined {
444
263
  if (!raw || typeof raw !== "object" || Array.isArray(raw)) return undefined;
445
264
  const input = raw as Partial<SteerRequest>;
@@ -664,8 +483,6 @@ export function watchAsyncControlInbox(
664
483
  onTimeout?: () => void;
665
484
  onStop?: (request: StopRequest) => void;
666
485
  onSteer?: (request: SteerRequest) => void;
667
- onSteerCapability?: (capability: SteerCapability) => void;
668
- onSteerAck?: (ack: SteerAck) => void;
669
486
  pollIntervalMs?: number;
670
487
  safetyPollIntervalMs?: number;
671
488
  platform?: NodeJS.Platform;
@@ -690,8 +507,6 @@ export function watchAsyncControlInbox(
690
507
  if (consumeTimeoutRequest(asyncDir, fsImpl)) opts.onTimeout?.();
691
508
  if (consumeInterruptRequest(asyncDir, fsImpl)) opts.onInterrupt();
692
509
  for (const request of consumeSteerRequests(asyncDir, fsImpl)) opts.onSteer?.(request);
693
- for (const capability of consumeSteerCapabilities(asyncDir, fsImpl)) opts.onSteerCapability?.(capability);
694
- for (const ack of consumeSteerAcks(asyncDir, fsImpl)) opts.onSteerAck?.(ack);
695
510
  } catch {
696
511
  // Never let inbox errors crash the runner.
697
512
  }
@@ -717,32 +532,16 @@ export function watchAsyncControlInbox(
717
532
  const watchDir = (target: string, create = false): void => {
718
533
  if (disposed || watchedDirs.has(target)) return;
719
534
  if (create) fsImpl.mkdirSync(target, { recursive: true });
720
- const watcher = fsImpl.watch(resolveWatchPath(target, fsImpl.realpathSync.native), () => {
721
- watchExistingSteerAckDirs();
722
- check();
723
- });
535
+ const watcher = fsImpl.watch(resolveWatchPath(target, fsImpl.realpathSync.native), () => check());
724
536
  watcher.on?.("error", startPolling);
725
537
  watchers.push(watcher);
726
538
  watchedDirs.add(target);
727
539
  };
728
- const watchExistingSteerAckDirs = (): void => {
729
- const ackRoot = path.join(dir, STEER_ACKS_DIR);
730
- let entries: string[];
731
- try {
732
- entries = fsImpl.readdirSync(ackRoot).filter((name) => /^\d+$/.test(name));
733
- } catch {
734
- return;
735
- }
736
- for (const entry of entries) watchDir(path.join(ackRoot, entry));
737
- };
738
540
  try {
739
541
  if (shouldUseNativeFsWatch("runner-control-inbox", opts.platform)) {
740
542
  watchDir(dir);
741
543
  watchDir(stopRequestsDir(asyncDir), true);
742
544
  watchDir(steerRequestsDir(asyncDir), true);
743
- watchDir(steerCapabilitiesDir(asyncDir), true);
744
- watchDir(path.join(dir, STEER_ACKS_DIR), true);
745
- watchExistingSteerAckDirs();
746
545
  startSafetyPolling();
747
546
  } else {
748
547
  startPolling();