@xzzpig/pi-subagents 0.24.2 → 0.25.1

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 +37 -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-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  8. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  9. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  10. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  11. package/bundle/{chunk-RU522D5W.js → chunk-FQPV4O6C.js} +183 -28
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  14. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  15. package/bundle/{chunk-CYY5UMJU.js → chunk-IXCEOEJT.js} +411 -249
  16. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  17. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  18. package/bundle/{chunk-224WMDIV.js → chunk-JUYNN63E.js} +350 -123
  19. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  20. package/bundle/{chunk-XWWUDWUW.js → chunk-KRNBJPZ2.js} +670 -400
  21. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  22. package/bundle/chunk-LYKG4FKH.js +523 -0
  23. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  24. package/bundle/{chunk-JEA2ZKUA.js → chunk-MMJQMPOK.js} +37 -165
  25. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  26. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  27. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  28. package/bundle/{chunk-4UH4WS4G.js → chunk-SNDCIJMK.js} +23 -12
  29. package/bundle/{chunk-O4D5PBVI.js → chunk-TM2K53NX.js} +3 -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-BQ2OAB4Q.js → chunk-WWDUNXSE.js} +67 -30
  34. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  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/package.json +2 -2
  49. package/skills/pi-subagents/SKILL.md +15 -6
  50. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  51. package/src/agents/agent-management.d.ts +1 -0
  52. package/src/agents/agent-management.js +46 -18
  53. package/src/agents/agent-memory.d.ts +1 -4
  54. package/src/agents/agent-memory.js +1 -4
  55. package/src/agents/agent-serializer.d.ts +2 -0
  56. package/src/agents/agent-serializer.js +1 -1
  57. package/src/agents/agents.d.ts +2 -3
  58. package/src/agents/agents.js +46 -20
  59. package/src/agents/frontmatter.js +1 -8
  60. package/src/agents/global-npm-root.d.ts +1 -0
  61. package/src/agents/global-npm-root.js +11 -3
  62. package/src/agents/skills.d.ts +0 -3
  63. package/src/agents/skills.js +0 -3
  64. package/src/api/preflight.d.ts +3 -1
  65. package/src/api/preflight.js +2 -0
  66. package/src/extension/config.d.ts +1 -0
  67. package/src/extension/config.js +13 -1
  68. package/src/extension/herdr-pi-bridge.js +10 -2
  69. package/src/extension/index.d.ts +0 -13
  70. package/src/extension/index.js +51 -37
  71. package/src/extension/public-execution.d.ts +1 -0
  72. package/src/extension/public-execution.js +4 -0
  73. package/src/extension/reply-workflow-script.js +24 -4
  74. package/src/extension/schemas.d.ts +12 -3
  75. package/src/extension/schemas.js +7 -3
  76. package/src/extension/session-switch.d.ts +25 -0
  77. package/src/extension/session-switch.js +138 -0
  78. package/src/extension/subagent-guide.d.ts +1 -1
  79. package/src/extension/subagent-guide.js +1 -1
  80. package/src/extension/subagent-launch-tool.d.ts +25 -0
  81. package/src/extension/subagent-launch-tool.js +48 -0
  82. package/src/extension/tool-activation.js +55 -15
  83. package/src/extension/tool-description.d.ts +1 -1
  84. package/src/extension/tool-description.js +14 -8
  85. package/src/inspectors/herdr/actions.d.ts +0 -1
  86. package/src/inspectors/herdr/actions.js +0 -1
  87. package/src/inspectors/session-roots-codec.d.ts +0 -1
  88. package/src/inspectors/session-roots-codec.js +0 -1
  89. package/src/inspectors/tmux/actions.d.ts +0 -1
  90. package/src/inspectors/tmux/actions.js +0 -1
  91. package/src/integrations/herdr-status.js +3 -8
  92. package/src/intercom/native-supervisor-channel.js +65 -9
  93. package/src/runs/background/async-execution.d.ts +7 -10
  94. package/src/runs/background/async-execution.js +66 -29
  95. package/src/runs/background/async-job-tracker.js +12 -0
  96. package/src/runs/background/async-resume.d.ts +2 -1
  97. package/src/runs/background/async-resume.js +114 -40
  98. package/src/runs/background/async-retention.d.ts +0 -2
  99. package/src/runs/background/async-retention.js +17 -6
  100. package/src/runs/background/async-status.d.ts +2 -0
  101. package/src/runs/background/async-status.js +4 -0
  102. package/src/runs/background/auto-drain.js +2 -1
  103. package/src/runs/background/boot-id.d.ts +1 -3
  104. package/src/runs/background/boot-id.js +1 -3
  105. package/src/runs/background/completion-batcher.d.ts +3 -4
  106. package/src/runs/background/completion-batcher.js +2 -3
  107. package/src/runs/background/control-channel.d.ts +0 -6
  108. package/src/runs/background/control-channel.js +0 -6
  109. package/src/runs/background/fleet-view.js +2 -3
  110. package/src/runs/background/notify.d.ts +0 -2
  111. package/src/runs/background/notify.js +0 -2
  112. package/src/runs/background/result-watcher.d.ts +1 -0
  113. package/src/runs/background/result-watcher.js +59 -29
  114. package/src/runs/background/resume-guidance.js +4 -2
  115. package/src/runs/background/retained-children.js +2 -1
  116. package/src/runs/background/run-child-session.d.ts +2 -3
  117. package/src/runs/background/run-child-session.js +5 -8
  118. package/src/runs/background/run-status.js +9 -7
  119. package/src/runs/background/runner-aliases.js +15 -0
  120. package/src/runs/background/scheduled-runs.d.ts +3 -1
  121. package/src/runs/background/scheduled-runs.js +13 -16
  122. package/src/runs/background/steering.d.ts +2 -11
  123. package/src/runs/background/steering.js +11 -6
  124. package/src/runs/background/subagent-runner.d.ts +2 -6
  125. package/src/runs/background/subagent-runner.js +88 -70
  126. package/src/runs/background/subagent-wait.js +12 -15
  127. package/src/runs/background/wait-config.d.ts +2 -0
  128. package/src/runs/background/wait-config.js +17 -3
  129. package/src/runs/background/wait-subscriptions.js +124 -12
  130. package/src/runs/background/wait-tool.js +4 -2
  131. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  132. package/src/runs/background/workflow-terminal-proof.js +0 -1
  133. package/src/runs/foreground/async-steering-action.js +24 -9
  134. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  135. package/src/runs/foreground/async-stop-action.js +9 -1
  136. package/src/runs/foreground/execution.d.ts +0 -3
  137. package/src/runs/foreground/execution.js +68 -84
  138. package/src/runs/foreground/fork-tool-result-handler.d.ts +60 -0
  139. package/src/runs/foreground/fork-tool-result-handler.js +83 -0
  140. package/src/runs/foreground/prompt-audit.js +1 -0
  141. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  142. package/src/runs/foreground/subagent-executor.js +164 -49
  143. package/src/runs/shared/acceptance.js +69 -26
  144. package/src/runs/shared/async-status-projection.d.ts +2 -0
  145. package/src/runs/shared/async-status-projection.js +10 -0
  146. package/src/runs/shared/child-commands.js +15 -2
  147. package/src/runs/shared/child-hooks.d.ts +1 -7
  148. package/src/runs/shared/child-hooks.js +13 -5
  149. package/src/runs/shared/child-launch.js +6 -2
  150. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  151. package/src/runs/shared/child-session.d.ts +6 -5
  152. package/src/runs/shared/child-session.js +85 -38
  153. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  154. package/src/runs/shared/child-tool-plan.js +0 -1
  155. package/src/runs/shared/claude-code-adapter.js +11 -0
  156. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  157. package/src/runs/shared/external-cli-contract.js +18 -13
  158. package/src/runs/shared/external-cli-runner.js +26 -6
  159. package/src/runs/shared/herdr-connection.js +2 -1
  160. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  161. package/src/runs/shared/herdr-pane-host.js +17 -1
  162. package/src/runs/shared/herdr-placed-run.js +51 -24
  163. package/src/runs/shared/lane-metadata.d.ts +0 -1
  164. package/src/runs/shared/lane-metadata.js +0 -1
  165. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  166. package/src/runs/shared/mcp-config-sources.js +1 -1
  167. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  168. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  169. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  170. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  171. package/src/runs/shared/model-resolution.d.ts +20 -5
  172. package/src/runs/shared/model-resolution.js +55 -50
  173. package/src/runs/shared/model-scope.d.ts +1 -5
  174. package/src/runs/shared/model-scope.js +1 -5
  175. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  176. package/src/runs/shared/mutation-evidence.js +52 -7
  177. package/src/runs/shared/nested-events.d.ts +1 -0
  178. package/src/runs/shared/nested-events.js +1 -1
  179. package/src/runs/shared/parallel-utils.d.ts +0 -1
  180. package/src/runs/shared/permissions.js +5 -3
  181. package/src/runs/shared/placement-host.d.ts +5 -1
  182. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  183. package/src/runs/shared/rex-pane-host.js +0 -2
  184. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  185. package/src/runs/shared/run-launch-folder.js +21 -0
  186. package/src/runs/shared/runner-launcher.d.ts +12 -1
  187. package/src/runs/shared/runner-launcher.js +16 -0
  188. package/src/runs/shared/single-output.d.ts +3 -3
  189. package/src/runs/shared/single-output.js +5 -3
  190. package/src/runs/shared/structured-output.d.ts +8 -0
  191. package/src/runs/shared/structured-output.js +40 -5
  192. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  193. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  194. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  195. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  196. package/src/runs/shared/tool-timeout.js +2 -1
  197. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  198. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  199. package/src/runs/shared/worktree.d.ts +3 -0
  200. package/src/runs/shared/worktree.js +20 -0
  201. package/src/shared/artifacts.d.ts +1 -0
  202. package/src/shared/artifacts.js +132 -22
  203. package/src/shared/capacity-resilient-json.d.ts +1 -1
  204. package/src/shared/child-cache-retention.d.ts +1 -2
  205. package/src/shared/child-cache-retention.js +1 -2
  206. package/src/shared/fleet-transcript-reader.d.ts +64 -0
  207. package/src/shared/fleet-transcript-reader.js +376 -0
  208. package/src/shared/formatters.d.ts +0 -18
  209. package/src/shared/formatters.js +0 -18
  210. package/src/shared/pruned-fork.js +2 -2
  211. package/src/shared/reported-progress.d.ts +1 -0
  212. package/src/shared/reported-progress.js +12 -0
  213. package/src/shared/session-succession.d.ts +16 -1
  214. package/src/shared/session-succession.js +41 -2
  215. package/src/shared/session-warnings.d.ts +7 -0
  216. package/src/shared/session-warnings.js +26 -0
  217. package/src/shared/settings.d.ts +0 -23
  218. package/src/shared/settings.js +3 -35
  219. package/src/shared/status-format.d.ts +1 -0
  220. package/src/shared/status-format.js +1 -1
  221. package/src/shared/types.d.ts +108 -59
  222. package/src/shared/types.js +0 -12
  223. package/src/shared/utils.d.ts +3 -15
  224. package/src/shared/utils.js +4 -22
  225. package/src/shared/wait-tool-name.d.ts +8 -0
  226. package/src/shared/wait-tool-name.js +13 -0
  227. package/src/slash/slash-commands.js +2 -1
  228. package/src/slash/subagent-cost.d.ts +3 -2
  229. package/src/slash/subagent-cost.js +22 -3
  230. package/src/slash/subagents-admin.js +0 -1
  231. package/src/tui/fleet-native-transcript.js +1 -1
  232. package/src/tui/fleet-status.d.ts +0 -5
  233. package/src/tui/fleet-status.js +4 -24
  234. package/src/tui/fleet-transcript.d.ts +1 -57
  235. package/src/tui/fleet-transcript.js +4 -370
  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-MMJQMPOK.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-CYY5UMJU.js";
