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