@xzzpig/pi-subagents 0.24.2 → 0.25.1

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 (263) hide show
  1. package/CHANGELOG.md +37 -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-EUPJB4S7.js → chunk-5Z7JAORM.js} +196 -1219
  8. package/bundle/{chunk-LCDJWBVM.js → chunk-66JNFRFS.js} +1 -1
  9. package/bundle/{chunk-ED55MIC2.js → chunk-CGFF4WA3.js} +42 -19
  10. package/bundle/{chunk-TMHVDPYW.js → chunk-DLVPMML3.js} +263 -154
  11. package/bundle/{chunk-RU522D5W.js → chunk-FQPV4O6C.js} +183 -28
  12. package/bundle/chunk-HXRB42AF.js +108 -0
  13. package/bundle/{chunk-355ECEP2.js → chunk-IH7LQVEE.js} +29 -14
  14. package/bundle/{chunk-Z6TFJ6BR.js → chunk-INWSUNI6.js} +1 -1
  15. package/bundle/{chunk-CYY5UMJU.js → chunk-IXCEOEJT.js} +411 -249
  16. package/bundle/{chunk-WW76JRIX.js → chunk-JAXVBXGF.js} +1 -1
  17. package/bundle/{chunk-ICNYIALB.js → chunk-JH5H4CYJ.js} +784 -474
  18. package/bundle/{chunk-224WMDIV.js → chunk-JUYNN63E.js} +350 -123
  19. package/bundle/{chunk-35GII5EF.js → chunk-JWFLPSTP.js} +41 -117
  20. package/bundle/{chunk-XWWUDWUW.js → chunk-KRNBJPZ2.js} +670 -400
  21. package/bundle/{chunk-RB4GELQA.js → chunk-LPJEKHOY.js} +1 -1
  22. package/bundle/chunk-LYKG4FKH.js +523 -0
  23. package/bundle/{chunk-X6LOM3Z4.js → chunk-LZ3HBDTR.js} +161 -78
  24. package/bundle/{chunk-JEA2ZKUA.js → chunk-MMJQMPOK.js} +37 -165
  25. package/bundle/{chunk-FG6SQJAR.js → chunk-OGPOCGWX.js} +24 -6
  26. package/bundle/{chunk-FJWI64H7.js → chunk-RMSABUN3.js} +27 -13
  27. package/bundle/{chunk-H36HBZB2.js → chunk-SJPABBZG.js} +2 -2
  28. package/bundle/{chunk-4UH4WS4G.js → chunk-SNDCIJMK.js} +23 -12
  29. package/bundle/{chunk-O4D5PBVI.js → chunk-TM2K53NX.js} +3 -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-BQ2OAB4Q.js → chunk-WWDUNXSE.js} +67 -30
  34. package/bundle/{chunk-V2KFIGFH.js → chunk-XAC2XNAP.js} +503 -304
  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 +68 -84
  138. package/src/runs/foreground/fork-tool-result-handler.d.ts +60 -0
  139. package/src/runs/foreground/fork-tool-result-handler.js +83 -0
  140. package/src/runs/foreground/prompt-audit.js +1 -0
  141. package/src/runs/foreground/subagent-executor.d.ts +5 -10
  142. package/src/runs/foreground/subagent-executor.js +164 -49
  143. package/src/runs/shared/acceptance.js +69 -26
  144. package/src/runs/shared/async-status-projection.d.ts +2 -0
  145. package/src/runs/shared/async-status-projection.js +10 -0
  146. package/src/runs/shared/child-commands.js +15 -2
  147. package/src/runs/shared/child-hooks.d.ts +1 -7
  148. package/src/runs/shared/child-hooks.js +13 -5
  149. package/src/runs/shared/child-launch.js +6 -2
  150. package/src/runs/shared/child-runtime-config.d.ts +0 -1
  151. package/src/runs/shared/child-session.d.ts +6 -5
  152. package/src/runs/shared/child-session.js +85 -38
  153. package/src/runs/shared/child-tool-plan.d.ts +0 -1
  154. package/src/runs/shared/child-tool-plan.js +0 -1
  155. package/src/runs/shared/claude-code-adapter.js +11 -0
  156. package/src/runs/shared/external-cli-contract.d.ts +49 -0
  157. package/src/runs/shared/external-cli-contract.js +18 -13
  158. package/src/runs/shared/external-cli-runner.js +26 -6
  159. package/src/runs/shared/herdr-connection.js +2 -1
  160. package/src/runs/shared/herdr-pane-host.d.ts +2 -2
  161. package/src/runs/shared/herdr-pane-host.js +17 -1
  162. package/src/runs/shared/herdr-placed-run.js +51 -24
  163. package/src/runs/shared/lane-metadata.d.ts +0 -1
  164. package/src/runs/shared/lane-metadata.js +0 -1
  165. package/src/runs/shared/mcp-config-sources.d.ts +4 -1
  166. package/src/runs/shared/mcp-config-sources.js +1 -1
  167. package/src/runs/shared/mcp-direct-tool-allowlist.d.ts +0 -3
  168. package/src/runs/shared/mcp-direct-tool-allowlist.js +26 -17
  169. package/src/runs/shared/mcp-direct-tool-grant.js +8 -1
  170. package/src/runs/shared/model-resolution-diagnostic.d.ts +0 -1
  171. package/src/runs/shared/model-resolution.d.ts +20 -5
  172. package/src/runs/shared/model-resolution.js +55 -50
  173. package/src/runs/shared/model-scope.d.ts +1 -5
  174. package/src/runs/shared/model-scope.js +1 -5
  175. package/src/runs/shared/mutation-evidence.d.ts +1 -1
  176. package/src/runs/shared/mutation-evidence.js +52 -7
  177. package/src/runs/shared/nested-events.d.ts +1 -0
  178. package/src/runs/shared/nested-events.js +1 -1
  179. package/src/runs/shared/parallel-utils.d.ts +0 -1
  180. package/src/runs/shared/permissions.js +5 -3
  181. package/src/runs/shared/placement-host.d.ts +5 -1
  182. package/src/runs/shared/rex-pane-host.d.ts +0 -1
  183. package/src/runs/shared/rex-pane-host.js +0 -2
  184. package/src/runs/shared/run-launch-folder.d.ts +12 -0
  185. package/src/runs/shared/run-launch-folder.js +21 -0
  186. package/src/runs/shared/runner-launcher.d.ts +12 -1
  187. package/src/runs/shared/runner-launcher.js +16 -0
  188. package/src/runs/shared/single-output.d.ts +3 -3
  189. package/src/runs/shared/single-output.js +5 -3
  190. package/src/runs/shared/structured-output.d.ts +8 -0
  191. package/src/runs/shared/structured-output.js +40 -5
  192. package/src/runs/shared/subagent-prompt-runtime.d.ts +0 -1
  193. package/src/runs/shared/subagent-prompt-runtime.js +18 -4
  194. package/src/runs/shared/supervisor-wait-timer.d.ts +16 -0
  195. package/src/runs/shared/supervisor-wait-timer.js +61 -0
  196. package/src/runs/shared/tool-timeout.js +2 -1
  197. package/src/runs/shared/worktree-cleanup-plan.d.ts +0 -1
  198. package/src/runs/shared/worktree-cleanup-plan.js +0 -1
  199. package/src/runs/shared/worktree.d.ts +3 -0
  200. package/src/runs/shared/worktree.js +20 -0
  201. package/src/shared/artifacts.d.ts +1 -0
  202. package/src/shared/artifacts.js +132 -22
  203. package/src/shared/capacity-resilient-json.d.ts +1 -1
  204. package/src/shared/child-cache-retention.d.ts +1 -2
  205. package/src/shared/child-cache-retention.js +1 -2
  206. package/src/shared/fleet-transcript-reader.d.ts +64 -0
  207. package/src/shared/fleet-transcript-reader.js +376 -0
  208. package/src/shared/formatters.d.ts +0 -18
  209. package/src/shared/formatters.js +0 -18
  210. package/src/shared/pruned-fork.js +2 -2
  211. package/src/shared/reported-progress.d.ts +1 -0
  212. package/src/shared/reported-progress.js +12 -0
  213. package/src/shared/session-succession.d.ts +16 -1
  214. package/src/shared/session-succession.js +41 -2
  215. package/src/shared/session-warnings.d.ts +7 -0
  216. package/src/shared/session-warnings.js +26 -0
  217. package/src/shared/settings.d.ts +0 -23
  218. package/src/shared/settings.js +3 -35
  219. package/src/shared/status-format.d.ts +1 -0
  220. package/src/shared/status-format.js +1 -1
  221. package/src/shared/types.d.ts +108 -59
  222. package/src/shared/types.js +0 -12
  223. package/src/shared/utils.d.ts +3 -15
  224. package/src/shared/utils.js +4 -22
  225. package/src/shared/wait-tool-name.d.ts +8 -0
  226. package/src/shared/wait-tool-name.js +13 -0
  227. package/src/slash/slash-commands.js +2 -1
  228. package/src/slash/subagent-cost.d.ts +3 -2
  229. package/src/slash/subagent-cost.js +22 -3
  230. package/src/slash/subagents-admin.js +0 -1
  231. package/src/tui/fleet-native-transcript.js +1 -1
  232. package/src/tui/fleet-status.d.ts +0 -5
  233. package/src/tui/fleet-status.js +4 -24
  234. package/src/tui/fleet-transcript.d.ts +1 -57
  235. package/src/tui/fleet-transcript.js +4 -370
  236. package/src/tui/fleet.js +6 -4
  237. package/src/tui/render.d.ts +0 -9
  238. package/src/tui/render.js +194 -68
  239. package/src/tui/subagent-messages.js +3 -2
  240. package/src/watchdog/model-selection.js +2 -2
  241. package/src/watchdog/permission-arbiter.js +1 -0
  242. package/src/watchdog/register-child.d.ts +2 -3
  243. package/src/watchdog/register-child.js +2 -3
  244. package/src/watchdog/review.d.ts +0 -5
  245. package/src/watchdog/review.js +4 -3
  246. package/src/watchdog/turn-delta.js +2 -1
  247. package/src/workflows/scripted-workflow.d.ts +2 -0
  248. package/src/workflows/scripted-workflow.js +344 -59
  249. package/src/workflows/structured-workflow-scripts.d.ts +4 -3
  250. package/src/workflows/structured-workflow-scripts.js +32 -11
  251. package/src/workflows/workflow-launch-record.d.ts +15 -6
  252. package/src/workflows/workflow-launch-record.js +30 -12
  253. package/src/workflows/workflow-receipt.js +36 -53
  254. package/src/workflows/workflow-resources.js +4 -4
  255. package/src/workflows/workflow-resume-claim.d.ts +2 -0
  256. package/src/workflows/workflow-resume-claim.js +3 -3
  257. package/src/workflows/workflow-resume.d.ts +1 -1
  258. package/src/workflows/workflow-resume.js +13 -8
  259. package/src/workflows/workflow-script-worker.d.ts +13 -0
  260. package/src/workflows/workflow-script-worker.js +81 -0
  261. package/workflow-script-process.cjs +36 -0
  262. package/workflow-script-worker.cjs +4 -1
  263. package/bundle/chunk-U4ODUYAG.js +0 -235
