@xzzpig/pi-subagents 0.24.1 → 0.25.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 (263) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/bundle/agent-management.js +4 -4
  3. package/bundle/agents.js +3 -3
  4. package/bundle/child-tool-plan.js +2 -2
  5. package/bundle/chunk-34TUUBRN.js +1107 -0
  6. package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
  7. package/bundle/{chunk-ZWXU5SPQ.js → chunk-5YEOWNSD.js} +371 -135
  8. package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  9. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  10. package/bundle/{chunk-6BJUEES3.js → chunk-6MNRKUHY.js} +23 -12
  11. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  12. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  13. package/bundle/chunk-HXRB42AF.js +108 -0
  14. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  15. package/bundle/{chunk-SLNMBXLL.js → chunk-IJWITCC6.js} +411 -249
  16. package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
  17. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  18. package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
  19. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  20. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  21. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  22. package/bundle/{chunk-LMGQAJ3O.js → chunk-KCJFGKVK.js} +350 -123
  23. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  24. package/bundle/chunk-LYKG4FKH.js +523 -0
  25. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  26. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  27. package/bundle/{chunk-Y6H2G6KX.js → chunk-OSVXFWPG.js} +67 -30
  28. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  29. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  30. package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
  31. package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
  32. package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
  33. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  34. package/bundle/{chunk-TGLFTQWJ.js → chunk-YWXILP5N.js} +5 -4
  35. package/bundle/control-channel.js +2 -2
  36. package/bundle/index.js +1 -1
  37. package/bundle/intercom-bridge.js +2 -2
  38. package/bundle/preflight.js +12 -10
  39. package/bundle/project-panes.js +3 -3
  40. package/bundle/workflow-resources.js +1 -1
  41. package/docs/agents.md +27 -6
  42. package/docs/configuration.md +20 -8
  43. package/docs/extension-api.md +18 -1
  44. package/docs/models.md +6 -2
  45. package/docs/observability.md +2 -0
  46. package/docs/tool-reference.md +7 -1
  47. package/docs/workflows.md +30 -2
  48. package/node_modules/@xzzpig/pi-components/CHANGELOG.md +12 -0
  49. package/node_modules/@xzzpig/pi-components/README.md +94 -0
  50. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.d.ts +186 -0
  51. package/node_modules/@xzzpig/pi-components/dist/src/transcript-presenter.js +693 -0
  52. package/node_modules/@xzzpig/pi-components/package.json +5 -1
  53. package/package.json +4 -4
  54. package/skills/pi-subagents/SKILL.md +15 -6
  55. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  56. package/src/agents/agent-management.d.ts +1 -0
  57. package/src/agents/agent-management.js +46 -18
  58. package/src/agents/agent-memory.d.ts +1 -4
  59. package/src/agents/agent-memory.js +1 -4
  60. package/src/agents/agent-serializer.d.ts +2 -0
  61. package/src/agents/agent-serializer.js +1 -1
  62. package/src/agents/agents.d.ts +2 -3
  63. package/src/agents/agents.js +46 -20
  64. package/src/agents/frontmatter.js +1 -8
  65. package/src/agents/global-npm-root.d.ts +1 -0
  66. package/src/agents/global-npm-root.js +11 -3
  67. package/src/agents/skills.d.ts +0 -3
  68. package/src/agents/skills.js +0 -3
  69. package/src/api/preflight.d.ts +3 -1
  70. package/src/api/preflight.js +2 -0
  71. package/src/extension/config.d.ts +1 -0
  72. package/src/extension/config.js +13 -1
  73. package/src/extension/herdr-pi-bridge.js +10 -2
  74. package/src/extension/index.d.ts +0 -13
  75. package/src/extension/index.js +51 -37
  76. package/src/extension/public-execution.d.ts +1 -0
  77. package/src/extension/public-execution.js +4 -0
  78. package/src/extension/reply-workflow-script.js +24 -4
  79. package/src/extension/schemas.d.ts +12 -3
  80. package/src/extension/schemas.js +7 -3
  81. package/src/extension/session-switch.d.ts +25 -0
  82. package/src/extension/session-switch.js +138 -0
  83. package/src/extension/subagent-guide.d.ts +1 -1
  84. package/src/extension/subagent-guide.js +1 -1
  85. package/src/extension/subagent-launch-tool.d.ts +25 -0
  86. package/src/extension/subagent-launch-tool.js +48 -0
  87. package/src/extension/tool-activation.js +55 -15
  88. package/src/extension/tool-description.d.ts +1 -1
  89. package/src/extension/tool-description.js +14 -8
  90. package/src/inspectors/herdr/actions.d.ts +0 -1
  91. package/src/inspectors/herdr/actions.js +0 -1
  92. package/src/inspectors/session-roots-codec.d.ts +0 -1
  93. package/src/inspectors/session-roots-codec.js +0 -1
  94. package/src/inspectors/tmux/actions.d.ts +0 -1
  95. package/src/inspectors/tmux/actions.js +0 -1
  96. package/src/integrations/herdr-status.js +3 -8
  97. package/src/intercom/native-supervisor-channel.js +65 -9
  98. package/src/runs/background/async-execution.d.ts +7 -10
  99. package/src/runs/background/async-execution.js +66 -29
  100. package/src/runs/background/async-job-tracker.js +12 -0
  101. package/src/runs/background/async-resume.d.ts +2 -1
  102. package/src/runs/background/async-resume.js +114 -40
  103. package/src/runs/background/async-retention.d.ts +0 -2
  104. package/src/runs/background/async-retention.js +17 -6
  105. package/src/runs/background/async-status.d.ts +2 -0
  106. package/src/runs/background/async-status.js +4 -0
  107. package/src/runs/background/auto-drain.js +2 -1
  108. package/src/runs/background/boot-id.d.ts +1 -3
  109. package/src/runs/background/boot-id.js +1 -3
  110. package/src/runs/background/completion-batcher.d.ts +3 -4
  111. package/src/runs/background/completion-batcher.js +2 -3
  112. package/src/runs/background/control-channel.d.ts +0 -6
  113. package/src/runs/background/control-channel.js +0 -6
  114. package/src/runs/background/fleet-view.js +2 -3
  115. package/src/runs/background/notify.d.ts +0 -2
  116. package/src/runs/background/notify.js +0 -2
  117. package/src/runs/background/result-watcher.d.ts +1 -0
  118. package/src/runs/background/result-watcher.js +59 -29
  119. package/src/runs/background/resume-guidance.js +4 -2
  120. package/src/runs/background/retained-children.js +2 -1
  121. package/src/runs/background/run-child-session.d.ts +2 -3
  122. package/src/runs/background/run-child-session.js +5 -8
  123. package/src/runs/background/run-status.js +9 -7
  124. package/src/runs/background/runner-aliases.js +15 -0
  125. package/src/runs/background/scheduled-runs.d.ts +3 -1
  126. package/src/runs/background/scheduled-runs.js +13 -16
  127. package/src/runs/background/steering.d.ts +2 -11
  128. package/src/runs/background/steering.js +11 -6
  129. package/src/runs/background/subagent-runner.d.ts +2 -6
  130. package/src/runs/background/subagent-runner.js +88 -70
  131. package/src/runs/background/subagent-wait.js +12 -15
  132. package/src/runs/background/wait-config.d.ts +2 -0
  133. package/src/runs/background/wait-config.js +17 -3
  134. package/src/runs/background/wait-subscriptions.js +124 -12
  135. package/src/runs/background/wait-tool.js +4 -2
  136. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  137. package/src/runs/background/workflow-terminal-proof.js +0 -1
  138. package/src/runs/foreground/async-steering-action.js +24 -9
  139. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  140. package/src/runs/foreground/async-stop-action.js +9 -1
  141. package/src/runs/foreground/execution.d.ts +0 -3
  142. package/src/runs/foreground/execution.js +56 -24
  143. package/src/runs/foreground/prompt-audit.js +1 -0
  144. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  145. package/src/runs/foreground/subagent-executor.js +164 -49
  146. package/src/runs/shared/acceptance.js +69 -26
  147. package/src/runs/shared/async-status-projection.d.ts +2 -0
  148. package/src/runs/shared/async-status-projection.js +10 -0
  149. package/src/runs/shared/child-commands.js +15 -2
  150. package/src/runs/shared/child-hooks.d.ts +1 -7
  151. package/src/runs/shared/child-hooks.js +13 -5
  152. package/src/runs/shared/child-launch.js +6 -2
  153. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  154. package/src/runs/shared/child-session.d.ts +6 -5
  155. package/src/runs/shared/child-session.js +85 -38
  156. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  157. package/src/runs/shared/child-tool-plan.js +0 -1
  158. package/src/runs/shared/claude-code-adapter.js +11 -0
  159. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  160. package/src/runs/shared/external-cli-contract.js +18 -13
  161. package/src/runs/shared/external-cli-runner.js +26 -6
  162. package/src/runs/shared/herdr-connection.js +2 -1
  163. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  164. package/src/runs/shared/herdr-pane-host.js +17 -1
  165. package/src/runs/shared/herdr-placed-run.js +51 -24
  166. package/src/runs/shared/lane-metadata.d.ts +0 -1
  167. package/src/runs/shared/lane-metadata.js +0 -1
  168. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  169. package/src/runs/shared/mcp-config-sources.js +1 -1
  170. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  171. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  172. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  173. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  174. package/src/runs/shared/model-resolution.d.ts +20 -5
  175. package/src/runs/shared/model-resolution.js +55 -50
  176. package/src/runs/shared/model-scope.d.ts +1 -5
  177. package/src/runs/shared/model-scope.js +1 -5
  178. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  179. package/src/runs/shared/mutation-evidence.js +52 -7
  180. package/src/runs/shared/nested-events.d.ts +1 -0
  181. package/src/runs/shared/nested-events.js +1 -1
  182. package/src/runs/shared/parallel-utils.d.ts +0 -1
  183. package/src/runs/shared/permissions.js +5 -3
  184. package/src/runs/shared/placement-host.d.ts +5 -1
  185. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  186. package/src/runs/shared/rex-pane-host.js +0 -2
  187. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  188. package/src/runs/shared/run-launch-folder.js +21 -0
  189. package/src/runs/shared/runner-launcher.d.ts +12 -1
  190. package/src/runs/shared/runner-launcher.js +16 -0
  191. package/src/runs/shared/single-output.d.ts +3 -3
  192. package/src/runs/shared/single-output.js +5 -3
  193. package/src/runs/shared/structured-output.d.ts +8 -0
  194. package/src/runs/shared/structured-output.js +40 -5
  195. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  196. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  197. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  198. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  199. package/src/runs/shared/tool-timeout.js +2 -1
  200. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  201. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  202. package/src/runs/shared/worktree.d.ts +3 -0
  203. package/src/runs/shared/worktree.js +20 -0
  204. package/src/shared/artifacts.d.ts +1 -0
  205. package/src/shared/artifacts.js +132 -22
  206. package/src/shared/capacity-resilient-json.d.ts +1 -1
  207. package/src/shared/child-cache-retention.d.ts +1 -2
  208. package/src/shared/child-cache-retention.js +1 -2
  209. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  210. package/src/shared/fleet-transcript-reader.js +333 -0
  211. package/src/shared/formatters.d.ts +0 -18
  212. package/src/shared/formatters.js +0 -18
  213. package/src/shared/pruned-fork.js +2 -2
  214. package/src/shared/reported-progress.d.ts +1 -0
  215. package/src/shared/reported-progress.js +12 -0
  216. package/src/shared/session-succession.d.ts +16 -1
  217. package/src/shared/session-succession.js +41 -2
  218. package/src/shared/session-warnings.d.ts +7 -0
  219. package/src/shared/session-warnings.js +26 -0
  220. package/src/shared/settings.d.ts +0 -23
  221. package/src/shared/settings.js +3 -35
  222. package/src/shared/status-format.d.ts +1 -0
  223. package/src/shared/status-format.js +1 -1
  224. package/src/shared/types.d.ts +108 -59
  225. package/src/shared/types.js +0 -12
  226. package/src/shared/utils.d.ts +3 -15
  227. package/src/shared/utils.js +4 -22
  228. package/src/shared/wait-tool-name.d.ts +8 -0
  229. package/src/shared/wait-tool-name.js +13 -0
  230. package/src/slash/slash-commands.js +2 -1
  231. package/src/slash/subagent-cost.d.ts +3 -2
  232. package/src/slash/subagent-cost.js +22 -3
  233. package/src/slash/subagents-admin.js +0 -1
  234. package/src/tui/fleet-status.d.ts +0 -5
  235. package/src/tui/fleet-status.js +4 -24
  236. package/src/tui/fleet.js +6 -4
  237. package/src/tui/render.d.ts +0 -9
  238. package/src/tui/render.js +194 -68
  239. package/src/tui/subagent-messages.js +3 -2
  240. package/src/watchdog/model-selection.js +2 -2
  241. package/src/watchdog/permission-arbiter.js +1 -0
  242. package/src/watchdog/register-child.d.ts +2 -3
  243. package/src/watchdog/register-child.js +2 -3
  244. package/src/watchdog/review.d.ts +0 -5
  245. package/src/watchdog/review.js +4 -3
  246. package/src/watchdog/turn-delta.js +2 -1
  247. package/src/workflows/scripted-workflow.d.ts +2 -0
  248. package/src/workflows/scripted-workflow.js +344 -59
  249. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  250. package/src/workflows/structured-workflow-scripts.js +32 -11
  251. package/src/workflows/workflow-launch-record.d.ts +15 -6
  252. package/src/workflows/workflow-launch-record.js +30 -12
  253. package/src/workflows/workflow-receipt.js +36 -53
  254. package/src/workflows/workflow-resources.js +4 -4
  255. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  256. package/src/workflows/workflow-resume-claim.js +3 -3
  257. package/src/workflows/workflow-resume.d.ts +1 -1
  258. package/src/workflows/workflow-resume.js +13 -8
  259. package/src/workflows/workflow-script-worker.d.ts +13 -0
  260. package/src/workflows/workflow-script-worker.js +81 -0
  261. package/workflow-script-process.cjs +36 -0
  262. package/workflow-script-worker.cjs +4 -1
  263. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -3,7 +3,7 @@ import {
3
3
  projectRuntimeAcknowledgedExtensions,
4
4
  registerSubagentPromptBoundary,
5
5
  registerSubagentPromptRuntime
6
- } from "./chunk-FG6SQJAR.js";
6
+ } from "./chunk-OGPOCGWX.js";
7
7
  import {
8
8
  INSPECTOR_ACTIONS,
9
9
  canQueueRetainedAsyncFollowUp,
@@ -25,13 +25,12 @@ import {
25
25
  updateSteeringTarget,
26
26
  waitForSteeringAction,
27
27
  workflowAsyncChildSteeringGuidance
28
- } from "./chunk-JEA2ZKUA.js";
28
+ } from "./chunk-IUDEI6FJ.js";
29
29
  import {
30
30
  PLACED_RESTORE_UNSUPPORTED,
31
31
  formatHerdrMachineRunnerUnsupported,
32
- isRexLocalMachine,
33
32
  resolveMachinePlacement
34
- } from "./chunk-35GII5EF.js";
33
+ } from "./chunk-JWFLPSTP.js";
35
34
  import {
36
35
  COMPLETION_ACTION,
37
36
  DEFAULT_CONTROL_CONFIG,
@@ -40,6 +39,7 @@ import {
40
39
  STATUS_ACTION,
41
40
  WORKFLOW_RUNTIME_REPLACED_STOP_NOTICE,
42
41
  appendWorkflowChildJournal,
42
+ approveWorkflowChildLaunch,
43
43
  attachNestedChildrenToResultChildren,
44
44
  buildControlEvent,
45
45
  buildSubagentResultIntercomPayload,
@@ -118,29 +118,25 @@ import {
118
118
  workflowResumeTargetId,
119
119
  workflowScriptDigest,
120
120
  workflowStopCause,
121
- writeWorkflowLaunchRecord,
122
121
  writeWorkflowReceipt
123
- } from "./chunk-SLNMBXLL.js";
122
+ } from "./chunk-IJWITCC6.js";
124
123
  import {
125
124
  HERDR_PROJECT_PANE_ACTIONS,
126
125
  handleHerdrProjectPaneAction
127
- } from "./chunk-H36HBZB2.js";
126
+ } from "./chunk-SJPABBZG.js";
128
127
  import {
129
- NATIVE_SUPERVISOR_TOOL_NAME,
130
128
  SUBAGENT_PARENT_SESSION_ENV,
131
129
  applyWatchdogLaunchRules,
132
- createNativeSupervisorChannel,
133
130
  createSubagentParamsSchema,
134
131
  finalizeToolResult,
135
132
  registerPinnedTool,
136
133
  resolveCurrentSessionId,
137
134
  resolvePiSessionId,
138
- resolveSupervisorChannelDir,
139
135
  resolveWaitToolConfig,
140
136
  resolveWatchdogConfig,
141
137
  sendRuleViolationWarning,
142
138
  writeWatchdogModelSettings
143
- } from "./chunk-EUPJB4S7.js";
139
+ } from "./chunk-5Z7JAORM.js";
144
140
  import {
145
141
  MAX_REMEMBERED_FOREGROUND_RUNS,
146
142
  discardRunningForegroundRun,
@@ -153,10 +149,9 @@ import {
153
149
  resolveSubagentRunId,
154
150
  resolveWorkflowChatProgress,
155
151
  stopAsyncRun
156
- } from "./chunk-LVWU2HOO.js";
152
+ } from "./chunk-ULGMXABL.js";
157
153
  import "./chunk-7J4ZXMY7.js";