122
+ } from "./chunk-IXCEOEJT.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";
@@ -4229,6 +4301,293 @@ function formatPartialOutput(text, cause) {
4229
4301
  ${text}`;
4230
4302
  }
4231
4303
 
4304
+ // src/runs/shared/long-running-guard.ts
4305
+ var MUTATING_BASH_PATTERNS = [
4306
+ /(^|[;&|()\s])rm\s+/,
4307
+ /(^|[;&|()\s])mv\s+/,
4308
+ /(^|[;&|()\s])cp\s+/,
4309
+ /(^|[;&|()\s])mkdir\s+/,
4310
+ /(^|[;&|()\s])touch\s+/,
4311
+ /(^|[;&|()\s])git\s+apply\b/,
4312
+ /(^|[;&|()\s])patch\s+/,
4313
+ /(^|[;&|()\s])sed\s+[^\n;&|]*\s-i\b/,
4314
+ /(^|[;&|()\s])perl\s+[^\n;&|]*\s-pi\b/,
4315
+ /(^|[;&|()]|\n)\s*tee\s+[^|&;]+/,
4316
+ /\b(writeFile|writeFileSync|appendFile|appendFileSync)\b/,
4317
+ /\bwrite_text\s*\(/,
4318
+ /\bopen\s*\([^)]*,\s*["'][wa]/
4319
+ ];
4320
+ function resolveCurrentPath(toolName, args) {
4321
+ if (!toolName || !args) return void 0;
4322
+ const direct = ["path", "file", "filename", "target", "cwd"];
4323
+ for (const key of direct) {
4324
+ const value = args[key];
4325
+ if (typeof value === "string" && value.trim()) return value.trim();
4326
+ }
4327
+ if (toolName === "bash") {
4328
+ const command = typeof args.command === "string" ? args.command : void 0;
4329
+ if (!command) return void 0;
4330
+ return firstWrittenFile(command);
4331
+ }
4332
+ return void 0;
4333
+ }
4334
+ function readShellWord(command, start) {
4335
+ let word = "";
4336
+ let quote;
4337
+ let i = start;
4338
+ for (; i < command.length; i++) {
4339
+ const char = command[i];
4340
+ if (quote) {
4341
+ if (char === quote) quote = void 0;
4342
+ else if (char === "\\" && quote === '"' && /[$`"\\\n]/.test(command[i + 1] ?? "")) word += command[++i];
4343
+ else word += char;
4344
+ continue;
4345
+ }
4346
+ if (char === "'" || char === '"') quote = char;
4347
+ else if (char === "\\" && i + 1 < command.length) word += command[++i];
4348
+ else if (/[\s;&|()<>]/.test(char)) break;
4349
+ else word += char;
4350
+ }
4351
+ return { word, end: i };
4352
+ }
4353
+ function firstWrittenFile(command) {
4354
+ let quote;
4355
+ for (let i = 0; i < command.length; i++) {
4356
+ const char = command[i];
4357
+ if (quote) {
4358
+ if (char === quote) quote = void 0;
4359
+ else if (char === "\\" && quote === '"') i++;
4360
+ continue;
4361
+ }
4362
+ if (char === "'" || char === '"') {
4363
+ quote = char;
4364
+ continue;
4365
+ }
4366
+ if (char === "\\") {
4367
+ i++;
4368
+ continue;
4369
+ }
4370
+ const isTee = command.startsWith("tee", i) && (i === 0 || /[\s|;&(]/.test(command[i - 1])) && /\s/.test(command[i + 3] ?? "");
4371
+ if (char !== ">" && !isTee) continue;
4372
+ let cursor = isTee ? i + 3 : command[i + 1] === ">" ? i + 2 : i + 1;
4373
+ for (; ; ) {
4374
+ while (cursor < command.length && /[ \t]/.test(command[cursor])) cursor++;
4375
+ if (command[cursor] === "&") break;
4376
+ const { word, end } = readShellWord(command, cursor);
4377
+ cursor = end;
4378
+ if (word && word !== "/dev/null" && !(isTee && word.startsWith("-"))) return word;
4379
+ if (!isTee || !word) break;
4380
+ }
4381
+ i = cursor - 1;
4382
+ }
4383
+ return void 0;
4384
+ }
4385
+ function hasUnquotedFileRedirection(command) {
4386
+ let inSingle = false;
4387
+ let inDouble = false;
4388
+ for (let i = 0; i < command.length; i++) {
4389
+ const char = command[i];
4390
+ if (char === "'" && !inDouble) {
4391
+ inSingle = !inSingle;
4392
+ continue;
4393
+ }
4394
+ if (char === '"' && !inSingle) {
4395
+ inDouble = !inDouble;
4396
+ continue;
4397
+ }
4398
+ if (inSingle || inDouble) continue;
4399
+ if (char !== ">") continue;
4400
+ if (command[i - 1] === "-") continue;
4401
+ const isDouble = command[i + 1] === ">";
4402
+ let cursor = i + (isDouble ? 2 : 1);
4403
+ while (cursor < command.length && /\s/.test(command[cursor])) cursor++;
4404
+ if (cursor >= command.length) continue;
4405
+ const targetStart = command[cursor];
4406
+ if (targetStart === "&" || targetStart === "|" || targetStart === ";") continue;
4407
+ if (targetStart === "(" || targetStart === ")") continue;
4408
+ if (/^\/dev\/null(?=$|[\s;&|()])/.test(command.slice(cursor))) continue;
4409
+ return true;
4410
+ }
4411
+ return false;
4412
+ }
4413
+ function unquotedShellText(command) {
4414
+ let inSingle = false;
4415
+ let inDouble = false;
4416
+ let escaped = false;
4417
+ let result2 = "";
4418
+ for (const char of command) {
4419
+ if (escaped) {
4420
+ result2 += inSingle || inDouble ? "_" : char;
4421
+ escaped = false;
4422
+ continue;
4423
+ }
4424
+ if (char === "\\" && !inSingle) {
4425
+ escaped = true;
4426
+ result2 += inDouble ? "_" : char;
4427
+ continue;
4428
+ }
4429
+ if (char === "'" && !inDouble) {
4430
+ inSingle = !inSingle;
4431
+ continue;
4432
+ }
4433
+ if (char === '"' && !inSingle) {
4434
+ inDouble = !inDouble;
4435
+ continue;
4436
+ }
4437
+ result2 += inSingle || inDouble ? "_" : char;
4438
+ }
4439
+ return result2;
4440
+ }
4441
+ function hasMutatingGitCommand(command) {
4442
+ const unquoted = unquotedShellText(command);
4443
+ for (const segment of unquoted.split(/(?:&&|\|\||[;|()\n])/)) {
4444
+ const trimmed = segment.trim();
4445
+ if (!trimmed || /^(?:echo|printf)\b/.test(trimmed)) continue;
4446
+ if (/^git\s+(?:(?:(?:-C|--git-dir|--work-tree)\s+\S+|(?:--git-dir|--work-tree)=\S+|--paginate)\s+)*(?:add|commit|push)\b/.test(trimmed)) return true;
4447
+ }
4448
+ return false;
4449
+ }
4450
+ function isMutatingBashCommand(command) {
4451
+ return hasUnquotedFileRedirection(command) || hasMutatingGitCommand(command) || MUTATING_BASH_PATTERNS.some((pattern) => pattern.test(command));
4452
+ }
4453
+ function isMutatingTool(toolName, args, mutationTools) {
4454
+ if (!toolName) return false;
4455
+ if (mutationTools?.includes(toolName)) return true;
4456
+ if (toolName === "edit" || toolName === "write") return true;
4457
+ if (toolName === "cursor") {
4458
+ const activityTitle = typeof args?.activityTitle === "string" ? args.activityTitle : "";
4459
+ return /^Cursor (?:edit|write)\b/i.test(activityTitle);
4460
+ }
4461
+ if (toolName !== "bash") return false;
4462
+ const command = typeof args?.command === "string" ? args.command : "";
4463
+ if (!command.trim()) return false;
4464
+ return isMutatingBashCommand(command);
4465
+ }
4466
+ function didMutatingToolFail(result2) {
4467
+ return result2.isError === true;
4468
+ }
4469
+ function nextLongRunningTrigger(config, metrics) {
4470
+ if (metrics.now - metrics.startedAt >= config.activeNoticeAfterMs) return "time_threshold";
4471
+ if (config.activeNoticeAfterTurns !== void 0 && metrics.turns >= config.activeNoticeAfterTurns) return "turn_threshold";
4472
+ if (config.activeNoticeAfterTokens !== void 0 && metrics.tokens >= config.activeNoticeAfterTokens) return "token_threshold";
4473
+ return void 0;
4474
+ }
4475
+ function resetMutatingFailureState(state) {
4476
+ state.consecutiveFailures = 0;
4477
+ state.lastFailureAt = void 0;
4478
+ state.recentFailures = [];
4479
+ state.lastMutatingPath = void 0;
4480
+ state.repeatedPathFailures = 0;
4481
+ }
4482
+ function createMutatingFailureState() {
4483
+ return {
4484
+ consecutiveFailures: 0,
4485
+ recentFailures: [],
4486
+ repeatedPathFailures: 0
4487
+ };
4488
+ }
4489
+ function recordMutatingFailure(state, input, windowMs) {
4490
+ if (state.lastFailureAt === void 0 || input.ts - state.lastFailureAt > windowMs) {
4491
+ state.consecutiveFailures = 0;
4492
+ state.recentFailures = [];
4493
+ state.repeatedPathFailures = 0;
4494
+ state.lastMutatingPath = void 0;
4495
+ }
4496
+ state.lastFailureAt = input.ts;
4497
+ state.consecutiveFailures += 1;
4498
+ if (input.path && state.lastMutatingPath === input.path) {
4499
+ state.repeatedPathFailures += 1;
4500
+ } else if (input.path) {
4501
+ state.lastMutatingPath = input.path;
4502
+ state.repeatedPathFailures = 1;
4503
+ }
4504
+ state.recentFailures.push(input);
4505
+ if (state.recentFailures.length > 3) state.recentFailures.shift();
4506
+ }
4507
+ function shouldEscalateMutatingFailures(state, threshold) {
4508
+ return state.consecutiveFailures >= threshold || state.repeatedPathFailures >= threshold;
4509
+ }
4510
+ function summarizeRecentMutatingFailures(state) {
4511
+ if (state.recentFailures.length === 0) return void 0;
4512
+ return state.recentFailures.map((entry) => `${entry.tool}${entry.path ? `(${entry.path})` : ""}: ${entry.error}`).join(" | ");
4513
+ }
4514
+
4515
+ // src/runs/foreground/fork-tool-result-handler.ts
4516
+ var MAX_HANDLED_TOOL_RESULT_IDS = 1024;
4517
+ function createToolResultHandler(deps) {
4518
+ const {
4519
+ result: result2,
4520
+ progress,
4521
+ options,
4522
+ agentName,
4523
+ handledToolResultIds,
4524
+ pendingToolResultsByCallId,
4525
+ pendingToolState,
4526
+ mutatingFailures,
4527
+ mutatingFailureWindowMs,
4528
+ controlConfig,
4529
+ appendRecentOutput: appendRecentOutput2,
4530
+ fireUpdate,
4531
+ emitNeedsAttention
4532
+ } = deps;
4533
+ return (message, completion, now) => {
4534
+ const rawCallId = completion.toolCallId ?? message.toolCallId;
4535
+ const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : void 0;
4536
+ if (callId) {
4537
+ if (handledToolResultIds.has(callId)) return;
4538
+ if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
4539
+ const oldest = handledToolResultIds.values().next().value;
4540
+ if (typeof oldest === "string") handledToolResultIds.delete(oldest);
4541
+ }
4542
+ handledToolResultIds.add(callId);
4543
+ }
4544
+ result2.messages.push(message);
4545
+ const resultText = extractTextFromContent(message.content);
4546
+ const keyedSnapshot = callId ? pendingToolResultsByCallId.get(callId) : void 0;
4547
+ if (callId && keyedSnapshot) pendingToolResultsByCallId.delete(callId);
4548
+ const toolSnapshot = keyedSnapshot ?? pendingToolState.current;
4549
+ if (!keyedSnapshot || pendingToolState.current === keyedSnapshot) pendingToolState.current = void 0;
4550
+ const resultToolName = completion.toolName ?? message.toolName;
4551
+ const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0 ? resultToolName : void 0) ?? toolSnapshot?.tool;
4552
+ const budgetBlocked = Boolean(options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool));
4553
+ if (options.toolBudget && budgetBlocked) {
4554
+ result2.toolBudgetBlocked = true;
4555
+ result2.toolBudget = toolBudgetState(
4556
+ options.toolBudget,
4557
+ Math.max(progress.toolCount, options.toolBudget.hard + 1),
4558
+ blockedTool
4559
+ );
4560
+ }
4561
+ appendRecentOutput2(progress, resultText.split("\n").slice(-10));
4562
+ const messageToolName = message.toolName;
4563
+ if (message.isError !== true && messageToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
4564
+ progress.progressText = toolSnapshot.progressText;
4565
+ progress.progressUpdatedAt = now;
4566
+ }
4567
+ if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
4568
+ recordMutatingFailure(mutatingFailures, {
4569
+ tool: toolSnapshot.tool,
4570
+ path: toolSnapshot.path,
4571
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
4572
+ ts: now
4573
+ }, mutatingFailureWindowMs);
4574
+ if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
4575
+ emitNeedsAttention(now, {
4576
+ message: `${agentName} needs attention after repeated mutating tool failures`,
4577
+ reason: "tool_failures",
4578
+ currentTool: toolSnapshot.tool,
4579
+ currentPath: toolSnapshot.path,
4580
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : void 0,
4581
+ recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures)
4582
+ });
4583
+ }
4584
+ } else if (toolSnapshot?.mutates) {
4585
+ resetMutatingFailureState(mutatingFailures);
4586
+ }
4587
+ fireUpdate();
4588
+ };
4589
+ }
4590
+
4232
4591
  // src/shared/jsonl-writer.ts
