@xzzpig/pi-subagents 0.24.2 → 0.25.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (258) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/bundle/agent-management.js +4 -4
  3. package/bundle/agents.js +3 -3
  4. package/bundle/child-tool-plan.js +2 -2
  5. package/bundle/chunk-34TUUBRN.js +1107 -0
  6. package/bundle/{chunk-SW2VMNIU.js → chunk-5OD3OWTE.js} +2 -2
  7. package/bundle/{chunk-XWWUDWUW.js → chunk-5YEOWNSD.js} +371 -135
  8. package/bundle/{chunk-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  9. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  10. package/bundle/{chunk-4UH4WS4G.js → chunk-6MNRKUHY.js} +23 -12
  11. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  12. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  13. package/bundle/chunk-HXRB42AF.js +108 -0
  14. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  15. package/bundle/{chunk-CYY5UMJU.js → chunk-IJWITCC6.js} +411 -249
  16. package/bundle/{chunk-RU522D5W.js → chunk-IKFKH5EL.js} +369 -50
  17. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  18. package/bundle/{chunk-JEA2ZKUA.js → chunk-IUDEI6FJ.js} +35 -200
  19. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  20. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  21. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  22. package/bundle/{chunk-224WMDIV.js → chunk-KCJFGKVK.js} +350 -123
  23. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  24. package/bundle/chunk-LYKG4FKH.js +523 -0
  25. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  26. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  27. package/bundle/{chunk-BQ2OAB4Q.js → chunk-OSVXFWPG.js} +67 -30
  28. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  29. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  30. package/bundle/{chunk-3U633XDZ.js → chunk-U3ZDUUTM.js} +11 -3
  31. package/bundle/{chunk-LVWU2HOO.js → chunk-ULGMXABL.js} +16 -7
  32. package/bundle/{chunk-WPW4V6HM.js → chunk-W7ZA6TYD.js} +2 -2
  33. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  34. package/bundle/{chunk-O4D5PBVI.js → chunk-YWXILP5N.js} +3 -2
  35. package/bundle/control-channel.js +2 -2
  36. package/bundle/index.js +1 -1
  37. package/bundle/intercom-bridge.js +2 -2
  38. package/bundle/preflight.js +12 -10
  39. package/bundle/project-panes.js +3 -3
  40. package/bundle/workflow-resources.js +1 -1
  41. package/docs/agents.md +27 -6
  42. package/docs/configuration.md +20 -8
  43. package/docs/extension-api.md +18 -1
  44. package/docs/models.md +6 -2
  45. package/docs/observability.md +2 -0
  46. package/docs/tool-reference.md +7 -1
  47. package/docs/workflows.md +30 -2
  48. package/package.json +2 -2
  49. package/skills/pi-subagents/SKILL.md +15 -6
  50. package/skills/pi-subagents/references/prompting-and-roles.md +1 -0
  51. package/src/agents/agent-management.d.ts +1 -0
  52. package/src/agents/agent-management.js +46 -18
  53. package/src/agents/agent-memory.d.ts +1 -4
  54. package/src/agents/agent-memory.js +1 -4
  55. package/src/agents/agent-serializer.d.ts +2 -0
  56. package/src/agents/agent-serializer.js +1 -1
  57. package/src/agents/agents.d.ts +2 -3
  58. package/src/agents/agents.js +46 -20
  59. package/src/agents/frontmatter.js +1 -8
  60. package/src/agents/global-npm-root.d.ts +1 -0
  61. package/src/agents/global-npm-root.js +11 -3
  62. package/src/agents/skills.d.ts +0 -3
  63. package/src/agents/skills.js +0 -3
  64. package/src/api/preflight.d.ts +3 -1
  65. package/src/api/preflight.js +2 -0
  66. package/src/extension/config.d.ts +1 -0
  67. package/src/extension/config.js +13 -1
  68. package/src/extension/herdr-pi-bridge.js +10 -2
  69. package/src/extension/index.d.ts +0 -13
  70. package/src/extension/index.js +51 -37
  71. package/src/extension/public-execution.d.ts +1 -0
  72. package/src/extension/public-execution.js +4 -0
  73. package/src/extension/reply-workflow-script.js +24 -4
  74. package/src/extension/schemas.d.ts +12 -3
  75. package/src/extension/schemas.js +7 -3
  76. package/src/extension/session-switch.d.ts +25 -0
  77. package/src/extension/session-switch.js +138 -0
  78. package/src/extension/subagent-guide.d.ts +1 -1
  79. package/src/extension/subagent-guide.js +1 -1
  80. package/src/extension/subagent-launch-tool.d.ts +25 -0
  81. package/src/extension/subagent-launch-tool.js +48 -0
  82. package/src/extension/tool-activation.js +55 -15
  83. package/src/extension/tool-description.d.ts +1 -1
  84. package/src/extension/tool-description.js +14 -8
  85. package/src/inspectors/herdr/actions.d.ts +0 -1
  86. package/src/inspectors/herdr/actions.js +0 -1
  87. package/src/inspectors/session-roots-codec.d.ts +0 -1
  88. package/src/inspectors/session-roots-codec.js +0 -1
  89. package/src/inspectors/tmux/actions.d.ts +0 -1
  90. package/src/inspectors/tmux/actions.js +0 -1
  91. package/src/integrations/herdr-status.js +3 -8
  92. package/src/intercom/native-supervisor-channel.js +65 -9
  93. package/src/runs/background/async-execution.d.ts +7 -10
  94. package/src/runs/background/async-execution.js +66 -29
  95. package/src/runs/background/async-job-tracker.js +12 -0
  96. package/src/runs/background/async-resume.d.ts +2 -1
  97. package/src/runs/background/async-resume.js +114 -40
  98. package/src/runs/background/async-retention.d.ts +0 -2
  99. package/src/runs/background/async-retention.js +17 -6
  100. package/src/runs/background/async-status.d.ts +2 -0
  101. package/src/runs/background/async-status.js +4 -0
  102. package/src/runs/background/auto-drain.js +2 -1
  103. package/src/runs/background/boot-id.d.ts +1 -3
  104. package/src/runs/background/boot-id.js +1 -3
  105. package/src/runs/background/completion-batcher.d.ts +3 -4
  106. package/src/runs/background/completion-batcher.js +2 -3
  107. package/src/runs/background/control-channel.d.ts +0 -6
  108. package/src/runs/background/control-channel.js +0 -6
  109. package/src/runs/background/fleet-view.js +2 -3
  110. package/src/runs/background/notify.d.ts +0 -2
  111. package/src/runs/background/notify.js +0 -2
  112. package/src/runs/background/result-watcher.d.ts +1 -0
  113. package/src/runs/background/result-watcher.js +59 -29
  114. package/src/runs/background/resume-guidance.js +4 -2
  115. package/src/runs/background/retained-children.js +2 -1
  116. package/src/runs/background/run-child-session.d.ts +2 -3
  117. package/src/runs/background/run-child-session.js +5 -8
  118. package/src/runs/background/run-status.js +9 -7
  119. package/src/runs/background/runner-aliases.js +15 -0
  120. package/src/runs/background/scheduled-runs.d.ts +3 -1
  121. package/src/runs/background/scheduled-runs.js +13 -16
  122. package/src/runs/background/steering.d.ts +2 -11
  123. package/src/runs/background/steering.js +11 -6
  124. package/src/runs/background/subagent-runner.d.ts +2 -6
  125. package/src/runs/background/subagent-runner.js +88 -70
  126. package/src/runs/background/subagent-wait.js +12 -15
  127. package/src/runs/background/wait-config.d.ts +2 -0
  128. package/src/runs/background/wait-config.js +17 -3
  129. package/src/runs/background/wait-subscriptions.js +124 -12
  130. package/src/runs/background/wait-tool.js +4 -2
  131. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  132. package/src/runs/background/workflow-terminal-proof.js +0 -1
  133. package/src/runs/foreground/async-steering-action.js +24 -9
  134. package/src/runs/foreground/async-stop-action.d.ts +1 -1
  135. package/src/runs/foreground/async-stop-action.js +9 -1
  136. package/src/runs/foreground/execution.d.ts +0 -3
  137. package/src/runs/foreground/execution.js +56 -24
  138. package/src/runs/foreground/prompt-audit.js +1 -0
  139. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  140. package/src/runs/foreground/subagent-executor.js +164 -49
  141. package/src/runs/shared/acceptance.js +69 -26
  142. package/src/runs/shared/async-status-projection.d.ts +2 -0
  143. package/src/runs/shared/async-status-projection.js +10 -0
  144. package/src/runs/shared/child-commands.js +15 -2
  145. package/src/runs/shared/child-hooks.d.ts +1 -7
  146. package/src/runs/shared/child-hooks.js +13 -5
  147. package/src/runs/shared/child-launch.js +6 -2
  148. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  149. package/src/runs/shared/child-session.d.ts +6 -5
  150. package/src/runs/shared/child-session.js +85 -38
  151. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  152. package/src/runs/shared/child-tool-plan.js +0 -1
  153. package/src/runs/shared/claude-code-adapter.js +11 -0
  154. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  155. package/src/runs/shared/external-cli-contract.js +18 -13
  156. package/src/runs/shared/external-cli-runner.js +26 -6
  157. package/src/runs/shared/herdr-connection.js +2 -1
  158. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  159. package/src/runs/shared/herdr-pane-host.js +17 -1
  160. package/src/runs/shared/herdr-placed-run.js +51 -24
  161. package/src/runs/shared/lane-metadata.d.ts +0 -1
  162. package/src/runs/shared/lane-metadata.js +0 -1
  163. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  164. package/src/runs/shared/mcp-config-sources.js +1 -1
  165. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  166. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  167. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  168. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  169. package/src/runs/shared/model-resolution.d.ts +20 -5
  170. package/src/runs/shared/model-resolution.js +55 -50
  171. package/src/runs/shared/model-scope.d.ts +1 -5
  172. package/src/runs/shared/model-scope.js +1 -5
  173. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  174. package/src/runs/shared/mutation-evidence.js +52 -7
  175. package/src/runs/shared/nested-events.d.ts +1 -0
  176. package/src/runs/shared/nested-events.js +1 -1
  177. package/src/runs/shared/parallel-utils.d.ts +0 -1
  178. package/src/runs/shared/permissions.js +5 -3
  179. package/src/runs/shared/placement-host.d.ts +5 -1
  180. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  181. package/src/runs/shared/rex-pane-host.js +0 -2
  182. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  183. package/src/runs/shared/run-launch-folder.js +21 -0
  184. package/src/runs/shared/runner-launcher.d.ts +12 -1
  185. package/src/runs/shared/runner-launcher.js +16 -0
  186. package/src/runs/shared/single-output.d.ts +3 -3
  187. package/src/runs/shared/single-output.js +5 -3
  188. package/src/runs/shared/structured-output.d.ts +8 -0
  189. package/src/runs/shared/structured-output.js +40 -5
  190. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  191. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  192. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  193. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  194. package/src/runs/shared/tool-timeout.js +2 -1
  195. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  196. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  197. package/src/runs/shared/worktree.d.ts +3 -0
  198. package/src/runs/shared/worktree.js +20 -0
  199. package/src/shared/artifacts.d.ts +1 -0
  200. package/src/shared/artifacts.js +132 -22
  201. package/src/shared/capacity-resilient-json.d.ts +1 -1
  202. package/src/shared/child-cache-retention.d.ts +1 -2
  203. package/src/shared/child-cache-retention.js +1 -2
  204. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  205. package/src/shared/fleet-transcript-reader.js +333 -0
  206. package/src/shared/formatters.d.ts +0 -18
  207. package/src/shared/formatters.js +0 -18
  208. package/src/shared/pruned-fork.js +2 -2
  209. package/src/shared/reported-progress.d.ts +1 -0
  210. package/src/shared/reported-progress.js +12 -0
  211. package/src/shared/session-succession.d.ts +16 -1
  212. package/src/shared/session-succession.js +41 -2
  213. package/src/shared/session-warnings.d.ts +7 -0
  214. package/src/shared/session-warnings.js +26 -0
  215. package/src/shared/settings.d.ts +0 -23
  216. package/src/shared/settings.js +3 -35
  217. package/src/shared/status-format.d.ts +1 -0
  218. package/src/shared/status-format.js +1 -1
  219. package/src/shared/types.d.ts +108 -59
  220. package/src/shared/types.js +0 -12
  221. package/src/shared/utils.d.ts +3 -15
  222. package/src/shared/utils.js +4 -22
  223. package/src/shared/wait-tool-name.d.ts +8 -0
  224. package/src/shared/wait-tool-name.js +13 -0
  225. package/src/slash/slash-commands.js +2 -1
  226. package/src/slash/subagent-cost.d.ts +3 -2
  227. package/src/slash/subagent-cost.js +22 -3
  228. package/src/slash/subagents-admin.js +0 -1
  229. package/src/tui/fleet-status.d.ts +0 -5
  230. package/src/tui/fleet-status.js +4 -24
  231. package/src/tui/fleet.js +6 -4
  232. package/src/tui/render.d.ts +0 -9
  233. package/src/tui/render.js +194 -68
  234. package/src/tui/subagent-messages.js +3 -2
  235. package/src/watchdog/model-selection.js +2 -2
  236. package/src/watchdog/permission-arbiter.js +1 -0
  237. package/src/watchdog/register-child.d.ts +2 -3
  238. package/src/watchdog/register-child.js +2 -3
  239. package/src/watchdog/review.d.ts +0 -5
  240. package/src/watchdog/review.js +4 -3
  241. package/src/watchdog/turn-delta.js +2 -1
  242. package/src/workflows/scripted-workflow.d.ts +2 -0
  243. package/src/workflows/scripted-workflow.js +344 -59
  244. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  245. package/src/workflows/structured-workflow-scripts.js +32 -11
  246. package/src/workflows/workflow-launch-record.d.ts +15 -6
  247. package/src/workflows/workflow-launch-record.js +30 -12
  248. package/src/workflows/workflow-receipt.js +36 -53
  249. package/src/workflows/workflow-resources.js +4 -4
  250. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  251. package/src/workflows/workflow-resume-claim.js +3 -3
  252. package/src/workflows/workflow-resume.d.ts +1 -1
  253. package/src/workflows/workflow-resume.js +13 -8
  254. package/src/workflows/workflow-script-worker.d.ts +13 -0
  255. package/src/workflows/workflow-script-worker.js +81 -0
  256. package/workflow-script-process.cjs +36 -0
  257. package/workflow-script-worker.cjs +4 -1
  258. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -10,22 +10,27 @@ import {
10
10
  drainOutstandingWork,
11
11
  evaluateChildToolDiagnostic,
12
12
  formatWatchdogCwdSection,
13
- registerNativeSupervisorClient,
14
13
  registerWaitTool,
15
14
  resolveCurrentSessionId,
16
15
  resolveWatchdogReviewModel,
17
16
  startWatchdogDiffBaselineCapture
18
- } from "./chunk-EUPJB4S7.js";
17
+ } from "./chunk-5Z7JAORM.js";
19
18
  import {
20
- MODEL_ONLY_TOOL,
21
19
  agentStreamOptions,
22
20
  opencodeSessionHeaders
23
- } from "./chunk-TMHVDPYW.js";
21
+ } from "./chunk-DLVPMML3.js";
22
+ import {
23
+ registerNativeSupervisorClient
24
+ } from "./chunk-34TUUBRN.js";
25
+ import {
26
+ MODEL_ONLY_TOOL
27
+ } from "./chunk-HXRB42AF.js";
24
28
  import {
25
29
  inheritedNestedRouteOf
26
- } from "./chunk-ICNYIALB.js";
30
+ } from "./chunk-JH5H4CYJ.js";
27
31
  import {
28
32
  CHILD_WATCHDOG_STATUS_EVENT,
33
+ DEFAULT_WAIT_TOOL_NAME,
29
34
  MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR,
30
35
  SUBAGENT_WATCHDOG_WARNING_TYPE,
31
36
  appendPermissionAudit,
@@ -34,12 +39,14 @@ import {
34
39
  getAgentDir,
35
40
  permissionArgsPreview,
36
41
  permissionDecision,
42
+ prepareStructuredOutputArguments,
43
+ setWaitToolName,
37
44
  shouldBlockToolForBudget,
38
45
  toolBudgetBlockedMessage,
39
46
  toolBudgetSoftNudge,
40
47
  validateAcceptanceReport,
41
48
  validateStructuredOutputValue
42
- } from "./chunk-V2KFIGFH.js";
49
+ } from "./chunk-XAC2XNAP.js";
43
50
  import {
44
51
  INTERCOM_SESSION_IDENTITY_EVENT
45
52
  } from "./chunk-UQDHXMUG.js";
