pi-subagents 0.84.0 → 0.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (204) hide show
  1. package/CHANGELOG.md +62 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-235AWJUQ.js → chunk-3UZ5FVVJ.js} +310 -101
  5. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  6. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  7. package/bundle/{chunk-VQVVHSY6.js → chunk-DV2NCNPR.js} +22 -11
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-NKQ6JNAS.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/chunk-HXRB42AF.js +108 -0
  12. package/bundle/{chunk-7BWGNDNK.js → chunk-IQIWF2VX.js} +190 -1177
  13. package/bundle/{chunk-XDQORLZ5.js → chunk-JNXT3MPI.js} +15 -6
  14. package/bundle/{chunk-J5YL7LYR.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-JG4QKI5M.js → chunk-JWYG26RE.js} +209 -93
  16. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  17. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  18. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  19. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  20. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  21. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  22. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  23. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  24. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  25. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  26. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  27. package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
  28. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  29. package/bundle/chunk-T5V5BRCL.js +1067 -0
  30. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  31. package/bundle/{chunk-DZDETGRJ.js → chunk-WOVMHDES.js} +231 -182
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +1 -1
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +5 -9
  78. package/src/runs/background/async-execution.js +62 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.js +6 -1
  83. package/src/runs/background/auto-drain.js +2 -1
  84. package/src/runs/background/boot-id.d.ts +1 -3
  85. package/src/runs/background/boot-id.js +1 -3
  86. package/src/runs/background/completion-batcher.d.ts +3 -4
  87. package/src/runs/background/completion-batcher.js +2 -3
  88. package/src/runs/background/control-channel.d.ts +0 -6
  89. package/src/runs/background/control-channel.js +0 -6
  90. package/src/runs/background/fleet-view.js +2 -3
  91. package/src/runs/background/notify.d.ts +0 -2
  92. package/src/runs/background/notify.js +0 -2
  93. package/src/runs/background/result-watcher.d.ts +1 -0
  94. package/src/runs/background/result-watcher.js +59 -29
  95. package/src/runs/background/resume-guidance.js +4 -2
  96. package/src/runs/background/retained-children.js +2 -1
  97. package/src/runs/background/run-child-session.d.ts +0 -1
  98. package/src/runs/background/run-child-session.js +1 -1
  99. package/src/runs/background/run-status.js +4 -3
  100. package/src/runs/background/scheduled-runs.d.ts +3 -1
  101. package/src/runs/background/scheduled-runs.js +13 -16
  102. package/src/runs/background/subagent-runner.d.ts +2 -4
  103. package/src/runs/background/subagent-runner.js +9 -6
  104. package/src/runs/background/subagent-wait.js +12 -15
  105. package/src/runs/background/wait-config.d.ts +2 -0
  106. package/src/runs/background/wait-config.js +17 -3
  107. package/src/runs/background/wait-tool.js +4 -2
  108. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  109. package/src/runs/background/workflow-terminal-proof.js +0 -1
  110. package/src/runs/foreground/execution.d.ts +0 -3
  111. package/src/runs/foreground/execution.js +17 -9
  112. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  113. package/src/runs/foreground/subagent-executor.js +107 -26
  114. package/src/runs/shared/child-commands.js +15 -2
  115. package/src/runs/shared/child-hooks.d.ts +1 -7
  116. package/src/runs/shared/child-hooks.js +13 -5
  117. package/src/runs/shared/child-launch.js +6 -2
  118. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  119. package/src/runs/shared/child-session.d.ts +1 -1
  120. package/src/runs/shared/child-session.js +21 -2
  121. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  122. package/src/runs/shared/child-tool-plan.js +0 -1
  123. package/src/runs/shared/claude-code-adapter.js +11 -0
  124. package/src/runs/shared/external-cli-runner.js +26 -6
  125. package/src/runs/shared/herdr-connection.js +2 -1
  126. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  127. package/src/runs/shared/herdr-pane-host.js +17 -1
  128. package/src/runs/shared/herdr-placed-run.js +48 -22
  129. package/src/runs/shared/lane-metadata.d.ts +0 -1
  130. package/src/runs/shared/lane-metadata.js +0 -1
  131. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  132. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  133. package/src/runs/shared/model-resolution.d.ts +2 -2
  134. package/src/runs/shared/model-resolution.js +7 -1
  135. package/src/runs/shared/model-scope.d.ts +1 -5
  136. package/src/runs/shared/model-scope.js +1 -5
  137. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  138. package/src/runs/shared/mutation-evidence.js +52 -7
  139. package/src/runs/shared/nested-events.d.ts +1 -0
  140. package/src/runs/shared/nested-events.js +1 -1
  141. package/src/runs/shared/parallel-utils.d.ts +0 -1
  142. package/src/runs/shared/permissions.js +5 -3
  143. package/src/runs/shared/placement-host.d.ts +5 -1
  144. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  145. package/src/runs/shared/rex-pane-host.js +0 -2
  146. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  147. package/src/runs/shared/run-launch-folder.js +21 -0
  148. package/src/runs/shared/runner-launcher.d.ts +12 -1
  149. package/src/runs/shared/runner-launcher.js +16 -0
  150. package/src/runs/shared/single-output.d.ts +3 -3
  151. package/src/runs/shared/single-output.js +5 -3
  152. package/src/runs/shared/structured-output.d.ts +8 -0
  153. package/src/runs/shared/structured-output.js +30 -2
  154. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  155. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  156. package/src/runs/shared/tool-timeout.js +2 -1
  157. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  158. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  159. package/src/runs/shared/worktree.d.ts +3 -0
  160. package/src/runs/shared/worktree.js +20 -0
  161. package/src/shared/capacity-resilient-json.d.ts +1 -1
  162. package/src/shared/child-cache-retention.d.ts +1 -2
  163. package/src/shared/child-cache-retention.js +1 -2
  164. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  165. package/src/shared/fleet-transcript-reader.js +333 -0
  166. package/src/shared/formatters.d.ts +0 -18
  167. package/src/shared/formatters.js +0 -18
  168. package/src/shared/session-succession.d.ts +16 -1
  169. package/src/shared/session-succession.js +41 -2
  170. package/src/shared/session-warnings.d.ts +7 -0
  171. package/src/shared/session-warnings.js +26 -0
  172. package/src/shared/settings.d.ts +0 -23
  173. package/src/shared/settings.js +3 -35
  174. package/src/shared/types.d.ts +28 -11
  175. package/src/shared/types.js +0 -12
  176. package/src/shared/utils.d.ts +0 -14
  177. package/src/shared/utils.js +0 -22
  178. package/src/shared/wait-tool-name.d.ts +8 -0
  179. package/src/shared/wait-tool-name.js +13 -0
  180. package/src/slash/slash-commands.js +2 -1
  181. package/src/slash/subagent-cost.d.ts +3 -2
  182. package/src/slash/subagent-cost.js +22 -3
  183. package/src/slash/subagents-admin.js +0 -1
  184. package/src/tui/fleet-status.d.ts +0 -5
  185. package/src/tui/fleet-status.js +4 -24
  186. package/src/tui/fleet-transcript.d.ts +1 -44
  187. package/src/tui/fleet-transcript.js +1 -327
  188. package/src/tui/fleet.js +6 -4
  189. package/src/tui/render.d.ts +0 -9
  190. package/src/tui/render.js +81 -47
  191. package/src/tui/subagent-messages.js +3 -2
  192. package/src/watchdog/register-child.d.ts +2 -3
  193. package/src/watchdog/register-child.js +2 -3
  194. package/src/watchdog/turn-delta.js +2 -1
  195. package/src/workflows/scripted-workflow.js +241 -20
  196. package/src/workflows/workflow-launch-record.d.ts +15 -6
  197. package/src/workflows/workflow-launch-record.js +30 -12
  198. package/src/workflows/workflow-resume-claim.js +2 -2
  199. package/src/workflows/workflow-resume.d.ts +1 -1
  200. package/src/workflows/workflow-resume.js +11 -8
  201. package/src/workflows/workflow-script-worker.d.ts +13 -0
  202. package/src/workflows/workflow-script-worker.js +79 -0
  203. package/workflow-script-process.cjs +36 -0
  204. package/workflow-script-worker.cjs +4 -1
