pi-subagents 0.83.1 → 0.85.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (206) hide show
  1. package/CHANGELOG.md +79 -0
  2. package/bundle/agents.js +3 -3
  3. package/bundle/child-tool-plan.js +2 -2
  4. package/bundle/{chunk-5YIITCPD.js → chunk-3UZ5FVVJ.js} +322 -110
  5. package/bundle/{chunk-F4ASL6OV.js → chunk-7MAE3DJV.js} +1 -1
  6. package/bundle/{chunk-YXFJVCOL.js → chunk-CS4O36CZ.js} +11 -156
  7. package/bundle/{chunk-AHIFYGR3.js → chunk-DV2NCNPR.js} +22 -11
  8. package/bundle/{chunk-G2Z6ZH26.js → chunk-GCSLVFCX.js} +1 -1
  9. package/bundle/{chunk-2S4K53MV.js → chunk-H2NLFTC5.js} +1 -1
  10. package/bundle/{chunk-MABL3FUM.js → chunk-HFTBF7SG.js} +2 -1
  11. package/bundle/chunk-HXRB42AF.js +108 -0
  12. package/bundle/{chunk-UFL7IYCW.js → chunk-IQIWF2VX.js} +190 -1177
  13. package/bundle/{chunk-NPIYWVOD.js → chunk-JNXT3MPI.js} +15 -6
  14. package/bundle/{chunk-C7JMPU5F.js → chunk-JO67XSKD.js} +59 -27
  15. package/bundle/{chunk-UUP372DR.js → chunk-JWYG26RE.js} +223 -93
  16. package/bundle/{chunk-C5P5CHYK.js → chunk-KDMFBYFM.js} +1 -1
  17. package/bundle/{chunk-V2BZYLEP.js → chunk-KEY3UQMQ.js} +7 -2
  18. package/bundle/{chunk-VLFZIN6D.js → chunk-KZ34KQQH.js} +9 -6
  19. package/bundle/{chunk-ZVOAMTUQ.js → chunk-L2ENOFVZ.js} +76 -58
  20. package/bundle/{chunk-RNIZLSEA.js → chunk-LGMILZNE.js} +323 -18
  21. package/bundle/{chunk-UYK5MZWE.js → chunk-LTPH2DXH.js} +247 -153
  22. package/bundle/{chunk-2D52JFLF.js → chunk-N7B2KD74.js} +41 -117
  23. package/bundle/{chunk-IPGZMQXV.js → chunk-O7CPL6H4.js} +183 -28
  24. package/bundle/{chunk-D3JAFGMO.js → chunk-PHZP3KHB.js} +1 -1
  25. package/bundle/{chunk-2DHZTCOL.js → chunk-PVIVCDG2.js} +2 -2
  26. package/bundle/{chunk-LFDBD4PW.js → chunk-QO75KJBT.js} +2 -2
  27. package/bundle/{chunk-SSG7IEP5.js → chunk-RQAUNAWG.js} +2 -2
  28. package/bundle/{chunk-QP5ZWNIS.js → chunk-RV5OGHLO.js} +6 -3
  29. package/bundle/chunk-T5V5BRCL.js +1067 -0
  30. package/bundle/{chunk-LNRJCP2Y.js → chunk-UX4SCV5N.js} +337 -207
  31. package/bundle/{chunk-F5DBXJ2G.js → chunk-WOVMHDES.js} +234 -182
  32. package/bundle/control-channel.js +2 -2
  33. package/bundle/index.js +1 -1
  34. package/bundle/intercom-bridge.js +2 -2
  35. package/bundle/preflight.js +8 -8
  36. package/bundle/project-panes.js +3 -3
  37. package/docs/agents.md +17 -2
  38. package/docs/configuration.md +2 -2
  39. package/docs/extension-api.md +16 -1
  40. package/docs/workflows.md +30 -2
  41. package/package.json +1 -1
  42. package/src/agents/agent-management.js +27 -11
  43. package/src/agents/agent-memory.d.ts +1 -4
  44. package/src/agents/agent-memory.js +1 -4
  45. package/src/agents/agents.d.ts +1 -3
  46. package/src/agents/agents.js +7 -6
  47. package/src/agents/frontmatter.js +1 -8
  48. package/src/agents/global-npm-root.d.ts +1 -0
  49. package/src/agents/global-npm-root.js +11 -3
  50. package/src/agents/skills.d.ts +0 -3
  51. package/src/agents/skills.js +0 -3
  52. package/src/extension/config.js +7 -1
  53. package/src/extension/herdr-pi-bridge.js +10 -2
  54. package/src/extension/index.d.ts +0 -13
  55. package/src/extension/index.js +43 -32
  56. package/src/extension/public-execution.d.ts +1 -0
  57. package/src/extension/public-execution.js +4 -0
  58. package/src/extension/reply-workflow-script.js +24 -4
  59. package/src/extension/schemas.d.ts +8 -3
  60. package/src/extension/schemas.js +5 -3
  61. package/src/extension/session-switch.d.ts +25 -0
  62. package/src/extension/session-switch.js +138 -0
  63. package/src/extension/subagent-guide.d.ts +1 -1
  64. package/src/extension/subagent-guide.js +1 -1
  65. package/src/extension/subagent-launch-tool.d.ts +25 -0
  66. package/src/extension/subagent-launch-tool.js +48 -0
  67. package/src/extension/tool-activation.js +25 -11
  68. package/src/extension/tool-description.js +6 -0
  69. package/src/inspectors/herdr/actions.d.ts +0 -1
  70. package/src/inspectors/herdr/actions.js +0 -1
  71. package/src/inspectors/session-roots-codec.d.ts +0 -1
  72. package/src/inspectors/session-roots-codec.js +0 -1
  73. package/src/inspectors/tmux/actions.d.ts +0 -1
  74. package/src/inspectors/tmux/actions.js +0 -1
  75. package/src/integrations/herdr-status.js +3 -8
  76. package/src/intercom/native-supervisor-channel.js +65 -9
  77. package/src/runs/background/async-execution.d.ts +8 -9
  78. package/src/runs/background/async-execution.js +77 -27
  79. package/src/runs/background/async-job-tracker.js +12 -0
  80. package/src/runs/background/async-resume.d.ts +2 -1
  81. package/src/runs/background/async-resume.js +112 -39
  82. package/src/runs/background/async-retention.d.ts +1 -0
  83. package/src/runs/background/async-retention.js +22 -11
  84. package/src/runs/background/auto-drain.js +2 -1
  85. package/src/runs/background/boot-id.d.ts +1 -3
  86. package/src/runs/background/boot-id.js +1 -3
  87. package/src/runs/background/completion-batcher.d.ts +3 -4
  88. package/src/runs/background/completion-batcher.js +2 -3
  89. package/src/runs/background/control-channel.d.ts +0 -6
  90. package/src/runs/background/control-channel.js +0 -6
  91. package/src/runs/background/fleet-view.js +2 -3
  92. package/src/runs/background/notify.d.ts +0 -2
  93. package/src/runs/background/notify.js +0 -2
  94. package/src/runs/background/result-watcher.d.ts +1 -0
  95. package/src/runs/background/result-watcher.js +59 -29
  96. package/src/runs/background/resume-guidance.js +4 -2
  97. package/src/runs/background/retained-children.js +2 -1
  98. package/src/runs/background/run-child-session.d.ts +2 -1
  99. package/src/runs/background/run-child-session.js +10 -2
  100. package/src/runs/background/run-status.js +4 -3
  101. package/src/runs/background/scheduled-runs.d.ts +3 -1
  102. package/src/runs/background/scheduled-runs.js +13 -16
  103. package/src/runs/background/subagent-runner.d.ts +2 -4
  104. package/src/runs/background/subagent-runner.js +10 -6
  105. package/src/runs/background/subagent-wait.js +12 -15
  106. package/src/runs/background/wait-config.d.ts +2 -0
  107. package/src/runs/background/wait-config.js +17 -3
  108. package/src/runs/background/wait-tool.js +4 -2
  109. package/src/runs/background/workflow-terminal-proof.d.ts +0 -1
  110. package/src/runs/background/workflow-terminal-proof.js +0 -1
  111. package/src/runs/foreground/execution.d.ts +0 -3
  112. package/src/runs/foreground/execution.js +17 -9
  113. package/src/runs/foreground/subagent-executor.d.ts +3 -2
  114. package/src/runs/foreground/subagent-executor.js +112 -26
  115. package/src/runs/shared/child-commands.js +15 -2
  116. package/src/runs/shared/child-hooks.d.ts +1 -7
  117. package/src/runs/shared/child-hooks.js +13 -5
  118. package/src/runs/shared/child-launch.js +6 -2
  119. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  120. package/src/runs/shared/child-session.d.ts +3 -1
  121. package/src/runs/shared/child-session.js +22 -2
  122. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  123. package/src/runs/shared/child-tool-plan.js +0 -1
  124. package/src/runs/shared/claude-code-adapter.js +11 -0
  125. package/src/runs/shared/external-cli-runner.js +26 -6
  126. package/src/runs/shared/herdr-connection.js +2 -1
  127. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  128. package/src/runs/shared/herdr-pane-host.js +17 -1
  129. package/src/runs/shared/herdr-placed-run.js +48 -22
  130. package/src/runs/shared/lane-metadata.d.ts +0 -1
  131. package/src/runs/shared/lane-metadata.js +0 -1
  132. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  133. package/src/runs/shared/model-resolution-diagnostic.d.ts +11 -1
  134. package/src/runs/shared/model-resolution-diagnostic.js +25 -0
  135. package/src/runs/shared/model-resolution.d.ts +2 -2
  136. package/src/runs/shared/model-resolution.js +7 -1
  137. package/src/runs/shared/model-scope.d.ts +1 -5
  138. package/src/runs/shared/model-scope.js +1 -5
  139. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  140. package/src/runs/shared/mutation-evidence.js +52 -7
  141. package/src/runs/shared/nested-events.d.ts +1 -0
  142. package/src/runs/shared/nested-events.js +1 -1
  143. package/src/runs/shared/parallel-utils.d.ts +2 -1
  144. package/src/runs/shared/permissions.js +5 -3
  145. package/src/runs/shared/placement-host.d.ts +5 -1
  146. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  147. package/src/runs/shared/rex-pane-host.js +0 -2
  148. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  149. package/src/runs/shared/run-launch-folder.js +21 -0
  150. package/src/runs/shared/runner-launcher.d.ts +12 -1
  151. package/src/runs/shared/runner-launcher.js +16 -0
  152. package/src/runs/shared/single-output.d.ts +3 -3
  153. package/src/runs/shared/single-output.js +5 -3
  154. package/src/runs/shared/structured-output.d.ts +8 -0
  155. package/src/runs/shared/structured-output.js +30 -2
  156. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  157. package/src/runs/shared/subagent-prompt-runtime.js +4 -2
  158. package/src/runs/shared/tool-timeout.js +2 -1
  159. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  160. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  161. package/src/runs/shared/worktree.d.ts +3 -0
  162. package/src/runs/shared/worktree.js +20 -0
  163. package/src/shared/capacity-resilient-json.d.ts +1 -1
  164. package/src/shared/child-cache-retention.d.ts +1 -2
  165. package/src/shared/child-cache-retention.js +1 -2
  166. package/src/shared/fleet-transcript-reader.d.ts +51 -0
  167. package/src/shared/fleet-transcript-reader.js +333 -0
  168. package/src/shared/formatters.d.ts +0 -18
  169. package/src/shared/formatters.js +0 -18
  170. package/src/shared/session-succession.d.ts +16 -1
  171. package/src/shared/session-succession.js +41 -2
  172. package/src/shared/session-warnings.d.ts +7 -0
  173. package/src/shared/session-warnings.js +26 -0
  174. package/src/shared/settings.d.ts +0 -23
  175. package/src/shared/settings.js +3 -35
  176. package/src/shared/types.d.ts +28 -11
  177. package/src/shared/types.js +0 -12
  178. package/src/shared/utils.d.ts +0 -14
  179. package/src/shared/utils.js +0 -22
  180. package/src/shared/wait-tool-name.d.ts +8 -0
  181. package/src/shared/wait-tool-name.js +13 -0
  182. package/src/slash/slash-commands.js +2 -1
  183. package/src/slash/subagent-cost.d.ts +3 -2
  184. package/src/slash/subagent-cost.js +22 -3
  185. package/src/slash/subagents-admin.js +0 -1
  186. package/src/tui/fleet-status.d.ts +0 -5
  187. package/src/tui/fleet-status.js +4 -24
  188. package/src/tui/fleet-transcript.d.ts +1 -44
  189. package/src/tui/fleet-transcript.js +1 -327
  190. package/src/tui/fleet.js +6 -4
  191. package/src/tui/render.d.ts +0 -9
  192. package/src/tui/render.js +81 -47
  193. package/src/tui/subagent-messages.js +3 -2
  194. package/src/watchdog/register-child.d.ts +2 -3
  195. package/src/watchdog/register-child.js +2 -3
  196. package/src/watchdog/turn-delta.js +2 -1
  197. package/src/workflows/scripted-workflow.js +243 -20
  198. package/src/workflows/workflow-launch-record.d.ts +15 -6
  199. package/src/workflows/workflow-launch-record.js +30 -12
  200. package/src/workflows/workflow-resume-claim.js +2 -2
  201. package/src/workflows/workflow-resume.d.ts +1 -1
  202. package/src/workflows/workflow-resume.js +11 -8
  203. package/src/workflows/workflow-script-worker.d.ts +13 -0
  204. package/src/workflows/workflow-script-worker.js +79 -0
  205. package/workflow-script-process.cjs +36 -0
  206. package/workflow-script-worker.cjs +453 -176
