@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/runner.ts DELETED
@@ -1,866 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import * as fs from "node:fs";
3
- import * as os from "node:os";
4
- import * as path from "node:path";
5
- import type { Message } from "@earendil-works/pi-ai";
6
- import { withFileMutationQueue } from "@earendil-works/pi-coding-agent";
7
- import type { AgentConfig, SubagentThinkingLevel } from "./agents/types.js";
8
- import { revokeCapabilityGrant } from "./capability-grant.js";
9
- import {
10
- appendBounded,
11
- DEFAULT_MAX_CONTEXT_BYTES,
12
- DEFAULT_MAX_MESSAGES,
13
- DEFAULT_MAX_OUTPUT_BYTES,
14
- DEFAULT_MAX_STDERR_BYTES,
15
- MAX_SUBAGENT_TIMEOUT_MS,
16
- truncateUtf8,
17
- } from "./limits.js";
18
- import { classifyStructuredOutcome } from "./outcome.js";
19
- import { buildPiArgs } from "./pi-args.js";
20
- import { resolvePiInvocation } from "./pi-invocation.js";
21
- import { KILL_GRACE_MS, terminateProcess } from "./process-control.js";
22
- import { JsonLineDecoder } from "./protocol.js";
23
- import { parseAnyStructuredSubagentResult } from "./result-contract.js";
24
- import { formatResultFailure, getResultFinalOutput, isResultError } from "./runner-outcome.js";
25
- import { getFinalOutput } from "./runner-result.js";
26
- import type { ChildLaunchPolicy, RecentActivityItem, SingleResult } from "./runner-types.js";
27
- import {
28
- addUsageValue,
29
- mergeUsageStats,
30
- protocolUsageCost,
31
- protocolUsageCount,
32
- } from "./runner-usage.js";
33
- import type { OnUpdateCallback, SubagentDetails } from "./subagent-details.js";
34
- import {
35
- formatTimeoutCheckpoint,
36
- formatTurnTerminationMessage,
37
- journalMessages,
38
- TimeoutProgressJournal,
39
- TURN_TERMINATION_VERSION,
40
- } from "./timeout-checkpoint.js";
41
- import {
42
- buildTimeoutFinalizationPrompt,
43
- resolveTimeoutFinalizationMs,
44
- } from "./timeout-finalization.js";
45
- import { TurnBudgetMonitor, type TurnBudgetStop } from "./turn-budget.js";
46
-
47
- export type { PiArgsOptions } from "./pi-args.js";
48
- export { buildPiArgs } from "./pi-args.js";
49
- export { KILL_GRACE_MS, terminateProcess } from "./process-control.js";
50
- export {
51
- formatResultFailure,
52
- getResultFinalOutput,
53
- isResultError,
54
- } from "./runner-outcome.js";
55
- export type { ChildLaunchPolicy, RecentActivityItem, SingleResult } from "./runner-types.js";
56
- export type { UsageStats } from "./runner-usage.js";
57
- export type { OnUpdateCallback, PanelDetails, SubagentDetails } from "./subagent-details.js";
58
-
59
- const MAX_RECENT_ACTIVITY_ITEMS = 10;
60
- const MAX_RECENT_ACTIVITY_BYTES = 8 * 1024;
61
- const MAX_RECENT_ACTIVITY_ARGUMENT_BYTES = 1024;
62
-
63
- function boundMessageText(
64
- message: Message,
65
- maxBytes: number,
66
- ): { message?: Message; bytes: number; truncated: boolean } {
67
- const originalBytes = Buffer.byteLength(JSON.stringify(message), "utf8");
68
- if (Number.isSafeInteger(maxBytes) && maxBytes >= 0 && originalBytes <= maxBytes) {
69
- return { message, bytes: originalBytes, truncated: false };
70
- }
71
- if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) return { bytes: 0, truncated: true };
72
-
73
- const content: Array<
74
- | { type: "text"; text: string }
75
- | { type: "toolCall"; id: string; name: string; arguments: Record<string, unknown> }
76
- > = [];
77
- const bounded = () => ({ ...message, content }) as Message;
78
- const fits = () => Buffer.byteLength(JSON.stringify(bounded()), "utf8") <= maxBytes;
79
- const addText = (text: string, prepend = false) => {
80
- if (!text.trim()) return;
81
- const part = { type: "text" as const, text: "" };
82
- if (prepend) content.unshift(part);
83
- else content.push(part);
84
- if (!fits()) {
85
- content.splice(content.indexOf(part), 1);
86
- return;
87
- }
88
- let low = 0;
89
- let high = Buffer.byteLength(text, "utf8");
90
- while (low < high) {
91
- const middle = Math.ceil((low + high) / 2);
92
- part.text = truncateUtf8(text, middle).text;
93
- if (fits()) low = middle;
94
- else high = middle - 1;
95
- }
96
- part.text = truncateUtf8(text, low).text;
97
- if (!part.text.trim()) content.splice(content.indexOf(part), 1);
98
- };
99
- const addToolCall = (part: Extract<Message["content"][number], { type: "toolCall" }>) => {
100
- const toolCall = {
101
- type: "toolCall" as const,
102
- id: part.id,
103
- name: part.name,
104
- arguments: part.arguments,
105
- };
106
- content.unshift(toolCall);
107
- if (fits()) return;
108
- const arguments_: Record<string, unknown> = {};
109
- for (const key of ["command", "path", "file_path", "pattern", "url"]) {
110
- const value = part.arguments[key];
111
- if (typeof value === "string") arguments_[key] = truncateUtf8(value, 256).text;
112
- }
113
- toolCall.arguments = arguments_;
114
- if (fits()) return;
115
- toolCall.arguments = {};
116
- if (!fits()) content.shift();
117
- };
118
-
119
- if (message.role === "assistant") {
120
- for (let index = message.content.length - 1; index >= 0; index--) {
121
- const part = message.content[index];
122
- if (part.type === "text") addText(part.text, true);
123
- else if (part.type === "toolCall") addToolCall(part);
124
- }
125
- } else {
126
- for (const part of message.content) {
127
- if (typeof part === "object" && part && part.type === "text") addText(part.text);
128
- }
129
- }
130
-
131
- if (content.length === 0) return { bytes: 0, truncated: true };
132
- const result = bounded();
133
- const bytes = Buffer.byteLength(JSON.stringify(result), "utf8");
134
- return { message: result, bytes, truncated: true };
135
- }
136
- function compactRecentActivityArguments(args: Record<string, unknown>): Record<string, unknown> {
137
- if (Buffer.byteLength(JSON.stringify(args), "utf8") <= MAX_RECENT_ACTIVITY_ARGUMENT_BYTES)
138
- return args;
139
- const compact: Record<string, unknown> = {};
140
- for (const key of ["command", "path", "file_path", "pattern", "url", "selector"]) {
141
- const value = args[key];
142
- if (typeof value === "string") compact[key] = truncateUtf8(value, 256).text;
143
- else if (typeof value === "number" || typeof value === "boolean") compact[key] = value;
144
- }
145
- return compact;
146
- }
147
-
148
- function appendRecentActivity(result: SingleResult, message: Message): void {
149
- if (message.role !== "assistant") return;
150
- const append = (item: RecentActivityItem) => {
151
- result.recentActivity ??= [];
152
- result.recentActivityTotal = (result.recentActivityTotal ?? 0) + 1;
153
- result.recentActivity.push(item);
154
- if (result.recentActivity.length > MAX_RECENT_ACTIVITY_ITEMS) {
155
- result.recentActivity.splice(0, result.recentActivity.length - MAX_RECENT_ACTIVITY_ITEMS);
156
- }
157
- while (
158
- Buffer.byteLength(JSON.stringify(result.recentActivity), "utf8") > MAX_RECENT_ACTIVITY_BYTES
159
- ) {
160
- result.recentActivity.shift();
161
- }
162
- };
163
- for (const part of message.content) {
164
- if (part.type === "text") {
165
- const text = part.text.trim();
166
- if (text) append({ type: "text", text: truncateUtf8(text, 1024).text });
167
- } else if (part.type === "toolCall") {
168
- append({
169
- type: "toolCall",
170
- name: part.name,
171
- args: compactRecentActivityArguments(part.arguments),
172
- });
173
- }
174
- }
175
- }
176
-
177
- export function buildFanInContext(
178
- results: SingleResult[],
179
- maxBytes = DEFAULT_MAX_CONTEXT_BYTES,
180
- ): string {
181
- const text = results
182
- .map((result, index) => {
183
- const failed = isResultError(result);
184
- const status = result.exitCode === -1 ? "running" : failed ? "failed" : "completed";
185
- const output = getResultFinalOutput(result);
186
- const error = result.errorMessage || result.stderr.trim();
187
- const resultText = failed
188
- ? `${error ? "Error" : output ? "Partial output" : "Error"}:\n${formatResultFailure(result)}`
189
- : result.structuredResult
190
- ? `Structured result:\n${JSON.stringify(result.structuredResult)}`
191
- : output
192
- ? `Output:\n${output}`
193
- : "Output: (no output)";
194
- return [
195
- `## Result ${index + 1}: ${result.agent} (${status})`,
196
- `Task: ${result.task}`,
197
- resultText,
198
- ].join("\n\n");
199
- })
200
- .join("\n\n---\n\n");
201
- return truncateUtf8(text, maxBytes).text;
202
- }
203
-
204
- export async function mapWithConcurrencyLimit<TIn, TOut>(
205
- items: TIn[],
206
- concurrency: number,
207
- fn: (item: TIn, index: number) => Promise<TOut>,
208
- signal?: AbortSignal,
209
- onSkipped?: (item: TIn, index: number) => TOut,
210
- ): Promise<TOut[]> {
211
- if (items.length === 0) return [];
212
- const limit = Math.max(1, Math.min(concurrency, items.length));
213
- const results: TOut[] = new Array(items.length);
214
- let nextIndex = 0;
215
- const workers = new Array(limit).fill(null).map(async () => {
216
- while (true) {
217
- const current = nextIndex++;
218
- if (current >= items.length) return;
219
- if (signal?.aborted && onSkipped) {
220
- results[current] = onSkipped(items[current], current);
221
- continue;
222
- }
223
- results[current] = await fn(items[current], current);
224
- }
225
- });
226
- await Promise.all(workers);
227
- return results;
228
- }
229
-
230
- async function writePromptToTempFile(
231
- agentName: string,
232
- prompt: string,
233
- ): Promise<{ dir: string; filePath: string }> {
234
- const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-"));
235
- const safeName = agentName.replace(/[^\w.-]+/g, "_");
236
- const filePath = path.join(tmpDir, `prompt-${safeName}.md`);
237
- await withFileMutationQueue(filePath, async () => {
238
- await fs.promises.writeFile(filePath, prompt, { encoding: "utf-8", mode: 0o600 });
239
- });
240
- return { dir: tmpDir, filePath };
241
- }
242
-
243
- export async function runSingleAgent(
244
- defaultCwd: string,
245
- agents: AgentConfig[],
246
- agentName: string,
247
- task: string,
248
- cwd: string | undefined,
249
- step: number | undefined,
250
- signal: AbortSignal | undefined,
251
- thinkingLevel: SubagentThinkingLevel | undefined,
252
- timeoutMs: number,
253
- onUpdate: OnUpdateCallback | undefined,
254
- makeDetails: (results: SingleResult[]) => SubagentDetails,
255
- invocationOverride?: { command: string; argsPrefix?: string[] },
256
- launchPolicy?: ChildLaunchPolicy,
257
- ): Promise<SingleResult> {
258
- const agent = agents.find((a) => a.name === agentName);
259
-
260
- if (!agent) {
261
- const available = agents.map((a) => `"${a.name}"`).join(", ") || "none";
262
- return {
263
- agent: agentName,
264
- agentSource: "unknown",
265
- task,
266
- exitCode: 1,
267
- messages: [],
268
- stderr: `Unknown agent: "${agentName}". Available agents: ${available}.`,
269
- usage: {
270
- input: 0,
271
- output: 0,
272
- cacheRead: 0,
273
- cacheWrite: 0,
274
- cost: 0,
275
- contextTokens: 0,
276
- turns: 0,
277
- },
278
- thinkingLevel,
279
- step,
280
- finalOutput: "",
281
- };
282
- }
283
-
284
- const temporaryPrompts: Array<{ dir: string; filePath: string }> = [];
285
- let tmpPromptPath: string | null = null;
286
- let baseSystemPromptPath: string | null = null;
287
-
288
- let latestAssistantOutput = "";
289
- let terminalAssistantOutput: string | undefined;
290
-
291
- const progressJournal = new TimeoutProgressJournal();
292
- const currentResult: SingleResult = {
293
- agent: agentName,
294
- agentSource: agent.source,
295
- task: launchPolicy?.displayTask ?? task,
296
- exitCode: 0,
297
- messages: [],
298
- stderr: "",
299
- usage: {
300
- input: 0,
301
- output: 0,
302
- cacheRead: 0,
303
- cacheWrite: 0,
304
- cost: 0,
305
- contextTokens: 0,
306
- turns: 0,
307
- },
308
- model: agent.model ?? undefined,
309
- thinkingLevel,
310
- step,
311
- timeoutMs,
312
- contract: launchPolicy?.contract,
313
- resultFormat: launchPolicy?.resultFormat,
314
- executionPlan: launchPolicy?.executionPlan,
315
- capabilityGrant: launchPolicy?.capabilityGrant,
316
- };
317
- const selectedAssistantOutput = () =>
318
- terminalAssistantOutput !== undefined
319
- ? terminalAssistantOutput
320
- : latestAssistantOutput || getFinalOutput(currentResult.messages);
321
- const setErrorMessage = (message: string) => {
322
- const bounded = truncateUtf8(message, DEFAULT_MAX_STDERR_BYTES);
323
- currentResult.errorMessage = bounded.text;
324
- currentResult.truncated ||= bounded.truncated;
325
- return bounded.text;
326
- };
327
-
328
- const emitUpdate = () => {
329
- const latest = truncateUtf8(selectedAssistantOutput(), DEFAULT_MAX_OUTPUT_BYTES);
330
- currentResult.finalOutput = latest.text;
331
- currentResult.truncated ||= latest.truncated;
332
- if (onUpdate) {
333
- onUpdate({
334
- content: [{ type: "text", text: currentResult.finalOutput || "(running...)" }],
335
- details: makeDetails([currentResult]),
336
- });
337
- }
338
- };
339
-
340
- try {
341
- const effectiveCwd = cwd ?? defaultCwd;
342
- try {
343
- if (!fs.statSync(effectiveCwd).isDirectory()) throw new Error("not a directory");
344
- } catch (error) {
345
- currentResult.exitCode = 1;
346
- currentResult.stopReason = "error";
347
- const reason = error instanceof Error ? error.message : String(error);
348
- currentResult.stderr = setErrorMessage(`Invalid subagent cwd: ${effectiveCwd} (${reason})`);
349
- return currentResult;
350
- }
351
-
352
- if (signal?.aborted) {
353
- currentResult.exitCode = 130;
354
- currentResult.aborted = true;
355
- currentResult.stopReason = "aborted";
356
- setErrorMessage("Subagent was aborted before start");
357
- return currentResult;
358
- }
359
- if (!Number.isFinite(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_SUBAGENT_TIMEOUT_MS) {
360
- currentResult.exitCode = 1;
361
- currentResult.stopReason = "error";
362
- setErrorMessage(
363
- `Invalid subagent timeout: expected 1-${MAX_SUBAGENT_TIMEOUT_MS}ms, received ${timeoutMs}`,
364
- );
365
- return currentResult;
366
- }
367
-
368
- if (launchPolicy?.baseSystemPrompt?.trim()) {
369
- const tmp = await writePromptToTempFile(`${agent.name}-base`, launchPolicy.baseSystemPrompt);
370
- temporaryPrompts.push(tmp);
371
- baseSystemPromptPath = tmp.filePath;
372
- }
373
- if (agent.systemPrompt.trim()) {
374
- const tmp = await writePromptToTempFile(agent.name, agent.systemPrompt);
375
- temporaryPrompts.push(tmp);
376
- tmpPromptPath = tmp.filePath;
377
- }
378
- if (signal?.aborted) {
379
- currentResult.exitCode = 130;
380
- currentResult.aborted = true;
381
- currentResult.stopReason = "aborted";
382
- setErrorMessage("Subagent was aborted before launch");
383
- return currentResult;
384
- }
385
-
386
- const effectiveTools =
387
- launchPolicy && Object.hasOwn(launchPolicy, "tools") ? launchPolicy.tools : agent.tools;
388
- const selectedTools =
389
- effectiveTools === undefined
390
- ? undefined
391
- : [...new Set([...effectiveTools, ...(launchPolicy?.additionalTools ?? [])])];
392
- const args = buildPiArgs({
393
- model: agent.model,
394
- thinkingLevel,
395
- tools: selectedTools,
396
- disableExtensions: launchPolicy?.disableExtensions,
397
- disableSkills: launchPolicy?.disableSkills,
398
- disablePromptTemplates: launchPolicy?.disablePromptTemplates,
399
- disableContextFiles: launchPolicy?.disableContextFiles,
400
- projectTrust: launchPolicy?.projectTrust,
401
- baseSystemPromptPath: baseSystemPromptPath ?? undefined,
402
- appendSystemPromptPaths: launchPolicy?.appendSystemPromptPaths,
403
- extensionPaths: launchPolicy?.extensionPaths,
404
- systemPromptPath: tmpPromptPath ?? undefined,
405
- task,
406
- });
407
- let invocation: { command: string; args: string[] };
408
- try {
409
- invocation = invocationOverride
410
- ? {
411
- command: invocationOverride.command,
412
- args: [...(invocationOverride.argsPrefix ?? []), ...args],
413
- }
414
- : resolvePiInvocation(args);
415
- } catch (error) {
416
- currentResult.launchFailed = true;
417
- currentResult.exitCode = 1;
418
- currentResult.stderr = setErrorMessage(
419
- error instanceof Error ? error.message : String(error),
420
- );
421
- return currentResult;
422
- }
423
- let wasAborted = false;
424
- let timedOut = false;
425
- let budgetStop:
426
- | TurnBudgetStop
427
- | { reason: "work_timeout" | "orchestration_timeout"; limit: number }
428
- | undefined;
429
-
430
- const exitCode = await new Promise<number>((resolve) => {
431
- let settled = false;
432
- let cleanupTermination: (() => void) | undefined;
433
- let timeout: NodeJS.Timeout | undefined;
434
- let terminationDeadline: NodeJS.Timeout | undefined;
435
- let abortHandler: (() => void) | undefined;
436
- let budgetMonitor: TurnBudgetMonitor | undefined;
437
- const finish = (code: number) => {
438
- if (settled) return;
439
- settled = true;
440
- if (timeout) clearTimeout(timeout);
441
- if (terminationDeadline) clearTimeout(terminationDeadline);
442
- cleanupTermination?.();
443
- budgetMonitor?.dispose();
444
- if (signal && abortHandler) signal.removeEventListener("abort", abortHandler);
445
- resolve(code);
446
- };
447
- let proc: ReturnType<typeof spawn>;
448
- try {
449
- proc = spawn(invocation.command, invocation.args, {
450
- cwd: effectiveCwd,
451
- detached: process.platform !== "win32",
452
- shell: false,
453
- stdio: ["ignore", "pipe", "pipe"],
454
- env: {
455
- ...process.env,
456
- ...launchPolicy?.env,
457
- PI_SUBAGENT_DEPTH: String(
458
- (Number.parseInt(process.env.PI_SUBAGENT_DEPTH ?? "0", 10) || 0) + 1,
459
- ),
460
- },
461
- });
462
- } catch (error) {
463
- currentResult.launchFailed = true;
464
- currentResult.stderr = setErrorMessage(
465
- error instanceof Error ? error.message : String(error),
466
- );
467
- finish(1);
468
- return;
469
- }
470
-
471
- const addMessage = (msg: Message) => {
472
- const boundedMessage = boundMessageText(msg, DEFAULT_MAX_OUTPUT_BYTES - 2);
473
- currentResult.truncated ||= boundedMessage.truncated;
474
- if (!boundedMessage.message) return;
475
- while (
476
- currentResult.messages.length >= DEFAULT_MAX_MESSAGES ||
477
- Buffer.byteLength(
478
- JSON.stringify([...currentResult.messages, boundedMessage.message]),
479
- "utf8",
480
- ) > DEFAULT_MAX_OUTPUT_BYTES
481
- ) {
482
- const removed = currentResult.messages.shift();
483
- if (!removed) break;
484
- currentResult.truncated = true;
485
- }
486
- if (
487
- Buffer.byteLength(
488
- JSON.stringify([...currentResult.messages, boundedMessage.message]),
489
- "utf8",
490
- ) > DEFAULT_MAX_OUTPUT_BYTES
491
- ) {
492
- currentResult.truncated = true;
493
- return;
494
- }
495
- currentResult.messages.push(boundedMessage.message);
496
- };
497
- const processEvent = (raw: unknown) => {
498
- if (!raw || typeof raw !== "object") return;
499
- const event = raw as { type?: string; message?: Message };
500
- if (event.type === "message_end" && event.message) {
501
- const msg = event.message;
502
- journalMessages(progressJournal, [msg]);
503
- if (msg.role === "assistant") {
504
- const output = truncateUtf8(getFinalOutput([msg]), DEFAULT_MAX_OUTPUT_BYTES);
505
- currentResult.truncated ||= output.truncated;
506
- if (output.text) latestAssistantOutput = output.text;
507
- if (msg.stopReason === "stop" || msg.stopReason === "length") {
508
- terminalAssistantOutput = output.text;
509
- }
510
- }
511
- appendRecentActivity(currentResult, msg);
512
- addMessage(msg);
513
- if (msg.role === "assistant") {
514
- currentResult.usage.turns++;
515
- budgetMonitor?.recordToolCalls(
516
- msg.content.filter((part) => part.type === "toolCall").length,
517
- );
518
- budgetMonitor?.recordAssistantTurn(msg.stopReason);
519
- const usage = msg.usage;
520
- if (usage && typeof usage === "object") {
521
- const input = protocolUsageCount(usage.input);
522
- const output = protocolUsageCount(usage.output);
523
- const cacheRead = protocolUsageCount(usage.cacheRead);
524
- const cacheWrite = protocolUsageCount(usage.cacheWrite);
525
- const reportedTotal = protocolUsageCount(usage.totalTokens);
526
- const turnTotal =
527
- reportedTotal ||
528
- addUsageValue(addUsageValue(input, output), addUsageValue(cacheRead, cacheWrite));
529
- const cost = usage.cost && typeof usage.cost === "object" ? usage.cost : undefined;
530
- currentResult.usage.input = addUsageValue(currentResult.usage.input, input);
531
- currentResult.usage.output = addUsageValue(currentResult.usage.output, output);
532
- currentResult.usage.cacheRead = addUsageValue(
533
- currentResult.usage.cacheRead,
534
- cacheRead,
535
- );
536
- currentResult.usage.cacheWrite = addUsageValue(
537
- currentResult.usage.cacheWrite,
538
- cacheWrite,
539
- );
540
- currentResult.usage.cost = addUsageValue(
541
- currentResult.usage.cost,
542
- protocolUsageCost(cost?.total),
543
- );
544
- currentResult.usage.costInput = addUsageValue(
545
- currentResult.usage.costInput ?? 0,
546
- protocolUsageCost(cost?.input),
547
- );
548
- currentResult.usage.costOutput = addUsageValue(
549
- currentResult.usage.costOutput ?? 0,
550
- protocolUsageCost(cost?.output),
551
- );
552
- currentResult.usage.costCacheRead = addUsageValue(
553
- currentResult.usage.costCacheRead ?? 0,
554
- protocolUsageCost(cost?.cacheRead),
555
- );
556
- currentResult.usage.costCacheWrite = addUsageValue(
557
- currentResult.usage.costCacheWrite ?? 0,
558
- protocolUsageCost(cost?.cacheWrite),
559
- );
560
- currentResult.usage.totalTokens = addUsageValue(
561
- currentResult.usage.totalTokens ?? 0,
562
- turnTotal,
563
- );
564
- currentResult.usage.contextTokens = turnTotal;
565
- }
566
- if (typeof msg.provider === "string") currentResult.actualProvider = msg.provider;
567
- const actualModel =
568
- typeof msg.responseModel === "string"
569
- ? msg.responseModel
570
- : typeof msg.model === "string"
571
- ? msg.model
572
- : undefined;
573
- if (actualModel) currentResult.actualModel = actualModel;
574
- if (typeof msg.stopReason === "string") currentResult.stopReason = msg.stopReason;
575
- if (typeof msg.errorMessage === "string") setErrorMessage(msg.errorMessage);
576
- }
577
- emitUpdate();
578
- } else if (event.type === "tool_result_end" && event.message) {
579
- journalMessages(progressJournal, [event.message]);
580
- budgetMonitor?.recordActivity();
581
- addMessage(event.message);
582
- emitUpdate();
583
- }
584
- };
585
- const decoder = new JsonLineDecoder({
586
- onValue: processEvent,
587
- onMalformed: () => {
588
- currentResult.malformedEvents = (currentResult.malformedEvents ?? 0) + 1;
589
- },
590
- onOversized: () => {
591
- currentResult.truncated = true;
592
- },
593
- });
594
- const beginTermination = (exitCode: number) => {
595
- if (cleanupTermination || settled) return;
596
- cleanupTermination = terminateProcess(proc);
597
- terminationDeadline = setTimeout(() => {
598
- decoder.finish();
599
- proc.stdin?.destroy();
600
- proc.stdout?.destroy();
601
- proc.stderr?.destroy();
602
- finish(exitCode);
603
- }, KILL_GRACE_MS + 1_000);
604
- };
605
- const stopForBudget = (
606
- stop: TurnBudgetStop | { reason: "work_timeout" | "orchestration_timeout"; limit: number },
607
- ) => {
608
- if (budgetStop || settled || wasAborted) return;
609
- budgetStop = stop;
610
- timedOut = stop.reason.endsWith("timeout");
611
- currentResult.timedOut = timedOut || undefined;
612
- currentResult.stopReason = timedOut ? "timeout" : "limit";
613
- const message = formatTurnTerminationMessage(stop.reason, stop.limit);
614
- setErrorMessage(message);
615
- const bounded = appendBounded(
616
- currentResult.stderr,
617
- `\n${message}.`,
618
- DEFAULT_MAX_STDERR_BYTES,
619
- );
620
- currentResult.stderr = bounded.text;
621
- currentResult.truncated ||= bounded.truncated;
622
- emitUpdate();
623
- beginTermination(124);
624
- };
625
- budgetMonitor = new TurnBudgetMonitor({
626
- ...launchPolicy?.turnLimits,
627
- onExceeded: stopForBudget,
628
- });
629
-
630
- proc.once("spawn", () => {
631
- currentResult.processStarted = true;
632
- if (settled || budgetStop || wasAborted) return;
633
- timeout = setTimeout(() => {
634
- stopForBudget({
635
- reason: launchPolicy?.workTimeoutReason ?? "work_timeout",
636
- limit: launchPolicy?.workTimeoutReportLimit ?? timeoutMs,
637
- });
638
- }, timeoutMs);
639
- timeout.unref();
640
- });
641
- proc.stdout?.on("data", (data) => decoder.push(data));
642
- proc.stderr?.on("data", (data) => {
643
- const bounded = appendBounded(
644
- currentResult.stderr,
645
- data.toString(),
646
- DEFAULT_MAX_STDERR_BYTES,
647
- );
648
- currentResult.stderr = bounded.text;
649
- currentResult.truncated ||= bounded.truncated;
650
- });
651
- proc.on("close", (code) => {
652
- decoder.finish();
653
- finish(budgetStop ? 124 : wasAborted ? 130 : (code ?? 0));
654
- });
655
- proc.on("error", (error) => {
656
- currentResult.launchFailed = currentResult.processStarted ? undefined : true;
657
- const message = setErrorMessage(error.message);
658
- const bounded = appendBounded(
659
- currentResult.stderr,
660
- `${currentResult.stderr ? "\n" : ""}${message}`,
661
- DEFAULT_MAX_STDERR_BYTES,
662
- );
663
- currentResult.stderr = bounded.text;
664
- currentResult.truncated ||= bounded.truncated;
665
- if (currentResult.processStarted) beginTermination(1);
666
- else finish(1);
667
- });
668
-
669
- if (signal) {
670
- abortHandler = () => {
671
- if (budgetStop || settled) return;
672
- wasAborted = true;
673
- currentResult.aborted = true;
674
- currentResult.stopReason = "aborted";
675
- setErrorMessage("Subagent was aborted");
676
- beginTermination(130);
677
- };
678
- if (signal.aborted) abortHandler();
679
- else signal.addEventListener("abort", abortHandler, { once: true });
680
- }
681
- });
682
-
683
- if (signal?.aborted && budgetStop) {
684
- budgetStop = undefined;
685
- timedOut = false;
686
- currentResult.timedOut = undefined;
687
- currentResult.aborted = true;
688
- currentResult.stopReason = "aborted";
689
- setErrorMessage("Subagent was aborted");
690
- }
691
- currentResult.exitCode = currentResult.aborted ? 130 : exitCode;
692
- const final = truncateUtf8(selectedAssistantOutput(), DEFAULT_MAX_OUTPUT_BYTES);
693
- currentResult.finalOutput = final.text;
694
- currentResult.truncated ||= final.truncated;
695
- if (budgetStop) {
696
- currentResult.partialOutput = currentResult.finalOutput || undefined;
697
- currentResult.termination = {
698
- version: TURN_TERMINATION_VERSION,
699
- reason: budgetStop.reason,
700
- limit: budgetStop.limit,
701
- checkpoint: progressJournal.checkpoint(task, currentResult.partialOutput),
702
- finalization: { attempted: false, status: "skipped", durationMs: 0 },
703
- };
704
- }
705
- const remainingFinalizationMs = launchPolicy?.orchestrationDeadlineAt
706
- ? Math.floor(launchPolicy.orchestrationDeadlineAt - Date.now())
707
- : undefined;
708
- if (
709
- budgetStop &&
710
- budgetStop.reason !== "orchestration_timeout" &&
711
- launchPolicy?.finalizeOnTimeout !== false &&
712
- !signal?.aborted &&
713
- (remainingFinalizationMs === undefined || remainingFinalizationMs > 0)
714
- ) {
715
- const finalizationStartedAt = Date.now();
716
- const requestedFinalizationMs = resolveTimeoutFinalizationMs(
717
- timeoutMs,
718
- launchPolicy?.timeoutFinalizationMs,
719
- );
720
- const finalizationMs = Math.min(
721
- requestedFinalizationMs,
722
- remainingFinalizationMs ?? requestedFinalizationMs,
723
- );
724
- const summary = await runSingleAgent(
725
- defaultCwd,
726
- agents,
727
- agentName,
728
- buildTimeoutFinalizationPrompt({
729
- task,
730
- partialOutput: currentResult.partialOutput,
731
- recentActivity: currentResult.recentActivity,
732
- checkpoint: currentResult.termination?.checkpoint,
733
- terminationReason: budgetStop.reason,
734
- resultFormat: launchPolicy?.timeoutResultFormat,
735
- }),
736
- cwd,
737
- step,
738
- signal,
739
- thinkingLevel,
740
- finalizationMs,
741
- undefined,
742
- makeDetails,
743
- invocationOverride,
744
- {
745
- ...launchPolicy,
746
- tools: [],
747
- disableExtensions: true,
748
- disableSkills: true,
749
- disablePromptTemplates: true,
750
- disableContextFiles: true,
751
- appendSystemPromptPaths: undefined,
752
- finalizeOnTimeout: false,
753
- turnLimits: undefined,
754
- workTimeoutReason: "work_timeout",
755
- workTimeoutReportLimit: finalizationMs,
756
- orchestrationDeadlineAt: undefined,
757
- },
758
- );
759
- mergeUsageStats(currentResult.usage, summary.usage);
760
- const summaryOutput = getResultFinalOutput(summary).trim();
761
- if (summary.exitCode === 0 && summaryOutput) {
762
- currentResult.timeoutSummary = summaryOutput;
763
- currentResult.finalOutput = summaryOutput;
764
- if (currentResult.termination) {
765
- currentResult.termination.finalization = {
766
- attempted: true,
767
- status: "completed",
768
- durationMs: Date.now() - finalizationStartedAt,
769
- };
770
- }
771
- } else {
772
- currentResult.timeoutSummaryError =
773
- summary.errorMessage || summary.stderr.trim() || "Summary produced no final text";
774
- if (currentResult.termination) {
775
- currentResult.termination.finalization = {
776
- attempted: true,
777
- status: summary.timedOut ? "timed_out" : "failed",
778
- durationMs: Date.now() - finalizationStartedAt,
779
- error: currentResult.timeoutSummaryError,
780
- };
781
- }
782
- }
783
- currentResult.truncated ||= summary.truncated;
784
- }
785
- if (currentResult.termination && !currentResult.finalOutput.trim()) {
786
- currentResult.finalOutput = formatTimeoutCheckpoint(currentResult.termination.checkpoint);
787
- }
788
- if (currentResult.exitCode === 0 && launchPolicy?.resultFormat !== undefined) {
789
- currentResult.structuredResult = parseAnyStructuredSubagentResult(
790
- currentResult.finalOutput ?? "",
791
- launchPolicy.resultFormat,
792
- );
793
- currentResult.resultContractInvalid =
794
- launchPolicy.resultFormat !== "text" && currentResult.structuredResult === undefined;
795
- if (
796
- currentResult.structuredResult?.version === "pi-subagents:result:v2" &&
797
- launchPolicy.executionPlan
798
- ) {
799
- currentResult.structuredResult.provenance = {
800
- ...currentResult.structuredResult.provenance,
801
- ...(launchPolicy.executionPlan.taskId
802
- ? { taskId: launchPolicy.executionPlan.taskId }
803
- : {}),
804
- taskGeneration: launchPolicy.executionPlan.taskGeneration,
805
- executionPlanId: launchPolicy.executionPlan.id,
806
- cancellationLineage: [...launchPolicy.executionPlan.cancellationLineage],
807
- };
808
- }
809
- if (currentResult.structuredResult?.version === "pi-subagents:result:v2") {
810
- currentResult.outcome = classifyStructuredOutcome(
811
- currentResult.structuredResult.status,
812
- currentResult.structuredResult.reasonCode,
813
- );
814
- } else if (currentResult.resultContractInvalid) {
815
- currentResult.outcome = classifyStructuredOutcome(
816
- "contract-invalid",
817
- "malformed-structured-result",
818
- );
819
- }
820
- }
821
- if (
822
- currentResult.exitCode === 0 &&
823
- currentResult.stopReason !== "error" &&
824
- (currentResult.stopReason === "toolUse" || !currentResult.finalOutput.trim())
825
- ) {
826
- currentResult.exitCode = 1;
827
- currentResult.stopReason = "error";
828
- setErrorMessage("Subagent completed without final text");
829
- }
830
- if (currentResult.capabilityGrant?.state === "active") {
831
- currentResult.capabilityGrant = revokeCapabilityGrant(
832
- currentResult.capabilityGrant,
833
- "turn-settled",
834
- Date.now(),
835
- );
836
- }
837
- currentResult.policy = {
838
- inherited: ["environment"],
839
- overridden: [
840
- "cwd",
841
- ...(agent.model ? ["model"] : []),
842
- ...(thinkingLevel ? ["thinkingLevel"] : []),
843
- ...(effectiveTools !== undefined ? ["tools"] : []),
844
- ...(launchPolicy?.disableExtensions ? ["extensions"] : []),
845
- ...(launchPolicy?.disableSkills ? ["skills"] : []),
846
- ...(launchPolicy?.disablePromptTemplates ? ["promptTemplates"] : []),
847
- ...(launchPolicy?.disableContextFiles ? ["contextFiles"] : []),
848
- ],
849
- unsupported: ["approvalPolicy", "sandboxProfile", "providerHeaders"],
850
- };
851
- return currentResult;
852
- } finally {
853
- for (const temporary of temporaryPrompts.reverse()) {
854
- try {
855
- fs.unlinkSync(temporary.filePath);
856
- } catch {
857
- /* ignore */
858
- }
859
- try {
860
- fs.rmdirSync(temporary.dir);
861
- } catch {
862
- /* ignore */
863
- }
864
- }
865
- }
866
- }