158
154
  import {
159
- MODEL_ONLY_TOOL,
160
155
  RunFanoutLimitError,
161
156
  annotateWorkflowPreflightTrace,
162
157
  applySteeringRecoveryAgentConfig,
@@ -186,13 +181,11 @@ import {
186
181
  formatWorkflowPreflightWarnings,
187
182
  formatWorkflowStageLine,
188
183
  getRunFanoutBudgetSnapshot,
189
- inheritedSessionIds,
190
184
  isStoppableAsyncStatusStep,
191
185
  isTerminalParallelHandoffChildStatus,
192
186
  listAsyncRuns,
193
187
  normalizeWorkflowPreflight,
194
188
  opencodeSessionHeaders,
195
- ownsRun,
196
189
  parallelHandoffPath,
197
190
  parseWorkflowChildSummary,
198
191
  projectWorkflowChecklist,
@@ -202,6 +195,7 @@ import {
202
195
  readRunFanoutBudgetDescriptor,
203
196
  recordParallelHandoffMerge,
204
197
  recordParallelHandoffSupersession,
198
+ recoveryDescriptorPath,
205
199
  resolveAsyncResumeTarget,
206
200
  resolveAsyncRunLocation,
207
201
  resolveAsyncStatusChild,
@@ -215,8 +209,20 @@ import {
215
209
  workflowPreflightWarnings,
216
210
  writeParallelHandoffGroup,
217
211
  writeRunFanoutBudgetDescriptor,
212
+ writeWorkflowLaunchRecord,
218
213
  writeWorktreeSetupHandoff
219
- } from "./chunk-TMHVDPYW.js";
214
+ } from "./chunk-DLVPMML3.js";
215
+ import {
216
+ NATIVE_SUPERVISOR_TOOL_NAME,
217
+ createNativeSupervisorChannel,
218
+ resolveSupervisorChannelDir
219
+ } from "./chunk-34TUUBRN.js";
220
+ import {
221
+ MODEL_ONLY_TOOL,
222
+ inheritedSessionIds,
223
+ ownsRun,
224
+ reportSessionWarning
225
+ } from "./chunk-HXRB42AF.js";
220
226
  import {
221
227
  authorizeWorkflowResourceHost,
222
228
  claimWorkflowChildPermit,
@@ -227,7 +233,7 @@ import {
227
233
  resolveStructuredWorkflowResource,
228
234
  resolveWorkflowResource,
229
235
  validateWorkflowChildPermitRoot
230
- } from "./chunk-FJWI64H7.js";
236
+ } from "./chunk-RMSABUN3.js";
231
237
  import {
232
238
  SANDBOX_DIAGNOSTICS_PATH_ENV,
233
239
  buildEffectiveSystemPrompt,
@@ -237,10 +243,10 @@ import {
237
243
  projectScopedProfileTrustError,
238
244
  readSandboxStartupDiagnostic,
239
245
  resolveSubagentLaunchContext
240
- } from "./chunk-WPW4V6HM.js";
246
+ } from "./chunk-W7ZA6TYD.js";
241
247
  import {
242
248
  handleRefinementAction
243
- } from "./chunk-SW2VMNIU.js";
249
+ } from "./chunk-5OD3OWTE.js";
244
250
  import {
245
251
  ActiveAsyncCapacityError,
246
252
  acquireActiveAsyncCapacity,
@@ -252,21 +258,25 @@ import {
252
258
  loadConfig,
253
259
  resolveAbandonedSlotReleaseAfterMs,
254
260
  resolveAsyncByDefault,
261
+ resolveConfigDefaultTimeoutMs,
255
262
  resolveDisabledFeatureSurface,
256
263
  resolveMaxActiveAsyncRunsPerSession,
257
264
  transferActiveAsyncCapacity
258
- } from "./chunk-3U633XDZ.js";
265
+ } from "./chunk-U3ZDUUTM.js";
259
266
  import {
260
267
  DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS,
261
268
  MACHINE_DIFF_OPTIONS,
262
269
  MISSION_ACTIONS,
263
270
  MissionNotFoundError,
271
+ REQUIRE_LAUNCHER_SHAPE_ERROR,
264
272
  WORKTREE_AGENT_CWD_PLACEHOLDER,
265
273
  WorkflowScriptError,
266
274
  activeRunMarkerAgeMs,
267
275
  attachMissionToLaunchResult,
268
276
  attachRootChildrenToSteps,
277
+ buildWorktreeNaming,
269
278
  checkRecordedPidLiveness,
279
+ checkRequiredRunnerLauncher,
270
280
  cleanupWorktrees,
271
281
  createMissionWorkflowState,
272
282
  createNestedRoute,
@@ -289,6 +299,7 @@ import {
289
299
  inheritedNestedParentAddressOf,
290
300
  inheritedNestedRouteOf,
291
301
  initializeProcessTerminal,
302
+ lookupRunnerLauncher,
292
303
  missionAcceptanceStatus,
293
304
  nestedResultsPath,
294
305
  nestedRunNotActiveMessage,
@@ -306,6 +317,7 @@ import {
306
317
  readWorkflowTerminalProof,
307
318
  reconcileAsyncRun,
308
319
  reconcileNestedAsyncDescendants,
320
+ resolveAgentRunnerLauncher,
309
321
  resolveAuthorityDecision,
310
322
  resolveExpectedWorktreeAgentCwd,
311
323
  resolveInheritedNestedRoute,
@@ -318,6 +330,7 @@ import {
318
330
  retainNestedLookupRoute,
319
331
  retireResultSnapshot,
320
332
  runWorkflowScript,
333
+ runnerLauncherPlacementError,
321
334
  sanitizeProcessTerminal,
322
335
  shouldDeferWorktreeCwd,
323
336
  snapshotNestedEventFiles,
@@ -335,7 +348,7 @@ import {
335
348
  writeNestedControlRequest,
336
349
  writeNestedControlResult,
337
350
  writeNestedEvent
338
- } from "./chunk-ICNYIALB.js";
351
+ } from "./chunk-JH5H4CYJ.js";
339
352
  import {
340
353
  PROJECT_SUBAGENTS_RELATIVE_DIR,
341
354
  appendJsonl,
@@ -345,12 +358,13 @@ import {
345
358
  getArtifactsDir,
346
359
  getProjectArtifactPackagingWarning,
347
360
  getProjectSubagentsDir,
361
+ missingForkCopyNote,
348
362
  writeArtifact,
349
363
  writeMetadata
350
- } from "./chunk-U4ODUYAG.js";
364
+ } from "./chunk-LYKG4FKH.js";
351
365
  import {
352
366
  handleManagementAction
353
- } from "./chunk-ED55MIC2.js";
367
+ } from "./chunk-CGFF4WA3.js";
354
368
  import {
355
369
  closeSteerInbox,
356
370
  consumeSteerRequests,
@@ -358,7 +372,7 @@ import {
358
372
  readRevivalBriefs,
359
373
  requestAsyncSteer,
360
374
  watchAsyncControlInbox
361
- } from "./chunk-RB4GELQA.js";
375
+ } from "./chunk-LPJEKHOY.js";
362
376
  import "./chunk-NIXWDZZV.js";
363
377
  import {
364
378
  INTERCOM_BRIDGE_MARKER,
@@ -367,8 +381,9 @@ import {
367
381
  resolveIntercomBridge,
368
382
  resolveIntercomSessionTarget,
369
383
  resolveSubagentIntercomTarget
370
- } from "./chunk-WW76JRIX.js";
384
+ } from "./chunk-JAXVBXGF.js";
371
385
  import {
386
+ agentDefinitionDigest,
372
387
  resolveLaunchBinding,
373
388
  stableJsonDigest
374
389
  } from "./chunk-BGIYHF2W.js";
@@ -382,7 +397,7 @@ import {
382
397
  resolvePiLaunchToolPlan,
383
398
  resolveRuntimeModulePath,
384
399
  supervisorChannelDir
385
- } from "./chunk-355ECEP2.js";
400
+ } from "./chunk-IH7LQVEE.js";
386
401
  import {
387
402
  assertRequiredChildExtensionsAdmitted,
388
403
  hasMandatoryRequiredChildExtensions,
@@ -394,9 +409,10 @@ import "./chunk-XA3DY6UG.js";
394
409
  import {
395
410
  getExternalJobProvider
396
411
  } from "./chunk-YYREO77V.js";
397
- import "./chunk-Z6TFJ6BR.js";
412
+ import "./chunk-INWSUNI6.js";
398
413
  import {
399
414
  ChainOutputValidationError,
415
+ DEFAULT_WAIT_TOOL_NAME,
400
416
  MAX_STREAMED_RECENT_TOOLS,
401
417
  MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR,
402
418
  MISSING_STRUCTURED_OUTPUT_CALL_ERROR,
@@ -412,6 +428,7 @@ import {
412
428
  SUBAGENT_STOPPED_MESSAGE,
413
429
  SUBAGENT_TIMED_OUT_MESSAGE,
414
430
  THINKING_LEVELS,
431
+ TRUNCATED_RESPONSE_ERROR,
415
432
  TYPED_VERIFY_OUTPUT_SCHEMA_CONFLICT,
416
433
  acceptChildWatchdogEvent,
417
434
  acceptanceFailureMessage,
@@ -465,6 +482,7 @@ import {
465
482
  getFinalOutput,
466
483
  getSingleResultOutput,
467
484
  getStepAgents,
485
+ getTerminalAssistantStopReason,
468
486
  hasEmptyTerminalAssistantResponse,
469
487
  hasSingleAdjacentTransposition,
470
488
  hasSingleOutputChangedSinceSnapshot,
@@ -479,10 +497,13 @@ import {
479
497
  isDynamicRunnerGroup,
480
498
  isParallelGroup,
481
499
  isParallelStep,
500
+ isRexLocalMachine,
482
501
  isSettlementFatalOutputError,
483
502
  isStorageCapacityError,
484
503
  isToolBudgetBlockedMessage,
504
+ knownModelProviders,
485
505
  mergeAgentsForScope,
506
+ normalizeAcceptanceInput,
486
507
  normalizeExtensionBindings,
487
508
  normalizeExternalCliRunnerStatus,
488
509
  normalizeGateAcceptance,
@@ -527,6 +548,7 @@ import {
527
548
  scopedModelIdsFromContext,
528
549
  splitKnownThinkingSuffix,
529
550
  stripAcceptanceReport,
551
+ structuredOutputValidatorReady,
530
552
  suggestAgentName,
531
553
  sumResultsCost,
532
554
  sumResultsUsage,
@@ -543,10 +565,11 @@ import {
543
565
  validateExecutionAcceptancePolicy,
544
566
  validateFileOnlyOutputMode,
545
567
  validateToolBudgetConfig,
568
+ waitToolName,
546
569
  writeAtomicJson,
547
570
  writeInitialProgressFile,
548
571
  writePrivateAtomicJson
549
- } from "./chunk-V2KFIGFH.js";
572
+ } from "./chunk-XAC2XNAP.js";
550
573
  import {
551
574
  CHAIN_RUNS_DIR,
552
575
  DEFAULT_ARTIFACT_CONFIG,
@@ -582,7 +605,8 @@ import {
582
605
  resolveCurrentSubagentCapabilityCeiling
583
606
  } from "./chunk-QXASAHIA.js";
584
607
  import {
585
- safeTerminalText
608
+ safeTerminalText,
609
+ sanitizeDisplayText
586
610
  } from "./chunk-YFCK7H2S.js";
587
611
  import "./chunk-62OCY2S4.js";
588
612
 
@@ -794,7 +818,7 @@ import * as fs8 from "node:fs";
794
818
  import * as path7 from "node:path";
795
819
 
796
820
  // src/runs/background/async-execution.ts
797
- import { spawn } from "node:child_process";
821
+ import { spawn, spawnSync } from "node:child_process";
798
822
  import { randomUUID as randomUUID3 } from "node:crypto";
799
823
  import * as fs7 from "node:fs";
800
824
  import * as path6 from "node:path";
@@ -1212,10 +1236,14 @@ function childHooks(config, capture, holdFinalDrain) {
1212
1236
  }
1213
1237
  const hooks = [
1214
1238
  { name: "pi-subagents:prompt-runtime", factory: function promptRuntime(pi) {
1215
- if (!proof?.observeNext) return registerSubagentPromptRuntime(pi, runtime);
1216
- proof.observation = proof.observeNext;
1217
- proof.observeNext = void 0;
1218
- registerSubagentPromptRuntime(pi, runtime, proof.observation);
1239
+ if (!proof?.observeNext) {
1240
+ registerSubagentPromptRuntime(pi, runtime);
1241
+ } else {
1242
+ proof.observation = proof.observeNext;
1243
+ proof.observeNext = void 0;
1244
+ registerSubagentPromptRuntime(pi, runtime, proof.observation);
1245
+ }
1246
+ if (runtime.structuredOutput) return structuredOutputValidatorReady();
1219
1247
  } }
1220
1248
  ];
1221
1249
  if (config.fast) hooks.push({ name: "pi-subagents:fast-mode", factory: (pi) => registerSubagentFastModeExtension(pi) });
@@ -1275,7 +1303,8 @@ function childStorage(input) {
1275
1303
  return { kind: "default" };
1276
1304
  }
1277
1305
  function buildInProcessChildLaunch(input) {
1278
- const requiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
1306
+ const resolvedRequiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
1307
+ const requiredExtensions = input.machine ? resolvedRequiredExtensions.filter((entry) => entry.requireForAllRunners) : resolvedRequiredExtensions;
1279
1308
  const agentCapabilityCeiling = input.descendantAllowedAgents === void 0 ? void 0 : { version: 1, allowedAgents: [...input.descendantAllowedAgents], denyExtensions: false, sources: [`agent:${input.childAgentName}`] };
1280
1309
  const inheritedCeiling = inheritedCapabilityCeiling(input.inherited);
1281
1310
  const capabilityCeilingForPlanning = agentCapabilityCeiling && !input.capabilityCeiling && !inheritedCeiling ? { version: 1, denyExtensions: false, sources: [] } : input.capabilityCeiling;
@@ -1365,7 +1394,8 @@ function buildInProcessChildLaunch(input) {
1365
1394
  ...input.watchdogStatus ? { watchdogStatus: input.watchdogStatus } : {},
1366
1395
  waitTool: {
1367
1396
  enabled: input.waitToolEnabled ?? true,
1368
- ...input.waitToolDefaultTimeoutMs !== void 0 ? { defaultTimeoutMs: input.waitToolDefaultTimeoutMs } : {}
1397
+ ...input.waitToolDefaultTimeoutMs !== void 0 ? { defaultTimeoutMs: input.waitToolDefaultTimeoutMs } : {},
1398
+ ...waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { name: waitToolName() } : {}
1369
1399
  },
1370
1400
  ...input.structuredOutput ? {
1371
1401
  structuredOutput: {
@@ -1643,25 +1673,6 @@ function statusStepDescription(task) {
1643
1673
  return description.length > MAX_STATUS_STEP_DESCRIPTION_CHARS ? `${description.slice(0, MAX_STATUS_STEP_DESCRIPTION_CHARS - 1)}\u2026` : description;
1644
1674
  }
1645
1675
 
1646
- // src/runs/shared/runner-launcher.ts
1647
- function lookupRunnerLauncher(runnerLaunchers, name) {
1648
- const argv = runnerLaunchers && Object.hasOwn(runnerLaunchers, name) ? runnerLaunchers[name] : void 0;
1649
- return argv ? { name, argv: [...argv] } : void 0;
1650
- }
1651
- function runnerLauncherPlacementError(agent, machine) {
1652
- if (agent.launcher === void 0) return void 0;
1653
- const runnerType = agent.runner?.type === "external-cli" || agent.runner?.type === "external-job" ? agent.runner.type : void 0;
1654
- if (!machine && !runnerType) return void 0;
1655
- return `Agent '${agent.name}' uses launcher '${agent.launcher}', which wraps the local Pi background runner, so it cannot run ${machine ? `on machine '${machine}'` : `with runner.type='${runnerType}'`}.`;
1656
- }
1657
- function resolveAgentRunnerLauncher(agent, runnerLaunchers, machine) {
1658
- if (agent.launcher === void 0) return {};
1659
- const placementError = runnerLauncherPlacementError(agent, machine);
1660
- if (placementError) return { error: placementError };
1661
- const launcher = lookupRunnerLauncher(runnerLaunchers, agent.launcher);
1662
- return launcher ? { launcher } : { error: `Agent '${agent.name}' uses launcher '${agent.launcher}', which is not defined in runnerLaunchers in the user subagent config.` };
1663
- }
1664
-
1665
1676
  // src/runs/background/async-execution.ts
1666
1677
  var require2 = nodeModule.createRequire(new URL("../src/runs/background/async-execution.js", import.meta.url).href);
1667
1678
  var piPackageSelection = (() => {
@@ -1733,10 +1744,10 @@ function parentExtensionProviderForChild(ctx, disableAmbientExtensions, model, a
1733
1744
  var DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1e3;
1734
1745
  function formatAsyncStartedMessage(headline, interactive) {
1735
1746
  const guidance = interactive ? [
1736
- "Detached. Return control now: native completion wakes you, so do not sleep, poll, or call bg_wait for it.",
1747
+ `Detached. Return control now: native completion wakes you, so do not sleep, poll, or call ${waitToolName()} for it.`,
1737
1748
  'One-shot check: subagent({ action: "status", id: "..." }).'
1738
1749
  ] : [
1739
- 'Detached non-interactive run: Pi auto-drains current-session subagent work at agent_end. Do not run sleep timers or polling loops. Use bg_wait only for results this turn needs from work without native notification, and subagent({ action: "status", id: "..." }) for a one-shot check.'
1750
+ `Detached non-interactive run: Pi auto-drains current-session subagent work at agent_end. Do not run sleep timers or polling loops. Use ${waitToolName()} only for results this turn needs from work without native notification, and subagent({ action: "status", id: "..." }) for a one-shot check.`
1740
1751
  ];
1741
1752
  return [headline, "", ...guidance].join("\n");
1742
1753
  }
@@ -1837,6 +1848,28 @@ function terminateRunnerBeforeProceed(pid) {
1837
1848
  }
1838
1849
  return !runnerIsAlive(pid);
1839
1850
  }
1851
+ function parentPid(pid) {
1852
+ let ppid;
1853
+ if (process.platform === "linux") {
1854
+ try {
1855
+ const stat = fs7.readFileSync(`/proc/${pid}/stat`, "utf-8");
1856
+ ppid = Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]);
1857
+ } catch {
1858
+ return void 0;
1859
+ }
1860
+ } else {
1861
+ const result2 = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf-8" });
1862
+ if (result2.error || result2.status !== 0) return void 0;
1863
+ ppid = Number(result2.stdout.trim());
1864
+ }
1865
+ return Number.isSafeInteger(ppid) && ppid > 0 ? ppid : void 0;
1866
+ }
1867
+ function isInProcessTree(pid, rootPid) {
1868
+ for (let current = pid; current !== void 0 && current > 1; current = parentPid(current)) {
1869
+ if (current === rootPid) return true;
1870
+ }
1871
+ return false;
1872
+ }
1840
1873
  async function terminateRunnerBeforeProceedAsyncDefault(proc, processClosed) {
1841
1874
  for (const signal of ["SIGTERM", "SIGKILL"]) {
1842
1875
  if (proc.pid === void 0 || !runnerIsAlive(proc.pid)) return true;
@@ -1972,7 +2005,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
1972
2005
  const launchBarrierToken = hasRevivalLease ? void 0 : runnerProcessInstanceId;
1973
2006
  const launcher = cfg.launcher;
1974
2007
  const bootId = launcher ? void 0 : currentBootId();
1975
- const launchConfig = { ...cfg, runnerProcessInstanceId, ...launchBarrierToken ? { launchBarrierToken } : {}, ...bootId ? { bootId } : {} };
2008
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...launchBarrierToken ? { launchBarrierToken } : {}, ...bootId ? { bootId } : {}, ...waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { waitToolName: waitToolName() } : {} };
1976
2009
  writePrivateAtomicJson(cfgPath, launchConfig);
1977
2010
  const command = binaryHost ?? nodeExecutable;
1978
2011
  const launchForStartup = launchConfig;
@@ -1991,7 +2024,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
1991
2024
  const identityPath = launcher && launchBarrierToken && launchAsyncDir ? path6.join(launchAsyncDir, "runner-startup.json") : void 0;
1992
2025
  if (identityPath) fs7.rmSync(identityPath, { force: true });
1993
2026
  let runnerIdentity;
1994
- const terminateBeforeProceed = (pid) => !launcher ? terminateRunnerBeforeProceed(pid) : runnerIdentity !== void 0 && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && terminateRunnerBeforeProceed(runnerIdentity.pid);
2027
+ const terminateBeforeProceed = (pid) => !launcher ? terminateRunnerBeforeProceed(pid) : runnerIdentity !== void 0 && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && isInProcessTree(runnerIdentity.pid, pid) && terminateRunnerBeforeProceed(runnerIdentity.pid);
1995
2028
  const adoptRunnerIdentity = (pid, pidNamespaceScope) => {
1996
2029
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1) return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
1997
2030
  runnerIdentity = { pid, ...typeof pidNamespaceScope === "string" ? { pidNamespaceScope } : {} };
@@ -2384,7 +2417,7 @@ function buildAsyncRunnerSteps(id, params) {
2384
2417
  taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
2385
2418
  taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
2386
2419
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
2387
- const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
2420
+ const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a, machine);
2388
2421
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
2389
2422
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
2390
2423
  const primaryModelFromParent = modelOrigin === "inherited";
@@ -2394,7 +2427,7 @@ function buildAsyncRunnerSteps(id, params) {
2394
2427
  ctx.currentModel,
2395
2428
  availableModels,
2396
2429
  a.modelProvider ?? ctx.currentModelProvider,
2397
- { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" }
2430
+ { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited", knownProviders: ctx.knownProviders }
2398
2431
  );
2399
2432
  const thinkingOverride = flatIndex === void 0 ? void 0 : thinkingOverridesByFlatIndex?.[flatIndex];
2400
2433
  let claudeCodeOverride;
@@ -2438,7 +2471,8 @@ function buildAsyncRunnerSteps(id, params) {
2438
2471
  const modelEvidence = resolveModelSelection(primaryModel, availableModels, a.modelProvider ?? ctx.currentModelProvider, {
2439
2472
  scope: modelScopes,
2440
2473
  primaryModelFromParent,
2441
- origin: modelOrigin
2474
+ origin: modelOrigin,
2475
+ knownProviders: ctx.knownProviders
2442
2476
  });
2443
2477
  requestedModel = modelEvidence.requestedModel;
2444
2478
  selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, thinkingOverride !== void 0);
@@ -2450,7 +2484,7 @@ function buildAsyncRunnerSteps(id, params) {
2450
2484
  const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
2451
2485
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
2452
2486
  const fast = s.fast ?? params.fast ?? a.fast;
2453
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2487
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2454
2488
  const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
2455
2489
  const toolPlan = resolvePiLaunchToolPlan({
2456
2490
  tools: a.tools,
@@ -3026,7 +3060,6 @@ function workflowAwaitedAsyncResultPath(asyncDir) {
3026
3060
  function executeAsyncSingle(id, params) {
3027
3061
  const {
3028
3062
  agent,
3029
- agentConfig,
3030
3063
  ctx,
3031
3064
  cwd,
3032
3065
  maxOutput,
@@ -3047,6 +3080,7 @@ function executeAsyncSingle(id, params) {
3047
3080
  childIntercomTarget,
3048
3081
  nestedRoute
3049
3082
  } = params;
3083
+ let agentConfig = params.agentConfig;
3050
3084
  let lane;
3051
3085
  try {
3052
3086
  lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
@@ -3097,6 +3131,11 @@ function executeAsyncSingle(id, params) {
3097
3131
  const resolvedLauncher = resolveAgentRunnerLauncher(agentConfig, ctx.runnerLaunchers, requestedMachine);
3098
3132
  if (resolvedLauncher.error) return formatAsyncStartError("single", resolvedLauncher.error);
3099
3133
  const launcher = resolvedLauncher.launcher;
3134
+ if (params.requireLauncher) {
3135
+ const required = checkRequiredRunnerLauncher(agentConfig, launcher?.name, params.requireLauncher);
3136
+ if (required.error !== void 0) return formatAsyncStartError("single", required.error);
3137
+ agentConfig = { ...agentConfig, definitionDigest: required.definitionDigest };
3138
+ }
3100
3139
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? void 0);
3101
3140
  try {
3102
3141
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
@@ -3160,7 +3199,7 @@ function executeAsyncSingle(id, params) {
3160
3199
  const outputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
3161
3200
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
3162
3201
  if (validationError) return formatAsyncStartError("single", validationError);
3163
- const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
3202
+ const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig, machine);
3164
3203
  const reads = params.reads !== void 0 ? params.reads : agentConfig.defaultReads ?? false;
3165
3204
  const readPaths = Array.isArray(reads) ? machine ? externalRunner ? reads.map((read) => read === "~" || read.startsWith("~/") || path6.posix.isAbsolute(read) ? read : path6.posix.resolve(instructionCwd, read)) : [] : managedWorktreeProvider === "worktrunk" ? resolveExistingReadInstructionPaths(reads, instructionCwd, readExistenceCwd) : resolveExistingReadPaths(reads, readExistenceCwd) : [];
3166
3205
  const readsInstruction = readPaths.length > 0 ? `[Read from: ${readPaths.join(", ")}]
@@ -3182,7 +3221,7 @@ function executeAsyncSingle(id, params) {
3182
3221
  ctx.currentModel,
3183
3222
  availableModels,
3184
3223
  ctx.currentModelProvider,
3185
- { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited" }
3224
+ { scope: modelScopes, source: modelOrigin === "explicit" ? "explicit" : "inherited", knownProviders: ctx.knownProviders }
3186
3225
  );
3187
3226
  } catch (error) {
3188
3227
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
@@ -3243,7 +3282,8 @@ function executeAsyncSingle(id, params) {
3243
3282
  const modelEvidence = resolveModelSelection(primaryModel, availableModels, agentConfig.modelProvider ?? ctx.currentModelProvider, {
3244
3283
  scope: modelScopes,
3245
3284
  primaryModelFromParent: modelOrigin === "inherited",
3246
- origin: modelOrigin
3285
+ origin: modelOrigin,
3286
+ knownProviders: ctx.knownProviders
3247
3287
  });
3248
3288
  requestedModel = modelEvidence.requestedModel;
3249
3289
  selectedModel = applyThinkingSuffix(modelEvidence.model, effectiveThinking, params.thinkingOverride !== void 0);
@@ -3252,7 +3292,7 @@ function executeAsyncSingle(id, params) {
3252
3292
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
3253
3293
  }
3254
3294
  }
3255
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
3295
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
3256
3296
  const hostAvailableBuiltins = getHostBuiltinToolNames(ctx.pi);
3257
3297
  const toolPlan = resolvePiLaunchToolPlan({
3258
3298
  tools: agentConfig.tools,
@@ -3309,6 +3349,7 @@ function executeAsyncSingle(id, params) {
3309
3349
  agentContract: params.agentContract
3310
3350
  });
3311
3351
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
3352
+ const requiredLauncher = params.requireLauncher ?? params.carriedRequiredLauncher;
3312
3353
  const recoveryDescriptor = {
3313
3354
  ...ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {},
3314
3355
  version: 1,
@@ -3318,6 +3359,10 @@ function executeAsyncSingle(id, params) {
3318
3359
  ...requiredExtensions.length > 0 ? { requiredExtensions } : {},
3319
3360
  runFanoutBudget,
3320
3361
  sourceRunId: id,
3362
+ ...ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {},
3363
+ // The worktree the runner will create, fixed here from launch inputs (the runner's own naming call).
3364
+ ...managedWorktreeProvider === "native" ? { managedWorktree: { provider: "native", cwd: instructionCwd } } : {},
3365
+ ...managedWorktreeProvider === "worktrunk" ? { managedWorktree: { provider: "worktrunk", branch: buildWorktreeNaming({ runId: `${id}-s0`, index: 0, agent, label: lane?.key ?? params.workflowKey, task: taskText, branchPrefix: worktreeBranchPrefix }).requestedBranch } } : {},
3321
3366
  ...params.agentContract ? { agentContract: params.agentContract } : {},
3322
3367
  agent,
3323
3368
  ...sandbox ? { sandbox } : {},
@@ -3356,7 +3401,8 @@ function executeAsyncSingle(id, params) {
3356
3401
  ...params.context ? { context: params.context } : {},
3357
3402
  ...params.intercomBridge !== void 0 ? { intercomBridge: params.intercomBridge } : {},
3358
3403
  ...params.baseRef !== void 0 ? { baseRef: params.baseRef } : {},
3359
- ...launcher ? { launcher: launcher.name } : {},
3404
+ launcher: launcher ? launcher.name : null,
3405
+ ...requiredLauncher ? { requiredLauncher } : {},
3360
3406
  ...deadlineAt !== void 0 ? { absoluteDeadlineAt: deadlineAt } : {},
3361
3407
  ...resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {},
3362
3408
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -3369,7 +3415,7 @@ function executeAsyncSingle(id, params) {
3369
3415
  };
3370
3416
  if (!externalRunner) {
3371
3417
  try {
3372
- writePrivateAtomicJson(path6.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
3418
+ writePrivateAtomicJson(recoveryDescriptorPath(path6.dirname(asyncDir), id), recoveryDescriptor);
3373
3419
  } catch (error) {
3374
3420
  return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
3375
3421
  }
@@ -3927,14 +3973,29 @@ function readReplyWorkflowScript(sessionManager, toolCallId) {
3927
3973
  const message = entry.message;
3928
3974
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
3929
3975
  if (!message.content.some((block) => block.type === "toolCall" && block.id === toolCallId)) continue;
3930
- return scriptFromReply(message.content);
3976
+ return scriptFromReply(message.content, () => earlierTurnHasJsBlock(branch, index));
3931
3977
  }
3932
3978
  return { error: 'workflow: true only works from a model subagent tool call whose assistant message contains the ```js workflow block; other callers must pass a script path such as workflow: "./script.js".' };
3933
3979
  }
3934
- function scriptFromReply(content) {
3980
+ function earlierTurnHasJsBlock(branch, callIndex) {
3981
+ for (let index = callIndex - 1; index >= 0; index--) {
3982
+ const entry = branch[index];
3983
+ if (entry.type !== "message") continue;
3984
+ if (entry.message?.role === "user") return false;
3985
+ if (entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
3986
+ const text = entry.message.content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
3987
+ const { tagged, plain } = workflowBlocks(text);
3988
+ if (tagged.length > 0 || plain.length > 0) return true;
3989
+ }
3990
+ return false;
3991
+ }
3992
+ function scriptFromReply(content, earlierBlock) {
3935
3993
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent" && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
3936
3994
  if (replyCalls > 1) return { error: `This reply has ${replyCalls} subagent calls with workflow: true; a reply can carry only one. Pass other scripts as workflow file paths.` };
3937
- if (!content.some((block) => block.type === "text")) return { error: `The assistant message that issued this call has no text in the session, so the reply's visible text, including any \`\`\`js workflow block, never reached it. ${SUMMARY_NOTE}` };
3995
+ if (!content.some((block) => block.type === "text")) {
3996
+ if (earlierBlock()) return { error: "The assistant message that issued this call has no text. A ```js block is in an earlier message of this turn, but workflow: true reads only the message that issues the call. Pass that script's source as options: { script: \"...\" } in place of workflow: true, with the call's other fields unchanged, or write the block and the call in one message." };
3997
+ return { error: `The assistant message that issued this call has no text in the session, so no \`\`\`js workflow block reached it. ${SUMMARY_NOTE}` };
3998
+ }
3938
3999
  const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
3939
4000
  const { tagged, plain, unclosed } = workflowBlocks(text);
3940
4001
  if (unclosed) return { error: "The script's fenced block in this reply is not closed." };
@@ -4203,6 +4264,17 @@ function createChildTranscriptWriter(input) {
4203
4264
  };
4204
4265
  }
4205
4266
 
4267
+ // src/shared/reported-progress.ts
4268
+ var MAX_REPORTED_PROGRESS_LENGTH = 512;
4269
+ function extractReportedProgress(toolName, args) {
4270
+ if (toolName !== "contact_supervisor" || typeof args !== "object" || args === null) return void 0;
4271
+ const call = args;
4272
+ if (call.reason !== "progress_update" || typeof call.message !== "string") return void 0;
4273
+ const firstLine = call.message.split(/\r?\n/, 1)[0] ?? "";
4274
+ const sanitized = sanitizeDisplayText(firstLine).replace(/^(?:progress|update):\s*/i, "");
4275
+ return sanitized ? sanitized.slice(0, MAX_REPORTED_PROGRESS_LENGTH) : void 0;
4276
+ }
4277
+
4206
4278
  // src/runs/shared/partial-output.ts
4207
4279
  function isAssistant(message) {
4208
4280
  return !!message && typeof message === "object" && message.role === "assistant";
@@ -5198,6 +5270,59 @@ function reconcileAttemptUsage(live, messages, baseline) {
5198
5270
  return reconciled;
5199
5271
  }
5200
5272
 
5273
+ // src/runs/shared/supervisor-wait-timer.ts
5274
+ function isBlockingSupervisorTool(toolName, args) {
5275
+ if (!args || typeof args !== "object") return false;
5276
+ const call = args;
5277
+ if (toolName === "contact_supervisor") return call.reason === "need_decision" || call.reason === "interview_request";
5278
+ return toolName === "intercom" && call.action === "ask";
5279
+ }
5280
+ function startPausableTimer(delayMs, onFire) {
5281
+ let remaining = Math.max(0, delayMs);
5282
+ let runningSince;
5283
+ let timer;
5284
+ let done = false;
5285
+ const pausedBy = /* @__PURE__ */ new Set();
5286
+ const remainingMs = () => runningSince === void 0 ? remaining : Math.max(0, remaining - (performance.now() - runningSince));
5287
+ const run = () => {
5288
+ runningSince = performance.now();
5289
+ timer = setTimeout(() => {
5290
+ done = true;
5291
+ runningSince = void 0;
5292
+ remaining = 0;
5293
+ onFire();
5294
+ }, remaining);
5295
+ timer.unref?.();
5296
+ };
5297
+ const stop = () => {
5298
+ clearTimeout(timer);
5299
+ remaining = remainingMs();
5300
+ runningSince = void 0;
5301
+ };
5302
+ run();
5303
+ return {
5304
+ pause(key) {
5305
+ if (done) return;
5306
+ if (pausedBy.size === 0) stop();
5307
+ pausedBy.add(key);
5308
+ },
5309
+ resume(key) {
5310
+ if (done || !pausedBy.delete(key) || pausedBy.size > 0) return;
5311
+ run();
5312
+ },
5313
+ remainingMs,
5314
+ clear() {
5315
+ done = true;
5316
+ stop();
5317
+ }
5318
+ };
5319
+ }
5320
+ function pauseForSupervisorWait(timer, event) {
5321
+ if (!timer || typeof event.toolCallId !== "string") return;
5322
+ if (event.type === "tool_execution_start" && isBlockingSupervisorTool(event.toolName, event.args)) timer.pause(event.toolCallId);
5323
+ else if (event.type === "tool_execution_end") timer.resume(event.toolCallId);
5324
+ }
5325
+
5201
5326
  // src/runs/foreground/execution.ts
5202
5327
  var artifactOutputByResult = /* @__PURE__ */ new WeakMap();
5203
5328
  var acceptanceOutputByResult = /* @__PURE__ */ new WeakMap();
@@ -5347,6 +5472,8 @@ function captureStructuredDelegationProgressState(progress, result2) {
5347
5472
  recentOutput: [...progress.recentOutput],
5348
5473
  recentTools: progress.recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map(({ tool, args }) => ({ tool, args })),
5349
5474
  activityState: progress.activityState,
5475
+ progressText: progress.progressText,
5476
+ progressUpdatedAt: progress.progressUpdatedAt,
5350
5477
  model: progress.model ?? result2.model,
5351
5478
  toolCount: progress.toolCount,
5352
5479
  tokens: progress.tokens,
@@ -5354,7 +5481,7 @@ function captureStructuredDelegationProgressState(progress, result2) {
5354
5481
  };
5355
5482
  }
5356
5483
  function structuredDelegationProgressChanged(previous, progress, result2) {
5357
- if (previous.providerDiagnostics !== progress.providerDiagnostics || previous.currentTool !== progress.currentTool || previous.currentToolArgs !== progress.currentToolArgs || previous.activityState !== progress.activityState || previous.model !== (progress.model ?? result2.model) || previous.toolCount !== progress.toolCount || previous.tokens !== progress.tokens || previous.turnCount !== progress.turnCount || previous.recentOutput.length !== progress.recentOutput.length) return true;
5484
+ if (previous.providerDiagnostics !== progress.providerDiagnostics || previous.currentTool !== progress.currentTool || previous.currentToolArgs !== progress.currentToolArgs || previous.activityState !== progress.activityState || previous.progressText !== progress.progressText || previous.progressUpdatedAt !== progress.progressUpdatedAt || previous.model !== (progress.model ?? result2.model) || previous.toolCount !== progress.toolCount || previous.tokens !== progress.tokens || previous.turnCount !== progress.turnCount || previous.recentOutput.length !== progress.recentOutput.length) return true;
5358
5485
  for (let index = 0; index < progress.recentOutput.length; index++) {
5359
5486
  if (previous.recentOutput[index] !== progress.recentOutput[index]) return true;
5360
5487
  }
@@ -5372,6 +5499,7 @@ function isCompleteUsageCounter(value) {
5372
5499
  }
5373
5500
  var STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
5374
5501
  var AFTER_COMPACTION_SETTLEMENT = /* @__PURE__ */ Symbol("afterCompactionSettlement");
5502
+ var REMAINING_TIMEOUT_MS = /* @__PURE__ */ Symbol("remainingTimeoutMs");
5375
5503
  async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared) {
5376
5504
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
5377
5505
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== void 0);
@@ -5570,6 +5698,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5570
5698
  let toolAvailabilityError;
5571
5699
  let abortedBySignal = options.signal?.aborted === true;
5572
5700
  let afterCompactionSettlement = false;
5701
+ let remainingTimeoutMs;
5573
5702
  if (options.workflowChildPermitLaunch) {
5574
5703
  const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
5575
5704
  workflowRunId: options.workflowChildPermitLaunch.workflowRunId,
@@ -5611,7 +5740,8 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5611
5740
  let timeoutHardFinishTimer;
5612
5741
  const clearTimeoutTimers = () => {
5613
5742
  if (timeoutTimer) {
5614
- clearTimeout(timeoutTimer);
5743
+ remainingTimeoutMs = timeoutTimer.remainingMs();
5744
+ timeoutTimer.clear();
5615
5745
  timeoutTimer = void 0;
5616
5746
  }
5617
5747
  if (timeoutHardFinishTimer) {
@@ -5941,12 +6071,20 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5941
6071
  toolAttentionTarget.attentionEmitted = true;
5942
6072
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
5943
6073
  const toolCallId = toolAttentionTarget.key.startsWith("id:") ? toolAttentionTarget.key.slice(3) : void 0;
6074
+ let hasCommandController = false;
6075
+ if (toolCallId) try {
6076
+ hasCommandController = retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId);
6077
+ } catch (error) {
6078
+ const message = `Could not read the command state of ${agent.name}; its command controls are not offered: ${error instanceof Error ? error.message : String(error)}`;
6079
+ if (options.onWarning) options.onWarning(message, "child-command-state");
6080
+ else console.warn(`[pi-subagents] ${message}`);
6081
+ }
5944
6082
  return emitNeedsAttention(now, {
5945
6083
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1e3)}s`,
5946
6084
  reason: "tool_open_threshold",
5947
6085
  currentTool: toolAttentionTarget.tool,
5948
6086
  toolCallId,
5949
- hasCommandController: Boolean(toolCallId && retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId)),
6087
+ hasCommandController,
5950
6088
  currentPath: toolAttentionTarget.path,
5951
6089
  currentToolDurationMs: durationMs
5952
6090
  });
@@ -6014,6 +6152,11 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6014
6152
  );
6015
6153
  }
6016
6154
  appendRecentOutput(progress, resultText.split("\n").slice(-10));
6155
+ const messageToolName = message.toolName;
6156
+ if (message.isError !== true && messageToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
6157
+ progress.progressText = toolSnapshot.progressText;
6158
+ progress.progressUpdatedAt = now;
6159
+ }
6017
6160
  if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
6018
6161
  recordMutatingFailure(mutatingFailures, {
6019
6162
  tool: toolSnapshot.tool,
@@ -6114,6 +6257,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6114
6257
  progress.durationMs = now - startTime;
6115
6258
  progress.lastActivityAt = now;
6116
6259
  updateActivityState(now);
6260
+ pauseForSupervisorWait(timeoutTimer, evt);
6117
6261
  if (evt.type === "tool_execution_start") {
6118
6262
  const toolArgs = evt.args && typeof evt.args === "object" && !Array.isArray(evt.args) ? evt.args : {};
6119
6263
  const activeTool = evt.toolName !== void 0 ? recordActiveToolCall(evt, toolArgs, now) : void 0;
@@ -6130,7 +6274,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6130
6274
  result2.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, result2.toolBudget?.blockedTool);
6131
6275
  }
6132
6276
  const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
6133
- pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
6277
+ pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
6134
6278
  if (typeof evt.toolCallId === "string" && evt.toolCallId) pendingToolResultsByCallId.set(evt.toolCallId, pendingToolResult);
6135
6279
  fireUpdate();
6136
6280
  }
@@ -6239,7 +6383,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6239
6383
  activityTimer.unref?.();
6240
6384
  }
6241
6385
  if (attemptTimeout) {
6242
- timeoutTimer = setTimeout(() => {
6386
+ timeoutTimer = startPausableTimer(attemptTimeout.remainingMs, () => {
6243
6387
  if (sessionSettled || lifecycleFinished || interruptedByControl || result2.timedOut) return;
6244
6388
  result2.timedOut = true;
6245
6389
  timeoutCause = attemptTimeout.message;
@@ -6256,8 +6400,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6256
6400
  settle(void 0, true);
6257
6401
  }, 4e3);
6258
6402
  timeoutHardFinishTimer.unref?.();
6259
- }, attemptTimeout.remainingMs);
6260
- timeoutTimer.unref?.();
6403
+ });
6261
6404
  }
6262
6405
  let toolTimeoutSequence = 0;
6263
6406
  const activeToolTimeouts = /* @__PURE__ */ new Map();
@@ -6285,7 +6428,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6285
6428
  };
6286
6429
  const terminateForToolTimeout = (message) => {
6287
6430
  if (sessionSettled || lifecycleFinished || interruptedByControl || result2.timedOut) return;
6288
- clearTimeout(timeoutTimer);
6431
+ timeoutTimer?.clear();
6289
6432
  result2.timedOut = true;
6290
6433
  timeoutCause = message;
6291
6434
  result2.error = message;
@@ -6304,9 +6447,6 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6304
6447
  const armToolTimeout = (event) => {
6305
6448
  const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
6306
6449
  if (timeoutForTool === void 0) return;
6307
- const elapsed = Date.now() - startTime;
6308
- const runRemaining = attemptTimeout ? Math.max(0, attemptTimeout.remainingMs - elapsed) : void 0;
6309
- if (runRemaining !== void 0 && timeoutForTool >= runRemaining) return;
6310
6450
  const key = toolTimeoutCallKey(event, ++toolTimeoutSequence);
6311
6451
  const toolName = event.toolName;
6312
6452
  const timer = setTimeout(() => {
@@ -6424,12 +6564,12 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6424
6564
  const steer = created.steer.bind(created);
6425
6565
  const followUp = created.followUp.bind(created);
6426
6566
  created.steer = async (text) => {
6567
+ await steer(text);
6427
6568
  if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
6428
- return steer(text);
6429
6569
  };
6430
6570
  created.followUp = async (text) => {
6571
+ await followUp(text);
6431
6572
  if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
6432
- return followUp(text);
6433
6573
  };
6434
6574
  created.detached = detached;
6435
6575
  unsubscribe = created.subscribe((event) => processEvent(event));
@@ -6460,9 +6600,8 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6460
6600
  result2.exitCode = exitCode;
6461
6601
  result2.providerDiagnostics = clearProviderRetry(result2.providerDiagnostics);
6462
6602
  progress.providerDiagnostics = result2.providerDiagnostics;
6463
- if (afterCompactionSettlement) {
6464
- result2[AFTER_COMPACTION_SETTLEMENT] = true;
6465
- }
6603
+ if (afterCompactionSettlement) result2[AFTER_COMPACTION_SETTLEMENT] = true;
6604
+ result2[REMAINING_TIMEOUT_MS] = remainingTimeoutMs;
6466
6605
  if (interruptedByControl) {
6467
6606
  result2.exitCode = 0;
6468
6607
  result2.interrupted = true;
@@ -6524,6 +6663,9 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6524
6663
  } else if (errInfo.hasError) {
6525
6664
  result2.exitCode = errInfo.exitCode ?? 1;
6526
6665
  result2.error = errInfo.details ? `${errInfo.errorType} failed (exit ${errInfo.exitCode}): ${errInfo.details}` : `${errInfo.errorType} failed with exit code ${errInfo.exitCode}`;
6666
+ } else if (!validatedStructuredOutput && getTerminalAssistantStopReason(messages) === "length") {
6667
+ result2.exitCode = 1;
6668
+ result2.error = TRUNCATED_RESPONSE_ERROR;
6527
6669
  }
6528
6670
  }
6529
6671
  progress.status = result2.exitCode === 0 ? "completed" : "failed";
@@ -6541,7 +6683,7 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6541
6683
  durationMs: progress.durationMs
6542
6684
  };
6543
6685
  const remoteGitChanged = result2.nativeMachine?.initialGit && result2.nativeMachine.finalGit ? result2.nativeMachine.initialGit.head !== result2.nativeMachine.finalGit.head || result2.nativeMachine.initialGit.dirty !== result2.nativeMachine.finalGit.dirty : void 0;
6544
- const mutationEvidence = result2.nativeMachine && !isRexLocalMachine(options.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...remoteGitChanged === void 0 ? { unavailable: "Remote Git before/after evidence was incomplete." } : {} } : collectTrackedMutationEvidence(mutationSnapshot, mutationCwd);
6686
+ const mutationEvidence = result2.nativeMachine && !isRexLocalMachine(options.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...remoteGitChanged === void 0 ? { unavailable: "Remote Git before/after evidence was incomplete." } : {} } : await collectTrackedMutationEvidence(mutationSnapshot, mutationCwd);
6545
6687
  const acceptanceOutput = getFinalOutput(result2.messages ?? []);
6546
6688
  const structuredText = result2.structuredOutput === void 0 ? void 0 : JSON.stringify(result2.structuredOutput, null, 2);
6547
6689
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -6633,7 +6775,7 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
6633
6775
  }
6634
6776
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
6635
6777
  const effectiveCwd = options.cwd ?? runtimeCwd;
6636
- const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6778
+ const cwdError = options.machine && !isRexLocalMachine(options.machine) ? void 0 : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6637
6779
  if (cwdError) {
6638
6780
  return redactResultPrompt(withRunContext({
6639
6781
  index: options.index ?? 0,
@@ -6776,7 +6918,8 @@ ${acceptancePrompt}` : task;
6776
6918
  {
6777
6919
  scope: options.modelScope,
6778
6920
  primaryModelFromParent: options.modelOverrideFromParent,
6779
- origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured")
6921
+ origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
6922
+ knownProviders: options.knownProviders
6780
6923
  }
6781
6924
  );
6782
6925
  try {
@@ -6924,6 +7067,8 @@ ${PROMPT_REDACTED}; live Prompt Audit only.
6924
7067
  });
6925
7068
  if (recovery.action === "resume") {
6926
7069
  recoveryPrompt = recovery.prompt;
7070
+ const remainingMs = attemptResult[REMAINING_TIMEOUT_MS];
7071
+ if (remainingMs !== void 0) attemptOptions.deadlineAt = Date.now() + remainingMs;
6927
7072
  attemptNotes.push("[abort-recovery] compaction abort after useful progress; resuming the retained child session once on the same model.");
6928
7073
  continue;
6929
7074
  }
@@ -7682,7 +7827,7 @@ async function createPrunedForkSessionWriter(ctx, config, signal) {
7682
7827
  };
7683
7828
  if (!config.model?.trim()) throw new Error("Pruned fork context requires config.forkContext.model.");
7684
7829
  const available = ctx.modelRegistry.getAvailable();
7685
- const resolved = resolveModelCandidate(config.model.trim(), available.map(toModelInfo), ctx.model?.provider);
7830
+ const resolved = resolveModelCandidate(config.model.trim(), available.map(toModelInfo), ctx.model?.provider, knownModelProviders(ctx.modelRegistry));
7686
7831
  if (!resolved) throw new Error(`Pruned fork model '${config.model}' did not match exactly one available model.`);
7687
7832
  const { baseModel } = splitKnownThinkingSuffix(resolved);
7688
7833
  const named = splitProviderModel(baseModel);
@@ -8510,7 +8655,7 @@ function formatResumeGuidance(runId, children, fallbackSessionFile, options = {}
8510
8655
  const resumableWorkflowChildren = workflowChildren.filter(({ child }) => !(child.status === "paused" && child.activityState === "needs_attention"));
8511
8656
  if (workflowChildren.length > 0) {
8512
8657
  return [
8513
- ...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.`),
8658
+ ...supervisorDetachedWorkflowChildren.map(({ child }) => `Recovery workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: reply to the supervisor request first, then wait with ${waitToolName()}({ 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.`),
8514
8659
  ...resumableWorkflowChildren.map(({ child }) => `Revive workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: subagent({ action: "resume", id: "${child.runId}", message: "..." })`)
8515
8660
  ].join("\n");
8516
8661
  }
@@ -8602,7 +8747,7 @@ function formatRememberedForegroundStatus(run) {
8602
8747
  const detached = run.children.some((child) => child.status === "detached");
8603
8748
  const resumable = run.children.find((child) => hasExistingSessionFile(child.sessionFile));
8604
8749
  if (detached) {
8605
- 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.`);
8750
+ lines.push(`Recovery: reply to the supervisor request first, then wait with ${waitToolName()}({ id: "${run.runId}" }); do not resume or launch a replacement while any child remains detached.`);
8606
8751
  } else if (resumable) {
8607
8752
  lines.push(run.children.length === 1 ? `Revive: subagent({ action: "resume", id: "${run.runId}", message: "..." })` : `Revive child: subagent({ action: "resume", id: "${run.runId}", message: "...", options: { index: ${resumable.index} } })`);
8608
8753
  } else {
@@ -8998,10 +9143,11 @@ Extensions denied: ${status.capabilityCeiling.denyExtensions ? "yes" : "no"} (so
8998
9143
  lines.push(` Runner: external-cli (${runner.command}${runner.args.length ? ` ${runner.args.join(" ")}` : ""})`);
8999
9144
  lines.push(` Adapter: ${runner.adapter.id} v${runner.adapter.version} (${runner.adapter.executionMode})`);
9000
9145
  if (runner.safety) {
9001
- 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}`);
9002
- 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}`);
9003
- 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}`);
9004
- 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}`);
9146
+ const safetyLabel = " Safety (adapter profile, not measured):";
9147
+ if ("approvalPolicy" in runner.safety) lines.push(`${safetyLabel} ${"access" in runner.safety ? `access=${runner.safety.access}, ` : ""}sandbox=${runner.safety.sandbox}, approval=${runner.safety.approvalPolicy}, ephemeral=${runner.safety.ephemeral}`);
9148
+ else if ("mode" in runner.safety) lines.push(`${safetyLabel} access=${runner.safety.access}, auth=${runner.safety.authentication}, mode=${runner.safety.mode}, sandbox=${runner.safety.sandbox}, workspaceTrust=${runner.safety.workspaceTrust}, sessionReuse=${runner.safety.sessionReuse}`);
9149
+ else if ("authentication" in runner.safety) lines.push(`${safetyLabel} 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}`);
9150
+ else lines.push(`${safetyLabel} access=read-only, permission=${runner.safety.permissionMode}, tools=${runner.safety.tools}, mcp=${runner.safety.mcp}, settings=${runner.safety.settingSources}, persistence=${runner.safety.sessionPersistence}`);
9005
9151
  }
9006
9152
  lines.push(` Capabilities: stop=${runner.capabilities.stop}, steer=false, resume=false, structuredOutput=false, toolEvents=false, supervisor=unsupported, forkContext=false, extensionBindings=false`);
9007
9153
  lines.push(` Unsupported steer: ${runner.unsupportedReasons.steer}`);
@@ -9169,13 +9315,13 @@ function applyForceTopLevelAsyncOverride(params, depth, forceTopLevelAsync) {
9169
9315
 
9170
9316
  // src/runs/shared/worktree-cleanup-apply.ts
9171
9317
  import { createHash as createHash5 } from "node:crypto";
9172
- import { spawnSync as spawnSync2 } from "node:child_process";
9318
+ import { spawnSync as spawnSync3 } from "node:child_process";
9173
9319
  import * as fs20 from "node:fs";
9174
9320
  import * as path18 from "node:path";
9175
9321
 
9176
9322
  // src/runs/shared/worktree-cleanup-plan.ts
9177
9323
  import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
9178
- import { spawnSync } from "node:child_process";
9324
+ import { spawnSync as spawnSync2 } from "node:child_process";
9179
9325
  import * as fs19 from "node:fs";
9180
9326
  import * as os2 from "node:os";
9181
9327
  import * as path17 from "node:path";
@@ -9186,7 +9332,7 @@ var MAX_PLAN_ENTRIES = 512;
9186
9332
  var MAX_METADATA_FILE_BYTES = 2 * 1024 * 1024;
9187
9333
  function runGit(cwd, args) {
9188
9334
  try {
9189
- const result2 = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
9335
+ const result2 = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
9190
9336
  return {
9191
9337
  stdout: result2.stdout ?? "",
9192
9338
  stderr: result2.stderr ?? "",
@@ -9927,7 +10073,7 @@ async function applyReviewedCleanupPlan(input) {
9927
10073
  const journalEntry = { path: entry.path, branch: entry.branch, state: "removing", reason: "removal prepared; outcome not yet recorded" };
9928
10074
  receipt.entries.push(journalEntry);
9929
10075
  writePrivateAtomicJson(receiptPath, receipt);
9930
- const removed = spawnSync2("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
10076
+ const removed = spawnSync3("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
9931
10077
  if (removed.status !== 0) throw new Error(removed.error?.message || removed.stderr.trim() || "git worktree remove failed");
9932
10078
  journalEntry.state = "removed";
9933
10079
  journalEntry.reason = "worktree removed; local branch retained";
@@ -10017,6 +10163,38 @@ function inheritedRunFanoutBudget(deps) {
10017
10163
  function resolveRequestedCwd(runtimeCwd, requestedCwd) {
10018
10164
  return requestedCwd ? path19.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
10019
10165
  }
10166
+ function workflowChildLaunchArgs(workflowRunId, key, request, scriptAgent, ctxCwd, discoverAgents2) {
10167
+ const resume = request.action === "resume" && typeof request.id === "string" ? request.id : void 0;
10168
+ const agent = request.agent ?? scriptAgent;
10169
+ const task = resume !== void 0 ? request.message : request.task;
10170
+ const scope = resolveExecutionAgentScope(request.agentScope);
10171
+ const findAgent = (dir) => typeof agent === "string" ? resolveAgentName(agent, discoverAgents2(dir, scope).agents).agent : void 0;
10172
+ const ctxAgent = request.machine === void 0 ? findAgent(ctxCwd) : void 0;
10173
+ const placed = request.machine !== void 0 || ctxAgent?.machine !== void 0;
10174
+ const runCwd = resolveRequestedCwd(ctxCwd, request.cwd);
10175
+ const cwd = resume === void 0 && !placed ? runCwd : void 0;
10176
+ const acceptanceInput = request.acceptance !== void 0 || resume !== void 0 ? request.acceptance : (placed || runCwd === ctxCwd ? ctxAgent ?? findAgent(ctxCwd) : findAgent(runCwd))?.defaultAcceptance;
10177
+ const acceptance = acceptanceInput !== void 0 && validateAcceptanceInput(acceptanceInput).length === 0 ? normalizeAcceptanceInput(acceptanceInput) : void 0;
10178
+ const commands = acceptance?.level === "verified" ? (acceptance.verify ?? []).map((verify) => ({
10179
+ command: verify.command,
10180
+ ...cwd !== void 0 ? { cwd: verify.cwd ? path19.resolve(cwd, verify.cwd) : cwd } : {},
10181
+ ...verify.env !== void 0 ? { env: verify.env } : {}
10182
+ })) : [];
10183
+ const output = resolveSingleOutputPath(request.output, ctxCwd);
10184
+ return {
10185
+ workflowRunId,
10186
+ key,
10187
+ ...typeof agent === "string" ? { agent } : {},
10188
+ ...typeof task === "string" ? { task } : {},
10189
+ ...cwd !== void 0 ? { cwd } : {},
10190
+ ...typeof request.model === "string" ? { model: request.model } : {},
10191
+ ...typeof request.async === "boolean" ? { async: request.async } : {},
10192
+ ...typeof request.worktree === "boolean" ? { worktree: request.worktree } : {},
10193
+ ...resume !== void 0 ? { resume } : {},
10194
+ ...commands.length > 0 ? { commands } : {},
10195
+ ...output !== void 0 ? { output } : {}
10196
+ };
10197
+ }
10020
10198
  function readWorkflowScriptFile(requestedPath, requestedCwd, runtimeCwd) {
10021
10199
  const scriptPath = path19.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
10022
10200
  let script;
@@ -10450,7 +10628,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
10450
10628
  if (matches.length === 0) return void 0;
10451
10629
  if (matches.length > 1) throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run2) => run2.runId).join(", ")}. Provide a longer id.`);
10452
10630
  const run = matches[0];
10453
- if (run.children.some((child2) => child2.status === "detached")) throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with bg_wait({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
10631
+ if (run.children.some((child2) => child2.status === "detached")) throw new Error(`Foreground run '${run.runId}' is detached for intercom coordination and cannot be revived safely while any child may still be live. Reply to the supervisor request first, then wait with ${waitToolName()}({ id: "${run.runId}" }); use status to recover the result and do not launch a replacement while it remains detached.`);
10454
10632
  if (run.children.length > 1 && params.index === void 0) throw new Error(`Foreground run '${run.runId}' has ${run.children.length} children. Provide index to choose one.`);
10455
10633
  const index = params.index ?? 0;
10456
10634
  if (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
@@ -10459,7 +10637,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
10459
10637
  if (!child.sessionFile) throw new Error(`Foreground run '${run.runId}' child ${index} does not have a persisted session file to resume from.`);
10460
10638
  if (path19.extname(child.sessionFile) !== ".jsonl") throw new Error(`Foreground run '${run.runId}' child ${index} session file must be a .jsonl file: ${child.sessionFile}`);
10461
10639
  const sessionFile = path19.resolve(child.sessionFile);
10462
- if (!fs21.existsSync(sessionFile)) throw new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}`);
10640
+ if (!fs21.existsSync(sessionFile)) throw new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}${missingForkCopyNote(sessionFile)}`);
10463
10641
  return {
10464
10642
  runId: run.runId,
10465
10643
  mode: run.mode,
@@ -10575,8 +10753,7 @@ function persistAsyncWorkflowControlEvent(input) {
10575
10753
  fs21.appendFileSync(path19.join(input.job.asyncDir, "events.jsonl"), `${JSON.stringify(record2)}
10576
10754
  `, "utf-8");
10577
10755
  } catch (error) {
10578
- if (!isStorageCapacityError(error)) throw error;
10579
- console.error("Failed to append async workflow control event while storage is full:", error);
10756
+ reportSessionWarning(input.state, `Failed to record a control event for workflow ${input.job.asyncId}: ${error instanceof Error ? error.message : String(error)}`, "async-workflow-control-event");
10580
10757
  }
10581
10758
  }
10582
10759
  function emitControlNotification(input) {
@@ -10789,6 +10966,7 @@ function appendStepToAsyncChain(input) {
10789
10966
  parentProviderRegistry: input.ctx.modelRegistry,
10790
10967
  currentModel: parentModel,
10791
10968
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
10969
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
10792
10970
  modelScope: discoveredForAppend.modelScope,
10793
10971
  projectTrusted: currentProjectTrusted(input.ctx),
10794
10972
  ...trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {},
@@ -10906,7 +11084,7 @@ function validateNestedSessionFile(run, trustedSessionRoots2, resolveSource, vis
10906
11084
  if (path19.extname(sessionFile) !== ".jsonl") throw new Error(`Nested run '${run.id}' session file must be a .jsonl file: ${sessionFile}`);
10907
11085
  const resolved = path19.resolve(sessionFile);
10908
11086
  if (!path19.isAbsolute(sessionFile)) throw new Error(`Nested run '${run.id}' session file must be absolute: ${sessionFile}`);
10909
- if (!fs21.existsSync(resolved)) throw new Error(`Nested run '${run.id}' session file does not exist: ${sessionFile}`);
11087
+ if (!fs21.existsSync(resolved)) throw new Error(`Nested run '${run.id}' session file does not exist: ${sessionFile}${missingForkCopyNote(resolved)}`);
10910
11088
  const stat = fs21.lstatSync(resolved);
10911
11089
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Nested run '${run.id}' session file is not a regular file: ${sessionFile}`);
10912
11090
  const realSessionFile = fs21.realpathSync(resolved);
@@ -10932,8 +11110,8 @@ function validateNestedSessionFile(run, trustedSessionRoots2, resolveSource, vis
10932
11110
  }
10933
11111
  return realSessionFile;
10934
11112
  }
10935
- function readNestedRecoveryDescriptor(asyncDir, runId, agent) {
10936
- const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
11113
+ function readNestedRecoveryDescriptor(rootRunId, runId, agent) {
11114
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(nestedRunScope(rootRunId).asyncDirRoot, runId);
10937
11115
  if (!recoveryDescriptor) return void 0;
10938
11116
  if (recoveryDescriptor.sourceRunId !== runId) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different source run.`);
10939
11117
  if (recoveryDescriptor.agent !== agent) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different agent.`);
@@ -10947,7 +11125,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots2, resolveSource) {
10947
11125
  if (!agent) throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
10948
11126
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
10949
11127
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
10950
- const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
11128
+ const recoveryDescriptor = asyncDir ? readNestedRecoveryDescriptor(match.match.rootRunId, run.id, agent) : void 0;
10951
11129
  return compactOptional({
10952
11130
  kind: "revive",
10953
11131
  source: "nested",
@@ -11195,6 +11373,7 @@ async function resumeExternalJobFollowUp(input) {
11195
11373
  parentProviderRegistry: input.ctx.modelRegistry,
11196
11374
  currentModel: parentModel,
11197
11375
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
11376
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
11198
11377
  modelScope: input.modelScope,
11199
11378
  modelResponseAliases: input.deps.config.modelResponseAliases,
11200
11379
  interactive: input.ctx.hasUI,
@@ -11363,6 +11542,14 @@ async function resumeAsyncRun(input) {
11363
11542
  details: { mode: "management", results: [] }
11364
11543
  };
11365
11544
  }
11545
+ const requiredLauncher = recoveryDescriptor?.requiredLauncher;
11546
+ if (requiredLauncher) {
11547
+ const refuse = (text) => ({ content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } });
11548
+ if (attachChain) return refuse(`Cannot attach a chain to run '${target.runId}': it was launched with requireLauncher, and appended steps would run inside its runner unchecked.`);
11549
+ const currentDigest = discoveredAgentConfig ? agentDefinitionDigest(discoveredAgentConfig) : void 0;
11550
+ const now = !discoveredAgentConfig ? "is missing" : recoveryDescriptor.launcher !== requiredLauncher.name || discoveredAgentConfig.launcher !== requiredLauncher.name ? `uses launcher '${discoveredAgentConfig.launcher ?? "none"}'` : currentDigest !== requiredLauncher.definitionDigest ? `has digest ${currentDigest}` : void 0;
11551
+ if (now) return refuse(`Cannot resume: run '${target.runId}' was launched requiring launcher '${requiredLauncher.name}' and agent definition ${requiredLauncher.definitionDigest}; agent '${target.agent}' now ${now}.`);
11552
+ }
11366
11553
  if (target.source === "async" && target.runner?.type === "external-cli") {
11367
11554
  const runner = normalizeExternalCliRunnerStatus(target.runner);
11368
11555
  const message = runner ? `External adapter '${runner.adapter.id}' cannot resume: ${runner.nonResumableReason}` : "External runners do not persist Pi sessions and cannot be resumed.";
@@ -11371,7 +11558,7 @@ async function resumeAsyncRun(input) {
11371
11558
  if (input.params.baseRef !== void 0 && "managedWorktree" in target && target.managedWorktree === true) {
11372
11559
  return { content: [{ type: "text", text: "Cannot resume with baseRef: retained managed-worktree children continue in their existing worktree. Start a new worktree run from that base ref instead." }], isError: true, details: { mode: "management", results: [] } };
11373
11560
  }
11374
- if (target.source === "async" && target.managedWorktree && target.asyncDir) {
11561
+ if (target.source === "async" && target.managedWorktree && target.asyncDir && fs21.existsSync(parallelHandoffPath(target.asyncDir))) {
11375
11562
  try {
11376
11563
  const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
11377
11564
  if (path19.resolve(protectedCwd) !== path19.resolve(effectiveCwd)) throw new Error("Retained worktree cwd changed during resume admission.");
@@ -11465,6 +11652,7 @@ async function resumeAsyncRun(input) {
11465
11652
  parentProviderRegistry: input.ctx.modelRegistry,
11466
11653
  currentModel: parentModel2,
11467
11654
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
11655
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
11468
11656
  modelScope,
11469
11657
  projectTrusted: currentProjectTrusted(input.ctx),
11470
11658
  ...trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {},
@@ -11532,7 +11720,7 @@ async function resumeAsyncRun(input) {
11532
11720
  if (target.source === "nested" && !target.recoveryDescriptor) {
11533
11721
  return { content: [{ type: "text", text: `Nested child '${target.runId}' is missing its required recovery identity. Start a new run instead.` }], isError: true, details: { mode: "management", results: [] } };
11534
11722
  }
11535
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: void 0 };
11723
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
11536
11724
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
11537
11725
  const foregroundContract = target.source === "foreground" ? target.resumeContract : void 0;
11538
11726
  const outputSchema = Object.hasOwn(input.params, "outputSchema") ? input.params.outputSchema : Object.hasOwn(foregroundContract ?? {}, "outputSchema") ? foregroundContract?.outputSchema : recoveryDescriptor?.structuredOutputSchema;
@@ -11542,7 +11730,7 @@ async function resumeAsyncRun(input) {
11542
11730
  return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
11543
11731
  }
11544
11732
  if (agentConfig.launcher !== void 0 && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
11545
- return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' was launched with launcher '${agentConfig.launcher}', which is no longer defined in runnerLaunchers in the user subagent config.` }], isError: true, details: { mode: "management", results: [] } };
11733
+ return { content: [{ type: "text", text: `Cannot resume: run '${target.runId}' uses launcher '${agentConfig.launcher}', which is no longer defined in runnerLaunchers in the user subagent config.` }], isError: true, details: { mode: "management", results: [] } };
11546
11734
  }
11547
11735
  const runId = randomUUID6();
11548
11736
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
@@ -11581,6 +11769,7 @@ async function resumeAsyncRun(input) {
11581
11769
  agentConfig,
11582
11770
  recoveryAgentConfig,
11583
11771
  ...recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : void 0) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : void 0) } : {},
11772
+ carriedRequiredLauncher: recoveryDescriptor?.requiredLauncher,
11584
11773
  ctx: compactOptional({
11585
11774
  pi: input.deps.pi,
11586
11775
  cwd: input.requestCwd,
@@ -11591,6 +11780,7 @@ async function resumeAsyncRun(input) {
11591
11780
  parentProviderRegistry: input.ctx.modelRegistry,
11592
11781
  currentModel: parentModel,
11593
11782
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
11783
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
11594
11784
  modelScope,
11595
11785
  projectTrusted: currentProjectTrusted(input.ctx),
11596
11786
  ...trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {},
@@ -11763,6 +11953,7 @@ function createForegroundControlNotifier(data, deps) {
11763
11953
  const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
11764
11954
  if (asyncWorkflow) {
11765
11955
  persistAsyncWorkflowControlEvent({
11956
+ state: deps.state,
11766
11957
  job: asyncWorkflow,
11767
11958
  event: enriched,
11768
11959
  controlConfig: data.controlConfig,
@@ -12216,10 +12407,6 @@ var MAX_TIMER_DELAY_MS = 2147483647;
12216
12407
  function timerDelayOverflowError(name, value) {
12217
12408
  return typeof value === "number" && value > MAX_TIMER_DELAY_MS ? `${name} must be a positive integer no larger than ${MAX_TIMER_DELAY_MS}.` : void 0;
12218
12409
  }
12219
- function resolveConfigDefaultTimeoutMs(raw) {
12220
- if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > MAX_TIMER_DELAY_MS) return void 0;
12221
- return raw;
12222
- }
12223
12410
  function resolveForegroundTimeout(params, defaultTimeoutMs) {
12224
12411
  const rawTimeout = params.timeoutMs;
12225
12412
  const rawMaxRuntime = params.maxRuntimeMs;
@@ -12362,7 +12549,7 @@ function resolveStaticLaunchSummary(input) {
12362
12549
  input.parentModel,
12363
12550
  input.availableModels,
12364
12551
  agentConfig?.modelProvider ?? input.currentProvider,
12365
- modelScopes.length === 0 ? {} : { scope: modelScopes }
12552
+ { scope: modelScopes, knownProviders: input.knownProviders }
12366
12553
  );
12367
12554
  const thinkingOverride = externalRunner ? void 0 : input.thinkingOverrideForTask();
12368
12555
  const thinking = externalRunner ? void 0 : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
@@ -12382,6 +12569,7 @@ function collectStaticLaunchSummaries(input) {
12382
12569
  parentModel: input.parentModel,
12383
12570
  scopedModelIds: input.scopedModelIds,
12384
12571
  availableModels: input.availableModels,
12572
+ knownProviders: input.knownProviders,
12385
12573
  currentProvider: input.currentProvider,
12386
12574
  modelScope: input.modelScope,
12387
12575
  thinkingOverrideForTask: input.thinkingOverrideForTask
@@ -12656,6 +12844,7 @@ async function runAsyncPath(data, deps) {
12656
12844
  parentProviderRegistry: ctx.modelRegistry,
12657
12845
  currentModel: parentModel,
12658
12846
  scopedModelIds: data.scopedModelIds,
12847
+ knownProviders: knownModelProviders(ctx.modelRegistry),
12659
12848
  modelScope: data.modelScope,
12660
12849
  projectTrusted: currentProjectTrusted(ctx),
12661
12850
  ...trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {},
@@ -12705,8 +12894,9 @@ async function runAsyncPath(data, deps) {
12705
12894
  parentModel
12706
12895
  });
12707
12896
  const modelOverride = a.runner?.type === "external-cli" || a.runner?.type === "external-job" ? params.model ?? (externalRunnerWithoutExplicitModel ? void 0 : a.model) : resolveEffectiveSubagentModel(params.model, a.model, parentModel, availableModels, a.modelProvider ?? currentProvider, {
12708
- ...modelScopes.length === 0 ? {} : { scope: modelScopes },
12709
- source: modelOrigin === "explicit" ? "explicit" : "inherited"
12897
+ scope: modelScopes,
12898
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
12899
+ knownProviders: asyncCtx.knownProviders
12710
12900
  });
12711
12901
  const modelOverrideFromParent = modelOrigin === "inherited";
12712
12902
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
@@ -12725,6 +12915,7 @@ async function runAsyncPath(data, deps) {
12725
12915
  requestedCwd: data.requestedCwd,
12726
12916
  machine: params.machine,
12727
12917
  machineCwd: params.machineCwd,
12918
+ requireLauncher: params.requireLauncher,
12728
12919
  maxOutput: params.maxOutput,
12729
12920
  artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
12730
12921
  artifactConfig,
@@ -13132,6 +13323,7 @@ async function runSinglePath(data, deps) {
13132
13323
  const parentModel = data.parentModel;
13133
13324
  const currentProvider = parentModel?.provider;
13134
13325
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
13326
+ const knownProviders = knownModelProviders(ctx.modelRegistry);
13135
13327
  const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel, data.scopedModelIds);
13136
13328
  let task = typeof params.task === "string" ? params.task : "";
13137
13329
  const modelOrigin = resolveModelOrigin({
@@ -13147,8 +13339,9 @@ async function runSinglePath(data, deps) {
13147
13339
  availableModels,
13148
13340
  agentConfig.modelProvider ?? currentProvider,
13149
13341
  {
13150
- ...modelScopes.length === 0 ? {} : { scope: modelScopes },
13151
- source: modelOrigin === "explicit" ? "explicit" : "inherited"
13342
+ scope: modelScopes,
13343
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
13344
+ knownProviders
13152
13345
  }
13153
13346
  );
13154
13347
  const modelOverrideFromParent = modelOrigin === "inherited";
@@ -13257,7 +13450,7 @@ async function runSinglePath(data, deps) {
13257
13450
 
13258
13451
  ` : "";
13259
13452
  task = readsInstruction + task;
13260
- task = injectSingleOutputInstruction(task, outputPath, agentConfig);
13453
+ task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
13261
13454
  let effectiveSkills;
13262
13455
  if (skillOverride === false) {
13263
13456
  effectiveSkills = [];
@@ -13403,6 +13596,7 @@ async function runSinglePath(data, deps) {
13403
13596
  suppressUnchangedDelegationUpdates,
13404
13597
  controlConfig,
13405
13598
  onControlEvent,
13599
+ onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
13406
13600
  intercomSessionName: childIntercomTarget,
13407
13601
  orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : void 0,
13408
13602
  nestedRoute: foregroundControl?.nestedRoute,
@@ -13415,6 +13609,7 @@ async function runSinglePath(data, deps) {
13415
13609
  thinkingCeiling: agentConfig.maxThinking,
13416
13610
  extensionBindings: params.extensionBindings,
13417
13611
  availableModels,
13612
+ knownProviders,
13418
13613
  modelResponseAliases,
13419
13614
  preferredModelProvider: currentProvider,
13420
13615
  modelScope: modelScopes,
@@ -13568,8 +13763,8 @@ async function runSinglePath(data, deps) {
13568
13763
  ${worktreeHandoff.suffix}` : "";
13569
13764
  if (r.detached) {
13570
13765
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
13571
- const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
13572
- const message = r.detachedReason === "intercom coordination" ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}` : r.detachedReason === "user request" ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with bg_wait({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}` : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
13766
+ const blockingRecovery = `${waitToolName()}({ id: "${runId}" }). Use ${statusRecovery}`;
13767
+ const message = r.detachedReason === "intercom coordination" ? `Detached for intercom coordination: ${params.agent}. Reply to the supervisor request first, then wait with ${blockingRecovery}` : r.detachedReason === "user request" ? `Detached at user request: ${params.agent}. The child continues independently. Register a completion wake-up with ${waitToolName()}({ id: "${runId}", nonBlocking: true }), or use ${statusRecovery}` : `Detached before task completion: ${params.agent}. Wait with ${blockingRecovery}`;
13573
13768
  return {
13574
13769
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
13575
13770
  details
@@ -13952,6 +14147,7 @@ async function preflightWorkflowWorktrees(input) {
13952
14147
  input.signal.throwIfAborted();
13953
14148
  }
13954
14149
  function prepareWorkflowLaunchParams(workflowDefaults, childParams, parentWorkflowRunId, workflowKey, options = {}) {
14150
+ if (childParams.requireLauncher !== void 0 || workflowDefaults.requireLauncher !== void 0) throw new Error(REQUIRE_LAUNCHER_SHAPE_ERROR);
13955
14151
  const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
13956
14152
  const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
13957
14153
  workflowDefaults = workflowDefaultsWithoutCapacity;
@@ -14189,9 +14385,10 @@ function savedWorkflowLaunchParams(params) {
14189
14385
  const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
14190
14386
  return saved;
14191
14387
  }
14192
- function workflowLaunchRecord(launch, cwd, scriptDigest) {
14193
- if (launch.source === "structured") return { version: 1, source: "structured", scriptDigest };
14194
- return { version: 1, source: launch.source, params: { ...launch.params, cwd }, scriptDigest };
14388
+ function workflowLaunchRecord(launch, cwd, scriptDigest, sessionId, ceiling) {
14389
+ const owner = { version: 2, scriptDigest, sessionId, ...ceiling ? { admissionCapabilityCeiling: ceiling } : {} };
14390
+ if (launch.source === "structured" || launch.source === "internal") return { ...owner, source: launch.source };
14391
+ return { ...owner, source: launch.source, params: { ...launch.params, cwd } };
14195
14392
  }
14196
14393
  function createSubagentExecutor(deps) {
14197
14394
  const executorDeps = deps;
@@ -14460,7 +14657,7 @@ function createSubagentExecutor(deps) {
14460
14657
  try {
14461
14658
  fs21.mkdirSync(asyncDir, { recursive: true });
14462
14659
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
14463
- if (topLevelAsyncWorkflow && publicWorkflowLaunch) writeWorkflowLaunchRecord(asyncDir, workflowLaunchRecord(publicWorkflowLaunch, workflowCwd, workflowScriptSourceDigest));
14660
+ if (topLevelAsyncWorkflow) writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling2));
14464
14661
  fs21.mkdirSync(DIRS.results, { recursive: true });
14465
14662
  } catch (error) {
14466
14663
  return storageFailure(error);
@@ -14468,6 +14665,7 @@ function createSubagentExecutor(deps) {
14468
14665
  const controller = new AbortController();
14469
14666
  deps2.state.workflowControllers ??= /* @__PURE__ */ new Map();
14470
14667
  deps2.state.workflowChildStops ??= /* @__PURE__ */ new Map();
14668
+ deps2.state.workflowDrains ??= /* @__PURE__ */ new Map();
14471
14669
  deps2.state.workflowControllers.set(workflowRunId, controller);
14472
14670
  workflowCapacity?.markWorkflowStarted();
14473
14671
  if (workflowCapacity) deps2.state.activeAsyncCapacity = getActiveAsyncCapacitySnapshot(currentSessionId, resolveMaxActiveAsyncRunsPerSession(deps2.config.maxActiveAsyncRunsPerSession), { liveWorkflowRunIds: new Set(deps2.state.workflowControllers.keys()), abandonedSlotReleaseAfterMs: resolveAbandonedSlotReleaseAfterMs(deps2.config.capacity?.abandonedSlotReleaseAfterMs) });
@@ -14992,6 +15190,30 @@ Parent action: ${STATUS_ACTION}`,
14992
15190
  if (stop) deps2.state.workflowChildStops?.set(workflowRunId, stop);
14993
15191
  else deps2.state.workflowChildStops?.delete(workflowRunId);
14994
15192
  },
15193
+ registerDrain: (drain) => {
15194
+ if (!drain) deps2.state.workflowDrains?.delete(workflowRunId);
15195
+ else deps2.state.workflowDrains?.set(workflowRunId, () => {
15196
+ if (workflowRunEvidence.drainRequestedAt === void 0) {
15197
+ const previousWorkflow = status.workflow;
15198
+ workflowRunEvidence.drainRequestedAt = Date.now();
15199
+ status.workflow = { ...previousWorkflow ?? { trace: [], emits: [], console: [] }, drainRequestedAt: workflowRunEvidence.drainRequestedAt };
15200
+ let saved = false;
15201
+ try {
15202
+ persist();
15203
+ saved = runPersistence.pendingCount() === 0;
15204
+ } catch (error) {
15205
+ console.error(`Failed to save the drain request for async workflow '${workflowRunId}':`, error);
15206
+ }
15207
+ if (!saved) {
15208
+ delete workflowRunEvidence.drainRequestedAt;
15209
+ status.workflow = previousWorkflow;
15210
+ persist({ tolerateStatusWriteFailure: true });
15211
+ return { ok: false };
15212
+ }
15213
+ }
15214
+ return { ok: true, started: drain(() => queueMicrotask(() => controller.abort(new Error("Workflow drained: started children finished; no new children were started.")))) };
15215
+ });
15216
+ },
14995
15217
  ...workflowState2 ? { state: workflowState2 } : {},
14996
15218
  onTrace: updateTrace,
14997
15219
  onChildSettled: (notification) => {
@@ -15100,7 +15322,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15100
15322
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
15101
15323
  });
15102
15324
  let preparedChildParams;
15103
- const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, () => {
15325
+ const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, async () => {
15104
15326
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
15105
15327
  { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults2, childParams, parentWorkflowRunId: workflowRunId, workflowKey: key, ctxCwd: parentCwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath2, configuredOutputBaseDir: configuredOutputBaseDir2, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults2.agentScope, outputOverride: childOutputOverrides2.get(key), outputClaimPath: childOutputClaimPaths2.get(key), options: { missionDetached: detachWorkflowChildMissions, awaitDetachedChild: true, runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt2, capabilityCeiling: workflowCapabilityCeiling2 } }), runFanoutAdmitted: admission.admitted },
15106
15328
  missionBinding2,
@@ -15109,6 +15331,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15109
15331
  inheritedNestedRoute(deps2)?.rootRunId
15110
15332
  );
15111
15333
  preparedChildParams = childRequest;
15334
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
15335
+ if (launchRefusal) return buildRequestedModeError(childRequest, launchRefusal);
15112
15336
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
15113
15337
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
15114
15338
  workflowLaunchObservers.set(childRequest, (launch) => {
@@ -15137,6 +15361,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15137
15361
  step2.currentToolArgs = progress.currentToolArgs;
15138
15362
  step2.currentToolStartedAt = progress.currentToolStartedAt;
15139
15363
  step2.currentPath = progress.currentPath;
15364
+ step2.progressText = progress.progressText;
15365
+ step2.progressUpdatedAt = progress.progressUpdatedAt;
15140
15366
  step2.recentTools = progress.recentTools.map((tool) => ({ ...tool }));
15141
15367
  step2.recentOutput = [...progress.recentOutput];
15142
15368
  step2.turnCount = progress.turnCount;
@@ -15383,7 +15609,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15383
15609
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
15384
15610
  });
15385
15611
  let preparedChildParams;
15386
- const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, () => {
15612
+ const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, async () => {
15387
15613
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
15388
15614
  { ...prepareWorkflowChildLaunchParams({ workflowDefaults: workflowChildDefaults, childParams: delegatedWorkflowPermit ? { ...childParams, async: false } : childParams, parentWorkflowRunId: foregroundWorkflowRunId, workflowKey: key, ctxCwd: ctx.cwd, workflowCwd, artifactsDir: workflowArtifactsDir, aggregateOutputPath: workflowAggregateOutputPath, configuredOutputBaseDir, discoverAgents: discoverWorkflowAgents, agents: workflowAgents, workflowAgentScope: workflowChildDefaults.agentScope, outputOverride: childOutputOverrides.get(key), outputClaimPath: childOutputClaimPaths.get(key), options: { missionDetached: detachWorkflowChildMissions, suppressRoutineResultIntercom: chatProgress.mode === "live-card", runFanoutBudget: workflowFanoutBudget, parentDeadlineAt: workflowDeadlineAt, capabilityCeiling: workflowCapabilityCeiling } }), runFanoutAdmitted: admission.admitted },
15389
15615
  missionBinding2,
@@ -15392,6 +15618,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15392
15618
  inheritedNestedRoute(deps2)?.rootRunId
15393
15619
  );
15394
15620
  preparedChildParams = childRequest;
15621
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
15622
+ if (launchRefusal) return buildRequestedModeError(childRequest, launchRefusal);
15395
15623
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
15396
15624
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
15397
15625
  if (delegatedWorkflowPermit) {
@@ -16095,6 +16323,7 @@ ${item.text}` } : item)
16095
16323
  }
16096
16324
  if (action === "stop") {
16097
16325
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
16326
+ if (paramsWithResolvedCwd.drain && paramsWithResolvedCwd.childId !== void 0) return { content: [{ type: "text", text: "action='stop' drain applies to a whole workflow; omit childId." }], isError: true, details: { mode: "management", results: [] } };
16098
16327
  const workflowRunId = targetRunId && paramsWithResolvedCwd.childId !== void 0 ? resolveLiveWorkflowRunId(deps2, targetRunId) : void 0;
16099
16328
  if (workflowRunId && paramsWithResolvedCwd.childId !== void 0) {
16100
16329
  const stopChild = deps2.state.workflowChildStops?.get(workflowRunId);
@@ -16134,7 +16363,7 @@ ${item.text}` } : item)
16134
16363
  if (paramsWithResolvedCwd.dir) {
16135
16364
  try {
16136
16365
  const location = resolveAsyncRunLocation(paramsWithResolvedCwd, DIRS.async, DIRS.results);
16137
- const stopResult2 = stopAsyncRun(deps2.state, location.resolvedId ?? targetRunId ?? path19.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps2.kill, location, paramsWithResolvedCwd.childId);
16366
+ const stopResult2 = stopAsyncRun(deps2.state, location.resolvedId ?? targetRunId ?? path19.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps2.kill, location, paramsWithResolvedCwd.childId, paramsWithResolvedCwd.drain);
16138
16367
  return stopResult2 ?? { content: [{ type: "text", text: `No running or queued async run was found for '${targetRunId ?? paramsWithResolvedCwd.dir}'.` }], isError: true, details: { mode: "management", results: [] } };
16139
16368
  } catch (error) {
16140
16369
  const text = error instanceof Error ? error.message : String(error);
@@ -16155,7 +16384,8 @@ ${item.text}` } : item)
16155
16384
  resolved?.kind === "async" ? resolved.id : targetRunId,
16156
16385
  deps2.kill,
16157
16386
  resolved?.kind === "async" ? resolved.location : void 0,
16158
- paramsWithResolvedCwd.childId
16387
+ paramsWithResolvedCwd.childId,
16388
+ paramsWithResolvedCwd.drain
16159
16389
  );
16160
16390
  if (stopResult) return stopResult;
16161
16391
  return {
@@ -16365,6 +16595,12 @@ ${item.text}` } : item)
16365
16595
  const launcherError = agent ? resolveAgentRunnerLauncher(agent, deps2.config.runnerLaunchers, effectiveParams.machine ?? agent.machine).error : void 0;
16366
16596
  if (launcherError) return buildRequestedModeError(effectiveParams, launcherError);
16367
16597
  }
16598
+ if (effectiveParams.requireLauncher !== void 0) {
16599
+ if (!effectiveParams.requireLauncher || typeof effectiveParams.requireLauncher !== "object") return buildRequestedModeError(effectiveParams, "requireLauncher must be { name, definitionDigest }.");
16600
+ if (!hasSingle || effectiveParams.resume !== void 0 || effectiveParams.workflowParentRunId !== void 0) return buildRequestedModeError(effectiveParams, REQUIRE_LAUNCHER_SHAPE_ERROR);
16601
+ const required = selectedAgents[0] ? checkRequiredRunnerLauncher(selectedAgents[0], selectedAgents[0].launcher, effectiveParams.requireLauncher) : void 0;
16602
+ if (required?.error) return buildRequestedModeError(effectiveParams, required.error);
16603
+ }
16368
16604
  if (effectiveAsync && hasSingle && effectiveParams.resume === void 0 && effectiveParams.worktree === true) {
16369
16605
  try {
16370
16606
  await preflightWorktreeSource(effectiveCwd, { signal });
@@ -16640,6 +16876,7 @@ ${item.text}` } : item)
16640
16876
  parentModel: requestParentModel,
16641
16877
  scopedModelIds: scopedModelIdsFromContext(ctx),
16642
16878
  availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
16879
+ knownProviders: knownModelProviders(ctx.modelRegistry),
16643
16880
  currentProvider: requestParentModel?.provider,
16644
16881
  modelScope,
16645
16882
  thinkingOverrideForTask,
@@ -16919,7 +17156,6 @@ export {
16919
17156
  promptAuditRedoParams,
16920
17157
  readNestedRecoveryDescriptor,
16921
17158
  removeForegroundControlIfIdle,
16922
- resolveConfigDefaultTimeoutMs,
16923
17159
  resolveForegroundTimeout,
16924
17160
  resolveRevivalControlConfig,
16925
17161
  resolveSingleAgentLaunchTimeout,