4233
4592
  import * as fs11 from "node:fs";
4234
4593
  var DEFAULT_MAX_JSONL_BYTES = 50 * 1024 * 1024;
@@ -4907,217 +5266,6 @@ function planAbortRecovery(input) {
4907
5266
  return { action: "resume", prompt: ABORT_RECOVERY_PROMPT };
4908
5267
  }
4909
5268
 
4910
- // src/runs/shared/long-running-guard.ts
4911
- var MUTATING_BASH_PATTERNS = [
4912
- /(^|[;&|()\s])rm\s+/,
4913
- /(^|[;&|()\s])mv\s+/,
4914
- /(^|[;&|()\s])cp\s+/,
4915
- /(^|[;&|()\s])mkdir\s+/,
4916
- /(^|[;&|()\s])touch\s+/,
4917
- /(^|[;&|()\s])git\s+apply\b/,
4918
- /(^|[;&|()\s])patch\s+/,
4919
- /(^|[;&|()\s])sed\s+[^\n;&|]*\s-i\b/,
4920
- /(^|[;&|()\s])perl\s+[^\n;&|]*\s-pi\b/,
4921
- /(^|[;&|()]|\n)\s*tee\s+[^|&;]+/,
4922
- /\b(writeFile|writeFileSync|appendFile|appendFileSync)\b/,
4923
- /\bwrite_text\s*\(/,
4924
- /\bopen\s*\([^)]*,\s*["'][wa]/
4925
- ];
4926
- function resolveCurrentPath(toolName, args) {
4927
- if (!toolName || !args) return void 0;
4928
- const direct = ["path", "file", "filename", "target", "cwd"];
4929
- for (const key of direct) {
4930
- const value = args[key];
4931
- if (typeof value === "string" && value.trim()) return value.trim();
4932
- }
4933
- if (toolName === "bash") {
4934
- const command = typeof args.command === "string" ? args.command : void 0;
4935
- if (!command) return void 0;
4936
- return firstWrittenFile(command);
4937
- }
4938
- return void 0;
4939
- }
4940
- function readShellWord(command, start) {
4941
- let word = "";
4942
- let quote;
4943
- let i = start;
4944
- for (; i < command.length; i++) {
4945
- const char = command[i];
4946
- if (quote) {
4947
- if (char === quote) quote = void 0;
4948
- else if (char === "\\" && quote === '"' && /[$`"\\\n]/.test(command[i + 1] ?? "")) word += command[++i];
4949
- else word += char;
4950
- continue;
4951
- }
4952
- if (char === "'" || char === '"') quote = char;
4953
- else if (char === "\\" && i + 1 < command.length) word += command[++i];
4954
- else if (/[\s;&|()<>]/.test(char)) break;
4955
- else word += char;
4956
- }
4957
- return { word, end: i };
4958
- }
4959
- function firstWrittenFile(command) {
4960
- let quote;
4961
- for (let i = 0; i < command.length; i++) {
4962
- const char = command[i];
4963
- if (quote) {
4964
- if (char === quote) quote = void 0;
4965
- else if (char === "\\" && quote === '"') i++;
4966
- continue;
4967
- }
4968
- if (char === "'" || char === '"') {
4969
- quote = char;
4970
- continue;
4971
- }
4972
- if (char === "\\") {
4973
- i++;
4974
- continue;
4975
- }
4976
- const isTee = command.startsWith("tee", i) && (i === 0 || /[\s|;&(]/.test(command[i - 1])) && /\s/.test(command[i + 3] ?? "");
4977
- if (char !== ">" && !isTee) continue;
4978
- let cursor = isTee ? i + 3 : command[i + 1] === ">" ? i + 2 : i + 1;
4979
- for (; ; ) {
4980
- while (cursor < command.length && /[ \t]/.test(command[cursor])) cursor++;
4981
- if (command[cursor] === "&") break;
4982
- const { word, end } = readShellWord(command, cursor);
4983
- cursor = end;
4984
- if (word && word !== "/dev/null" && !(isTee && word.startsWith("-"))) return word;
4985
- if (!isTee || !word) break;
4986
- }
4987
- i = cursor - 1;
4988
- }
4989
- return void 0;
4990
- }
4991
- function hasUnquotedFileRedirection(command) {
4992
- let inSingle = false;
4993
- let inDouble = false;
4994
- for (let i = 0; i < command.length; i++) {
4995
- const char = command[i];
4996
- if (char === "'" && !inDouble) {
4997
- inSingle = !inSingle;
4998
- continue;
4999
- }
5000
- if (char === '"' && !inSingle) {
5001
- inDouble = !inDouble;
5002
- continue;
5003
- }
5004
- if (inSingle || inDouble) continue;
5005
- if (char !== ">") continue;
5006
- if (command[i - 1] === "-") continue;
5007
- const isDouble = command[i + 1] === ">";
5008
- let cursor = i + (isDouble ? 2 : 1);
5009
- while (cursor < command.length && /\s/.test(command[cursor])) cursor++;
5010
- if (cursor >= command.length) continue;
5011
- const targetStart = command[cursor];
5012
- if (targetStart === "&" || targetStart === "|" || targetStart === ";") continue;
5013
- if (targetStart === "(" || targetStart === ")") continue;
5014
- if (/^\/dev\/null(?=$|[\s;&|()])/.test(command.slice(cursor))) continue;
5015
- return true;
5016
- }
5017
- return false;
5018
- }
5019
- function unquotedShellText(command) {
5020
- let inSingle = false;
5021
- let inDouble = false;
5022
- let escaped = false;
5023
- let result2 = "";
5024
- for (const char of command) {
5025
- if (escaped) {
5026
- result2 += inSingle || inDouble ? "_" : char;
5027
- escaped = false;
5028
- continue;
5029
- }
5030
- if (char === "\\" && !inSingle) {
5031
- escaped = true;
5032
- result2 += inDouble ? "_" : char;
5033
- continue;
5034
- }
5035
- if (char === "'" && !inDouble) {
5036
- inSingle = !inSingle;
5037
- continue;
5038
- }
5039
- if (char === '"' && !inSingle) {
5040
- inDouble = !inDouble;
5041
- continue;
5042
- }
5043
- result2 += inSingle || inDouble ? "_" : char;
5044
- }
5045
- return result2;
5046
- }
5047
- function hasMutatingGitCommand(command) {
5048
- const unquoted = unquotedShellText(command);
5049
- for (const segment of unquoted.split(/(?:&&|\|\||[;|()\n])/)) {
5050
- const trimmed = segment.trim();
5051
- if (!trimmed || /^(?:echo|printf)\b/.test(trimmed)) continue;
5052
- if (/^git\s+(?:(?:(?:-C|--git-dir|--work-tree)\s+\S+|(?:--git-dir|--work-tree)=\S+|--paginate)\s+)*(?:add|commit|push)\b/.test(trimmed)) return true;
5053
- }
5054
- return false;
5055
- }
5056
- function isMutatingBashCommand(command) {
5057
- return hasUnquotedFileRedirection(command) || hasMutatingGitCommand(command) || MUTATING_BASH_PATTERNS.some((pattern) => pattern.test(command));
5058
- }
5059
- function isMutatingTool(toolName, args, mutationTools) {
5060
- if (!toolName) return false;
5061
- if (mutationTools?.includes(toolName)) return true;
5062
- if (toolName === "edit" || toolName === "write") return true;
5063
- if (toolName === "cursor") {
5064
- const activityTitle = typeof args?.activityTitle === "string" ? args.activityTitle : "";
5065
- return /^Cursor (?:edit|write)\b/i.test(activityTitle);
5066
- }
5067
- if (toolName !== "bash") return false;
5068
- const command = typeof args?.command === "string" ? args.command : "";
5069
- if (!command.trim()) return false;
5070
- return isMutatingBashCommand(command);
5071
- }
5072
- function didMutatingToolFail(result2) {
5073
- return result2.isError === true;
5074
- }
5075
- function nextLongRunningTrigger(config, metrics) {
5076
- if (metrics.now - metrics.startedAt >= config.activeNoticeAfterMs) return "time_threshold";
5077
- if (config.activeNoticeAfterTurns !== void 0 && metrics.turns >= config.activeNoticeAfterTurns) return "turn_threshold";
5078
- if (config.activeNoticeAfterTokens !== void 0 && metrics.tokens >= config.activeNoticeAfterTokens) return "token_threshold";
5079
- return void 0;
5080
- }
5081
- function resetMutatingFailureState(state) {
5082
- state.consecutiveFailures = 0;
5083
- state.lastFailureAt = void 0;
5084
- state.recentFailures = [];
5085
- state.lastMutatingPath = void 0;
5086
- state.repeatedPathFailures = 0;
5087
- }
5088
- function createMutatingFailureState() {
5089
- return {
5090
- consecutiveFailures: 0,
5091
- recentFailures: [],
5092
- repeatedPathFailures: 0
5093
- };
5094
- }
5095
- function recordMutatingFailure(state, input, windowMs) {
5096
- if (state.lastFailureAt === void 0 || input.ts - state.lastFailureAt > windowMs) {
5097
- state.consecutiveFailures = 0;
5098
- state.recentFailures = [];
5099
- state.repeatedPathFailures = 0;
5100
- state.lastMutatingPath = void 0;
5101
- }
5102
- state.lastFailureAt = input.ts;
5103
- state.consecutiveFailures += 1;
5104
- if (input.path && state.lastMutatingPath === input.path) {
5105
- state.repeatedPathFailures += 1;
5106
- } else if (input.path) {
5107
- state.lastMutatingPath = input.path;
5108
- state.repeatedPathFailures = 1;
5109
- }
5110
- state.recentFailures.push(input);
5111
- if (state.recentFailures.length > 3) state.recentFailures.shift();
5112
- }
5113
- function shouldEscalateMutatingFailures(state, threshold) {
5114
- return state.consecutiveFailures >= threshold || state.repeatedPathFailures >= threshold;
5115
- }
5116
- function summarizeRecentMutatingFailures(state) {
5117
- if (state.recentFailures.length === 0) return void 0;
5118
- return state.recentFailures.map((entry) => `${entry.tool}${entry.path ? `(${entry.path})` : ""}: ${entry.error}`).join(" | ");
5119
- }
5120
-
5121
5269
  // src/runs/shared/child-lifecycle.ts
5122
5270
  function projectChildLifecycle(event, terminalAssistantStop = false, state) {
5123
5271
  if (event.type === "compaction_end") {
@@ -5198,6 +5346,59 @@ function reconcileAttemptUsage(live, messages, baseline) {
5198
5346
  return reconciled;
5199
5347
  }
5200
5348
 
5349
+ // src/runs/shared/supervisor-wait-timer.ts
5350
+ function isBlockingSupervisorTool(toolName, args) {
5351
+ if (!args || typeof args !== "object") return false;
5352
+ const call = args;
5353
+ if (toolName === "contact_supervisor") return call.reason === "need_decision" || call.reason === "interview_request";
5354
+ return toolName === "intercom" && call.action === "ask";
5355
+ }
5356
+ function startPausableTimer(delayMs, onFire) {
5357
+ let remaining = Math.max(0, delayMs);
5358
+ let runningSince;
5359
+ let timer;
5360
+ let done = false;
5361
+ const pausedBy = /* @__PURE__ */ new Set();
5362
+ const remainingMs = () => runningSince === void 0 ? remaining : Math.max(0, remaining - (performance.now() - runningSince));
5363
+ const run = () => {
5364
+ runningSince = performance.now();
5365
+ timer = setTimeout(() => {
5366
+ done = true;
5367
+ runningSince = void 0;
5368
+ remaining = 0;
5369
+ onFire();
5370
+ }, remaining);
5371
+ timer.unref?.();
5372
+ };
5373
+ const stop = () => {
5374
+ clearTimeout(timer);
5375
+ remaining = remainingMs();
5376
+ runningSince = void 0;
5377
+ };
5378
+ run();
5379
+ return {
5380
+ pause(key) {
5381
+ if (done) return;
5382
+ if (pausedBy.size === 0) stop();
5383
+ pausedBy.add(key);
5384
+ },
5385
+ resume(key) {
5386
+ if (done || !pausedBy.delete(key) || pausedBy.size > 0) return;
5387
+ run();
5388
+ },
5389
+ remainingMs,
5390
+ clear() {
5391
+ done = true;
5392
+ stop();
5393
+ }
5394
+ };
5395
+ }
5396
+ function pauseForSupervisorWait(timer, event) {
5397
+ if (!timer || typeof event.toolCallId !== "string") return;
5398
+ if (event.type === "tool_execution_start" && isBlockingSupervisorTool(event.toolName, event.args)) timer.pause(event.toolCallId);
5399
+ else if (event.type === "tool_execution_end") timer.resume(event.toolCallId);
5400
+ }
5401
+
5201
5402
  // src/runs/foreground/execution.ts
5202
5403
  var artifactOutputByResult = /* @__PURE__ */ new WeakMap();
5203
5404
  var acceptanceOutputByResult = /* @__PURE__ */ new WeakMap();
@@ -5347,6 +5548,8 @@ function captureStructuredDelegationProgressState(progress, result2) {
5347
5548
  recentOutput: [...progress.recentOutput],
5348
5549
  recentTools: progress.recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map(({ tool, args }) => ({ tool, args })),
5349
5550
  activityState: progress.activityState,
5551
+ progressText: progress.progressText,
5552
+ progressUpdatedAt: progress.progressUpdatedAt,
5350
5553
  model: progress.model ?? result2.model,
5351
5554
  toolCount: progress.toolCount,
5352
5555
  tokens: progress.tokens,
@@ -5354,7 +5557,7 @@ function captureStructuredDelegationProgressState(progress, result2) {
5354
5557
  };
5355
5558
  }
5356
5559
  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;
5560
+ 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
5561
  for (let index = 0; index < progress.recentOutput.length; index++) {
5359
5562
  if (previous.recentOutput[index] !== progress.recentOutput[index]) return true;
5360
5563
  }
@@ -5372,6 +5575,7 @@ function isCompleteUsageCounter(value) {
5372
5575
  }
5373
5576
  var STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
5374
5577
  var AFTER_COMPACTION_SETTLEMENT = /* @__PURE__ */ Symbol("afterCompactionSettlement");
5578
+ var REMAINING_TIMEOUT_MS = /* @__PURE__ */ Symbol("remainingTimeoutMs");
5375
5579
  async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared) {
5376
5580
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
5377
5581
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== void 0);
@@ -5570,6 +5774,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5570
5774
  let toolAvailabilityError;
5571
5775
  let abortedBySignal = options.signal?.aborted === true;
5572
5776
  let afterCompactionSettlement = false;
5777
+ let remainingTimeoutMs;
5573
5778
  if (options.workflowChildPermitLaunch) {
5574
5779
  const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
5575
5780
  workflowRunId: options.workflowChildPermitLaunch.workflowRunId,
@@ -5611,7 +5816,8 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5611
5816
  let timeoutHardFinishTimer;
5612
5817
  const clearTimeoutTimers = () => {
5613
5818
  if (timeoutTimer) {
5614
- clearTimeout(timeoutTimer);
5819
+ remainingTimeoutMs = timeoutTimer.remainingMs();
5820
+ timeoutTimer.clear();
5615
5821
  timeoutTimer = void 0;
5616
5822
  }
5617
5823
  if (timeoutHardFinishTimer) {
@@ -5812,9 +6018,8 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5812
6018
  };
5813
6019
  let activeLongRunningNotified = false;
5814
6020
  const pendingToolResultsByCallId = /* @__PURE__ */ new Map();
5815
- let pendingToolResult;
6021
+ const pendingToolState = { current: void 0 };
5816
6022
  const handledToolResultIds = /* @__PURE__ */ new Set();
5817
- const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
5818
6023
  let activeToolSequence = 0;
5819
6024
  const activeToolCalls = /* @__PURE__ */ new Map();
5820
6025
  const activeToolKeysByName = /* @__PURE__ */ new Map();
@@ -5941,12 +6146,20 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5941
6146
  toolAttentionTarget.attentionEmitted = true;
5942
6147
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
5943
6148
  const toolCallId = toolAttentionTarget.key.startsWith("id:") ? toolAttentionTarget.key.slice(3) : void 0;
6149
+ let hasCommandController = false;
6150
+ if (toolCallId) try {
6151
+ hasCommandController = retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId);
6152
+ } catch (error) {
6153
+ const message = `Could not read the command state of ${agent.name}; its command controls are not offered: ${error instanceof Error ? error.message : String(error)}`;
6154
+ if (options.onWarning) options.onWarning(message, "child-command-state");
6155
+ else console.warn(`[pi-subagents] ${message}`);
6156
+ }
5944
6157
  return emitNeedsAttention(now, {
5945
6158
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1e3)}s`,
5946
6159
  reason: "tool_open_threshold",
5947
6160
  currentTool: toolAttentionTarget.tool,
5948
6161
  toolCallId,
5949
- hasCommandController: Boolean(toolCallId && retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId)),
6162
+ hasCommandController,
5950
6163
  currentPath: toolAttentionTarget.path,
5951
6164
  currentToolDurationMs: durationMs
5952
6165
  });
@@ -5985,57 +6198,21 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5985
6198
  const output = result2.timedOut && result2.finalOutput ? result2.finalOutput : getFinalOutput(result2.messages ?? []);
5986
6199
  emitUpdateSnapshot(output || "(running...)");
5987
6200
  };
5988
- const handleToolResult = (message, completion, now) => {
5989
- const rawCallId = completion.toolCallId ?? message.toolCallId;
5990
- const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : void 0;
5991
- if (callId) {
5992
- if (handledToolResultIds.has(callId)) return;
5993
- if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
5994
- const oldest = handledToolResultIds.values().next().value;
5995
- if (typeof oldest === "string") handledToolResultIds.delete(oldest);
5996
- }
5997
- handledToolResultIds.add(callId);
5998
- }
5999
- result2.messages.push(message);
6000
- const resultText = extractTextFromContent(message.content);
6001
- const keyedSnapshot = callId ? pendingToolResultsByCallId.get(callId) : void 0;
6002
- if (callId && keyedSnapshot) pendingToolResultsByCallId.delete(callId);
6003
- const toolSnapshot = keyedSnapshot ?? pendingToolResult;
6004
- if (!keyedSnapshot || pendingToolResult === keyedSnapshot) pendingToolResult = void 0;
6005
- const resultToolName = completion.toolName ?? message.toolName;
6006
- const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0 ? resultToolName : void 0) ?? toolSnapshot?.tool;
6007
- const budgetBlocked = Boolean(options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool));
6008
- if (options.toolBudget && budgetBlocked) {
6009
- result2.toolBudgetBlocked = true;
6010
- result2.toolBudget = toolBudgetState(
6011
- options.toolBudget,
6012
- Math.max(progress.toolCount, options.toolBudget.hard + 1),
6013
- blockedTool
6014
- );
6015
- }
6016
- appendRecentOutput(progress, resultText.split("\n").slice(-10));
6017
- if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
6018
- recordMutatingFailure(mutatingFailures, {
6019
- tool: toolSnapshot.tool,
6020
- path: toolSnapshot.path,
6021
- error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
6022
- ts: now
6023
- }, mutatingFailureWindowMs);
6024
- if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
6025
- emitNeedsAttention(now, {
6026
- message: `${agent.name} needs attention after repeated mutating tool failures`,
6027
- reason: "tool_failures",
6028
- currentTool: toolSnapshot.tool,
6029
- currentPath: toolSnapshot.path,
6030
- currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : void 0,
6031
- recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures)
6032
- });
6033
- }
6034
- } else if (toolSnapshot?.mutates) {
6035
- resetMutatingFailureState(mutatingFailures);
6036
- }
6037
- fireUpdate();
6038
- };
6201
+ const handleToolResult = createToolResultHandler({
6202
+ result: result2,
6203
+ progress,
6204
+ options,
6205
+ agentName: agent.name,
6206
+ handledToolResultIds,
6207
+ pendingToolResultsByCallId,
6208
+ pendingToolState,
6209
+ mutatingFailures,
6210
+ mutatingFailureWindowMs,
6211
+ controlConfig,
6212
+ appendRecentOutput,
6213
+ fireUpdate,
6214
+ emitNeedsAttention
6215
+ });
6039
6216
  const processEvent = (evt) => {
6040
6217
  if (lifecycleFinished) return;
6041
6218
  partialOutput.observe(evt);
@@ -6114,6 +6291,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6114
6291
  progress.durationMs = now - startTime;
6115
6292
  progress.lastActivityAt = now;
6116
6293
  updateActivityState(now);
6294
+ pauseForSupervisorWait(timeoutTimer, evt);
6117
6295
  if (evt.type === "tool_execution_start") {
6118
6296
  const toolArgs = evt.args && typeof evt.args === "object" && !Array.isArray(evt.args) ? evt.args : {};
6119
6297
  const activeTool = evt.toolName !== void 0 ? recordActiveToolCall(evt, toolArgs, now) : void 0;
@@ -6130,8 +6308,8 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6130
6308
  result2.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, result2.toolBudget?.blockedTool);
6131
6309
  }
