@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,941 +0,0 @@
1
- import type { Api, Model } from "@earendil-works/pi-ai";
2
- import {
3
- type AgentSessionServices,
4
- getAgentDir,
5
- type ModelRegistry,
6
- type ModelRuntime,
7
- SessionManager,
8
- SettingsManager,
9
- } from "@earendil-works/pi-coding-agent";
10
- import { discoverAgents } from "./agents/discovery.js";
11
- import type { AgentConfig, SubagentThinkingLevel } from "./agents/types.js";
12
- import { formatPeerMessage } from "./child-peer-tools.js";
13
- import { redactPrivateText } from "./context.js";
14
- import { appendDelegationContract } from "./delegation-contract.js";
15
- import { resolveDefaultSubagentTimeoutMs } from "./execution/runtime-policy.js";
16
- import { DEFAULT_MAX_CONTEXT_BYTES, DEFAULT_MAX_OUTPUT_BYTES, truncateUtf8 } from "./limits.js";
17
- import {
18
- CHILD_PEER_TOOL_NAMES,
19
- createInProcessPeerExtension,
20
- type PeerTransportRuntime,
21
- } from "./peer-transport.js";
22
- import { resolvePiPromptResources } from "./prompt-resources.js";
23
- import type { AgentMailboxMessage, AgentTurn, ManagedAgent, TurnOutcome } from "./registry.js";
24
- import { appendResultInstruction } from "./result-contract.js";
25
- import { safeTerminalLine } from "./safe-text.js";
26
- import { readSubagentSettings } from "./settings.js";
27
- import {
28
- formatTimeoutCheckpoint,
29
- formatTurnTerminationMessage,
30
- journalMessages,
31
- TimeoutProgressJournal,
32
- TURN_TERMINATION_VERSION,
33
- type TurnTerminationReport,
34
- } from "./timeout-checkpoint.js";
35
- import {
36
- buildTimeoutFinalizationPrompt,
37
- resolveTimeoutFinalizationMs,
38
- } from "./timeout-finalization.js";
39
- import type { SubagentTransport } from "./transport.js";
40
- import type { TransportProgressCallback, TransportTelemetry } from "./transport-types.js";
41
- import { TurnBudgetMonitor, type TurnBudgetStop, type TurnLimits } from "./turn-budget.js";
42
-
43
- const BUILT_IN_TOOL_NAMES = new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]);
44
- const DEFAULT_ABORT_GRACE_MS = 5_000;
45
-
46
- interface ChildModelRuntime {
47
- getModel(provider: string, modelId: string): Model<Api> | undefined;
48
- registerProvider(provider: string, config: unknown): void;
49
- registerNativeProvider?(provider: unknown): void;
50
- setRuntimeApiKey(provider: string, apiKey: string): Promise<void> | void;
51
- }
52
-
53
- interface CodingAgentRuntimeModule {
54
- createAgentSessionFromServices?: typeof import("@earendil-works/pi-coding-agent").createAgentSessionFromServices;
55
- createAgentSessionServices?: typeof import("@earendil-works/pi-coding-agent").createAgentSessionServices;
56
- resolveCliModel?: typeof import("@earendil-works/pi-coding-agent").resolveCliModel;
57
- }
58
-
59
- interface CoreModelSupport {
60
- modelRuntime: ModelRuntime;
61
- resolveCliModel: typeof import("@earendil-works/pi-coding-agent").resolveCliModel;
62
- }
63
-
64
- interface CoreSessionSupport {
65
- createAgentSessionFromServices: typeof import("@earendil-works/pi-coding-agent").createAgentSessionFromServices;
66
- createAgentSessionServices: typeof import("@earendil-works/pi-coding-agent").createAgentSessionServices;
67
- resolveCliModel: typeof import("@earendil-works/pi-coding-agent").resolveCliModel;
68
- }
69
-
70
- interface RegisteredProviderRegistry {
71
- getRegisteredProviderConfig?(provider: string): unknown;
72
- getRegisteredProviderIds?(): readonly string[];
73
- getRegisteredNativeProvider?(provider: string): unknown;
74
- }
75
-
76
- export interface ParentRuntimeSnapshot {
77
- model: Model<Api> | undefined;
78
- thinkingLevel: SubagentThinkingLevel;
79
- }
80
-
81
- export interface ChildSession {
82
- readonly sessionId: string;
83
- readonly messages: readonly unknown[];
84
- readonly provider?: string;
85
- readonly model?: string;
86
- readonly thinkingLevel?: SubagentThinkingLevel;
87
- prompt(text: string): Promise<void>;
88
- steer?(text: string): Promise<void>;
89
- subscribe(listener: (event: unknown) => void): () => void;
90
- abort(): Promise<void>;
91
- dispose(): void;
92
- getActiveToolNames(): string[];
93
- }
94
-
95
- export interface ChildSessionCreateOptions {
96
- agent: ManagedAgent;
97
- agentConfig: AgentConfig;
98
- context?: string;
99
- history: AgentTurn[];
100
- modelRegistry: ModelRegistry;
101
- parentRuntime: ParentRuntimeSnapshot;
102
- tools?: string[];
103
- peerRuntime?: PeerTransportRuntime;
104
- }
105
-
106
- export type ChildSessionFactory = (options: ChildSessionCreateOptions) => Promise<ChildSession>;
107
-
108
- export interface InProcessTransportOptions {
109
- modelRegistry: ModelRegistry;
110
- getParentRuntime: () => ParentRuntimeSnapshot;
111
- createSession?: ChildSessionFactory;
112
- discoverAgent?: (agent: ManagedAgent) => AgentConfig | undefined;
113
- defaultTimeoutMs?: number;
114
- abortGraceMs?: number;
115
- timeoutFinalizationMs?: number;
116
- peerRuntime?: PeerTransportRuntime;
117
- }
118
-
119
- interface ChildSessionRecord {
120
- session: ChildSession;
121
- unsubscribe: () => void;
122
- lastOutput: string;
123
- disposed: boolean;
124
- }
125
-
126
- type PromptSettlement =
127
- | { kind: "completed" }
128
- | { kind: "failed"; error: unknown }
129
- | { kind: "timeout" }
130
- | { kind: "limit"; stop: TurnBudgetStop }
131
- | { kind: "aborted" };
132
-
133
- export class InProcessTransport implements SubagentTransport {
134
- readonly kind = "in-process" as const;
135
- private readonly sessions = new Map<string, ChildSessionRecord>();
136
- private readonly createSession: ChildSessionFactory;
137
- private readonly discoverAgent: (agent: ManagedAgent) => AgentConfig | undefined;
138
- private readonly defaultTimeoutMs: number;
139
- private readonly abortGraceMs: number;
140
-
141
- constructor(private readonly options: InProcessTransportOptions) {
142
- this.createSession = options.createSession ?? createSdkChildSession;
143
- this.discoverAgent =
144
- options.discoverAgent ??
145
- ((agent) =>
146
- discoverAgents(agent.cwd, agent.agentScope ?? "user", readSubagentSettings()).agents.find(
147
- (candidate) => candidate.name === agent.agent,
148
- ));
149
- this.defaultTimeoutMs = options.defaultTimeoutMs ?? resolveDefaultSubagentTimeoutMs();
150
- this.abortGraceMs = options.abortGraceMs ?? DEFAULT_ABORT_GRACE_MS;
151
- }
152
-
153
- async runTurn(
154
- agent: ManagedAgent,
155
- task: string,
156
- signal: AbortSignal,
157
- onProgress?: TransportProgressCallback,
158
- ): Promise<TurnOutcome> {
159
- const startedAt = Date.now();
160
- let telemetry: TransportTelemetry = {
161
- transport: "in-process",
162
- phase: "starting",
163
- updatedAt: startedAt,
164
- timing: { startedAt, transportStartedAt: startedAt },
165
- };
166
- const publish = (patch: Partial<TransportTelemetry>) => {
167
- telemetry = {
168
- ...telemetry,
169
- ...patch,
170
- timing: { ...telemetry.timing, ...patch.timing },
171
- updatedAt: Date.now(),
172
- };
173
- onProgress?.({ ...telemetry, timing: { ...telemetry.timing } });
174
- };
175
- publish({});
176
- if (signal.aborted) {
177
- publish({ phase: "interrupted", failurePhase: "starting" });
178
- return { ...interruptedOutcome(""), telemetry };
179
- }
180
- const agentConfig = this.discoverAgent(agent);
181
- if (!agentConfig) {
182
- publish({ phase: "failed", failurePhase: "starting" });
183
- return {
184
- output: "",
185
- exitCode: 1,
186
- error: `Unknown subagent: ${agent.agent}`,
187
- telemetry,
188
- };
189
- }
190
- let tools: string[] | undefined;
191
- try {
192
- tools = validateInProcessTools(agent.executionPlan?.effectiveTools ?? agentConfig.tools);
193
- } catch (error) {
194
- publish({ phase: "failed", failurePhase: "starting" });
195
- return { output: "", exitCode: 1, error: errorMessage(error), telemetry };
196
- }
197
- let record: ChildSessionRecord;
198
- try {
199
- record = await this.getOrCreate(agent, agentConfig, tools);
200
- } catch (error) {
201
- publish({ phase: "failed", failurePhase: "starting" });
202
- return { output: "", exitCode: 1, error: errorMessage(error), telemetry };
203
- }
204
- publish({
205
- phase: "ready",
206
- provider: record.session.provider,
207
- model: record.session.model,
208
- thinkingLevel: record.session.thinkingLevel,
209
- timing: { readyAt: Date.now() },
210
- });
211
- if (signal.aborted) {
212
- await this.releaseById(agent.id).catch(() => undefined);
213
- publish({ phase: "interrupted", failurePhase: "ready" });
214
- return { ...interruptedOutcome(""), telemetry };
215
- }
216
- const prompt = buildCurrentTurnPrompt(agent, task);
217
- const timeoutMs =
218
- agent.currentTimeoutMs ?? agent.timeoutMs ?? agentConfig.timeoutMs ?? this.defaultTimeoutMs;
219
- const startingMessageCount = record.session.messages.length;
220
- record.lastOutput = "";
221
- publish({ phase: "running", timing: { promptAcceptedAt: Date.now() } });
222
- const settlement = await this.runPrompt(record, prompt, signal, timeoutMs, {
223
- idleTimeoutMs: agent.currentIdleTimeoutMs ?? agent.idleTimeoutMs,
224
- maxTurns: agent.currentMaxTurns ?? agent.maxTurns,
225
- maxToolCalls: agent.currentMaxToolCalls ?? agent.maxToolCalls,
226
- });
227
- const final = latestAssistant(record.session.messages.slice(startingMessageCount));
228
- const output = truncateUtf8(final.output || record.lastOutput, DEFAULT_MAX_OUTPUT_BYTES);
229
- const truncated = output.truncated || agent.contextTruncated;
230
- const policy = inProcessPolicy(agentConfig, agent);
231
- const settledAt = Date.now();
232
- if (signal.aborted && (settlement.kind === "timeout" || settlement.kind === "limit")) {
233
- publish({ phase: "interrupted", failurePhase: "running", timing: { settledAt } });
234
- return {
235
- ...interruptedOutcome(output.text),
236
- truncated,
237
- policy,
238
- telemetry,
239
- };
240
- }
241
-
242
- switch (settlement.kind) {
243
- case "completed":
244
- publish({
245
- phase: final.stopReason === "error" ? "failed" : "settled",
246
- timing: { settledAt },
247
- });
248
- if (final.stopReason === "error") {
249
- return {
250
- output: output.text,
251
- exitCode: 1,
252
- truncated,
253
- error: final.error || "In-process subagent returned an error",
254
- policy,
255
- telemetry,
256
- };
257
- }
258
- if (final.stopReason === "aborted") {
259
- publish({ phase: "interrupted", failurePhase: "running" });
260
- return {
261
- ...interruptedOutcome(output.text),
262
- truncated,
263
- policy,
264
- telemetry,
265
- };
266
- }
267
- return {
268
- output: output.text,
269
- exitCode: 0,
270
- truncated,
271
- policy,
272
- telemetry,
273
- };
274
- case "failed":
275
- publish({ phase: "failed", failurePhase: "running", timing: { settledAt } });
276
- return {
277
- output: output.text,
278
- exitCode: 1,
279
- truncated,
280
- error: errorMessage(settlement.error),
281
- policy,
282
- telemetry,
283
- };
284
- case "timeout":
285
- case "limit": {
286
- const stop =
287
- settlement.kind === "limit"
288
- ? settlement.stop
289
- : ({ reason: "work_timeout", limit: timeoutMs } as const);
290
- const journal = new TimeoutProgressJournal();
291
- journalMessages(journal, record.session.messages.slice(startingMessageCount));
292
- const termination: TurnTerminationReport = {
293
- version: TURN_TERMINATION_VERSION,
294
- reason: stop.reason,
295
- limit: stop.limit,
296
- checkpoint: journal.checkpoint(task, output.text),
297
- finalization: { attempted: false, status: "skipped", durationMs: 0 },
298
- };
299
- let finalizedOutput = output.text || formatTimeoutCheckpoint(termination.checkpoint);
300
- let finalizationError: string | undefined;
301
- if (!signal.aborted && this.sessions.get(agent.id) === record) {
302
- publish({ phase: "finalizing", failurePhase: "running" });
303
- const summaryStart = record.session.messages.length;
304
- const finalizationStartedAt = Date.now();
305
- record.lastOutput = "";
306
- const summarySettlement = await this.runPrompt(
307
- record,
308
- buildTimeoutFinalizationPrompt({
309
- task,
310
- partialOutput: output.text,
311
- checkpoint: termination.checkpoint,
312
- terminationReason: stop.reason,
313
- resultFormat: agent.resultFormat,
314
- }),
315
- signal,
316
- resolveTimeoutFinalizationMs(timeoutMs, this.options.timeoutFinalizationMs),
317
- );
318
- const summary = latestAssistant(record.session.messages.slice(summaryStart));
319
- const boundedSummary = truncateUtf8(
320
- summary.output || record.lastOutput,
321
- DEFAULT_MAX_OUTPUT_BYTES,
322
- );
323
- if (
324
- summarySettlement.kind === "completed" &&
325
- summary.stopReason !== "error" &&
326
- boundedSummary.text.trim()
327
- ) {
328
- finalizedOutput = boundedSummary.text;
329
- termination.finalization = {
330
- attempted: true,
331
- status: "completed",
332
- durationMs: Date.now() - finalizationStartedAt,
333
- };
334
- } else {
335
- finalizationError =
336
- summarySettlement.kind === "failed"
337
- ? errorMessage(summarySettlement.error)
338
- : `timeout summary ${summarySettlement.kind}`;
339
- termination.finalization = {
340
- attempted: true,
341
- status: summarySettlement.kind === "timeout" ? "timed_out" : "failed",
342
- durationMs: Date.now() - finalizationStartedAt,
343
- error: finalizationError,
344
- };
345
- }
346
- }
347
- publish({ phase: "failed", failurePhase: "running", timing: { settledAt: Date.now() } });
348
- return {
349
- output: finalizedOutput,
350
- exitCode: 124,
351
- truncated,
352
- error: [
353
- formatTurnTerminationMessage(stop.reason, stop.limit, "In-process subagent"),
354
- finalizationError,
355
- ]
356
- .filter(Boolean)
357
- .join("; "),
358
- policy,
359
- termination,
360
- telemetry,
361
- };
362
- }
363
- case "aborted":
364
- publish({ phase: "interrupted", failurePhase: "running", timing: { settledAt } });
365
- return {
366
- ...interruptedOutcome(output.text),
367
- truncated,
368
- policy,
369
- telemetry,
370
- };
371
- }
372
- }
373
-
374
- async deliverMessage(agent: ManagedAgent, message: AgentMailboxMessage): Promise<boolean> {
375
- const record = this.sessions.get(agent.id);
376
- if (!record || record.disposed || !record.session.steer) return false;
377
- await record.session.steer(formatPeerMessage(message));
378
- return true;
379
- }
380
-
381
- async release(agent: ManagedAgent): Promise<void> {
382
- await this.releaseById(agent.id);
383
- }
384
-
385
- async shutdown(): Promise<void> {
386
- const agentIds = [...this.sessions.keys()];
387
- const results = await Promise.allSettled(agentIds.map((agentId) => this.releaseById(agentId)));
388
- const failures = results.flatMap((result) =>
389
- result.status === "rejected" ? [result.reason] : [],
390
- );
391
- if (failures.length > 0) {
392
- throw new AggregateError(
393
- failures,
394
- `Failed to dispose ${failures.length} in-process subagent session(s)`,
395
- );
396
- }
397
- }
398
-
399
- private async releaseById(agentId: string): Promise<void> {
400
- const record = this.sessions.get(agentId);
401
- if (!record) return;
402
- this.sessions.delete(agentId);
403
- this.options.peerRuntime?.revoke(agentId);
404
- if (record.disposed) return;
405
- record.disposed = true;
406
- const failures: unknown[] = [];
407
- try {
408
- record.unsubscribe();
409
- } catch (error) {
410
- failures.push(error);
411
- }
412
- if (record.session.messages.length > 0) {
413
- await settleWithin(record.session.abort(), this.abortGraceMs);
414
- }
415
- try {
416
- record.session.dispose();
417
- } catch (error) {
418
- failures.push(error);
419
- }
420
- if (failures.length > 0) {
421
- throw new AggregateError(
422
- failures,
423
- `Failed to release in-process subagent ${agentId}: ${failures.map(errorMessage).join("; ")}`,
424
- );
425
- }
426
- }
427
-
428
- private async getOrCreate(
429
- agent: ManagedAgent,
430
- agentConfig: AgentConfig,
431
- tools: string[] | undefined,
432
- ): Promise<ChildSessionRecord> {
433
- const existing = this.sessions.get(agent.id);
434
- if (existing) return existing;
435
- const session = await this.createSession({
436
- agent,
437
- agentConfig,
438
- context: agent.context,
439
- history: agent.history.map((turn) => ({ ...turn })),
440
- modelRegistry: this.options.modelRegistry,
441
- parentRuntime: this.options.getParentRuntime(),
442
- tools,
443
- peerRuntime: this.options.peerRuntime,
444
- });
445
- const record: ChildSessionRecord = {
446
- session,
447
- lastOutput: "",
448
- disposed: false,
449
- unsubscribe: () => undefined,
450
- };
451
- try {
452
- record.unsubscribe = session.subscribe((event) => {
453
- const message = eventMessage(event);
454
- if (!message) return;
455
- const output = assistantText(message);
456
- if (output) record.lastOutput = truncateUtf8(output, DEFAULT_MAX_OUTPUT_BYTES).text;
457
- });
458
- } catch (error) {
459
- record.disposed = true;
460
- try {
461
- session.dispose();
462
- } catch {
463
- // Preserve the subscription failure, which explains why creation was rejected.
464
- }
465
- throw error;
466
- }
467
- this.sessions.set(agent.id, record);
468
- return record;
469
- }
470
-
471
- private async runPrompt(
472
- record: ChildSessionRecord,
473
- prompt: string,
474
- signal: AbortSignal,
475
- timeoutMs: number,
476
- limits: TurnLimits = {},
477
- ): Promise<PromptSettlement> {
478
- if (signal.aborted) return { kind: "aborted" };
479
- let timeout: NodeJS.Timeout | undefined;
480
- let abortHandler: (() => void) | undefined;
481
- let resolveLimit!: (settlement: PromptSettlement) => void;
482
- const limitSettlement = new Promise<PromptSettlement>((resolve) => {
483
- resolveLimit = resolve;
484
- });
485
- const monitor = new TurnBudgetMonitor({
486
- ...limits,
487
- onExceeded: (stop) => resolveLimit({ kind: "limit", stop }),
488
- });
489
- const unsubscribeBudget = record.session.subscribe((event) => {
490
- const type = childEventType(event);
491
- if (type === "tool_execution_end") monitor.recordActivity();
492
- if (type !== "message_end") return;
493
- const message = eventMessage(event);
494
- if (!message || typeof message !== "object" || Array.isArray(message)) return;
495
- const value = message as Record<string, unknown>;
496
- if (value.role === "toolResult") {
497
- monitor.recordActivity();
498
- return;
499
- }
500
- if (value.role !== "assistant") return;
501
- monitor.recordToolCalls(assistantToolCallCount(value.content));
502
- monitor.recordAssistantTurn(
503
- typeof value.stopReason === "string" ? value.stopReason : undefined,
504
- );
505
- });
506
- const promptSettlement: Promise<PromptSettlement> = Promise.resolve()
507
- .then(() => {
508
- if (signal.aborted) throw new Error("In-process subagent prompt aborted before start");
509
- return record.session.prompt(prompt);
510
- })
511
- .then(() => ({ kind: "completed" as const }))
512
- .catch((error: unknown) => ({ kind: "failed" as const, error }));
513
- const timeoutSettlement = new Promise<PromptSettlement>((resolve) => {
514
- timeout = setTimeout(() => resolve({ kind: "timeout" }), timeoutMs);
515
- });
516
- const abortSettlement = new Promise<PromptSettlement>((resolve) => {
517
- abortHandler = () => resolve({ kind: "aborted" });
518
- signal.addEventListener("abort", abortHandler, { once: true });
519
- if (signal.aborted) abortHandler();
520
- });
521
- const settlement = await Promise.race([
522
- promptSettlement,
523
- timeoutSettlement,
524
- abortSettlement,
525
- limitSettlement,
526
- ]);
527
- if (timeout) clearTimeout(timeout);
528
- if (abortHandler) signal.removeEventListener("abort", abortHandler);
529
- try {
530
- unsubscribeBudget();
531
- } catch {
532
- // The owning record's unsubscribe/dispose path remains authoritative.
533
- }
534
- monitor.dispose();
535
- if (
536
- settlement.kind === "timeout" ||
537
- settlement.kind === "limit" ||
538
- settlement.kind === "aborted"
539
- ) {
540
- const [, settledAfterAbort] = await Promise.all([
541
- settleWithin(record.session.abort(), this.abortGraceMs),
542
- completesWithin(promptSettlement, this.abortGraceMs),
543
- ]);
544
- if (!settledAfterAbort) this.discardRecord(record);
545
- }
546
- return settlement;
547
- }
548
-
549
- private discardRecord(record: ChildSessionRecord): void {
550
- for (const [agentId, candidate] of this.sessions) {
551
- if (candidate === record) this.sessions.delete(agentId);
552
- }
553
- if (record.disposed) return;
554
- record.disposed = true;
555
- record.unsubscribe();
556
- record.session.dispose();
557
- }
558
- }
559
-
560
- export function validateInProcessTools(tools: string[] | undefined): string[] | undefined {
561
- if (tools === undefined) return undefined;
562
- const unique = [...new Set(tools)];
563
- const unsupported = unique.filter((tool) => !BUILT_IN_TOOL_NAMES.has(tool));
564
- if (unsupported.length > 0) {
565
- throw new Error(
566
- `In-process subagents cannot load extension/custom tools: ${unsupported.map((tool) => safeTerminalLine(tool, 256)).join(", ")}. Use stateful.transport "subprocess" for this agent.`,
567
- );
568
- }
569
- return unique;
570
- }
571
-
572
- export async function createSdkChildSession(
573
- options: ChildSessionCreateOptions,
574
- ): Promise<ChildSession> {
575
- const agentDir = getAgentDir();
576
- const projectTrusted =
577
- options.agent.target?.trust.projectTrusted ??
578
- (options.agent.agentScope === "project" || options.agent.agentScope === "both");
579
- const { services, support: coreSupport } = await prepareInProcessServices(
580
- options.agent.cwd,
581
- agentDir,
582
- options.agentConfig.systemPrompt,
583
- projectTrusted,
584
- options.peerRuntime
585
- ? createInProcessPeerExtension(options.peerRuntime, options.agent.id)
586
- : undefined,
587
- );
588
- copyRegisteredProviders(
589
- options.modelRegistry as unknown as RegisteredProviderRegistry,
590
- services.modelRuntime as unknown as ChildModelRuntime,
591
- );
592
- const modelSupport: CoreModelSupport = {
593
- modelRuntime: services.modelRuntime,
594
- resolveCliModel: coreSupport.resolveCliModel,
595
- };
596
- const resolved = await resolveChildModel(options, modelSupport);
597
- await transferChildModelAuth(options.modelRegistry, resolved.model, services.modelRuntime);
598
- const model = resolved.model;
599
- const sessionManager = SessionManager.inMemory(options.agent.cwd);
600
- seedChildSessionManager(sessionManager, options, model);
601
- const selectedTools =
602
- options.tools === undefined
603
- ? undefined
604
- : options.peerRuntime
605
- ? [...options.tools, ...CHILD_PEER_TOOL_NAMES]
606
- : options.tools;
607
- const created = await coreSupport.createAgentSessionFromServices({
608
- services,
609
- sessionManager,
610
- model,
611
- thinkingLevel: resolved.thinkingLevel,
612
- tools: selectedTools,
613
- noTools: selectedTools?.length === 0 ? "all" : undefined,
614
- });
615
- const session = created.session;
616
- if (selectedTools !== undefined) {
617
- const active = session.getActiveToolNames();
618
- const expected = [...selectedTools].sort();
619
- if (
620
- active.length !== expected.length ||
621
- [...active].sort().some((name, index) => name !== expected[index])
622
- ) {
623
- session.dispose();
624
- throw new Error(
625
- `In-process child activated an unexpected tool set (${active.join(", ") || "none"}); use stateful.transport "subprocess".`,
626
- );
627
- }
628
- }
629
- return {
630
- get sessionId() {
631
- return session.sessionId;
632
- },
633
- get messages() {
634
- return session.messages;
635
- },
636
- get provider() {
637
- return session.model?.provider;
638
- },
639
- get model() {
640
- return session.model?.id;
641
- },
642
- get thinkingLevel() {
643
- return session.thinkingLevel;
644
- },
645
- prompt: (text) => session.prompt(text),
646
- steer: (text) => session.steer(text),
647
- subscribe: (listener) => session.subscribe((event) => listener(event)),
648
- abort: () => session.abort(),
649
- dispose: () => session.dispose(),
650
- getActiveToolNames: () => session.getActiveToolNames(),
651
- };
652
- }
653
-
654
- async function loadCoreSessionSupport(): Promise<CoreSessionSupport | undefined> {
655
- const codingAgentModule = (await import(
656
- "@earendil-works/pi-coding-agent"
657
- )) as unknown as CodingAgentRuntimeModule;
658
- if (
659
- !codingAgentModule.createAgentSessionFromServices ||
660
- !codingAgentModule.createAgentSessionServices ||
661
- !codingAgentModule.resolveCliModel
662
- ) {
663
- return undefined;
664
- }
665
- return {
666
- createAgentSessionFromServices: codingAgentModule.createAgentSessionFromServices,
667
- createAgentSessionServices: codingAgentModule.createAgentSessionServices,
668
- resolveCliModel: codingAgentModule.resolveCliModel,
669
- };
670
- }
671
-
672
- async function transferChildModelAuth(
673
- modelRegistry: ModelRegistry,
674
- model: Model<Api>,
675
- modelRuntime: ModelRuntime,
676
- ): Promise<void> {
677
- const auth = await modelRegistry.getApiKeyAndHeaders(model);
678
- if (auth.ok && auth.apiKey) await modelRuntime.setRuntimeApiKey(model.provider, auth.apiKey);
679
- }
680
-
681
- export function copyRegisteredProviders(
682
- registeredProviders: RegisteredProviderRegistry,
683
- modelRuntime: ChildModelRuntime,
684
- ): void {
685
- for (const provider of registeredProviders.getRegisteredProviderIds?.() ?? []) {
686
- const config = registeredProviders.getRegisteredProviderConfig?.(provider);
687
- if (config !== undefined) {
688
- modelRuntime.registerProvider(provider, config);
689
- continue;
690
- }
691
- const nativeProvider = registeredProviders.getRegisteredNativeProvider?.(provider);
692
- if (nativeProvider) modelRuntime.registerNativeProvider?.(nativeProvider);
693
- }
694
- }
695
-
696
- export async function resolveChildModel(
697
- options: ChildSessionCreateOptions,
698
- support?: CoreModelSupport,
699
- ): Promise<{
700
- model: Model<Api>;
701
- thinkingLevel: SubagentThinkingLevel;
702
- }> {
703
- if (!support) throw unsupportedInProcessCoreError();
704
- let model = options.parentRuntime.model;
705
- let modelThinkingLevel: SubagentThinkingLevel | undefined;
706
- if (options.agentConfig.model !== undefined) {
707
- const requested = options.agentConfig.model.trim();
708
- if (!requested) throw new Error("In-process subagent model cannot be empty");
709
- const resolved = support.resolveCliModel({
710
- cliModel: requested,
711
- modelRuntime: support.modelRuntime,
712
- });
713
- if (resolved.error) throw new Error(resolved.error);
714
- if (!resolved.model)
715
- throw new Error(`Unable to resolve in-process subagent model ${requested}`);
716
- model = resolved.model;
717
- modelThinkingLevel = resolved.thinkingLevel;
718
- }
719
- if (!model) model = options.modelRegistry.getAvailable()[0];
720
- if (!model)
721
- throw new Error("No model with configured authentication is available for in-process subagent");
722
- model = support.modelRuntime.getModel(model.provider, model.id) ?? model;
723
- return {
724
- model,
725
- thinkingLevel:
726
- options.agent.thinkingLevel ??
727
- options.agentConfig.thinkingLevel ??
728
- modelThinkingLevel ??
729
- options.parentRuntime.thinkingLevel,
730
- };
731
- }
732
-
733
- function unsupportedInProcessCoreError(): Error {
734
- return new Error(
735
- 'In-process subagents require Pi core createAgentSessionServices, createAgentSessionFromServices, and resolveCliModel support; set stateful.transport to "subprocess".',
736
- );
737
- }
738
-
739
- async function prepareInProcessServices(
740
- cwd: string,
741
- agentDir: string,
742
- agentSystemPrompt: string,
743
- projectTrusted: boolean,
744
- peerExtension?: import("@earendil-works/pi-coding-agent").ExtensionFactory,
745
- ): Promise<{ services: AgentSessionServices; support: CoreSessionSupport }> {
746
- const promptResources = await resolvePiPromptResources(cwd, projectTrusted, agentDir);
747
- const settingsManager = SettingsManager.create(cwd, agentDir, { projectTrusted });
748
- const support = await loadCoreSessionSupport();
749
- if (!support) throw unsupportedInProcessCoreError();
750
- const services = await support.createAgentSessionServices({
751
- cwd,
752
- agentDir,
753
- settingsManager,
754
- resourceLoaderOptions: {
755
- noExtensions: true,
756
- ...(peerExtension ? { extensionFactories: [peerExtension] } : {}),
757
- appendSystemPrompt: [
758
- ...promptResources.appendSystemPromptPaths,
759
- ...(agentSystemPrompt.trim() ? [agentSystemPrompt] : []),
760
- ],
761
- },
762
- });
763
- return { services, support };
764
- }
765
-
766
- export async function createInProcessServices(
767
- cwd: string,
768
- agentDir: string,
769
- agentSystemPrompt: string,
770
- projectTrusted = false,
771
- ): Promise<AgentSessionServices> {
772
- return (await prepareInProcessServices(cwd, agentDir, agentSystemPrompt, projectTrusted))
773
- .services;
774
- }
775
-
776
- export function seedChildSessionManager(
777
- sessionManager: SessionManager,
778
- options: ChildSessionCreateOptions,
779
- model: Model<Api>,
780
- ): void {
781
- let timestamp = Date.now() - (options.history.length * 2 + 1);
782
- if (options.context?.trim()) {
783
- sessionManager.appendMessage({
784
- role: "user",
785
- content: `Parent context:\n${redactPrivateText(options.context)}`,
786
- timestamp: timestamp++,
787
- });
788
- }
789
- for (const turn of options.history) {
790
- sessionManager.appendMessage({
791
- role: "user",
792
- content: redactPrivateText(turn.task),
793
- timestamp: timestamp++,
794
- });
795
- sessionManager.appendMessage({
796
- role: "assistant",
797
- content: [{ type: "text", text: redactPrivateText(turn.output) }],
798
- api: model.api,
799
- provider: model.provider,
800
- model: model.id,
801
- usage: {
802
- input: 0,
803
- output: 0,
804
- cacheRead: 0,
805
- cacheWrite: 0,
806
- totalTokens: 0,
807
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
808
- },
809
- stopReason: turn.exitCode === 0 ? "stop" : "error",
810
- timestamp: timestamp++,
811
- });
812
- }
813
- }
814
-
815
- export function buildCurrentTurnPrompt(agent: ManagedAgent, task: string): string {
816
- const ids = new Set(agent.currentMailboxMessageIds ?? []);
817
- const messages = agent.mailbox
818
- .filter((message) => ids.has(message.id))
819
- .slice(-20)
820
- .map((message) =>
821
- formatPeerMessage({ ...message, content: redactPrivateText(message.content) }),
822
- )
823
- .join("\n\n");
824
- const base = messages
825
- ? `${redactPrivateText(task)}\n\nMailbox messages:\n${messages}`
826
- : redactPrivateText(task);
827
- const contracted = appendDelegationContract(base, agent.contract, DEFAULT_MAX_CONTEXT_BYTES);
828
- return truncateUtf8(
829
- appendResultInstruction(contracted.text, agent.resultFormat),
830
- DEFAULT_MAX_CONTEXT_BYTES,
831
- ).text;
832
- }
833
-
834
- function latestAssistant(messages: readonly unknown[]): {
835
- output: string;
836
- stopReason?: string;
837
- error?: string;
838
- } {
839
- for (let index = messages.length - 1; index >= 0; index--) {
840
- const message = messages[index];
841
- if (!message || typeof message !== "object") continue;
842
- const candidate = message as { role?: string; stopReason?: string; errorMessage?: string };
843
- if (candidate.role !== "assistant") continue;
844
- return {
845
- output: assistantText(message),
846
- stopReason: candidate.stopReason,
847
- error: candidate.errorMessage,
848
- };
849
- }
850
- return { output: "" };
851
- }
852
-
853
- function childEventType(event: unknown): string | undefined {
854
- if (!event || typeof event !== "object" || Array.isArray(event)) return undefined;
855
- const type = (event as { type?: unknown }).type;
856
- return typeof type === "string" ? type : undefined;
857
- }
858
-
859
- function assistantToolCallCount(content: unknown): number {
860
- if (!Array.isArray(content)) return 0;
861
- return content.filter(
862
- (part) =>
863
- part &&
864
- typeof part === "object" &&
865
- !Array.isArray(part) &&
866
- (part as { type?: unknown }).type === "toolCall",
867
- ).length;
868
- }
869
-
870
- function eventMessage(event: unknown): unknown {
871
- if (!event || typeof event !== "object") return undefined;
872
- const candidate = event as { type?: string; message?: unknown };
873
- return candidate.type === "message_update" || candidate.type === "message_end"
874
- ? candidate.message
875
- : undefined;
876
- }
877
-
878
- function assistantText(message: unknown): string {
879
- if (!message || typeof message !== "object") return "";
880
- const content = (message as { content?: unknown }).content;
881
- if (typeof content === "string") return content;
882
- if (!Array.isArray(content)) return "";
883
- return content
884
- .filter((part): part is { type: "text"; text: string } =>
885
- Boolean(
886
- part &&
887
- typeof part === "object" &&
888
- (part as { type?: unknown }).type === "text" &&
889
- typeof (part as { text?: unknown }).text === "string",
890
- ),
891
- )
892
- .map((part) => part.text)
893
- .join("\n");
894
- }
895
-
896
- function interruptedOutcome(output: string): TurnOutcome {
897
- return { output, exitCode: 130, aborted: true, error: "In-process subagent was aborted" };
898
- }
899
-
900
- function inProcessPolicy(
901
- agentConfig: AgentConfig,
902
- managedAgent: ManagedAgent,
903
- ): NonNullable<TurnOutcome["policy"]> {
904
- return {
905
- inherited: ["modelRegistry", "authentication", "cwdResources"],
906
- overridden: [
907
- ...(agentConfig.model ? ["model"] : []),
908
- ...(managedAgent.thinkingLevel || agentConfig.thinkingLevel ? ["thinkingLevel"] : []),
909
- ...(agentConfig.tools ? ["tools"] : []),
910
- ],
911
- unsupported: ["approvalPolicy", "sandboxProfile", "providerHeaders", "extensionState"],
912
- };
913
- }
914
-
915
- async function settleWithin(promise: Promise<unknown>, timeoutMs: number): Promise<void> {
916
- await completesWithin(
917
- promise.catch(() => undefined),
918
- timeoutMs,
919
- );
920
- }
921
-
922
- async function completesWithin(promise: Promise<unknown>, timeoutMs: number): Promise<boolean> {
923
- let timeout: NodeJS.Timeout | undefined;
924
- try {
925
- return await Promise.race([
926
- promise.then(() => true),
927
- new Promise<boolean>((resolve) => {
928
- timeout = setTimeout(() => resolve(false), timeoutMs);
929
- }),
930
- ]);
931
- } finally {
932
- if (timeout) clearTimeout(timeout);
933
- }
934
- }
935
-
936
- function errorMessage(error: unknown): string {
937
- return truncateUtf8(
938
- error instanceof Error ? error.message : String(error),
939
- DEFAULT_MAX_OUTPUT_BYTES,
940
- ).text;
941
- }