@vicary/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 (207) 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-7BWGNDNK.js → chunk-A7VJ5XXE.js} +196 -1183
  6. package/bundle/{chunk-DZDETGRJ.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-NKQ6JNAS.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/{chunk-XDQORLZ5.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-J5YL7LYR.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-VQVVHSY6.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-RWPNQZHS.js → chunk-VEZMZDTW.js} +212 -102
  31. package/bundle/{chunk-RSLHTEQV.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 +18 -3
  38. package/docs/configuration.md +7 -7
  39. package/docs/extension-api.md +16 -1
  40. package/docs/observability.md +1 -1
  41. package/docs/tool-reference.md +1 -1
  42. package/docs/workflows.md +31 -3
  43. package/package.json +2 -2
  44. package/src/agents/agent-management.js +27 -11
  45. package/src/agents/agent-memory.d.ts +1 -4
  46. package/src/agents/agent-memory.js +1 -4
  47. package/src/agents/agents.d.ts +1 -3
  48. package/src/agents/agents.js +7 -6
  49. package/src/agents/frontmatter.js +1 -8
  50. package/src/agents/global-npm-root.d.ts +1 -0
  51. package/src/agents/global-npm-root.js +11 -3
  52. package/src/agents/skills.d.ts +0 -3
  53. package/src/agents/skills.js +0 -3
  54. package/src/extension/config.js +7 -1
  55. package/src/extension/herdr-pi-bridge.js +10 -2
  56. package/src/extension/index.d.ts +0 -13
  57. package/src/extension/index.js +43 -32
  58. package/src/extension/public-execution.d.ts +1 -0
  59. package/src/extension/public-execution.js +4 -0
  60. package/src/extension/reply-workflow-script.js +24 -4
  61. package/src/extension/schemas.d.ts +8 -3
  62. package/src/extension/schemas.js +6 -4
  63. package/src/extension/session-switch.d.ts +25 -0
  64. package/src/extension/session-switch.js +138 -0
  65. package/src/extension/subagent-guide.d.ts +1 -1
  66. package/src/extension/subagent-guide.js +1 -1
  67. package/src/extension/subagent-launch-tool.d.ts +25 -0
  68. package/src/extension/subagent-launch-tool.js +48 -0
  69. package/src/extension/tool-activation.js +25 -11
  70. package/src/extension/tool-description.js +6 -0
  71. package/src/inspectors/herdr/actions.d.ts +0 -1
  72. package/src/inspectors/herdr/actions.js +0 -1
  73. package/src/inspectors/session-roots-codec.d.ts +0 -1
  74. package/src/inspectors/session-roots-codec.js +0 -1
  75. package/src/inspectors/tmux/actions.d.ts +0 -1
  76. package/src/inspectors/tmux/actions.js +0 -1
  77. package/src/integrations/herdr-status.js +3 -8
  78. package/src/intercom/native-supervisor-channel.js +65 -9
  79. package/src/runs/background/async-execution.d.ts +5 -10
  80. package/src/runs/background/async-execution.js +63 -29
  81. package/src/runs/background/async-job-tracker.js +12 -0
  82. package/src/runs/background/async-resume.d.ts +2 -1
  83. package/src/runs/background/async-resume.js +112 -39
  84. package/src/runs/background/async-retention.js +6 -1
  85. package/src/runs/background/auto-drain.d.ts +0 -1
  86. package/src/runs/background/auto-drain.js +7 -6
  87. package/src/runs/background/boot-id.d.ts +1 -3
  88. package/src/runs/background/boot-id.js +1 -3
  89. package/src/runs/background/completion-batcher.d.ts +3 -4
  90. package/src/runs/background/completion-batcher.js +2 -3
  91. package/src/runs/background/control-channel.d.ts +0 -6
  92. package/src/runs/background/control-channel.js +0 -6
  93. package/src/runs/background/fleet-view.js +2 -3
  94. package/src/runs/background/notify.d.ts +0 -2
  95. package/src/runs/background/notify.js +0 -2
  96. package/src/runs/background/result-watcher.d.ts +1 -0
  97. package/src/runs/background/result-watcher.js +59 -29
  98. package/src/runs/background/resume-guidance.js +4 -2
  99. package/src/runs/background/retained-children.js +2 -1
  100. package/src/runs/background/run-child-session.d.ts +0 -1
  101. package/src/runs/background/run-child-session.js +1 -1
  102. package/src/runs/background/run-status.js +4 -3
  103. package/src/runs/background/scheduled-runs.d.ts +3 -1
  104. package/src/runs/background/scheduled-runs.js +13 -16
  105. package/src/runs/background/subagent-runner.d.ts +2 -4
  106. package/src/runs/background/subagent-runner.js +9 -6
  107. package/src/runs/background/subagent-wait.js +12 -15
  108. package/src/runs/background/wait-config.d.ts +2 -0
  109. package/src/runs/background/wait-config.js +17 -3
  110. package/src/runs/background/wait-tool.js +4 -2
  111. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  112. package/src/runs/background/workflow-terminal-proof.js +0 -1
  113. package/src/runs/foreground/execution.d.ts +0 -3
  114. package/src/runs/foreground/execution.js +17 -9
  115. package/src/runs/foreground/subagent-executor.d.ts +7 -8
  116. package/src/runs/foreground/subagent-executor.js +113 -44
  117. package/src/runs/shared/child-commands.js +15 -2
  118. package/src/runs/shared/child-hooks.d.ts +1 -7
  119. package/src/runs/shared/child-hooks.js +13 -5
  120. package/src/runs/shared/child-launch.js +6 -2
  121. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  122. package/src/runs/shared/child-session.d.ts +1 -1
  123. package/src/runs/shared/child-session.js +21 -2
  124. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  125. package/src/runs/shared/child-tool-plan.js +0 -1
  126. package/src/runs/shared/claude-code-adapter.js +11 -0
  127. package/src/runs/shared/external-cli-runner.js +26 -6
  128. package/src/runs/shared/herdr-connection.js +2 -1
  129. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  130. package/src/runs/shared/herdr-pane-host.js +17 -1
  131. package/src/runs/shared/herdr-placed-run.js +48 -22
  132. package/src/runs/shared/lane-metadata.d.ts +0 -1
  133. package/src/runs/shared/lane-metadata.js +0 -1
  134. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  135. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  136. package/src/runs/shared/model-resolution.d.ts +2 -2
  137. package/src/runs/shared/model-resolution.js +7 -1
  138. package/src/runs/shared/model-scope.d.ts +1 -5
  139. package/src/runs/shared/model-scope.js +1 -5
  140. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  141. package/src/runs/shared/mutation-evidence.js +52 -7
  142. package/src/runs/shared/nested-events.d.ts +1 -0
  143. package/src/runs/shared/nested-events.js +1 -1
  144. package/src/runs/shared/parallel-utils.d.ts +0 -1
  145. package/src/runs/shared/permissions.js +5 -3
  146. package/src/runs/shared/placement-host.d.ts +5 -1
  147. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  148. package/src/runs/shared/rex-pane-host.js +0 -2
  149. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  150. package/src/runs/shared/run-launch-folder.js +21 -0
  151. package/src/runs/shared/runner-launcher.d.ts +12 -1
  152. package/src/runs/shared/runner-launcher.js +16 -0
  153. package/src/runs/shared/single-output.d.ts +3 -3
  154. package/src/runs/shared/single-output.js +5 -3
  155. package/src/runs/shared/structured-output.d.ts +8 -0
  156. package/src/runs/shared/structured-output.js +30 -2
  157. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  158. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  159. package/src/runs/shared/tool-timeout.js +2 -1
  160. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  161. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  162. package/src/runs/shared/worktree.d.ts +3 -0
  163. package/src/runs/shared/worktree.js +20 -0
  164. package/src/shared/capacity-resilient-json.d.ts +1 -1
  165. package/src/shared/child-cache-retention.d.ts +1 -2
  166. package/src/shared/child-cache-retention.js +1 -2
  167. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  168. package/src/shared/fleet-transcript-reader.js +333 -0
  169. package/src/shared/formatters.d.ts +0 -18
  170. package/src/shared/formatters.js +0 -18
  171. package/src/shared/session-succession.d.ts +16 -1
  172. package/src/shared/session-succession.js +41 -2
  173. package/src/shared/session-warnings.d.ts +7 -0
  174. package/src/shared/session-warnings.js +26 -0
  175. package/src/shared/settings.d.ts +0 -23
  176. package/src/shared/settings.js +3 -35
  177. package/src/shared/types.d.ts +33 -17
  178. package/src/shared/types.js +0 -12
  179. package/src/shared/utils.d.ts +0 -14
  180. package/src/shared/utils.js +0 -22
  181. package/src/shared/wait-tool-name.d.ts +8 -0
  182. package/src/shared/wait-tool-name.js +13 -0
  183. package/src/slash/slash-commands.js +2 -1
  184. package/src/slash/subagent-cost.d.ts +3 -2
  185. package/src/slash/subagent-cost.js +22 -3
  186. package/src/slash/subagents-admin.js +0 -1
  187. package/src/tui/fleet-status.d.ts +0 -5
  188. package/src/tui/fleet-status.js +4 -24
  189. package/src/tui/fleet-transcript.d.ts +1 -44
  190. package/src/tui/fleet-transcript.js +1 -327
  191. package/src/tui/fleet.js +6 -4
  192. package/src/tui/render.d.ts +0 -9
  193. package/src/tui/render.js +81 -47
  194. package/src/tui/subagent-messages.js +3 -2
  195. package/src/watchdog/register-child.d.ts +2 -3
  196. package/src/watchdog/register-child.js +2 -3
  197. package/src/watchdog/turn-delta.js +2 -1
  198. package/src/workflows/scripted-workflow.js +241 -20
  199. package/src/workflows/workflow-launch-record.d.ts +15 -6
  200. package/src/workflows/workflow-launch-record.js +30 -12
  201. package/src/workflows/workflow-resume-claim.js +2 -2
  202. package/src/workflows/workflow-resume.d.ts +1 -1
  203. package/src/workflows/workflow-resume.js +11 -8
  204. package/src/workflows/workflow-script-worker.d.ts +13 -0
  205. package/src/workflows/workflow-script-worker.js +79 -0
  206. package/workflow-script-process.cjs +36 -0
  207. 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-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-DZDETGRJ.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-7BWGNDNK.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 = (() => {
@@ -1654,13 +1659,12 @@ function parentExtensionProviderForChild(ctx, disableAmbientExtensions, model, a
1654
1659
  const provider = findModelInfo(model, availableModels, preferredProvider)?.provider;
1655
1660
  return provider && ctx.parentProviderRegistry.getRegisteredProviderIds().includes(provider) ? provider : void 0;
1656
1661
  }
1657
- var DEFAULT_ASYNC_TIMEOUT_MS = 30 * 60 * 1e3;
1658
1662
  function formatAsyncStartedMessage(headline, interactive) {
1659
1663
  const guidance = interactive ? [
1660
- "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.`,
1661
1665
  'One-shot check: subagent({ action: "status", id: "..." }).'
1662
1666
  ] : [
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.'
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.`
1664
1668
  ];
1665
1669
  return [headline, "", ...guidance].join("\n");
1666
1670
  }
@@ -1761,6 +1765,28 @@ function terminateRunnerBeforeProceed(pid) {
1761
1765
  }
1762
1766
  return !runnerIsAlive(pid);
1763
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
+ }
1764
1790
  async function terminateRunnerBeforeProceedAsyncDefault(proc, processClosed) {
1765
1791
  for (const signal of ["SIGTERM", "SIGKILL"]) {
1766
1792
  if (proc.pid === void 0 || !runnerIsAlive(proc.pid)) return true;
@@ -1896,7 +1922,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
1896
1922
  const launchBarrierToken = hasRevivalLease ? void 0 : runnerProcessInstanceId;
1897
1923
  const launcher = cfg.launcher;
1898
1924
  const bootId = launcher ? void 0 : currentBootId();
1899
- const launchConfig = { ...cfg, runnerProcessInstanceId, ...launchBarrierToken ? { launchBarrierToken } : {}, ...bootId ? { bootId } : {} };
1925
+ const launchConfig = { ...cfg, runnerProcessInstanceId, ...launchBarrierToken ? { launchBarrierToken } : {}, ...bootId ? { bootId } : {}, ...waitToolName() !== DEFAULT_WAIT_TOOL_NAME ? { waitToolName: waitToolName() } : {} };
1900
1926
  writePrivateAtomicJson(cfgPath, launchConfig);
1901
1927
  const command = binaryHost ?? nodeExecutable;
1902
1928
  const launchForStartup = launchConfig;
@@ -1915,7 +1941,7 @@ function spawnRunner(cfg, suffix, cwd, initialStatus, initialStatusPath, launchP
1915
1941
  const identityPath = launcher && launchBarrierToken && launchAsyncDir ? path5.join(launchAsyncDir, "runner-startup.json") : void 0;
1916
1942
  if (identityPath) fs6.rmSync(identityPath, { force: true });
1917
1943
  let runnerIdentity;
1918
- 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);
1919
1945
  const adoptRunnerIdentity = (pid, pidNamespaceScope) => {
1920
1946
  if (typeof pid !== "number" || !Number.isSafeInteger(pid) || pid < 1) return `Async runner reported an invalid process identity in '${launchAsyncDir}'.`;
1921
1947
  runnerIdentity = { pid, ...typeof pidNamespaceScope === "string" ? { pidNamespaceScope } : {} };
@@ -2294,7 +2320,7 @@ function buildAsyncRunnerSteps(id, params) {
2294
2320
  taskTemplate = taskTemplate.replace(/\{task\}/g, originalTask ?? "");
2295
2321
  taskTemplate = taskTemplate.replace(/\{chain_dir\}/g, behaviorCwd ?? runnerCwd);
2296
2322
  const taskText = `${readInstructions.prefix}${taskTemplate}${progressInstructions.suffix}`;
2297
- const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a);
2323
+ const task = namespaceOutputPath ? taskText : injectSingleOutputInstruction(taskText, outputPath, a, machine);
2298
2324
  const modelScopes = resolveModelScopesForAgent(ctx.modelScope, a.name, ctx.currentModel, ctx.scopedModelIds);
2299
2325
  const modelOrigin = resolveModelOrigin({ explicitModel: s.model, agentModel: a.model, parentModel: ctx.currentModel });
2300
2326
  const primaryModelFromParent = modelOrigin === "inherited";
@@ -2360,7 +2386,7 @@ function buildAsyncRunnerSteps(id, params) {
2360
2386
  const launchRuleError = applyWatchdogLaunchRules({ cwd: machine ? runnerCwd : stepCwd, agent: a.name, model: selectedModel, warn: (violation) => sendRuleViolationWarning(ctx.pi, violation) });
2361
2387
  if (launchRuleError) throw new AsyncStartValidationError(launchRuleError);
2362
2388
  const fast = s.fast ?? params.fast ?? a.fast;
2363
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2389
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
2364
2390
  const toolPlan = resolvePiLaunchToolPlan({
2365
2391
  tools: a.tools,
2366
2392
  excludeTools: a.excludeTools,
@@ -2437,7 +2463,7 @@ function buildAsyncRunnerSteps(id, params) {
2437
2463
  outputMode: behavior.outputMode,
2438
2464
  sessionFile,
2439
2465
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, a.maxSubagentDepth),
2440
- timeoutMs: a.defaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS,
2466
+ timeoutMs: a.defaultTimeoutMs,
2441
2467
  toolTimeoutMs: resolvedToolTimeout.toolTimeoutMs,
2442
2468
  waitToolEnabled: params.waitToolEnabled,
2443
2469
  waitToolDefaultTimeoutMs: params.waitToolDefaultTimeoutMs,
@@ -2926,7 +2952,6 @@ function workflowAwaitedAsyncResultPath(asyncDir) {
2926
2952
  function executeAsyncSingle(id, params) {
2927
2953
  const {
2928
2954
  agent,
2929
- agentConfig,
2930
2955
  ctx,
2931
2956
  cwd,
2932
2957
  maxOutput,
@@ -2947,6 +2972,7 @@ function executeAsyncSingle(id, params) {
2947
2972
  childIntercomTarget,
2948
2973
  nestedRoute
2949
2974
  } = params;
2975
+ let agentConfig = params.agentConfig;
2950
2976
  let lane;
2951
2977
  try {
2952
2978
  lane = normalizeWorkflowLaneMetadata(params.lane, "lane");
@@ -2995,6 +3021,11 @@ function executeAsyncSingle(id, params) {
2995
3021
  const resolvedLauncher = resolveAgentRunnerLauncher(agentConfig, ctx.runnerLaunchers, requestedMachine);
2996
3022
  if (resolvedLauncher.error) return formatAsyncStartError("single", resolvedLauncher.error);
2997
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
+ }
2998
3029
  const registeredExtensions = resolveRequiredChildExtensions(ctx.parentSessionId ?? ctx.currentSessionId ?? void 0);
2999
3030
  try {
3000
3031
  assertRequiredChildExtensionsAdmitted([params.requiredExtensions, ctx.childRuntime?.requiredExtensions, registeredExtensions], { agent: agentConfig.name, runnerType: agentConfig.runner?.type, machine: requestedMachine });
@@ -3055,7 +3086,7 @@ function executeAsyncSingle(id, params) {
3055
3086
  const outputMode = params.outputMode ?? agentConfig.outputMode ?? "inline";
3056
3087
  const validationError = validateFileOnlyOutputMode(outputMode, outputPath, `Async single run (${agent})`);
3057
3088
  if (validationError) return formatAsyncStartError("single", validationError);
3058
- const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig);
3089
+ const taskWithOutputInstruction = injectSingleOutputInstruction(task, outputPath, agentConfig, machine);
3059
3090
  const reads = params.reads !== void 0 ? params.reads : agentConfig.defaultReads ?? false;
3060
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) : [];
3061
3092
  const readsInstruction = readPaths.length > 0 ? `[Read from: ${readPaths.join(", ")}]
@@ -3147,7 +3178,7 @@ function executeAsyncSingle(id, params) {
3147
3178
  return formatAsyncStartError("single", error instanceof Error ? error.message : String(error));
3148
3179
  }
3149
3180
  }
3150
- const requiredExtensions = externalRunner ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
3181
+ const requiredExtensions = externalRunner || machine ? [] : params.requiredExtensions ?? ctx.childRuntime?.requiredExtensions ?? registeredExtensions;
3151
3182
  const toolPlan = resolvePiLaunchToolPlan({
3152
3183
  tools: agentConfig.tools,
3153
3184
  excludeTools: agentConfig.excludeTools,
@@ -3195,6 +3226,7 @@ function executeAsyncSingle(id, params) {
3195
3226
  agentContract: params.agentContract
3196
3227
  });
3197
3228
  const recoveryAgentConfig = params.recoveryAgentConfig ?? agentConfig;
3229
+ const requiredLauncher = params.requireLauncher ?? params.carriedRequiredLauncher;
3198
3230
  const recoveryDescriptor = {
3199
3231
  ...ctx.modelResponseAliases ? { modelResponseAliases: ctx.modelResponseAliases } : {},
3200
3232
  version: 1,
@@ -3204,6 +3236,10 @@ function executeAsyncSingle(id, params) {
3204
3236
  ...requiredExtensions.length > 0 ? { requiredExtensions } : {},
3205
3237
  runFanoutBudget,
3206
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 } } : {},
3207
3243
  ...params.agentContract ? { agentContract: params.agentContract } : {},
3208
3244
  agent,
3209
3245
  launchResolvedExtensions,
@@ -3241,7 +3277,8 @@ function executeAsyncSingle(id, params) {
3241
3277
  ...params.context ? { context: params.context } : {},
3242
3278
  ...params.intercomBridge !== void 0 ? { intercomBridge: params.intercomBridge } : {},
3243
3279
  ...params.baseRef !== void 0 ? { baseRef: params.baseRef } : {},
3244
- ...launcher ? { launcher: launcher.name } : {},
3280
+ launcher: launcher ? launcher.name : null,
3281
+ ...requiredLauncher ? { requiredLauncher } : {},
3245
3282
  ...deadlineAt !== void 0 ? { absoluteDeadlineAt: deadlineAt } : {},
3246
3283
  ...resolvedToolBudget.budget ? { initialToolBudget: resolvedToolBudget.budget } : {},
3247
3284
  maxSubagentDepth: resolveChildMaxSubagentDepth(maxSubagentDepth, recoveryAgentConfig.maxSubagentDepth),
@@ -3254,7 +3291,7 @@ function executeAsyncSingle(id, params) {
3254
3291
  };
3255
3292
  if (!externalRunner) {
3256
3293
  try {
3257
- writePrivateAtomicJson(path5.join(asyncDir, "recovery-descriptor.json"), recoveryDescriptor);
3294
+ writePrivateAtomicJson(recoveryDescriptorPath(path5.dirname(asyncDir), id), recoveryDescriptor);
3258
3295
  } catch (error) {
3259
3296
  return formatAsyncStartError("single", `Failed to persist async recovery descriptor for '${id}': ${error instanceof Error ? error.message : String(error)}`);
3260
3297
  }
@@ -3797,14 +3834,29 @@ function readReplyWorkflowScript(sessionManager, toolCallId) {
3797
3834
  const message = entry.message;
3798
3835
  if (message?.role !== "assistant" || !Array.isArray(message.content)) continue;
3799
3836
  if (!message.content.some((block) => block.type === "toolCall" && block.id === toolCallId)) continue;
3800
- return scriptFromReply(message.content);
3837
+ return scriptFromReply(message.content, () => earlierTurnHasJsBlock(branch, index));
3801
3838
  }
3802
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".' };
3803
3840
  }
3804
- 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) {
3805
3854
  const replyCalls = content.filter((block) => block.type === "toolCall" && block.name === "subagent" && (block.arguments?.workflow === true || block.arguments?.workflow === "true")).length;
3806
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.` };
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}` };
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
+ }
3808
3860
  const text = content.flatMap((block) => block.type === "text" && typeof block.text === "string" ? [block.text] : []).join("\n");
3809
3861
  const { tagged, plain, unclosed } = workflowBlocks(text);
3810
3862
  if (unclosed) return { error: "The script's fenced block in this reply is not closed." };
@@ -5795,12 +5847,20 @@ ${shared.acceptancePrompt}` : shared.systemPrompt,
5795
5847
  toolAttentionTarget.attentionEmitted = true;
5796
5848
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
5797
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
+ }
5798
5858
  return emitNeedsAttention(now, {
5799
5859
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1e3)}s`,
5800
5860
  reason: "tool_open_threshold",
5801
5861
  currentTool: toolAttentionTarget.tool,
5802
5862
  toolCallId,
5803
- hasCommandController: Boolean(toolCallId && retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId)),
5863
+ hasCommandController,
5804
5864
  currentPath: toolAttentionTarget.path,
5805
5865
  currentToolDurationMs: durationMs
5806
5866
  });
@@ -6356,7 +6416,7 @@ ${formatInheritedProviderDiagnostic({ agent: agent.name, model: launch.session.m
6356
6416
  durationMs: progress.durationMs
6357
6417
  };
6358
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;
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);
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);
6360
6420
  const acceptanceOutput = getFinalOutput(result2.messages ?? []);
6361
6421
  const structuredText = result2.structuredOutput === void 0 ? void 0 : JSON.stringify(result2.structuredOutput, null, 2);
6362
6422
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -6448,7 +6508,7 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
6448
6508
  }
6449
6509
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
6450
6510
  const effectiveCwd = options.cwd ?? runtimeCwd;
6451
- const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6511
+ const cwdError = options.machine && !isRexLocalMachine(options.machine) ? void 0 : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
6452
6512
  if (cwdError) {
6453
6513
  return redactResultPrompt(withRunContext({
6454
6514
  index: options.index ?? 0,
@@ -8325,7 +8385,7 @@ function formatResumeGuidance(runId, children, fallbackSessionFile, options = {}
8325
8385
  const resumableWorkflowChildren = workflowChildren.filter(({ child }) => !(child.status === "paused" && child.activityState === "needs_attention"));
8326
8386
  if (workflowChildren.length > 0) {
8327
8387
  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.`),
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.`),
8329
8389
  ...resumableWorkflowChildren.map(({ child }) => `Revive workflow child${typeof child.workflowKey === "string" && child.workflowKey.trim() ? ` '${child.workflowKey}'` : ""}: subagent({ action: "resume", id: "${child.runId}", message: "..." })`)
8330
8390
  ].join("\n");
8331
8391
  }
@@ -8417,7 +8477,7 @@ function formatRememberedForegroundStatus(run) {
8417
8477
  const detached = run.children.some((child) => child.status === "detached");
8418
8478
  const resumable = run.children.find((child) => hasExistingSessionFile(child.sessionFile));
8419
8479
  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.`);
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.`);
8421
8481
  } else if (resumable) {
8422
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} } })`);
8423
8483
  } else {
@@ -8984,13 +9044,13 @@ function applyForceTopLevelAsyncOverride(params, depth, forceTopLevelAsync) {
8984
9044
 
8985
9045
  // src/runs/shared/worktree-cleanup-apply.ts
8986
9046
  import { createHash as createHash5 } from "node:crypto";
8987
- import { spawnSync as spawnSync2 } from "node:child_process";
9047
+ import { spawnSync as spawnSync3 } from "node:child_process";
8988
9048
  import * as fs19 from "node:fs";
8989
9049
  import * as path17 from "node:path";
8990
9050
 
8991
9051
  // src/runs/shared/worktree-cleanup-plan.ts
8992
9052
  import { createHash as createHash4, randomUUID as randomUUID4 } from "node:crypto";
8993
- import { spawnSync } from "node:child_process";
9053
+ import { spawnSync as spawnSync2 } from "node:child_process";
8994
9054
  import * as fs18 from "node:fs";
8995
9055
  import * as os2 from "node:os";
8996
9056
  import * as path16 from "node:path";
@@ -9001,7 +9061,7 @@ var MAX_PLAN_ENTRIES = 512;
9001
9061
  var MAX_METADATA_FILE_BYTES = 2 * 1024 * 1024;
9002
9062
  function runGit(cwd, args) {
9003
9063
  try {
9004
- 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 });
9005
9065
  return {
9006
9066
  stdout: result2.stdout ?? "",
9007
9067
  stderr: result2.stderr ?? "",
@@ -9742,7 +9802,7 @@ async function applyReviewedCleanupPlan(input) {
9742
9802
  const journalEntry = { path: entry.path, branch: entry.branch, state: "removing", reason: "removal prepared; outcome not yet recorded" };
9743
9803
  receipt.entries.push(journalEntry);
9744
9804
  writePrivateAtomicJson(receiptPath, receipt);
9745
- 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 });
9746
9806
  if (removed.status !== 0) throw new Error(removed.error?.message || removed.stderr.trim() || "git worktree remove failed");
9747
9807
  journalEntry.state = "removed";
9748
9808
  journalEntry.reason = "worktree removed; local branch retained";
@@ -9832,6 +9892,38 @@ function inheritedRunFanoutBudget(deps) {
9832
9892
  function resolveRequestedCwd(runtimeCwd, requestedCwd) {
9833
9893
  return requestedCwd ? path18.resolve(runtimeCwd, requestedCwd) : runtimeCwd;
9834
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
+ }
9835
9927
  function readWorkflowScriptFile(requestedPath, requestedCwd, runtimeCwd) {
9836
9928
  const scriptPath = path18.resolve(resolveRequestedCwd(runtimeCwd, requestedCwd), requestedPath);
9837
9929
  let script;
@@ -10233,7 +10325,7 @@ function resolveForegroundResumeTarget(params, state, options = {}) {
10233
10325
  if (matches.length === 0) return void 0;
10234
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.`);
10235
10327
  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.`);
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.`);
10237
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.`);
10238
10330
  const index = params.index ?? 0;
10239
10331
  if (!Number.isInteger(index)) throw new Error(`Foreground run '${run.runId}' index must be an integer.`);
@@ -10356,8 +10448,7 @@ function persistAsyncWorkflowControlEvent(input) {
10356
10448
  fs20.appendFileSync(path18.join(input.job.asyncDir, "events.jsonl"), `${JSON.stringify(record2)}