6132
6310
  const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
6133
- pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
6134
- if (typeof evt.toolCallId === "string" && evt.toolCallId) pendingToolResultsByCallId.set(evt.toolCallId, pendingToolResult);
6311
+ pendingToolState.current = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
6312
+ if (typeof evt.toolCallId === "string" && evt.toolCallId) pendingToolResultsByCallId.set(evt.toolCallId, pendingToolState.current);
6135
6313
  fireUpdate();
6136
6314
  }
6137
6315
  if (evt.type === "tool_execution_end") {
@@ -6239,7 +6417,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6239
6417
  activityTimer.unref?.();
6240
6418
  }
6241
6419
  if (attemptTimeout) {
6242
- timeoutTimer = setTimeout(() => {
6420
+ timeoutTimer = startPausableTimer(attemptTimeout.remainingMs, () => {
6243
6421
  if (sessionSettled || lifecycleFinished || interruptedByControl || result2.timedOut) return;
6244
6422
  result2.timedOut = true;
6245
6423
  timeoutCause = attemptTimeout.message;
@@ -6256,8 +6434,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6256
6434
  settle(void 0, true);
6257
6435
  }, 4e3);
6258
6436
  timeoutHardFinishTimer.unref?.();
6259
- }, attemptTimeout.remainingMs);
6260
- timeoutTimer.unref?.();
6437
+ });
6261
6438
  }
