@narumitw/pi-subagents 2.1.3 → 3.0.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 (314) hide show
  1. package/README.md +181 -1250
  2. package/dist/child-communication-bridge.ts +136 -0
  3. package/dist/child-communication-bridge.ts.map +7 -0
  4. package/dist/chunks/chunk-UKTWUQRM.js +667 -0
  5. package/dist/chunks/chunk-UKTWUQRM.js.map +7 -0
  6. package/dist/index.ts +1448 -1598
  7. package/dist/index.ts.map +4 -4
  8. package/docs/design-principles.md +31 -0
  9. package/docs/ipc-transport-idea.md +103 -0
  10. package/docs/tools.md +109 -0
  11. package/package.json +11 -19
  12. package/src/broker-credentials.ts +71 -0
  13. package/src/child-communication-bridge.ts +153 -0
  14. package/src/child-communication-tools.ts +147 -0
  15. package/src/completion-renderer.ts +60 -0
  16. package/src/index.ts +1 -1
  17. package/src/message-broker.ts +628 -0
  18. package/src/model-output.ts +42 -0
  19. package/src/process.ts +688 -0
  20. package/src/runtime.ts +538 -0
  21. package/src/subagents.ts +33 -34
  22. package/src/tools.ts +416 -0
  23. package/src/types.ts +85 -0
  24. package/src/widget.ts +130 -0
  25. package/dist/chunks/auto-transport-FUUKFDIG.ts +0 -109
  26. package/dist/chunks/auto-transport-FUUKFDIG.ts.map +0 -7
  27. package/dist/chunks/capability-grant-PR72SWWS.ts +0 -19
  28. package/dist/chunks/capability-grant-PR72SWWS.ts.map +0 -7
  29. package/dist/chunks/child-peer-bridge.ts +0 -108
  30. package/dist/chunks/child-peer-bridge.ts.map +0 -7
  31. package/dist/chunks/chunk-2LMJU25E.ts +0 -1641
  32. package/dist/chunks/chunk-2LMJU25E.ts.map +0 -7
  33. package/dist/chunks/chunk-47SK2QYC.ts +0 -56
  34. package/dist/chunks/chunk-47SK2QYC.ts.map +0 -7
  35. package/dist/chunks/chunk-4AQSF7AS.ts +0 -29
  36. package/dist/chunks/chunk-4AQSF7AS.ts.map +0 -7
  37. package/dist/chunks/chunk-5DGRMKNV.ts +0 -126
  38. package/dist/chunks/chunk-5DGRMKNV.ts.map +0 -7
  39. package/dist/chunks/chunk-6H6TBBED.ts +0 -108
  40. package/dist/chunks/chunk-6H6TBBED.ts.map +0 -7
  41. package/dist/chunks/chunk-6KJ34M6S.ts +0 -159
  42. package/dist/chunks/chunk-6KJ34M6S.ts.map +0 -7
  43. package/dist/chunks/chunk-6NSJVPXX.ts +0 -480
  44. package/dist/chunks/chunk-6NSJVPXX.ts.map +0 -7
  45. package/dist/chunks/chunk-7AAJEUSL.ts +0 -238
  46. package/dist/chunks/chunk-7AAJEUSL.ts.map +0 -7
  47. package/dist/chunks/chunk-BFK2Z4ZF.ts +0 -189
  48. package/dist/chunks/chunk-BFK2Z4ZF.ts.map +0 -7
  49. package/dist/chunks/chunk-BOAXY55Y.ts +0 -153
  50. package/dist/chunks/chunk-BOAXY55Y.ts.map +0 -7
  51. package/dist/chunks/chunk-D4CR7T73.ts +0 -353
  52. package/dist/chunks/chunk-D4CR7T73.ts.map +0 -7
  53. package/dist/chunks/chunk-FEVPWRMU.ts +0 -300
  54. package/dist/chunks/chunk-FEVPWRMU.ts.map +0 -7
  55. package/dist/chunks/chunk-G6VZTCFH.ts +0 -70
  56. package/dist/chunks/chunk-G6VZTCFH.ts.map +0 -7
  57. package/dist/chunks/chunk-H3FP6DLR.ts +0 -160
  58. package/dist/chunks/chunk-H3FP6DLR.ts.map +0 -7
  59. package/dist/chunks/chunk-HA36LPCO.ts +0 -130
  60. package/dist/chunks/chunk-HA36LPCO.ts.map +0 -7
  61. package/dist/chunks/chunk-HOP5FXDT.ts +0 -27
  62. package/dist/chunks/chunk-HOP5FXDT.ts.map +0 -7
  63. package/dist/chunks/chunk-IGAMVWFN.ts +0 -139
  64. package/dist/chunks/chunk-IGAMVWFN.ts.map +0 -7
  65. package/dist/chunks/chunk-ILEQ27AL.ts +0 -45
  66. package/dist/chunks/chunk-ILEQ27AL.ts.map +0 -7
  67. package/dist/chunks/chunk-ITVWPNU4.ts +0 -819
  68. package/dist/chunks/chunk-ITVWPNU4.ts.map +0 -7
  69. package/dist/chunks/chunk-IWC32VPY.ts +0 -172
  70. package/dist/chunks/chunk-IWC32VPY.ts.map +0 -7
  71. package/dist/chunks/chunk-JSZIP73U.ts +0 -362
  72. package/dist/chunks/chunk-JSZIP73U.ts.map +0 -7
  73. package/dist/chunks/chunk-JU6LUNLP.ts +0 -380
  74. package/dist/chunks/chunk-JU6LUNLP.ts.map +0 -7
  75. package/dist/chunks/chunk-KMGKCEO4.ts +0 -38
  76. package/dist/chunks/chunk-KMGKCEO4.ts.map +0 -7
  77. package/dist/chunks/chunk-LASD73CM.ts +0 -339
  78. package/dist/chunks/chunk-LASD73CM.ts.map +0 -7
  79. package/dist/chunks/chunk-LEOYDZI3.ts +0 -22
  80. package/dist/chunks/chunk-LEOYDZI3.ts.map +0 -7
  81. package/dist/chunks/chunk-LL4LP2T7.ts +0 -737
  82. package/dist/chunks/chunk-LL4LP2T7.ts.map +0 -7
  83. package/dist/chunks/chunk-N2T5IN4X.ts +0 -18
  84. package/dist/chunks/chunk-N2T5IN4X.ts.map +0 -7
  85. package/dist/chunks/chunk-N7BLVXKK.ts +0 -73
  86. package/dist/chunks/chunk-N7BLVXKK.ts.map +0 -7
  87. package/dist/chunks/chunk-NLT67IZS.ts +0 -322
  88. package/dist/chunks/chunk-NLT67IZS.ts.map +0 -7
  89. package/dist/chunks/chunk-NTRPLF46.ts +0 -63
  90. package/dist/chunks/chunk-NTRPLF46.ts.map +0 -7
  91. package/dist/chunks/chunk-ONDTY4EL.ts +0 -91
  92. package/dist/chunks/chunk-ONDTY4EL.ts.map +0 -7
  93. package/dist/chunks/chunk-OVPHFGKO.ts +0 -1769
  94. package/dist/chunks/chunk-OVPHFGKO.ts.map +0 -7
  95. package/dist/chunks/chunk-P7OH4XMF.ts +0 -60
  96. package/dist/chunks/chunk-P7OH4XMF.ts.map +0 -7
  97. package/dist/chunks/chunk-PBZMBTNJ.ts +0 -422
  98. package/dist/chunks/chunk-PBZMBTNJ.ts.map +0 -7
  99. package/dist/chunks/chunk-PGLSFLYW.ts +0 -52
  100. package/dist/chunks/chunk-PGLSFLYW.ts.map +0 -7
  101. package/dist/chunks/chunk-RRR66UWR.ts +0 -28
  102. package/dist/chunks/chunk-RRR66UWR.ts.map +0 -7
  103. package/dist/chunks/chunk-RSUXZD6S.ts +0 -275
  104. package/dist/chunks/chunk-RSUXZD6S.ts.map +0 -7
  105. package/dist/chunks/chunk-RTCVYIZA.ts +0 -221
  106. package/dist/chunks/chunk-RTCVYIZA.ts.map +0 -7
  107. package/dist/chunks/chunk-RY2AEGMZ.ts +0 -34
  108. package/dist/chunks/chunk-RY2AEGMZ.ts.map +0 -7
  109. package/dist/chunks/chunk-SWGQLFSD.ts +0 -60
  110. package/dist/chunks/chunk-SWGQLFSD.ts.map +0 -7
  111. package/dist/chunks/chunk-TM2R67J3.ts +0 -52
  112. package/dist/chunks/chunk-TM2R67J3.ts.map +0 -7
  113. package/dist/chunks/chunk-TMZRHIIK.ts +0 -497
  114. package/dist/chunks/chunk-TMZRHIIK.ts.map +0 -7
  115. package/dist/chunks/chunk-TZ34IQ3M.ts +0 -59
  116. package/dist/chunks/chunk-TZ34IQ3M.ts.map +0 -7
  117. package/dist/chunks/chunk-UMBPMVJW.ts +0 -22
  118. package/dist/chunks/chunk-UMBPMVJW.ts.map +0 -7
  119. package/dist/chunks/chunk-VDG7LTYE.ts +0 -80
  120. package/dist/chunks/chunk-VDG7LTYE.ts.map +0 -7
  121. package/dist/chunks/chunk-X4NMONPE.ts +0 -73
  122. package/dist/chunks/chunk-X4NMONPE.ts.map +0 -7
  123. package/dist/chunks/chunk-YPJEN6NU.ts +0 -65
  124. package/dist/chunks/chunk-YPJEN6NU.ts.map +0 -7
  125. package/dist/chunks/chunk-YU53SHA7.ts +0 -328
  126. package/dist/chunks/chunk-YU53SHA7.ts.map +0 -7
  127. package/dist/chunks/completion-delivery-RSJU6BXL.ts +0 -17
  128. package/dist/chunks/completion-delivery-RSJU6BXL.ts.map +0 -7
  129. package/dist/chunks/config-status-FKGDECZ3.ts +0 -35
  130. package/dist/chunks/config-status-FKGDECZ3.ts.map +0 -7
  131. package/dist/chunks/config-ui-ABHYNGQ7.ts +0 -1212
  132. package/dist/chunks/config-ui-ABHYNGQ7.ts.map +0 -7
  133. package/dist/chunks/consult-LJU3IQY5.ts +0 -519
  134. package/dist/chunks/consult-LJU3IQY5.ts.map +0 -7
  135. package/dist/chunks/context-QDKLVQXE.ts +0 -11
  136. package/dist/chunks/context-QDKLVQXE.ts.map +0 -7
  137. package/dist/chunks/create-stateful-transport-JWC2EFYL.ts +0 -130
  138. package/dist/chunks/create-stateful-transport-JWC2EFYL.ts.map +0 -7
  139. package/dist/chunks/cwd-policy-NB6XZ5GF.ts +0 -17
  140. package/dist/chunks/cwd-policy-NB6XZ5GF.ts.map +0 -7
  141. package/dist/chunks/delegation-contract-LA56I5DT.ts +0 -24
  142. package/dist/chunks/delegation-contract-LA56I5DT.ts.map +0 -7
  143. package/dist/chunks/discovery-MIFB2U4Y.ts +0 -12
  144. package/dist/chunks/discovery-MIFB2U4Y.ts.map +0 -7
  145. package/dist/chunks/execution-Q2JZLKJA.ts +0 -4037
  146. package/dist/chunks/execution-Q2JZLKJA.ts.map +0 -7
  147. package/dist/chunks/in-process-transport-HJ6TZXC3.ts +0 -39
  148. package/dist/chunks/in-process-transport-HJ6TZXC3.ts.map +0 -7
  149. package/dist/chunks/inspect-UH2TKH6E.ts +0 -634
  150. package/dist/chunks/inspect-UH2TKH6E.ts.map +0 -7
  151. package/dist/chunks/peer-communication-KL36Z6CO.ts +0 -294
  152. package/dist/chunks/peer-communication-KL36Z6CO.ts.map +0 -7
  153. package/dist/chunks/persistence-UY3PY6E5.ts +0 -348
  154. package/dist/chunks/persistence-UY3PY6E5.ts.map +0 -7
  155. package/dist/chunks/registry-BT54L6CY.ts +0 -1445
  156. package/dist/chunks/registry-BT54L6CY.ts.map +0 -7
  157. package/dist/chunks/retained-semantic-state-GM75FZGE.ts +0 -81
  158. package/dist/chunks/retained-semantic-state-GM75FZGE.ts.map +0 -7
  159. package/dist/chunks/rpc-transport-7R7DVCEB.ts +0 -1222
  160. package/dist/chunks/rpc-transport-7R7DVCEB.ts.map +0 -7
  161. package/dist/chunks/runtime-policy-5YELCOVC.ts +0 -15
  162. package/dist/chunks/runtime-policy-5YELCOVC.ts.map +0 -7
  163. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts +0 -19
  164. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts.map +0 -7
  165. package/dist/chunks/spawn-idempotency-BNHOSMZW.ts +0 -13
  166. package/dist/chunks/spawn-idempotency-BNHOSMZW.ts.map +0 -7
  167. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts +0 -15
  168. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts.map +0 -7
  169. package/dist/chunks/subprocess-transport-VHZJRBTW.ts +0 -160
  170. package/dist/chunks/subprocess-transport-VHZJRBTW.ts.map +0 -7
  171. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts +0 -164
  172. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts.map +0 -7
  173. package/dist/chunks/workspace-WDKLN72J.ts +0 -11
  174. package/dist/chunks/workspace-WDKLN72J.ts.map +0 -7
  175. package/docs/async-runtime-protocol.md +0 -84
  176. package/docs/implementation-notes/pi-subagents-capability-matrix.md +0 -62
  177. package/docs/implementation-notes/pi-subagents-current-direction.md +0 -99
  178. package/docs/implementation-notes/pi-subagents-rpc-v1.md +0 -153
  179. package/docs/pi-subagents-diagrams.md +0 -183
  180. package/src/adaptive-scheduler.ts +0 -224
  181. package/src/admission-benchmark.ts +0 -95
  182. package/src/admission-policy.ts +0 -78
  183. package/src/agent-projection.ts +0 -53
  184. package/src/agents/built-ins.ts +0 -71
  185. package/src/agents/catalog.ts +0 -241
  186. package/src/agents/discovery.ts +0 -265
  187. package/src/agents/types.ts +0 -100
  188. package/src/agents.ts +0 -51
  189. package/src/async-subagent-benchmark.ts +0 -532
  190. package/src/auto-transport.ts +0 -121
  191. package/src/blocking-status.ts +0 -63
  192. package/src/cached-module-loader.ts +0 -18
  193. package/src/capabilities.ts +0 -145
  194. package/src/capability-grant.ts +0 -115
  195. package/src/capability-router.ts +0 -107
  196. package/src/child-peer-bridge.ts +0 -124
  197. package/src/child-peer-tools.ts +0 -132
  198. package/src/completion-delivery.ts +0 -409
  199. package/src/completion-render.ts +0 -190
  200. package/src/completion-requirement.ts +0 -479
  201. package/src/completion-routing.ts +0 -24
  202. package/src/config-registration.ts +0 -114
  203. package/src/config-status.ts +0 -217
  204. package/src/config-ui.ts +0 -983
  205. package/src/consult-policy.ts +0 -15
  206. package/src/consult-registration.ts +0 -125
  207. package/src/consult-render.ts +0 -194
  208. package/src/consult-resources.ts +0 -51
  209. package/src/consult-tool.ts +0 -95
  210. package/src/consult.ts +0 -566
  211. package/src/context.ts +0 -126
  212. package/src/create-stateful-transport.ts +0 -157
  213. package/src/cwd-policy.ts +0 -183
  214. package/src/delegation-contract.ts +0 -463
  215. package/src/execution/budget.ts +0 -56
  216. package/src/execution/runtime-policy.ts +0 -19
  217. package/src/execution-plan.ts +0 -322
  218. package/src/execution-ui.ts +0 -259
  219. package/src/execution.ts +0 -1679
  220. package/src/in-process-transport.ts +0 -941
  221. package/src/inspect-registration.ts +0 -64
  222. package/src/inspect-render.ts +0 -334
  223. package/src/inspect-tool.ts +0 -45
  224. package/src/inspect.ts +0 -769
  225. package/src/integration-controller.ts +0 -98
  226. package/src/limits.ts +0 -75
  227. package/src/orchestration-metrics.ts +0 -116
  228. package/src/outcome.ts +0 -61
  229. package/src/panel-child-group.ts +0 -35
  230. package/src/panel-contract.ts +0 -343
  231. package/src/panel-evidence.ts +0 -59
  232. package/src/panel-execution.ts +0 -769
  233. package/src/panel-failure.ts +0 -56
  234. package/src/panel-planning.ts +0 -175
  235. package/src/panel-presets.ts +0 -3
  236. package/src/panel-prompts.ts +0 -132
  237. package/src/panel-reconciliation.ts +0 -57
  238. package/src/panel-render.ts +0 -103
  239. package/src/parallel-limit-ui.ts +0 -113
  240. package/src/params.ts +0 -278
  241. package/src/peer-communication.ts +0 -352
  242. package/src/peer-transport.ts +0 -49
  243. package/src/persistence.ts +0 -522
  244. package/src/pi-args.ts +0 -43
  245. package/src/pi-invocation.ts +0 -168
  246. package/src/process-control.ts +0 -43
  247. package/src/prompt-resources.ts +0 -38
  248. package/src/prompt-source-safety.ts +0 -48
  249. package/src/protocol.ts +0 -76
  250. package/src/registry-types.ts +0 -204
  251. package/src/registry.ts +0 -1698
  252. package/src/render-common.ts +0 -252
  253. package/src/render.ts +0 -704
  254. package/src/result-contract.ts +0 -431
  255. package/src/retained-semantic-state.ts +0 -100
  256. package/src/rpc-timeout-finalization.ts +0 -207
  257. package/src/rpc-transport-metadata.ts +0 -65
  258. package/src/rpc-transport.ts +0 -1035
  259. package/src/rpc-turn-capture.ts +0 -217
  260. package/src/runner-outcome.ts +0 -31
  261. package/src/runner-result.ts +0 -55
  262. package/src/runner-types.ts +0 -102
  263. package/src/runner-usage.ts +0 -48
  264. package/src/runner.ts +0 -866
  265. package/src/safe-text.ts +0 -67
  266. package/src/semantic-snapshot.ts +0 -214
  267. package/src/session-guidance-contract.ts +0 -399
  268. package/src/settings/inspection.ts +0 -302
  269. package/src/settings/schema.ts +0 -195
  270. package/src/settings-reader.ts +0 -215
  271. package/src/settings.ts +0 -452
  272. package/src/spawn-idempotency.ts +0 -68
  273. package/src/stateful-agent-view.ts +0 -85
  274. package/src/stateful-config.ts +0 -13
  275. package/src/stateful-guidance.ts +0 -29
  276. package/src/stateful-lifecycle.ts +0 -74
  277. package/src/stateful-limit-ui.ts +0 -249
  278. package/src/stateful-limits.ts +0 -96
  279. package/src/stateful-prompt.ts +0 -49
  280. package/src/stateful-registration.ts +0 -1320
  281. package/src/stateful-render.ts +0 -318
  282. package/src/stateful-safety.ts +0 -47
  283. package/src/stateful-tool-params.ts +0 -215
  284. package/src/stateful.ts +0 -12
  285. package/src/subagent-details.ts +0 -43
  286. package/src/subagents-extension.ts +0 -355
  287. package/src/subprocess-transport.ts +0 -145
  288. package/src/supervision.ts +0 -104
  289. package/src/task-path.ts +0 -65
  290. package/src/timeout-checkpoint.ts +0 -305
  291. package/src/timeout-finalization.ts +0 -75
  292. package/src/tool-schema-compatibility.ts +0 -73
  293. package/src/transport-types.ts +0 -74
  294. package/src/transport-ui.ts +0 -135
  295. package/src/transport.ts +0 -43
  296. package/src/turn-budget.ts +0 -109
  297. package/src/usage-format.ts +0 -42
  298. package/src/usage-recording-config.ts +0 -13
  299. package/src/usage-recording-store.ts +0 -183
  300. package/src/usage-recording.ts +0 -478
  301. package/src/verification-harness.ts +0 -516
  302. package/src/verification-policy.ts +0 -67
  303. package/src/verification-receipt.ts +0 -275
  304. package/src/verified-execution-benchmark.ts +0 -86
  305. package/src/verified-execution-contract.ts +0 -191
  306. package/src/verified-execution-schema.ts +0 -32
  307. package/src/work-item-ledger.ts +0 -1404
  308. package/src/work-item-persistence.ts +0 -254
  309. package/src/workflow-completion-controller.ts +0 -397
  310. package/src/workflow-planning.ts +0 -172
  311. package/src/workflow-tree-identity.ts +0 -289
  312. package/src/workflow-ui.ts +0 -69
  313. package/src/workflow-verification.ts +0 -296
  314. package/src/workspace.ts +0 -174