10357
10449
  `, "utf-8");
10358
10450
  } catch (error) {
10359
- if (!isStorageCapacityError(error)) throw error;
10360
- 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");
10361
10452
  }
10362
10453
  }
10363
10454
  function emitControlNotification(input) {
@@ -10710,8 +10801,8 @@ function validateNestedSessionFile(run, trustedSessionRoots2, resolveSource, vis
10710
10801
  }
10711
10802
  return realSessionFile;
10712
10803
  }
10713
- function readNestedRecoveryDescriptor(asyncDir, runId, agent) {
10714
- const recoveryDescriptor = readAsyncRecoveryDescriptor(asyncDir);
10804
+ function readNestedRecoveryDescriptor(rootRunId, runId, agent) {
10805
+ const recoveryDescriptor = readAsyncRecoveryDescriptor(nestedRunScope(rootRunId).asyncDirRoot, runId);
10715
10806
  if (!recoveryDescriptor) return void 0;
10716
10807
  if (recoveryDescriptor.sourceRunId !== runId) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different source run.`);
10717
10808
  if (recoveryDescriptor.agent !== agent) throw new Error(`Nested run '${runId}' has a recovery descriptor for a different agent.`);
@@ -10725,7 +10816,7 @@ function resolveNestedResumeTarget(match, trustedSessionRoots2, resolveSource) {
10725
10816
  if (!agent) throw new Error(`Could not determine child agent for nested run '${run.id}'.`);
10726
10817
  const state = run.state === "complete" || run.state === "failed" || run.state === "paused" ? run.state : "failed";
10727
10818
  const asyncDir = resolveNestedAsyncDir(match.match.rootRunId, run);
10728
- const recoveryDescriptor = readNestedRecoveryDescriptor(asyncDir, run.id, agent);
10819
+ const recoveryDescriptor = asyncDir ? readNestedRecoveryDescriptor(match.match.rootRunId, run.id, agent) : void 0;
10729
10820
  return compactOptional({
10730
10821
  kind: "revive",
10731
10822
  source: "nested",
@@ -11140,6 +11231,14 @@ async function resumeAsyncRun(input) {
11140
11231
  details: { mode: "management", results: [] }
11141
11232
  };
11142
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
+ }
11143
11242
  if (target.source === "async" && target.runner?.type === "external-cli") {
11144
11243
  const runner = normalizeExternalCliRunnerStatus(target.runner);
11145
11244
  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 +11247,7 @@ async function resumeAsyncRun(input) {
11148
11247
  if (input.params.baseRef !== void 0 && "managedWorktree" in target && target.managedWorktree === true) {
11149
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: [] } };
11150
11249
  }
11151
- if (target.source === "async" && target.managedWorktree && target.asyncDir) {
11250
+ if (target.source === "async" && target.managedWorktree && target.asyncDir && fs20.existsSync(parallelHandoffPath(target.asyncDir))) {
11152
11251
  try {
11153
11252
  const protectedCwd = await protectRetainedWorktreeForResume(parallelHandoffPath(target.asyncDir), target.runId, target.index, input.signal);
11154
11253
  if (path18.resolve(protectedCwd) !== path18.resolve(effectiveCwd)) throw new Error("Retained worktree cwd changed during resume admission.");
@@ -11308,7 +11407,7 @@ async function resumeAsyncRun(input) {
11308
11407
  if (target.source === "nested" && !target.recoveryDescriptor) {
11309
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: [] } };
11310
11409
  }
11311
- const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : { ...baseAgentConfig, launcher: void 0 };
11410
+ const recoveryAgentConfig = recoveryDescriptor ? applySteeringRecoveryAgentConfig(baseAgentConfig, recoveryDescriptor) : baseAgentConfig;
11312
11411
  const agentConfig = intercomBridge.active ? applyIntercomBridgeToAgent(recoveryAgentConfig, intercomBridge) : recoveryAgentConfig;
11313
11412
  const foregroundContract = target.source === "foreground" ? target.resumeContract : void 0;
11314
11413
  const outputSchema = Object.hasOwn(input.params, "outputSchema") ? input.params.outputSchema : Object.hasOwn(foregroundContract ?? {}, "outputSchema") ? foregroundContract?.outputSchema : recoveryDescriptor?.structuredOutputSchema;
@@ -11318,7 +11417,7 @@ async function resumeAsyncRun(input) {
11318
11417
  return { content: [{ type: "text", text: `Cannot resume: ${acceptanceErrors.join(" ")}` }], isError: true, details: { mode: "management", results: [] } };
11319
11418
  }
11320
11419
  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: [] } };
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: [] } };
11322
11421
  }