6262
6439
  let toolTimeoutSequence = 0;
6263
6440
  const activeToolTimeouts = /* @__PURE__ */ new Map();
@@ -6285,7 +6462,7 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6285
6462
  };
6286
6463
  const terminateForToolTimeout = (message) => {
6287
6464
  if (sessionSettled || lifecycleFinished || interruptedByControl || result2.timedOut) return;
6288
- clearTimeout(timeoutTimer);
6465
+ timeoutTimer?.clear();
6289
6466
  result2.timedOut = true;
6290
6467
  timeoutCause = message;
6291
6468
  result2.error = message;
@@ -6304,9 +6481,6 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
6304
6481
  const armToolTimeout = (event) => {
6305
6482
  const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
6306
6483
  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
6484
  const key = toolTimeoutCallKey(event, ++toolTimeoutSequence);
6311
6485
  const toolName = event.toolName;
6312
6486
  const timer = setTimeout(() => {
@@ -6424,12 +6598,12 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6424
6598
  const steer = created.steer.bind(created);
6425
6599
  const followUp = created.followUp.bind(created);
6426
6600
  created.steer = async (text) => {
6601
+ await steer(text);
6427
6602
  if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
6428
- return steer(text);
6429
6603
  };
6430
6604
  created.followUp = async (text) => {
6605
+ await followUp(text);
6431
6606
  if (cleanTerminalAssistantStopReceived || agentSettledReceived) queuedDrainHold = true;
6432
- return followUp(text);
6433
6607
  };
6434
6608
  created.detached = detached;
6435
6609
  unsubscribe = created.subscribe((event) => processEvent(event));
@@ -6460,9 +6634,8 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6460
6634
  result2.exitCode = exitCode;
6461
6635
  result2.providerDiagnostics = clearProviderRetry(result2.providerDiagnostics);
6462
6636
  progress.providerDiagnostics = result2.providerDiagnostics;
6463
- if (afterCompactionSettlement) {
6464
- result2[AFTER_COMPACTION_SETTLEMENT] = true;
6465
- }
6637
+ if (afterCompactionSettlement) result2[AFTER_COMPACTION_SETTLEMENT] = true;
6638
+ result2[REMAINING_TIMEOUT_MS] = remainingTimeoutMs;
6466
6639
  if (interruptedByControl) {
6467
6640
  result2.exitCode = 0;
6468
6641
  result2.interrupted = true;
@@ -6524,6 +6697,9 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6524
6697
  } else if (errInfo.hasError) {
6525
6698
  result2.exitCode = errInfo.exitCode ?? 1;
6526
6699
  result2.error = errInfo.details ? `${errInfo.errorType} failed (exit ${errInfo.exitCode}): ${errInfo.details}` : `${errInfo.errorType} failed with exit code ${errInfo.exitCode}`;
6700
+ } else if (!validatedStructuredOutput && getTerminalAssistantStopReason(messages) === "length") {
6701
+ result2.exitCode = 1;
6702
+ result2.error = TRUNCATED_RESPONSE_ERROR;
6527
6703
  }
6528
6704
  }
6529
6705
  progress.status = result2.exitCode === 0 ? "completed" : "failed";
@@ -6541,7 +6717,7 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6541
6717
  durationMs: progress.durationMs
6542
6718
  };
6543
6719
  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);
6720
+ 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
6721
  const acceptanceOutput = getFinalOutput(result2.messages ?? []);
6546
6722
  const structuredText = result2.structuredOutput === void 0 ? void 0 : JSON.stringify(result2.structuredOutput, null, 2);
6547
6723
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -6633,7 +6809,7 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
6633
6809
  }
6634
6810
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
6635
6811
  const effectiveCwd = options.cwd ?? runtimeCwd;
