@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
@@ -1,1222 +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
- JsonLineDecoder,
5
- terminateProcess
6
- } from "./chunk-6H6TBBED.ts";
7
- import {
8
- resolvePiInvocation
9
- } from "./chunk-IGAMVWFN.ts";
10
- import {
11
- buildStatefulTurnPrompt,
12
- resolveStatefulTurnTimeout
13
- } from "./chunk-PGLSFLYW.ts";
14
- import {
15
- buildCurrentTurnPrompt,
16
- validateInProcessTools
17
- } from "./chunk-LL4LP2T7.ts";
18
- import {
19
- CHILD_PEER_TOOL_NAMES,
20
- childPeerBridgePath,
21
- peerBridgeEnvironment
22
- } from "./chunk-RY2AEGMZ.ts";
23
- import {
24
- resolvePiPromptResources
25
- } from "./chunk-G6VZTCFH.ts";
26
- import {
27
- buildTimeoutFinalizationPrompt,
28
- resolveTimeoutFinalizationMs
29
- } from "./chunk-NTRPLF46.ts";
30
- import {
31
- TURN_TERMINATION_VERSION,
32
- TimeoutProgressJournal,
33
- formatTimeoutCheckpoint,
34
- formatTurnTerminationMessage,
35
- journalMessages
36
- } from "./chunk-RTCVYIZA.ts";
37
- import {
38
- TurnBudgetMonitor
39
- } from "./chunk-ONDTY4EL.ts";
40
- import {
41
- formatPeerMessage
42
- } from "./chunk-5DGRMKNV.ts";
43
- import {
44
- discoverAgents
45
- } from "./chunk-LASD73CM.ts";
46
- import "./chunk-RSUXZD6S.ts";
47
- import "./chunk-D4CR7T73.ts";
48
- import {
49
- readSubagentSettings
50
- } from "./chunk-TMZRHIIK.ts";
51
- import "./chunk-VDG7LTYE.ts";
52
- import "./chunk-4AQSF7AS.ts";
53
- import {
54
- PI_SUBAGENTS_RPC_PROTOCOL,
55
- emptyTransportUsage
56
- } from "./chunk-LEOYDZI3.ts";
57
- import {
58
- boundedPrivateText,
59
- safeTerminalText
60
- } from "./chunk-SWGQLFSD.ts";
61
- import "./chunk-JSZIP73U.ts";
62
- import {
63
- DEFAULT_MAX_OUTPUT_BYTES,
64
- DEFAULT_MAX_STDERR_BYTES,
65
- appendBounded,
66
- truncateUtf8
67
- } from "./chunk-H3FP6DLR.ts";
68
- import "./chunk-RRR66UWR.ts";
69
-
70
- // src/rpc-transport.ts
71
- import { spawn } from "node:child_process";
72
- import * as fs from "node:fs";
73
- import * as os from "node:os";
74
- import * as path from "node:path";
75
-
76
- // src/rpc-timeout-finalization.ts
77
- async function finalizeTimedOutRpcTurn(options) {
78
- options.resetCapture();
79
- let settleResolve;
80
- let settleReject;
81
- const settled = new Promise((resolve, reject) => {
82
- settleResolve = resolve;
83
- settleReject = reject;
84
- });
85
- void settled.catch(() => void 0);
86
- const unsubscribeEvent = options.client.onEvent((event) => {
87
- if (eventType(event) === "agent_settled") settleResolve();
88
- });
89
- const unsubscribeClose = options.client.onClose(settleReject);
90
- let error;
91
- try {
92
- const finalizationMs = resolveTimeoutFinalizationMs(
93
- options.workTimeoutMs,
94
- options.finalizationTimeoutMs
95
- );
96
- const deadline = Date.now() + finalizationMs;
97
- await raceWithAbort(
98
- () => options.client.prompt(
99
- buildTimeoutFinalizationPrompt({
100
- task: options.task,
101
- partialOutput: options.partialOutput,
102
- checkpoint: options.checkpoint,
103
- terminationReason: options.terminationReason,
104
- resultFormat: options.resultFormat
105
- }),
106
- remainingMs(deadline)
107
- ),
108
- options.signal,
109
- remainingMs(deadline)
110
- );
111
- const settlement = await waitForSettlement(settled, options.signal, remainingMs(deadline));
112
- if (settlement !== "settled") {
113
- const [abortCompleted, stopped] = await Promise.all([
114
- settlesWithin(options.client.abort(), options.abortGraceMs),
115
- settlesWithin(settled, options.abortGraceMs)
116
- ]);
117
- if (!stopped) await boundedRelease(options);
118
- error = [
119
- `timeout summary ${settlement}`,
120
- abortCompleted ? void 0 : "summary abort command did not settle"
121
- ].filter(Boolean).join("; ");
122
- }
123
- } catch (caught) {
124
- error = boundedError(caught);
125
- await boundedRelease(options);
126
- } finally {
127
- unsubscribeEvent();
128
- unsubscribeClose();
129
- }
130
- const capture = options.getCapture();
131
- const output = truncateUtf8(capture.output || capture.partial, DEFAULT_MAX_OUTPUT_BYTES);
132
- if (!error && (capture.stopReason === "error" || !output.text.trim())) {
133
- error = capture.error || "Timeout summary produced no final text";
134
- }
135
- return {
136
- output: output.text,
137
- truncated: output.truncated,
138
- status: error ? /timed out|timeout/iu.test(error) ? "timed_out" : "failed" : "completed",
139
- error
140
- };
141
- }
142
- function eventType(value) {
143
- return value && typeof value === "object" && typeof value.type === "string" ? value.type ?? void 0 : void 0;
144
- }
145
- function remainingMs(deadline) {
146
- return Math.max(1, deadline - Date.now());
147
- }
148
- async function raceWithAbort(start, signal, timeoutMs) {
149
- if (signal.aborted) throw abortError();
150
- let onAbort;
151
- let timer;
152
- const aborted = new Promise((_resolve, reject) => {
153
- onAbort = () => reject(abortError());
154
- signal.addEventListener("abort", onAbort, { once: true });
155
- if (signal.aborted) onAbort();
156
- });
157
- const timedOut = new Promise((_resolve, reject) => {
158
- timer = setTimeout(() => reject(new Error("RPC timeout summary prompt timed out")), timeoutMs);
159
- });
160
- try {
161
- return await Promise.race([start(), aborted, timedOut]);
162
- } finally {
163
- if (timer) clearTimeout(timer);
164
- if (onAbort) signal.removeEventListener("abort", onAbort);
165
- }
166
- }
167
- async function waitForSettlement(settled, signal, timeoutMs) {
168
- if (signal.aborted) return "aborted";
169
- let timer;
170
- let onAbort;
171
- try {
172
- return await Promise.race([
173
- settled.then(() => "settled"),
174
- new Promise((resolve) => {
175
- onAbort = () => resolve("aborted");
176
- signal.addEventListener("abort", onAbort, { once: true });
177
- }),
178
- new Promise((resolve) => {
179
- timer = setTimeout(() => resolve("timeout"), timeoutMs);
180
- })
181
- ]);
182
- } finally {
183
- if (timer) clearTimeout(timer);
184
- if (onAbort) signal.removeEventListener("abort", onAbort);
185
- }
186
- }
187
- async function boundedRelease(options) {
188
- return settlesWithin(options.release(), options.abortGraceMs + 1e3);
189
- }
190
- async function settlesWithin(settled, timeoutMs) {
191
- let timer;
192
- try {
193
- return await Promise.race([
194
- settled.then(
195
- () => true,
196
- () => true
197
- ),
198
- new Promise((resolve) => {
199
- timer = setTimeout(() => resolve(false), timeoutMs);
200
- })
201
- ]);
202
- } finally {
203
- if (timer) clearTimeout(timer);
204
- }
205
- }
206
- function abortError() {
207
- const error = new Error("RPC timeout summary aborted");
208
- error.name = "AbortError";
209
- return error;
210
- }
211
- function boundedError(error) {
212
- return truncateUtf8(error instanceof Error ? error.message : String(error), 16 * 1024).text;
213
- }
214
-
215
- // src/rpc-transport-metadata.ts
216
- function modelIdentity(value) {
217
- if (!value || typeof value !== "object") return {};
218
- const model = value;
219
- return {
220
- provider: typeof model.provider === "string" ? boundedPrivateText(model.provider, 256) : void 0,
221
- model: typeof model.id === "string" ? boundedPrivateText(model.id, 256) : void 0
222
- };
223
- }
224
- function normalizeThinking(value) {
225
- return typeof value === "string" && ["off", "minimal", "low", "medium", "high", "xhigh", "max"].includes(value) ? value : void 0;
226
- }
227
- function rpcPolicy(config, agent) {
228
- return {
229
- inherited: ["environment", "cwdResources"],
230
- overridden: [
231
- "cwd",
232
- "extensions",
233
- ...config.model ? ["model"] : [],
234
- ...agent.thinkingLevel || config.thinkingLevel ? ["thinkingLevel"] : [],
235
- ...config.tools ? ["tools"] : []
236
- ],
237
- unsupported: ["approvalPolicy", "sandboxProfile", "providerHeaders", "extensionState"]
238
- };
239
- }
240
- function interruptedRpcOutcome(output, telemetry, failurePhase) {
241
- return {
242
- output,
243
- exitCode: 130,
244
- aborted: true,
245
- error: "RPC subagent was aborted",
246
- telemetry: {
247
- ...telemetry,
248
- phase: "interrupted",
249
- failurePhase,
250
- updatedAt: Date.now()
251
- }
252
- };
253
- }
254
- function boundedError2(error) {
255
- return boundedPrivateText(
256
- error instanceof Error ? error.message : String(error),
257
- DEFAULT_MAX_OUTPUT_BYTES
258
- );
259
- }
260
-
261
- // src/rpc-turn-capture.ts
262
- function createRpcTurnCapture() {
263
- return {
264
- output: "",
265
- partial: "",
266
- usage: emptyTransportUsage(),
267
- journal: new TimeoutProgressJournal()
268
- };
269
- }
270
- function captureRpcEvent(event, capture) {
271
- if (!isRecord(event)) return false;
272
- const previousUsage = snapshotRpcUsage(capture);
273
- if (event.type === "tool_execution_start") {
274
- capture.journal.recordToolCall(
275
- typeof event.toolCallId === "string" ? event.toolCallId : "",
276
- typeof event.toolName === "string" ? event.toolName : "tool",
277
- isRecord(event.args) ? event.args : {}
278
- );
279
- }
280
- if (event.type === "tool_execution_end") {
281
- const result = isRecord(event.result) ? event.result : {};
282
- capture.journal.recordToolResult(
283
- typeof event.toolCallId === "string" ? event.toolCallId : "",
284
- typeof event.toolName === "string" ? event.toolName : "tool",
285
- { content: result.content, isError: event.isError }
286
- );
287
- }
288
- if (event.type === "message_start" && isRecord(event.message)) {
289
- if (event.message.role === "assistant") commitRpcInFlightUsage(capture);
290
- }
291
- if (event.type === "message_update") {
292
- const usage = normalizeUsage(event.usage);
293
- if (usage) capture.inFlightUsage = usage;
294
- const delta = event.assistantMessageEvent;
295
- if (isRecord(delta) && delta.type === "text_delta" && typeof delta.delta === "string") {
296
- capture.partial = truncateUtf8(
297
- `${capture.partial}${delta.delta}`,
298
- DEFAULT_MAX_OUTPUT_BYTES
299
- ).text;
300
- }
301
- }
302
- if (event.type === "message_end" && isRecord(event.message)) {
303
- const candidate = event.message;
304
- if (candidate.role !== "toolResult") journalMessages(capture.journal, [candidate]);
305
- if (candidate.role === "assistant") captureAssistantEnd(candidate, capture);
306
- }
307
- return !sameUsage(previousUsage, snapshotRpcUsage(capture));
308
- }
309
- function snapshotRpcUsage(capture) {
310
- const usage = { ...capture.usage };
311
- if (capture.inFlightUsage) addUsage(usage, capture.inFlightUsage);
312
- return usage;
313
- }
314
- function commitRpcInFlightUsage(capture) {
315
- if (!capture.inFlightUsage) return false;
316
- addUsage(capture.usage, capture.inFlightUsage);
317
- capture.inFlightUsage = void 0;
318
- return true;
319
- }
320
- function captureAssistantEnd(candidate, capture) {
321
- capture.output = truncateUtf8(
322
- assistantText(candidate.content) || capture.partial,
323
- DEFAULT_MAX_OUTPUT_BYTES
324
- ).text;
325
- capture.partial = capture.output;
326
- capture.stopReason = typeof candidate.stopReason === "string" ? candidate.stopReason : void 0;
327
- capture.error = typeof candidate.errorMessage === "string" ? boundedPrivateText(candidate.errorMessage, 4 * 1024) : void 0;
328
- capture.provider = typeof candidate.provider === "string" ? boundedPrivateText(candidate.provider, 256) : void 0;
329
- const responseModel = typeof candidate.responseModel === "string" ? candidate.responseModel : typeof candidate.model === "string" ? candidate.model : void 0;
330
- capture.model = responseModel ? boundedPrivateText(responseModel, 256) : void 0;
331
- const finalUsage = normalizeUsage(candidate.usage);
332
- const completedUsage = finalUsage ?? capture.inFlightUsage;
333
- if (completedUsage) addUsage(capture.usage, completedUsage);
334
- capture.inFlightUsage = void 0;
335
- capture.usage.turns = addUsageValue(capture.usage.turns, 1);
336
- }
337
- function observeRpcBudgetEvent(event, monitor) {
338
- if (!isRecord(event)) return;
339
- if (event.type === "tool_execution_end") monitor.recordActivity();
340
- if (event.type !== "message_end" || !isRecord(event.message)) return;
341
- const message = event.message;
342
- if (message.role === "toolResult") {
343
- monitor.recordActivity();
344
- return;
345
- }
346
- if (message.role !== "assistant") return;
347
- monitor.recordToolCalls(assistantToolCallCount(message.content));
348
- monitor.recordAssistantTurn(
349
- typeof message.stopReason === "string" ? message.stopReason : void 0
350
- );
351
- }
352
- function assistantToolCallCount(content) {
353
- if (!Array.isArray(content)) return 0;
354
- return content.filter((part) => isRecord(part) && part.type === "toolCall").length;
355
- }
356
- function normalizeUsage(value) {
357
- if (!isRecord(value)) return void 0;
358
- const input = safeNonNegative(value.input);
359
- const output = safeNonNegative(value.output);
360
- const cacheRead = safeNonNegative(value.cacheRead);
361
- const cacheWrite = safeNonNegative(value.cacheWrite);
362
- const reportedTotal = safeNonNegative(value.totalTokens);
363
- const cost = isRecord(value.cost) ? safeNonNegative(value.cost.total) : void 0;
364
- if (input === void 0 && output === void 0 && cacheRead === void 0 && cacheWrite === void 0 && reportedTotal === void 0 && cost === void 0) {
365
- return void 0;
366
- }
367
- const components = [input, output, cacheRead, cacheWrite].reduce(
368
- (total, current) => addUsageValue(total, current ?? 0),
369
- 0
370
- );
371
- return {
372
- input: input ?? 0,
373
- output: output ?? 0,
374
- cacheRead: cacheRead ?? 0,
375
- cacheWrite: cacheWrite ?? 0,
376
- totalTokens: reportedTotal ?? components,
377
- cost: cost ?? 0,
378
- turns: 0
379
- };
380
- }
381
- function addUsage(target, value) {
382
- for (const key of [
383
- "input",
384
- "output",
385
- "cacheRead",
386
- "cacheWrite",
387
- "totalTokens",
388
- "cost",
389
- "turns"
390
- ]) {
391
- target[key] = addUsageValue(target[key], value[key]);
392
- }
393
- }
394
- function addUsageValue(current, addition) {
395
- return Math.min(Number.MAX_SAFE_INTEGER, current + addition);
396
- }
397
- function safeNonNegative(value) {
398
- return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER ? value : void 0;
399
- }
400
- function sameUsage(left, right) {
401
- return left.input === right.input && left.output === right.output && left.cacheRead === right.cacheRead && left.cacheWrite === right.cacheWrite && left.totalTokens === right.totalTokens && left.cost === right.cost && left.turns === right.turns;
402
- }
403
- function assistantText(value) {
404
- if (typeof value === "string") return value;
405
- if (!Array.isArray(value)) return "";
406
- return value.flatMap((part) => {
407
- if (!isRecord(part)) return [];
408
- return part.type === "text" && typeof part.text === "string" ? [part.text] : [];
409
- }).join("\n");
410
- }
411
- function isRecord(value) {
412
- return Boolean(value && typeof value === "object" && !Array.isArray(value));
413
- }
414
-
415
- // src/rpc-transport.ts
416
- var COMMAND_TIMEOUT_MS = 3e4;
417
- var STARTUP_TIMEOUT_MS = 3e4;
418
- var ABORT_GRACE_MS = 5e3;
419
- var BUILT_IN_TOOL_NAMES = /* @__PURE__ */ new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]);
420
- var RpcProtocolClient = class {
421
- constructor(options) {
422
- this.options = options;
423
- }
424
- options;
425
- process;
426
- processClosed = false;
427
- decoder;
428
- pending = /* @__PURE__ */ new Map();
429
- listeners = /* @__PURE__ */ new Set();
430
- closeListeners = /* @__PURE__ */ new Set();
431
- nextRequestId = 0;
432
- stderr = "";
433
- malformedLines = 0;
434
- oversizedLines = 0;
435
- closedError;
436
- closePromise;
437
- cleanupTermination;
438
- async start(signal) {
439
- if (this.process) throw new Error("RPC subagent client already started");
440
- if (signal?.aborted) throw abortError2("RPC subagent start aborted");
441
- const invocation = this.options.invocation ? {
442
- command: this.options.invocation.command,
443
- args: [...this.options.invocation.args, ...this.options.args]
444
- } : resolvePiInvocation(this.options.args);
445
- const proc = spawn(invocation.command, invocation.args, {
446
- cwd: this.options.cwd,
447
- detached: process.platform !== "win32",
448
- shell: false,
449
- stdio: ["pipe", "pipe", "pipe"],
450
- env: { ...process.env, ...this.options.env }
451
- });
452
- this.process = proc;
453
- this.processClosed = false;
454
- this.decoder = new JsonLineDecoder({
455
- onValue: (value) => this.handleValue(value),
456
- onMalformed: () => {
457
- this.malformedLines++;
458
- this.fail(new Error("RPC subagent emitted malformed JSONL"));
459
- },
460
- onOversized: () => {
461
- this.oversizedLines++;
462
- this.fail(new Error("RPC subagent emitted an oversized JSONL record"));
463
- }
464
- });
465
- proc.stdout?.on("data", (chunk) => this.decoder?.push(chunk));
466
- proc.stdin?.on("error", (error) => this.fail(errorMessage("RPC stdin failed", error)));
467
- proc.stderr?.on("data", (chunk) => {
468
- this.stderr = appendBounded(
469
- this.stderr,
470
- Buffer.isBuffer(chunk) ? chunk.toString("utf8") : String(chunk),
471
- DEFAULT_MAX_STDERR_BYTES
472
- ).text;
473
- });
474
- proc.once("error", (error) => this.fail(errorMessage("RPC process failed", error)));
475
- proc.once("close", (code, childSignal) => {
476
- this.processClosed = true;
477
- this.decoder?.finish();
478
- this.fail(
479
- new Error(
480
- `RPC subagent exited (code=${code ?? "null"}, signal=${childSignal ?? "null"})${this.stderr ? `: ${safeTerminalText(this.stderr)}` : ""}`
481
- )
482
- );
483
- });
484
- try {
485
- await waitForSpawn(proc, signal, this.options.startupTimeoutMs ?? STARTUP_TIMEOUT_MS);
486
- if (signal?.aborted) throw abortError2("RPC subagent start aborted");
487
- const state = await raceWithAbort2(
488
- this.requestData(
489
- { type: "get_state" },
490
- this.options.startupTimeoutMs ?? STARTUP_TIMEOUT_MS
491
- ),
492
- signal,
493
- "RPC subagent readiness aborted"
494
- );
495
- return {
496
- state,
497
- stderr: this.stderr,
498
- malformedLines: this.malformedLines,
499
- oversizedLines: this.oversizedLines
500
- };
501
- } catch (error) {
502
- await this.stop();
503
- throw error;
504
- }
505
- }
506
- onEvent(listener) {
507
- this.listeners.add(listener);
508
- return () => this.listeners.delete(listener);
509
- }
510
- onClose(listener) {
511
- this.closeListeners.add(listener);
512
- return () => this.closeListeners.delete(listener);
513
- }
514
- async prompt(message, timeoutMs) {
515
- await this.request({ type: "prompt", message }, timeoutMs);
516
- }
517
- async steer(message, timeoutMs) {
518
- await this.request({ type: "steer", message }, timeoutMs);
519
- }
520
- async abort() {
521
- await this.request(
522
- { type: "abort" },
523
- this.options.abortTimeoutMs ?? Math.min(COMMAND_TIMEOUT_MS, ABORT_GRACE_MS)
524
- );
525
- }
526
- async getState() {
527
- return this.requestData({ type: "get_state" });
528
- }
529
- getStderr() {
530
- return this.stderr;
531
- }
532
- async stop() {
533
- if (this.closePromise) return this.closePromise;
534
- const proc = this.process;
535
- if (!proc) return;
536
- if (this.processClosed) {
537
- this.cleanupTermination?.();
538
- this.cleanupTermination = void 0;
539
- this.process = void 0;
540
- this.rejectPending(this.closedError ?? new Error("RPC subagent process already exited"));
541
- this.listeners.clear();
542
- this.closeListeners.clear();
543
- return;
544
- }
545
- this.closePromise = new Promise((resolve) => {
546
- let settled = false;
547
- let terminationDeadline;
548
- const finish = () => {
549
- if (settled) return;
550
- settled = true;
551
- if (terminationDeadline) clearTimeout(terminationDeadline);
552
- proc.off("close", finish);
553
- this.cleanupTermination?.();
554
- this.cleanupTermination = void 0;
555
- resolve();
556
- };
557
- proc.once("close", finish);
558
- try {
559
- proc.stdin?.end();
560
- } catch {
561
- }
562
- const graceMs = this.options.terminationGraceMs ?? ABORT_GRACE_MS;
563
- this.cleanupTermination?.();
564
- this.cleanupTermination = terminateProcess(proc, graceMs);
565
- terminationDeadline = setTimeout(() => {
566
- proc.stdin?.destroy();
567
- proc.stdout?.destroy();
568
- proc.stderr?.destroy();
569
- finish();
570
- }, graceMs + 1e3);
571
- });
572
- await this.closePromise;
573
- this.process = void 0;
574
- this.rejectPending(new Error("RPC subagent client stopped"));
575
- this.listeners.clear();
576
- this.closeListeners.clear();
577
- }
578
- async requestData(command, timeoutMs = this.options.commandTimeoutMs ?? COMMAND_TIMEOUT_MS) {
579
- const response = await this.request(command, timeoutMs);
580
- return response.data;
581
- }
582
- request(command, timeoutMs = this.options.commandTimeoutMs ?? COMMAND_TIMEOUT_MS) {
583
- const proc = this.process;
584
- if (!proc?.stdin || proc.stdin.destroyed || !proc.stdin.writable) {
585
- return Promise.reject(this.closedError ?? new Error("RPC subagent stdin is unavailable"));
586
- }
587
- const id = `psa_${++this.nextRequestId}`;
588
- return new Promise((resolve, reject) => {
589
- const timer = setTimeout(() => {
590
- this.pending.delete(id);
591
- reject(rpcTimeoutError(`RPC ${command.type} response timed out after ${timeoutMs}ms`));
592
- }, timeoutMs);
593
- timer.unref();
594
- this.pending.set(id, { command: command.type, resolve, reject, timer });
595
- try {
596
- proc.stdin?.write(`${JSON.stringify({ ...command, id })}
597
- `, (error) => {
598
- if (!error) return;
599
- this.fail(errorMessage("RPC stdin write failed", error));
600
- });
601
- } catch (error) {
602
- this.pending.delete(id);
603
- clearTimeout(timer);
604
- reject(error instanceof Error ? error : new Error(String(error)));
605
- }
606
- }).then((response) => {
607
- if (!response.success) throw new Error(response.error || `RPC ${command.type} failed`);
608
- return response;
609
- });
610
- }
611
- handleValue(value) {
612
- if (!value || typeof value !== "object" || Array.isArray(value)) return;
613
- const event = value;
614
- if (event.type === "response" && typeof event.id === "string") {
615
- const pending = this.pending.get(event.id);
616
- if (!pending) return;
617
- if (typeof event.command !== "string" || event.command !== pending.command) {
618
- this.fail(
619
- new Error(`RPC response command mismatch for ${event.id}: expected ${pending.command}`)
620
- );
621
- return;
622
- }
623
- this.pending.delete(event.id);
624
- clearTimeout(pending.timer);
625
- pending.resolve(event);
626
- return;
627
- }
628
- if (event.type === "extension_ui_request" && typeof event.id === "string") {
629
- this.writeFireAndForget({
630
- type: "extension_ui_response",
631
- id: event.id,
632
- cancelled: true
633
- });
634
- }
635
- for (const listener of this.listeners) listener(value);
636
- }
637
- writeFireAndForget(value) {
638
- try {
639
- this.process?.stdin?.write(`${JSON.stringify(value)}
640
- `);
641
- } catch {
642
- }
643
- }
644
- fail(error) {
645
- if (this.closedError) return;
646
- this.closedError = error;
647
- this.rejectPending(error);
648
- for (const listener of this.closeListeners) listener(error);
649
- if (this.process && !this.closePromise) {
650
- this.cleanupTermination = terminateProcess(
651
- this.process,
652
- this.options.terminationGraceMs ?? ABORT_GRACE_MS
653
- );
654
- }
655
- }
656
- rejectPending(error) {
657
- for (const pending of this.pending.values()) {
658
- clearTimeout(pending.timer);
659
- pending.reject(error);
660
- }
661
- this.pending.clear();
662
- }
663
- };
664
- var RpcTransport = class {
665
- constructor(options) {
666
- this.options = options;
667
- this.createClient = options.createClient ?? ((clientOptions) => new RpcProtocolClient(clientOptions));
668
- }
669
- options;
670
- kind = "rpc";
671
- children = /* @__PURE__ */ new Map();
672
- createClient;
673
- async runTurn(agent, task, signal, onProgress) {
674
- const startedAt = Date.now();
675
- let telemetry = {
676
- transport: "rpc",
677
- protocol: PI_SUBAGENTS_RPC_PROTOCOL,
678
- phase: "starting",
679
- updatedAt: startedAt,
680
- timing: { startedAt, transportStartedAt: startedAt }
681
- };
682
- const publish = (patch) => {
683
- telemetry = {
684
- ...telemetry,
685
- ...patch,
686
- timing: { ...telemetry.timing, ...patch.timing },
687
- usage: patch.usage ? { ...patch.usage } : telemetry.usage,
688
- updatedAt: Date.now()
689
- };
690
- onProgress?.({
691
- ...telemetry,
692
- timing: { ...telemetry.timing },
693
- usage: telemetry.usage ? { ...telemetry.usage } : void 0
694
- });
695
- };
696
- publish({});
697
- if (signal.aborted) return interruptedRpcOutcome("", telemetry, "starting");
698
- const settings = this.options.getSettings ? this.options.getSettings() : readSubagentSettings();
699
- const agentConfig = discoverAgents(agent.cwd, agent.agentScope ?? "user", settings).agents.find(
700
- (candidate) => candidate.name === agent.agent
701
- );
702
- if (!agentConfig) {
703
- publish({ phase: "failed", failurePhase: "starting" });
704
- return { output: "", exitCode: 1, error: `Unknown subagent: ${agent.agent}`, telemetry };
705
- }
706
- const effectiveAgentConfig = {
707
- ...agentConfig,
708
- tools: agent.executionPlan?.effectiveTools ?? agentConfig.tools
709
- };
710
- try {
711
- validateRpcTools(effectiveAgentConfig.tools);
712
- } catch (error) {
713
- publish({ phase: "failed", failurePhase: "starting" });
714
- return { output: "", exitCode: 1, error: boundedError2(error), telemetry };
715
- }
716
- let child;
717
- try {
718
- child = await this.getOrCreate(agent, effectiveAgentConfig, signal);
719
- } catch (error) {
720
- publish({ phase: signal.aborted ? "interrupted" : "failed", failurePhase: "starting" });
721
- return {
722
- output: "",
723
- exitCode: signal.aborted ? 130 : 1,
724
- aborted: signal.aborted,
725
- error: boundedError2(error),
726
- telemetry
727
- };
728
- }
729
- const stateModel = modelIdentity(child.state.model);
730
- publish({
731
- phase: "ready",
732
- provider: stateModel.provider,
733
- model: stateModel.model,
734
- thinkingLevel: normalizeThinking(child.state.thinkingLevel),
735
- timing: { readyAt: Date.now() }
736
- });
737
- if (signal.aborted) {
738
- await this.releaseById(agent.id).catch(() => void 0);
739
- return interruptedRpcOutcome("", telemetry, "ready");
740
- }
741
- const timeoutMs = agent.currentTimeoutMs ?? agent.timeoutMs ?? agentConfig.timeoutMs ?? this.options.defaultTimeoutMs ?? resolveStatefulTurnTimeout(agentConfig);
742
- const capture = createRpcTurnCapture();
743
- let resolveBudget;
744
- let resolvePreAcceptanceIdle;
745
- const budgetExceeded = new Promise((resolve) => {
746
- resolveBudget = resolve;
747
- });
748
- const preAcceptanceIdleExceeded = new Promise((resolve) => {
749
- resolvePreAcceptanceIdle = resolve;
750
- });
751
- const budgetMonitor = new TurnBudgetMonitor({
752
- idleTimeoutMs: agent.currentIdleTimeoutMs ?? agent.idleTimeoutMs,
753
- maxTurns: agent.currentMaxTurns ?? agent.maxTurns,
754
- maxToolCalls: agent.currentMaxToolCalls ?? agent.maxToolCalls,
755
- onExceeded(stop) {
756
- resolveBudget(stop);
757
- if (stop.reason === "idle_timeout") resolvePreAcceptanceIdle(stop);
758
- }
759
- });
760
- let settledResolve;
761
- let settledReject;
762
- const settled = new Promise((resolve, reject) => {
763
- settledResolve = resolve;
764
- settledReject = reject;
765
- });
766
- void settled.catch(() => void 0);
767
- const unsubscribeEvent = child.client.onEvent((event) => {
768
- const usageChanged = captureRpcEvent(event, capture);
769
- observeRpcBudgetEvent(event, budgetMonitor);
770
- if (!capture.firstActivityAt && isActivityEvent(event)) {
771
- capture.firstActivityAt = Date.now();
772
- publish({
773
- phase: "running",
774
- timing: { firstActivityAt: capture.firstActivityAt },
775
- ...usageChanged ? { usage: snapshotRpcUsage(capture) } : {}
776
- });
777
- } else if (usageChanged) {
778
- publish({ usage: snapshotRpcUsage(capture) });
779
- }
780
- const type = eventType2(event);
781
- if (type === "auto_retry_start") publish({ phase: "retrying" });
782
- if (type === "compaction_start" || type === "summarization_retry_attempt_start") {
783
- publish({ phase: "compacting" });
784
- }
785
- if (type === "agent_settled") settledResolve();
786
- });
787
- const unsubscribeClose = child.client.onClose(settledReject);
788
- const prompt = child.started ? buildCurrentTurnPrompt(agent, task) : buildStatefulTurnPrompt(agent, task).text;
789
- let accepted = false;
790
- let preAcceptanceStop;
791
- const deadline = Date.now() + timeoutMs;
792
- try {
793
- await Promise.race([
794
- raceWithAbort2(
795
- child.client.prompt(prompt, remainingMs2(deadline)),
796
- signal,
797
- "RPC subagent prompt acceptance aborted"
798
- ),
799
- preAcceptanceIdleExceeded.then((stop) => {
800
- preAcceptanceStop = stop;
801
- throw new Error(formatTurnTerminationMessage(stop.reason, stop.limit, "RPC subagent"));
802
- })
803
- ]);
804
- accepted = true;
805
- child.started = true;
806
- publish({ phase: "accepted", timing: { promptAcceptedAt: Date.now() } });
807
- const settlement = await Promise.race([
808
- waitForTurnSettlement(settled, signal, remainingMs2(deadline)).then((kind) => ({
809
- kind
810
- })),
811
- budgetExceeded.then((stop) => ({ kind: "limit", stop }))
812
- ]);
813
- if (settlement.kind !== "settled") {
814
- const [, stopped] = await Promise.all([
815
- child.client.abort().catch(() => void 0),
816
- settlesWithin2(settled, this.options.abortGraceMs ?? ABORT_GRACE_MS)
817
- ]);
818
- const partial = truncateUtf8(capture.output || capture.partial, DEFAULT_MAX_OUTPUT_BYTES);
819
- const stop = settlement.kind === "limit" ? settlement.stop : { reason: "work_timeout", limit: timeoutMs };
820
- const explicitAbort = settlement.kind === "aborted" || signal.aborted;
821
- const termination = explicitAbort ? void 0 : {
822
- version: TURN_TERMINATION_VERSION,
823
- reason: stop.reason,
824
- limit: stop.limit,
825
- checkpoint: capture.journal.checkpoint(task, partial.text),
826
- finalization: {
827
- attempted: false,
828
- status: "skipped",
829
- durationMs: 0
830
- }
831
- };
832
- if (explicitAbort || !stopped) {
833
- if (!stopped) await this.releaseById(agent.id);
834
- publish({
835
- phase: explicitAbort ? "interrupted" : "failed",
836
- failurePhase: "running",
837
- timing: { settledAt: Date.now() },
838
- usage: snapshotRpcUsage(capture)
839
- });
840
- const checkpointOutput2 = termination ? formatTimeoutCheckpoint(termination.checkpoint) : partial.text;
841
- return {
842
- output: partial.text || checkpointOutput2,
843
- exitCode: explicitAbort ? 130 : 124,
844
- aborted: explicitAbort,
845
- truncated: partial.truncated || agent.contextTruncated,
846
- error: explicitAbort ? "RPC subagent was aborted" : `${formatTurnTerminationMessage(stop.reason, stop.limit, "RPC subagent")}; abort did not settle`,
847
- policy: rpcPolicy(agentConfig, agent),
848
- termination,
849
- telemetry
850
- };
851
- }
852
- publish({
853
- phase: "finalizing",
854
- failurePhase: "running",
855
- usage: snapshotRpcUsage(capture)
856
- });
857
- const finalizationStartedAt = Date.now();
858
- const summary = await finalizeTimedOutRpcTurn({
859
- client: child.client,
860
- task,
861
- partialOutput: partial.text,
862
- checkpoint: termination?.checkpoint,
863
- terminationReason: stop.reason,
864
- resultFormat: agent.resultFormat,
865
- signal,
866
- workTimeoutMs: timeoutMs,
867
- finalizationTimeoutMs: this.options.timeoutFinalizationMs,
868
- abortGraceMs: this.options.abortGraceMs ?? ABORT_GRACE_MS,
869
- resetCapture() {
870
- commitRpcInFlightUsage(capture);
871
- capture.output = "";
872
- capture.partial = "";
873
- capture.stopReason = void 0;
874
- capture.error = void 0;
875
- },
876
- getCapture: () => capture,
877
- release: () => this.releaseById(agent.id)
878
- });
879
- if (termination) {
880
- termination.finalization = {
881
- attempted: true,
882
- status: summary.status,
883
- durationMs: Date.now() - finalizationStartedAt,
884
- error: summary.error
885
- };
886
- }
887
- publish({
888
- phase: "failed",
889
- failurePhase: "running",
890
- timing: { settledAt: Date.now() },
891
- usage: snapshotRpcUsage(capture)
892
- });
893
- const checkpointOutput = termination ? formatTimeoutCheckpoint(termination.checkpoint) : "";
894
- return {
895
- output: summary.error ? partial.text || checkpointOutput : summary.output,
896
- exitCode: 124,
897
- truncated: partial.truncated || summary.truncated || agent.contextTruncated,
898
- error: [
899
- formatTurnTerminationMessage(stop.reason, stop.limit, "RPC subagent"),
900
- summary.error
901
- ].filter(Boolean).join("; "),
902
- policy: rpcPolicy(agentConfig, agent),
903
- termination,
904
- telemetry
905
- };
906
- }
907
- const output = truncateUtf8(capture.output || capture.partial, DEFAULT_MAX_OUTPUT_BYTES);
908
- const failed = capture.stopReason === "error" || !output.text.trim();
909
- publish({
910
- phase: failed ? "failed" : "settled",
911
- failurePhase: failed ? "running" : void 0,
912
- timing: { settledAt: Date.now() },
913
- provider: capture.provider ?? telemetry.provider,
914
- model: capture.model ?? telemetry.model,
915
- usage: snapshotRpcUsage(capture)
916
- });
917
- return {
918
- output: output.text,
919
- exitCode: failed ? 1 : 0,
920
- truncated: output.truncated || agent.contextTruncated,
921
- error: failed ? capture.error || "RPC subagent completed without final text" : void 0,
922
- policy: rpcPolicy(agentConfig, agent),
923
- telemetry
924
- };
925
- } catch (error) {
926
- await this.releaseById(agent.id).catch(() => void 0);
927
- const timedOut = isTimeoutError(error);
928
- const stop = preAcceptanceStop ?? (timedOut ? { reason: "work_timeout", limit: timeoutMs } : void 0);
929
- const partial = truncateUtf8(capture.output || capture.partial, DEFAULT_MAX_OUTPUT_BYTES);
930
- const termination = stop && !signal.aborted ? {
931
- version: TURN_TERMINATION_VERSION,
932
- reason: stop.reason,
933
- limit: stop.limit,
934
- checkpoint: capture.journal.checkpoint(task, partial.text),
935
- finalization: {
936
- attempted: false,
937
- status: "skipped",
938
- durationMs: 0
939
- }
940
- } : void 0;
941
- publish({
942
- phase: signal.aborted ? "interrupted" : "failed",
943
- failurePhase: accepted ? "running" : "ready",
944
- timing: { settledAt: Date.now() },
945
- usage: snapshotRpcUsage(capture)
946
- });
947
- return {
948
- output: partial.text || (termination ? formatTimeoutCheckpoint(termination.checkpoint) : ""),
949
- exitCode: signal.aborted ? 130 : stop ? 124 : 1,
950
- aborted: signal.aborted,
951
- error: stop ? formatTurnTerminationMessage(stop.reason, stop.limit, "RPC subagent") : boundedError2(error),
952
- policy: rpcPolicy(agentConfig, agent),
953
- termination,
954
- telemetry
955
- };
956
- } finally {
957
- budgetMonitor.dispose();
958
- unsubscribeEvent();
959
- unsubscribeClose();
960
- }
961
- }
962
- async deliverMessage(agent, message) {
963
- const child = this.children.get(agent.id);
964
- if (!child) return false;
965
- await child.client.steer(formatPeerMessage(message));
966
- return true;
967
- }
968
- async release(agent) {
969
- await this.releaseById(agent.id);
970
- }
971
- async shutdown() {
972
- const results = await Promise.allSettled(
973
- [...this.children.keys()].map((agentId) => this.releaseById(agentId))
974
- );
975
- const failures = results.flatMap(
976
- (result) => result.status === "rejected" ? [result.reason] : []
977
- );
978
- if (failures.length > 0) {
979
- throw new AggregateError(failures, `Failed to release ${failures.length} RPC subagent(s)`);
980
- }
981
- }
982
- async getOrCreate(agent, agentConfig, signal) {
983
- const existing = this.children.get(agent.id);
984
- if (existing) return existing;
985
- const hasRolePrompt = agentConfig.systemPrompt.trim().length > 0;
986
- const resources = hasRolePrompt ? await (this.options.resolvePromptResources ?? resolvePiPromptResources)(
987
- agent.cwd,
988
- agent.target?.trust.projectTrusted ?? false
989
- ) : { appendSystemPromptPaths: [] };
990
- if (signal.aborted) throw abortError2("RPC subagent start aborted");
991
- const temporaryPrompt = hasRolePrompt ? await writeRolePrompt(agentConfig.name, agentConfig.systemPrompt) : void 0;
992
- if (signal.aborted) {
993
- cleanupRolePrompt(temporaryPrompt);
994
- throw abortError2("RPC subagent start aborted");
995
- }
996
- let client;
997
- try {
998
- const credentials = this.options.peerRuntime ? await this.options.peerRuntime.issueCredentials(
999
- agent.id,
1000
- agent.currentTurnGeneration ?? agent.turnGeneration ?? 1
1001
- ) : void 0;
1002
- if (signal.aborted) throw abortError2("RPC subagent start aborted");
1003
- client = this.createClient({
1004
- cwd: agent.cwd,
1005
- abortTimeoutMs: this.options.abortGraceMs ?? ABORT_GRACE_MS,
1006
- terminationGraceMs: this.options.abortGraceMs ?? ABORT_GRACE_MS,
1007
- args: buildRpcArgs(
1008
- agent,
1009
- agentConfig,
1010
- this.options.getParentRuntime(),
1011
- temporaryPrompt?.filePath,
1012
- resources.appendSystemPromptPaths,
1013
- credentials !== void 0
1014
- ),
1015
- env: {
1016
- PI_SUBAGENT_DEPTH: String(
1017
- (Number.parseInt(process.env.PI_SUBAGENT_DEPTH ?? "0", 10) || 0) + 1
1018
- ),
1019
- PI_SUBAGENT_RPC_PROTOCOL: PI_SUBAGENTS_RPC_PROTOCOL,
1020
- ...credentials ? peerBridgeEnvironment(credentials) : {}
1021
- }
1022
- });
1023
- const snapshot = await client.start(signal);
1024
- if (signal.aborted) throw abortError2("RPC subagent start aborted");
1025
- const record = {
1026
- client,
1027
- state: snapshot.state,
1028
- started: false,
1029
- temporaryPrompt
1030
- };
1031
- this.children.set(agent.id, record);
1032
- return record;
1033
- } catch (error) {
1034
- await client?.stop().catch(() => void 0);
1035
- this.options.peerRuntime?.revoke(agent.id);
1036
- cleanupRolePrompt(temporaryPrompt);
1037
- throw error;
1038
- }
1039
- }
1040
- async releaseById(agentId) {
1041
- const child = this.children.get(agentId);
1042
- if (!child) return;
1043
- this.children.delete(agentId);
1044
- this.options.peerRuntime?.revoke(agentId);
1045
- try {
1046
- await child.client.abort().catch(() => void 0);
1047
- await child.client.stop();
1048
- } finally {
1049
- cleanupRolePrompt(child.temporaryPrompt);
1050
- }
1051
- }
1052
- };
1053
- function validateRpcTools(tools) {
1054
- const validated = validateInProcessTools(tools);
1055
- if (validated?.some((tool) => !BUILT_IN_TOOL_NAMES.has(tool))) {
1056
- throw new Error("RPC subagents support only built-in Pi tools in pi-subagents:v1");
1057
- }
1058
- return validated;
1059
- }
1060
- function buildRpcArgs(agent, agentConfig, parentRuntime, rolePromptPath, appendSystemPromptPaths = [], peerBridge = false) {
1061
- const args = ["--mode", "rpc", "--no-session", "--no-extensions"];
1062
- if (peerBridge) args.push("-e", childPeerBridgePath());
1063
- const model = agentConfig.model ?? (parentRuntime.model ? `${parentRuntime.model.provider}/${parentRuntime.model.id}` : void 0);
1064
- if (model) args.push("--model", model);
1065
- const modelSelectsThinking = agentConfig.model ? /:(?:off|minimal|low|medium|high|xhigh|max)$/u.test(agentConfig.model.trim()) : false;
1066
- const thinking = agent.thinkingLevel ?? agentConfig.thinkingLevel ?? (modelSelectsThinking ? void 0 : parentRuntime.thinkingLevel);
1067
- if (thinking) args.push("--thinking", thinking);
1068
- if (agent.target?.trust.projectTrusted ?? false) args.push("--approve");
1069
- else args.push("--no-approve");
1070
- if (Array.isArray(agentConfig.tools)) {
1071
- const tools = [...agentConfig.tools, ...peerBridge ? CHILD_PEER_TOOL_NAMES : []];
1072
- if (tools.length > 0) args.push("--tools", [...new Set(tools)].join(","));
1073
- else args.push("--no-tools");
1074
- }
1075
- for (const promptPath of appendSystemPromptPaths) {
1076
- args.push("--append-system-prompt", promptPath);
1077
- }
1078
- if (rolePromptPath) args.push("--append-system-prompt", rolePromptPath);
1079
- return args;
1080
- }
1081
- function eventType2(value) {
1082
- if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
1083
- const type = value.type;
1084
- return typeof type === "string" ? type : void 0;
1085
- }
1086
- function isActivityEvent(value) {
1087
- return [
1088
- "message_start",
1089
- "message_update",
1090
- "message_end",
1091
- "tool_execution_start",
1092
- "tool_execution_update",
1093
- "auto_retry_start",
1094
- "compaction_start"
1095
- ].includes(eventType2(value) ?? "");
1096
- }
1097
- async function writeRolePrompt(agentName, prompt) {
1098
- const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "pi-subagent-rpc-"));
1099
- const safeName = agentName.replace(/[^\w.-]+/gu, "_");
1100
- const filePath = path.join(dir, `prompt-${safeName}.md`);
1101
- await fs.promises.writeFile(filePath, prompt, {
1102
- encoding: "utf8",
1103
- mode: 384
1104
- });
1105
- return { dir, filePath };
1106
- }
1107
- function cleanupRolePrompt(value) {
1108
- if (!value) return;
1109
- try {
1110
- fs.rmSync(value.dir, { recursive: true, force: true });
1111
- } catch {
1112
- }
1113
- }
1114
- function waitForSpawn(proc, signal, timeoutMs) {
1115
- return new Promise((resolve, reject) => {
1116
- let settled = false;
1117
- const finish = (error) => {
1118
- if (settled) return;
1119
- settled = true;
1120
- clearTimeout(timer);
1121
- proc.off("spawn", onSpawn);
1122
- proc.off("error", onError);
1123
- signal?.removeEventListener("abort", onAbort);
1124
- if (error) reject(error);
1125
- else resolve();
1126
- };
1127
- const onSpawn = () => finish();
1128
- const onError = (error) => finish(error);
1129
- const onAbort = () => finish(abortError2("RPC subagent start aborted"));
1130
- const timer = setTimeout(
1131
- () => finish(new Error(`RPC subagent start timed out after ${timeoutMs}ms`)),
1132
- timeoutMs
1133
- );
1134
- timer.unref();
1135
- proc.once("spawn", onSpawn);
1136
- proc.once("error", onError);
1137
- signal?.addEventListener("abort", onAbort, { once: true });
1138
- if (signal?.aborted) onAbort();
1139
- });
1140
- }
1141
- async function raceWithAbort2(promise, signal, message) {
1142
- if (!signal) return promise;
1143
- if (signal.aborted) throw abortError2(message);
1144
- let onAbort;
1145
- try {
1146
- return await Promise.race([
1147
- promise,
1148
- new Promise((_resolve, reject) => {
1149
- onAbort = () => reject(abortError2(message));
1150
- signal.addEventListener("abort", onAbort, { once: true });
1151
- if (signal.aborted) onAbort();
1152
- })
1153
- ]);
1154
- } finally {
1155
- if (onAbort) signal.removeEventListener("abort", onAbort);
1156
- }
1157
- }
1158
- function waitForTurnSettlement(settled, signal, timeoutMs) {
1159
- if (signal.aborted) return Promise.resolve("aborted");
1160
- return new Promise((resolve, reject) => {
1161
- let finished = false;
1162
- const finish = (value, error) => {
1163
- if (finished) return;
1164
- finished = true;
1165
- clearTimeout(timer);
1166
- signal.removeEventListener("abort", onAbort);
1167
- if (error) reject(error);
1168
- else resolve(value);
1169
- };
1170
- const onAbort = () => finish("aborted");
1171
- const timer = setTimeout(() => finish("timeout"), timeoutMs);
1172
- timer.unref();
1173
- signal.addEventListener("abort", onAbort, { once: true });
1174
- if (signal.aborted) onAbort();
1175
- settled.then(
1176
- () => finish("settled"),
1177
- (error) => finish("settled", error)
1178
- );
1179
- });
1180
- }
1181
- async function settlesWithin2(settled, timeoutMs) {
1182
- let timer;
1183
- try {
1184
- return await Promise.race([
1185
- settled.then(
1186
- () => true,
1187
- () => true
1188
- ),
1189
- new Promise((resolve) => {
1190
- timer = setTimeout(() => resolve(false), timeoutMs);
1191
- })
1192
- ]);
1193
- } finally {
1194
- if (timer) clearTimeout(timer);
1195
- }
1196
- }
1197
- function remainingMs2(deadline) {
1198
- return Math.max(1, deadline - Date.now());
1199
- }
1200
- function rpcTimeoutError(message) {
1201
- const error = new Error(message);
1202
- error.name = "RpcTimeoutError";
1203
- return error;
1204
- }
1205
- function isTimeoutError(error) {
1206
- return error instanceof Error && error.name === "RpcTimeoutError";
1207
- }
1208
- function abortError2(message) {
1209
- const error = new Error(message);
1210
- error.name = "AbortError";
1211
- return error;
1212
- }
1213
- function errorMessage(prefix, error) {
1214
- return new Error(`${prefix}: ${error.message}`);
1215
- }
1216
- export {
1217
- RpcProtocolClient,
1218
- RpcTransport,
1219
- buildRpcArgs,
1220
- validateRpcTools
1221
- };
1222
- //# sourceMappingURL=rpc-transport-7R7DVCEB.ts.map