@@ -288,6 +295,7 @@ function createWatchdogPermissionArbiter(options = {}) {
288
295
  ].join("\n");
289
296
  const tools = [tool];
290
297
  agent = new Agent({
298
+ sessionId,
291
299
  initialState: {
292
300
  systemPrompt,
293
301
  model: selection.model,
@@ -577,6 +585,11 @@ function modelBefore(messages, forkedAt) {
577
585
  return void 0;
578
586
  }
579
587
  var LOADOUT_SECTIONS = /* @__PURE__ */ new Set(["tools", "rules", "docs", "skills", "advertised_subagents", "mcp_servers", "project_context"]);
588
+ function projectInstructionBlocks(section) {
589
+ const blocks = /* @__PURE__ */ new Map();
590
+ for (const match of (section ?? "").matchAll(/<project_instructions\s+path=(["'])(.*?)\1\s*>[\s\S]*?<\/project_instructions>/gi)) blocks.set(match[2], match[0]);
591
+ return blocks;
592
+ }
580
593
  function forkInstructions(input) {
581
594
  const parent = getCurrentSystemMessage(input.parent);
582
595
  const child = getCurrentSystemMessage(input.child);
@@ -589,6 +602,9 @@ function forkInstructions(input) {
589
602
  for (const [name, value] of Object.entries(child?.sections ?? {})) {
590
603
  if (!LOADOUT_SECTIONS.has(name) && value && parent?.sections?.[name] !== value) parts.push(value);
591
604
  }
605
+ const parentFiles = projectInstructionBlocks(parent?.sections?.project_context);
606
+ const missingFiles = [...projectInstructionBlocks(child?.sections?.project_context)].filter(([filePath]) => !parentFiles.has(filePath)).map(([, block]) => block);
607
+ if (missingFiles.length > 0) parts.push(["Project instructions for your working folder, which the parent's prompt does not include:", ...missingFiles].join("\n\n"));
592
608
  if (input.boundary) parts.push(input.boundary);
593
609
  return `<subagent_instructions>
594
610
  ${parts.join("\n\n")}
@@ -786,6 +802,7 @@ function registerStructuredOutputTool(pi, structured) {
786
802
  label: "Structured Output",
787
803
  description: "Submit the required final structured output for this subagent step. This terminates the step.",
788
804
  parameters,
805
+ prepareArguments: (args) => prepareStructuredOutputArguments(structured.schema, args),
789
806
  async execute(_id, params) {
790
807
  const validation = await validateStructuredOutputValue(structured.schema, params.value);
791
808
  if (validation.status === "invalid") {
@@ -839,6 +856,7 @@ function registerSubagentPromptRuntime(pi, config, drainObservation) {
839
856
  } }
840
857
  };
841
858
  const nestedRootRunId = inheritedNestedRouteOf(config)?.rootRunId;
859
+ setWaitToolName(config.waitTool.name ?? DEFAULT_WAIT_TOOL_NAME);
842
860
  if (typeof pi.registerTool === "function") registerWaitTool(pi, waitState, config.waitTool.enabled, void 0, config.waitTool.defaultTimeoutMs, { nestedRootRunId }, () => config.hasPendingSupervisorRequest?.() === true);
843
861
  const supervisorMetadata = childSupervisorMetadata(config);
844
862
  let nativeSupervisorClientRegistered = false;
@@ -1,22 +1,18 @@
1
1
  import {
2
2
  PLACED_RESTORE_UNSUPPORTED,
3
- REX_BUNDLE_BIN,
4
- REX_CALL_TIMEOUT_MS,
5
- REX_EXIT_GONE,
6
- REX_EXIT_UNREACHABLE,
7
- REX_MAX_OUTPUT,
8
3
  connectHerdrMachine,
9
- isRexLocalMachine,
10
4
  remoteShellCommand,
11
- resolveRexBinary,
12
- rexCommandEnv,
13
- rexGlobalArgs,
14
5
  runBoundedCommand,
15
6
  sshMachineAccess
16
- } from "./chunk-35GII5EF.js";
7
+ } from "./chunk-JWFLPSTP.js";
17
8
  import {
18
9
  package_default
19
- } from "./chunk-O4D5PBVI.js";
10
+ } from "./chunk-YWXILP5N.js";
11
+ import {
12
+ ensureSupervisorChannelDir
13
+ } from "./chunk-34TUUBRN.js";
14
+ import "./chunk-HXRB42AF.js";
15
+ import "./chunk-NIXWDZZV.js";
20
16
  import {
21
17
  HERDR_PI_MODE_ENV,
22
18
  HERDR_PI_PROTOCOL,
@@ -27,11 +23,20 @@ import {
27
23
  validateHerdrPiRunId
28
24
  } from "./chunk-4QFZZV3O.js";
29
25
  import {
26
+ REX_BUNDLE_BIN,
27
+ REX_CALL_TIMEOUT_MS,
28
+ REX_EXIT_GONE,
29
+ REX_EXIT_UNREACHABLE,
30
+ REX_MAX_OUTPUT,
30
31
  SUBAGENT_PERMISSION_PROFILE_ENV,
31
32
  SUBAGENT_PERMISSION_PROFILE_PINNED_ENV,
32
33
  getAgentDir,
33
- getPiSpawnCommand
34
- } from "./chunk-V2KFIGFH.js";
34
+ getPiSpawnCommand,
35
+ isRexLocalMachine,
36
+ resolveRexBinary,
37
+ rexCommandEnv,
38
+ rexGlobalArgs
39
+ } from "./chunk-XAC2XNAP.js";
35
40
  import "./chunk-UQDHXMUG.js";
36
41
  import "./chunk-QXASAHIA.js";
37
42
  import "./chunk-YFCK7H2S.js";
@@ -461,8 +466,18 @@ var herdrPaneHost = {
461
466
  const { terminalId } = await startHerdrAgent(connection, owned, request.kind, request.name, request.args, options);
462
467
  return { owned, terminalId };
463
468
  },
464
- async prompt(connection, identity, text) {
465
- await connection.client.call("agent.prompt", { target: identity.agentName, text });
469
+ async prompt(connection, identity, text, options = {}) {
470
+ const clock = options.clock ?? { now: () => Date.now(), wait: (ms) => new Promise((resolve) => setTimeout(resolve, ms)) }, deadline = clock.now() + (options.timeoutMs ?? 5e3), pollMs = options.pollMs ?? 100;
471
+ for (; ; ) {
472
+ try {
473
+ await connection.client.call("agent.prompt", { target: identity.agentName, text });
474
+ return;
475
+ } catch (error) {
476
+ if (!(error instanceof Error) || !error.message.includes("is not an active named agent") || clock.now() >= deadline) throw error;
477
+ await clock.wait(Math.min(pollMs, deadline - clock.now()));
478
+ if (options.stopped?.()) throw new Error("Remote Pi prompt was not sent because the run was stopped.", { cause: error });
479
+ }
480
+ }
466
481
  },
467
482
  subscribe(connection, paneId, listener, onDisconnect) {
468
483
  return connection.client.subscribe(herdrStatusSubscriptions(paneId), listener, onDisconnect);
@@ -975,6 +990,7 @@ var HerdrPiSession = class {
975
990
  #reconnectFactory;
976
991
  #reconnectFailure;
977
992
  #replyTimer;
993
+ #repliesInFlight = /* @__PURE__ */ new Set();
978
994
  supervisorDir;
979
995
  runtime;
980
996
  owner;
@@ -989,20 +1005,35 @@ var HerdrPiSession = class {
989
1005
  this.#initialGit = initialGit;
990
1006
  bridge.adopt((frame) => this.#frame(frame));
991
1007
  if (this.supervisorDir) {
992
- this.#replyTimer = setInterval(() => {
993
- const replies = path5.join(this.supervisorDir, "replies");
994
- for (const name of fs3.existsSync(replies) ? fs3.readdirSync(replies) : []) {
995
- const file = path5.join(replies, name);
996
- try {
997
- const value = JSON.parse(fs3.readFileSync(file, "utf8"));
998
- if (typeof value.message === "string" && typeof value.requestId === "string") void this.#operation("supervisor-reply", value.message, value.requestId, typeof value.error === "string" ? value.error : void 0).then(() => fs3.rmSync(file, { force: true }));
999
- } catch {
1000
- }
1001
- }
1002
- }, 50);
1008
+ this.#replyTimer = setInterval(() => this.#deliverSupervisorReplies(this.supervisorDir), 50);
1003
1009
  this.#replyTimer.unref?.();
1004
1010
  }
1005
1011
  }
1012
+ // Runs on a timer, where a throw or an unhandled rejection exits Pi. A reply that can't be read or delivered stays
1013
+ // on disk for the next tick, once its earlier delivery has settled; a lost transport reaches the session through the
1014
+ // bridge failure.
1015
+ #deliverSupervisorReplies(supervisorDir) {
1016
+ const replies = path5.join(supervisorDir, "replies");
1017
+ let names;
1018
+ try {
1019
+ names = fs3.existsSync(replies) ? fs3.readdirSync(replies) : [];
1020
+ } catch {
1021
+ return;
1022
+ }
1023
+ for (const name of names) {
1024
+ const file = path5.join(replies, name);
1025
+ if (this.#repliesInFlight.has(file)) continue;
1026
+ try {
1027
+ const value = JSON.parse(fs3.readFileSync(file, "utf8"));
1028
+ if (typeof value.message === "string" && typeof value.requestId === "string") {
1029
+ this.#repliesInFlight.add(file);
1030
+ void this.#operation("supervisor-reply", value.message, value.requestId, typeof value.error === "string" ? value.error : void 0).then(() => fs3.rmSync(file, { force: true })).catch(() => {
1031
+ }).finally(() => this.#repliesInFlight.delete(file));
1032
+ }
1033
+ } catch {
1034
+ }
1035
+ }
1036
+ }
1006
1037
  get host() {
1007
1038
  return this.owner.host;
1008
1039
  }
@@ -1113,6 +1144,7 @@ var HerdrPiSession = class {
1113
1144
  const createdAt = Date.now();
1114
1145
  const file = path5.join(this.supervisorDir, "requests", `${path5.basename(frame.requestId)}.json`);
1115
1146
  const request = { type: "subagent.supervisor.request", id: frame.requestId, createdAt, ...reason !== "progress_update" ? { expiresAt: createdAt + 10 * 6e4 } : {}, reason, message: typeof frame.message === "string" ? frame.message : "", ...frame.interview && typeof frame.interview === "object" ? { interview: frame.interview } : {}, expectsReply: reason !== "progress_update", runId: this.runtime.runId ?? this.identity.runId, agent: this.runtime.agent ?? "remote", childIndex: this.runtime.childIndex ?? 0, orchestratorSessionId: this.runtime.orchestratorSessionId };
1147
+ ensureSupervisorChannelDir(this.supervisorDir);
1116
1148
  try {
1117
1149
  fs3.writeFileSync(file, JSON.stringify(request), { mode: 384, flag: "wx" });
1118
1150
  } catch (error) {
@@ -1128,7 +1160,7 @@ var HerdrPiSession = class {
1128
1160
  if (operation === "prompt") completion = new Promise((resolve, reject) => this.#operations.set(requestId, { resolve, reject, accepted: false, settled: false }));
1129
1161
  try {
1130
1162
  await Promise.race([this.bridge.prepare(requestId, operation, text, supervisorId, supervisorError), this.bridge.failure]);
1131
- await this.host.prompt(this.connection, this.identity, `/pi-subagents-bridge ${requestId}`);
1163
+ await this.host.prompt(this.connection, this.identity, `/pi-subagents-bridge ${requestId}`, operation === "abort" ? {} : { stopped: () => this.#aborted || this.#disposed });
1132
1164
  await completion;
1133
1165
  } catch (error) {
1134
1166
  if (operation === "prompt" && this.bridge.failed) {
@@ -1284,17 +1316,22 @@ function createPlacedPiSession(launch) {
1284
1316
  return launch.machine?.provider === "rex" ? createRexPiSession(launch) : createHerdrPiSession(launch);
1285
1317
  }
1286
1318
  function createPlacementAwareChildSessionFactory(local, createRemote = createPlacedPiSession) {
1287
- const remote = /* @__PURE__ */ new Set();
1319
+ const remote = /* @__PURE__ */ new Map();
1288
1320
  return { async create(launch) {
1289
1321
  if (!launch.machine) return local.create(launch);
1290
1322
  serializeHerdrPiLaunch(launch);
1291
1323
  const child = await createRemote(launch);
1292
- remote.add(child);
1324
+ remote.set(child, launch.parentSessionFile);
1293
1325
  return child;
1294
1326
  }, async dispose() {
1295
- await Promise.allSettled([...remote].map((child) => child.dispose()));
1327
+ await Promise.allSettled([...remote.keys()].map((child) => child.dispose()));
1296
1328
  remote.clear();
1297
1329
  await local.dispose();
1330
+ }, async disposeForParent(parentSessionFile) {
1331
+ const matching = [...remote].filter(([, parent]) => parent === parentSessionFile).map(([child]) => child);
1332
+ await Promise.allSettled(matching.map((child) => child.dispose()));
1333
+ for (const child of matching) remote.delete(child);
1334
+ await local.disposeForParent(parentSessionFile);
1298
1335
  } };
1299
1336
  }
1300
1337
  export {
@@ -112,7 +112,21 @@ import { randomUUID } from "node:crypto";
112
112
  var OUTPUT_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
113
113
  var PLACEHOLDER_PATTERN = /\{(?:task|previous|outputs\.([A-Za-z_][A-Za-z0-9_]*))\}/g;
114
114
  var CHILD_FIELDS = ["cwd", "model"];
115
- var TOP_LEVEL_CONTROLS_HINT = " Put worktree and other child controls on the subagent call itself; they apply to every child.";
115
+ var SHARED_CHILD_CONTROLS = /* @__PURE__ */ new Set(["worktree", "baseRef", "context", "skill", "fast", "agentScope", "outputMode", "outputSchema", "agentContract", "acceptance", "gate", "toolBudget", "toolTimeoutMs", "control"]);
116
+ var SCRIPT_CHILD_FIELDS = /* @__PURE__ */ new Set(["key", "label", "phase", "resume", "async", "timeoutMs"]);
117
+ function unsupportedChildFieldAdvice(fields, scripts) {
118
+ const perChild = scripts ? "use workflow: true with runs.all items" : "you need workflow scripts, which disabledFeatures has turned off";
119
+ const advice = [];
120
+ const itemFields = fields.filter((field) => CHILD_FIELDS.includes(field));
121
+ if (itemFields.length > 0) advice.push(`Set ${itemFields.join(", ")} on each item, or on the subagent call itself to give every child the same value.`);
122
+ if (fields.includes("output")) advice.push(`For one shared output, set output on the subagent call itself: the workflow result is written there and each child gets its own file beside it. For exact or different per-child paths, ${perChild}. Do not drop output if you need durable child files.`);
123
+ const shared = fields.filter((field) => SHARED_CHILD_CONTROLS.has(field));
124
+ if (shared.length > 0) advice.push(`Set ${shared.join(", ")} on the subagent call itself to give every child the same value; for different values per child, ${perChild}.`);
125
+ const scriptOnly = fields.filter((field) => SCRIPT_CHILD_FIELDS.has(field));
126
+ if (scriptOnly.length > 0) advice.push(`For per-child ${scriptOnly.join(", ")}, ${perChild}.`);
127
+ advice.push("No child was launched.");
128
+ return advice.join(" ");
129
+ }
116
130
  function isPlainRecord(value) {
117
131
  if (!value || typeof value !== "object" || Array.isArray(value)) return false;
118
132
  const prototype = Object.getPrototypeOf(value);
@@ -122,10 +136,10 @@ function nonEmptyString(value, path) {
122
136
  if (typeof value !== "string" || !value.trim()) throw new Error(`${path} must be a non-empty string.`);
123
137
  return value;
124
138
  }
125
- function exactFields(value, path, allowed, hint) {
139
+ function exactFields(value, path, allowed, hint, scripts) {
126
140
  if (!isPlainRecord(value)) throw new Error(`${path} must be an object.`);
127
141
  const unsupported = Object.keys(value).filter((key) => !allowed.includes(key));
128
- if (unsupported.length > 0) throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint}`);
142
+ if (unsupported.length > 0) throw new Error(`${path} contains unsupported fields: ${unsupported.join(", ")}. ${hint} ${unsupportedChildFieldAdvice(unsupported, scripts)}`);
129
143
  return value;
130
144
  }
131
145
  function compileTemplate(template, scope) {
@@ -184,11 +198,11 @@ var SETTLE_HELPER = [
184
198
  ' return new Error(label + ": " + children.filter(function (child) { return !child.ok; }).map(function (child) { return child.key + " (" + child.agent + ") failed" + (child.error ? ": " + child.error : ""); }).join("; "));',
185
199
  "}"
186
200
  ].join("\n");
187
- function buildTasksScript(steps, originalTask) {
201
+ function buildTasksScript(steps, originalTask, scripts) {
188
202
  if (!Array.isArray(steps) || steps.length === 0) throw new Error("tasks must be a non-empty array of { agent, task } items.");
189
203
  const children = steps.map((item, index) => {
190
204
  const path = `tasks[${index}]`;
191
- const record = exactFields(item, path, ["agent", "task", ...CHILD_FIELDS], `Each tasks item accepts agent and task, plus optional cwd and model.${TOP_LEVEL_CONTROLS_HINT}`);
205
+ const record = exactFields(item, path, ["agent", "task", ...CHILD_FIELDS], "Each tasks item accepts agent and task, plus optional cwd and model.", scripts);
192
206
  const agent = nonEmptyString(record.agent, `${path}.agent`);
193
207
  const task = nonEmptyString(record.task, `${path}.task`);
194
208
  const taskExpression = compileTemplate(task, {
@@ -219,18 +233,18 @@ function buildChainScript(steps, originalTask) {
219
233
  let stepChildren;
220
234
  let outputName;
221
235
  if (isPlainRecord(step) && Object.hasOwn(step, "parallel")) {
222
- const record = exactFields(step, path, ["parallel"], `A parallel step accepts only parallel; as is supported on sequential steps only.${TOP_LEVEL_CONTROLS_HINT}`);
236
+ const record = exactFields(step, path, ["parallel"], "A parallel step accepts only parallel; as is supported on sequential steps only.", false);
223
237
  const items = record.parallel;
224
238
  if (!Array.isArray(items) || items.length === 0) throw new Error(`${path}.parallel must be a non-empty array of { agent, task } items.`);
225
239
  stepChildren = items.map((item, itemIndex) => {
226
240
  const itemPath = `${path}.parallel[${itemIndex}]`;
227
- const itemRecord = exactFields(item, itemPath, ["agent", "task", ...CHILD_FIELDS], `Each parallel item accepts agent and task, plus optional cwd and model.${TOP_LEVEL_CONTROLS_HINT}`);
241
+ const itemRecord = exactFields(item, itemPath, ["agent", "task", ...CHILD_FIELDS], "Each parallel item accepts agent and task, plus optional cwd and model.", false);
228
242
  const agent = nonEmptyString(itemRecord.agent, `${itemPath}.agent`);
229
243
  const task = nonEmptyString(itemRecord.task, `${itemPath}.task`);
230
244
  return { key: `step-${number}-${itemIndex + 1}`, agent, fields: childFields(itemRecord, itemPath), taskExpression: compileTemplate(task, { path: `${itemPath}.task`, hasOriginalTask, previous, outputs }) };
231
245
  });
232
246
  } else {
233
- const record = exactFields(step, path, ["agent", "task", "as", ...CHILD_FIELDS], `A sequential step accepts agent, task, as, cwd and model; a parallel step accepts only parallel.${TOP_LEVEL_CONTROLS_HINT}`);
247
+ const record = exactFields(step, path, ["agent", "task", "as", ...CHILD_FIELDS], "A sequential step accepts agent, task, as, cwd and model; a parallel step accepts only parallel.", false);
234
248
  const agent = nonEmptyString(record.agent, `${path}.agent`);
235
249
  let task;
236
250
  if (record.task === void 0) {
@@ -256,8 +270,8 @@ function buildChainScript(steps, originalTask) {
256
270
  lines.push("return { ok: true, children };");
257
271
  return lines.join("\n");
258
272
  }
259
- function buildStructuredWorkflowScript(kind, steps, originalTask) {
260
- return kind === "tasks" ? buildTasksScript(steps, originalTask) : buildChainScript(steps, originalTask);
273
+ function buildStructuredWorkflowScript(kind, steps, originalTask, scripts) {
274
+ return kind === "tasks" ? buildTasksScript(steps, originalTask, scripts) : buildChainScript(steps, originalTask);
261
275
  }
262
276
 
263
277
  // src/workflows/workflow-resources.ts
@@ -375,9 +389,9 @@ function resolveRunCi(args) {
375
389
  }
376
390
  function resolveParallel(args) {
377
391
  const unsupported = Object.keys(args).filter((key) => key !== "tasks");
378
- if (unsupported.length > 0) return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task, cwd?, model? }, ...].${TOP_LEVEL_CONTROLS_HINT}` };
392
+ if (unsupported.length > 0) return { error: `workflow 'parallel' args contain unsupported fields: ${unsupported.join(", ")}. Pass args.tasks: [{ agent, task, cwd?, model? }, ...]. ${unsupportedChildFieldAdvice(unsupported, true)}` };
379
393
  try {
380
- return { script: buildStructuredWorkflowScript("tasks", args.tasks, void 0) };
394
+ return { script: buildStructuredWorkflowScript("tasks", args.tasks, void 0, true) };
381
395
  } catch (error) {
382
396
  return { error: `workflow 'parallel' args.${error instanceof Error ? error.message : String(error)}` };
383
397
  }
@@ -415,7 +429,7 @@ function resolveStructuredWorkflowResource(input) {
415
429
  validatePlainJson(task, "task");
416
430
  }
417
431
  if (jsonByteLength({ [kind]: steps, task }) > MAX_ARGS_BYTES) return { ok: false, error: `${kind} input exceeds ${MAX_ARGS_BYTES} bytes.` };
418
- const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task);
432
+ const script = buildStructuredWorkflowScript(kind, JSON.parse(JSON.stringify(steps)), task, false);
419
433
  return { ok: true, resource: issueWorkflowResource(kind, STRUCTURED_WORKFLOW_RESOURCE_VERSION, script) };
420
434
  } catch (error) {
421
435
  return { ok: false, error: error instanceof Error ? error.message.slice(0, 4096) : "Structured workflow resolution failed." };
@@ -3,11 +3,11 @@ import {
3
3
  } from "./chunk-7J4ZXMY7.js";
4
4
  import {
5
5
  getProjectSubagentsDir
6
- } from "./chunk-U4ODUYAG.js";
6
+ } from "./chunk-LYKG4FKH.js";
7
7
  import {
8
8
  getPiSpawnCommand,
9
9
  writeAtomicJson
10
- } from "./chunk-V2KFIGFH.js";
10
+ } from "./chunk-XAC2XNAP.js";
11
11
 
12
12
  // src/inspectors/herdr/project-panes.ts
13
13
  import * as fs from "node:fs";
@@ -11,13 +11,13 @@ import {
11
11
  validateAuthorityPolicy,
12
12
  validateMissionStoreConfig,
13
13
  validateModelResponseAliases
14
- } from "./chunk-ICNYIALB.js";
14
+ } from "./chunk-JH5H4CYJ.js";
15
15
  import {
16
16
  getAgentDir,
17
17
  readStatus,
18
18
  validatePermissionConfig,
19
19
  writePrivateAtomicJson
20
- } from "./chunk-V2KFIGFH.js";
20
+ } from "./chunk-XAC2XNAP.js";
21
21
  import {
22
22
  FLEET_KEYBINDING_ACTIONS,
23
23
  RUNNER_LAUNCHER_NAME_PATTERN,
@@ -525,7 +525,7 @@ import * as fs2 from "node:fs";
525
525
  import * as os from "node:os";
526
526
  import * as path2 from "node:path";
527
527
  import { Key } from "@earendil-works/pi-tui";
528
- var FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation", "authorityPolicy", "permissions", "toolBudget", "runnerLaunchers"];
528
+ var FAIL_CLOSED_CONFIG_KEYS = ["worktreeProvider", "worktreeBranchPrefix", "modelResponseAliases", "modelExclusions", "checkpointBeforeDeadlineMs", "disabledFeatures", "scheduledRuns", "toolActivation", "authorityPolicy", "permissions", "toolBudget", "runnerLaunchers", "globalConcurrencyLimit"];
529
529
  var ARTIFACT_DIR_PREFERENCES = /* @__PURE__ */ new Set(["project", "session", "temp"]);
530
530
  var FLEET_KEYBINDING_ACTION_SET = new Set(FLEET_KEYBINDING_ACTIONS);
531
531
  var KEY_MODIFIERS = /* @__PURE__ */ new Set(["ctrl", "shift", "alt", "super"]);
@@ -658,6 +658,9 @@ function validateConfig(config) {
658
658
  if (config.maxActiveAsyncRunsPerSession !== void 0 && (typeof config.maxActiveAsyncRunsPerSession !== "number" || !Number.isInteger(config.maxActiveAsyncRunsPerSession) || config.maxActiveAsyncRunsPerSession < 0)) {
659
659
  throw new Error("config.maxActiveAsyncRunsPerSession must be a non-negative integer");
660
660
  }
661
+ if (config.globalConcurrencyLimit !== void 0 && (typeof config.globalConcurrencyLimit !== "number" || !Number.isInteger(config.globalConcurrencyLimit) || config.globalConcurrencyLimit < 1)) {
662
+ throw new Error("config.globalConcurrencyLimit must be a positive integer");
663
+ }
661
664
  if (config.resultScanLogging !== void 0 && config.resultScanLogging !== "all" && config.resultScanLogging !== "activity" && config.resultScanLogging !== "off") {
662
665
  throw new Error('config.resultScanLogging must be "all", "activity", or "off"');
663
666
  }
@@ -699,6 +702,10 @@ function validateConfig(config) {
699
702
  validateOrcaProgressTabsConfig(config.orcaProgressTabs);
700
703
  validateRunnerLaunchersConfig(config.runnerLaunchers);
701
704
  }
705
+ function resolveConfigDefaultTimeoutMs(raw) {
706
+ if (typeof raw !== "number" || !Number.isInteger(raw) || raw <= 0 || raw > 2147483647) return void 0;
707
+ return raw;
708
+ }
702
709
  function getConfigPath() {
703
710
  return path2.join(getAgentDir(), "extensions", "subagent", "config.json");
704
711
  }
@@ -744,6 +751,7 @@ export {
744
751
  acquireActiveAsyncCapacity,
745
752
  transferActiveAsyncCapacity,
746
753
  resolveScheduledStoreRoot,
754
+ resolveConfigDefaultTimeoutMs,
747
755
  resolveAsyncByDefault,
748
756
  loadConfig
749
757
  };
@@ -7,13 +7,15 @@ import {
7
7
  formatNestedRunStatusLines,
8
8
  isStoppableAsyncStatusStep,
9
9
  listAsyncRuns,
10
- ownsRun,
11
10
  resolveAsyncStatusChild,
12
11
  stopStoppableAsyncStatusChildren,
13
12
  summarizeContextModes,
14
13
  utf8Tail,
15
14
  workflowPreflightLaneForRuntimeKey
16
- } from "./chunk-TMHVDPYW.js";
15
+ } from "./chunk-DLVPMML3.js";
16
+ import {
17
+ ownsRun
18
+ } from "./chunk-HXRB42AF.js";
17
19
  import {
18
20
  assertSafeNestedId,
19
21
  checkRecordedPidLiveness,
@@ -32,11 +34,11 @@ import {
32
34
  updateActiveRunIndex,
33
35
  validateModelResponseAliases,
34
36
  writeAsyncResultFile
35
- } from "./chunk-ICNYIALB.js";
37
+ } from "./chunk-JH5H4CYJ.js";
36
38
  import {
37
39
  deliverStopRequest,
38
40
  stopInboxClosedPath
39
- } from "./chunk-RB4GELQA.js";
41
+ } from "./chunk-LPJEKHOY.js";
40
42
  import {
41
43
  SUBAGENT_STOPPED_MESSAGE,
42
44
  formatDuration,
@@ -45,9 +47,10 @@ import {
45
47
  readStatus,
46
48
  shortenPath,
47
49
  validateAcceptanceInput,
50
+ waitToolName,
48
51
  writeAtomicJson,
49
52
  writePrivateAtomicJson
50
- } from "./chunk-V2KFIGFH.js";
53
+ } from "./chunk-XAC2XNAP.js";
51
54
  import {
52
55
  DIRS
53
56
  } from "./chunk-UQDHXMUG.js";
@@ -403,7 +406,7 @@ function formatDetachedForegroundFleetLines(runs) {
403
406
  const childSummary = detachedChildren.map((child) => `${fleetChildDisplayName(child)} #${child.index}`).join(", ");
404
407
  lines.push(`- ${run.runId} | detached | ${run.mode}${childSummary ? ` | ${childSummary}` : ""}`);
405
408
  lines.push(` status: subagent({ action: "status", id: "${run.runId}" })`);
406
- 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.`);
409
+ 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.`);
407
410
  }
408
411
  return lines;
409
412
  }
@@ -934,13 +937,19 @@ function deliverAsyncRunStop(input) {
934
937
  if (!(pausedWholeRun && fs5.existsSync(stopInboxClosedPath(delivery.asyncDir)))) deliverStopRequest(delivery);
935
938
  if (pausedWholeRun) return sealPausedRun(delivery.asyncDir, status, resultsDir);
936
939
  }
937
- function stopAsyncRun(state, runId, kill, location, childId) {
940
+ function stopAsyncRun(state, runId, kill, location, childId, drain) {
938
941
  const target = getAsyncStopTarget(state, runId, location);
939
942
  const workflowRunId = target?.asyncId ?? runId;
940
943
  const workflowController = childId === void 0 && workflowRunId ? state.workflowControllers?.get(workflowRunId) : void 0;
941
944
  const workflowAsyncDir = workflowController && workflowRunId ? target?.asyncDir ?? state.asyncJobs.get(workflowRunId)?.asyncDir : void 0;
942
945
  const workflowStatus = workflowAsyncDir ? readStatus(workflowAsyncDir) : void 0;
943
946
  const foreignWorkflow = Boolean(state.currentSessionId && workflowStatus && workflowStatus.sessionId !== state.currentSessionId);
947
+ if (drain) {
948
+ const drained = workflowController && workflowRunId && !foreignWorkflow && !workflowController.signal.aborted ? state.workflowDrains?.get(workflowRunId)?.() : void 0;
949
+ if (!drained) return { content: [{ type: "text", text: `drain applies only to live async workflows in this session; '${runId ?? "current"}' is not one.` }], isError: true, details: { mode: "management", results: [] } };
950
+ if (!drained.ok) return { content: [{ type: "text", text: `Could not save the drain request for '${workflowRunId}'; nothing was stopped. Retry, or use stop without drain.` }], isError: true, details: { mode: "management", results: [] } };
951
+ return { content: [{ type: "text", text: `Drain requested for async workflow ${workflowRunId}: no new children will start; ${drained.started} started child(ren) will finish.` }], details: { mode: "management", results: [] } };
952
+ }
944
953
  if (workflowController && workflowRunId && !foreignWorkflow) {
945
954
  if (workflowStatus) stopStoppableAsyncStatusChildren(workflowStatus, state.workflowChildStops?.get(workflowRunId), "Workflow stopped.");
946
955
  workflowController.abort(new Error("Workflow stopped."));
@@ -1,10 +1,10 @@
1
1
  import {
2
2
  appendAgentRefinementOverlay
3
- } from "./chunk-SW2VMNIU.js";
3
+ } from "./chunk-5OD3OWTE.js";
4
4
  import {
5
5
  buildAgentMemoryInjection,
6
6
  buildSkillInjection
7
- } from "./chunk-V2KFIGFH.js";
7
+ } from "./chunk-XAC2XNAP.js";
8
8
 
9
9
  // src/runs/shared/effective-system-prompt.ts
10
10
  function appendSection(prompt, section) {