6636
- const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6812
+ const cwdError = options.machine && !isRexLocalMachine(options.machine) ? void 0 : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6637
6813
  if (cwdError) {
6638
6814
  return redactResultPrompt(withRunContext({
6639
6815
  index: options.index ?? 0,
@@ -6776,7 +6952,8 @@ ${acceptancePrompt}` : task;
6776
6952
  {
6777
6953
  scope: options.modelScope,
6778
6954
  primaryModelFromParent: options.modelOverrideFromParent,
6779
- origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured")
6955
+ origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
6956
+ knownProviders: options.knownProviders
6780
6957
  }
6781
6958
  );
6782
6959
  try {
@@ -6924,6 +7101,8 @@ ${PROMPT_REDACTED}; live Prompt Audit only.
6924
7101
  });
6925
7102
  if (recovery.action === "resume") {
6926
7103
  recoveryPrompt = recovery.prompt;
7104
+ const remainingMs = attemptResult[REMAINING_TIMEOUT_MS];
7105
+ if (remainingMs !== void 0) attemptOptions.deadlineAt = Date.now() + remainingMs;
6927
7106
  attemptNotes.push("[abort-recovery] compaction abort after useful progress; resuming the retained child session once on the same model.");
6928
7107
  continue;
6929
7108
  }
@@ -7682,7 +7861,7 @@ async function createPrunedForkSessionWriter(ctx, config, signal) {
7682
7861
  };
7683
7862
  if (!config.model?.trim()) throw new Error("Pruned fork context requires config.forkContext.model.");
7684
7863
  const available = ctx.modelRegistry.getAvailable();
7685
- const resolved = resolveModelCandidate(config.model.trim(), available.map(toModelInfo), ctx.model?.provider);
7864
+ const resolved = resolveModelCandidate(config.model.trim(), available.map(toModelInfo), ctx.model?.provider, knownModelProviders(ctx.modelRegistry));
7686
7865
  if (!resolved) throw new Error(`Pruned fork model '${config.model}' did not match exactly one available model.`);
7687
7866
  const { baseModel } = splitKnownThinkingSuffix(resolved);
7688
7867
  const named = splitProviderModel(baseModel);
@@ -8510,7 +8689,7 @@ function formatResumeGuidance(runId, children, fallbackSessionFile, options = {}
8510
8689
  const resumableWorkflowChildren = workflowChildren.filter(({ child }) => !(child.status === "paused" && child.activityState === "needs_attention"));
8511
8690
  if (workflowChildren.length > 0) {
8512
8691
  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.`),
8692
+ ...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
8693
  ...resumableWorkflowChildren.map(({ child }) => `Revive workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: subagent({ action: "resume", id: "${child.runId}", message: "..." })`)
8515
8694
  ].join("\n");
8516
8695
  }
@@ -8602,7 +8781,7 @@ function formatRememberedForegroundStatus(run) {
8602
8781
  const detached = run.children.some((child) => child.status === "detached");
8603
8782
  const resumable = run.children.find((child) => hasExistingSessionFile(child.sessionFile));
8604
8783
  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.`);
8784
+ 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
8785
  } else if (resumable) {
8607
8786
  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
8787
  } else {
@@ -8998,10 +9177,11 @@ Extensions denied: ${status.capabilityCeiling.denyExtensions ? "yes" : "no"} (so
8998
9177
  lines.push(` Runner: external-cli (${runner.command}${runner.args.length ? ` ${runner.args.join(" ")}` : ""})`);
8999
9178
  lines.push(` Adapter: ${runner.adapter.id} v${runner.adapter.version} (${runner.adapter.executionMode})`);
9000
9179
  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}`);
9180
+ const safetyLabel = " Safety (adapter profile, not measured):";
9181
+ 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}`);
9182
+ 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}`);
9183
+ 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}`);
9184
+ 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
9185
  }
9006
9186
  lines.push(` Capabilities: stop=${runner.capabilities.stop}, steer=false, resume=false, structuredOutput=false, toolEvents=false, supervisor=unsupported, forkContext=false, extensionBindings=false`);
9007
9187
  lines.push(` Unsupported steer: ${runner.unsupportedReasons.steer}`);
@@ -9169,13 +9349,13 @@ function applyForceTopLevelAsyncOverride(params, depth, forceTopLevelAsync) {
9169
9349
 
9170
9350
  // src/runs/shared/worktree-cleanup-apply.ts
9171
9351
  import { createHash as createHash5 } from "node:crypto";
9172
- import { spawnSync as spawnSync2 } from "node:child_process";
9352
+ import { spawnSync as spawnSync3 } from "node:child_process";
9173
9353
  import * as fs20 from "node:fs";
9174
9354
  import * as path18 from "node:path";
9175
9355
 
9176
9356
  // src/runs/shared/worktree-cleanup-plan.ts
9177
9357
  import { createHash as createHash4, randomUUID as randomUUID5 } from "node:crypto";
9178
- import { spawnSync } from "node:child_process";
9358
+ import { spawnSync as spawnSync2 } from "node:child_process";
9179
9359
  import * as fs19 from "node:fs";
9180
9360
  import * as os2 from "node:os";
9181
9361
  import * as path17 from "node:path";
@@ -9186,7 +9366,7 @@ var MAX_PLAN_ENTRIES = 512;
9186
9366
  var MAX_METADATA_FILE_BYTES = 2 * 1024 * 1024;
9187
9367
  function runGit(cwd, args) {
9188
9368
  try {
9189
- const result2 = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
9369
+ const result2 = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
9190
9370
  return {
9191
9371
  stdout: result2.stdout ?? "",
9192
9372
  stderr: result2.stderr ?? "",
@@ -9927,7 +10107,7 @@ async function applyReviewedCleanupPlan(input) {
9927
10107
  const journalEntry = { path: entry.path, branch: entry.branch, state: "removing", reason: "removal prepared; outcome not yet recorded" };
9928
10108
  receipt.entries.push(journalEntry);
9929
10109
  writePrivateAtomicJson(receiptPath, receipt);
9930
- const removed = spawnSync2("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
10110
+ const removed = spawnSync3("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
9931
10111
  if (removed.status !== 0) throw new Error(removed.error?.message || removed.stderr.trim() || "git worktree remove failed");
9932
10112
  journalEntry.state = "removed";
9933
10113
  journalEntry.reason = "worktree removed; local branch retained";
@@ -10017,6 +10197,38 @@ function inheritedRunFanoutBudget(deps) {
10017
10197
  function resolveRequestedCwd(runtimeCwd, requestedCwd) {
10018
10198
  return requestedCwd ? path19.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
10019
10199
  }
10200
+ function workflowChildLaunchArgs(workflowRunId, key, request, scriptAgent, ctxCwd, discoverAgents2) {
10201
+ const resume = request.action === "resume" && typeof request.id === "string" ? request.id : void 0;
10202
+ const agent = request.agent ?? scriptAgent;
10203
+ const task = resume !== void 0 ? request.message : request.task;
10204
+ const scope = resolveExecutionAgentScope(request.agentScope);
10205
+ const findAgent = (dir) => typeof agent === "string" ? resolveAgentName(agent, discoverAgents2(dir, scope).agents).agent : void 0;
10206
+ const ctxAgent = request.machine === void 0 ? findAgent(ctxCwd) : void 0;
10207
+ const placed = request.machine !== void 0 || ctxAgent?.machine !== void 0;
10208
+ const runCwd = resolveRequestedCwd(ctxCwd, request.cwd);
10209
+ const cwd = resume === void 0 && !placed ? runCwd : void 0;
10210
+ const acceptanceInput = request.acceptance !== void 0 || resume !== void 0 ? request.acceptance : (placed || runCwd === ctxCwd ? ctxAgent ?? findAgent(ctxCwd) : findAgent(runCwd))?.defaultAcceptance;
10211
+ const acceptance = acceptanceInput !== void 0 && validateAcceptanceInput(acceptanceInput).length === 0 ? normalizeAcceptanceInput(acceptanceInput) : void 0;
10212
+ const commands = acceptance?.level === "verified" ? (acceptance.verify ?? []).map((verify) => ({
10213
+ command: verify.command,
10214
+ ...cwd !== void 0 ? { cwd: verify.cwd ? path19.resolve(cwd, verify.cwd) : cwd } : {},
10215
+ ...verify.env !== void 0 ? { env: verify.env } : {}
10216
+ })) : [];
10217
+ const output = resolveSingleOutputPath(request.output, ctxCwd);
10218
+ return {
10219
+ workflowRunId,
10220
+ key,
10221
+ ...typeof agent === "string" ? { agent } : {},
10222
+ ...typeof task === "string" ? { task } : {},
10223
+ ...cwd !== void 0 ? { cwd } : {},
10224
+ ...typeof request.model === "string" ? { model: request.model } : {},
10225
+ ...typeof request.async === "boolean" ? { async: request.async } : {},
10226
+ ...typeof request.worktree === "boolean" ? { worktree: request.worktree } : {},
10227
+ ...resume !== void 0 ? { resume } : {},
10228
+ ...commands.length > 0 ? { commands } : {},
10229
+ ...output !== void 0 ? { output } : {}
10230
+ };
10231
+ }
10020
10232
  function readWorkflowScriptFile(requestedPath, requestedCwd, runtimeCwd) {
10021
10233
  const scriptPath = path19.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
10022
10234
  let script;
@@ -10450,7 +10662,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
10450
10662
  if (matches.length === 0) return void 0;
10451
10663
  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
10664
  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.`);
10665
+ 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
10666
  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
10667
  const index = params.index ?? 0;
10456
10668
  if (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
@@ -10459,7 +10671,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
10459
10671
  if (!child.sessionFile) throw new Error(`Foreground run '${run.runId}' child ${index} does not have a persisted session file to resume from.`);
10460
10672
  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
10673
  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}`);
10674
+ if (!fs21.existsSync(sessionFile)) throw new Error(`Foreground run '${run.runId}' child ${index} session file does not exist: ${child.sessionFile}${missingForkCopyNote(sessionFile)}`);
10463
10675
  return {
10464
10676
  runId: run.runId,
10465
10677
  mode: run.mode,
@@ -10575,8 +10787,7 @@ function persistAsyncWorkflowControlEvent(input) {
10575
10787
  fs21.appendFileSync(path19.join(input.job.asyncDir, "events.jsonl"), `${JSON.stringify(record2)}
10576
10788
  `, "utf-8");
10577
10789
  } catch (error) {
10578
- if (!isStorageCapacityError(error)) throw error;
10579
- console.error("Failed to append async workflow control event while storage is full:", error);
10790
+ 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
10791
  }
10581
10792
  }
10582
10793
  function emitControlNotification(input) {
@@ -10789,6 +11000,7 @@ function appendStepToAsyncChain(input) {
10789
11000
  parentProviderRegistry: input.ctx.modelRegistry,
10790
11001
  currentModel: parentModel,
10791
11002
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
11003
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
10792
11004
  modelScope: discoveredForAppend.modelScope,
10793
11005
  projectTrusted: currentProjectTrusted(input.ctx),
10794
11006
  ...trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {},
@@ -10906,7 +11118,7 @@ function validateNestedSessionFile(run, trustedSessionRoots2, resolveSource, vis
10906
11118
  if (path19.extname(sessionFile) !== ".jsonl") throw new Error(`Nested run '${run.id}' session file must be a .jsonl file: ${sessionFile}`);
10907
11119
  const resolved = path19.resolve(sessionFile);
10908
11120
  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}`);
11121
+ if (!fs21.existsSync(resolved)) throw new Error(`Nested run '${run.id}' session file does not exist: ${sessionFile}${missingForkCopyNote(resolved)}`);
10910
11122
  const stat = fs21.lstatSync(resolved);
10911
11123
  if (!stat.isFile() || stat.isSymbolicLink()) throw new Error(`Nested run '${run.id}' session file is not a regular file: ${sessionFile}`);
10912
11124
  const realSessionFile = fs21.realpathSync(resolved);
@@ -10932,8 +11144,8 @@ function validateNestedSessionFile(run, trustedSessionRoots2, resolveSource, vis
10932
11144
  }
10933
11145
  return realSessionFile;
10934
11146
  }