11323
11422
  const runId = randomUUID5();
11324
11423
  const topLevelResume = depth === 0 && !inheritedNestedRoute(input.deps) && !input.params.workflowParentRunId;
@@ -11356,6 +11455,7 @@ async function resumeAsyncRun(input) {
11356
11455
  goal: effectiveFollowUp,
11357
11456
  agentConfig,
11358
11457
  recoveryAgentConfig,
11458
+ carriedRequiredLauncher: recoveryDescriptor?.requiredLauncher,
11359
11459
  ctx: compactOptional({
11360
11460
  pi: input.deps.pi,
11361
11461
  cwd: input.requestCwd,
@@ -11537,6 +11637,7 @@ function createForegroundControlNotifier(data, deps) {
11537
11637
  const enriched = workflowKey && !event.workflowKey ? { ...event, workflowKey } : event;
11538
11638
  if (asyncWorkflow) {
11539
11639
  persistAsyncWorkflowControlEvent({
11640
+ state: deps.state,
11540
11641
  job: asyncWorkflow,
11541
11642
  event: enriched,
11542
11643
  controlConfig: data.controlConfig,
@@ -11985,7 +12086,6 @@ function validateLaunchOutputSchemaOverrides(params) {
11985
12086
  }
11986
12087
  return void 0;
11987
12088
  }
11988
- var DEFAULT_FOREGROUND_TIMEOUT_MS = 30 * 60 * 1e3;
11989
12089
  var MAX_TIMER_DELAY_MS = 2147483647;
11990
12090
  function timerDelayOverflowError(name, value) {
11991
12091
  return typeof value === "number" && value > MAX_TIMER_DELAY_MS ? `${name} must be a positive integer no larger than ${MAX_TIMER_DELAY_MS}.` : void 0;
@@ -12016,9 +12116,7 @@ function resolveForegroundTimeout(params, defaultTimeoutMs) {
12016
12116
  }
12017
12117
  function resolveSingleAgentLaunchTimeout(params, async, configDefaultTimeoutMs) {
12018
12118
  const isComposite = (params.chain?.length ?? 0) > 0 || (params.tasks?.length ?? 0) > 0 || params.workflowScript !== void 0;
12019
- const foregroundDefault = configDefaultTimeoutMs ?? DEFAULT_FOREGROUND_TIMEOUT_MS;
12020
- const asyncSingleDefault = configDefaultTimeoutMs ?? DEFAULT_ASYNC_TIMEOUT_MS;
12021
- const defaultTimeoutMs = !async ? foregroundDefault : isComposite ? void 0 : asyncSingleDefault;
12119
+ const defaultTimeoutMs = !async || !isComposite ? configDefaultTimeoutMs : void 0;
12022
12120
  return resolveForegroundTimeout(params, defaultTimeoutMs);
12023
12121
  }
12024
12122
  function resolveToolBudget(raw, label = "toolBudget", options) {
@@ -12488,6 +12586,7 @@ async function runAsyncPath(data, deps) {
12488
12586
  requestedCwd: data.requestedCwd,
12489
12587
  machine: params.machine,
12490
12588
  machineCwd: params.machineCwd,
12589
+ requireLauncher: params.requireLauncher,
12491
12590
  maxOutput: params.maxOutput,
12492
12591
  artifactsDir: artifactConfig.enabled ? artifactsDir : void 0,
12493
12592
  artifactConfig,
@@ -12996,7 +13095,7 @@ async function runSinglePath(data, deps) {
12996
13095
 
12997
13096
  ` : "";
12998
13097
  task = readsInstruction + task;
12999
- task = injectSingleOutputInstruction(task, outputPath, agentConfig);
13098
+ task = injectSingleOutputInstruction(task, outputPath, agentConfig, foregroundMachine);
13000
13099
  let effectiveSkills;
13001
13100
  if (skillOverride === false) {
13002
13101
  effectiveSkills = [];
@@ -13141,6 +13240,7 @@ async function runSinglePath(data, deps) {
13141
13240
  suppressUnchangedDelegationUpdates,
13142
13241
  controlConfig,
13143
13242
  onControlEvent,
13243
+ onWarning: (message, key) => reportSessionWarning(deps.state, message, key),
13144
13244
  intercomSessionName: childIntercomTarget,
13145
13245
  orchestratorIntercomTarget: childBridgeActive ? data.intercomBridge.orchestratorTarget : void 0,
13146
13246
  nestedRoute: foregroundControl?.nestedRoute,
@@ -13306,8 +13406,8 @@ async function runSinglePath(data, deps) {
13306
13406
  ${worktreeHandoff.suffix}` : "";
13307
13407
  if (r.detached) {
13308
13408
  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}`;
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}`;
13311
13411
  return {
13312
13412
  content: [{ type: "text", text: `${message}${worktreeSuffix}` }],
13313
13413
  details
@@ -13690,6 +13790,7 @@ async function preflightWorkflowWorktrees(input) {
13690
13790
  input.signal.throwIfAborted();
13691
13791
  }
13692
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);
13693
13794
  const { globalConcurrencyLimit: _globalConcurrencyLimit, maxSubagentSpawnsPerRun: _maxSubagentSpawnsPerRun, ...workflowDefaultsWithoutCapacity } = workflowDefaults;
13694
13795
  const { globalConcurrencyLimit: _childGlobalConcurrencyLimit, maxSubagentSpawnsPerRun: _childMaxSubagentSpawnsPerRun, ...childParamsWithoutCapacity } = childParams;
13695
13796
  workflowDefaults = workflowDefaultsWithoutCapacity;
@@ -13927,9 +14028,10 @@ function savedWorkflowLaunchParams(params) {
13927
14028
  const { reuseFrom: _reuseFrom, scheduleOrigin: _scheduleOrigin, resumeOrigin: _resumeOrigin, ...saved } = params;
13928
14029
  return saved;
13929
14030
  }
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 };
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 } };
13933
14035
  }
13934
14036
  function createSubagentExecutor(deps) {
13935
14037
  const executorDeps = deps;
@@ -14062,7 +14164,7 @@ function createSubagentExecutor(deps) {
14062
14164
  const overflowError = timerDelayOverflowError(name, value);
14063
14165
  if (overflowError) return buildRequestedModeError(requestParams, overflowError);
14064
14166
  }
14065
- const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps2.config.timeoutMs) ?? DEFAULT_FOREGROUND_TIMEOUT_MS : void 0);
14167
+ const timeout = requestParams.timeoutMs ?? requestParams.maxRuntimeMs ?? (requestParams.async === false ? resolveConfigDefaultTimeoutMs(deps2.config.timeoutMs) : void 0);
14066
14168
  const workflowUsageBudget = validateUsageBudgetConfig(requestParams.usageBudget ?? deps2.config.usageBudget, requestParams.usageBudget ? "usageBudget" : "config.usageBudget");
14067
14169
  if (workflowUsageBudget.error) return buildRequestedModeError(requestParams, workflowUsageBudget.error);
14068
14170
  const workflowCwd = resolveRequestedCwd(parentCwd, requestParams.cwd);
@@ -14196,7 +14298,7 @@ function createSubagentExecutor(deps) {
14196
14298
  try {
14197
14299
  fs20.mkdirSync(asyncDir, { recursive: true });
14198
14300
  writeRunFanoutBudgetDescriptor(asyncDir, workflowFanoutBudget);
14199
- if (topLevelAsyncWorkflow && publicWorkflowLaunch) writeWorkflowLaunchRecord(asyncDir, workflowLaunchRecord(publicWorkflowLaunch, workflowCwd, workflowScriptSourceDigest));
14301
+ if (topLevelAsyncWorkflow) writeWorkflowLaunchRecord(DIRS.async, workflowRunId, workflowLaunchRecord(publicWorkflowLaunch ?? { source: "internal" }, workflowCwd, workflowScriptSourceDigest, currentSessionId, workflowCapabilityCeiling2));
14200
14302
  fs20.mkdirSync(DIRS.results, { recursive: true });
14201
14303
  } catch (error) {
14202
14304
  return storageFailure(error);
@@ -14835,7 +14937,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
14835
14937
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
14836
14938
  });
14837
14939
  let preparedChildParams;
14838
- const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, () => {
14940
+ const result2 = await runMissionWorkflowChild(missionBinding2, workflowRunId, key, childPhase, async () => {
14839
14941
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
14840
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 },
14841
14943
  missionBinding2,
@@ -14844,6 +14946,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
14844
14946
  inheritedNestedRoute(deps2)?.rootRunId
14845
14947
  );
14846
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);
14847
14951
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
14848
14952
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
14849
14953
  workflowLaunchObservers.set(childRequest, (launch) => {
@@ -15118,7 +15222,7 @@ Parent action: ${COMPLETION_ACTION}` : content,
15118
15222
  heartbeat: { status: "running", ...childPhase ? { phase: childPhase } : {} }
15119
15223
  });
15120
15224
  let preparedChildParams;
15121
- const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, () => {
15225
+ const result2 = await runMissionWorkflowChild(missionBinding2, foregroundWorkflowRunId, key, childPhase, async () => {
15122
15226
  const childRequest = bindMissionWorkflowChildAsyncLaunch(
15123
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 },
15124
15228
  missionBinding2,
@@ -15127,6 +15231,8 @@ Parent action: ${COMPLETION_ACTION}` : content,
15127
15231
  inheritedNestedRoute(deps2)?.rootRunId
15128
15232
  );
15129
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);
15130
15236
  if (workflowUsageBudget.budget) workflowOwnedUsageBudgets.set(childRequest, workflowUsageBudget.budget);
15131
15237
  if (workflowRequiredExtensions) workflowRetainedRequiredExtensions.set(childRequest, workflowRequiredExtensions);
15132
15238
  if (delegatedWorkflowPermit) {
@@ -16102,6 +16208,12 @@ ${item.text}` } : item)
16102
16208
  const launcherError = agent ? resolveAgentRunnerLauncher(agent, deps2.config.runnerLaunchers, effectiveParams.machine ?? agent.machine).error : void 0;
16103
16209
  if (launcherError) return buildRequestedModeError(effectiveParams, launcherError);
16104
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
+ }
16105
16217
  if (effectiveAsync && hasSingle && effectiveParams.resume === void 0 && effectiveParams.worktree === true) {
16106
16218
  try {
16107
16219
  await preflightWorktreeSource(effectiveCwd, { signal });
@@ -16640,8 +16752,6 @@ ${first.text}` };
16640
16752
  return { execute: executeWithSingleDispatchGuard, executePublic, executeDelegated, executeScheduled, executeWorkflowResume, getCurrentSupervisorOwnerStates };
16641
16753
  }
16642
16754
  export {
16643
- DEFAULT_ASYNC_TIMEOUT_MS,
16644
- DEFAULT_FOREGROUND_TIMEOUT_MS,
16645
16755
  bindMissionWorkflowChildAsyncLaunch,
16646
16756
  createSubagentExecutor,
16647
16757
  foregroundResultIntercomStatus,