@@ -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";
@@ -8,11 +5,13 @@ import { alignForkedSessionCwd } from "../../shared/fork-session-cwd.js";
8
5
  import { buildEffectiveSystemPrompt } from "../shared/effective-system-prompt.js";
9
6
  import { ensureArtifactsDir, formatOutputArtifactContent, getArtifactPaths, writeArtifact, writeMetadata, } from "../../shared/artifacts.js";
10
7
  import { createChildTranscriptWriter } from "../../shared/child-transcript.js";
8
+ import { extractReportedProgress } from "../../shared/reported-progress.js";
11
9
  import { DEFAULT_MAX_OUTPUT, INTERCOM_DETACH_REQUEST_EVENT, INTERCOM_DETACH_RESPONSE_EVENT, truncateOutput, } from "../../shared/types.js";
12
10
  import { DEFAULT_CONTROL_CONFIG, buildControlEvent, claimControlNotification, deriveActivityState, shouldEmitOpenToolAttention, shouldNotifyControlEvent, } from "../shared/subagent-control.js";
13
- import { getFinalOutput, findLatestSessionFile, detectSubagentError, hasEmptyTerminalAssistantResponse, formatEmptyTerminalAssistantResponseError, extractToolArgsPreview, assistantMessageError, extractTextFromContent, MAX_STREAMED_RECENT_TOOLS, boundStreamedRecentTools, boundStreamedRecentOutput, boundStreamedToolCalls, } from "../../shared/utils.js";
11
+ import { getFinalOutput, findLatestSessionFile, detectSubagentError, hasEmptyTerminalAssistantResponse, formatEmptyTerminalAssistantResponseError, getTerminalAssistantStopReason, TRUNCATED_RESPONSE_ERROR, extractToolArgsPreview, assistantMessageError, extractTextFromContent, MAX_STREAMED_RECENT_TOOLS, boundStreamedRecentTools, boundStreamedRecentOutput, boundStreamedToolCalls, } from "../../shared/utils.js";
14
12
  import { resolveSkillsWithFallback } from "../../agents/skills.js";