@@ -3,7 +3,7 @@ import {
3
3
  projectRuntimeAcknowledgedExtensions,
4
4
  registerSubagentPromptBoundary,
5
5
  registerSubagentPromptRuntime
6
- } from "./chunk-XDQORLZ5.js";
6
+ } from "./chunk-JNXT3MPI.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-4E7BKDTX.js";
28
+ } from "./chunk-CS4O36CZ.js";
29
29
  import {
30
30
  PLACED_RESTORE_UNSUPPORTED,
31
31
  formatHerdrMachineRunnerUnsupported,
32
- isRexLocalMachine,
33
32
  resolveMachinePlacement
34
- } from "./chunk-2D52JFLF.js";
33
+ } from "./chunk-N7B2KD74.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,25 +118,21 @@ import {
118
118
  workflowResumeTargetId,
119
119
  workflowScriptDigest,
120
120
  workflowStopCause,
121
- writeWorkflowLaunchRecord,
122
121
  writeWorkflowReceipt
123
- } from "./chunk-DZDETGRJ.js";
122
+ } from "./chunk-WOVMHDES.js";
124
123
  import {
125
- NATIVE_SUPERVISOR_TOOL_NAME,
126
124
  SUBAGENT_PARENT_SESSION_ENV,
127
125
  applyWatchdogLaunchRules,
128
- createNativeSupervisorChannel,
129
126
  createSubagentParamsSchema,
130
127
  finalizeToolResult,
131
128
  registerPinnedTool,
132
129
  resolveCurrentSessionId,
133
130
  resolvePiSessionId,
134
- resolveSupervisorChannelDir,
135
131
  resolveWaitToolConfig,
136
132
  resolveWatchdogConfig,
137
133
  sendRuleViolationWarning,
138
134
  writeWatchdogModelSettings
139
- } from "./chunk-7BWGNDNK.js";
135
+ } from "./chunk-IQIWF2VX.js";
140
136
  import {
141
137
  MAX_REMEMBERED_FOREGROUND_RUNS,
142
138
  discardRunningForegroundRun,
@@ -149,9 +145,8 @@ import {
149
145
  resolveSubagentRunId,
150
146
  resolveWorkflowChatProgress,
151
147
  stopAsyncRun
152
- } from "./chunk-NENDSQUY.js";
148
+ } from "./chunk-KZ34KQQH.js";
153
149
  import {
154
- MODEL_ONLY_TOOL,
155
150
  RunFanoutLimitError,
156
151
  annotateWorkflowPreflightTrace,
157
152
  applySteeringRecoveryAgentConfig,
@@ -181,13 +176,11 @@ import {
181
176
  formatWorkflowPreflightWarnings,
182
177
  formatWorkflowStageLine,
183
178
  getRunFanoutBudgetSnapshot,
184
- inheritedSessionIds,
185
179
  isStoppableAsyncStatusStep,
186
180
  isTerminalParallelHandoffChildStatus,
187
181
  listAsyncRuns,
188
182
  normalizeWorkflowPreflight,
189
183
  opencodeSessionHeaders,
190
- ownsRun,
191
184
  parallelHandoffPath,
192
185
  parseWorkflowChildSummary,
193
186
  projectWorkflowChecklist,
@@ -197,6 +190,7 @@ import {
197
190
  readRunFanoutBudgetDescriptor,
198
191
  recordParallelHandoffMerge,
199
192
  recordParallelHandoffSupersession,
193
+ recoveryDescriptorPath,
200
194
  resolveAsyncResumeTarget,
201
195
  resolveAsyncRunLocation,
202
196
  resolveAsyncStatusChild,
@@ -210,8 +204,20 @@ import {
210
204
  workflowPreflightWarnings,
211
205
  writeParallelHandoffGroup,
212
206
  writeRunFanoutBudgetDescriptor,
207
+ writeWorkflowLaunchRecord,
213
208
  writeWorktreeSetupHandoff
214
- } from "./chunk-L3WFKBEI.js";
209
+ } from "./chunk-LTPH2DXH.js";
210
+ import {
211
+ NATIVE_SUPERVISOR_TOOL_NAME,
212
+ createNativeSupervisorChannel,
213
+ resolveSupervisorChannelDir
214
+ } from "./chunk-T5V5BRCL.js";
215
+ import {
216
+ MODEL_ONLY_TOOL,
217
+ inheritedSessionIds,
218
+ ownsRun,
219
+ reportSessionWarning
220
+ } from "./chunk-HXRB42AF.js";
215
221
  import {
216
222
  authorizeWorkflowResourceHost,
217
223
  claimWorkflowChildPermit,
@@ -228,10 +234,10 @@ import {
228
234
  canPreferFork,
229
235
  createForkContextResolver,
230
236
  resolveSubagentLaunchContext
231
- } from "./chunk-SSG7IEP5.js";
237
+ } from "./chunk-RQAUNAWG.js";
232
238
  import {
233
239
  handleRefinementAction
234
- } from "./chunk-LFDBD4PW.js";
240
+ } from "./chunk-QO75KJBT.js";
235
241
  import {
236
242
  ActiveAsyncCapacityError,
237
243
  acquireActiveAsyncCapacity,
@@ -246,18 +252,21 @@ import {
246
252
  resolveDisabledFeatureSurface,
247
253
  resolveMaxActiveAsyncRunsPerSession,
248
254
  transferActiveAsyncCapacity
249
- } from "./chunk-PALJGGYC.js";
255
+ } from "./chunk-RV5OGHLO.js";
250
256
  import {
251
257
  DEFAULT_STALE_TERMINAL_ACTIVE_MARKER_MS,
252
258
  MACHINE_DIFF_OPTIONS,
253
259
  MISSION_ACTIONS,
254
260
  MissionNotFoundError,
261
+ REQUIRE_LAUNCHER_SHAPE_ERROR,
255
262
  WORKTREE_AGENT_CWD_PLACEHOLDER,
256
263
  WorkflowScriptError,
257
264
  activeRunMarkerAgeMs,
258
265
  attachMissionToLaunchResult,
259
266
  attachRootChildrenToSteps,
267
+ buildWorktreeNaming,
260
268
  checkRecordedPidLiveness,
269
+ checkRequiredRunnerLauncher,
261
270
  cleanupWorktrees,
262
271
  createMissionWorkflowState,
263
272
  createNestedRoute,
@@ -280,6 +289,7 @@ import {
280
289
  inheritedNestedParentAddressOf,
281
290
  inheritedNestedRouteOf,
282
291
  initializeProcessTerminal,
292
+ lookupRunnerLauncher,
283
293
  missionAcceptanceStatus,
284
294
  nestedResultsPath,
285
295
  nestedRunNotActiveMessage,
@@ -297,6 +307,7 @@ import {
297
307
  readWorkflowTerminalProof,
298
308
  reconcileAsyncRun,
299
309
  reconcileNestedAsyncDescendants,
310
+ resolveAgentRunnerLauncher,
300
311
  resolveAuthorityDecision,
301
312
  resolveExpectedWorktreeAgentCwd,
302
313
  resolveInheritedNestedRoute,
@@ -309,6 +320,7 @@ import {
309
320
  retainNestedLookupRoute,
310
321
  retireResultSnapshot,
311
322
  runWorkflowScript,
323
+ runnerLauncherPlacementError,
312
324
  sanitizeProcessTerminal,
313
325
  shouldDeferWorktreeCwd,
314
326
  snapshotNestedEventFiles,
@@ -326,7 +338,7 @@ import {
326
338
  writeNestedControlRequest,
327
339
  writeNestedControlResult,
328
340
  writeNestedEvent
329
- } from "./chunk-CGN2TVE7.js";
341
+ } from "./chunk-LGMILZNE.js";
330
342
  import {
331
343
  closeSteerInbox,
332
344
  consumeSteerRequests,
@@ -334,7 +346,7 @@ import {
334
346
  readRevivalBriefs,
335
347
  requestAsyncSteer,
336
348
  watchAsyncControlInbox
337
- } from "./chunk-F4ASL6OV.js";
349
+ } from "./chunk-7MAE3DJV.js";
338
350
  import "./chunk-NIXWDZZV.js";
339
351
  import {
340
352
  INTERCOM_BRIDGE_MARKER,
@@ -343,8 +355,9 @@ import {
343
355
  resolveIntercomBridge,
344
356
  resolveIntercomSessionTarget,
345
357
  resolveSubagentIntercomTarget
346
- } from "./chunk-C5P5CHYK.js";
358
+ } from "./chunk-KDMFBYFM.js";
347
359
  import {
360
+ agentDefinitionDigest,
348
361
  resolveLaunchBinding,
349
362
  stableJsonDigest
350
363
  } from "./chunk-7F6RKT6W.js";
@@ -357,7 +370,7 @@ import {
357
370
  resolvePiLaunchToolPlan,
358
371
  resolveRuntimeModulePath,
359
372
  supervisorChannelDir
360
- } from "./chunk-V2BZYLEP.js";
373
+ } from "./chunk-KEY3UQMQ.js";
361
374
  import {
362
375
  assertRequiredChildExtensionsAdmitted,
363
376
  hasMandatoryRequiredChildExtensions,
@@ -368,7 +381,7 @@ import {
368
381
  import {
369
382
  HERDR_PROJECT_PANE_ACTIONS,
370
383
  handleHerdrProjectPaneAction
371
- } from "./chunk-2DHZTCOL.js";
384
+ } from "./chunk-PVIVCDG2.js";
372
385
  import "./chunk-7J4ZXMY7.js";
373
386
  import {
374
387
  PROJECT_SUBAGENTS_RELATIVE_DIR,
@@ -381,14 +394,15 @@ import {
381
394
  getProjectSubagentsDir,
382
395
  writeArtifact,
383
396
  writeMetadata
384
- } from "./chunk-D3JAFGMO.js";
397
+ } from "./chunk-PHZP3KHB.js";
385
398
  import "./chunk-XA3DY6UG.js";
386
399
  import {
387
400
  getExternalJobProvider
388
401
  } from "./chunk-YYREO77V.js";
389
- import "./chunk-G2Z6ZH26.js";
402
+ import "./chunk-GCSLVFCX.js";
390
403
  import {
391
404
  ChainOutputValidationError,
405
+ DEFAULT_WAIT_TOOL_NAME,
392
406
  MAX_STREAMED_RECENT_TOOLS,
393
407
  MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR,
394
408
  MISSING_STRUCTURED_OUTPUT_CALL_ERROR,
@@ -467,9 +481,11 @@ import {
467
481
  isDynamicRunnerGroup,
468
482
  isParallelGroup,
469
483
  isParallelStep,
484
+ isRexLocalMachine,
470
485
  isSettlementFatalOutputError,
471
486
  isStorageCapacityError,
472
487
  isToolBudgetBlockedMessage,
488
+ normalizeAcceptanceInput,
473
489
  normalizeExtensionBindings,
474
490
  normalizeExternalCliRunnerStatus,
475
491
  normalizeGateAcceptance,
@@ -513,6 +529,7 @@ import {
513
529
  scopedModelIdsFromContext,
514
530
  splitKnownThinkingSuffix,
515
531
  stripAcceptanceReport,
532
+ structuredOutputValidatorReady,
516
533
  suggestAgentName,
517
534
  sumResultsCost,
518
535
  sumResultsUsage,
@@ -529,10 +546,11 @@ import {
529
546
  validateExecutionAcceptancePolicy,
530
547
  validateFileOnlyOutputMode,
531
548
  validateToolBudgetConfig,
549
+ waitToolName,
532
550
  writeAtomicJson,
533
551
  writeInitialProgressFile,
534
552
  writePrivateAtomicJson
535
- } from "./chunk-LNRJCP2Y.js";
553
+ } from "./chunk-UX4SCV5N.js";
536
554
  import {
537
555
  CHAIN_RUNS_DIR,
538
556
  DEFAULT_ARTIFACT_CONFIG,
@@ -780,7 +798,7 @@ import * as fs7 from "node:fs";
780
798
  import * as path6 from "node:path";
781
799
 
782
800
  // src/runs/background/async-execution.ts
783
- import { spawn } from "node:child_process";
801
+ import { spawn, spawnSync } from "node:child_process";
784
802
  import { randomUUID as randomUUID2 } from "node:crypto";
785
803
  import * as fs6 from "node:fs";
786
804
  import * as path5 from "node:path";
@@ -1151,10 +1169,14 @@ function childHooks(config, capture, holdFinalDrain) {
1151
1169
  }
1152
1170
  const hooks = [
1153
1171
  { name: "pi-subagents:prompt-runtime", factory: function promptRuntime(pi) {
1154
- if (!proof?.observeNext) return registerSubagentPromptRuntime(pi, runtime);
1155
- proof.observation = proof.observeNext;
1156
- proof.observeNext = void 0;
1157
- registerSubagentPromptRuntime(pi, runtime, proof.observation);
1172
+ if (!proof?.observeNext) {
1173
+ registerSubagentPromptRuntime(pi, runtime);
1174
+ } else {
1175
+ proof.observation = proof.observeNext;
1176
+ proof.observeNext = void 0;
1177
+ registerSubagentPromptRuntime(pi, runtime, proof.observation);
1178
+ }
1179
+ if (runtime.structuredOutput) return structuredOutputValidatorReady();
1158
1180
  } }
1159
1181
  ];
1160
1182
  if (config.fast) hooks.push({ name: "pi-subagents:fast-mode", factory: (pi) => registerSubagentFastModeExtension(pi) });
@@ -1214,7 +1236,8 @@ function childStorage(input) {
1214
1236
  return { kind: "default" };
1215
1237
  }
1216
1238
  function buildInProcessChildLaunch(input) {
1217
- const requiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
1239
+ const resolvedRequiredExtensions = input.requiredExtensions ?? input.inherited?.requiredExtensions ?? resolveRequiredChildExtensions(input.parentSessionId);
1240
+ const requiredExtensions = input.machine ? resolvedRequiredExtensions.filter((entry) => entry.requireForAllRunners) : resolvedRequiredExtensions;
1218
1241
  const agentCapabilityCeiling = input.descendantAllowedAgents === void 0 ? void 0 : { version: 1, allowedAgents: [...input.descendantAllowedAgents], denyExtensions: false, sources: [`agent:${input.childAgentName}`] };
1219
1242
  const inheritedCeiling = inheritedCapabilityCeiling(input.inherited);
1220
1243
  const capabilityCeilingForPlanning = agentCapabilityCeiling && !input.capabilityCeiling && !inheritedCeiling ? { version: 1, denyExtensions: false, sources: [] } : input.capabilityCeiling;
@@ -1300,7 +1323,8 @@ function buildInProcessChildLaunch(input) {
1300
1323
  ...input.watchdogStatus ? { watchdogStatus: input.watchdogStatus } : {},
1301
1324
  waitTool: {
1302
1325
  enabled: input.waitToolEnabled ?? true,
1303
- ...input.waitToolDefaultTimeoutMs !== void 0 ? { defaultTimeoutMs: input.waitToolDefaultTimeoutMs } : {}
1326
+ ...input.waitToolDefaultTimeoutMs !== void 0 ? { defaultTimeoutMs: input.waitToolDefaultTimeoutMs } : {},
1327
+ ...waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { name: waitToolName() } : {}
1304
1328
  },
1305
1329
  ...input.structuredOutput ? {
1306
1330
  structuredOutput: {
@@ -1574,25 +1598,6 @@ function statusStepDescription(task) {
1574
1598
  return description.length > MAX_STATUS_STEP_DESCRIPTION_CHARS ? `${description.slice(0, MAX_STATUS_STEP_DESCRIPTION_CHARS - 1)}\u2026` : description;
1575
1599
  }
1576
1600
 
1577
- // src/runs/shared/runner-launcher.ts
1578
- function lookupRunnerLauncher(runnerLaunchers, name) {
1579
- const argv = runnerLaunchers && Object.hasOwn(runnerLaunchers, name) ? runnerLaunchers[name] : void 0;
1580
- return argv ? { name, argv: [...argv] } : void 0;
1581
- }
1582
- function runnerLauncherPlacementError(agent, machine) {
1583
- if (agent.launcher === void 0) return void 0;
1584
- const runnerType = agent.runner?.type === "external-cli" || agent.runner?.type === "external-job" ? agent.runner.type : void 0;
1585
- if (!machine && !runnerType) return void 0;
1586
- 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}'`}.`;
1587
- }
1588
- function resolveAgentRunnerLauncher(agent, runnerLaunchers, machine) {
1589
- if (agent.launcher === void 0) return {};
1590
- const placementError = runnerLauncherPlacementError(agent, machine);
1591
- if (placementError) return { error: placementError };
1592
- const launcher = lookupRunnerLauncher(runnerLaunchers, agent.launcher);
1593
- return launcher ? { launcher } : { error: `Agent '${agent.name}' uses launcher '${agent.launcher}', which is not defined in runnerLaunchers in the user subagent config.` };
1594
- }
1595
-
1596
1601
  // src/runs/background/async-execution.ts
1597
1602
  var require2 = nodeModule.createRequire(new URL("../src/runs/background/async-execution.js", import.meta.url).href);
1598
1603
  var piPackageSelection = (() => {
@@ -1657,10 +1662,10 @@ function parentExtensionProviderForChild(ctx, disableAmbientExtensions, model, a
1657
1662
  var DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1e3;
1658
1663
  function formatAsyncStartedMessage(headline, interactive) {
1659
1664
  const guidance = interactive ? [
1660
- "Detached. Return control now: native completion wakes you, so do not sleep, poll, or call bg_wait for it.",
1665
+ `Detached. Return control now: native completion wakes you, so do not sleep, poll, or call ${waitToolName()} for it.`,
1661
1666
  'One-shot check: subagent({ action: "status", id: "..." }).'
1662
1667
  ] : [
1663
- '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.'
1668
+ `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.`
1664
1669
  ];
1665
1670
  return [headline, "", ...guidance].join("\n");
1666
1671
  }
@@ -1761,6 +1766,28 @@ function terminateRunnerBeforeProceed(pid) {
1761
1766
  }
1762
1767
  return !runnerIsAlive(pid);
1763
1768
  }
1769
+ function parentPid(pid) {
1770
+ let ppid;
1771
+ if (process.platform === "linux") {
1772
+ try {
1773
+ const stat = fs6.readFileSync(`/proc/${pid}/stat`, "utf-8");
1774
+ ppid = Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]);
1775
+ } catch {
1776
+ return void 0;
1777
+ }
1778
+ } else {
1779
+ const result2 = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf-8" });
1780
+ if (result2.error || result2.status !== 0) return void 0;
1781
+ ppid = Number(result2.stdout.trim());
1782
+ }
1783
+ return Number.isSafeInteger(ppid) && ppid > 0 ? ppid : void 0;
1784
+ }
1785
+ function isInProcessTree(pid, rootPid) {
1786
+ for (let current = pid; current !== void 0 && current > 1; current = parentPid(current)) {
1787
+ if (current === rootPid) return true;
1788
+ }
1789
+ return false;
1790
+ }
1764
1791
  async function terminateRunnerBeforeProceedAsyncDefault(proc, processClosed) {
1765
1792
  for (const signal of ["SIGTERM", "SIGKILL"]) {
1766
1793
  if (proc.pid === void 0 || !runnerIsAlive(proc.pid)) return true;
@@ -1896,7 +1923,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
1896
1923
  const launchBarrierToken = hasRevivalLease ? void 0 : runnerProcessInstanceId;
1897
1924
  const launcher = cfg.launcher;
1898
1925
  const bootId = launcher ? void 0 : currentBootId();
1899
- const launchConfig = { ...cfg, runnerProcessInstanceId, ...launchBarrierToken ? { launchBarrierToken } : {}, ...bootId ? { bootId } : {} };
1926
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...launchBarrierToken ? { launchBarrierToken } : {}, ...bootId ? { bootId } : {}, ...waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { waitToolName: waitToolName() } : {} };
1900
1927
  writePrivateAtomicJson(cfgPath, launchConfig);
1901
1928
  const command = binaryHost ?? nodeExecutable;
1902
1929
  const launchForStartup = launchConfig;
@@ -1915,7 +1942,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
1915
1942
  const identityPath = launcher && launchBarrierToken && launchAsyncDir ? path5.join(launchAsyncDir, "runner-startup.json") : void 0;
1916
1943
  if (identityPath) fs6.rmSync(identityPath, { force: true });
1917
1944
  let runnerIdentity;
1918
- const terminateBeforeProceed = (pid) => !launcher ? terminateRunnerBeforeProceed(pid) : runnerIdentity !== void 0 && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && terminateRunnerBeforeProceed(runnerIdentity.pid);
1945
+ const terminateBeforeProceed = (pid) => !launcher ? terminateRunnerBeforeProceed(pid) : runnerIdentity !== void 0 && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && isInProcessTree(runnerIdentity.pid, pid) && terminateRunnerBeforeProceed(runnerIdentity.pid);
1919
1946
  const adoptRunnerIdentity = (pid, pidNamespaceScope) => {
1920
1947
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1) return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
1921
1948
  runnerIdentity = { pid, ...typeof pidNamespaceScope === "string" ? { pidNamespaceScope } : {} };
@@ -2294,7 +2321,7 @@ function buildAsyncRunnerSteps(id, params) {
2294
2321
  taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
2295
2322
  taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
2296
2323
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
2297
- const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
2324
+ const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a, machine);
2298
2325
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
2299
2326
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
2300
2327
  const primaryModelFromParent = modelOrigin === "inherited";
@@ -2360,7 +2387,7 @@ function buildAsyncRunnerSteps(id, params) {
2360
2387
  const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
2361
2388
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
2362
2389
  const fast = s.fast ?? params.fast ?? a.fast;
2363
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2390
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2364
2391
  const toolPlan = resolvePiLaunchToolPlan({
2365
2392
  tools: a.tools,
2366
2393
  excludeTools: a.excludeTools,
@@ -2926,7 +2953,6 @@ function workflowAwaitedAsyncResultPath(asyncDir) {
2926
2953
  function executeAsyncSingle(id, params) {
2927
2954
  const {
2928
2955
  agent,
2929
- agentConfig,
2930
2956
  ctx,
2931
2957
  cwd,
2932
2958
  maxOutput,
@@ -2947,6 +2973,7 @@ function executeAsyncSingle(id, params) {
2947
2973
  childIntercomTarget,
2948
2974
  nestedRoute
2949
2975
  } = params;
2976
+ let agentConfig = params.agentConfig;
2950
2977
  let lane;
2951
2978
  try {
2952
2979
  lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
@@ -2995,6 +3022,11 @@ function executeAsyncSingle(id, params) {
2995
3022
  const resolvedLauncher = resolveAgentRunnerLauncher(agentConfig, ctx.runnerLaunchers, requestedMachine);
2996
3023
  if (resolvedLauncher.error) return formatAsyncStartError("single", resolvedLauncher.error);
2997
3024
  const launcher = resolvedLauncher.launcher;
3025
+ if (params.requireLauncher) {
3026
+ const required = checkRequiredRunnerLauncher(agentConfig, launcher?.name, params.requireLauncher);
3027
+ if (required.error !== void 0) return formatAsyncStartError("single", required.error);
3028
+ agentConfig = { ...agentConfig, definitionDigest: required.definitionDigest };
3029
+ }
2998
3030
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? void 0);
2999
3031
  try {
3000
3032
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
@@ -3055,7 +3087,7 @@ function executeAsyncSingle(id, params) {
3055
3087
  const outputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
3056
3088
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
3057
3089
  if (validationError) return formatAsyncStartError("single", validationError);
3058
- const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
3090
+ const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig, machine);
3059
3091
  const reads = params.reads !== void 0 ? params.reads : agentConfig.defaultReads ?? false;
3060
3092
  const readPaths = Array.isArray(reads) ? machine ? externalRunner ? reads.map((read) => read === "~" || read.startsWith("~/") || path5.posix.isAbsolute(read) ? read : path5.posix.resolve(instructionCwd, read)) : [] : managedWorktreeProvider === "worktrunk" ? resolveExistingReadInstructionPaths(reads, instructionCwd, readExistenceCwd) : resolveExistingReadPaths(reads, readExistenceCwd) : [];
3061
3093
  const readsInstruction = readPaths.length > 0 ? `[Read from: ${readPaths.join(", ")}]
@@ -3147,7 +3179,7 @@ function executeAsyncSingle(id, params) {
3147
3179
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
3148
3180
  }
3149
3181
  }
3150
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
3182
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
3151
3183
  const toolPlan = resolvePiLaunchToolPlan({
3152
3184
  tools: agentConfig.tools,
3153
3185
  excludeTools: agentConfig.excludeTools,
@@ -3195,6 +3227,7 @@ function executeAsyncSingle(id, params) {
3195
3227
  agentContract: params.agentContract
3196
3228
  });
3197
3229
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
3230
+ const requiredLauncher = params.requireLauncher ?? params.carriedRequiredLauncher;
3198
3231
  const recoveryDescriptor = {
3199
3232
  ...ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {},
3200
3233
  version: 1,
@@ -3204,6 +3237,10 @@ function executeAsyncSingle(id, params) {
3204
3237
  ...requiredExtensions.length > 0 ? { requiredExtensions } : {},
3205
3238
  runFanoutBudget,
3206
3239
  sourceRunId: id,
3240
+ ...ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {},
3241
+ // The worktree the runner will create, fixed here from launch inputs (the runner's own naming call).
3242
+ ...managedWorktreeProvider === "native" ? { managedWorktree: { provider: "native", cwd: instructionCwd } } : {},
3243
+ ...managedWorktreeProvider === "worktrunk" ? { managedWorktree: { provider: "worktrunk", branch: buildWorktreeNaming({ runId: `${id}-s0`, index: 0, agent, label: lane?.key ?? params.workflowKey, task: taskText, branchPrefix: worktreeBranchPrefix }).requestedBranch } } : {},
3207
3244
  ...params.agentContract ? { agentContract: params.agentContract } : {},
3208
3245
  agent,
3209
3246
  launchResolvedExtensions,
@@ -3241,7 +3278,8 @@ function executeAsyncSingle(id, params) {
3241
3278
  ...params.context ? { context: params.context } : {},
3242
3279
  ...params.intercomBridge !== void 0 ? { intercomBridge: params.intercomBridge } : {},
3243
3280
  ...params.baseRef !== void 0 ? { baseRef: params.baseRef } : {},
3244
- ...launcher ? { launcher: launcher.name } : {},
3281
+ launcher: launcher ? launcher.name : null,
3282
+ ...requiredLauncher ? { requiredLauncher } : {},
3245
3283
  ...deadlineAt !== void 0 ? { absoluteDeadlineAt: deadlineAt } : {},
3246
3284
  ...resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {},
3247
3285
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -3254,7 +3292,7 @@ function executeAsyncSingle(id, params) {
3254
3292
  };
3255
3293
  if (!externalRunner) {
3256
3294
  try {
3257
- writePrivateAtomicJson(path5.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
3295
+ writePrivateAtomicJson(recoveryDescriptorPath(path5.dirname(asyncDir), id), recoveryDescriptor);
3258
3296
  } catch (error) {
3259
3297
  return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
3260
3298
  }
@@ -3797,14 +3835,29 @@ function readReplyWorkflowScript(sessionManager, toolCallId) {
3797
3835
  const message = entry.message;
3798
3836
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
3799
3837
  if (!message.content.some((block) => block.type === "toolCall" && block.id === toolCallId)) continue;
3800
- return scriptFromReply(message.content);
3838
+ return scriptFromReply(message.content, () => earlierTurnHasJsBlock(branch, index));
3801
3839
  }
3802
3840
  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".' };
3803
3841
  }
3804
- function scriptFromReply(content) {
3842
+ function earlierTurnHasJsBlock(branch, callIndex) {
3843
+ for (let index = callIndex - 1; index >= 0; index--) {
3844
+ const entry = branch[index];
3845
+ if (entry.type !== "message") continue;
3846
+ if (entry.message?.role === "user") return false;
3847
+ if (entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
3848
+ const text = entry.message.content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
3849
+ const { tagged, plain } = workflowBlocks(text);
3850
+ if (tagged.length > 0 || plain.length > 0) return true;
3851
+ }
3852
+ return false;
3853
+ }
3854
+ function scriptFromReply(content, earlierBlock) {
3805
3855
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent" && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
3806
3856
  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.` };
3807
- 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}` };
3857
+ if (!content.some((block) => block.type === "text")) {
3858
+ 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." };
3859
+ return { error: `The assistant message that issued this call has no text in the session, so no \`\`\`js workflow block reached it. ${SUMMARY_NOTE}` };
3860
+ }
3808
3861
  const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
3809
3862
  const { tagged, plain, unclosed } = workflowBlocks(text);
3810
3863
  if (unclosed) return { error: "The script's fenced block in this reply is not closed." };
@@ -5795,12 +5848,20 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5795
5848
  toolAttentionTarget.attentionEmitted = true;
5796
5849
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
5797
5850
  const toolCallId = toolAttentionTarget.key.startsWith("id:") ? toolAttentionTarget.key.slice(3) : void 0;
5851
+ let hasCommandController = false;
5852
+ if (toolCallId) try {
5853
+ hasCommandController = retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId);
5854
+ } catch (error) {
5855
+ const message = `Could not read the command state of ${agent.name}; its command controls are not offered: ${error instanceof Error ? error.message : String(error)}`;
5856
+ if (options.onWarning) options.onWarning(message, "child-command-state");
5857
+ else console.warn(`[pi-subagents] ${message}`);
5858
+ }
5798
5859
  return emitNeedsAttention(now, {
5799
5860
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1e3)}s`,
5800
5861
  reason: "tool_open_threshold",
5801
5862
  currentTool: toolAttentionTarget.tool,
5802
5863
  toolCallId,
5803
- hasCommandController: Boolean(toolCallId && retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId)),
5864
+ hasCommandController,
5804
5865
  currentPath: toolAttentionTarget.path,
5805
5866
  currentToolDurationMs: durationMs
5806
5867
  });
@@ -6356,7 +6417,7 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6356
6417
  durationMs: progress.durationMs
6357
6418
  };
6358
6419
  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;
6359
- 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);
6420
+ 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);
6360
6421
  const acceptanceOutput = getFinalOutput(result2.messages ?? []);
6361
6422
  const structuredText = result2.structuredOutput === void 0 ? void 0 : JSON.stringify(result2.structuredOutput, null, 2);
6362
6423
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -6448,7 +6509,7 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
6448
6509
  }
6449
6510
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
6450
6511
  const effectiveCwd = options.cwd ?? runtimeCwd;
6451
- const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6512
+ const cwdError = options.machine && !isRexLocalMachine(options.machine) ? void 0 : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6452
6513
  if (cwdError) {
6453
6514
  return redactResultPrompt(withRunContext({
6454
6515
  index: options.index ?? 0,
@@ -8325,7 +8386,7 @@ function formatResumeGuidance(runId, children, fallbackSessionFile, options = {}
8325
8386
  const resumableWorkflowChildren = workflowChildren.filter(({ child }) => !(child.status === "paused" && child.activityState === "needs_attention"));
8326
8387
  if (workflowChildren.length > 0) {
8327
8388
  return [
8328
- ...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.`),
8389
+ ...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.`),
8329
8390
  ...resumableWorkflowChildren.map(({ child }) => `Revive workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: subagent({ action: "resume", id: "${child.runId}", message: "..." })`)
8330
8391
  ].join("\n");
8331
8392
  }
@@ -8417,7 +8478,7 @@ function formatRememberedForegroundStatus(run) {
8417
8478
  const detached = run.children.some((child) => child.status === "detached");
8418
8479
  const resumable = run.children.find((child) => hasExistingSessionFile(child.sessionFile));
8419
8480
  if (detached) {
8420
- 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.`);
8481
+ 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.`);
8421
8482
  } else if (resumable) {
8422
8483
  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} } })`);
8423
8484
  } else {
@@ -8984,13 +9045,13 @@ function applyForceTopLevelAsyncOverride(params, depth, forceTopLevelAsync) {
8984
9045
 
8985
9046
  // src/runs/shared/worktree-cleanup-apply.ts
8986
9047
  import { createHash as createHash5 } from "node:crypto";
8987
- import { spawnSync as spawnSync2 } from "node:child_process";
9048
+ import { spawnSync as spawnSync3 } from "node:child_process";
8988
9049
  import * as fs19 from "node:fs";
8989
9050
  import * as path17 from "node:path";
8990
9051
 
8991
9052
  // src/runs/shared/worktree-cleanup-plan.ts
8992
9053
  import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
8993
- import { spawnSync } from "node:child_process";
9054
+ import { spawnSync as spawnSync2 } from "node:child_process";
8994
9055
  import * as fs18 from "node:fs";
8995
9056
  import * as os2 from "node:os";
8996
9057
  import * as path16 from "node:path";
@@ -9001,7 +9062,7 @@ var MAX_PLAN_ENTRIES = 512;
9001
9062
  var MAX_METADATA_FILE_BYTES = 2 * 1024 * 1024;
9002
9063
  function runGit(cwd, args) {
9003
9064
  try {
9004
- const result2 = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
9065
+ const result2 = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
9005
9066
  return {
9006
9067
  stdout: result2.stdout ?? "",
9007
9068
  stderr: result2.stderr ?? "",
@@ -9742,7 +9803,7 @@ async function applyReviewedCleanupPlan(input) {
9742
9803
  const journalEntry = { path: entry.path, branch: entry.branch, state: "removing", reason: "removal prepared; outcome not yet recorded" };
9743
9804
  receipt.entries.push(journalEntry);
9744
9805
  writePrivateAtomicJson(receiptPath, receipt);
9745
- const removed = spawnSync2("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
9806
+ const removed = spawnSync3("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
9746
9807
  if (removed.status !== 0) throw new Error(removed.error?.message || removed.stderr.trim() || "git worktree remove failed");
9747
9808
  journalEntry.state = "removed";
9748
9809
  journalEntry.reason = "worktree removed; local branch retained";
@@ -9832,6 +9893,38 @@ function inheritedRunFanoutBudget(deps) {
9832
9893
  function resolveRequestedCwd(runtimeCwd, requestedCwd) {
9833
9894
  return requestedCwd ? path18.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
9834
9895
  }
9896
+ function workflowChildLaunchArgs(workflowRunId, key, request, scriptAgent, ctxCwd, discoverAgents2) {
9897
+ const resume = request.action === "resume" && typeof request.id === "string" ? request.id : void 0;
9898
+ const agent = request.agent ?? scriptAgent;
9899
+ const task = resume !== void 0 ? request.message : request.task;
9900
+ const scope = resolveExecutionAgentScope(request.agentScope);
9901
+ const findAgent = (dir) => typeof agent === "string" ? resolveAgentName(agent, discoverAgents2(dir, scope).agents).agent : void 0;
9902
+ const ctxAgent = request.machine === void 0 ? findAgent(ctxCwd) : void 0;
9903
+ const placed = request.machine !== void 0 || ctxAgent?.machine !== void 0;
9904
+ const runCwd = resolveRequestedCwd(ctxCwd, request.cwd);
9905
+ const cwd = resume === void 0 && !placed ? runCwd : void 0;
9906
+ const acceptanceInput = request.acceptance !== void 0 || resume !== void 0 ? request.acceptance : (placed || runCwd === ctxCwd ? ctxAgent ?? findAgent(ctxCwd) : findAgent(runCwd))?.defaultAcceptance;
9907
+ const acceptance = acceptanceInput !== void 0 && validateAcceptanceInput(acceptanceInput).length === 0 ? normalizeAcceptanceInput(acceptanceInput) : void 0;
9908
+ const commands = acceptance?.level === "verified" ? (acceptance.verify ?? []).map((verify) => ({
9909
+ command: verify.command,
9910
+ ...cwd !== void 0 ? { cwd: verify.cwd ? path18.resolve(cwd, verify.cwd) : cwd } : {},
9911
+ ...verify.env !== void 0 ? { env: verify.env } : {}
9912
+ })) : [];
9913
+ const output = resolveSingleOutputPath(request.output, ctxCwd);
9914
+ return {
9915
+ workflowRunId,
9916
+ key,
9917
+ ...typeof agent === "string" ? { agent } : {},
9918
+ ...typeof task === "string" ? { task } : {},
9919
+ ...cwd !== void 0 ? { cwd } : {},
9920
+ ...typeof request.model === "string" ? { model: request.model } : {},
9921
+ ...typeof request.async === "boolean" ? { async: request.async } : {},
9922
+ ...typeof request.worktree === "boolean" ? { worktree: request.worktree } : {},
9923
+ ...resume !== void 0 ? { resume } : {},
9924
+ ...commands.length > 0 ? { commands } : {},
9925
+ ...output !== void 0 ? { output } : {}
9926
+ };
9927
+ }
9835
9928
  function readWorkflowScriptFile(requestedPath, requestedCwd, runtimeCwd) {
9836
9929
  const scriptPath = path18.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
9837
9930
  let script;
@@ -10233,7 +10326,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
10233
10326
  if (matches.length === 0) return void 0;
10234
10327
  if (matches.length > 1) throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run2) => run2.runId).join(", ")}. Provide a longer id.`);
10235
10328
  const run = matches[0];
10236
- 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.`);
10329
+ 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.`);
10237
10330
  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.`);
10238
10331
  const index = params.index ?? 0;
10239
10332
  if (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
@@ -10356,8 +10449,7 @@ function persistAsyncWorkflowControlEvent(input) {
10356
10449
  fs20.appendFileSync(path18.join(input.job.asyncDir, "events.jsonl"), `${JSON.stringify(record2)}
10357
10450
  `, "utf-8");
10358
10451
  } catch (error) {
10359
- if (!isStorageCapacityError(error)) throw error;
10360
- console.error("Failed to append async workflow control event while storage is full:", error);
10452
+ 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");
10361
10453
  }
10362
10454
  }
10363
10455
  function emitControlNotification(input) {
@@ -10710,8 +10802,8 @@ function validateNestedSessionFile(run, trustedSessionRoots2, resolveSource, vis
10710
10802
  }
10711
10803
  return realSessionFile;
10712
10804
  }
10713
- function readNestedRecoveryDescriptor(asyncDir, runId, agent) {
10714
- const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
10805
+ function readNestedRecoveryDescriptor(rootRunId, runId, agent) {
10806
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(nestedRunScope(rootRunId).asyncDirRoot, runId);
10715
10807
  if (!recoveryDescriptor) return void 0;
10716
10808
  if (recoveryDescriptor.sourceRunId !== runId) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different source run.`);
10717
10809
  if (recoveryDescriptor.agent !== agent) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different agent.`);
@@ -10725,7 +10817,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots2, resolveSource) {
10725
10817
  if (!agent) throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
10726
10818
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
10727
10819
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
10728
- const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
10820
+ const recoveryDescriptor = asyncDir ? readNestedRecoveryDescriptor(match.match.rootRunId, run.id, agent) : void 0;
10729
10821
  return compactOptional({
10730
10822
  kind: "revive",
10731
10823
  source: "nested",
@@ -11140,6 +11232,14 @@ async function resumeAsyncRun(input) {
11140
11232
  details: { mode: "management", results: [] }
11141
11233
  };
11142
11234
  }
11235
+ const requiredLauncher = recoveryDescriptor?.requiredLauncher;
11236
+ if (requiredLauncher) {
11237
+ const refuse = (text) => ({ content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } });
11238
+ 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.`);
11239
+ const currentDigest = discoveredAgentConfig ? agentDefinitionDigest(discoveredAgentConfig) : void 0;
11240
+ 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;
11241
+ 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}.`);
11242
+ }
11143
11243
  if (target.source === "async" && target.runner?.type === "external-cli") {
11144
11244
  const runner = normalizeExternalCliRunnerStatus(target.runner);
11145
11245
  const message = runner ? `External adapter '${runner.adapter.id}' cannot resume: ${runner.nonResumableReason}` : "External runners do not persist Pi sessions and cannot be resumed.";
@@ -11148,7 +11248,7 @@ async function resumeAsyncRun(input) {
11148
11248
  if (input.params.baseRef !== void 0 && "managedWorktree" in target && target.managedWorktree === true) {
11149
11249
  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: [] } };
11150
11250
  }
11151
- if (target.source === "async" && target.managedWorktree && target.asyncDir) {
11251
+ if (target.source === "async" && target.managedWorktree && target.asyncDir && fs20.existsSync(parallelHandoffPath(target.asyncDir))) {
11152
11252
  try {
11153
11253
  const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
11154
11254
  if (path18.resolve(protectedCwd) !== path18.resolve(effectiveCwd)) throw new Error("Retained worktree cwd changed during resume admission.");
@@ -11308,7 +11408,7 @@ async function resumeAsyncRun(input) {
11308
11408
  if (target.source === "nested" && !target.recoveryDescriptor) {
11309
11409
  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: [] } };
11310
11410
  }
11311
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: void 0 };
11411
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
11312
11412
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
11313
11413
  const foregroundContract = target.source === "foreground" ? target.resumeContract : void 0;
11314
11414
  const outputSchema = Object.hasOwn(input.params, "outputSchema") ? input.params.outputSchema : Object.hasOwn(foregroundContract ?? {}, "outputSchema") ? foregroundContract?.outputSchema : recoveryDescriptor?.structuredOutputSchema;
@@ -11318,7 +11418,7 @@ async function resumeAsyncRun(input) {
11318
11418
  return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
11319
11419
  }
11320
11420
  if (agentConfig.launcher !== void 0 && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
11321
- 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: [] } };
11421
+ 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: [] } };
11322
11422
  }
11323
11423
  const runId = randomUUID5();
11324
11424
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
@@ -11356,6 +11456,7 @@ async function resumeAsyncRun(input) {
11356
11456
  goal: effectiveFollowUp,
11357
11457
  agentConfig,
11358
11458
  recoveryAgentConfig,
11459
+ carriedRequiredLauncher: recoveryDescriptor?.requiredLauncher,
11359
11460
  ctx: compactOptional({
11360
11461
  pi: input.deps.pi,
11361
11462
  cwd: input.requestCwd,
@@ -11537,6 +11638,7 @@ function createForegroundControlNotifier(data, deps) {
11537
11638
  const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
11538
11639
  if (asyncWorkflow) {
11539
11640
  persistAsyncWorkflowControlEvent({
11641
+ state: deps.state,
11540
11642
  job: asyncWorkflow,
11541
11643
  event: enriched,
11542
11644
  controlConfig: data.controlConfig,
@@ -12488,6 +12590,7 @@ async function runAsyncPath(data, deps) {
12488
12590
  requestedCwd: data.requestedCwd,
12489
12591
  machine: params.machine,
12490
12592
  machineCwd: params.machineCwd,
12593
+ requireLauncher: params.requireLauncher,
12491
12594
  maxOutput: params.maxOutput,
12492
12595
  artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
12493
12596
  artifactConfig,
@@ -12996,7 +13099,7 @@ async function runSinglePath(data, deps) {
12996
13099
 
12997
13100
  ` : "";
12998
13101
  task = readsInstruction + task;
12999
- task = injectSingleOutputInstruction(task, outputPath, agentConfig);
13102
+ task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
13000
13103
  let effectiveSkills;
13001
13104
  if (skillOverride === false) {
13002
13105
  effectiveSkills = [];
@@ -13141,6 +13244,7 @@ async function runSinglePath(data, deps) {
13141
13244
  suppressUnchangedDelegationUpdates,
13142
13245
  controlConfig,
13143
13246
  onControlEvent,
13247
+ onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
13144
13248
  intercomSessionName: childIntercomTarget,
13145
13249
  orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : void 0,
13146
13250
  nestedRoute: foregroundControl?.nestedRoute,
@@ -13306,8 +13410,8 @@ async function runSinglePath(data, deps) {
13306
13410
  ${worktreeHandoff.suffix}` : "";
13307
13411
  if (r.detached) {
13308
13412
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
13309
- const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
13310
- 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}`;
13413
+ const blockingRecovery = `${waitToolName()}({ id: "${runId}" }). Use ${statusRecovery}`;
13414
+ 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}`;
13311
13415
  return {
13312
13416
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
13313
13417
  details
@@ -13690,6 +13794,7 @@ async function preflightWorkflowWorktrees(input) {
13690
13794
  input.signal.throwIfAborted();
13691
13795
  }
13692
13796
  function prepareWorkflowLaunchParams(workflowDefaults, childParams, parentWorkflowRunId, workflowKey, options = {}) {
13797
+ if (childParams.requireLauncher !== void 0 || workflowDefaults.requireLauncher !== void 0) throw new Error(REQUIRE_LAUNCHER_SHAPE_ERROR);
13693
13798
  const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
13694
13799
  const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
13695
13800
  workflowDefaults = workflowDefaultsWithoutCapacity;
@@ -13927,9 +14032,10 @@ function savedWorkflowLaunchParams(params) {
13927
14032
  const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
13928
14033
  return saved;
13929
14034
  }
13930
- function workflowLaunchRecord(launch, cwd, scriptDigest) {
13931
- if (launch.source === "structured") return { version: 1, source: "structured", scriptDigest };
13932
- return { version: 1, source: launch.source, params: { ...launch.params, cwd }, scriptDigest };
14035
+ function workflowLaunchRecord(launch, cwd, scriptDigest, sessionId, ceiling) {
14036
+ const owner = { version: 2, scriptDigest, sessionId, ...ceiling ? { admissionCapabilityCeiling: ceiling } : {} };
14037
+ if (launch.source === "structured" || launch.source === "internal") return { ...owner, source: launch.source };
14038
+ return { ...owner, source: launch.source, params: { ...launch.params, cwd } };
13933
14039
  }
13934
14040
  function createSubagentExecutor(deps) {
13935
14041
  const executorDeps = deps;
@@ -14196,7 +14302,7 @@ function createSubagentExecutor(deps) {
14196
14302
  try {
14197
14303
  fs20.mkdirSync(asyncDir, { recursive: true });
14198
14304
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
14199
- if (topLevelAsyncWorkflow && publicWorkflowLaunch) writeWorkflowLaunchRecord(asyncDir, workflowLaunchRecord(publicWorkflowLaunch, workflowCwd, workflowScriptSourceDigest));
14305
+ if (topLevelAsyncWorkflow) writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling2));
14200
14306
  fs20.mkdirSync(DIRS.results, { recursive: true });
14201
14307
  } catch (error) {
14202
14308
  return storageFailure(error);
@@ -14835,7 +14941,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
14835
14941
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
14836
14942
  });
14837
14943
  let preparedChildParams;
14838
- const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, () => {
14944
+ const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, async () => {
14839
14945
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
14840
14946
  { ...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 },
14841
14947
  missionBinding2,
@@ -14844,6 +14950,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
14844
14950
  inheritedNestedRoute(deps2)?.rootRunId
14845
14951
  );
14846
14952
  preparedChildParams = childRequest;
14953
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
14954
+ if (launchRefusal) return buildRequestedModeError(childRequest, launchRefusal);
14847
14955
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
14848
14956
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
14849
14957
  workflowLaunchObservers.set(childRequest, (launch) => {
@@ -15118,7 +15226,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15118
15226
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
15119
15227
  });
15120
15228
  let preparedChildParams;
15121
- const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, () => {
15229
+ const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, async () => {
15122
15230
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
15123
15231
  { ...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 },
15124
15232
  missionBinding2,
@@ -15127,6 +15235,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15127
15235
  inheritedNestedRoute(deps2)?.rootRunId
15128
15236
  );
15129
15237
  preparedChildParams = childRequest;
15238
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
15239
+ if (launchRefusal) return buildRequestedModeError(childRequest, launchRefusal);
15130
15240
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
15131
15241
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
15132
15242
  if (delegatedWorkflowPermit) {
@@ -16100,6 +16210,12 @@ ${item.text}` } : item)
16100
16210
  const launcherError = agent ? resolveAgentRunnerLauncher(agent, deps2.config.runnerLaunchers, effectiveParams.machine ?? agent.machine).error : void 0;
16101
16211
  if (launcherError) return buildRequestedModeError(effectiveParams, launcherError);
16102
16212
  }
16213
+ if (effectiveParams.requireLauncher !== void 0) {
16214
+ if (!effectiveParams.requireLauncher || typeof effectiveParams.requireLauncher !== "object") return buildRequestedModeError(effectiveParams, "requireLauncher must be { name, definitionDigest }.");
16215
+ if (!hasSingle || effectiveParams.resume !== void 0 || effectiveParams.workflowParentRunId !== void 0) return buildRequestedModeError(effectiveParams, REQUIRE_LAUNCHER_SHAPE_ERROR);
16216
+ const required = selectedAgents[0] ? checkRequiredRunnerLauncher(selectedAgents[0], selectedAgents[0].launcher, effectiveParams.requireLauncher) : void 0;
16217
+ if (required?.error) return buildRequestedModeError(effectiveParams, required.error);
16218
+ }
16103
16219
  if (effectiveAsync && hasSingle && effectiveParams.resume === void 0 && effectiveParams.worktree === true) {
16104
16220
  try {
16105
16221
  await preflightWorktreeSource(effectiveCwd, { signal });