@vicary/pi-subagents 0.84.0-1 → 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-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  5. package/bundle/{chunk-4MDR6V46.js → chunk-A7VJ5XXE.js} +190 -1177
  6. package/bundle/{chunk-LGLEH7B6.js → chunk-B3OOJJA6.js} +231 -182
  7. package/bundle/{chunk-4E7BKDTX.js → chunk-CS4O36CZ.js} +11 -156
  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-T44HVL5U.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/{chunk-F4AMYP5N.js → chunk-HS4WPO6B.js} +15 -6
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-4NIY3BE6.js → chunk-JHBQ7N2L.js} +2 -2
  14. package/bundle/{chunk-HKJLSMXV.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  16. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  17. package/bundle/{chunk-NENDSQUY.js → chunk-KZ34KQQH.js} +9 -6
  18. package/bundle/{chunk-AKOIVLA5.js → chunk-L2ENOFVZ.js} +76 -58
  19. package/bundle/{chunk-CGN2TVE7.js → chunk-LGMILZNE.js} +322 -18
  20. package/bundle/{chunk-L3WFKBEI.js → chunk-LTPH2DXH.js} +247 -153
  21. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  22. package/bundle/{chunk-PV63UFUR.js → chunk-O7CPL6H4.js} +183 -28
  23. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  24. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  25. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  26. package/bundle/{chunk-67ENPDDA.js → chunk-QZL2ZZPM.js} +22 -11
  27. package/bundle/{chunk-PALJGGYC.js → chunk-RV5OGHLO.js} +6 -3
  28. package/bundle/chunk-T5V5BRCL.js +1067 -0
  29. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  30. package/bundle/{chunk-TE4LHYHN.js → chunk-VEZMZDTW.js} +209 -93
  31. package/bundle/{chunk-X2MXCSA5.js → chunk-YZBCREP5.js} +310 -101
  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 +2 -2
  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-F4AMYP5N.js";
6
+ } from "./chunk-HS4WPO6B.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-LGLEH7B6.js";
122
+ } from "./chunk-B3OOJJA6.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-4MDR6V46.js";
135
+ } from "./chunk-A7VJ5XXE.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-4NIY3BE6.js";
237
+ } from "./chunk-JHBQ7N2L.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 = (() => {
@@ -1656,10 +1661,10 @@ function parentExtensionProviderForChild(ctx, disableAmbientExtensions, model, a
1656
1661
  }
1657
1662
  function formatAsyncStartedMessage(headline, interactive) {
1658
1663
  const guidance = interactive ? [
1659
- "Detached. Return control now: native completion wakes you, so do not sleep, poll, or call bg_wait for it.",
1664
+ `Detached. Return control now: native completion wakes you, so do not sleep, poll, or call ${waitToolName()} for it.`,
1660
1665
  'One-shot check: subagent({ action: "status", id: "..." }).'
1661
1666
  ] : [
1662
- '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.'
1667
+ `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.`
1663
1668
  ];
1664
1669
  return [headline, "", ...guidance].join("\n");
1665
1670
  }
@@ -1760,6 +1765,28 @@ function terminateRunnerBeforeProceed(pid) {
1760
1765
  }
1761
1766
  return !runnerIsAlive(pid);
1762
1767
  }