@@ -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
  }
@@ -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;
@@ -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
  /**
@@ -1,6 +1,3 @@
1
- /**
2
- * Core execution logic for running subagents
3
- */
4
1
  import { existsSync, mkdirSync, rmSync, writeFileSync } from "node:fs";
5
2
  import * as path from "node:path";
6
3
  import { discoverAgents, formatUnknownAgentError, unknownAgentDiagnosticContext } from "../../agents/agents.js";
@@ -876,12 +873,25 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
876
873
  toolAttentionTarget.attentionEmitted = true;
877
874
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
878
875
  const toolCallId = toolAttentionTarget.key.startsWith("id:") ? toolAttentionTarget.key.slice(3) : undefined;
876
+ let hasCommandController = false;
877
+ // Runs from the 1 s activity timer, where a throw reaches Pi's uncaughtException handler and exits Pi.
878
+ if (toolCallId)
879
+ try {
880
+ hasCommandController = retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId);
881
+ }
882
+ catch (error) {
883
+ const message = `Could not read the command state of ${agent.name}; its command controls are not offered: ${error instanceof Error ? error.message : String(error)}`;
884
+ if (options.onWarning)
885
+ options.onWarning(message, "child-command-state");
886
+ else
887
+ console.warn(`[pi-subagents] ${message}`);
888
+ }
879
889
  return emitNeedsAttention(now, {
880
890
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1000)}s`,
881
891
  reason: "tool_open_threshold",
882
892
  currentTool: toolAttentionTarget.tool,
883
893
  toolCallId,
884
- hasCommandController: Boolean(toolCallId && retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId)),
894
+ hasCommandController,
885
895
  currentPath: toolAttentionTarget.path,
886
896
  currentToolDurationMs: durationMs,
887
897
  });
@@ -1552,7 +1562,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1552
1562
  durationMs: progress.durationMs,
1553
1563
  };
1554
1564
  const remoteGitChanged = result.nativeMachine?.initialGit && result.nativeMachine.finalGit ? result.nativeMachine.initialGit.head !== result.nativeMachine.finalGit.head || result.nativeMachine.initialGit.dirty !== result.nativeMachine.finalGit.dirty : undefined;
1555
- const mutationEvidence = result.nativeMachine && !isRexLocalMachine(options.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : collectTrackedMutationEvidence(mutationSnapshot, mutationCwd);
1565
+ const mutationEvidence = result.nativeMachine && !isRexLocalMachine(options.machine) ? { source: "tracked-files", trackedOnly: true, changedFiles: [], attemptedMutation: remoteGitChanged === true, ...(remoteGitChanged === undefined ? { unavailable: "Remote Git before/after evidence was incomplete." } : {}) } : await collectTrackedMutationEvidence(mutationSnapshot, mutationCwd);
1556
1566
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1557
1567
  const structuredText = result.structuredOutput === undefined ? undefined : JSON.stringify(result.structuredOutput, null, 2);
1558
1568
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -1652,12 +1662,10 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
1652
1662
  // The captured value is already on the result; the file is observability only.
1653
1663
  }
1654
1664
  }
1655
- /**
1656
- * Run a subagent synchronously (blocking until complete)
1657
- */
1658
1665
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
1659
1666
  const effectiveCwd = options.cwd ?? runtimeCwd;
1660
- const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1667
+ // A placed child's cwd is a directory on its machine; only machine 'local' shares this disk.
1668
+ const cwdError = options.machine && !isRexLocalMachine(options.machine) ? undefined : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1661
1669
  if (cwdError) {
1662
1670
  return redactResultPrompt(withRunContext({
1663
1671
  index: options.index ?? 0,
@@ -16,7 +16,7 @@ import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
16
16
  import { type MissionLaunchBinding } from "../../missions/lifecycle.ts";
17
17
  import { type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
18
18
  import { type PreparedWorkflowResume, type WorkflowResumeRefusalReason } from "../../workflows/workflow-resume.ts";
19
- import { type AcceptanceInput, type AgentContract, type ControlConfig, type Details, type ExtensionConfig, type IntercomBridgeConfig, type JsonSchemaObject, type MaxOutputConfig, type ResolvedControlConfig, type RunFanoutBudgetDescriptor, type SteeringRecoveryDescriptor, type SingleResult, type ToolBudgetConfig, type UsageBudgetConfig, type SubagentState, type ScheduleOrigin } from "../../shared/types.ts";
19
+ import { type AcceptanceInput, type AgentContract, type ControlConfig, type Details, type ExtensionConfig, type IntercomBridgeConfig, type JsonSchemaObject, type MaxOutputConfig, type ResolvedControlConfig, type RunFanoutBudgetDescriptor, type SteeringRecoveryDescriptor, type SingleResult, type ToolBudgetConfig, type UsageBudgetConfig, type SubagentState, type ScheduleOrigin, type RequiredRunnerLauncher } from "../../shared/types.ts";
20
20
  export declare function unknownSubagentActionMessage(action: string, disabled?: DisabledFeatureSurface): string;
21
21
  interface TaskParam {
22
22
  agent: string;
@@ -121,6 +121,7 @@ export interface SubagentParamsLike {
121
121
  machine?: string;
122
122
  /** Internal: the typed cwd when a machine is set, kept as a remote path and never resolved locally. */
123
123
  machineCwd?: string;
124
+ requireLauncher?: RequiredRunnerLauncher;
124
125
  maxOutput?: MaxOutputConfig;
125
126
  artifacts?: boolean;
126
127
  includeProgress?: boolean;
@@ -204,7 +205,7 @@ interface ExecutorDeps {
204
205
  }
205
206
  export declare function removeForegroundControlIfIdle(state: SubagentState, runId: string, trackRetainedNestedRoute?: (rootRunId: string) => void): boolean;
206
207
  export declare function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike;
207
- export declare function readNestedRecoveryDescriptor(asyncDir: string | undefined, runId: string, agent: string): SteeringRecoveryDescriptor | undefined;
208
+ export declare function readNestedRecoveryDescriptor(rootRunId: string, runId: string, agent: string): SteeringRecoveryDescriptor | undefined;
208
209
  export declare function foregroundResultIntercomStatus(result: SingleResult): ReturnType<typeof resolveSubagentResultStatus>;
209
210
  export declare function shouldSuppressRoutineResultIntercom(input: {
210
211
  suppressRoutineResultIntercom?: boolean;