package/src/execution.ts DELETED
@@ -1,1679 +0,0 @@
1
- /**
2
- * Blocking execution stays in one module so preflight, confirmation, cancellation generation,
3
- * launch, and settlement retain one ordered lifecycle owner across every mode.
4
- */
5
-
6
- import type { AgentToolResult, AgentToolUpdateCallback } from "@earendil-works/pi-agent-core";
7
- import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
8
- import { AdaptiveScheduler } from "./adaptive-scheduler.js";
9
- import { evaluateDelegationAdmission } from "./admission-policy.js";
10
- import { discoverAgents } from "./agents/discovery.js";
11
- import type {
12
- AgentConfig,
13
- AgentScope,
14
- SubagentSettings,
15
- SubagentThinkingLevel,
16
- } from "./agents/types.js";
17
- import {
18
- chainStatus,
19
- fanInStatus,
20
- parallelStatus,
21
- singleStatus,
22
- startSubagentStatus,
23
- } from "./blocking-status.js";
24
- import { issueCapabilityGrant, revokeCapabilityGrant } from "./capability-grant.js";
25
- import { redactPrivateText } from "./context.js";
26
- import {
27
- assertDelegationTargetAllowed,
28
- type ResolvedSubagentTarget,
29
- resolveSubagentTarget,
30
- targetPolicyAudit,
31
- } from "./cwd-policy.js";
32
- import {
33
- appendDelegationContract,
34
- type DelegationContract,
35
- normalizeDelegationContract,
36
- } from "./delegation-contract.js";
37
- import {
38
- calculateExecutionBudget,
39
- mergeTurnLimits,
40
- resolveConfiguredTimeout,
41
- } from "./execution/budget.js";
42
- import {
43
- assertSubagentDepthAllowed,
44
- resolveDefaultSubagentTimeoutMs,
45
- } from "./execution/runtime-policy.js";
46
- import {
47
- acknowledgeExecutionPlan,
48
- createExecutionPlan,
49
- resolveContractTools,
50
- } from "./execution-plan.js";
51
- import {
52
- DEFAULT_MAX_CONTEXT_BYTES,
53
- MAX_BLOCKING_PARALLEL_CONCURRENCY,
54
- MAX_SUBAGENT_TIMEOUT_MS,
55
- truncateUtf8,
56
- } from "./limits.js";
57
- import { calculateOrchestrationMetrics } from "./orchestration-metrics.js";
58
- import { executePanel, preflightPanelExecution } from "./panel-execution.js";
59
- import { validatePanelRequest } from "./panel-planning.js";
60
- import { hasUsableAggregator, type SubagentParams } from "./params.js";
61
- import { appendResultInstruction, type SubagentResultFormat } from "./result-contract.js";
62
- import {
63
- buildFanInContext,
64
- formatResultFailure,
65
- getResultFinalOutput,
66
- isResultError,
67
- mapWithConcurrencyLimit,
68
- runSingleAgent,
69
- } from "./runner.js";
70
- import type { SingleResult } from "./runner-types.js";
71
- import { safeTerminalLine } from "./safe-text.js";
72
- import {
73
- DEFAULT_DELEGATION_CWD_POLICY,
74
- resolveBlockingMaxParallelTasks,
75
- } from "./settings/inspection.js";
76
- import { readSubagentSettings, resolveSubagentThinkingLevel } from "./settings.js";
77
- import type { OnUpdateCallback, SubagentDetails } from "./subagent-details.js";
78
- import { isRetryableResult, runHedgedAttempt, supervisionDelay } from "./supervision.js";
79
- import { TimeoutProgressJournal, TURN_TERMINATION_VERSION } from "./timeout-checkpoint.js";
80
- import type { TurnLimits } from "./turn-budget.js";
81
- import {
82
- requiresIndependentVerification,
83
- validateWorkflowVerificationGraph,
84
- } from "./verification-policy.js";
85
- import { prepareVerifiedWorkflow } from "./verified-execution-contract.js";
86
- import type { WorkItemLedger } from "./work-item-ledger.js";
87
- import {
88
- createSessionWorkItemPersistence,
89
- type WorkItemPersistence,
90
- } from "./work-item-persistence.js";
91
- import {
92
- WorkflowCompletionController,
93
- workflowCompletionFailureReason,
94
- } from "./workflow-completion-controller.js";
95
- import { createBlockingWorkLedger, resolveWorkflowTasks } from "./workflow-planning.js";
96
- import { captureWorkflowTreeIdentity, sameWorkflowTreeIdentity } from "./workflow-tree-identity.js";
97
- import {
98
- createWorkflowVerificationReceipt,
99
- workflowVerificationInstruction,
100
- } from "./workflow-verification.js";
101
-
102
- export {
103
- assertSubagentDepthAllowed,
104
- FALLBACK_TIMEOUT_MS,
105
- parsePositiveInteger,
106
- resolveDefaultSubagentTimeoutMs,
107
- } from "./execution/runtime-policy.js";
108
-
109
- export async function executeSubagent(
110
- toolCallId: string,
111
- params: SubagentParams,
112
- signal: AbortSignal | undefined,
113
- onUpdate: AgentToolUpdateCallback<SubagentDetails> | undefined,
114
- ctx: ExtensionContext,
115
- settingsOverride?: SubagentSettings,
116
- ): Promise<AgentToolResult<SubagentDetails> & { isError?: boolean }> {
117
- assertSubagentDepthAllowed();
118
- const agentScope: AgentScope = params.agentScope ?? "user";
119
- if ((agentScope === "project" || agentScope === "both") && !ctx.isProjectTrusted()) {
120
- throw new Error("Project-local subagent definitions require a trusted project");
121
- }
122
- const aggregator = hasUsableAggregator(params.aggregator) ? params.aggregator : undefined;
123
- const config = settingsOverride ?? readSubagentSettings();
124
- const maxParallelTasks = resolveBlockingMaxParallelTasks(config);
125
- const discovery = discoverAgents(ctx.cwd, agentScope, config);
126
- const agents = discovery.agents;
127
- let resolvedWorkflowTasks = resolveWorkflowTasks(params, agents);
128
- const verifiedWorkflow = params.workflow?.verifiedExecution
129
- ? prepareVerifiedWorkflow(resolvedWorkflowTasks, params.workflow.verifiedExecution)
130
- : undefined;
131
- if (verifiedWorkflow) {
132
- const verifierAgent = agents.find(
133
- (agent) => agent.name === params.workflow?.verifiedExecution?.verifierAgent,
134
- );
135
- if (!verifierAgent) {
136
- throw new Error(
137
- `Unknown verified execution agent: ${params.workflow?.verifiedExecution?.verifierAgent}`,
138
- );
139
- }
140
- if (
141
- !verifierAgent.capabilityManifest?.verificationRoles.includes("independent-review") ||
142
- !verifierAgent.capabilityManifest.resultFormats.includes("structured-v2")
143
- ) {
144
- throw new Error(
145
- `Verified execution agent ${verifierAgent.name} lacks independent structured-v2 review capability`,
146
- );
147
- }
148
- resolvedWorkflowTasks = verifiedWorkflow.tasks;
149
- }
150
- const confirmProjectAgents = params.confirmProjectAgents ?? true;
151
- const resolveTimeoutMs = (agentName: string, localTimeoutMs?: number) =>
152
- resolveConfiguredTimeout(
153
- agents,
154
- agentName,
155
- localTimeoutMs,
156
- params.timeoutMs,
157
- resolveDefaultSubagentTimeoutMs(),
158
- );
159
- const resolveThinkingLevel = (agentName: string, localThinkingLevel?: SubagentThinkingLevel) =>
160
- resolveSubagentThinkingLevel(agents, agentName, params.thinkingLevel, localThinkingLevel);
161
- let orchestrationDeadline: number | undefined;
162
- const resolveTurnLimits = (local?: TurnLimits): TurnLimits =>
163
- mergeTurnLimits(local, {
164
- idleTimeoutMs: params.idleTimeoutMs,
165
- maxTurns: params.maxTurns,
166
- maxToolCalls: params.maxToolCalls,
167
- });
168
- const resolveExecutionBudget = (agentName: string, localTimeoutMs?: number) =>
169
- calculateExecutionBudget({
170
- requestedTimeoutMs: resolveTimeoutMs(agentName, localTimeoutMs),
171
- orchestrationDeadline,
172
- totalTimeoutMs: params.totalTimeoutMs,
173
- now: Date.now(),
174
- });
175
-
176
- const hasChain = (params.chain?.length ?? 0) > 0;
177
- const hasTasks = (params.tasks?.length ?? 0) > 0;
178
- const hasWorkflow = (params.workflow?.tasks.length ?? 0) > 0;
179
- const hasPanel = params.panel !== undefined;
180
- const hasSingle = Boolean(params.agent && params.task);
181
- const modeCount =
182
- Number(hasChain) +
183
- Number(hasTasks) +
184
- Number(hasWorkflow) +
185
- Number(hasPanel) +
186
- Number(hasSingle);
187
- let workLedger: WorkItemLedger | undefined;
188
- const workflowScheduling: ReturnType<AdaptiveScheduler["decide"]>[] = [];
189
- const verificationTargetIds = new Set<string>();
190
-
191
- const makeDetails =
192
- (mode: "single" | "parallel" | "chain" | "workflow" | "panel") =>
193
- (results: SingleResult[], aggregator?: SingleResult): SubagentDetails => {
194
- const workflow = workLedger?.snapshot();
195
- const metricResults = aggregator ? [...results, aggregator] : results;
196
- return {
197
- mode,
198
- agentScope,
199
- projectAgentsDir: discovery.projectAgentsDir,
200
- results,
201
- aggregator,
202
- workflow,
203
- schedulerDecisions:
204
- workflowScheduling.length > 0 ? workflowScheduling.slice(-64) : undefined,
205
- metrics: calculateOrchestrationMetrics(workflow, metricResults),
206
- };
207
- };
208
- const workflowFailureResult = (
209
- agentName: string,
210
- task: string,
211
- reasonCode: string,
212
- message: string,
213
- thinkingLevel?: SubagentThinkingLevel,
214
- ): SingleResult => ({
215
- agent: agentName,
216
- agentSource: agents.find((agent) => agent.name === agentName)?.source ?? "unknown",
217
- task,
218
- exitCode: 1,
219
- messages: [],
220
- stderr: message,
221
- errorMessage: message,
222
- usage: {
223
- input: 0,
224
- output: 0,
225
- cacheRead: 0,
226
- cacheWrite: 0,
227
- cost: 0,
228
- contextTokens: 0,
229
- turns: 0,
230
- },
231
- thinkingLevel,
232
- finalOutput: "",
233
- outcome: {
234
- status: "failed",
235
- reasonCode,
236
- recoveryActions: ["revalidate"],
237
- retryable: false,
238
- },
239
- });
240
- const exhaustedResult = (
241
- agentName: string,
242
- task: string,
243
- thinkingLevel: SubagentThinkingLevel | undefined,
244
- step?: number,
245
- ): SingleResult => {
246
- const limit = Math.floor(params.totalTimeoutMs as number);
247
- const message = `Subagent orchestration deadline expired after ${limit}ms`;
248
- return {
249
- agent: agentName,
250
- agentSource: agents.find((agent) => agent.name === agentName)?.source ?? "unknown",
251
- task,
252
- exitCode: 124,
253
- messages: [],
254
- stderr: message,
255
- errorMessage: message,
256
- usage: {
257
- input: 0,
258
- output: 0,
259
- cacheRead: 0,
260
- cacheWrite: 0,
261
- cost: 0,
262
- contextTokens: 0,
263
- turns: 0,
264
- },
265
- thinkingLevel,
266
- step,
267
- finalOutput: "",
268
- timedOut: true,
269
- stopReason: "timeout",
270
- termination: {
271
- version: TURN_TERMINATION_VERSION,
272
- reason: "orchestration_timeout",
273
- limit,
274
- checkpoint: new TimeoutProgressJournal().checkpoint(task),
275
- finalization: { attempted: false, status: "skipped", durationMs: 0 },
276
- },
277
- };
278
- };
279
-
280
- if (modeCount !== 1 || (aggregator && !hasTasks)) {
281
- const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
282
- const reason =
283
- modeCount !== 1
284
- ? "Provide exactly one mode."
285
- : "Aggregator is only valid with parallel tasks.";
286
- return {
287
- content: [
288
- {
289
- type: "text",
290
- text: `Invalid parameters. ${reason}\nAvailable agents: ${available}`,
291
- },
292
- ],
293
- details: makeDetails("single")([]),
294
- };
295
- }
296
- if (
297
- (hasWorkflow || hasPanel) &&
298
- (Number.parseInt(process.env.PI_SUBAGENT_DEPTH ?? "0", 10) || 0) > 0
299
- ) {
300
- throw new Error("Explicit workflow and panel recursion is disabled until separately evaluated");
301
- }
302
- if (params.panel) {
303
- validatePanelRequest(params.panel, maxParallelTasks);
304
- for (const agentName of [
305
- ...params.panel.reviewers.map((reviewer) => reviewer.agent),
306
- params.panel.synthesizer.agent,
307
- ]) {
308
- if (!agents.some((agent) => agent.name === agentName)) {
309
- throw new Error(`Unknown panel agent: ${agentName}`);
310
- }
311
- }
312
- }
313
- if (
314
- (hasTasks && (params.tasks?.length ?? 0) > maxParallelTasks) ||
315
- (hasWorkflow && (params.workflow?.tasks.length ?? 0) > maxParallelTasks) ||
316
- (hasPanel && (params.panel?.reviewers.length ?? 0) > maxParallelTasks)
317
- ) {
318
- const count = hasWorkflow
319
- ? (params.workflow?.tasks.length ?? 0)
320
- : hasPanel
321
- ? (params.panel?.reviewers.length ?? 0)
322
- : (params.tasks?.length ?? 0);
323
- throw new Error(`Too many delegated tasks (${count}). Configured max is ${maxParallelTasks}.`);
324
- }
325
-
326
- const nonWorkflowRetryConfigured =
327
- !hasWorkflow &&
328
- Boolean(
329
- params.retryPolicy ||
330
- params.hedgeAfterMs ||
331
- params.tasks?.some((task) => task.retryPolicy || task.hedgeAfterMs) ||
332
- params.chain?.some((task) => task.retryPolicy || task.hedgeAfterMs) ||
333
- aggregator?.retryPolicy ||
334
- aggregator?.hedgeAfterMs,
335
- );
336
- if (nonWorkflowRetryConfigured) {
337
- throw new Error("Retry and hedge policies are supported only by explicit workflow tasks");
338
- }
339
- if (hasWorkflow && params.workflow) {
340
- for (const task of resolvedWorkflowTasks) {
341
- if (task.verifierFor) verificationTargetIds.add(task.verifierFor);
342
- const contract = normalizeDelegationContract(task.contract);
343
- if (params.workflow.honorAdmission) {
344
- const admission = contract?.admission;
345
- const decision = evaluateDelegationAdmission({
346
- contextPressure: admission?.contextPressure ?? "low",
347
- independentWorkItems: admission?.independentWorkItems ?? 1,
348
- coupling: admission?.coupling ?? "dense",
349
- verificationRequired: admission?.verificationRequired ?? false,
350
- verificationAvailable: admission?.verificationAvailable ?? false,
351
- capabilitiesSupported: true,
352
- budgetAllowsChildren: admission?.budgetAllowsChildren ?? false,
353
- generationCurrent: true,
354
- requirementsComplete: admission?.requirementsComplete ?? false,
355
- });
356
- if (
357
- decision.recommendation === "parent-owned-direct" ||
358
- decision.recommendation === "abstain-insufficient-evidence"
359
- ) {
360
- throw new Error(
361
- `Admission declined workflow task ${task.id}: ${decision.reasonCodes.join(", ")}`,
362
- );
363
- }
364
- }
365
- if (
366
- requiresIndependentVerification({
367
- contract,
368
- integrationOwner: task.integrationOwner === true,
369
- requiredCapabilities: task.requiredCapabilities ?? [],
370
- })
371
- ) {
372
- verificationTargetIds.add(task.id);
373
- }
374
- if (!task.retryPolicy && !task.hedgeAfterMs) continue;
375
- const policy = contract?.sideEffectPolicy;
376
- if (
377
- (task.retryPolicy && policy !== "read-only" && policy !== "idempotent") ||
378
- (task.hedgeAfterMs && policy !== "read-only")
379
- ) {
380
- throw new Error(
381
- `Workflow task ${task.id} must declare an idempotent retry or read-only hedge delegation contract`,
382
- );
383
- }
384
- }
385
- validateWorkflowVerificationGraph(
386
- resolvedWorkflowTasks.map((task) => ({
387
- ...task,
388
- resultFormat: task.resultFormat ?? params.resultFormat,
389
- })),
390
- verificationTargetIds,
391
- );
392
- }
393
- workLedger = createBlockingWorkLedger(
394
- params,
395
- resolvedWorkflowTasks,
396
- aggregator,
397
- verifiedWorkflow
398
- ? {
399
- id: verifiedWorkflow.targetTaskId,
400
- maxReworkCycles: verifiedWorkflow.maxReworkCycles,
401
- }
402
- : undefined,
403
- );
404
- let workflowPersistence: WorkItemPersistence | undefined;
405
- if (hasWorkflow && workLedger) {
406
- const owner =
407
- ctx.sessionManager.getSessionId?.() ??
408
- ctx.sessionManager.getSessionFile?.() ??
409
- `ephemeral:${ctx.cwd}`;
410
- workflowPersistence = createSessionWorkItemPersistence(owner, workLedger.workflowId);
411
- }
412
- const persistWorkLedger = async () => {
413
- if (workflowPersistence && workLedger) await workflowPersistence.save(workLedger.snapshot());
414
- };
415
-
416
- const delegationPolicy = config?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY;
417
- const resolveTarget = (cwd: string | undefined): ResolvedSubagentTarget => {
418
- const target = resolveSubagentTarget({
419
- workspace: ctx.cwd,
420
- requestedCwd: cwd,
421
- currentProjectTrusted: ctx.isProjectTrusted(),
422
- });
423
- assertDelegationTargetAllowed(target, delegationPolicy);
424
- return target;
425
- };
426
- const singleTarget = hasSingle ? resolveTarget(params.cwd) : undefined;
427
- const panelTarget = hasPanel ? resolveTarget(undefined) : undefined;
428
- const chainTargets = params.chain?.map((step) => resolveTarget(step.cwd)) ?? [];
429
- const parallelTargets = params.tasks?.map((task) => resolveTarget(task.cwd)) ?? [];
430
- const workflowTargets = resolvedWorkflowTasks.map((task) => resolveTarget(task.cwd));
431
- const aggregatorTarget = aggregator ? resolveTarget(aggregator.cwd) : undefined;
432
- if (params.panel && panelTarget) {
433
- await preflightPanelExecution({
434
- panel: params.panel,
435
- agents,
436
- signal,
437
- target: panelTarget,
438
- resolveThinkingLevel,
439
- resolveTimeoutMs,
440
- });
441
- }
442
- const attachTarget = (result: SingleResult, target: ResolvedSubagentTarget): SingleResult => {
443
- result.target = targetPolicyAudit(target);
444
- return result;
445
- };
446
- type ContractRequest = {
447
- contract?: unknown;
448
- resultFormat?: SubagentResultFormat;
449
- };
450
- const prepareTask = (task: string, local?: ContractRequest) => {
451
- const contracted = appendDelegationContract(task, local?.contract ?? params.contract);
452
- const resultFormat = local?.resultFormat ?? params.resultFormat;
453
- return {
454
- text: appendResultInstruction(contracted.text, resultFormat, DEFAULT_MAX_CONTEXT_BYTES),
455
- contract: contracted.contract,
456
- resultFormat,
457
- };
458
- };
459
- const launchPolicy = (
460
- target: ResolvedSubagentTarget,
461
- prepared: { contract?: DelegationContract; resultFormat?: SubagentResultFormat },
462
- displayTask: string,
463
- agentName: string,
464
- thinkingLevel: SubagentThinkingLevel | undefined,
465
- timeoutMs: number,
466
- taskGeneration = 0,
467
- budget?: NonNullable<ReturnType<typeof resolveExecutionBudget>>,
468
- turnLimits?: TurnLimits,
469
- ) => {
470
- const agent = agents.find((candidate) => candidate.name === agentName);
471
- const effectiveTools = agent ? resolveContractTools(agent.tools, prepared.contract) : undefined;
472
- const executionPlan = agent
473
- ? createExecutionPlan({
474
- contract: prepared.contract,
475
- agent,
476
- effectiveTools,
477
- target: targetPolicyAudit(target),
478
- workspaceMode: "shared",
479
- transport: "subprocess",
480
- resultFormat: prepared.resultFormat ?? "text",
481
- model: agent.model,
482
- thinkingLevel,
483
- timeoutMs,
484
- taskGeneration,
485
- })
486
- : undefined;
487
- if (executionPlan) {
488
- const acknowledgement = acknowledgeExecutionPlan(executionPlan);
489
- if (acknowledgement.status === "rejected") {
490
- throw new Error(`Execution plan rejected: ${JSON.stringify(acknowledgement)}`);
491
- }
492
- }
493
- const capabilityGrant = executionPlan
494
- ? issueCapabilityGrant(executionPlan, Date.now(), Math.max(1, timeoutMs + 60_000))
495
- : undefined;
496
- return {
497
- projectTrust: target.trust.projectTrusted,
498
- turnLimits,
499
- workTimeoutReason: budget?.workTimeoutReason,
500
- workTimeoutReportLimit: budget?.workTimeoutReportLimit,
501
- orchestrationDeadlineAt: budget ? orchestrationDeadline : undefined,
502
- tools: effectiveTools,
503
- contract: prepared.contract,
504
- resultFormat: prepared.resultFormat,
505
- displayTask,
506
- executionPlan,
507
- capabilityGrant,
508
- };
509
- };
510
-
511
- // Build and acknowledge every contracted plan before confirmation or child launch.
512
- if (hasSingle && singleTarget && params.agent && params.task) {
513
- const prepared = prepareTask(params.task, params);
514
- launchPolicy(
515
- singleTarget,
516
- prepared,
517
- params.task,
518
- params.agent,
519
- resolveThinkingLevel(params.agent, params.thinkingLevel),
520
- resolveTimeoutMs(params.agent, params.timeoutMs),
521
- );
522
- }
523
- for (const [index, step] of (params.chain ?? []).entries()) {
524
- const prepared = prepareTask(step.task, step);
525
- launchPolicy(
526
- chainTargets[index],
527
- prepared,
528
- step.task,
529
- step.agent,
530
- resolveThinkingLevel(step.agent, step.thinkingLevel),
531
- resolveTimeoutMs(step.agent, step.timeoutMs),
532
- );
533
- }
534
- for (const [index, task] of (params.tasks ?? []).entries()) {
535
- const prepared = prepareTask(task.task, task);
536
- launchPolicy(
537
- parallelTargets[index],
538
- prepared,
539
- task.task,
540
- task.agent,
541
- resolveThinkingLevel(task.agent, task.thinkingLevel),
542
- resolveTimeoutMs(task.agent, task.timeoutMs),
543
- );
544
- }
545
- for (const [index, task] of resolvedWorkflowTasks.entries()) {
546
- const prepared = prepareTask(task.task, task);
547
- launchPolicy(
548
- workflowTargets[index],
549
- prepared,
550
- task.task,
551
- task.agent,
552
- resolveThinkingLevel(task.agent, task.thinkingLevel),
553
- resolveTimeoutMs(task.agent, task.timeoutMs),
554
- workLedger?.get(task.id)?.taskGeneration ?? 0,
555
- );
556
- }
557
- if (aggregator && aggregatorTarget) {
558
- const prepared = prepareTask(aggregator.task, aggregator);
559
- launchPolicy(
560
- aggregatorTarget,
561
- prepared,
562
- aggregator.task,
563
- aggregator.agent,
564
- resolveThinkingLevel(aggregator.agent, aggregator.thinkingLevel),
565
- resolveTimeoutMs(aggregator.agent, aggregator.timeoutMs),
566
- );
567
- }
568
-
569
- const artifactsFromResult = (result: SingleResult) => {
570
- const structured =
571
- result.structuredResult?.version === "pi-subagents:result:v2"
572
- ? result.structuredResult
573
- : undefined;
574
- return (structured?.artifacts ?? []).map((artifact) => ({
575
- id: artifact.id,
576
- kind: artifact.kind,
577
- version: artifact.version ?? artifact.digest ?? "unversioned",
578
- digest: artifact.digest,
579
- verified: false,
580
- }));
581
- };
582
- const startWorkItem = (id: string, agentName: string) => {
583
- if (workLedger?.get(id)?.state === "ready") {
584
- return workLedger.start(id, `agent:${agentName}`);
585
- }
586
- return workLedger?.get(id);
587
- };
588
- const settleWorkItem = (id: string, result: SingleResult, taskGeneration: number) => {
589
- if (!workLedger) return;
590
- if (workLedger.get(id)?.taskGeneration !== taskGeneration) {
591
- result.outcome = {
592
- status: "stale",
593
- reasonCode: "stale-task-generation",
594
- recoveryActions: ["discard", "replan"],
595
- retryable: false,
596
- };
597
- }
598
- if (result.outcome?.status === "stale") {
599
- workLedger.invalidate(id, result.outcome.reasonCode ?? "stale-result");
600
- return;
601
- }
602
- if (isResultError(result)) {
603
- const state =
604
- result.outcome?.status === "blocked"
605
- ? "blocked"
606
- : result.outcome?.status === "needs-input"
607
- ? "needs-input"
608
- : result.aborted || result.outcome?.status === "interrupted"
609
- ? "interrupted"
610
- : "failed";
611
- workLedger.settle(
612
- id,
613
- state,
614
- result.outcome?.reasonCode ?? result.errorMessage ?? result.stopReason,
615
- );
616
- return;
617
- }
618
- workLedger.complete(id, {
619
- taskGeneration,
620
- executionPlanId: result.executionPlan?.id,
621
- artifacts: artifactsFromResult(result),
622
- });
623
- };
624
-
625
- if (agentScope === "project" || agentScope === "both") {
626
- const requestedAgentNames = new Set<string>();
627
- if (params.chain) for (const step of params.chain) requestedAgentNames.add(step.agent);
628
- if (params.tasks) for (const t of params.tasks) requestedAgentNames.add(t.agent);
629
- for (const task of resolvedWorkflowTasks) requestedAgentNames.add(task.agent);
630
- if (aggregator) requestedAgentNames.add(aggregator.agent);
631
- if (params.panel) {
632
- for (const reviewer of params.panel.reviewers) requestedAgentNames.add(reviewer.agent);
633
- requestedAgentNames.add(params.panel.synthesizer.agent);
634
- }
635
- if (params.agent) requestedAgentNames.add(params.agent);
636
-
637
- const projectAgentsRequested = Array.from(requestedAgentNames)
638
- .map((name) => agents.find((a) => a.name === name))
639
- .filter((a): a is AgentConfig => a?.source === "project");
640
-
641
- if (projectAgentsRequested.length > 0) {
642
- if (!ctx.isProjectTrusted()) {
643
- throw new Error("Project-local subagent definitions require a trusted project");
644
- }
645
- if (confirmProjectAgents && ctx.hasUI) {
646
- const names = projectAgentsRequested
647
- .map((agent) => safeTerminalLine(agent.name, 256))
648
- .join(", ");
649
- const dir = safeTerminalLine(discovery.projectAgentsDir ?? "(unknown)");
650
- const ok = await ctx.ui.confirm(
651
- "Run project-local agents?",
652
- `Agents: ${names}\nSource: ${dir}\n\nProject agents are repo-controlled. Only continue for trusted repositories.`,
653
- );
654
- if (signal?.aborted) {
655
- const error = new Error("Subagent call was aborted during project-agent confirmation");
656
- error.name = "AbortError";
657
- throw error;
658
- }
659
- if (!ok) {
660
- return {
661
- content: [{ type: "text", text: "Canceled: project-local agents not approved." }],
662
- details: makeDetails(
663
- hasChain
664
- ? "chain"
665
- : hasTasks
666
- ? "parallel"
667
- : hasWorkflow
668
- ? "workflow"
669
- : hasPanel
670
- ? "panel"
671
- : "single",
672
- )([]),
673
- };
674
- }
675
- }
676
- }
677
- }
678
-
679
- orchestrationDeadline =
680
- params.totalTimeoutMs === undefined
681
- ? undefined
682
- : Date.now() + Math.floor(params.totalTimeoutMs);
683
- if (params.panel && panelTarget) {
684
- return executePanel({
685
- toolCallId,
686
- params,
687
- panel: params.panel,
688
- signal,
689
- onUpdate,
690
- ctx,
691
- agents,
692
- agentScope,
693
- projectAgentsDir: discovery.projectAgentsDir,
694
- maxParallelTasks,
695
- target: panelTarget,
696
- resolveThinkingLevel,
697
- resolveTimeoutMs,
698
- });
699
- }
700
- if (params.workflow && resolvedWorkflowTasks.length > 0 && workLedger) {
701
- await persistWorkLedger();
702
- const status = startSubagentStatus(
703
- ctx,
704
- toolCallId,
705
- parallelStatus(0, resolvedWorkflowTasks.length, 0),
706
- );
707
- const scheduler = new AdaptiveScheduler();
708
- const taskById = new Map(
709
- resolvedWorkflowTasks.map((task, index) => [task.id, { task, index }]),
710
- );
711
- const resultsById = new Map<string, SingleResult>();
712
- const deadline = orchestrationDeadline;
713
- const cancelWorkflowGeneration = () => {
714
- for (const item of workLedger.snapshot().items) {
715
- if (
716
- item.state === "running" ||
717
- item.state === "awaiting-verification" ||
718
- (item.state === "completed" && item.acceptanceState === "pending")
719
- ) {
720
- workLedger.invalidate(item.id, "parent-aborted");
721
- }
722
- }
723
- };
724
- let completionController: WorkflowCompletionController | undefined;
725
- let abortListenerAttached = false;
726
- try {
727
- completionController = verifiedWorkflow
728
- ? new WorkflowCompletionController({
729
- ledger: workLedger,
730
- cwd:
731
- workflowTargets[
732
- resolvedWorkflowTasks.findIndex((task) => task.id === verifiedWorkflow.targetTaskId)
733
- ]?.cwd ?? ctx.cwd,
734
- targetTaskId: verifiedWorkflow.targetTaskId,
735
- verifierTaskId: verifiedWorkflow.verifierTaskId,
736
- checks: verifiedWorkflow.checks,
737
- signal,
738
- deadlineAt: deadline,
739
- })
740
- : undefined;
741
- signal?.addEventListener("abort", cancelWorkflowGeneration, { once: true });
742
- abortListenerAttached = signal !== undefined;
743
- while (true) {
744
- const snapshot = workLedger.snapshot();
745
- const remainingBudgetMs =
746
- deadline === undefined
747
- ? MAX_SUBAGENT_TIMEOUT_MS
748
- : Math.max(0, Math.floor(deadline - Date.now()));
749
- const decision = scheduler.decide(snapshot, {
750
- maxConcurrency: Math.min(MAX_BLOCKING_PARALLEL_CONCURRENCY, maxParallelTasks),
751
- activeCount: 0,
752
- transportCapacity: MAX_BLOCKING_PARALLEL_CONCURRENCY,
753
- remainingBudgetMs,
754
- });
755
- workflowScheduling.push(decision);
756
- if (decision.selected.length === 0) break;
757
- status.update(
758
- parallelStatus(resultsById.size, resolvedWorkflowTasks.length, decision.selected.length),
759
- );
760
- const batch = await mapWithConcurrencyLimit(
761
- decision.selected,
762
- decision.effectiveConcurrency,
763
- async (workItemId) => {
764
- const entry = taskById.get(workItemId);
765
- if (!entry) throw new Error(`Missing workflow task ${workItemId}`);
766
- const { task, index } = entry;
767
- const dependencies = (task.dependsOn ?? [])
768
- .map((dependency) => resultsById.get(dependency))
769
- .filter((result): result is SingleResult => result !== undefined);
770
- const managedVerifier =
771
- completionController !== undefined && workItemId === verifiedWorkflow?.verifierTaskId;
772
- const verifierDependency = task.verifierFor
773
- ? resultsById.get(task.verifierFor)
774
- : undefined;
775
- const verifierStructuredResult =
776
- verifierDependency?.structuredResult?.version === "pi-subagents:result:v2"
777
- ? verifierDependency.structuredResult
778
- : undefined;
779
- const dependencyContext = managedVerifier
780
- ? ""
781
- : task.verifierFor
782
- ? verifierStructuredResult
783
- ? `\n\nStaged target result:\n${redactPrivateText(
784
- JSON.stringify(verifierStructuredResult),
785
- )}`
786
- : ""
787
- : dependencies.length
788
- ? `\n\nDependency results:\n${buildFanInContext(dependencies)}`
789
- : "";
790
- const displayTask = task.task;
791
- const target = workflowTargets[index];
792
- const thinkingLevel = resolveThinkingLevel(task.agent, task.thinkingLevel);
793
- let verifierTreeIdentity:
794
- | Awaited<ReturnType<typeof captureWorkflowTreeIdentity>>
795
- | undefined;
796
- let verifierPreflightError: string | undefined;
797
- let verifierPreflightCode: string | undefined;
798
- if (task.verifierFor) {
799
- const staged = workLedger.get(task.verifierFor);
800
- if (!staged?.stagedTreeIdentity) {
801
- verifierPreflightCode = "verification-tree-unavailable";
802
- verifierPreflightError = `Verification target ${task.verifierFor} has no staged tree identity`;
803
- } else {
804
- try {
805
- verifierTreeIdentity = await captureWorkflowTreeIdentity(target.cwd, { signal });
806
- if (!sameWorkflowTreeIdentity(staged.stagedTreeIdentity, verifierTreeIdentity)) {
807
- verifierPreflightCode = "verification-tree-mismatch";
808
- verifierPreflightError =
809
- "Workflow verification tree changed before verifier launch";
810
- }
811
- } catch (error) {
812
- if (signal?.aborted) throw error;
813
- verifierPreflightCode = "verification-tree-unavailable";
814
- verifierPreflightError = error instanceof Error ? error.message : String(error);
815
- }
816
- }
817
- }
818
- const verificationTargetTask = task.verifierFor
819
- ? taskById.get(task.verifierFor)?.task
820
- : undefined;
821
- const verificationTargetContract = normalizeDelegationContract(
822
- verificationTargetTask?.contract,
823
- );
824
- const managedVerificationInstruction = managedVerifier
825
- ? completionController?.verifierPrompt()
826
- : undefined;
827
- if (managedVerifier && !managedVerificationInstruction) {
828
- throw new Error("Verified execution verifier instruction is unavailable");
829
- }
830
- const verificationSuffix = managedVerifier
831
- ? `\n\n${managedVerificationInstruction}`
832
- : task.verifierFor && verifierTreeIdentity
833
- ? `\n\n${workflowVerificationInstruction(task.verifierFor, verifierTreeIdentity, {
834
- acceptanceCriteria: [
835
- ...(verificationTargetTask?.acceptanceCriteria ?? []),
836
- ...(verificationTargetContract?.acceptanceCriteria ?? []),
837
- ],
838
- requiredEvidence: verificationTargetContract?.requiredEvidence ?? [],
839
- })}`
840
- : "";
841
- const reworkSuffix =
842
- completionController &&
843
- workItemId === verifiedWorkflow?.targetTaskId &&
844
- (workLedger.get(workItemId)?.taskGeneration ?? 1) > 1
845
- ? `\n\n${completionController.reworkPrompt()}`
846
- : "";
847
- const baseTask = `${task.task}${dependencyContext}`;
848
- const requiredSuffix = `${reworkSuffix}${verificationSuffix}`;
849
- const baseBudget = Math.max(
850
- 0,
851
- DEFAULT_MAX_CONTEXT_BYTES - Buffer.byteLength(requiredSuffix, "utf8"),
852
- );
853
- const taskWithContext = `${truncateUtf8(baseTask, baseBudget).text}${requiredSuffix}`;
854
- const prepared = prepareTask(taskWithContext, task);
855
- const startedItem = startWorkItem(workItemId, task.agent);
856
- const acceptedTaskGeneration = startedItem?.taskGeneration ?? 0;
857
- await persistWorkLedger();
858
- const runAttempt = (attemptSignal: AbortSignal | undefined) => {
859
- const budget = resolveExecutionBudget(task.agent, task.timeoutMs);
860
- if (!budget) {
861
- return Promise.resolve(exhaustedResult(task.agent, displayTask, thinkingLevel));
862
- }
863
- const childPolicy = launchPolicy(
864
- target,
865
- prepared,
866
- displayTask,
867
- task.agent,
868
- thinkingLevel,
869
- budget.timeoutMs,
870
- acceptedTaskGeneration,
871
- budget,
872
- resolveTurnLimits(task),
873
- );
874
- return runSingleAgent(
875
- ctx.cwd,
876
- agents,
877
- task.agent,
878
- prepared.text,
879
- target.cwd,
880
- undefined,
881
- attemptSignal,
882
- thinkingLevel,
883
- budget.timeoutMs,
884
- undefined,
885
- makeDetails("workflow"),
886
- undefined,
887
- managedVerifier
888
- ? {
889
- ...childPolicy,
890
- disableExtensions: true,
891
- disableSkills: true,
892
- disablePromptTemplates: true,
893
- disableContextFiles: true,
894
- }
895
- : childPolicy,
896
- );
897
- };
898
- const maxAttempts = task.retryPolicy?.maxAttempts ?? 1;
899
- let result: SingleResult | undefined = verifierPreflightError
900
- ? attachTarget(
901
- workflowFailureResult(
902
- task.agent,
903
- displayTask,
904
- verifierPreflightCode ?? "verification-tree-unavailable",
905
- verifierPreflightError,
906
- thinkingLevel,
907
- ),
908
- target,
909
- )
910
- : undefined;
911
- let hedged = false;
912
- for (let attempt = 1; !verifierPreflightError && attempt <= maxAttempts; attempt++) {
913
- if (attempt > 1 && deadline !== undefined && Date.now() >= deadline) break;
914
- const attempted = await runHedgedAttempt(runAttempt, signal, task.hedgeAfterMs);
915
- hedged ||= attempted.hedged;
916
- result = attachTarget(
917
- {
918
- ...attempted.result,
919
- attemptCount: attempt,
920
- hedged: hedged || undefined,
921
- },
922
- target,
923
- );
924
- if (!isRetryableResult(result) || attempt >= maxAttempts) break;
925
- if (deadline !== undefined && Date.now() >= deadline) break;
926
- await supervisionDelay(task.retryPolicy?.backoffMs ?? 0, signal);
927
- }
928
- if (!result) throw new Error(`Workflow task ${workItemId} produced no result`);
929
- if (workLedger.get(workItemId)?.taskGeneration !== acceptedTaskGeneration) {
930
- result.outcome = {
931
- status: "stale",
932
- reasonCode: "cancelled-generation",
933
- recoveryActions: ["discard", "replan"],
934
- retryable: false,
935
- };
936
- }
937
- resultsById.set(workItemId, result);
938
- if (result.outcome?.status === "stale") {
939
- // Cancellation or replacement already rotated and invalidated this generation.
940
- } else if (managedVerifier && completionController) {
941
- const structured =
942
- result.structuredResult?.version === "pi-subagents:result:v2"
943
- ? result.structuredResult
944
- : undefined;
945
- try {
946
- if (!structured || !result.executionPlan?.id) {
947
- throw new Error(
948
- "Verified execution verifier did not return a current structured-v2 result",
949
- );
950
- }
951
- const completion = await completionController.completeVerifier({
952
- taskGeneration: acceptedTaskGeneration,
953
- executionPlanId: result.executionPlan.id,
954
- verifierAgent: task.agent,
955
- result: structured,
956
- sourceTruncated: result.truncated,
957
- });
958
- const targetItem = workLedger.get(verifiedWorkflow?.targetTaskId ?? "");
959
- if (
960
- completion.decision === "rework" &&
961
- targetItem?.acceptanceState === "rework-requested"
962
- ) {
963
- const targetResult = resultsById.get(targetItem.id);
964
- if (targetResult?.capabilityGrant?.state === "active") {
965
- targetResult.capabilityGrant = revokeCapabilityGrant(
966
- targetResult.capabilityGrant,
967
- "verification-rework",
968
- Date.now(),
969
- );
970
- }
971
- if (result.capabilityGrant?.state === "active") {
972
- result.capabilityGrant = revokeCapabilityGrant(
973
- result.capabilityGrant,
974
- "verification-rework",
975
- Date.now(),
976
- );
977
- }
978
- completionController.beginRework();
979
- } else if (completion.decision !== "accept" && targetItem) {
980
- const targetResult = resultsById.get(targetItem.id);
981
- if (targetResult) {
982
- targetResult.outcome = {
983
- status: "failed",
984
- reasonCode: targetItem.outcomeReason ?? "verification-rejected",
985
- recoveryActions: ["stop"],
986
- retryable: false,
987
- };
988
- }
989
- }
990
- } catch (error) {
991
- if (signal?.aborted) throw error;
992
- const message = error instanceof Error ? error.message : String(error);
993
- const reasonCode = workflowCompletionFailureReason(error);
994
- result.outcome = {
995
- status: "failed",
996
- reasonCode,
997
- recoveryActions: ["revalidate"],
998
- retryable: false,
999
- };
1000
- result.errorMessage = message;
1001
- const verifierItem = workLedger.get(workItemId);
1002
- if (verifierItem?.state === "running") {
1003
- workLedger.failVerification(workItemId, reasonCode);
1004
- }
1005
- }
1006
- } else if (task.verifierFor) {
1007
- const staged = workLedger.get(task.verifierFor);
1008
- const structured =
1009
- result.structuredResult?.version === "pi-subagents:result:v2"
1010
- ? result.structuredResult
1011
- : undefined;
1012
- let failureReason: string | undefined = verifierPreflightError;
1013
- let failureCode: string | undefined = verifierPreflightCode;
1014
- let postVerifierIdentity = verifierTreeIdentity;
1015
- if (!failureReason) {
1016
- try {
1017
- postVerifierIdentity = await captureWorkflowTreeIdentity(target.cwd, { signal });
1018
- if (
1019
- !verifierTreeIdentity ||
1020
- !staged?.stagedTreeIdentity ||
1021
- !sameWorkflowTreeIdentity(verifierTreeIdentity, postVerifierIdentity) ||
1022
- !sameWorkflowTreeIdentity(staged.stagedTreeIdentity, postVerifierIdentity)
1023
- ) {
1024
- failureCode = "verification-tree-mismatch";
1025
- failureReason = "Workflow verification tree changed during verifier execution";
1026
- }
1027
- } catch (error) {
1028
- if (signal?.aborted) throw error;
1029
- failureCode = "verification-tree-unavailable";
1030
- failureReason = error instanceof Error ? error.message : String(error);
1031
- }
1032
- }
1033
- if (
1034
- !failureReason &&
1035
- structured &&
1036
- staged?.acceptedExecutionPlanId &&
1037
- result.executionPlan?.id &&
1038
- postVerifierIdentity
1039
- ) {
1040
- try {
1041
- const receipt = createWorkflowVerificationReceipt(structured, {
1042
- targetTaskId: staged.id,
1043
- targetTaskGeneration: staged.taskGeneration,
1044
- targetExecutionPlanId: staged.acceptedExecutionPlanId,
1045
- verifierTaskId: workItemId,
1046
- verifierTaskGeneration: acceptedTaskGeneration,
1047
- verifierExecutionPlanId: result.executionPlan.id,
1048
- treeIdentity: postVerifierIdentity,
1049
- sourceTruncated: result.truncated === true,
1050
- });
1051
- workLedger.completeVerification(workItemId, {
1052
- taskGeneration: acceptedTaskGeneration,
1053
- executionPlanId: result.executionPlan.id,
1054
- receipt,
1055
- });
1056
- if (receipt.decision !== "accept") {
1057
- const targetResult = resultsById.get(staged.id);
1058
- if (targetResult) {
1059
- targetResult.outcome = {
1060
- status: receipt.decision === "rework" ? "blocked" : "failed",
1061
- reasonCode:
1062
- receipt.decision === "rework"
1063
- ? "verification-rework"
1064
- : "verification-rejected",
1065
- recoveryActions:
1066
- receipt.decision === "rework" ? ["replan", "verify"] : ["stop"],
1067
- retryable: false,
1068
- };
1069
- }
1070
- }
1071
- } catch (error) {
1072
- failureCode = "verification-receipt-invalid";
1073
- failureReason = error instanceof Error ? error.message : String(error);
1074
- }
1075
- } else if (!failureReason) {
1076
- failureCode = "verification-receipt-invalid";
1077
- failureReason = "Workflow verifier did not return a current structured-v2 result";
1078
- }
1079
- if (failureReason) {
1080
- const reasonCode = failureCode ?? "verification-receipt-invalid";
1081
- result.outcome = {
1082
- status:
1083
- reasonCode === "verification-receipt-invalid" ? "contract-invalid" : "failed",
1084
- reasonCode,
1085
- recoveryActions:
1086
- reasonCode === "verification-receipt-invalid"
1087
- ? ["repair-contract"]
1088
- : ["revalidate"],
1089
- retryable: false,
1090
- };
1091
- result.errorMessage = failureReason;
1092
- workLedger.failVerification(workItemId, reasonCode);
1093
- }
1094
- } else if (
1095
- completionController &&
1096
- workItemId === verifiedWorkflow?.targetTaskId &&
1097
- !isResultError(result)
1098
- ) {
1099
- try {
1100
- if (!result.executionPlan?.id) {
1101
- throw new Error("Verified execution producer has no accepted ExecutionPlan");
1102
- }
1103
- await completionController.stageTarget({
1104
- taskGeneration: acceptedTaskGeneration,
1105
- executionPlanId: result.executionPlan.id,
1106
- artifacts: artifactsFromResult(result),
1107
- });
1108
- } catch (error) {
1109
- if (signal?.aborted) throw error;
1110
- const message = error instanceof Error ? error.message : String(error);
1111
- result.outcome = {
1112
- status: "failed",
1113
- reasonCode: "verification-checks-unavailable",
1114
- recoveryActions: ["revalidate"],
1115
- retryable: false,
1116
- };
1117
- result.errorMessage = message;
1118
- if (workLedger.get(workItemId)?.state === "running") {
1119
- settleWorkItem(workItemId, result, acceptedTaskGeneration);
1120
- }
1121
- }
1122
- } else if (verificationTargetIds.has(workItemId) && !isResultError(result)) {
1123
- try {
1124
- const treeIdentity = await captureWorkflowTreeIdentity(target.cwd, { signal });
1125
- if (!result.executionPlan?.id) {
1126
- throw new Error("Verification-required producer has no accepted ExecutionPlan");
1127
- }
1128
- workLedger.stageForVerification(workItemId, {
1129
- taskGeneration: acceptedTaskGeneration,
1130
- executionPlanId: result.executionPlan.id,
1131
- artifacts: artifactsFromResult(result),
1132
- treeIdentity,
1133
- });
1134
- } catch (error) {
1135
- if (signal?.aborted) throw error;
1136
- const message = error instanceof Error ? error.message : String(error);
1137
- result.outcome = {
1138
- status: "failed",
1139
- reasonCode: "verification-tree-unavailable",
1140
- recoveryActions: ["revalidate"],
1141
- retryable: false,
1142
- };
1143
- result.errorMessage = message;
1144
- settleWorkItem(workItemId, result, acceptedTaskGeneration);
1145
- }
1146
- } else {
1147
- settleWorkItem(workItemId, result, acceptedTaskGeneration);
1148
- }
1149
- await persistWorkLedger();
1150
- return result;
1151
- },
1152
- signal,
1153
- );
1154
- if (batch.length === 0 || signal?.aborted) break;
1155
- }
1156
- for (const item of workLedger.snapshot().items) {
1157
- if (
1158
- item.state !== "pending" &&
1159
- item.state !== "ready" &&
1160
- item.state !== "awaiting-verification" &&
1161
- !(item.state === "completed" && item.acceptanceState === "pending")
1162
- ) {
1163
- continue;
1164
- }
1165
- if (signal?.aborted) {
1166
- workLedger.settle(item.id, "interrupted", "parent-aborted");
1167
- } else if (deadline !== undefined && Date.now() >= deadline) {
1168
- workLedger.settle(item.id, "blocked", "budget-exhausted");
1169
- } else if (
1170
- item.state === "awaiting-verification" ||
1171
- (item.state === "completed" && item.acceptanceState === "pending")
1172
- ) {
1173
- workLedger.settle(item.id, "blocked", "verification-not-completed");
1174
- } else {
1175
- const dependencyBlocked = item.dependencies.some(
1176
- (dependency) => workLedger.get(dependency)?.state !== "completed",
1177
- );
1178
- workLedger.settle(
1179
- item.id,
1180
- dependencyBlocked ? "blocked" : "needs-input",
1181
- dependencyBlocked ? "dependency-not-completed" : "artifact-version-mismatch",
1182
- );
1183
- }
1184
- }
1185
- await persistWorkLedger();
1186
- const results = resolvedWorkflowTasks.map((task) => {
1187
- const completed = resultsById.get(task.id);
1188
- const item = workLedger.get(task.id);
1189
- if (completed) {
1190
- if (
1191
- item &&
1192
- (item.state !== "completed" ||
1193
- (item.acceptanceRequired && item.acceptanceState !== "accepted")) &&
1194
- !isResultError(completed)
1195
- ) {
1196
- completed.outcome = {
1197
- status:
1198
- item.state === "needs-input"
1199
- ? "needs-input"
1200
- : item.state === "interrupted"
1201
- ? "interrupted"
1202
- : item.state === "failed"
1203
- ? "failed"
1204
- : "blocked",
1205
- reasonCode: item.outcomeReason ?? "verification-not-accepted",
1206
- recoveryActions:
1207
- item.outcomeReason === "verification-rework" ? ["replan", "verify"] : ["stop"],
1208
- retryable: false,
1209
- };
1210
- }
1211
- return completed;
1212
- }
1213
- const outcomeStatus =
1214
- item?.state === "interrupted"
1215
- ? "interrupted"
1216
- : item?.state === "needs-input"
1217
- ? "needs-input"
1218
- : "blocked";
1219
- const reasonCode = item?.outcomeReason ?? "dependency-not-satisfied";
1220
- return {
1221
- agent: task.agent,
1222
- agentSource: agents.find((agent) => agent.name === task.agent)?.source ?? "unknown",
1223
- task: task.task,
1224
- exitCode: 1,
1225
- messages: [],
1226
- stderr: "Workflow dependency was not satisfied",
1227
- errorMessage: `Workflow task did not start: ${reasonCode}`,
1228
- aborted: outcomeStatus === "interrupted",
1229
- outcome: {
1230
- status: outcomeStatus,
1231
- reasonCode,
1232
- recoveryActions:
1233
- outcomeStatus === "needs-input"
1234
- ? ["supply-input"]
1235
- : outcomeStatus === "interrupted"
1236
- ? ["retry"]
1237
- : ["resolve-dependency"],
1238
- retryable: outcomeStatus === "interrupted",
1239
- },
1240
- usage: {
1241
- input: 0,
1242
- output: 0,
1243
- cacheRead: 0,
1244
- cacheWrite: 0,
1245
- cost: 0,
1246
- contextTokens: 0,
1247
- turns: 0,
1248
- },
1249
- finalOutput: "",
1250
- } satisfies SingleResult;
1251
- });
1252
- const successCount = results.filter((result) => !isResultError(result)).length;
1253
- const attemptCount = results.reduce((sum, result) => sum + (result.attemptCount ?? 1), 0);
1254
- const hedgeCount = results.filter((result) => result.hedged).length;
1255
- const isError = successCount !== results.length;
1256
- return {
1257
- content: [
1258
- {
1259
- type: "text",
1260
- text: `Workflow: ${successCount}/${results.length} succeeded; ${attemptCount} attempt(s), ${hedgeCount} hedged task(s).`,
1261
- },
1262
- ],
1263
- details: { ...makeDetails("workflow")(results), isError },
1264
- isError: isError || undefined,
1265
- };
1266
- } finally {
1267
- if (abortListenerAttached) {
1268
- signal?.removeEventListener("abort", cancelWorkflowGeneration);
1269
- }
1270
- completionController?.dispose();
1271
- try {
1272
- await persistWorkLedger();
1273
- } finally {
1274
- status.clear();
1275
- }
1276
- }
1277
- }
1278
-
1279
- if (params.chain && params.chain.length > 0) {
1280
- const results: SingleResult[] = [];
1281
- let previousOutput = "";
1282
- const status = startSubagentStatus(ctx, toolCallId, chainStatus(0, params.chain.length));
1283
-
1284
- try {
1285
- for (let i = 0; i < params.chain.length; i++) {
1286
- const step = params.chain[i];
1287
- status.update(chainStatus(i + 1, params.chain.length, step.agent));
1288
- const taskWithContext = truncateUtf8(
1289
- step.task.replace(/\{previous\}/g, previousOutput),
1290
- DEFAULT_MAX_CONTEXT_BYTES,
1291
- ).text;
1292
- const prepared = prepareTask(taskWithContext, step);
1293
-
1294
- // Create update callback that includes all previous results
1295
- const chainUpdate: OnUpdateCallback | undefined = onUpdate
1296
- ? (partial) => {
1297
- // Combine completed results with current streaming result
1298
- const currentResult = partial.details?.results[0];
1299
- if (currentResult) {
1300
- const allResults = [...results, currentResult];
1301
- onUpdate({
1302
- content: partial.content,
1303
- details: makeDetails("chain")(allResults),
1304
- });
1305
- }
1306
- }
1307
- : undefined;
1308
-
1309
- const target = chainTargets[i];
1310
- const thinkingLevel = resolveThinkingLevel(step.agent, step.thinkingLevel);
1311
- const budget = resolveExecutionBudget(step.agent, step.timeoutMs);
1312
- const taskGeneration = startWorkItem(`step-${i + 1}`, step.agent)?.taskGeneration ?? 0;
1313
- const result = attachTarget(
1314
- budget
1315
- ? await runSingleAgent(
1316
- ctx.cwd,
1317
- agents,
1318
- step.agent,
1319
- prepared.text,
1320
- target.cwd,
1321
- i + 1,
1322
- signal,
1323
- thinkingLevel,
1324
- budget.timeoutMs,
1325
- chainUpdate,
1326
- makeDetails("chain"),
1327
- undefined,
1328
- launchPolicy(
1329
- target,
1330
- prepared,
1331
- taskWithContext,
1332
- step.agent,
1333
- thinkingLevel,
1334
- budget.timeoutMs,
1335
- taskGeneration,
1336
- budget,
1337
- resolveTurnLimits(step),
1338
- ),
1339
- )
1340
- : exhaustedResult(step.agent, taskWithContext, thinkingLevel, i + 1),
1341
- target,
1342
- );
1343
- results.push(result);
1344
- settleWorkItem(`step-${i + 1}`, result, taskGeneration);
1345
-
1346
- const isError = isResultError(result);
1347
- if (isError) {
1348
- const errorMsg = formatResultFailure(result);
1349
- return {
1350
- content: [
1351
- { type: "text", text: `Chain stopped at step ${i + 1} (${step.agent}): ${errorMsg}` },
1352
- ],
1353
- details: { ...makeDetails("chain")(results), isError: true },
1354
- isError: true,
1355
- };
1356
- }
1357
- previousOutput = result.structuredResult
1358
- ? JSON.stringify(result.structuredResult)
1359
- : getResultFinalOutput(result);
1360
- }
1361
- return {
1362
- content: [
1363
- {
1364
- type: "text",
1365
- text: getResultFinalOutput(results[results.length - 1]) || "(no output)",
1366
- },
1367
- ],
1368
- details: makeDetails("chain")(results),
1369
- };
1370
- } finally {
1371
- status.clear();
1372
- }
1373
- }
1374
-
1375
- if (params.tasks && params.tasks.length > 0) {
1376
- const status = startSubagentStatus(
1377
- ctx,
1378
- toolCallId,
1379
- parallelStatus(0, params.tasks.length, params.tasks.length),
1380
- );
1381
-
1382
- try {
1383
- // Track all results for streaming updates
1384
- const allResults: SingleResult[] = new Array(params.tasks.length);
1385
-
1386
- // Initialize placeholder results
1387
- for (let i = 0; i < params.tasks.length; i++) {
1388
- allResults[i] = {
1389
- agent: params.tasks[i].agent,
1390
- agentSource: "unknown",
1391
- task: params.tasks[i].task,
1392
- exitCode: -1, // -1 = still running
1393
- messages: [],
1394
- stderr: "",
1395
- usage: {
1396
- input: 0,
1397
- output: 0,
1398
- cacheRead: 0,
1399
- cacheWrite: 0,
1400
- cost: 0,
1401
- contextTokens: 0,
1402
- turns: 0,
1403
- },
1404
- thinkingLevel: resolveThinkingLevel(params.tasks[i].agent, params.tasks[i].thinkingLevel),
1405
- finalOutput: "",
1406
- };
1407
- }
1408
-
1409
- let doneCount = 0;
1410
- let runningCount = params.tasks.length;
1411
-
1412
- const emitParallelUpdate = () => {
1413
- status.update(parallelStatus(doneCount, allResults.length, runningCount));
1414
- if (onUpdate) {
1415
- const pendingAggregator: SingleResult | undefined =
1416
- aggregator && !signal?.aborted && doneCount === allResults.length
1417
- ? {
1418
- agent: aggregator.agent,
1419
- agentSource:
1420
- agents.find((agent) => agent.name === aggregator.agent)?.source ?? "unknown",
1421
- task: aggregator.task,
1422
- exitCode: -1,
1423
- messages: [],
1424
- stderr: "",
1425
- usage: {
1426
- input: 0,
1427
- output: 0,
1428
- cacheRead: 0,
1429
- cacheWrite: 0,
1430
- cost: 0,
1431
- contextTokens: 0,
1432
- turns: 0,
1433
- },
1434
- thinkingLevel: resolveThinkingLevel(aggregator.agent, aggregator.thinkingLevel),
1435
- timeoutMs: resolveTimeoutMs(aggregator.agent, aggregator.timeoutMs),
1436
- finalOutput: "",
1437
- }
1438
- : undefined;
1439
- onUpdate({
1440
- content: [
1441
- {
1442
- type: "text",
1443
- text: `Parallel: ${doneCount}/${allResults.length} done, ${runningCount} running...`,
1444
- },
1445
- ],
1446
- details: makeDetails("parallel")([...allResults], pendingAggregator),
1447
- });
1448
- }
1449
- };
1450
-
1451
- const results = await mapWithConcurrencyLimit(
1452
- params.tasks,
1453
- MAX_BLOCKING_PARALLEL_CONCURRENCY,
1454
- async (t, index) => {
1455
- const target = parallelTargets[index];
1456
- const prepared = prepareTask(t.task, t);
1457
- const thinkingLevel = resolveThinkingLevel(t.agent, t.thinkingLevel);
1458
- const budget = resolveExecutionBudget(t.agent, t.timeoutMs);
1459
- const taskGeneration = startWorkItem(`task-${index + 1}`, t.agent)?.taskGeneration ?? 0;
1460
- const result = attachTarget(
1461
- budget
1462
- ? await runSingleAgent(
1463
- ctx.cwd,
1464
- agents,
1465
- t.agent,
1466
- prepared.text,
1467
- target.cwd,
1468
- undefined,
1469
- signal,
1470
- thinkingLevel,
1471
- budget.timeoutMs,
1472
- (partial) => {
1473
- if (partial.details?.results[0]) {
1474
- allResults[index] = { ...partial.details.results[0], exitCode: -1 };
1475
- emitParallelUpdate();
1476
- }
1477
- },
1478
- makeDetails("parallel"),
1479
- undefined,
1480
- launchPolicy(
1481
- target,
1482
- prepared,
1483
- t.task,
1484
- t.agent,
1485
- thinkingLevel,
1486
- budget.timeoutMs,
1487
- taskGeneration,
1488
- budget,
1489
- resolveTurnLimits(t),
1490
- ),
1491
- )
1492
- : exhaustedResult(t.agent, t.task, thinkingLevel),
1493
- target,
1494
- );
1495
- allResults[index] = result;
1496
- settleWorkItem(`task-${index + 1}`, result, taskGeneration);
1497
- doneCount += 1;
1498
- runningCount -= 1;
1499
- emitParallelUpdate();
1500
- return result;
1501
- },
1502
- signal,
1503
- (task, index) => {
1504
- const taskGeneration =
1505
- startWorkItem(`task-${index + 1}`, task.agent)?.taskGeneration ?? 0;
1506
- const skipped: SingleResult = {
1507
- ...allResults[index],
1508
- task: task.task,
1509
- exitCode: 130,
1510
- stopReason: "aborted",
1511
- aborted: true,
1512
- errorMessage: "Subagent was not started because the parent call was aborted",
1513
- };
1514
- allResults[index] = skipped;
1515
- settleWorkItem(`task-${index + 1}`, skipped, taskGeneration);
1516
- doneCount += 1;
1517
- runningCount -= 1;
1518
- emitParallelUpdate();
1519
- return skipped;
1520
- },
1521
- );
1522
-
1523
- let aggregatorResult: SingleResult | undefined;
1524
- if (aggregator && !signal?.aborted) {
1525
- status.update(fanInStatus(aggregator.agent));
1526
- const fanInContext = buildFanInContext(results);
1527
- const aggregatorTask = truncateUtf8(
1528
- aggregator.task.includes("{previous}")
1529
- ? aggregator.task.replace(/\{previous\}/g, fanInContext)
1530
- : `${aggregator.task}\n\nParallel task outputs:\n\n${fanInContext}`,
1531
- DEFAULT_MAX_CONTEXT_BYTES,
1532
- ).text;
1533
- const prepared = prepareTask(aggregatorTask, aggregator);
1534
- const target = aggregatorTarget as ResolvedSubagentTarget;
1535
- const thinkingLevel = resolveThinkingLevel(aggregator.agent, aggregator.thinkingLevel);
1536
- const budget = resolveExecutionBudget(aggregator.agent, aggregator.timeoutMs);
1537
- const taskGeneration = startWorkItem("aggregator", aggregator.agent)?.taskGeneration ?? 0;
1538
- aggregatorResult = attachTarget(
1539
- budget
1540
- ? await runSingleAgent(
1541
- ctx.cwd,
1542
- agents,
1543
- aggregator.agent,
1544
- prepared.text,
1545
- target.cwd,
1546
- undefined,
1547
- signal,
1548
- thinkingLevel,
1549
- budget.timeoutMs,
1550
- (partial) => {
1551
- status.update(fanInStatus(aggregator.agent));
1552
- if (onUpdate && partial.details?.results[0]) {
1553
- onUpdate({
1554
- content: partial.content,
1555
- details: makeDetails("parallel")(results, partial.details.results[0]),
1556
- });
1557
- }
1558
- },
1559
- makeDetails("parallel"),
1560
- undefined,
1561
- launchPolicy(
1562
- target,
1563
- prepared,
1564
- aggregatorTask,
1565
- aggregator.agent,
1566
- thinkingLevel,
1567
- budget.timeoutMs,
1568
- taskGeneration,
1569
- budget,
1570
- resolveTurnLimits(aggregator),
1571
- ),
1572
- )
1573
- : exhaustedResult(aggregator.agent, aggregatorTask, thinkingLevel),
1574
- target,
1575
- );
1576
- settleWorkItem("aggregator", aggregatorResult, taskGeneration);
1577
- }
1578
-
1579
- const successCount = results.filter((result) => !isResultError(result)).length;
1580
- const summaries = results.map((result) => {
1581
- const failed = isResultError(result);
1582
- const output = getResultFinalOutput(result);
1583
- const error = result.errorMessage || result.stderr.trim();
1584
- const summaryText = failed ? formatResultFailure(result) : output || error;
1585
- const preview = truncateUtf8(summaryText, 160).text;
1586
- return `[${result.agent}] ${failed ? "failed" : "completed"}: ${preview || "(no output)"}`;
1587
- });
1588
- const aggregatorFailed = aggregatorResult ? isResultError(aggregatorResult) : false;
1589
- const aggregatorOutput = aggregatorResult ? getResultFinalOutput(aggregatorResult) : "";
1590
- const aggregatorError =
1591
- aggregatorResult?.errorMessage || aggregatorResult?.stderr.trim() || "";
1592
- return {
1593
- content: [
1594
- {
1595
- type: "text",
1596
- text: aggregatorResult
1597
- ? aggregatorFailed
1598
- ? formatResultFailure(aggregatorResult)
1599
- : aggregatorOutput ||
1600
- aggregatorError ||
1601
- `(aggregator ${aggregatorResult.agent} produced no output)`
1602
- : `Parallel: ${successCount}/${results.length} succeeded\n\n${summaries.join("\n\n")}`,
1603
- },
1604
- ],
1605
- details: {
1606
- ...makeDetails("parallel")(results, aggregatorResult),
1607
- isError: aggregatorFailed,
1608
- },
1609
- isError: aggregatorResult ? aggregatorFailed : undefined,
1610
- };
1611
- } finally {
1612
- status.clear();
1613
- }
1614
- }
1615
-
1616
- if (params.agent && params.task) {
1617
- const status = startSubagentStatus(ctx, toolCallId, singleStatus(params.agent));
1618
-
1619
- try {
1620
- const target = singleTarget as ResolvedSubagentTarget;
1621
- const prepared = prepareTask(params.task, params);
1622
- const thinkingLevel = resolveThinkingLevel(params.agent, params.thinkingLevel);
1623
- const budget = resolveExecutionBudget(params.agent, params.timeoutMs);
1624
- const taskGeneration = startWorkItem("task-1", params.agent)?.taskGeneration ?? 0;
1625
- const result = attachTarget(
1626
- budget
1627
- ? await runSingleAgent(
1628
- ctx.cwd,
1629
- agents,
1630
- params.agent,
1631
- prepared.text,
1632
- target.cwd,
1633
- undefined,
1634
- signal,
1635
- thinkingLevel,
1636
- budget.timeoutMs,
1637
- onUpdate,
1638
- makeDetails("single"),
1639
- undefined,
1640
- launchPolicy(
1641
- target,
1642
- prepared,
1643
- params.task,
1644
- params.agent,
1645
- thinkingLevel,
1646
- budget.timeoutMs,
1647
- taskGeneration,
1648
- budget,
1649
- resolveTurnLimits(params),
1650
- ),
1651
- )
1652
- : exhaustedResult(params.agent, params.task, thinkingLevel),
1653
- target,
1654
- );
1655
- settleWorkItem("task-1", result, taskGeneration);
1656
- const isError = isResultError(result);
1657
- if (isError) {
1658
- const errorMsg = formatResultFailure(result);
1659
- return {
1660
- content: [{ type: "text", text: `Agent ${result.stopReason || "failed"}: ${errorMsg}` }],
1661
- details: { ...makeDetails("single")([result]), isError: true },
1662
- isError: true,
1663
- };
1664
- }
1665
- return {
1666
- content: [{ type: "text", text: getResultFinalOutput(result) || "(no output)" }],
1667
- details: makeDetails("single")([result]),
1668
- };
1669
- } finally {
1670
- status.clear();
1671
- }
1672
- }
1673
-
1674
- const available = agents.map((a) => `${a.name} (${a.source})`).join(", ") || "none";
1675
- return {
1676
- content: [{ type: "text", text: `Invalid parameters. Available agents: ${available}` }],
1677
- details: makeDetails("single")([]),
1678
- };
1679
- }