1768
+ function parentPid(pid) {
1769
+ let ppid;
1770
+ if (process.platform === "linux") {
1771
+ try {
1772
+ const stat = fs6.readFileSync(`/proc/${pid}/stat`, "utf-8");
1773
+ ppid = Number(stat.slice(stat.lastIndexOf(")") + 1).trim().split(/\s+/)[1]);
1774
+ } catch {
1775
+ return void 0;
1776
+ }
1777
+ } else {
1778
+ const result2 = spawnSync("ps", ["-o", "ppid=", "-p", String(pid)], { encoding: "utf-8" });
1779
+ if (result2.error || result2.status !== 0) return void 0;
1780
+ ppid = Number(result2.stdout.trim());
1781
+ }
1782
+ return Number.isSafeInteger(ppid) && ppid > 0 ? ppid : void 0;
1783
+ }
1784
+ function isInProcessTree(pid, rootPid) {
1785
+ for (let current = pid; current !== void 0 && current > 1; current = parentPid(current)) {
1786
+ if (current === rootPid) return true;
1787
+ }
1788
+ return false;
1789
+ }
1763
1790
  async function terminateRunnerBeforeProceedAsyncDefault(proc, processClosed) {
1764
1791
  for (const signal of ["SIGTERM", "SIGKILL"]) {
1765
1792
  if (proc.pid === void 0 || !runnerIsAlive(proc.pid)) return true;
@@ -1895,7 +1922,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
1895
1922
  const launchBarrierToken = hasRevivalLease ? void 0 : runnerProcessInstanceId;
1896
1923
  const launcher = cfg.launcher;
1897
1924
  const bootId = launcher ? void 0 : currentBootId();
1898
- const launchConfig = { ...cfg, runnerProcessInstanceId, ...launchBarrierToken ? { launchBarrierToken } : {}, ...bootId ? { bootId } : {} };
1925
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...launchBarrierToken ? { launchBarrierToken } : {}, ...bootId ? { bootId } : {}, ...waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { waitToolName: waitToolName() } : {} };
1899
1926
  writePrivateAtomicJson(cfgPath, launchConfig);
1900
1927
  const command = binaryHost ?? nodeExecutable;
1901
1928
  const launchForStartup = launchConfig;
@@ -1914,7 +1941,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
1914
1941
  const identityPath = launcher && launchBarrierToken && launchAsyncDir ? path5.join(launchAsyncDir, "runner-startup.json") : void 0;
1915
1942
  if (identityPath) fs6.rmSync(identityPath, { force: true });
1916
1943
  let runnerIdentity;
1917
- const terminateBeforeProceed = (pid) => !launcher ? terminateRunnerBeforeProceed(pid) : runnerIdentity !== void 0 && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && terminateRunnerBeforeProceed(runnerIdentity.pid);
1944
+ const terminateBeforeProceed = (pid) => !launcher ? terminateRunnerBeforeProceed(pid) : runnerIdentity !== void 0 && runnerIdentity.pidNamespaceScope === currentPidNamespaceScope() && isInProcessTree(runnerIdentity.pid, pid) && terminateRunnerBeforeProceed(runnerIdentity.pid);
1918
1945
  const adoptRunnerIdentity = (pid, pidNamespaceScope) => {
1919
1946
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1) return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
1920
1947
  runnerIdentity = { pid, ...typeof pidNamespaceScope === "string" ? { pidNamespaceScope } : {} };
@@ -2293,7 +2320,7 @@ function buildAsyncRunnerSteps(id, params) {
2293
2320
  taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
2294
2321
  taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
2295
2322
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
2296
- const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
2323
+ const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a, machine);
2297
2324
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
2298
2325
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
2299
2326
  const primaryModelFromParent = modelOrigin === "inherited";
@@ -2359,7 +2386,7 @@ function buildAsyncRunnerSteps(id, params) {
2359
2386
  const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
2360
2387
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
2361
2388
  const fast = s.fast ?? params.fast ?? a.fast;
2362
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2389
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2363
2390
  const toolPlan = resolvePiLaunchToolPlan({
2364
2391
  tools: a.tools,
2365
2392
  excludeTools: a.excludeTools,
@@ -2925,7 +2952,6 @@ function workflowAwaitedAsyncResultPath(asyncDir) {
2925
2952
  function executeAsyncSingle(id, params) {
2926
2953
  const {
2927
2954
  agent,
2928
- agentConfig,
2929
2955
  ctx,
2930
2956
  cwd,
2931
2957
  maxOutput,
@@ -2946,6 +2972,7 @@ function executeAsyncSingle(id, params) {
2946
2972
  childIntercomTarget,
2947
2973
  nestedRoute
2948
2974
  } = params;
2975
+ let agentConfig = params.agentConfig;
2949
2976
  let lane;
2950
2977
  try {
2951
2978
  lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
@@ -2994,6 +3021,11 @@ function executeAsyncSingle(id, params) {
2994
3021
  const resolvedLauncher = resolveAgentRunnerLauncher(agentConfig, ctx.runnerLaunchers, requestedMachine);
2995
3022
  if (resolvedLauncher.error) return formatAsyncStartError("single", resolvedLauncher.error);
2996
3023
  const launcher = resolvedLauncher.launcher;
3024
+ if (params.requireLauncher) {
3025
+ const required = checkRequiredRunnerLauncher(agentConfig, launcher?.name, params.requireLauncher);
3026
+ if (required.error !== void 0) return formatAsyncStartError("single", required.error);
3027
+ agentConfig = { ...agentConfig, definitionDigest: required.definitionDigest };
3028
+ }
2997
3029
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? void 0);
2998
3030
  try {
2999
3031
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
@@ -3054,7 +3086,7 @@ function executeAsyncSingle(id, params) {
3054
3086
  const outputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
3055
3087
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
3056
3088
  if (validationError) return formatAsyncStartError("single", validationError);
3057
- const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
3089
+ const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig, machine);
3058
3090
  const reads = params.reads !== void 0 ? params.reads : agentConfig.defaultReads ?? false;
3059
3091
  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) : [];
3060
3092
  const readsInstruction = readPaths.length > 0 ? `[Read from: ${readPaths.join(", ")}]
@@ -3146,7 +3178,7 @@ function executeAsyncSingle(id, params) {
3146
3178
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
3147
3179
  }
3148
3180
  }
3149
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
3181
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
3150
3182
  const toolPlan = resolvePiLaunchToolPlan({
3151
3183
  tools: agentConfig.tools,
3152
3184
  excludeTools: agentConfig.excludeTools,
@@ -3194,6 +3226,7 @@ function executeAsyncSingle(id, params) {
3194
3226
  agentContract: params.agentContract
3195
3227
  });
3196
3228
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
3229
+ const requiredLauncher = params.requireLauncher ?? params.carriedRequiredLauncher;
3197
3230
  const recoveryDescriptor = {
3198
3231
  ...ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {},
3199
3232
  version: 1,
@@ -3203,6 +3236,10 @@ function executeAsyncSingle(id, params) {
3203
3236
  ...requiredExtensions.length > 0 ? { requiredExtensions } : {},
3204
3237
  runFanoutBudget,
3205
3238
  sourceRunId: id,
3239
+ ...ctx.currentSessionId ? { sessionId: ctx.currentSessionId } : {},
3240
+ // The worktree the runner will create, fixed here from launch inputs (the runner's own naming call).
3241
+ ...managedWorktreeProvider === "native" ? { managedWorktree: { provider: "native", cwd: instructionCwd } } : {},
3242
+ ...managedWorktreeProvider === "worktrunk" ? { managedWorktree: { provider: "worktrunk", branch: buildWorktreeNaming({ runId: `${id}-s0`, index: 0, agent, label: lane?.key ?? params.workflowKey, task: taskText, branchPrefix: worktreeBranchPrefix }).requestedBranch } } : {},
3206
3243
  ...params.agentContract ? { agentContract: params.agentContract } : {},
3207
3244
  agent,
3208
3245
  launchResolvedExtensions,
@@ -3240,7 +3277,8 @@ function executeAsyncSingle(id, params) {
3240
3277
  ...params.context ? { context: params.context } : {},
3241
3278
  ...params.intercomBridge !== void 0 ? { intercomBridge: params.intercomBridge } : {},
3242
3279
  ...params.baseRef !== void 0 ? { baseRef: params.baseRef } : {},
3243
- ...launcher ? { launcher: launcher.name } : {},
3280
+ launcher: launcher ? launcher.name : null,
3281
+ ...requiredLauncher ? { requiredLauncher } : {},
3244
3282
  ...deadlineAt !== void 0 ? { absoluteDeadlineAt: deadlineAt } : {},
3245
3283
  ...resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {},
3246
3284
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -3253,7 +3291,7 @@ function executeAsyncSingle(id, params) {
3253
3291
  };
3254
3292
  if (!externalRunner) {
3255
3293
  try {
3256
- writePrivateAtomicJson(path5.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
3294
+ writePrivateAtomicJson(recoveryDescriptorPath(path5.dirname(asyncDir), id), recoveryDescriptor);
3257
3295
  } catch (error) {
3258
3296
  return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
3259
3297
  }
@@ -3796,14 +3834,29 @@ function readReplyWorkflowScript(sessionManager, toolCallId) {
3796
3834
  const message = entry.message;
3797
3835
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
3798
3836
  if (!message.content.some((block) => block.type === "toolCall" && block.id === toolCallId)) continue;
3799
- return scriptFromReply(message.content);
3837
+ return scriptFromReply(message.content, () => earlierTurnHasJsBlock(branch, index));
3800
3838
  }
3801
3839
  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".' };
3802
3840
  }
3803
- function scriptFromReply(content) {
3841
+ function earlierTurnHasJsBlock(branch, callIndex) {
3842
+ for (let index = callIndex - 1; index >= 0; index--) {
3843
+ const entry = branch[index];
3844
+ if (entry.type !== "message") continue;
3845
+ if (entry.message?.role === "user") return false;
3846
+ if (entry.message?.role !== "assistant" || !Array.isArray(entry.message.content)) continue;
3847
+ const text = entry.message.content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
3848
+ const { tagged, plain } = workflowBlocks(text);
3849
+ if (tagged.length > 0 || plain.length > 0) return true;
3850
+ }
3851
+ return false;
3852
+ }
3853
+ function scriptFromReply(content, earlierBlock) {
3804
3854
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent" && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
3805
3855
  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.` };
3806
- 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}` };
3856
+ if (!content.some((block) => block.type === "text")) {
3857
+ 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." };
3858
+ return { error: `The assistant message that issued this call has no text in the session, so no \`\`\`js workflow block reached it. ${SUMMARY_NOTE}` };
3859
+ }
3807
3860
  const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
3808
3861
  const { tagged, plain, unclosed } = workflowBlocks(text);
3809
3862
  if (unclosed) return { error: "The script's fenced block in this reply is not closed." };
@@ -5794,12 +5847,20 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5794
5847
  toolAttentionTarget.attentionEmitted = true;
5795
5848
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
5796
5849
  const toolCallId = toolAttentionTarget.key.startsWith("id:") ? toolAttentionTarget.key.slice(3) : void 0;
5850
+ let hasCommandController = false;
5851
+ if (toolCallId) try {
5852
+ hasCommandController = retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId);
5853
+ } catch (error) {
5854
+ const message = `Could not read the command state of ${agent.name}; its command controls are not offered: ${error instanceof Error ? error.message : String(error)}`;
5855
+ if (options.onWarning) options.onWarning(message, "child-command-state");
5856
+ else console.warn(`[pi-subagents] ${message}`);
5857
+ }
5797
5858
  return emitNeedsAttention(now, {
5798
5859
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1e3)}s`,
5799
5860
  reason: "tool_open_threshold",
5800
5861
  currentTool: toolAttentionTarget.tool,
5801
5862
  toolCallId,
5802
- hasCommandController: Boolean(toolCallId && retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId)),
5863
+ hasCommandController,
5803
5864
  currentPath: toolAttentionTarget.path,
5804
5865
  currentToolDurationMs: durationMs
5805
5866
  });
@@ -6355,7 +6416,7 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6355
6416
  durationMs: progress.durationMs
6356
6417
  };
6357
6418
  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;
6358
- 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);
6419
+ 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);
6359
6420
  const acceptanceOutput = getFinalOutput(result2.messages ?? []);
6360
6421
  const structuredText = result2.structuredOutput === void 0 ? void 0 : JSON.stringify(result2.structuredOutput, null, 2);
6361
6422
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -6447,7 +6508,7 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
6447
6508
  }
6448
6509
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
6449
6510
  const effectiveCwd = options.cwd ?? runtimeCwd;
6450
- const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6511
+ const cwdError = options.machine && !isRexLocalMachine(options.machine) ? void 0 : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6451
6512
  if (cwdError) {
6452
6513
  return redactResultPrompt(withRunContext({
6453
6514
  index: options.index ?? 0,
@@ -8324,7 +8385,7 @@ function formatResumeGuidance(runId, children, fallbackSessionFile, options = {}
8324
8385
  const resumableWorkflowChildren = workflowChildren.filter(({ child }) => !(child.status === "paused" && child.activityState === "needs_attention"));
8325
8386
  if (workflowChildren.length > 0) {
8326
8387
  return [
8327
- ...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.`),
8388
+ ...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.`),
8328
8389
  ...resumableWorkflowChildren.map(({ child }) => `Revive workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: subagent({ action: "resume", id: "${child.runId}", message: "..." })`)
8329
8390
  ].join("\n");
8330
8391
  }
@@ -8416,7 +8477,7 @@ function formatRememberedForegroundStatus(run) {
8416
8477
  const detached = run.children.some((child) => child.status === "detached");
8417
8478
  const resumable = run.children.find((child) => hasExistingSessionFile(child.sessionFile));
8418
8479
  if (detached) {
8419
- 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.`);
8480
+ 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.`);
8420
8481
  } else if (resumable) {
8421
8482
  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} } })`);