10935
- function readNestedRecoveryDescriptor(asyncDir, runId, agent) {
10936
- const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
11147
+ function readNestedRecoveryDescriptor(rootRunId, runId, agent) {
11148
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(nestedRunScope(rootRunId).asyncDirRoot, runId);
10937
11149
  if (!recoveryDescriptor) return void 0;
10938
11150
  if (recoveryDescriptor.sourceRunId !== runId) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different source run.`);
10939
11151
  if (recoveryDescriptor.agent !== agent) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different agent.`);
@@ -10947,7 +11159,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots2, resolveSource) {
10947
11159
  if (!agent) throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
10948
11160
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
10949
11161
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
10950
- const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
11162
+ const recoveryDescriptor = asyncDir ? readNestedRecoveryDescriptor(match.match.rootRunId, run.id, agent) : void 0;
10951
11163
  return compactOptional({
10952
11164
  kind: "revive",
10953
11165
  source: "nested",
@@ -11195,6 +11407,7 @@ async function resumeExternalJobFollowUp(input) {
11195
11407
  parentProviderRegistry: input.ctx.modelRegistry,
11196
11408
  currentModel: parentModel,
11197
11409
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
11410
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
11198
11411
  modelScope: input.modelScope,
11199
11412
  modelResponseAliases: input.deps.config.modelResponseAliases,
11200
11413
  interactive: input.ctx.hasUI,
@@ -11363,6 +11576,14 @@ async function resumeAsyncRun(input) {
11363
11576
  details: { mode: "management", results: [] }
11364
11577
  };
11365
11578
  }
11579
+ const requiredLauncher = recoveryDescriptor?.requiredLauncher;
11580
+ if (requiredLauncher) {
11581
+ const refuse = (text) => ({ content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } });
11582
+ 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.`);
11583
+ const currentDigest = discoveredAgentConfig ? agentDefinitionDigest(discoveredAgentConfig) : void 0;
11584
+ 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;
11585
+ 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}.`);
11586
+ }
11366
11587
  if (target.source === "async" && target.runner?.type === "external-cli") {
11367
11588
  const runner = normalizeExternalCliRunnerStatus(target.runner);
11368
11589
  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 +11592,7 @@ async function resumeAsyncRun(input) {
11371
11592
  if (input.params.baseRef !== void 0 && "managedWorktree" in target && target.managedWorktree === true) {
11372
11593
  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
11594
  }
11374
- if (target.source === "async" && target.managedWorktree && target.asyncDir) {
11595
+ if (target.source === "async" && target.managedWorktree && target.asyncDir && fs21.existsSync(parallelHandoffPath(target.asyncDir))) {
11375
11596
  try {
11376
11597
  const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
11377
11598
  if (path19.resolve(protectedCwd) !== path19.resolve(effectiveCwd)) throw new Error("Retained worktree cwd changed during resume admission.");
@@ -11465,6 +11686,7 @@ async function resumeAsyncRun(input) {
11465
11686
  parentProviderRegistry: input.ctx.modelRegistry,
11466
11687
  currentModel: parentModel2,
11467
11688
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
11689
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
11468
11690
  modelScope,
11469
11691
  projectTrusted: currentProjectTrusted(input.ctx),
11470
11692
  ...trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {},
@@ -11532,7 +11754,7 @@ async function resumeAsyncRun(input) {
11532
11754
  if (target.source === "nested" && !target.recoveryDescriptor) {
11533
11755
  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
11756
  }
11535
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: void 0 };
11757
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
11536
11758
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
11537
11759
  const foregroundContract = target.source === "foreground" ? target.resumeContract : void 0;
11538
11760
  const outputSchema = Object.hasOwn(input.params, "outputSchema") ? input.params.outputSchema : Object.hasOwn(foregroundContract ?? {}, "outputSchema") ? foregroundContract?.outputSchema : recoveryDescriptor?.structuredOutputSchema;
@@ -11542,7 +11764,7 @@ async function resumeAsyncRun(input) {
11542
11764
  return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
11543
11765
  }
11544
11766
  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: [] } };
11767
+ 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
11768
  }
11547
11769
  const runId = randomUUID6();
11548
11770
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
@@ -11581,6 +11803,7 @@ async function resumeAsyncRun(input) {
11581
11803
  agentConfig,
11582
11804
  recoveryAgentConfig,
11583
11805
  ...recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : void 0) ? { sandbox: recoveryDescriptor?.sandbox ?? ("sandbox" in target ? target.sandbox : void 0) } : {},
11806
+ carriedRequiredLauncher: recoveryDescriptor?.requiredLauncher,
11584
11807
  ctx: compactOptional({
11585
11808
  pi: input.deps.pi,
11586
11809
  cwd: input.requestCwd,
@@ -11591,6 +11814,7 @@ async function resumeAsyncRun(input) {
11591
11814
  parentProviderRegistry: input.ctx.modelRegistry,
11592
11815
  currentModel: parentModel,
11593
11816
  scopedModelIds: scopedModelIdsFromContext(input.ctx),
11817
+ knownProviders: knownModelProviders(input.ctx.modelRegistry),
11594
11818
  modelScope,
11595
11819
  projectTrusted: currentProjectTrusted(input.ctx),
11596
11820
  ...trustedProjectCwd(input.ctx) ? { trustedProjectCwd: trustedProjectCwd(input.ctx) } : {},
@@ -11763,6 +11987,7 @@ function createForegroundControlNotifier(data, deps) {
11763
11987
  const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
11764
11988
  if (asyncWorkflow) {
11765
11989
  persistAsyncWorkflowControlEvent({
11990
+ state: deps.state,
11766
11991
  job: asyncWorkflow,
11767
11992
  event: enriched,
11768
11993
  controlConfig: data.controlConfig,
@@ -12216,10 +12441,6 @@ var MAX_TIMER_DELAY_MS = 2147483647;
12216
12441
  function timerDelayOverflowError(name, value) {
12217
12442
  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
12443
  }
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
12444
  function resolveForegroundTimeout(params, defaultTimeoutMs) {
12224
12445
  const rawTimeout = params.timeoutMs;
12225
12446
  const rawMaxRuntime = params.maxRuntimeMs;
@@ -12362,7 +12583,7 @@ function resolveStaticLaunchSummary(input) {
12362
12583
  input.parentModel,
12363
12584
  input.availableModels,
12364
12585
  agentConfig?.modelProvider ?? input.currentProvider,
12365
- modelScopes.length === 0 ? {} : { scope: modelScopes }
12586
+ { scope: modelScopes, knownProviders: input.knownProviders }
12366
12587
  );
12367
12588
  const thinkingOverride = externalRunner ? void 0 : input.thinkingOverrideForTask();
12368
12589
  const thinking = externalRunner ? void 0 : resolveEffectiveThinking(model, thinkingOverride ?? agentConfig?.thinking);
@@ -12382,6 +12603,7 @@ function collectStaticLaunchSummaries(input) {
12382
12603
  parentModel: input.parentModel,
12383
12604
  scopedModelIds: input.scopedModelIds,
12384
12605
  availableModels: input.availableModels,
12606
+ knownProviders: input.knownProviders,
12385
12607
  currentProvider: input.currentProvider,
12386
12608
  modelScope: input.modelScope,
12387
12609
  thinkingOverrideForTask: input.thinkingOverrideForTask
@@ -12656,6 +12878,7 @@ async function runAsyncPath(data, deps) {
12656
12878
  parentProviderRegistry: ctx.modelRegistry,
12657
12879
  currentModel: parentModel,
12658
12880
  scopedModelIds: data.scopedModelIds,
12881
+ knownProviders: knownModelProviders(ctx.modelRegistry),
12659
12882
  modelScope: data.modelScope,
12660
12883
  projectTrusted: currentProjectTrusted(ctx),
12661
12884
  ...trustedProjectCwd(ctx) ? { trustedProjectCwd: trustedProjectCwd(ctx) } : {},
@@ -12705,8 +12928,9 @@ async function runAsyncPath(data, deps) {
12705
12928
  parentModel
12706
12929
  });
12707
12930
  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"
12931
+ scope: modelScopes,
12932
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
12933
+ knownProviders: asyncCtx.knownProviders
12710
12934
  });
12711
12935
  const modelOverrideFromParent = modelOrigin === "inherited";
12712
12936
  const launchRuleError = applyWatchdogLaunchRules({ cwd: effectiveCwd, agent: a.name, model: modelOverride ?? (parentModel && `${parentModel.provider}/${parentModel.id}`), warn: (violation) => deps.watchdog?.displayRuleWarning(violation) });
@@ -12725,6 +12949,7 @@ async function runAsyncPath(data, deps) {
12725
12949
  requestedCwd: data.requestedCwd,
12726
12950
  machine: params.machine,
12727
12951
  machineCwd: params.machineCwd,
12952
+ requireLauncher: params.requireLauncher,
12728
12953
  maxOutput: params.maxOutput,
12729
12954
  artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
12730
12955
  artifactConfig,
@@ -13132,6 +13357,7 @@ async function runSinglePath(data, deps) {
13132
13357
  const parentModel = data.parentModel;
13133
13358
  const currentProvider = parentModel?.provider;
13134
13359
  const availableModels = ctx.modelRegistry.getAvailable().map(toModelInfo);
13360
+ const knownProviders = knownModelProviders(ctx.modelRegistry);
13135
13361
  const modelScopes = resolveModelScopesForAgent(data.modelScope, agentConfig.name, parentModel, data.scopedModelIds);
13136
13362
  let task = typeof params.task === "string" ? params.task : "";
13137
13363
  const modelOrigin = resolveModelOrigin({
@@ -13147,8 +13373,9 @@ async function runSinglePath(data, deps) {
13147
13373
  availableModels,
13148
13374
  agentConfig.modelProvider ?? currentProvider,
13149
13375
  {
13150
- ...modelScopes.length === 0 ? {} : { scope: modelScopes },
13151
- source: modelOrigin === "explicit" ? "explicit" : "inherited"
13376
+ scope: modelScopes,
13377
+ source: modelOrigin === "explicit" ? "explicit" : "inherited",
13378
+ knownProviders
13152
13379
  }
13153
13380
  );
13154
13381
  const modelOverrideFromParent = modelOrigin === "inherited";
@@ -13257,7 +13484,7 @@ async function runSinglePath(data, deps) {
13257
13484
 
13258
13485
  ` : "";
13259
13486
  task = readsInstruction + task;
13260
- task = injectSingleOutputInstruction(task, outputPath, agentConfig);
13487
+ task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
13261
13488
  let effectiveSkills;
13262
13489
  if (skillOverride === false) {
13263
13490
  effectiveSkills = [];
@@ -13403,6 +13630,7 @@ async function runSinglePath(data, deps) {
13403
13630
  suppressUnchangedDelegationUpdates,
13404
13631
  controlConfig,
13405
13632
  onControlEvent,
13633
+ onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
13406
13634
  intercomSessionName: childIntercomTarget,
13407
13635
  orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : void 0,
13408
13636
  nestedRoute: foregroundControl?.nestedRoute,
@@ -13415,6 +13643,7 @@ async function runSinglePath(data, deps) {
13415
13643
  thinkingCeiling: agentConfig.maxThinking,
13416
13644
  extensionBindings: params.extensionBindings,
13417
13645
  availableModels,
13646
+ knownProviders,
13418
13647
  modelResponseAliases,
13419
13648
  preferredModelProvider: currentProvider,
13420
13649
  modelScope: modelScopes,
@@ -13568,8 +13797,8 @@ async function runSinglePath(data, deps) {
13568
13797
  ${worktreeHandoff.suffix}` : "";
13569
13798
  if (r.detached) {
13570
13799
  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}`;
13800
+ const blockingRecovery = `${waitToolName()}({ id: "${runId}" }). Use ${statusRecovery}`;
13801
+ 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
13802
  return {
13574
13803
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
13575
13804
  details
@@ -13952,6 +14181,7 @@ async function preflightWorkflowWorktrees(input) {
13952
14181
  input.signal.throwIfAborted();
13953
14182
  }
13954
14183
  function prepareWorkflowLaunchParams(workflowDefaults, childParams, parentWorkflowRunId, workflowKey, options = {}) {
14184
+ if (childParams.requireLauncher !== void 0 || workflowDefaults.requireLauncher !== void 0) throw new Error(REQUIRE_LAUNCHER_SHAPE_ERROR);
13955
14185
  const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
13956
14186
  const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
13957
14187
  workflowDefaults = workflowDefaultsWithoutCapacity;
@@ -14189,9 +14419,10 @@ function savedWorkflowLaunchParams(params) {
14189
14419
  const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
14190
14420
  return saved;
14191
14421
  }
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 };
14422
+ function workflowLaunchRecord(launch, cwd, scriptDigest, sessionId, ceiling) {
14423
+ const owner = { version: 2, scriptDigest, sessionId, ...ceiling ? { admissionCapabilityCeiling: ceiling } : {} };
14424
+ if (launch.source === "structured" || launch.source === "internal") return { ...owner, source: launch.source };
14425
+ return { ...owner, source: launch.source, params: { ...launch.params, cwd } };
14195
14426
  }
14196
14427
  function createSubagentExecutor(deps) {
14197
14428
  const executorDeps = deps;
@@ -14460,7 +14691,7 @@ function createSubagentExecutor(deps) {
14460
14691
  try {
14461
14692
  fs21.mkdirSync(asyncDir, { recursive: true });
14462
14693
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
14463
- if (topLevelAsyncWorkflow && publicWorkflowLaunch) writeWorkflowLaunchRecord(asyncDir, workflowLaunchRecord(publicWorkflowLaunch, workflowCwd, workflowScriptSourceDigest));
14694
+ if (topLevelAsyncWorkflow) writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling2));
14464
14695
  fs21.mkdirSync(DIRS.results, { recursive: true });
14465
14696
  } catch (error) {
14466
14697
  return storageFailure(error);
@@ -14468,6 +14699,7 @@ function createSubagentExecutor(deps) {
14468
14699
  const controller = new AbortController();
14469
14700
  deps2.state.workflowControllers ??= /* @__PURE__ */ new Map();
14470
14701
  deps2.state.workflowChildStops ??= /* @__PURE__ */ new Map();
14702
+ deps2.state.workflowDrains ??= /* @__PURE__ */ new Map();
14471
14703
  deps2.state.workflowControllers.set(workflowRunId, controller);
14472
14704
  workflowCapacity?.markWorkflowStarted();
14473
14705
  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 +15224,30 @@ Parent action: ${STATUS_ACTION}`,
14992
15224
  if (stop) deps2.state.workflowChildStops?.set(workflowRunId, stop);
14993
15225
  else deps2.state.workflowChildStops?.delete(workflowRunId);
14994
15226
  },
15227
+ registerDrain: (drain) => {
15228
+ if (!drain) deps2.state.workflowDrains?.delete(workflowRunId);
15229
+ else deps2.state.workflowDrains?.set(workflowRunId, () => {
15230
+ if (workflowRunEvidence.drainRequestedAt === void 0) {
15231
+ const previousWorkflow = status.workflow;
15232
+ workflowRunEvidence.drainRequestedAt = Date.now();
15233
+ status.workflow = { ...previousWorkflow ?? { trace: [], emits: [], console: [] }, drainRequestedAt: workflowRunEvidence.drainRequestedAt };
15234
+ let saved = false;
15235
+ try {
15236
+ persist();
15237
+ saved = runPersistence.pendingCount() === 0;
15238
+ } catch (error) {
15239
+ console.error(`Failed to save the drain request for async workflow '${workflowRunId}':`, error);
15240
+ }
15241
+ if (!saved) {
15242
+ delete workflowRunEvidence.drainRequestedAt;
15243
+ status.workflow = previousWorkflow;
15244
+ persist({ tolerateStatusWriteFailure: true });
15245
+ return { ok: false };
15246
+ }
15247
+ }
15248
+ return { ok: true, started: drain(() => queueMicrotask(() => controller.abort(new Error("Workflow drained: started children finished; no new children were started.")))) };
15249
+ });
15250
+ },
14995
15251
  ...workflowState2 ? { state: workflowState2 } : {},
14996
15252
  onTrace: updateTrace,
14997
15253
  onChildSettled: (notification) => {
@@ -15100,7 +15356,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15100
15356
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
15101
15357
  });
15102
15358
  let preparedChildParams;
15103
- const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, () => {
15359
+ const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, async () => {
15104
15360
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
15105
15361
  { ...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
15362
  missionBinding2,
@@ -15109,6 +15365,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15109
15365
  inheritedNestedRoute(deps2)?.rootRunId
15110
15366
  );
15111
15367
  preparedChildParams = childRequest;
15368
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
15369
+ if (launchRefusal) return buildRequestedModeError(childRequest, launchRefusal);
15112
15370
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
15113
15371
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
15114
15372
  workflowLaunchObservers.set(childRequest, (launch) => {
@@ -15137,6 +15395,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15137
15395
  step2.currentToolArgs = progress.currentToolArgs;
15138
15396
  step2.currentToolStartedAt = progress.currentToolStartedAt;
15139
15397
  step2.currentPath = progress.currentPath;
15398
+ step2.progressText = progress.progressText;
15399
+ step2.progressUpdatedAt = progress.progressUpdatedAt;
15140
15400
  step2.recentTools = progress.recentTools.map((tool) => ({ ...tool }));
15141
15401
  step2.recentOutput = [...progress.recentOutput];
15142
15402
  step2.turnCount = progress.turnCount;
@@ -15383,7 +15643,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15383
15643
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
15384
15644
  });
15385
15645
  let preparedChildParams;
15386
- const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, () => {
15646
+ const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, async () => {
15387
15647
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
15388
15648
  { ...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
15649
  missionBinding2,
@@ -15392,6 +15652,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15392
15652
  inheritedNestedRoute(deps2)?.rootRunId
15393
15653
  );
15394
15654
  preparedChildParams = childRequest;
15655
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
15656
+ if (launchRefusal) return buildRequestedModeError(childRequest, launchRefusal);
15395
15657
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
15396
15658
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
15397
15659
  if (delegatedWorkflowPermit) {
@@ -16095,6 +16357,7 @@ ${item.text}` } : item)
16095
16357
  }
16096
16358
  if (action === "stop") {
16097
16359
  const targetRunId = paramsWithResolvedCwd.runId ?? paramsWithResolvedCwd.id;
16360
+ 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
16361
  const workflowRunId = targetRunId && paramsWithResolvedCwd.childId !== void 0 ? resolveLiveWorkflowRunId(deps2, targetRunId) : void 0;
16099
16362
  if (workflowRunId && paramsWithResolvedCwd.childId !== void 0) {
16100
16363
  const stopChild = deps2.state.workflowChildStops?.get(workflowRunId);
@@ -16134,7 +16397,7 @@ ${item.text}` } : item)
16134
16397
  if (paramsWithResolvedCwd.dir) {
16135
16398
  try {
16136
16399
  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);
16400
+ const stopResult2 = stopAsyncRun(deps2.state, location.resolvedId ?? targetRunId ?? path19.basename(location.asyncDir ?? paramsWithResolvedCwd.dir), deps2.kill, location, paramsWithResolvedCwd.childId, paramsWithResolvedCwd.drain);
16138
16401
  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
16402
  } catch (error) {
16140
16403
  const text = error instanceof Error ? error.message : String(error);
@@ -16155,7 +16418,8 @@ ${item.text}` } : item)
16155
16418
  resolved?.kind === "async" ? resolved.id : targetRunId,
16156
16419
  deps2.kill,
16157
16420
  resolved?.kind === "async" ? resolved.location : void 0,
16158
- paramsWithResolvedCwd.childId
16421
+ paramsWithResolvedCwd.childId,
16422
+ paramsWithResolvedCwd.drain
16159
16423
  );
16160
16424
  if (stopResult) return stopResult;
16161
16425
  return {
@@ -16365,6 +16629,12 @@ ${item.text}` } : item)
16365
16629
  const launcherError = agent ? resolveAgentRunnerLauncher(agent, deps2.config.runnerLaunchers, effectiveParams.machine ?? agent.machine).error : void 0;
16366
16630
  if (launcherError) return buildRequestedModeError(effectiveParams, launcherError);
16367
16631
  }
16632
+ if (effectiveParams.requireLauncher !== void 0) {
16633
+ if (!effectiveParams.requireLauncher || typeof effectiveParams.requireLauncher !== "object") return buildRequestedModeError(effectiveParams, "requireLauncher must be { name, definitionDigest }.");
16634
+ if (!hasSingle || effectiveParams.resume !== void 0 || effectiveParams.workflowParentRunId !== void 0) return buildRequestedModeError(effectiveParams, REQUIRE_LAUNCHER_SHAPE_ERROR);
16635
+ const required = selectedAgents[0] ? checkRequiredRunnerLauncher(selectedAgents[0], selectedAgents[0].launcher, effectiveParams.requireLauncher) : void 0;
16636
+ if (required?.error) return buildRequestedModeError(effectiveParams, required.error);
16637
+ }
16368
16638
  if (effectiveAsync && hasSingle && effectiveParams.resume === void 0 && effectiveParams.worktree === true) {
16369
16639
  try {
16370
16640
  await preflightWorktreeSource(effectiveCwd, { signal });
@@ -16640,6 +16910,7 @@ ${item.text}` } : item)
16640
16910
  parentModel: requestParentModel,
16641
16911
  scopedModelIds: scopedModelIdsFromContext(ctx),
16642
16912
  availableModels: ctx.modelRegistry.getAvailable().map(toModelInfo),
16913
+ knownProviders: knownModelProviders(ctx.modelRegistry),
16643
16914
  currentProvider: requestParentModel?.provider,
16644
16915
  modelScope,
16645
16916
  thinkingOverrideForTask,
@@ -16919,7 +17190,6 @@ export {
16919
17190
  promptAuditRedoParams,
16920
17191
  readNestedRecoveryDescriptor,
16921
17192
  removeForegroundControlIfIdle,
16922
- resolveConfigDefaultTimeoutMs,
16923
17193
  resolveForegroundTimeout,
16924
17194
  resolveRevivalControlConfig,
16925
17195
  resolveSingleAgentLaunchTimeout,