15
13
  import { createPartialOutputTracker, formatPartialOutput } from "../shared/partial-output.js";
14
+ import { createToolResultHandler } from "./fork-tool-result-handler.js";
16
15
  import { effectiveToolTimeoutMs, formatToolTimeoutMessage, resolveToolTimeoutMs, toolTimeoutCallKey, toolTimeoutFromEnv } from "../shared/tool-timeout.js";
17
16
  import { preflightLaunchCwd } from "../shared/launch-cwd.js";
18
17
  import { createJsonlWriter } from "../../shared/jsonl-writer.js";
@@ -33,11 +32,11 @@ import { planAbortRecovery } from "../shared/abort-recovery.js";
33
32
  import { buildTimeoutRecoverySummary, collectTrackedMutationEvidence, snapshotTrackedMutations } from "../shared/mutation-evidence.js";
34
33
  import { captureSingleOutputSnapshot, extractChildWrittenOutput, finalizeSingleOutput, formatSavedOutputReference, hasSingleOutputChangedSinceSnapshot, isSettlementFatalOutputError, resolveSingleOutput, validateFileOnlyOutputMode } from "../shared/single-output.js";
35
34
  import { formatSubagentModelVerificationError, isContextOverflow, resolveModelSelection, } from "../shared/model-resolution.js";
