@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
@@ -48,13 +48,12 @@ import { toAgentToolUsage } from "../../shared/utils.js";
48
48
  import { collectWaitCompletions } from "./wait-completions.js";
49
49
  import { formatResumeFirstFailedRunsNote } from "./resume-guidance.js";
50
50
  import { formatTimeoutRecoveryLines } from "../shared/mutation-evidence.js";
51
+ import { waitToolName } from "../../shared/wait-tool-name.js";
51
52
  export { WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV, WAIT_TOOL_ENABLED_ENV, resolveWaitToolConfig } from "./wait-config.js";
52
- /** States that mean a run is still in flight (not yet resolved). */
53
53
  const ACTIVE_STATES = ["queued", "running"];
54
- const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes
54
+ const DEFAULT_TIMEOUT_MS = 30 * 60 * 1000;
55
55
  const MIN_POLL_INTERVAL_MS = 250;
56
56
  const DEFAULT_POLL_INTERVAL_MS = 1000;
57
- /** Bus channels that indicate a run changed state or needs attention. */
58
57
  const WAKE_CHANNELS = [
59
58
  INTERCOM_DETACH_REQUEST_EVENT,
60
59
  SUBAGENT_ASYNC_COMPLETE_EVENT,
@@ -167,9 +166,8 @@ function foregroundChildrenNeedingAttention(run, indices) {
167
166
  }
168
167
  function formatForegroundAttention(run, children, elapsedMs) {
169
168
  const childList = children.map((child) => `${child.agent}${child.index !== undefined ? `#${child.index}` : ""}`).join(", ");
170
- return result(`Waited ${formatDuration(elapsedMs)} for remembered detached foreground run "${run.runId}"; attention required. ${children.length} child run(s) need attention: ${childList}. Reply to any pending supervisor request, then call bg_wait({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`);
169
+ return result(`Waited ${formatDuration(elapsedMs)} for remembered detached foreground run "${run.runId}"; attention required. ${children.length} child run(s) need attention: ${childList}. Reply to any pending supervisor request, then call ${waitToolName()}({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`);
171
170
  }
172
- /** A running run that has flagged it needs the parent's attention. */
173
171
  function needsAttention(run) {
174
172
  return run.activityState === "needs_attention" || run.steps.some((step) => step.activityState === "needs_attention");
175
173
  }
@@ -184,7 +182,7 @@ function backgroundWorkIdentity(item) {
184
182
  export function backgroundWorkForSession(deps, nowMs) {
185
183
  const sessionId = deps.state.currentSessionId;
186
184
  if (!sessionId)
187
- throw new Error("bg_wait requires an active session identity to scope background work safely.");
185
+ throw new Error(`${waitToolName()} requires an active session identity to scope background work safely.`);
188
186
  // Providers may key items by the session file path or by getSessionId(); accept both.
189
187
  const piSessionId = deps.state.supervisorOwnerSessionId;
190
188
  const sessionIds = piSessionId ? [sessionId, piSessionId] : [sessionId];
@@ -216,7 +214,6 @@ function runsForSession(params, deps, activeOnly = true) {
216
214
  function activeRunsForSession(params, deps) {
217
215
  return runsForSession(params, deps);
218
216
  }
219
- /** Runs (from the initial set) currently flagged needs_attention, for reporting. */
220
217
  function attentionRunsForSession(params, deps, initialIds) {
221
218
  return activeRunsForSession(params, deps).filter((run) => needsAttention(run) && initialIds.has(run.id));
222
219
  }
@@ -497,7 +494,7 @@ async function waitForDetachedForegroundRun(run, signal, deps, startedAt, now, p
497
494
  return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Remembered foreground run "${run.runId}" remains detached. Reply to any pending supervisor request before resuming or launching a replacement.`, true);
498
495
  }
499
496
  if (now() - startedAt >= timeoutMs) {
500
- return windowElapsedResult(`Wait window elapsed after ${formatDuration(timeoutMs)} with remembered foreground run "${run.runId}" still detached. Reply to any pending supervisor request, then call bg_wait({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`, [run.runId]);
497
+ return windowElapsedResult(`Wait window elapsed after ${formatDuration(timeoutMs)} with remembered foreground run "${run.runId}" still detached. Reply to any pending supervisor request, then call ${waitToolName()}({ id: "${run.runId}" }) again or inspect status; do not resume or launch a replacement while it remains detached.`, [run.runId]);
501
498
  }
502
499
  await waitForWake(pollIntervalMs, wake, deps);
503
500
  }
@@ -531,10 +528,10 @@ async function waitForSessionDetachedForegroundRuns(runs, signal, deps, startedA
531
528
  */
532
529
  export async function waitForSubagents(params, signal, deps) {
533
530
  if (deps.enabled === false) {
534
- return result("bg_wait is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED; returning immediately without blocking background work. Active work keeps going, and you can inspect subagents with subagent({ action: \"status\" }) or rely on completion notifications.");
531
+ return result(`${waitToolName()} is disabled by config.waitTool or PI_SUBAGENT_WAIT_TOOL_ENABLED; returning immediately without blocking background work. Active work keeps going, and you can inspect subagents with subagent({ action: \"status\" }) or rely on completion notifications.`);
535
532
  }
536
533
  if (!deps.state.currentSessionId) {
537
- return result("bg_wait requires an active session identity to scope background work safely.", true);
534
+ return result(`${waitToolName()} requires an active session identity to scope background work safely.`, true);
538
535
  }
539
536
  const now = deps.now ?? Date.now;
540
537
  const pollIntervalMs = Math.max(MIN_POLL_INTERVAL_MS, deps.pollIntervalMs ?? DEFAULT_POLL_INTERVAL_MS);
@@ -588,7 +585,7 @@ export async function waitForSubagents(params, signal, deps) {
588
585
  }
589
586
  if (selected && params.nonBlocking) {
590
587
  if (!deps.subscribe) {
591
- return result("Non-blocking wait subscriptions require a long-lived interactive subagent runtime; this runtime can only use blocking bg_wait calls.", true);
588
+ return result(`Non-blocking wait subscriptions require a long-lived interactive subagent runtime; this runtime can only use blocking ${waitToolName()} calls.`, true);
592
589
  }
593
590
  try {
594
591
  const registration = deps.subscribe({ targetKind: selected.kind, runId: selected.id, requestedId: params.id, timeoutMs });
@@ -663,7 +660,7 @@ export async function waitForSubagents(params, signal, deps) {
663
660
  return result(`Wait aborted after ${formatDuration(now() - startedAt)}. Still active: ${stillActive}.`, true);
664
661
  }
665
662
  if (now() - startedAt >= timeoutMs) {
666
- return windowElapsedResult(`Wait window elapsed after ${formatDuration(timeoutMs)} with ${activeInitialRuns.length} async run(s) and ${activeInitialProviderItems.length} provider item(s) still active: ${stillActive}. The work keeps going; call bg_wait again or inspect subagent status.`, activeInitialRuns.map((run) => run.id), activeInitialProviderItems);
663
+ return windowElapsedResult(`Wait window elapsed after ${formatDuration(timeoutMs)} with ${activeInitialRuns.length} async run(s) and ${activeInitialProviderItems.length} provider item(s) still active: ${stillActive}. The work keeps going; call ${waitToolName()} again or inspect subagent status.`, activeInitialRuns.map((run) => run.id), activeInitialProviderItems);
667
664
  }
668
665
  try {
669
666
  await waitForWake(pollIntervalMs, wake, deps);
@@ -674,7 +671,7 @@ export async function waitForSubagents(params, signal, deps) {
674
671
  providerSnapshot = params.id ? providerSnapshot : backgroundWorkForSession(deps, now());
675
672
  for (const provider of initialProviderNames) {
676
673
  if (!providerSnapshot.providers.includes(provider)) {
677
- return result(`Background-work provider '${provider}' disappeared while bg_wait was tracking its active work; completion cannot be confirmed.`, true);
674
+ return result(`Background-work provider '${provider}' disappeared while ${waitToolName()} was tracking its active work; completion cannot be confirmed.`, true);
678
675
  }
679
676
  }
680
677
  providerActive = providerSnapshot.items;
@@ -713,7 +710,7 @@ export async function waitForSubagents(params, signal, deps) {
713
710
  // Only when watchdog attention alone ended the wait: stopOnAttention: false would have kept blocking.
714
711
  const keepWaitingHint = stopOnAttention && supervisorAttentionHint === ""
715
712
  && (waitForAll || finishedAsyncCount + providerFinishedCount === 0)
716
- ? " These runs are still running and none is waiting on a supervisor reply. To keep waiting through this kind of attention, call bg_wait again with stopOnAttention: false; supervisor requests still end that wait."
713
+ ? ` These runs are still running and none is waiting on a supervisor reply. To keep waiting through this kind of attention, call ${waitToolName()} again with stopOnAttention: false; supervisor requests still end that wait.`
717
714
  : "";
718
715
  const attentionNote = relevantAttention.length > 0
719
716
  ? ` ${relevantAttention.length} run(s) need attention: ${relevantAttention.map((run) => run.id).join(", ")} —${supervisorAttentionHint} inspect with subagent({ action: "status" }) then steer a top-level live async child, resume a paused/completed/failed child, or interrupt explicitly.${keepWaitingHint}`
@@ -745,7 +742,7 @@ export async function waitForSubagents(params, signal, deps) {
745
742
  const finishedCount = finishedAsyncCount + providerFinishedCount;
746
743
  const subject = initialProviderIds.size === 0 ? "run(s)" : "item(s)";
747
744
  const remainder = stillRunning > 0
748
- ? ` ${stillRunning} ${subject} still in flight — call bg_wait again to catch the next one.`
745
+ ? ` ${stillRunning} ${subject} still in flight — call ${waitToolName()} again to catch the next one.`
749
746
  : relevantAttention.length > 0
750
747
  ? " No other work is waitable until attention is handled."
751
748
  : initialProviderIds.size === 0 ? " No runs remain in flight." : " No work remains in flight.";
@@ -4,5 +4,7 @@ export declare const WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV = "PI_SUBAGENT_WAIT_TOOL_D
4
4
  export interface ResolvedWaitToolConfig {
5
5
  enabled: boolean;
6
6
  defaultTimeoutMs?: number;
7
+ /** Set only when it differs from bg_wait, so default launch configs are unchanged. */
8
+ name?: string;
7
9
  }
8
10
  export declare function resolveWaitToolConfig(config?: WaitToolConfig, env?: Record<string, string | undefined>): ResolvedWaitToolConfig;
@@ -1,5 +1,9 @@
1
+ import { DEFAULT_WAIT_TOOL_NAME } from "../../shared/wait-tool-name.js";
1
2
  export const WAIT_TOOL_ENABLED_ENV = "PI_SUBAGENT_WAIT_TOOL_ENABLED";
2
3
  export const WAIT_TOOL_DEFAULT_TIMEOUT_MS_ENV = "PI_SUBAGENT_WAIT_TOOL_DEFAULT_TIMEOUT_MS";
4
+ const WAIT_TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_]{0,63}$/;
5
+ // Tools pi-subagents itself registers; a wait tool under one of these names would collide with it.
6
+ const RESERVED_TOOL_NAMES = new Set(["subagent", "subagents_enable", "subagent_supervisor", "contact_supervisor", "intercom", "structured_output", "subagent_launch", "subagent_command", "watchdog_diff", "watchdog_ask", "watchdog_warn", "watchdog_permission_decision"]);
3
7
  const TRUE_VALUES = new Set(["1", "true", "yes", "on", "enabled"]);
4
8
  const FALSE_VALUES = new Set(["0", "false", "no", "off", "disabled"]);
5
9
  function environmentValue(value) {
@@ -26,15 +30,24 @@ function configuredValue(config) {
26
30
  if (typeof config === "boolean")
27
31
  return { enabled: config };
28
32
  if (!config || typeof config !== "object" || Array.isArray(config)) {
29
- throw new Error("config.waitTool must be a boolean or an object with optional enabled and defaultTimeoutMs values.");
33
+ throw new Error("config.waitTool must be a boolean or an object with optional enabled, defaultTimeoutMs and name values.");
30
34
  }
31
- const { enabled, defaultTimeoutMs } = config;
35
+ const { enabled, defaultTimeoutMs, name } = config;
32
36
  if (enabled !== undefined && typeof enabled !== "boolean")
33
37
  throw new Error("config.waitTool.enabled must be a boolean.");
34
38
  if (defaultTimeoutMs !== undefined && (!Number.isInteger(defaultTimeoutMs) || defaultTimeoutMs < 1)) {
35
39
  throw new Error("config.waitTool.defaultTimeoutMs must be a positive integer.");
36
40
  }
37
- return { enabled, ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs: defaultTimeoutMs } : {}) };
41
+ if (name !== undefined && (typeof name !== "string" || !WAIT_TOOL_NAME_PATTERN.test(name))) {
42
+ throw new Error("config.waitTool.name must start with a letter and contain only letters, digits and underscores (at most 64 characters).");
43
+ }
44
+ if (typeof name === "string" && RESERVED_TOOL_NAMES.has(name))
45
+ throw new Error(`config.waitTool.name "${name}" is already a pi-subagents tool.`);
46
+ return {
47
+ enabled,
48
+ ...(defaultTimeoutMs !== undefined ? { defaultTimeoutMs: defaultTimeoutMs } : {}),
49
+ ...(name !== undefined && name !== DEFAULT_WAIT_TOOL_NAME ? { name } : {}),
50
+ };
38
51
  }
39
52
  export function resolveWaitToolConfig(config, env = process.env) {
40
53
  const configured = configuredValue(config);
@@ -42,5 +55,6 @@ export function resolveWaitToolConfig(config, env = process.env) {
42
55
  return {
43
56
  enabled: environmentValue(env[WAIT_TOOL_ENABLED_ENV]) ?? configured.enabled ?? true,
44
57
  ...(envDefaultTimeoutMs ?? configured.defaultTimeoutMs !== undefined ? { defaultTimeoutMs: envDefaultTimeoutMs ?? configured.defaultTimeoutMs } : {}),
58
+ ...(configured.name ? { name: configured.name } : {}),
45
59
  };
46
60
  }
@@ -1,12 +1,16 @@
1
1
  import * as fs from "node:fs";
2
2
  import * as path from "node:path";
3
- import { randomUUID } from "node:crypto";
3
+ import { createHash, randomUUID } from "node:crypto";
4
4
  import { listAsyncRuns } from "./async-status.js";
5
5
  import { formatResumeFirstFailedRunDetail } from "./resume-guidance.js";
6
6
  import { readCompletionReplay } from "./completion-replay.js";
7
7
  import { writeAtomicJson } from "../../shared/atomic-json.js";
8
8
  import { COMPLETION_ACTION, STATUS_ACTION } from "../../shared/parent-wake.js";
9
9
  import { DIRS, INTERCOM_DETACH_REQUEST_EVENT, SUBAGENT_ASYNC_COMPLETE_EVENT, SUBAGENT_CONTROL_EVENT, SUBAGENT_CONTROL_INTERCOM_EVENT, SUBAGENT_FOREGROUND_COMPLETE_EVENT, SUBAGENT_RESULT_INTERCOM_EVENT, } from "../../shared/types.js";
10
+ import { currentBootId, currentRecordedPid } from "./boot-id.js";
11
+ import { currentPidNamespaceScope } from "./pid-namespace.js";
12
+ import { checkRecordedPidLiveness, isRecordedPid } from "./stale-run-reconciler.js";
13
+ import { createClaimFile } from "../../workflows/workflow-resume-claim.js";
10
14
  const SUBSCRIPTION_VERSION = 1;
11
15
  // Outcomes that report no saved results, so the notice points the parent at the run status instead.
12
16
  const STATUS_OUTCOMES = new Set(["timed out", "could not be reconciled", "needs attention", "reconciliation failed"]);
@@ -36,6 +40,8 @@ function parseRecord(value) {
36
40
  || typeof record.token !== "string"
37
41
  || !/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(record.token)
38
42
  || typeof record.sessionId !== "string"
43
+ || (record.completionOwnerId !== undefined && typeof record.completionOwnerId !== "string")
44
+ || (record.completionOwnerProcess !== undefined && !isRecordedPid(record.completionOwnerProcess))
39
45
  || (record.targetKind !== "async" && record.targetKind !== "foreground")
40
46
  || typeof record.runId !== "string"
41
47
  || typeof record.requestedId !== "string"
@@ -50,6 +56,40 @@ function needsAttention(run) {
50
56
  function subscriptionFile(dir, token) {
51
57
  return path.join(dir, `${token}.json`);
52
58
  }
59
+ /**
60
+ * Takeover claims are `<token>.claim-<owner hash>.<generation>`, not `.json`, so record scans skip them.
61
+ * Each generation is created exclusively, so one process takes over from a dead owner per generation;
62
+ * a dead claimant's generation is superseded by the next one.
63
+ */
64
+ function claimPrefix(token, replacedOwnerId) {
65
+ return `${token}.claim-${createHash("sha256").update(replacedOwnerId).digest("hex").slice(0, 16)}.`;
66
+ }
67
+ function latestClaimGeneration(files, prefix) {
68
+ let latest = 0;
69
+ for (const file of files) {
70
+ const generation = file.startsWith(prefix) ? file.slice(prefix.length) : "";
71
+ // Exact digits only: leftover `<claim>.<pid>.<uuid>.tmp` files from a crashed create are not generations.
72
+ if (/^[1-9][0-9]*$/.test(generation))
73
+ latest = Math.max(latest, Number(generation));
74
+ }
75
+ return latest;
76
+ }
77
+ /**
78
+ * Call only after the record file is gone, so a late claimer that wins a freed claim finds no record to bring back.
79
+ * Never throws: a leftover claim cannot bring a removed record back.
80
+ */
81
+ function removeClaimFiles(dir, token) {
82
+ try {
83
+ for (const file of fs.readdirSync(dir)) {
84
+ if (file.startsWith(`${token}.claim-`))
85
+ fs.rmSync(path.join(dir, file), { force: true });
86
+ }
87
+ }
88
+ catch (error) {
89
+ if (!isNotFound(error))
90
+ console.error(`Failed to remove claims of wait subscription '${token}':`, error);
91
+ }
92
+ }
53
93
  export function formatWaitSubscriptions(state, now = Date.now()) {
54
94
  const subscriptions = [...(state.waitSubscriptions?.values() ?? [])].sort((left, right) => left.createdAt - right.createdAt);
55
95
  if (subscriptions.length === 0)
@@ -71,6 +111,64 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
71
111
  let disposed = false;
72
112
  let interval;
73
113
  let lastForeignSweepAt = 0;
114
+ const readRecordFile = (filePath) => {
115
+ try {
116
+ return parseRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
117
+ }
118
+ catch (error) {
119
+ if (isNotFound(error))
120
+ return undefined;
121
+ throw error;
122
+ }
123
+ };
124
+ const isDead = (recorded) => recorded !== undefined && checkRecordedPidLiveness(recorded, {
125
+ observedScope: currentPidNamespaceScope(),
126
+ observedBootId: currentBootId(),
127
+ kill: options.kill,
128
+ }) === "dead";
129
+ const latestClaimantHolds = (claimPath) => {
130
+ let body;
131
+ try {
132
+ body = JSON.parse(fs.readFileSync(claimPath, "utf-8"));
133
+ }
134
+ catch (error) {
135
+ // Claims are created whole, so a body that does not parse is damage; a claim that cannot be read counts as held.
136
+ return !(error instanceof SyntaxError);
137
+ }
138
+ const claimant = body?.process;
139
+ return isRecordedPid(claimant) && !isDead(claimant);
140
+ };
141
+ // Two Pi processes can share one session. The arming process owns the wake while it lives;
142
+ // after it dies, the next process to open the session claims the record and becomes its owner.
143
+ const claimRecord = (filePath, record) => {
144
+ if (!record.completionOwnerId || record.completionOwnerId === state.completionOwnerId)
145
+ return record;
146
+ if (!isDead(record.completionOwnerProcess))
147
+ return undefined;
148
+ if (!state.completionOwnerId)
149
+ return record;
150
+ const prefix = claimPrefix(record.token, record.completionOwnerId);
151
+ const latest = latestClaimGeneration(fs.readdirSync(subscriptionsDir), prefix);
152
+ if (latest > 0 && latestClaimantHolds(path.join(subscriptionsDir, `${prefix}${latest}`)))
153
+ return undefined;
154
+ const claimPath = path.join(subscriptionsDir, `${prefix}${latest + 1}`);
155
+ if (!createClaimFile(claimPath, { ownerId: state.completionOwnerId, process: currentRecordedPid() }))
156
+ return undefined;
157
+ try {
158
+ // The record may have been settled (and its claims removed) after this process first read it.
159
+ if (readRecordFile(filePath)?.completionOwnerId !== record.completionOwnerId) {
160
+ fs.rmSync(claimPath, { force: true });
161
+ return undefined;
162
+ }
163
+ const claimed = { ...record, completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() };
164
+ writeAtomicJson(filePath, claimed);
165
+ return claimed;
166
+ }
167
+ catch (error) {
168
+ fs.rmSync(claimPath, { force: true });
169
+ throw error;
170
+ }
171
+ };
74
172
  /**
75
173
  * Remove expired records armed by another session.
76
174
  *
@@ -109,7 +207,7 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
109
207
  const filePath = path.join(subscriptionsDir, file);
110
208
  let record;
111
209
  try {
112
- record = parseRecord(JSON.parse(fs.readFileSync(filePath, "utf-8")));
210
+ record = readRecordFile(filePath);
113
211
  }
114
212
  catch (error) {
115
213
  console.error(`Ignoring invalid wait subscription '${filePath}':`, error);
@@ -130,27 +228,36 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
130
228
  // Losing this race is harmless: another session may have swept the
131
229
  // same expired record. Anything else is reported and retried on the
132
230
  // next sweep rather than interrupting the caller.
133
- if (!isNotFound(error))
231
+ if (!isNotFound(error)) {
134
232
  console.error(`Failed to remove expired wait subscription '${filePath}':`, error);
233
+ continue;
234
+ }
135
235
  }
236
+ removeClaimFiles(subscriptionsDir, record.token);
136
237
  }
137
238
  };
138
239
  const remove = (record) => {
240
+ let removed = true;
139
241
  try {
140
242
  fs.unlinkSync(subscriptionFile(subscriptionsDir, record.token));
141
243
  }
142
244
  catch (error) {
143
245
  if (!isNotFound(error))
144
246
  throw error;
247
+ removed = false;
145
248
  }
146
249
  subscriptions.delete(record.token);
147
250
  unresolvedRestoredForegroundTokens.delete(record.token);
251
+ removeClaimFiles(subscriptionsDir, record.token);
252
+ return removed;
148
253
  };
149
254
  const settle = (record, outcome, detail, completion) => {
150
255
  if (disposed || state.currentSessionId !== record.sessionId)
151
256
  return;
152
257
  try {
153
- remove(record);
258
+ // Only the process that removes the record may deliver its wake.
259
+ if (!remove(record))
260
+ return;
154
261
  }
155
262
  catch (error) {
156
263
  console.error(`Failed to clear wait subscription '${record.token}'; it remains armed:`, error);
@@ -274,6 +381,7 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
274
381
  version: SUBSCRIPTION_VERSION,
275
382
  token: randomUUID(),
276
383
  sessionId,
384
+ ...(state.completionOwnerId ? { completionOwnerId: state.completionOwnerId, completionOwnerProcess: currentRecordedPid() } : {}),
277
385
  targetKind: input.targetKind,
278
386
  runId: input.runId,
279
387
  requestedId: input.requestedId,
@@ -303,19 +411,23 @@ export function createWaitSubscriptionManager(pi, state, options = {}) {
303
411
  throw error;
304
412
  }
305
413
  for (const file of files) {
414
+ const filePath = path.join(subscriptionsDir, file);
415
+ let record;
306
416
  try {
307
- const record = parseRecord(JSON.parse(fs.readFileSync(path.join(subscriptionsDir, file), "utf-8")));
308
- if (!record || file !== `${record.token}.json`)
417
+ const found = readRecordFile(filePath);
418
+ if (!found || file !== `${found.token}.json` || found.sessionId !== state.currentSessionId)
309
419
  continue;
310
- if (record.sessionId === state.currentSessionId) {
311
- subscriptions.set(record.token, record);
312
- if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId))
313
- unresolvedRestoredForegroundTokens.add(record.token);
314
- }
420
+ record = claimRecord(filePath, found);
315
421
  }
316
422
  catch (error) {
317
- console.error(`Ignoring invalid wait subscription '${path.join(subscriptionsDir, file)}':`, error);
423
+ console.error(`Failed to restore wait subscription '${filePath}':`, error);
424
+ continue;
318
425
  }
426
+ if (!record)
427
+ continue;
428
+ subscriptions.set(record.token, record);
429
+ if (record.targetKind === "foreground" && !state.foregroundRuns?.has(record.runId))
430
+ unresolvedRestoredForegroundTokens.add(record.token);
319
431
  }
320
432
  reconcile();
321
433
  },
@@ -2,8 +2,10 @@ import { SubagentWaitParams } from "../../extension/schemas.js";
2
2
  import { resolveWaitToolConfig, waitForSubagents } from "./subagent-wait.js";
3
3
  import { finalizeToolResult } from "../../extension/tool-result.js";
4
4
  import { registerPinnedTool } from "../../extension/declaration-pinning.js";
5
+ import { waitToolName } from "../../shared/wait-tool-name.js";
5
6
  export function registerWaitTool(pi, state, enabled = resolveWaitToolConfig().enabled, subscriptions, defaultTimeoutMs, child, hasPendingSupervisorRequest) {
6
- const description = `Wait for background work, then return. ${child ? "This child runtime has no native completion notifier: use blocking bg_wait to collect your owned descendants this turn and read their result references; agent_end draining does not synthesize results." : "Ordinary async subagent runs already wake this session natively; use bg_wait only for provider, detached, or other background work without native notification, when a same-turn result is needed."}
7
+ const name = waitToolName();
8
+ const description = `Wait for background work, then return. ${child ? `This child runtime has no native completion notifier: use blocking ${name} to collect your owned descendants this turn and read their result references; agent_end draining does not synthesize results.` : `Ordinary async subagent runs already wake this session natively; use ${name} only for provider, detached, or other background work without native notification, when a same-turn result is needed.`}
7
9
  {} — first active run or provider item to finish or need attention.
8
10
  {all:true} — all work active at call time.
9
11
  {id} — one run; a finished async run returns its result references.
@@ -38,7 +40,7 @@ Timeout or a user message ends the wait without error; work keeps running.${enab
38
40
  }
39
41
  };
40
42
  const primaryTool = {
41
- name: "bg_wait",
43
+ name,
42
44
  label: "Background Wait",
43
45
  description,
44
46
  parameters: SubagentWaitParams,
@@ -11,7 +11,6 @@ export declare function readWorkflowChildRunModel(workflowAsyncDir: string, step
11
11
  model?: string;
12
12
  thinking?: string;
13
13
  } | undefined;
14
- /** Fill a workflow child roster row from the child's own reported model. */
15
14
  export declare function withWorkflowChildRunModel<T extends {
16
15
  runId?: string;
17
16
  model?: string;
@@ -24,7 +24,6 @@ export function readWorkflowChildRunModel(workflowAsyncDir, step) {
24
24
  return undefined;
25
25
  }
26
26
  }
27
- /** Fill a workflow child roster row from the child's own reported model. */
28
27
  export function withWorkflowChildRunModel(workflowAsyncDir, child) {
29
28
  if (child.model && child.thinking)
30
29
  return child;
@@ -12,6 +12,9 @@ function steerTargetsAccepted(result) {
12
12
  const targets = result?.targets ?? [];
13
13
  return targets.length > 0 && targets.every((target) => target.state === "queued" || target.state === "delivered");
14
14
  }
15
+ function steerTargetsRejected(result) {
16
+ return result?.targets.some((target) => target.state === "failed" && target.failureKind === "rejected") === true;
17
+ }
15
18
  export function canQueueRetainedAsyncFollowUp(status, index) {
16
19
  const steps = status.steps ?? [];
17
20
  return status.state === "complete"
@@ -174,8 +177,10 @@ export async function steerAsyncRun(input) {
174
177
  if (input.signal?.aborted) {
175
178
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering pending for async run ${status.runId} (request ${requestId}); caller aborted before recovery.`) }], details: { mode: "management", results: [], steering: result } };
176
179
  }
180
+ const projected = (current) => current?.steering ? actionResultFromSteeringStatus(current.steering, status.runId, requestId) : undefined;
181
+ const rejected = () => new Error(`Child rejected the guidance; continue it with action "resume" and id "${status.runId}".`);
177
182
  const finalStatus = readStatus(asyncDir);
178
- const finalResult = finalStatus?.steering ? actionResultFromSteeringStatus(finalStatus.steering, status.runId, requestId) : undefined;
183
+ const finalResult = projected(finalStatus);
179
184
  const acceptedReply = (accepted) => {
180
185
  const acceptedState = accepted.state === "delivered" ? "delivered" : "queued";
181
186
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering ${acceptedState} for async run ${status.runId} (request ${requestId}).`) }], details: { mode: "management", results: [], steering: accepted } };
@@ -184,7 +189,7 @@ export async function steerAsyncRun(input) {
184
189
  return acceptedReply(finalResult);
185
190
  const running = (finalStatus?.steps ?? status.steps ?? []).filter((step) => step.status === "running");
186
191
  const recoveryAllowed = (input.mode ?? "steer") === "steer" && status.mode === "single" && status.isNested !== true && running.length === 1 && Boolean(finalStatus?.steering) && (input.index === undefined || input.index === 0);
187
- if (recoveryAllowed && finalResult?.state !== "scheduled" && input.recover) {
192
+ if (recoveryAllowed && finalResult?.state !== "scheduled" && !steerTargetsRejected(finalResult) && input.recover) {
188
193
  const appendSteeringNotice = (state, message) => {
189
194
  try {
190
195
  fs.appendFileSync(path.join(asyncDir, "events.jsonl"), `${JSON.stringify({ type: "subagent.steering.notice", ts: Date.now(), runId: status.runId, requestId, state, message, ...(status.sessionId ? { currentSessionId: status.sessionId } : {}) })}\n`);
@@ -194,21 +199,23 @@ export async function steerAsyncRun(input) {
194
199
  }
195
200
  };
196
201
  try {
197
- const latest = readStatus(asyncDir);
198
- const latestResult = latest?.steering ? actionResultFromSteeringStatus(latest.steering, status.runId, requestId) : undefined;
202
+ const latestResult = projected(readStatus(asyncDir));
199
203
  if (latestResult && steerTargetsAccepted(latestResult))
200
204
  return acceptedReply(latestResult);
205
+ if (steerTargetsRejected(latestResult))
206
+ throw rejected();
201
207
  const committedAt = Date.now();
202
208
  input.onBeforeRecoveryClaim?.(requestId, committedAt);
203
209
  const { claimPath, markerPath } = claimSteeringRecovery(asyncDir, { requestId, sourceRunId: status.runId, committedAt });
204
210
  input.onRecoveryCommitted?.(requestId, committedAt);
205
- const preCommitStatus = readStatus(asyncDir);
206
- const preCommitResult = preCommitStatus?.steering ? actionResultFromSteeringStatus(preCommitStatus.steering, status.runId, requestId) : undefined;
211
+ const preCommitResult = projected(readStatus(asyncDir));
207
212
  if (preCommitResult
208
- && preCommitResult.targets.length > 0
209
- && preCommitResult.targets.every((target) => target.state === "queued" || (target.deliveredAt !== undefined && target.deliveredAt <= committedAt))) {
213
+ && (steerTargetsRejected(preCommitResult) || (preCommitResult.targets.length > 0
214
+ && preCommitResult.targets.every((target) => target.state === "queued" || (target.deliveredAt !== undefined && target.deliveredAt <= committedAt))))) {
210
215
  fs.rmSync(markerPath, { force: true });
211
216
  fs.rmSync(claimPath, { force: true });
217
+ if (steerTargetsRejected(preCommitResult))
218
+ throw rejected();
212
219
  return acceptedReply(preCommitResult);
213
220
  }
214
221
  try {
@@ -228,6 +235,10 @@ export async function steerAsyncRun(input) {
228
235
  break;
229
236
  const candidate = readStatus(asyncDir);
230
237
  lastObservedState = candidate?.state;
238
+ if (steerTargetsRejected(projected(candidate))) {
239
+ fs.rmSync(claimPath, { force: true });
240
+ throw rejected();
241
+ }
231
242
  if (candidate?.state === "paused" && candidate.endedAt !== undefined) {
232
243
  paused = candidate;
233
244
  break;
@@ -252,6 +263,10 @@ export async function steerAsyncRun(input) {
252
263
  if (!recoveryTarget.recoveryDescriptor)
253
264
  throw new Error("Source run has no private recovery descriptor; it remains paused and is not safely resumable.");
254
265
  const limits = remainingSteeringRecoveryLimits(recoveryTarget.recoveryDescriptor, paused);
266
+ if (steerTargetsRejected(projected(readStatus(asyncDir)))) {
267
+ fs.rmSync(claimPath, { force: true });
268
+ throw rejected();
269
+ }
255
270
  const revived = await input.recover(limits);
256
271
  if (revived.isError || !revived.details.asyncId)
257
272
  throw new Error(revived.content[0]?.type === "text" ? revived.content[0].text : "Replacement launch failed; source run remains paused.");
@@ -279,7 +294,7 @@ export async function steerAsyncRun(input) {
279
294
  failedStatus.activityState = "needs_attention";
280
295
  writeAtomicJson(path.join(asyncDir, "status.json"), failedStatus);
281
296
  }
282
- const failed = failedStatus?.steering ? actionResultFromSteeringStatus(failedStatus.steering, status.runId, requestId) : undefined;
297
+ const failed = projected(failedStatus);
283
298
  appendSteeringNotice("failed", `Steering failed for run ${status.runId}: ${reason}`);
284
299
  return { content: [{ type: "text", text: steeringReceipt(input.message, `Steering failed for async run ${status.runId} (request ${requestId}): ${reason}`) }], isError: true, details: { mode: "management", results: [], steering: failed ?? { requestId, state: "failed", sourceRunId: status.runId, deliveryStatus: "queued", targets: [{ index: input.index ?? 0, state: "failed", reason }] } } };
285
300
  }
@@ -10,4 +10,4 @@ export declare function stopAsyncRun(state: SubagentState, runId: string | undef
10
10
  asyncDir: string | null;
11
11
  resolvedId?: string;
12
12
  reattachedRunId?: string;
13
- }, childId?: string): AgentToolResult<Details> | null;
13
+ }, childId?: string, drain?: boolean): AgentToolResult<Details> | null;
@@ -130,7 +130,7 @@ export function deliverAsyncRunStop(input) {
130
130
  if (pausedWholeRun)
131
131
  return sealPausedRun(delivery.asyncDir, status, resultsDir);
132
132
  }
133
- export function stopAsyncRun(state, runId, kill, location, childId) {
133
+ export function stopAsyncRun(state, runId, kill, location, childId, drain) {
134
134
  const target = getAsyncStopTarget(state, runId, location);
135
135
  // An async workflow runs in this process: it has no runner to read a stop request, so stop it through its controller.
136
136
  const workflowRunId = target?.asyncId ?? runId;
@@ -139,6 +139,14 @@ export function stopAsyncRun(state, runId, kill, location, childId) {
139
139
  const workflowStatus = workflowAsyncDir ? readStatus(workflowAsyncDir) : undefined;
140
140
  // Controllers outlive a session switch; a workflow owned by another session falls through to the ownership check below.
141
141
  const foreignWorkflow = Boolean(state.currentSessionId && workflowStatus && workflowStatus.sessionId !== state.currentSessionId);
142
+ if (drain) {
143
+ const drained = workflowController && workflowRunId && !foreignWorkflow && !workflowController.signal.aborted ? state.workflowDrains?.get(workflowRunId)?.() : undefined;
144
+ if (!drained)
145
+ 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: [] } };
146
+ if (!drained.ok)
147
+ 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: [] } };
148
+ 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: [] } };
149
+ }
142
150
  if (workflowController && workflowRunId && !foreignWorkflow) {
143
151
  if (workflowStatus)
144
152
  stopStoppableAsyncStatusChildren(workflowStatus, state.workflowChildStops?.get(workflowRunId), "Workflow stopped.");
@@ -1,6 +1,3 @@
1
- /**
2
- * Core execution logic for running subagents
3
- */
4
1
  import { type AgentConfig } from "../../agents/agents.ts";
5
2
  import { type RunSyncOptions, type SingleResult } from "../../shared/types.ts";
6
3
  /**