@narumitw/pi-subagents 2.1.3 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (314) hide show
  1. package/README.md +181 -1250
  2. package/dist/child-communication-bridge.ts +136 -0
  3. package/dist/child-communication-bridge.ts.map +7 -0
  4. package/dist/chunks/chunk-UKTWUQRM.js +667 -0
  5. package/dist/chunks/chunk-UKTWUQRM.js.map +7 -0
  6. package/dist/index.ts +1448 -1598
  7. package/dist/index.ts.map +4 -4
  8. package/docs/design-principles.md +31 -0
  9. package/docs/ipc-transport-idea.md +103 -0
  10. package/docs/tools.md +109 -0
  11. package/package.json +11 -19
  12. package/src/broker-credentials.ts +71 -0
  13. package/src/child-communication-bridge.ts +153 -0
  14. package/src/child-communication-tools.ts +147 -0
  15. package/src/completion-renderer.ts +60 -0
  16. package/src/index.ts +1 -1
  17. package/src/message-broker.ts +628 -0
  18. package/src/model-output.ts +42 -0
  19. package/src/process.ts +688 -0
  20. package/src/runtime.ts +538 -0
  21. package/src/subagents.ts +33 -34
  22. package/src/tools.ts +416 -0
  23. package/src/types.ts +85 -0
  24. package/src/widget.ts +130 -0
  25. package/dist/chunks/auto-transport-FUUKFDIG.ts +0 -109
  26. package/dist/chunks/auto-transport-FUUKFDIG.ts.map +0 -7
  27. package/dist/chunks/capability-grant-PR72SWWS.ts +0 -19
  28. package/dist/chunks/capability-grant-PR72SWWS.ts.map +0 -7
  29. package/dist/chunks/child-peer-bridge.ts +0 -108
  30. package/dist/chunks/child-peer-bridge.ts.map +0 -7
  31. package/dist/chunks/chunk-2LMJU25E.ts +0 -1641
  32. package/dist/chunks/chunk-2LMJU25E.ts.map +0 -7
  33. package/dist/chunks/chunk-47SK2QYC.ts +0 -56
  34. package/dist/chunks/chunk-47SK2QYC.ts.map +0 -7
  35. package/dist/chunks/chunk-4AQSF7AS.ts +0 -29
  36. package/dist/chunks/chunk-4AQSF7AS.ts.map +0 -7
  37. package/dist/chunks/chunk-5DGRMKNV.ts +0 -126
  38. package/dist/chunks/chunk-5DGRMKNV.ts.map +0 -7
  39. package/dist/chunks/chunk-6H6TBBED.ts +0 -108
  40. package/dist/chunks/chunk-6H6TBBED.ts.map +0 -7
  41. package/dist/chunks/chunk-6KJ34M6S.ts +0 -159
  42. package/dist/chunks/chunk-6KJ34M6S.ts.map +0 -7
  43. package/dist/chunks/chunk-6NSJVPXX.ts +0 -480
  44. package/dist/chunks/chunk-6NSJVPXX.ts.map +0 -7
  45. package/dist/chunks/chunk-7AAJEUSL.ts +0 -238
  46. package/dist/chunks/chunk-7AAJEUSL.ts.map +0 -7
  47. package/dist/chunks/chunk-BFK2Z4ZF.ts +0 -189
  48. package/dist/chunks/chunk-BFK2Z4ZF.ts.map +0 -7
  49. package/dist/chunks/chunk-BOAXY55Y.ts +0 -153
  50. package/dist/chunks/chunk-BOAXY55Y.ts.map +0 -7
  51. package/dist/chunks/chunk-D4CR7T73.ts +0 -353
  52. package/dist/chunks/chunk-D4CR7T73.ts.map +0 -7
  53. package/dist/chunks/chunk-FEVPWRMU.ts +0 -300
  54. package/dist/chunks/chunk-FEVPWRMU.ts.map +0 -7
  55. package/dist/chunks/chunk-G6VZTCFH.ts +0 -70
  56. package/dist/chunks/chunk-G6VZTCFH.ts.map +0 -7
  57. package/dist/chunks/chunk-H3FP6DLR.ts +0 -160
  58. package/dist/chunks/chunk-H3FP6DLR.ts.map +0 -7
  59. package/dist/chunks/chunk-HA36LPCO.ts +0 -130
  60. package/dist/chunks/chunk-HA36LPCO.ts.map +0 -7
  61. package/dist/chunks/chunk-HOP5FXDT.ts +0 -27
  62. package/dist/chunks/chunk-HOP5FXDT.ts.map +0 -7
  63. package/dist/chunks/chunk-IGAMVWFN.ts +0 -139
  64. package/dist/chunks/chunk-IGAMVWFN.ts.map +0 -7
  65. package/dist/chunks/chunk-ILEQ27AL.ts +0 -45
  66. package/dist/chunks/chunk-ILEQ27AL.ts.map +0 -7
  67. package/dist/chunks/chunk-ITVWPNU4.ts +0 -819
  68. package/dist/chunks/chunk-ITVWPNU4.ts.map +0 -7
  69. package/dist/chunks/chunk-IWC32VPY.ts +0 -172
  70. package/dist/chunks/chunk-IWC32VPY.ts.map +0 -7
  71. package/dist/chunks/chunk-JSZIP73U.ts +0 -362
  72. package/dist/chunks/chunk-JSZIP73U.ts.map +0 -7
  73. package/dist/chunks/chunk-JU6LUNLP.ts +0 -380
  74. package/dist/chunks/chunk-JU6LUNLP.ts.map +0 -7
  75. package/dist/chunks/chunk-KMGKCEO4.ts +0 -38
  76. package/dist/chunks/chunk-KMGKCEO4.ts.map +0 -7
  77. package/dist/chunks/chunk-LASD73CM.ts +0 -339
  78. package/dist/chunks/chunk-LASD73CM.ts.map +0 -7
  79. package/dist/chunks/chunk-LEOYDZI3.ts +0 -22
  80. package/dist/chunks/chunk-LEOYDZI3.ts.map +0 -7
  81. package/dist/chunks/chunk-LL4LP2T7.ts +0 -737
  82. package/dist/chunks/chunk-LL4LP2T7.ts.map +0 -7
  83. package/dist/chunks/chunk-N2T5IN4X.ts +0 -18
  84. package/dist/chunks/chunk-N2T5IN4X.ts.map +0 -7
  85. package/dist/chunks/chunk-N7BLVXKK.ts +0 -73
  86. package/dist/chunks/chunk-N7BLVXKK.ts.map +0 -7
  87. package/dist/chunks/chunk-NLT67IZS.ts +0 -322
  88. package/dist/chunks/chunk-NLT67IZS.ts.map +0 -7
  89. package/dist/chunks/chunk-NTRPLF46.ts +0 -63
  90. package/dist/chunks/chunk-NTRPLF46.ts.map +0 -7
  91. package/dist/chunks/chunk-ONDTY4EL.ts +0 -91
  92. package/dist/chunks/chunk-ONDTY4EL.ts.map +0 -7
  93. package/dist/chunks/chunk-OVPHFGKO.ts +0 -1769
  94. package/dist/chunks/chunk-OVPHFGKO.ts.map +0 -7
  95. package/dist/chunks/chunk-P7OH4XMF.ts +0 -60
  96. package/dist/chunks/chunk-P7OH4XMF.ts.map +0 -7
  97. package/dist/chunks/chunk-PBZMBTNJ.ts +0 -422
  98. package/dist/chunks/chunk-PBZMBTNJ.ts.map +0 -7
  99. package/dist/chunks/chunk-PGLSFLYW.ts +0 -52
  100. package/dist/chunks/chunk-PGLSFLYW.ts.map +0 -7
  101. package/dist/chunks/chunk-RRR66UWR.ts +0 -28
  102. package/dist/chunks/chunk-RRR66UWR.ts.map +0 -7
  103. package/dist/chunks/chunk-RSUXZD6S.ts +0 -275
  104. package/dist/chunks/chunk-RSUXZD6S.ts.map +0 -7
  105. package/dist/chunks/chunk-RTCVYIZA.ts +0 -221
  106. package/dist/chunks/chunk-RTCVYIZA.ts.map +0 -7
  107. package/dist/chunks/chunk-RY2AEGMZ.ts +0 -34
  108. package/dist/chunks/chunk-RY2AEGMZ.ts.map +0 -7
  109. package/dist/chunks/chunk-SWGQLFSD.ts +0 -60
  110. package/dist/chunks/chunk-SWGQLFSD.ts.map +0 -7
  111. package/dist/chunks/chunk-TM2R67J3.ts +0 -52
  112. package/dist/chunks/chunk-TM2R67J3.ts.map +0 -7
  113. package/dist/chunks/chunk-TMZRHIIK.ts +0 -497
  114. package/dist/chunks/chunk-TMZRHIIK.ts.map +0 -7
  115. package/dist/chunks/chunk-TZ34IQ3M.ts +0 -59
  116. package/dist/chunks/chunk-TZ34IQ3M.ts.map +0 -7
  117. package/dist/chunks/chunk-UMBPMVJW.ts +0 -22
  118. package/dist/chunks/chunk-UMBPMVJW.ts.map +0 -7
  119. package/dist/chunks/chunk-VDG7LTYE.ts +0 -80
  120. package/dist/chunks/chunk-VDG7LTYE.ts.map +0 -7
  121. package/dist/chunks/chunk-X4NMONPE.ts +0 -73
  122. package/dist/chunks/chunk-X4NMONPE.ts.map +0 -7
  123. package/dist/chunks/chunk-YPJEN6NU.ts +0 -65
  124. package/dist/chunks/chunk-YPJEN6NU.ts.map +0 -7
  125. package/dist/chunks/chunk-YU53SHA7.ts +0 -328
  126. package/dist/chunks/chunk-YU53SHA7.ts.map +0 -7
  127. package/dist/chunks/completion-delivery-RSJU6BXL.ts +0 -17
  128. package/dist/chunks/completion-delivery-RSJU6BXL.ts.map +0 -7
  129. package/dist/chunks/config-status-FKGDECZ3.ts +0 -35
  130. package/dist/chunks/config-status-FKGDECZ3.ts.map +0 -7
  131. package/dist/chunks/config-ui-ABHYNGQ7.ts +0 -1212
  132. package/dist/chunks/config-ui-ABHYNGQ7.ts.map +0 -7
  133. package/dist/chunks/consult-LJU3IQY5.ts +0 -519
  134. package/dist/chunks/consult-LJU3IQY5.ts.map +0 -7
  135. package/dist/chunks/context-QDKLVQXE.ts +0 -11
  136. package/dist/chunks/context-QDKLVQXE.ts.map +0 -7
  137. package/dist/chunks/create-stateful-transport-JWC2EFYL.ts +0 -130
  138. package/dist/chunks/create-stateful-transport-JWC2EFYL.ts.map +0 -7
  139. package/dist/chunks/cwd-policy-NB6XZ5GF.ts +0 -17
  140. package/dist/chunks/cwd-policy-NB6XZ5GF.ts.map +0 -7
  141. package/dist/chunks/delegation-contract-LA56I5DT.ts +0 -24
  142. package/dist/chunks/delegation-contract-LA56I5DT.ts.map +0 -7
  143. package/dist/chunks/discovery-MIFB2U4Y.ts +0 -12
  144. package/dist/chunks/discovery-MIFB2U4Y.ts.map +0 -7
  145. package/dist/chunks/execution-Q2JZLKJA.ts +0 -4037
  146. package/dist/chunks/execution-Q2JZLKJA.ts.map +0 -7
  147. package/dist/chunks/in-process-transport-HJ6TZXC3.ts +0 -39
  148. package/dist/chunks/in-process-transport-HJ6TZXC3.ts.map +0 -7
  149. package/dist/chunks/inspect-UH2TKH6E.ts +0 -634
  150. package/dist/chunks/inspect-UH2TKH6E.ts.map +0 -7
  151. package/dist/chunks/peer-communication-KL36Z6CO.ts +0 -294
  152. package/dist/chunks/peer-communication-KL36Z6CO.ts.map +0 -7
  153. package/dist/chunks/persistence-UY3PY6E5.ts +0 -348
  154. package/dist/chunks/persistence-UY3PY6E5.ts.map +0 -7
  155. package/dist/chunks/registry-BT54L6CY.ts +0 -1445
  156. package/dist/chunks/registry-BT54L6CY.ts.map +0 -7
  157. package/dist/chunks/retained-semantic-state-GM75FZGE.ts +0 -81
  158. package/dist/chunks/retained-semantic-state-GM75FZGE.ts.map +0 -7
  159. package/dist/chunks/rpc-transport-7R7DVCEB.ts +0 -1222
  160. package/dist/chunks/rpc-transport-7R7DVCEB.ts.map +0 -7
  161. package/dist/chunks/runtime-policy-5YELCOVC.ts +0 -15
  162. package/dist/chunks/runtime-policy-5YELCOVC.ts.map +0 -7
  163. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts +0 -19
  164. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts.map +0 -7
  165. package/dist/chunks/spawn-idempotency-BNHOSMZW.ts +0 -13
  166. package/dist/chunks/spawn-idempotency-BNHOSMZW.ts.map +0 -7
  167. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts +0 -15
  168. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts.map +0 -7
  169. package/dist/chunks/subprocess-transport-VHZJRBTW.ts +0 -160
  170. package/dist/chunks/subprocess-transport-VHZJRBTW.ts.map +0 -7
  171. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts +0 -164
  172. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts.map +0 -7
  173. package/dist/chunks/workspace-WDKLN72J.ts +0 -11
  174. package/dist/chunks/workspace-WDKLN72J.ts.map +0 -7
  175. package/docs/async-runtime-protocol.md +0 -84
  176. package/docs/implementation-notes/pi-subagents-capability-matrix.md +0 -62
  177. package/docs/implementation-notes/pi-subagents-current-direction.md +0 -99
  178. package/docs/implementation-notes/pi-subagents-rpc-v1.md +0 -153
  179. package/docs/pi-subagents-diagrams.md +0 -183
  180. package/src/adaptive-scheduler.ts +0 -224
  181. package/src/admission-benchmark.ts +0 -95
  182. package/src/admission-policy.ts +0 -78
  183. package/src/agent-projection.ts +0 -53
  184. package/src/agents/built-ins.ts +0 -71
  185. package/src/agents/catalog.ts +0 -241
  186. package/src/agents/discovery.ts +0 -265
  187. package/src/agents/types.ts +0 -100
  188. package/src/agents.ts +0 -51
  189. package/src/async-subagent-benchmark.ts +0 -532
  190. package/src/auto-transport.ts +0 -121
  191. package/src/blocking-status.ts +0 -63
  192. package/src/cached-module-loader.ts +0 -18
  193. package/src/capabilities.ts +0 -145
  194. package/src/capability-grant.ts +0 -115
  195. package/src/capability-router.ts +0 -107
  196. package/src/child-peer-bridge.ts +0 -124
  197. package/src/child-peer-tools.ts +0 -132
  198. package/src/completion-delivery.ts +0 -409
  199. package/src/completion-render.ts +0 -190
  200. package/src/completion-requirement.ts +0 -479
  201. package/src/completion-routing.ts +0 -24
  202. package/src/config-registration.ts +0 -114
  203. package/src/config-status.ts +0 -217
  204. package/src/config-ui.ts +0 -983
  205. package/src/consult-policy.ts +0 -15
  206. package/src/consult-registration.ts +0 -125
  207. package/src/consult-render.ts +0 -194
  208. package/src/consult-resources.ts +0 -51
  209. package/src/consult-tool.ts +0 -95
  210. package/src/consult.ts +0 -566
  211. package/src/context.ts +0 -126
  212. package/src/create-stateful-transport.ts +0 -157
  213. package/src/cwd-policy.ts +0 -183
  214. package/src/delegation-contract.ts +0 -463
  215. package/src/execution/budget.ts +0 -56
  216. package/src/execution/runtime-policy.ts +0 -19
  217. package/src/execution-plan.ts +0 -322
  218. package/src/execution-ui.ts +0 -259
  219. package/src/execution.ts +0 -1679
  220. package/src/in-process-transport.ts +0 -941
  221. package/src/inspect-registration.ts +0 -64
  222. package/src/inspect-render.ts +0 -334
  223. package/src/inspect-tool.ts +0 -45
  224. package/src/inspect.ts +0 -769
  225. package/src/integration-controller.ts +0 -98
  226. package/src/limits.ts +0 -75
  227. package/src/orchestration-metrics.ts +0 -116
  228. package/src/outcome.ts +0 -61
  229. package/src/panel-child-group.ts +0 -35
  230. package/src/panel-contract.ts +0 -343
  231. package/src/panel-evidence.ts +0 -59
  232. package/src/panel-execution.ts +0 -769
  233. package/src/panel-failure.ts +0 -56
  234. package/src/panel-planning.ts +0 -175
  235. package/src/panel-presets.ts +0 -3
  236. package/src/panel-prompts.ts +0 -132
  237. package/src/panel-reconciliation.ts +0 -57
  238. package/src/panel-render.ts +0 -103
  239. package/src/parallel-limit-ui.ts +0 -113
  240. package/src/params.ts +0 -278
  241. package/src/peer-communication.ts +0 -352
  242. package/src/peer-transport.ts +0 -49
  243. package/src/persistence.ts +0 -522
  244. package/src/pi-args.ts +0 -43
  245. package/src/pi-invocation.ts +0 -168
  246. package/src/process-control.ts +0 -43
  247. package/src/prompt-resources.ts +0 -38
  248. package/src/prompt-source-safety.ts +0 -48
  249. package/src/protocol.ts +0 -76
  250. package/src/registry-types.ts +0 -204
  251. package/src/registry.ts +0 -1698
  252. package/src/render-common.ts +0 -252
  253. package/src/render.ts +0 -704
  254. package/src/result-contract.ts +0 -431
  255. package/src/retained-semantic-state.ts +0 -100
  256. package/src/rpc-timeout-finalization.ts +0 -207
  257. package/src/rpc-transport-metadata.ts +0 -65
  258. package/src/rpc-transport.ts +0 -1035
  259. package/src/rpc-turn-capture.ts +0 -217
  260. package/src/runner-outcome.ts +0 -31
  261. package/src/runner-result.ts +0 -55
  262. package/src/runner-types.ts +0 -102
  263. package/src/runner-usage.ts +0 -48
  264. package/src/runner.ts +0 -866
  265. package/src/safe-text.ts +0 -67
  266. package/src/semantic-snapshot.ts +0 -214
  267. package/src/session-guidance-contract.ts +0 -399
  268. package/src/settings/inspection.ts +0 -302
  269. package/src/settings/schema.ts +0 -195
  270. package/src/settings-reader.ts +0 -215
  271. package/src/settings.ts +0 -452
  272. package/src/spawn-idempotency.ts +0 -68
  273. package/src/stateful-agent-view.ts +0 -85
  274. package/src/stateful-config.ts +0 -13
  275. package/src/stateful-guidance.ts +0 -29
  276. package/src/stateful-lifecycle.ts +0 -74
  277. package/src/stateful-limit-ui.ts +0 -249
  278. package/src/stateful-limits.ts +0 -96
  279. package/src/stateful-prompt.ts +0 -49
  280. package/src/stateful-registration.ts +0 -1320
  281. package/src/stateful-render.ts +0 -318
  282. package/src/stateful-safety.ts +0 -47
  283. package/src/stateful-tool-params.ts +0 -215
  284. package/src/stateful.ts +0 -12
  285. package/src/subagent-details.ts +0 -43
  286. package/src/subagents-extension.ts +0 -355
  287. package/src/subprocess-transport.ts +0 -145
  288. package/src/supervision.ts +0 -104
  289. package/src/task-path.ts +0 -65
  290. package/src/timeout-checkpoint.ts +0 -305
  291. package/src/timeout-finalization.ts +0 -75
  292. package/src/tool-schema-compatibility.ts +0 -73
  293. package/src/transport-types.ts +0 -74
  294. package/src/transport-ui.ts +0 -135
  295. package/src/transport.ts +0 -43
  296. package/src/turn-budget.ts +0 -109
  297. package/src/usage-format.ts +0 -42
  298. package/src/usage-recording-config.ts +0 -13
  299. package/src/usage-recording-store.ts +0 -183
  300. package/src/usage-recording.ts +0 -478
  301. package/src/verification-harness.ts +0 -516
  302. package/src/verification-policy.ts +0 -67
  303. package/src/verification-receipt.ts +0 -275
  304. package/src/verified-execution-benchmark.ts +0 -86
  305. package/src/verified-execution-contract.ts +0 -191
  306. package/src/verified-execution-schema.ts +0 -32
  307. package/src/work-item-ledger.ts +0 -1404
  308. package/src/work-item-persistence.ts +0 -254
  309. package/src/workflow-completion-controller.ts +0 -397
  310. package/src/workflow-planning.ts +0 -172
  311. package/src/workflow-tree-identity.ts +0 -289
  312. package/src/workflow-ui.ts +0 -69
  313. package/src/workflow-verification.ts +0 -296
  314. package/src/workspace.ts +0 -174