36
- import { createMutatingFailureState, didMutatingToolFail, isMutatingTool, nextLongRunningTrigger, recordMutatingFailure, resetMutatingFailureState, resolveCurrentPath, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/long-running-guard.js";
35
+ import { createMutatingFailureState, isMutatingTool, nextLongRunningTrigger, resolveCurrentPath, } from "../shared/long-running-guard.js";
37
36
  import { acceptanceFailureMessage, buildSkippedAcceptanceLedger, captureStagedIndexBaseline, evaluateAcceptance, formatAcceptancePrompt, resolveEffectiveAcceptance, stripAcceptanceReport, validateAcceptanceInput, typedVerifyOutput } from "../shared/acceptance.js";
38
37
  import { PROMPT_REDACTED } from "../../shared/utils.js";
39
38
  import { attachContractProjections, isAgentContract } from "../shared/agent-contract.js";
40
- import { initialToolBudgetState, isToolBudgetBlockedMessage, toolBudgetState } from "../shared/tool-budget.js";
39
+ import { initialToolBudgetState, toolBudgetState } from "../shared/tool-budget.js";
41
40
  import { resolveWatchdogConfig } from "../../watchdog/settings.js";
42
41
  import { resolveLaunchBinding } from "../../shared/launch-contract.js";
43
42
  import { consumeWorkflowChildPermit } from "../../shared/workflow-child-permit.js";
@@ -48,6 +47,7 @@ import { childSessionFactory, childSessionHasQueuedMessages, projectChildSession
48
47
  import { reconcileAttemptUsage } from "../shared/usage-reconciliation.js";
49
48
  import { clearProviderRetry, observeProviderDiagnostics, snapshotProviderDiagnostics } from "../../shared/provider-diagnostics.js";
50
49
  import { isRexLocalMachine } from "../shared/rex-machine.js";
50
+ import { pauseForSupervisorWait, startPausableTimer } from "../shared/supervisor-wait-timer.js";
51
51
  const artifactOutputByResult = new WeakMap();
52
52
  const acceptanceOutputByResult = new WeakMap();
53
53
  function emptyUsage() {
@@ -210,6 +210,8 @@ function captureStructuredDelegationProgressState(progress, result) {
210
210
  recentOutput: [...progress.recentOutput],
211
211
  recentTools: progress.recentTools.slice(-MAX_STREAMED_RECENT_TOOLS).map(({ tool, args }) => ({ tool, args })),
212
212
  activityState: progress.activityState,
213
+ progressText: progress.progressText,
214
+ progressUpdatedAt: progress.progressUpdatedAt,
213
215
  model: progress.model ?? result.model,
214
216
  toolCount: progress.toolCount,
215
217
  tokens: progress.tokens,
@@ -222,6 +224,8 @@ function structuredDelegationProgressChanged(previous, progress, result) {
222
224
  || previous.currentTool !== progress.currentTool
223
225
  || previous.currentToolArgs !== progress.currentToolArgs
224
226
  || previous.activityState !== progress.activityState
227
+ || previous.progressText !== progress.progressText
228
+ || previous.progressUpdatedAt !== progress.progressUpdatedAt
225
229
  || previous.model !== (progress.model ?? result.model)
226
230
  || previous.toolCount !== progress.toolCount
227
231
  || previous.tokens !== progress.tokens
@@ -248,6 +252,7 @@ function isCompleteUsageCounter(value) {
248
252
  }
249
253
  const STOPPED_BEFORE_COMPLETION_ERROR = "Subagent stopped before completion.";
250
254
  const AFTER_COMPACTION_SETTLEMENT = Symbol("afterCompactionSettlement");
255
+ const REMAINING_TIMEOUT_MS = Symbol("remainingTimeoutMs");
251
256
  async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared) {
252
257
  const effectiveThinking = options.thinkingOverride ?? agent.thinking;
253
258
  const modelArg = applyThinkingSuffix(model, effectiveThinking, options.thinkingOverride !== undefined);
@@ -465,6 +470,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
465
470
  let toolAvailabilityError;
466
471
  let abortedBySignal = options.signal?.aborted === true;
467
472
  let afterCompactionSettlement = false;
473
+ let remainingTimeoutMs;
468
474
  if (options.workflowChildPermitLaunch) {
469
475
  const permitError = consumeWorkflowChildPermit(options.workflowChildPermitLaunch.permit, {
470
476
  workflowRunId: options.workflowChildPermitLaunch.workflowRunId,
@@ -504,7 +510,8 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
504
510
  let timeoutHardFinishTimer;
505
511
  const clearTimeoutTimers = () => {
506
512
  if (timeoutTimer) {
507
- clearTimeout(timeoutTimer);
513
+ remainingTimeoutMs = timeoutTimer.remainingMs();
514
+ timeoutTimer.clear();
508
515
  timeoutTimer = undefined;
509
516
  }
510
517
  if (timeoutHardFinishTimer) {
@@ -747,13 +754,14 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
747
754
  return events;
748
755
  };
749
756
  let activeLongRunningNotified = false;
757
+ // Pi's parallel tool execution emits every tool_execution_start before the first result message,
758
+ // so results are matched to their call by toolCallId; the last-started slot covers events without one.
750
759
  const pendingToolResultsByCallId = new Map();
751
- let pendingToolResult;
760
+ const pendingToolState = { current: undefined };
752
761
  // Pi host versions may represent one tool result as either a dedicated
753
762
  // tool_result_end event or a message_end whose message role is toolResult.
754
763
  // Remember correlated ids so normalizing both forms cannot duplicate output.
755
764
  const handledToolResultIds = new Set();
756
- const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
757
765
  let activeToolSequence = 0;
758
766
  const activeToolCalls = new Map();
759
767
  const activeToolKeysByName = new Map();
@@ -894,12 +902,25 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
894
902
  toolAttentionTarget.attentionEmitted = true;
895
903
  const durationMs = Math.max(0, now - toolAttentionTarget.startedAt);
896
904
  const toolCallId = toolAttentionTarget.key.startsWith("id:") ? toolAttentionTarget.key.slice(3) : undefined;
905
+ let hasCommandController = false;
906
+ // Runs from the 1 s activity timer, where a throw reaches Pi's uncaughtException handler and exits Pi.
907
+ if (toolCallId)
908
+ try {
909
+ hasCommandController = retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId);
910
+ }
911
+ catch (error) {
912
+ const message = `Could not read the command state of ${agent.name}; its command controls are not offered: ${error instanceof Error ? error.message : String(error)}`;
913
+ if (options.onWarning)
914
+ options.onWarning(message, "child-command-state");
915
+ else
916
+ console.warn(`[pi-subagents] ${message}`);
917
+ }
897
918
  return emitNeedsAttention(now, {
898
919
  message: `${agent.name} has had tool '${toolAttentionTarget.tool}' open for ${Math.floor(durationMs / 1000)}s`,
899
920
  reason: "tool_open_threshold",
900
921
  currentTool: toolAttentionTarget.tool,
901
922
  toolCallId,
902
- hasCommandController: Boolean(toolCallId && retainsChildCommand(supervisorChannelDir(options.runId, agent.name, options.index ?? 0), toolCallId)),
923
+ hasCommandController,
903
924
  currentPath: toolAttentionTarget.path,
904
925
  currentToolDurationMs: durationMs,
905
926
  });
@@ -945,61 +966,21 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
945
966
  // deliver the same result either as a tool_result_end event or as a
946
967
  // message_end whose message role is toolResult; both funnel through here
947
968
  // so one result updates budget, output, and mutating-failure state once.
948
- const handleToolResult = (message, completion, now) => {
949
- const rawCallId = completion.toolCallId ?? message.toolCallId;
950
- const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
951
- if (callId) {
952
- if (handledToolResultIds.has(callId))
953
- return;
954
- if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
955
- const oldest = handledToolResultIds.values().next().value;
956
- if (typeof oldest === "string")
957
- handledToolResultIds.delete(oldest);
958
- }
959
- handledToolResultIds.add(callId);
960
- }
961
- result.messages.push(message);
962
- const resultText = extractTextFromContent(message.content);
963
- const keyedSnapshot = callId ? pendingToolResultsByCallId.get(callId) : undefined;
964
- if (callId && keyedSnapshot)
965
- pendingToolResultsByCallId.delete(callId);
966
- const toolSnapshot = keyedSnapshot ?? pendingToolResult;
967
- if (!keyedSnapshot || pendingToolResult === keyedSnapshot)
968
- pendingToolResult = undefined;
969
- // The result event's own tool name is authoritative; the snapshot is a fallback.
970
- const resultToolName = completion.toolName ?? message.toolName;
971
- const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0
972
- ? resultToolName
973
- : undefined) ?? toolSnapshot?.tool;
974
- const budgetBlocked = Boolean(options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool));
975
- if (options.toolBudget && budgetBlocked) {
976
- result.toolBudgetBlocked = true;
977
- result.toolBudget = toolBudgetState(options.toolBudget, Math.max(progress.toolCount, options.toolBudget.hard + 1), blockedTool);
978
- }
979
- appendRecentOutput(progress, resultText.split("\n").slice(-10));
980
- if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
981
- recordMutatingFailure(mutatingFailures, {
982
- tool: toolSnapshot.tool,
983
- path: toolSnapshot.path,
984
- error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
985
- ts: now,
986
- }, mutatingFailureWindowMs);
987
- if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
988
- emitNeedsAttention(now, {
989
- message: `${agent.name} needs attention after repeated mutating tool failures`,
990
- reason: "tool_failures",
991
- currentTool: toolSnapshot.tool,
992
- currentPath: toolSnapshot.path,
993
- currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
994
- recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
995
- });
996
- }
997
- }
998
- else if (toolSnapshot?.mutates) {
999
- resetMutatingFailureState(mutatingFailures);
1000
- }
1001
- fireUpdate();
1002
- };
969
+ const handleToolResult = createToolResultHandler({
970
+ result,
971
+ progress,
972
+ options,
973
+ agentName: agent.name,
974
+ handledToolResultIds,
975
+ pendingToolResultsByCallId,
976
+ pendingToolState,
977
+ mutatingFailures,
978
+ mutatingFailureWindowMs,
979
+ controlConfig,
980
+ appendRecentOutput,
981
+ fireUpdate,
982
+ emitNeedsAttention,
983
+ });
1003
984
  const processEvent = (evt) => {
1004
985
  if (lifecycleFinished)
1005
986
  return;
@@ -1087,6 +1068,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1087
1068
  progress.durationMs = now - startTime;
1088
1069
  progress.lastActivityAt = now;
1089
1070
  updateActivityState(now);
1071
+ pauseForSupervisorWait(timeoutTimer, evt);
1090
1072
  if (evt.type === "tool_execution_start") {
1091
1073
  const toolArgs = evt.args && typeof evt.args === "object" && !Array.isArray(evt.args)
1092
1074
  ? evt.args
@@ -1106,9 +1088,9 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1106
1088
  result.toolBudget = toolBudgetState(options.toolBudget, progress.toolCount, result.toolBudget?.blockedTool);
1107
1089
  }
1108
1090
  const mutates = isMutatingTool(evt.toolName, toolArgs, agent.mutationTools);
1109
- pendingToolResult = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now };
1091
+ pendingToolState.current = { tool: evt.toolName ?? "tool", path: activeTool?.path, mutates, startedAt: now, progressText: extractReportedProgress(evt.toolName ?? "", evt.args) };
1110
1092
  if (typeof evt.toolCallId === "string" && evt.toolCallId)
1111
- pendingToolResultsByCallId.set(evt.toolCallId, pendingToolResult);
1093
+ pendingToolResultsByCallId.set(evt.toolCallId, pendingToolState.current);
1112
1094
  fireUpdate();
1113
1095
  }
1114
1096
  if (evt.type === "tool_execution_end") {
@@ -1235,7 +1217,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1235
1217
  activityTimer.unref?.();
1236
1218
  }
1237
1219
  if (attemptTimeout) {
1238
- timeoutTimer = setTimeout(() => {
1220
+ timeoutTimer = startPausableTimer(attemptTimeout.remainingMs, () => {
1239
1221
  if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut)
1240
1222
  return;
1241
1223
  result.timedOut = true;
@@ -1254,8 +1236,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1254
1236
  settle(undefined, true);
1255
1237
  }, 4000);
1256
1238
  timeoutHardFinishTimer.unref?.();
1257
- }, attemptTimeout.remainingMs);
1258
- timeoutTimer.unref?.();
1239
+ });
1259
1240
  }