8422
8483
  } else {
@@ -8983,13 +9044,13 @@ function applyForceTopLevelAsyncOverride(params, depth, forceTopLevelAsync) {
8983
9044
 
8984
9045
  // src/runs/shared/worktree-cleanup-apply.ts
8985
9046
  import { createHash as createHash5 } from "node:crypto";
8986
- import { spawnSync as spawnSync2 } from "node:child_process";
9047
+ import { spawnSync as spawnSync3 } from "node:child_process";
8987
9048
  import * as fs19 from "node:fs";
8988
9049
  import * as path17 from "node:path";
8989
9050
 
8990
9051
  // src/runs/shared/worktree-cleanup-plan.ts
8991
9052
  import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
8992
- import { spawnSync } from "node:child_process";
9053
+ import { spawnSync as spawnSync2 } from "node:child_process";
8993
9054
  import * as fs18 from "node:fs";
8994
9055
  import * as os2 from "node:os";
8995
9056
  import * as path16 from "node:path";
@@ -9000,7 +9061,7 @@ var MAX_PLAN_ENTRIES = 512;
9000
9061
  var MAX_METADATA_FILE_BYTES = 2 * 1024 * 1024;
9001
9062
  function runGit(cwd, args) {
9002
9063
  try {
9003
- const result2 = spawnSync("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
9064
+ const result2 = spawnSync2("git", ["-C", cwd, ...args], { encoding: "utf-8", windowsHide: true });
9004
9065
  return {
9005
9066
  stdout: result2.stdout ?? "",
9006
9067
  stderr: result2.stderr ?? "",
@@ -9741,7 +9802,7 @@ async function applyReviewedCleanupPlan(input) {
9741
9802
  const journalEntry = { path: entry.path, branch: entry.branch, state: "removing", reason: "removal prepared; outcome not yet recorded" };
9742
9803
  receipt.entries.push(journalEntry);
9743
9804
  writePrivateAtomicJson(receiptPath, receipt);
9744
- const removed = spawnSync2("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
9805
+ const removed = spawnSync3("git", ["-C", plan.repoRoot, "worktree", "remove", "--", entry.path], { encoding: "utf-8", windowsHide: true });
9745
9806
  if (removed.status !== 0) throw new Error(removed.error?.message || removed.stderr.trim() || "git worktree remove failed");
9746
9807
  journalEntry.state = "removed";
9747
9808
  journalEntry.reason = "worktree removed; local branch retained";
@@ -9831,6 +9892,38 @@ function inheritedRunFanoutBudget(deps) {
9831
9892
  function resolveRequestedCwd(runtimeCwd, requestedCwd) {
9832
9893
  return requestedCwd ? path18.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
9833
9894
  }
9895
+ function workflowChildLaunchArgs(workflowRunId, key, request, scriptAgent, ctxCwd, discoverAgents2) {
9896
+ const resume = request.action === "resume" && typeof request.id === "string" ? request.id : void 0;
9897
+ const agent = request.agent ?? scriptAgent;
9898
+ const task = resume !== void 0 ? request.message : request.task;
9899
+ const scope = resolveExecutionAgentScope(request.agentScope);
9900
+ const findAgent = (dir) => typeof agent === "string" ? resolveAgentName(agent, discoverAgents2(dir, scope).agents).agent : void 0;
9901
+ const ctxAgent = request.machine === void 0 ? findAgent(ctxCwd) : void 0;
9902
+ const placed = request.machine !== void 0 || ctxAgent?.machine !== void 0;
9903
+ const runCwd = resolveRequestedCwd(ctxCwd, request.cwd);
9904
+ const cwd = resume === void 0 && !placed ? runCwd : void 0;
9905
+ const acceptanceInput = request.acceptance !== void 0 || resume !== void 0 ? request.acceptance : (placed || runCwd === ctxCwd ? ctxAgent ?? findAgent(ctxCwd) : findAgent(runCwd))?.defaultAcceptance;
9906
+ const acceptance = acceptanceInput !== void 0 && validateAcceptanceInput(acceptanceInput).length === 0 ? normalizeAcceptanceInput(acceptanceInput) : void 0;
9907
+ const commands = acceptance?.level === "verified" ? (acceptance.verify ?? []).map((verify) => ({
9908
+ command: verify.command,
9909
+ ...cwd !== void 0 ? { cwd: verify.cwd ? path18.resolve(cwd, verify.cwd) : cwd } : {},
9910
+ ...verify.env !== void 0 ? { env: verify.env } : {}
9911
+ })) : [];
9912
+ const output = resolveSingleOutputPath(request.output, ctxCwd);
9913
+ return {
9914
+ workflowRunId,
9915
+ key,
9916
+ ...typeof agent === "string" ? { agent } : {},
9917
+ ...typeof task === "string" ? { task } : {},
9918
+ ...cwd !== void 0 ? { cwd } : {},
9919
+ ...typeof request.model === "string" ? { model: request.model } : {},
9920
+ ...typeof request.async === "boolean" ? { async: request.async } : {},
9921
+ ...typeof request.worktree === "boolean" ? { worktree: request.worktree } : {},
9922
+ ...resume !== void 0 ? { resume } : {},
9923
+ ...commands.length > 0 ? { commands } : {},
9924
+ ...output !== void 0 ? { output } : {}
9925
+ };
9926
+ }
9834
9927
  function readWorkflowScriptFile(requestedPath, requestedCwd, runtimeCwd) {
9835
9928
  const scriptPath = path18.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
9836
9929
  let script;
@@ -10232,7 +10325,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
10232
10325
  if (matches.length === 0) return void 0;
10233
10326
  if (matches.length > 1) throw new Error(`Ambiguous foreground run id prefix '${requested}' matched: ${matches.map((run2) => run2.runId).join(", ")}. Provide a longer id.`);
10234
10327
  const run = matches[0];
10235
- 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.`);
10328
+ 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.`);
10236
10329
  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.`);
10237
10330
  const index = params.index ?? 0;
10238
10331
  if (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
@@ -10355,8 +10448,7 @@ function persistAsyncWorkflowControlEvent(input) {
10355
10448
  fs20.appendFileSync(path18.join(input.job.asyncDir, "events.jsonl"), `${JSON.stringify(record2)}
10356
10449
  `, "utf-8");
10357
10450
  } catch (error) {
10358
- if (!isStorageCapacityError(error)) throw error;
10359
- console.error("Failed to append async workflow control event while storage is full:", error);
10451
+ 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");
10360
10452
  }
10361
10453
  }
10362
10454
  function emitControlNotification(input) {
@@ -10709,8 +10801,8 @@ function validateNestedSessionFile(run, trustedSessionRoots2, resolveSource, vis
10709
10801
  }
10710
10802
  return realSessionFile;
10711
10803
  }
10712
- function readNestedRecoveryDescriptor(asyncDir, runId, agent) {
10713
- const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
10804
+ function readNestedRecoveryDescriptor(rootRunId, runId, agent) {
10805
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(nestedRunScope(rootRunId).asyncDirRoot, runId);
10714
10806
  if (!recoveryDescriptor) return void 0;
10715
10807
  if (recoveryDescriptor.sourceRunId !== runId) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different source run.`);
10716
10808
  if (recoveryDescriptor.agent !== agent) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different agent.`);
@@ -10724,7 +10816,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots2, resolveSource) {
10724
10816
  if (!agent) throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
10725
10817
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
10726
10818
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
10727
- const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
10819
+ const recoveryDescriptor = asyncDir ? readNestedRecoveryDescriptor(match.match.rootRunId, run.id, agent) : void 0;
10728
10820
  return compactOptional({
10729
10821
  kind: "revive",
10730
10822
  source: "nested",
@@ -11139,6 +11231,14 @@ async function resumeAsyncRun(input) {
11139
11231
  details: { mode: "management", results: [] }
11140
11232
  };
11141
11233
  }
11234
+ const requiredLauncher = recoveryDescriptor?.requiredLauncher;
11235
+ if (requiredLauncher) {
11236
+ const refuse = (text) => ({ content: [{ type: "text", text }], isError: true, details: { mode: "management", results: [] } });
11237
+ 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.`);
11238
+ const currentDigest = discoveredAgentConfig ? agentDefinitionDigest(discoveredAgentConfig) : void 0;
11239
+ 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;
11240
+ 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}.`);
11241
+ }
11142
11242
  if (target.source === "async" && target.runner?.type === "external-cli") {
11143
11243
  const runner = normalizeExternalCliRunnerStatus(target.runner);
11144
11244
  const message = runner ? `External adapter '${runner.adapter.id}' cannot resume: ${runner.nonResumableReason}` : "External runners do not persist Pi sessions and cannot be resumed.";
@@ -11147,7 +11247,7 @@ async function resumeAsyncRun(input) {
11147
11247
  if (input.params.baseRef !== void 0 && "managedWorktree" in target && target.managedWorktree === true) {
11148
11248
  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: [] } };
11149
11249
  }
11150
- if (target.source === "async" && target.managedWorktree && target.asyncDir) {
11250
+ if (target.source === "async" && target.managedWorktree && target.asyncDir && fs20.existsSync(parallelHandoffPath(target.asyncDir))) {
11151
11251
  try {
11152
11252
  const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
11153
11253
  if (path18.resolve(protectedCwd) !== path18.resolve(effectiveCwd)) throw new Error("Retained worktree cwd changed during resume admission.");
@@ -11307,7 +11407,7 @@ async function resumeAsyncRun(input) {
11307
11407
  if (target.source === "nested" && !target.recoveryDescriptor) {
11308
11408
  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: [] } };
11309
11409
  }
11310
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: void 0 };
11410
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
11311
11411
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
11312
11412
  const foregroundContract = target.source === "foreground" ? target.resumeContract : void 0;
11313
11413
  const outputSchema = Object.hasOwn(input.params, "outputSchema") ? input.params.outputSchema : Object.hasOwn(foregroundContract ?? {}, "outputSchema") ? foregroundContract?.outputSchema : recoveryDescriptor?.structuredOutputSchema;
@@ -11317,7 +11417,7 @@ async function resumeAsyncRun(input) {
11317
11417
  return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
11318
11418
  }
11319
11419
  if (agentConfig.launcher !== void 0 && !lookupRunnerLauncher(input.deps.config.runnerLaunchers, agentConfig.launcher)) {
11320
- 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: [] } };
11420
+ 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: [] } };
11321
11421
  }
11322
11422
  const runId = randomUUID5();
11323
11423
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
@@ -11355,6 +11455,7 @@ async function resumeAsyncRun(input) {
11355
11455
  goal: effectiveFollowUp,
11356
11456
  agentConfig,
11357
11457
  recoveryAgentConfig,
11458
+ carriedRequiredLauncher: recoveryDescriptor?.requiredLauncher,
11358
11459
  ctx: compactOptional({
11359
11460
  pi: input.deps.pi,
11360
11461
  cwd: input.requestCwd,
@@ -11536,6 +11637,7 @@ function createForegroundControlNotifier(data, deps) {
11536
11637
  const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
11537
11638
  if (asyncWorkflow) {
11538
11639
  persistAsyncWorkflowControlEvent({
11640
+ state: deps.state,
11539
11641
  job: asyncWorkflow,
11540
11642
  event: enriched,
11541
11643
  controlConfig: data.controlConfig,
@@ -12484,6 +12586,7 @@ async function runAsyncPath(data, deps) {
12484
12586
  requestedCwd: data.requestedCwd,
12485
12587
  machine: params.machine,
12486
12588
  machineCwd: params.machineCwd,
12589
+ requireLauncher: params.requireLauncher,
12487
12590
  maxOutput: params.maxOutput,
12488
12591
  artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
12489
12592
  artifactConfig,
@@ -12992,7 +13095,7 @@ async function runSinglePath(data, deps) {
12992
13095
 
12993
13096
  ` : "";
12994
13097
  task = readsInstruction + task;
12995
- task = injectSingleOutputInstruction(task, outputPath, agentConfig);
13098
+ task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
12996
13099
  let effectiveSkills;
12997
13100
  if (skillOverride === false) {
12998
13101
  effectiveSkills = [];
@@ -13137,6 +13240,7 @@ async function runSinglePath(data, deps) {
13137
13240
  suppressUnchangedDelegationUpdates,
13138
13241
  controlConfig,
13139
13242
  onControlEvent,
13243
+ onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
13140
13244
  intercomSessionName: childIntercomTarget,
13141
13245
  orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : void 0,
13142
13246
  nestedRoute: foregroundControl?.nestedRoute,
@@ -13302,8 +13406,8 @@ async function runSinglePath(data, deps) {
13302
13406
  ${worktreeHandoff.suffix}` : "";
13303
13407
  if (r.detached) {
13304
13408
  const statusRecovery = `subagent({ action: "status", id: "${runId}" }) to recover the result; do not resume or launch a replacement while it remains detached.`;
13305
- const blockingRecovery = `bg_wait({ id: "${runId}" }). Use ${statusRecovery}`;
13306
- 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}`;
13409
+ const blockingRecovery = `${waitToolName()}({ id: "${runId}" }). Use ${statusRecovery}`;
13410
+ 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}`;
13307
13411
  return {
13308
13412
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
13309
13413
  details
@@ -13686,6 +13790,7 @@ async function preflightWorkflowWorktrees(input) {
13686
13790
  input.signal.throwIfAborted();
13687
13791
  }
13688
13792
  function prepareWorkflowLaunchParams(workflowDefaults, childParams, parentWorkflowRunId, workflowKey, options = {}) {
13793
+ if (childParams.requireLauncher !== void 0 || workflowDefaults.requireLauncher !== void 0) throw new Error(REQUIRE_LAUNCHER_SHAPE_ERROR);
13689
13794
  const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
13690
13795
  const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
13691
13796
  workflowDefaults = workflowDefaultsWithoutCapacity;
@@ -13923,9 +14028,10 @@ function savedWorkflowLaunchParams(params) {
13923
14028
  const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
13924
14029
  return saved;
13925
14030
  }
13926
- function workflowLaunchRecord(launch, cwd, scriptDigest) {
13927
- if (launch.source === "structured") return { version: 1, source: "structured", scriptDigest };
13928
- return { version: 1, source: launch.source, params: { ...launch.params, cwd }, scriptDigest };
14031
+ function workflowLaunchRecord(launch, cwd, scriptDigest, sessionId, ceiling) {
14032
+ const owner = { version: 2, scriptDigest, sessionId, ...ceiling ? { admissionCapabilityCeiling: ceiling } : {} };
14033
+ if (launch.source === "structured" || launch.source === "internal") return { ...owner, source: launch.source };
14034
+ return { ...owner, source: launch.source, params: { ...launch.params, cwd } };
13929
14035
  }
13930
14036
  function createSubagentExecutor(deps) {
13931
14037
  const executorDeps = deps;
@@ -14192,7 +14298,7 @@ function createSubagentExecutor(deps) {
14192
14298
  try {
14193
14299
  fs20.mkdirSync(asyncDir, { recursive: true });
14194
14300
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
14195
- if (topLevelAsyncWorkflow && publicWorkflowLaunch) writeWorkflowLaunchRecord(asyncDir, workflowLaunchRecord(publicWorkflowLaunch, workflowCwd, workflowScriptSourceDigest));
14301
+ if (topLevelAsyncWorkflow) writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling2));
14196
14302
  fs20.mkdirSync(DIRS.results, { recursive: true });
14197
14303
  } catch (error) {
14198
14304
  return storageFailure(error);
@@ -14831,7 +14937,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
14831
14937
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
14832
14938
  });
14833
14939
  let preparedChildParams;
14834
- const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, () => {
14940
+ const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, async () => {
14835
14941
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
14836
14942
  { ...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 },
14837
14943
  missionBinding2,
@@ -14840,6 +14946,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
14840
14946
  inheritedNestedRoute(deps2)?.rootRunId
14841
14947
  );
14842
14948
  preparedChildParams = childRequest;
14949
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(workflowRunId, key, childRequest, childParams.agent, parentCwd, discoverWorkflowAgents), workflowSignal);
14950
+ if (launchRefusal) return buildRequestedModeError(childRequest, launchRefusal);
14843
14951
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
14844
14952
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
14845
14953
  workflowLaunchObservers.set(childRequest, (launch) => {
@@ -15114,7 +15222,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15114
15222
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
15115
15223
  });
15116
15224
  let preparedChildParams;
15117
- const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, () => {
15225
+ const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, async () => {
15118
15226
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
15119
15227
  { ...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 },
15120
15228
  missionBinding2,
@@ -15123,6 +15231,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15123
15231
  inheritedNestedRoute(deps2)?.rootRunId
15124
15232
  );
15125
15233
  preparedChildParams = childRequest;
15234
+ const launchRefusal = await approveWorkflowChildLaunch(ctx, () => workflowChildLaunchArgs(foregroundWorkflowRunId, key, childRequest, childParams.agent, ctx.cwd, discoverWorkflowAgents), workflowSignal);
15235
+ if (launchRefusal) return buildRequestedModeError(childRequest, launchRefusal);
15126
15236
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
15127
15237
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
15128
15238
  if (delegatedWorkflowPermit) {
@@ -16098,6 +16208,12 @@ ${item.text}` } : item)
16098
16208
  const launcherError = agent ? resolveAgentRunnerLauncher(agent, deps2.config.runnerLaunchers, effectiveParams.machine ?? agent.machine).error : void 0;
16099
16209
  if (launcherError) return buildRequestedModeError(effectiveParams, launcherError);
16100
16210
  }
16211
+ if (effectiveParams.requireLauncher !== void 0) {
16212
+ if (!effectiveParams.requireLauncher || typeof effectiveParams.requireLauncher !== "object") return buildRequestedModeError(effectiveParams, "requireLauncher must be { name, definitionDigest }.");
16213
+ if (!hasSingle || effectiveParams.resume !== void 0 || effectiveParams.workflowParentRunId !== void 0) return buildRequestedModeError(effectiveParams, REQUIRE_LAUNCHER_SHAPE_ERROR);
16214
+ const required = selectedAgents[0] ? checkRequiredRunnerLauncher(selectedAgents[0], selectedAgents[0].launcher, effectiveParams.requireLauncher) : void 0;
16215
+ if (required?.error) return buildRequestedModeError(effectiveParams, required.error);
16216
+ }
16101
16217
  if (effectiveAsync && hasSingle && effectiveParams.resume === void 0 && effectiveParams.worktree === true) {
16102
16218
  try {
16103
16219
  await preflightWorktreeSource(effectiveCwd, { signal });