package/src/process.ts ADDED
@@ -0,0 +1,688 @@
1
+ import { type ChildProcess, spawn } from "node:child_process";
2
+ import * as fs from "node:fs";
3
+ import * as path from "node:path";
4
+ import { StringDecoder } from "node:string_decoder";
5
+ import { fileURLToPath } from "node:url";
6
+ import { getPackageDir } from "@earendil-works/pi-coding-agent";
7
+ import {
8
+ BROKER_CREDENTIAL_FD,
9
+ brokerCredentialEnvironment,
10
+ serializeBrokerCredentials,
11
+ } from "./broker-credentials.js";
12
+ import { CHILD_COMMUNICATION_TOOL_NAMES } from "./child-communication-tools.js";
13
+ import type { ChildControl, ChildRequest, ChildResult } from "./types.js";
14
+
15
+ const CORE_PACKAGE_NAME = "@earendil-works/pi-coding-agent";
16
+ const MAX_TIMEOUT_MS = 2_147_483_647;
17
+ const MAX_TIMEOUT_SECONDS = MAX_TIMEOUT_MS / 1000;
18
+ const MAX_OUTPUT_BYTES = 32 * 1024;
19
+ const MAX_ERROR_BYTES = 8 * 1024;
20
+ const MAX_EVENT_LINE_BYTES = 256 * 1024;
21
+ const RPC_RESPONSE_TIMEOUT_MS = 30_000;
22
+ const KILL_GRACE_MS = 1_000;
23
+
24
+ interface ProcessSettlement {
25
+ code: number;
26
+ cancelled: boolean;
27
+ timedOut: boolean;
28
+ completed: boolean;
29
+ launchError?: string;
30
+ }
31
+
32
+ interface AssistantEvent {
33
+ type?: string;
34
+ id?: string;
35
+ success?: boolean;
36
+ error?: string;
37
+ message?: {
38
+ role?: string;
39
+ content?: Array<{ type?: string; text?: string }>;
40
+ stopReason?: string;
41
+ errorMessage?: string;
42
+ };
43
+ }
44
+
45
+ interface PendingRpcCommand {
46
+ command: string;
47
+ resolve: () => void;
48
+ reject: (error: Error) => void;
49
+ timer: NodeJS.Timeout;
50
+ onAccepted?: () => void;
51
+ signal?: AbortSignal;
52
+ onAbort?: () => void;
53
+ }
54
+
55
+ export function resolveTimeoutMs(timeout: number | undefined): number | undefined {
56
+ if (timeout === undefined) return undefined;
57
+ if (!Number.isFinite(timeout) || timeout <= 0) {
58
+ throw new Error("Invalid timeout: must be a finite number of seconds");
59
+ }
60
+ const timeoutMs = timeout * 1000;
61
+ if (timeoutMs > MAX_TIMEOUT_MS) {
62
+ throw new Error(`Invalid timeout: maximum is ${MAX_TIMEOUT_SECONDS} seconds`);
63
+ }
64
+ return timeoutMs;
65
+ }
66
+
67
+ export async function runChild(request: ChildRequest): Promise<ChildResult> {
68
+ if (request.signal.aborted) return cancelledResult();
69
+ try {
70
+ const invocation = resolvePiInvocation(buildPiArgs(request));
71
+ return await executeProcess(invocation, request);
72
+ } catch (error) {
73
+ if (request.signal.aborted) return cancelledResult();
74
+ return {
75
+ state: "failed",
76
+ error: truncateText(error instanceof Error ? error.message : String(error), MAX_ERROR_BYTES)
77
+ .text,
78
+ limitations: [],
79
+ truncated: false,
80
+ };
81
+ }
82
+ }
83
+
84
+ export function buildPiArgs(request: ChildRequest): string[] {
85
+ const args = [
86
+ "--mode",
87
+ "rpc",
88
+ "--no-session",
89
+ "--no-extensions",
90
+ "--no-skills",
91
+ "--no-prompt-templates",
92
+ "-e",
93
+ childCommunicationBridgePath(),
94
+ "--model",
95
+ request.model,
96
+ "--thinking",
97
+ request.thinkingLevel,
98
+ request.projectTrusted ? "--approve" : "--no-approve",
99
+ ];
100
+ const tools = [...new Set([...request.tools, ...CHILD_COMMUNICATION_TOOL_NAMES])];
101
+ args.push("--tools", tools.join(","));
102
+ return args;
103
+ }
104
+
105
+ export function childCommunicationBridgePath(): string {
106
+ return fileURLToPath(new URL("./child-communication-bridge.ts", import.meta.url));
107
+ }
108
+
109
+ async function executeProcess(
110
+ invocation: { command: string; args: string[] },
111
+ request: ChildRequest,
112
+ ): Promise<ChildResult> {
113
+ const timeoutMs = resolveTimeoutMs(request.timeout);
114
+ let latestOutput = "";
115
+ let terminalOutput: string | undefined;
116
+ let terminalStopReason: "stop" | "length" | undefined;
117
+ let errorMessage = "";
118
+ let assistantFailed = false;
119
+ let stderr = "";
120
+ let truncated = false;
121
+ let malformedEvents = 0;
122
+ let rpcCounter = 0;
123
+ const pendingCommands = new Map<string, PendingRpcCommand>();
124
+ let rpcInputError: Error | undefined;
125
+ let sendCommand: (
126
+ command: { type: "prompt" | "steer"; message: string },
127
+ onAccepted?: () => void,
128
+ signal?: AbortSignal,
129
+ ) => Promise<void> = () => Promise.reject(new Error("Subagent RPC process is unavailable."));
130
+ let onAgentSettled: () => void = () => undefined;
131
+
132
+ const takePendingCommand = (id: string): PendingRpcCommand | undefined => {
133
+ const pending = pendingCommands.get(id);
134
+ if (!pending) return undefined;
135
+ pendingCommands.delete(id);
136
+ clearTimeout(pending.timer);
137
+ if (pending.signal && pending.onAbort) {
138
+ pending.signal.removeEventListener("abort", pending.onAbort);
139
+ }
140
+ return pending;
141
+ };
142
+ const rejectPendingCommand = (id: string, error: Error) => {
143
+ takePendingCommand(id)?.reject(error);
144
+ };
145
+ const rejectPendingCommands = (error: Error) => {
146
+ for (const id of [...pendingCommands.keys()]) rejectPendingCommand(id, error);
147
+ };
148
+ const resolvePendingCommand = (id: string) => {
149
+ const pending = takePendingCommand(id);
150
+ if (!pending) return;
151
+ try {
152
+ pending.onAccepted?.();
153
+ pending.resolve();
154
+ } catch (error) {
155
+ pending.reject(error instanceof Error ? error : new Error(String(error)));
156
+ }
157
+ };
158
+ const failRpcInput = (error: Error) => {
159
+ rpcInputError ??= error;
160
+ rejectPendingCommands(rpcInputError);
161
+ };
162
+
163
+ const decoder = new JsonLineDecoder(
164
+ (value) => {
165
+ const event = value as AssistantEvent;
166
+ if (event.type === "response" && typeof event.id === "string") {
167
+ const pending = pendingCommands.get(event.id);
168
+ if (!pending) return;
169
+ if (event.success === true) {
170
+ resolvePendingCommand(event.id);
171
+ } else {
172
+ rejectPendingCommand(
173
+ event.id,
174
+ new Error(
175
+ typeof event.error === "string"
176
+ ? event.error
177
+ : `Subagent RPC ${pending.command} command failed.`,
178
+ ),
179
+ );
180
+ }
181
+ return;
182
+ }
183
+ if (event.type === "agent_settled") {
184
+ onAgentSettled();
185
+ return;
186
+ }
187
+ if (event.type === "message_end" && event.message?.role === "assistant") {
188
+ const text = (event.message.content ?? [])
189
+ .filter((part) => part.type === "text" && typeof part.text === "string")
190
+ .map((part) => part.text)
191
+ .join("\n")
192
+ .trim();
193
+ if (text) {
194
+ const limited = truncateText(text, MAX_OUTPUT_BYTES);
195
+ latestOutput = limited.text;
196
+ truncated ||= limited.truncated;
197
+ if (event.message.stopReason === "stop" || event.message.stopReason === "length") {
198
+ terminalOutput = limited.text;
199
+ terminalStopReason = event.message.stopReason;
200
+ }
201
+ }
202
+ if (event.message.stopReason === "error" || event.message.stopReason === "aborted") {
203
+ assistantFailed = true;
204
+ }
205
+ if (event.message.errorMessage) {
206
+ const limited = truncateText(event.message.errorMessage, MAX_ERROR_BYTES);
207
+ errorMessage = limited.text;
208
+ truncated ||= limited.truncated;
209
+ }
210
+ }
211
+ },
212
+ () => {
213
+ malformedEvents++;
214
+ },
215
+ );
216
+
217
+ const settlement = await new Promise<ProcessSettlement>((resolve) => {
218
+ let process: ChildProcess;
219
+ let settled = false;
220
+ let finishRequested = false;
221
+ let spawned = false;
222
+ let terminating = false;
223
+ let cancelled = false;
224
+ let timedOut = false;
225
+ let completed = false;
226
+ let ready = false;
227
+ let deadline: NodeJS.Timeout | undefined;
228
+ let forceClose: NodeJS.Timeout | undefined;
229
+ let escalation: NodeJS.Timeout | undefined;
230
+ let termination: Promise<void> | undefined;
231
+
232
+ const finish = (code: number, launchError?: string) => {
233
+ if (settled || finishRequested) return;
234
+ finishRequested = true;
235
+ const complete = () => {
236
+ if (settled) return;
237
+ settled = true;
238
+ if (deadline) clearTimeout(deadline);
239
+ if (forceClose) clearTimeout(forceClose);
240
+ if (escalation) clearTimeout(escalation);
241
+ request.signal.removeEventListener("abort", onAbort);
242
+ rejectPendingCommands(new Error("Subagent RPC process closed."));
243
+ resolve({ code, cancelled, timedOut, completed, launchError });
244
+ };
245
+ if (termination) void termination.then(complete, complete);
246
+ else complete();
247
+ };
248
+ const terminate = (code: number) => {
249
+ if (settled || terminating) return;
250
+ terminating = true;
251
+ if (deadline) {
252
+ clearTimeout(deadline);
253
+ deadline = undefined;
254
+ }
255
+ if (globalThis.process.platform === "win32") {
256
+ termination = terminateWindowsProcessTree(process);
257
+ } else {
258
+ signalPosixProcess(process, "SIGTERM");
259
+ escalation = setTimeout(() => signalPosixProcess(process, "SIGKILL"), KILL_GRACE_MS);
260
+ escalation.unref();
261
+ }
262
+ forceClose = setTimeout(() => {
263
+ decoder.finish();
264
+ process.stdin?.destroy();
265
+ process.stdout?.destroy();
266
+ process.stderr?.destroy();
267
+ finish(code);
268
+ }, KILL_GRACE_MS * 2);
269
+ forceClose.unref();
270
+ };
271
+ const onAbort = () => {
272
+ if (settled) return;
273
+ cancelled = true;
274
+ terminate(130);
275
+ };
276
+ const completeNormally = () => {
277
+ if (settled || terminating || !ready) return;
278
+ completed = true;
279
+ terminate(0);
280
+ };
281
+ onAgentSettled = completeNormally;
282
+
283
+ try {
284
+ process = spawn(invocation.command, invocation.args, {
285
+ cwd: request.cwd,
286
+ detached: globalThis.process.platform !== "win32",
287
+ shell: false,
288
+ stdio: ["pipe", "pipe", "pipe", "pipe"],
289
+ env: {
290
+ ...globalThis.process.env,
291
+ ...brokerCredentialEnvironment(),
292
+ PI_SUBAGENT_DEPTH: String(
293
+ (Number.parseInt(globalThis.process.env.PI_SUBAGENT_DEPTH ?? "0", 10) || 0) + 1,
294
+ ),
295
+ },
296
+ });
297
+ } catch (error) {
298
+ finish(1, error instanceof Error ? error.message : String(error));
299
+ return;
300
+ }
301
+
302
+ process.stdin?.on("error", failRpcInput);
303
+ sendCommand = (command, onAccepted, signal) => {
304
+ if (settled || terminating || process.exitCode !== null) {
305
+ return Promise.reject(new Error("Subagent RPC process is no longer active."));
306
+ }
307
+ if (signal?.aborted) {
308
+ return Promise.reject(abortError("Subagent RPC command was cancelled."));
309
+ }
310
+ if (rpcInputError) return Promise.reject(rpcInputError);
311
+ const stdin = process.stdin;
312
+ if (!stdin || stdin.destroyed || !stdin.writable) {
313
+ return Promise.reject(new Error("Subagent RPC stdin is unavailable."));
314
+ }
315
+ const id = `rpc_${++rpcCounter}`;
316
+ return new Promise<void>((resolveCommand, rejectCommand) => {
317
+ const timer = setTimeout(
318
+ () =>
319
+ rejectPendingCommand(id, new Error(`Subagent RPC ${command.type} response timed out.`)),
320
+ RPC_RESPONSE_TIMEOUT_MS,
321
+ );
322
+ timer.unref();
323
+ const pending: PendingRpcCommand = {
324
+ command: command.type,
325
+ resolve: resolveCommand,
326
+ reject: rejectCommand,
327
+ timer,
328
+ onAccepted,
329
+ signal,
330
+ };
331
+ if (signal) {
332
+ pending.onAbort = () =>
333
+ rejectPendingCommand(id, abortError("Subagent RPC command was cancelled."));
334
+ }
335
+ pendingCommands.set(id, pending);
336
+ if (signal && pending.onAbort) {
337
+ signal.addEventListener("abort", pending.onAbort, { once: true });
338
+ if (signal.aborted) {
339
+ pending.onAbort();
340
+ return;
341
+ }
342
+ }
343
+ try {
344
+ stdin.write(`${JSON.stringify({ id, ...command })}\n`, (error) => {
345
+ if (error) failRpcInput(error);
346
+ });
347
+ } catch (error) {
348
+ failRpcInput(error instanceof Error ? error : new Error(String(error)));
349
+ }
350
+ });
351
+ };
352
+
353
+ request.signal.addEventListener("abort", onAbort, { once: true });
354
+ if (request.signal.aborted) onAbort();
355
+ process.once("spawn", () => {
356
+ spawned = true;
357
+ if (settled || cancelled) return;
358
+ void sendCommand(
359
+ { type: "prompt", message: `Task: ${request.task}` },
360
+ () => {
361
+ if (settled || terminating || request.signal.aborted) {
362
+ throw new Error("Subagent RPC prompt was superseded.");
363
+ }
364
+ ready = true;
365
+ if (timeoutMs !== undefined) {
366
+ deadline = setTimeout(() => {
367
+ timedOut = true;
368
+ terminate(124);
369
+ }, timeoutMs);
370
+ deadline.unref();
371
+ }
372
+ const control: ChildControl = {
373
+ send: async (message, signal) => {
374
+ if (!ready || completed || terminating) {
375
+ throw new Error("Subagent job is no longer accepting messages.");
376
+ }
377
+ await sendCommand({ type: "steer", message }, undefined, signal);
378
+ },
379
+ };
380
+ request.onControl?.(control);
381
+ },
382
+ request.signal,
383
+ ).catch((error) => {
384
+ if (settled || terminating) return;
385
+ errorMessage = truncateText(
386
+ error instanceof Error ? error.message : String(error),
387
+ MAX_ERROR_BYTES,
388
+ ).text;
389
+ terminate(1);
390
+ });
391
+ });
392
+ process.stdout?.on("data", (chunk) => decoder.push(chunk));
393
+ process.stderr?.on("data", (chunk) => {
394
+ const limited = truncateTail(`${stderr}${chunk.toString()}`, MAX_ERROR_BYTES);
395
+ stderr = limited.text;
396
+ truncated ||= limited.truncated;
397
+ });
398
+ process.once("close", (code) => {
399
+ decoder.finish();
400
+ finish(cancelled ? 130 : timedOut ? 124 : completed ? 0 : (code ?? 1));
401
+ });
402
+ process.once("error", (error) => {
403
+ const limited = truncateText(error.message, MAX_ERROR_BYTES);
404
+ errorMessage = limited.text;
405
+ truncated ||= limited.truncated;
406
+ if (spawned) terminate(1);
407
+ else finish(1, error.message);
408
+ });
409
+ const credentialPipe = process.stdio[BROKER_CREDENTIAL_FD];
410
+ if (!credentialPipe || !("end" in credentialPipe)) {
411
+ errorMessage = "Subagent broker credential pipe is unavailable.";
412
+ terminate(1);
413
+ } else {
414
+ const onCredentialError = () => {
415
+ if (settled || finishRequested) return;
416
+ errorMessage = "Subagent broker credential transfer failed.";
417
+ terminate(1);
418
+ };
419
+ const removeCredentialListeners = () => {
420
+ credentialPipe.removeListener("error", onCredentialError);
421
+ credentialPipe.removeListener("close", removeCredentialListeners);
422
+ };
423
+ credentialPipe.on("error", onCredentialError);
424
+ credentialPipe.once("close", removeCredentialListeners);
425
+ try {
426
+ credentialPipe.end(serializeBrokerCredentials(request.communication));
427
+ } catch {
428
+ onCredentialError();
429
+ }
430
+ }
431
+ });
432
+
433
+ const output = terminalOutput ?? latestOutput;
434
+ const limitations =
435
+ malformedEvents > 0
436
+ ? [`Ignored ${malformedEvents} malformed or oversized child event(s).`]
437
+ : [];
438
+ if (truncated) limitations.push("Child output was truncated to runtime limits.");
439
+ if (terminalStopReason === "length") {
440
+ limitations.push("Child output ended at the model output limit and may be incomplete.");
441
+ }
442
+ if (settlement.cancelled) return cancelledResult(output, limitations, truncated);
443
+ if (settlement.timedOut) {
444
+ return {
445
+ state: "timed_out",
446
+ ...(output ? { result: output } : {}),
447
+ error: "Subagent execution timed out.",
448
+ limitations,
449
+ truncated,
450
+ };
451
+ }
452
+ const error = settlement.launchError || errorMessage || stderr.trim();
453
+ if (settlement.completed && terminalStopReason === "stop" && !assistantFailed && !errorMessage) {
454
+ return {
455
+ state: "completed",
456
+ result: terminalOutput,
457
+ limitations,
458
+ truncated,
459
+ };
460
+ }
461
+ const failure =
462
+ error ||
463
+ (terminalStopReason === "length"
464
+ ? "Subagent output reached the model limit."
465
+ : assistantFailed
466
+ ? "Subagent model turn failed."
467
+ : settlement.completed
468
+ ? "Subagent settled without a terminal assistant result."
469
+ : settlement.code === 0
470
+ ? "Subagent exited without settling."
471
+ : `Subagent exited with code ${settlement.code}.`);
472
+ if (output) {
473
+ return {
474
+ state: "partial",
475
+ result: output,
476
+ error: failure,
477
+ limitations,
478
+ truncated,
479
+ };
480
+ }
481
+ return {
482
+ state: "failed",
483
+ error: failure,
484
+ limitations,
485
+ truncated,
486
+ };
487
+ }
488
+
489
+ function resolvePiInvocation(args: string[]): { command: string; args: string[] } {
490
+ const packageDirectory = fs.realpathSync(getPackageDir());
491
+ const manifestPath = path.join(packageDirectory, "package.json");
492
+ const manifest = JSON.parse(fs.readFileSync(manifestPath, "utf8")) as {
493
+ name?: string;
494
+ bin?: { pi?: string };
495
+ };
496
+ if (manifest.name !== CORE_PACKAGE_NAME || typeof manifest.bin?.pi !== "string") {
497
+ throw new Error("Loaded Pi core package does not declare a valid bin.pi entry.");
498
+ }
499
+ const declared = manifest.bin.pi;
500
+ if (path.isAbsolute(declared)) throw new Error("Pi core bin.pi must be package-relative.");
501
+ const cliPath = fs.realpathSync(path.resolve(packageDirectory, declared));
502
+ const relative = path.relative(packageDirectory, cliPath);
503
+ if (relative === ".." || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
504
+ throw new Error("Pi core bin.pi escapes its package directory.");
505
+ }
506
+ if (!fs.statSync(cliPath).isFile()) throw new Error("Pi core bin.pi is not a file.");
507
+ if (
508
+ globalThis.process.versions.bun &&
509
+ /^pi(?:\.exe)?$/iu.test(path.basename(globalThis.process.execPath)) &&
510
+ path.dirname(fs.realpathSync(globalThis.process.execPath)) === packageDirectory
511
+ ) {
512
+ return { command: globalThis.process.execPath, args };
513
+ }
514
+ return { command: globalThis.process.execPath, args: [cliPath, ...args] };
515
+ }
516
+
517
+ function signalPosixProcess(process: ChildProcess, signal: NodeJS.Signals): void {
518
+ if (process.pid) {
519
+ try {
520
+ globalThis.process.kill(-process.pid, signal);
521
+ return;
522
+ } catch {
523
+ // Fall back to the immediate child.
524
+ }
525
+ }
526
+ try {
527
+ process.kill(signal);
528
+ } catch {
529
+ // The process may already be terminal.
530
+ }
531
+ }
532
+
533
+ export function terminateWindowsProcessTree(
534
+ process: ChildProcess,
535
+ spawnProcess: typeof spawn = spawn,
536
+ taskkillPath = resolveTaskkillPath(),
537
+ helperTimeoutMs = KILL_GRACE_MS,
538
+ ): Promise<void> {
539
+ if (!process.pid || !taskkillPath) {
540
+ killImmediateChild(process);
541
+ return Promise.resolve();
542
+ }
543
+ return new Promise((resolve) => {
544
+ let settled = false;
545
+ let treeKiller: ChildProcess;
546
+ let deadline: NodeJS.Timeout | undefined;
547
+ const onError = () => finish(true, false);
548
+ const onClose = (code: number | null) => finish(code !== 0, false);
549
+ const finish = (fallback: boolean, terminateHelper: boolean) => {
550
+ if (settled) return;
551
+ settled = true;
552
+ if (deadline) clearTimeout(deadline);
553
+ treeKiller.removeListener("error", onError);
554
+ treeKiller.removeListener("close", onClose);
555
+ if (terminateHelper) killImmediateChild(treeKiller);
556
+ if (fallback) killImmediateChild(process);
557
+ resolve();
558
+ };
559
+ try {
560
+ treeKiller = spawnProcess(taskkillPath, ["/PID", String(process.pid), "/T", "/F"], {
561
+ stdio: "ignore",
562
+ windowsHide: true,
563
+ });
564
+ } catch {
565
+ killImmediateChild(process);
566
+ resolve();
567
+ return;
568
+ }
569
+ treeKiller.once("error", onError);
570
+ treeKiller.once("close", onClose);
571
+ deadline = setTimeout(() => finish(true, true), helperTimeoutMs);
572
+ deadline.unref();
573
+ });
574
+ }
575
+
576
+ function resolveTaskkillPath(): string | undefined {
577
+ const systemRoot = globalThis.process.env.SystemRoot ?? globalThis.process.env.WINDIR;
578
+ if (!systemRoot || !path.win32.isAbsolute(systemRoot)) return undefined;
579
+ return path.win32.join(systemRoot, "System32", "taskkill.exe");
580
+ }
581
+
582
+ function killImmediateChild(process: ChildProcess): void {
583
+ try {
584
+ process.kill("SIGKILL");
585
+ } catch {
586
+ // The process may already be terminal.
587
+ }
588
+ }
589
+
590
+ function abortError(message: string): Error {
591
+ const error = new Error(message);
592
+ error.name = "AbortError";
593
+ return error;
594
+ }
595
+
596
+ function cancelledResult(
597
+ result?: string,
598
+ limitations: string[] = [],
599
+ truncated = false,
600
+ ): ChildResult {
601
+ return {
602
+ state: "cancelled",
603
+ ...(result ? { result } : {}),
604
+ error: "Subagent execution was cancelled.",
605
+ limitations,
606
+ truncated,
607
+ };
608
+ }
609
+
610
+ function truncateText(text: string, maxBytes: number): { text: string; truncated: boolean } {
611
+ const bytes = Buffer.from(text, "utf8");
612
+ if (bytes.length <= maxBytes) return { text, truncated: false };
613
+ return {
614
+ text: `${bytes
615
+ .subarray(0, Math.max(0, maxBytes - 18))
616
+ .toString("utf8")
617
+ .replace(/�+$/gu, "")}\n… [truncated]`,
618
+ truncated: true,
619
+ };
620
+ }
621
+
622
+ function truncateTail(text: string, maxBytes: number): { text: string; truncated: boolean } {
623
+ const bytes = Buffer.from(text, "utf8");
624
+ if (bytes.length <= maxBytes) return { text, truncated: false };
625
+ return {
626
+ text: `… [truncated]\n${bytes
627
+ .subarray(bytes.length - Math.max(0, maxBytes - 18))
628
+ .toString("utf8")
629
+ .replace(/^�+/gu, "")}`,
630
+ truncated: true,
631
+ };
632
+ }
633
+
634
+ class JsonLineDecoder {
635
+ private buffer = "";
636
+ private dropping = false;
637
+ private readonly decoder = new StringDecoder("utf8");
638
+
639
+ constructor(
640
+ private readonly onValue: (value: unknown) => void,
641
+ private readonly onMalformed: () => void,
642
+ ) {}
643
+
644
+ push(chunk: Buffer | string): void {
645
+ this.buffer += typeof chunk === "string" ? chunk : this.decoder.write(chunk);
646
+ this.drain(false);
647
+ }
648
+
649
+ finish(): void {
650
+ this.buffer += this.decoder.end();
651
+ this.drain(true);
652
+ this.buffer = "";
653
+ this.dropping = false;
654
+ }
655
+
656
+ private drain(flush: boolean): void {
657
+ while (true) {
658
+ const newline = this.buffer.indexOf("\n");
659
+ if (newline < 0) break;
660
+ const line = this.buffer.slice(0, newline).replace(/\r$/u, "");
661
+ this.buffer = this.buffer.slice(newline + 1);
662
+ if (this.dropping) {
663
+ this.dropping = false;
664
+ continue;
665
+ }
666
+ this.parse(line);
667
+ }
668
+ if (!flush && Buffer.byteLength(this.buffer, "utf8") > MAX_EVENT_LINE_BYTES) {
669
+ this.onMalformed();
670
+ this.buffer = "";
671
+ this.dropping = true;
672
+ }
673
+ if (flush && this.buffer && !this.dropping) this.parse(this.buffer.replace(/\r$/u, ""));
674
+ }
675
+
676
+ private parse(line: string): void {
677
+ if (!line.trim()) return;
678
+ if (Buffer.byteLength(line, "utf8") > MAX_EVENT_LINE_BYTES) {
679
+ this.onMalformed();
680
+ return;
681
+ }
682
+ try {
683
+ this.onValue(JSON.parse(line));
684
+ } catch {
685
+ this.onMalformed();
686
+ }
687
+ }
688
+ }