1260
1241
  let toolTimeoutSequence = 0;
1261
1242
  const activeToolTimeouts = new Map();
@@ -1295,7 +1276,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1295
1276
  const terminateForToolTimeout = (message) => {
1296
1277
  if (sessionSettled || lifecycleFinished || interruptedByControl || result.timedOut)
1297
1278
  return;
1298
- clearTimeout(timeoutTimer);
1279
+ timeoutTimer?.clear();
1299
1280
  result.timedOut = true;
1300
1281
  timeoutCause = message;
1301
1282
  result.error = message;
@@ -1316,10 +1297,6 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1316
1297
  const timeoutForTool = effectiveToolTimeoutMs(event.toolName, options.toolTimeoutMs);
1317
1298
  if (timeoutForTool === undefined)
1318
1299
  return;
1319
- const elapsed = Date.now() - startTime;
1320
- const runRemaining = attemptTimeout ? Math.max(0, attemptTimeout.remainingMs - elapsed) : undefined;
1321
- if (runRemaining !== undefined && timeoutForTool >= runRemaining)
1322
- return;
1323
1300
  const key = toolTimeoutCallKey(event, ++toolTimeoutSequence);
1324
1301
  const toolName = event.toolName;
1325
1302
  const timer = setTimeout(() => {
@@ -1468,14 +1445,14 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1468
1445
  const steer = created.steer.bind(created);
1469
1446
  const followUp = created.followUp.bind(created);
1470
1447
  created.steer = async (text) => {
1448
+ await steer(text);
1471
1449
  if (cleanTerminalAssistantStopReceived || agentSettledReceived)
1472
1450
  queuedDrainHold = true;
1473
- return steer(text);
1474
1451
  };
1475
1452
  created.followUp = async (text) => {
1453
+ await followUp(text);
1476
1454
  if (cleanTerminalAssistantStopReceived || agentSettledReceived)
1477
1455
  queuedDrainHold = true;
1478
- return followUp(text);
1479
1456
  };
1480
1457
  created.detached = detached;
1481
1458
  unsubscribe = created.subscribe((event) => processEvent(event));
@@ -1524,9 +1501,9 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1524
1501
  result.exitCode = exitCode;
1525
1502
  result.providerDiagnostics = clearProviderRetry(result.providerDiagnostics);
1526
1503
  progress.providerDiagnostics = result.providerDiagnostics;
1527
- if (afterCompactionSettlement) {
1504
+ if (afterCompactionSettlement)
1528
1505
  result[AFTER_COMPACTION_SETTLEMENT] = true;
1529
- }
1506
+ result[REMAINING_TIMEOUT_MS] = remainingTimeoutMs;
1530
1507
  if (interruptedByControl) {
1531
1508
  result.exitCode = 0;
1532
1509
  result.interrupted = true;
@@ -1611,6 +1588,10 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1611
1588
  ? `${errInfo.errorType} failed (exit ${errInfo.exitCode}): ${errInfo.details}`
1612
1589
  : `${errInfo.errorType} failed with exit code ${errInfo.exitCode}`;
1613
1590
  }
1591
+ else if (!validatedStructuredOutput && getTerminalAssistantStopReason(messages) === "length") {
1592
+ result.exitCode = 1;
1593
+ result.error = TRUNCATED_RESPONSE_ERROR;
1594
+ }
1614
1595
  }
1615
1596
  progress.status = result.exitCode === 0 ? "completed" : "failed";
1616
1597
  progress.durationMs = Date.now() - startTime;
@@ -1627,7 +1608,7 @@ async function runSingleAttempt(runtimeCwd, agent, task, model, options, shared)
1627
1608
  durationMs: progress.durationMs,
1628
1609
  };
1629
1610
  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;
1630
- 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);
1611
+ 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);
1631
1612
  const acceptanceOutput = getFinalOutput(result.messages ?? []);
1632
1613
  const structuredText = result.structuredOutput === undefined ? undefined : JSON.stringify(result.structuredOutput, null, 2);
1633
1614
  let fullOutput = stripAcceptanceReport(acceptanceOutput);
@@ -1727,12 +1708,10 @@ function writeStructuredOutputArtifacts(runtime, value, acceptanceReport) {
1727
1708
  // The captured value is already on the result; the file is observability only.
1728
1709
  }
1729
1710
  }
1730
- /**
1731
- * Run a subagent synchronously (blocking until complete)
1732
- */
1733
1711
  async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, options) {
1734
1712
  const effectiveCwd = options.cwd ?? runtimeCwd;
1735
- const cwdError = preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1713
+ // A placed child's cwd is a directory on its machine; only machine 'local' shares this disk.
1714
+ const cwdError = options.machine && !isRexLocalMachine(options.machine) ? undefined : preflightLaunchCwd(options.requestedCwd ?? effectiveCwd, effectiveCwd);
1736
1715
  if (cwdError) {
1737
1716
  return redactResultPrompt(withRunContext({
1738
1717
  index: options.index ?? 0,
@@ -1863,6 +1842,7 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
1863
1842
  scope: options.modelScope,
1864
1843
  primaryModelFromParent: options.modelOverrideFromParent,
1865
1844
  origin: options.modelOrigin ?? (options.modelOverrideFromParent ? "inherited" : "configured"),
1845
+ knownProviders: options.knownProviders,
1866
1846
  });
1867
1847
  try {
1868
1848
  const model = applyThinkingSuffix(selectedModel, options.thinkingOverride ?? agent.thinking, options.thinkingOverride !== undefined);
@@ -2011,6 +1991,10 @@ async function runSyncCompletionInner(runtimeCwd, agents, agentName, task, optio
2011
1991
  });
2012
1992
  if (recovery.action === "resume") {
2013
1993
  recoveryPrompt = recovery.prompt;
1994
+ // The retry gets the budget the first attempt left, so that attempt's supervisor waits stay uncounted.
1995
+ const remainingMs = attemptResult[REMAINING_TIMEOUT_MS];
1996
+ if (remainingMs !== undefined)
1997
+ attemptOptions.deadlineAt = Date.now() + remainingMs;
2014
1998
  attemptNotes.push("[abort-recovery] compaction abort after useful progress; resuming the retained child session once on the same model.");
2015
1999
  continue;
2016
2000
  }
@@ -0,0 +1,60 @@
1
+ /**
2
+ * Fork-only tool-result handler for a foreground subagent run.
3
+ *
4
+ * Why this file exists: upstream `execution.ts` has no `handleToolResult`; the
5
+ * fork added ~60 lines of tool-result bookkeeping (budget blocking, mutating
6
+ * failure escalation, supervisor progress publication) inside the run closure.
7
+ * It only reads/writes state the run already owns, so the handler lives here and
8
+ * the upstream run keeps one factory call.
9
+ *
10
+ * `handledToolResultIds` is bounded so a long run cannot grow it without limit;
11
+ * the oldest id is evicted first, which only risks re-processing results the
12
+ * child itself re-sends, never dropping a live one.
13
+ */
14
+ import type { Message } from "@earendil-works/pi-ai";
15
+ import type { AgentProgress, RunSyncOptions, SingleResult } from "../../shared/types.ts";
16
+ import { createMutatingFailureState } from "../shared/long-running-guard.ts";
17
+ import type { ControlEvent } from "../../shared/types.ts";
18
+ export type PendingToolResult = {
19
+ tool: string;
20
+ path?: string;
21
+ mutates: boolean;
22
+ startedAt?: number;
23
+ progressText?: string;
24
+ };
25
+ type MutatingFailureState = ReturnType<typeof createMutatingFailureState>;
26
+ export interface ToolResultHandlerDeps {
27
+ result: SingleResult;
28
+ progress: AgentProgress;
29
+ options: RunSyncOptions;
30
+ /** Name used in the needs-attention message. */
31
+ agentName: string;
32
+ handledToolResultIds: Set<string>;
33
+ pendingToolResultsByCallId: Map<string, PendingToolResult>;
34
+ /** Unkeyed snapshot taken at `tool_call`; the handler consumes it. */
35
+ pendingToolState: {
36
+ current: PendingToolResult | undefined;
37
+ };
38
+ mutatingFailures: MutatingFailureState;
39
+ mutatingFailureWindowMs: number;
40
+ controlConfig: {
41
+ failedToolAttemptsBeforeAttention: number;
42
+ };
43
+ appendRecentOutput(progress: AgentProgress, lines: string[]): void;
44
+ fireUpdate(): void;
45
+ emitNeedsAttention(now: number, input: {
46
+ message?: string;
47
+ reason?: ControlEvent["reason"];
48
+ recentFailureSummary?: string;
49
+ currentTool?: string;
50
+ toolCallId?: string;
51
+ hasCommandController?: boolean;
52
+ currentPath?: string;
53
+ currentToolDurationMs?: number;
54
+ }): boolean;
55
+ }
56
+ export declare function createToolResultHandler(deps: ToolResultHandlerDeps): (message: Message, completion: {
57
+ toolCallId?: unknown;
58
+ toolName?: unknown;
59
+ }, now: number) => void;
60
+ export {};
@@ -0,0 +1,83 @@
1
+ /**
2
+ * Fork-only tool-result handler for a foreground subagent run.
3
+ *
4
+ * Why this file exists: upstream `execution.ts` has no `handleToolResult`; the
5
+ * fork added ~60 lines of tool-result bookkeeping (budget blocking, mutating
6
+ * failure escalation, supervisor progress publication) inside the run closure.
7
+ * It only reads/writes state the run already owns, so the handler lives here and
8
+ * the upstream run keeps one factory call.
9
+ *
10
+ * `handledToolResultIds` is bounded so a long run cannot grow it without limit;
11
+ * the oldest id is evicted first, which only risks re-processing results the
12
+ * child itself re-sends, never dropping a live one.
13
+ */
14
+ import { extractTextFromContent } from "../../shared/utils.js";
15
+ import { didMutatingToolFail, recordMutatingFailure, resetMutatingFailureState, shouldEscalateMutatingFailures, summarizeRecentMutatingFailures, } from "../shared/long-running-guard.js";
16
+ import { isToolBudgetBlockedMessage, toolBudgetState } from "../shared/tool-budget.js";
17
+ const MAX_HANDLED_TOOL_RESULT_IDS = 1024;
18
+ export function createToolResultHandler(deps) {
19
+ const { result, progress, options, agentName, handledToolResultIds, pendingToolResultsByCallId, pendingToolState, mutatingFailures, mutatingFailureWindowMs, controlConfig, appendRecentOutput, fireUpdate, emitNeedsAttention, } = deps;
20
+ return (message, completion, now) => {
21
+ const rawCallId = completion.toolCallId ?? message.toolCallId;
22
+ const callId = typeof rawCallId === "string" && rawCallId.length > 0 ? rawCallId : undefined;
23
+ if (callId) {
24
+ if (handledToolResultIds.has(callId))
25
+ return;
26
+ if (handledToolResultIds.size >= MAX_HANDLED_TOOL_RESULT_IDS) {
27
+ const oldest = handledToolResultIds.values().next().value;
28
+ if (typeof oldest === "string")
29
+ handledToolResultIds.delete(oldest);
30
+ }
31
+ handledToolResultIds.add(callId);
32
+ }
33
+ result.messages.push(message);
34
+ const resultText = extractTextFromContent(message.content);
35
+ const keyedSnapshot = callId ? pendingToolResultsByCallId.get(callId) : undefined;
36
+ if (callId && keyedSnapshot)
37
+ pendingToolResultsByCallId.delete(callId);
38
+ const toolSnapshot = keyedSnapshot ?? pendingToolState.current;
39
+ if (!keyedSnapshot || pendingToolState.current === keyedSnapshot)
40
+ pendingToolState.current = undefined;
41
+ // The result event's own tool name is authoritative; the snapshot is a fallback.
42
+ const resultToolName = completion.toolName ?? message.toolName;
43
+ const blockedTool = (typeof resultToolName === "string" && resultToolName.length > 0
44
+ ? resultToolName
45
+ : undefined) ?? toolSnapshot?.tool;
46
+ const budgetBlocked = Boolean(options.toolBudget && isToolBudgetBlockedMessage(options.toolBudget, resultText, blockedTool));
47
+ if (options.toolBudget && budgetBlocked) {
48
+ result.toolBudgetBlocked = true;
49
+ result.toolBudget = toolBudgetState(options.toolBudget, Math.max(progress.toolCount, options.toolBudget.hard + 1), blockedTool);
50
+ }
51
+ appendRecentOutput(progress, resultText.split("\n").slice(-10));
52
+ // Pi 1.2+: a successful contact_supervisor progress_update call carries
53
+ // its text back through the result message. Publish the matching
54
+ // snapshot's text so the widget shows the latest successful update.
55
+ const messageToolName = message.toolName;
56
+ if (message.isError !== true && messageToolName === toolSnapshot?.tool && toolSnapshot?.progressText) {
57
+ progress.progressText = toolSnapshot.progressText;
58
+ progress.progressUpdatedAt = now;
59
+ }
60
+ if (toolSnapshot?.mutates && !budgetBlocked && message.role === "toolResult" && didMutatingToolFail(message)) {
61
+ recordMutatingFailure(mutatingFailures, {
62
+ tool: toolSnapshot.tool,
63
+ path: toolSnapshot.path,
64
+ error: resultText.split("\n").find((line) => line.trim())?.trim().slice(0, 180) ?? "mutating tool failed",
65
+ ts: now,
66
+ }, mutatingFailureWindowMs);
67
+ if (shouldEscalateMutatingFailures(mutatingFailures, controlConfig.failedToolAttemptsBeforeAttention)) {
68
+ emitNeedsAttention(now, {
69
+ message: `${agentName} needs attention after repeated mutating tool failures`,
70
+ reason: "tool_failures",
71
+ currentTool: toolSnapshot.tool,
72
+ currentPath: toolSnapshot.path,
73
+ currentToolDurationMs: toolSnapshot.startedAt ? Math.max(0, now - toolSnapshot.startedAt) : undefined,
74
+ recentFailureSummary: summarizeRecentMutatingFailures(mutatingFailures),
75
+ });
76
+ }
77
+ }
78
+ else if (toolSnapshot?.mutates) {
79
+ resetMutatingFailureState(mutatingFailures);
80
+ }
81
+ fireUpdate();
82
+ };
83
+ }
@@ -49,6 +49,7 @@ export async function rewritePromptWithGuidance(input) {
49
49
  });
50
50
  const ctxThinking = input.ctx.getThinkingLevel?.();
51
51
  const agent = new Agent({
52
+ sessionId,
52
53
  initialState: {
53
54
  systemPrompt: [
54
55
  "Rewrite one subagent authored task from Prompt Audit context.",
@@ -17,7 +17,7 @@ import type { ChildRuntimeConfig } from "../shared/child-runtime-config.ts";
17
17
  import { type MissionLaunchBinding } from "../../missions/lifecycle.ts";
18
18
  import { type WorkflowSteerOptions, type WorkflowSteerResult } from "../../workflows/scripted-workflow.ts";
19
19
  import { type PreparedWorkflowResume, type WorkflowResumeRefusalReason } from "../../workflows/workflow-resume.ts";
20
- 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";
20
+ 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";
21
21
  export declare function unknownSubagentActionMessage(action: string, disabled?: DisabledFeatureSurface): string;
22
22
  interface TaskParam {
23
23
  agent: string;
@@ -49,6 +49,7 @@ export interface SubagentParamsLike {
49
49
  index?: number;
50
50
  toolCallId?: string;
51
51
  childId?: string;
52
+ drain?: boolean;
52
53
  view?: "fleet" | "transcript";
53
54
  lines?: number;
54
55
  topic?: string;
@@ -59,6 +60,7 @@ export interface SubagentParamsLike {
59
60
  agent?: string;
60
61
  task?: string;
61
62
  capabilities?: boolean;
63
+ search?: string;
62
64
  extensionBindings?: ExtensionBindings;
63
65
  /** Retained async child run id. Valid only on workflow runs.run items. */
64
66
  resume?: string;
@@ -122,6 +124,7 @@ export interface SubagentParamsLike {
122
124
  machine?: string;
123
125
  /** Internal: the typed cwd when a machine is set, kept as a remote path and never resolved locally. */
124
126
  machineCwd?: string;
127
+ requireLauncher?: RequiredRunnerLauncher;
125
128
  maxOutput?: MaxOutputConfig;
126
129
  artifacts?: boolean;
127
130
  includeProgress?: boolean;
@@ -205,7 +208,7 @@ interface ExecutorDeps {
205
208
  }
206
209
  export declare function removeForegroundControlIfIdle(state: SubagentState, runId: string, trackRetainedNestedRoute?: (rootRunId: string) => void): boolean;
207
210
  export declare function promptAuditRedoParams(value: unknown, rewrittenTask: string): SubagentParamsLike;
208
- export declare function readNestedRecoveryDescriptor(asyncDir: string | undefined, runId: string, agent: string): SteeringRecoveryDescriptor | undefined;
211
+ export declare function readNestedRecoveryDescriptor(rootRunId: string, runId: string, agent: string): SteeringRecoveryDescriptor | undefined;
209
212
  export declare function foregroundResultIntercomStatus(result: SingleResult): ReturnType<typeof resolveSubagentResultStatus>;
210
213
  export declare function shouldSuppressRoutineResultIntercom(input: {
211
214
  suppressRoutineResultIntercom?: boolean;
@@ -213,14 +216,6 @@ export declare function shouldSuppressRoutineResultIntercom(input: {
213
216
  }): boolean;
214
217
  export declare const DEFAULT_FOREGROUND_TIMEOUT_MS: number;
215
218
  export { DEFAULT_ASYNC_TIMEOUT_MS };
216
- /**
217
- * Resolve the optional global default runtime deadline from extension config
218
- * (`config.timeoutMs`). Returns undefined for unset or invalid values so callers
219
- * fall back to the built-in defaults. "Invalid" covers non-positive-integer
220
- * values and values above `MAX_TIMER_DELAY_MS`; the latter would overflow the
221
- * Node.js timer and expire the run almost immediately instead of running long.
222
- */
223
- export declare function resolveConfigDefaultTimeoutMs(raw: unknown): number | undefined;
224
219
  export declare function resolveForegroundTimeout(params: SubagentParamsLike, defaultTimeoutMs?: number): {
225
220
  timeoutMs?: number;
226
221
  error?: string;