@narumitw/pi-subagents 2.1.4 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (312) hide show
  1. package/README.md +187 -1228
  2. package/dist/child-communication-bridge.ts +136 -0
  3. package/dist/child-communication-bridge.ts.map +7 -0
  4. package/dist/chunks/chunk-UKTWUQRM.js +667 -0
  5. package/dist/chunks/chunk-UKTWUQRM.js.map +7 -0
  6. package/dist/index.ts +1448 -1614
  7. package/dist/index.ts.map +4 -4
  8. package/docs/design-principles.md +31 -0
  9. package/docs/ipc-transport-idea.md +103 -0
  10. package/docs/tools.md +109 -0
  11. package/package.json +11 -19
  12. package/src/broker-credentials.ts +71 -0
  13. package/src/child-communication-bridge.ts +153 -0
  14. package/src/child-communication-tools.ts +147 -0
  15. package/src/completion-renderer.ts +60 -0
  16. package/src/index.ts +1 -1
  17. package/src/message-broker.ts +628 -0
  18. package/src/model-output.ts +42 -0
  19. package/src/process.ts +688 -0
  20. package/src/runtime.ts +538 -0
  21. package/src/subagents.ts +33 -34
  22. package/src/tools.ts +416 -0
  23. package/src/types.ts +85 -0
  24. package/src/widget.ts +130 -0
  25. package/dist/chunks/auto-transport-FUUKFDIG.ts +0 -109
  26. package/dist/chunks/auto-transport-FUUKFDIG.ts.map +0 -7
  27. package/dist/chunks/capability-grant-PR72SWWS.ts +0 -19
  28. package/dist/chunks/capability-grant-PR72SWWS.ts.map +0 -7
  29. package/dist/chunks/child-peer-bridge.ts +0 -108
  30. package/dist/chunks/child-peer-bridge.ts.map +0 -7
  31. package/dist/chunks/chunk-2LMJU25E.ts +0 -1641
  32. package/dist/chunks/chunk-2LMJU25E.ts.map +0 -7
  33. package/dist/chunks/chunk-47SK2QYC.ts +0 -56
  34. package/dist/chunks/chunk-47SK2QYC.ts.map +0 -7
  35. package/dist/chunks/chunk-4AQSF7AS.ts +0 -29
  36. package/dist/chunks/chunk-4AQSF7AS.ts.map +0 -7
  37. package/dist/chunks/chunk-5DGRMKNV.ts +0 -126
  38. package/dist/chunks/chunk-5DGRMKNV.ts.map +0 -7
  39. package/dist/chunks/chunk-6H6TBBED.ts +0 -108
  40. package/dist/chunks/chunk-6H6TBBED.ts.map +0 -7
  41. package/dist/chunks/chunk-6KJ34M6S.ts +0 -159
  42. package/dist/chunks/chunk-6KJ34M6S.ts.map +0 -7
  43. package/dist/chunks/chunk-6NSJVPXX.ts +0 -480
  44. package/dist/chunks/chunk-6NSJVPXX.ts.map +0 -7
  45. package/dist/chunks/chunk-7AAJEUSL.ts +0 -238
  46. package/dist/chunks/chunk-7AAJEUSL.ts.map +0 -7
  47. package/dist/chunks/chunk-BFK2Z4ZF.ts +0 -189
  48. package/dist/chunks/chunk-BFK2Z4ZF.ts.map +0 -7
  49. package/dist/chunks/chunk-BOAXY55Y.ts +0 -153
  50. package/dist/chunks/chunk-BOAXY55Y.ts.map +0 -7
  51. package/dist/chunks/chunk-D4CR7T73.ts +0 -353
  52. package/dist/chunks/chunk-D4CR7T73.ts.map +0 -7
  53. package/dist/chunks/chunk-FEVPWRMU.ts +0 -300
  54. package/dist/chunks/chunk-FEVPWRMU.ts.map +0 -7
  55. package/dist/chunks/chunk-G6VZTCFH.ts +0 -70
  56. package/dist/chunks/chunk-G6VZTCFH.ts.map +0 -7
  57. package/dist/chunks/chunk-H3FP6DLR.ts +0 -160
  58. package/dist/chunks/chunk-H3FP6DLR.ts.map +0 -7
  59. package/dist/chunks/chunk-HA36LPCO.ts +0 -130
  60. package/dist/chunks/chunk-HA36LPCO.ts.map +0 -7
  61. package/dist/chunks/chunk-HOP5FXDT.ts +0 -27
  62. package/dist/chunks/chunk-HOP5FXDT.ts.map +0 -7
  63. package/dist/chunks/chunk-IGAMVWFN.ts +0 -139
  64. package/dist/chunks/chunk-IGAMVWFN.ts.map +0 -7
  65. package/dist/chunks/chunk-ILEQ27AL.ts +0 -45
  66. package/dist/chunks/chunk-ILEQ27AL.ts.map +0 -7
  67. package/dist/chunks/chunk-ITVWPNU4.ts +0 -819
  68. package/dist/chunks/chunk-ITVWPNU4.ts.map +0 -7
  69. package/dist/chunks/chunk-IWC32VPY.ts +0 -172
  70. package/dist/chunks/chunk-IWC32VPY.ts.map +0 -7
  71. package/dist/chunks/chunk-JSZIP73U.ts +0 -362
  72. package/dist/chunks/chunk-JSZIP73U.ts.map +0 -7
  73. package/dist/chunks/chunk-JU6LUNLP.ts +0 -380
  74. package/dist/chunks/chunk-JU6LUNLP.ts.map +0 -7
  75. package/dist/chunks/chunk-KMGKCEO4.ts +0 -38
  76. package/dist/chunks/chunk-KMGKCEO4.ts.map +0 -7
  77. package/dist/chunks/chunk-LASD73CM.ts +0 -339
  78. package/dist/chunks/chunk-LASD73CM.ts.map +0 -7
  79. package/dist/chunks/chunk-LEOYDZI3.ts +0 -22
  80. package/dist/chunks/chunk-LEOYDZI3.ts.map +0 -7
  81. package/dist/chunks/chunk-LL4LP2T7.ts +0 -737
  82. package/dist/chunks/chunk-LL4LP2T7.ts.map +0 -7
  83. package/dist/chunks/chunk-N2T5IN4X.ts +0 -18
  84. package/dist/chunks/chunk-N2T5IN4X.ts.map +0 -7
  85. package/dist/chunks/chunk-N7BLVXKK.ts +0 -73
  86. package/dist/chunks/chunk-N7BLVXKK.ts.map +0 -7
  87. package/dist/chunks/chunk-NLT67IZS.ts +0 -322
  88. package/dist/chunks/chunk-NLT67IZS.ts.map +0 -7
  89. package/dist/chunks/chunk-NTRPLF46.ts +0 -63
  90. package/dist/chunks/chunk-NTRPLF46.ts.map +0 -7
  91. package/dist/chunks/chunk-ONDTY4EL.ts +0 -91
  92. package/dist/chunks/chunk-ONDTY4EL.ts.map +0 -7
  93. package/dist/chunks/chunk-OVPHFGKO.ts +0 -1769
  94. package/dist/chunks/chunk-OVPHFGKO.ts.map +0 -7
  95. package/dist/chunks/chunk-P7OH4XMF.ts +0 -60
  96. package/dist/chunks/chunk-P7OH4XMF.ts.map +0 -7
  97. package/dist/chunks/chunk-PBZMBTNJ.ts +0 -422
  98. package/dist/chunks/chunk-PBZMBTNJ.ts.map +0 -7
  99. package/dist/chunks/chunk-PGLSFLYW.ts +0 -52
  100. package/dist/chunks/chunk-PGLSFLYW.ts.map +0 -7
  101. package/dist/chunks/chunk-RRR66UWR.ts +0 -28
  102. package/dist/chunks/chunk-RRR66UWR.ts.map +0 -7
  103. package/dist/chunks/chunk-RSUXZD6S.ts +0 -275
  104. package/dist/chunks/chunk-RSUXZD6S.ts.map +0 -7
  105. package/dist/chunks/chunk-RTCVYIZA.ts +0 -221
  106. package/dist/chunks/chunk-RTCVYIZA.ts.map +0 -7
  107. package/dist/chunks/chunk-RY2AEGMZ.ts +0 -34
  108. package/dist/chunks/chunk-RY2AEGMZ.ts.map +0 -7
  109. package/dist/chunks/chunk-SWGQLFSD.ts +0 -60
  110. package/dist/chunks/chunk-SWGQLFSD.ts.map +0 -7
  111. package/dist/chunks/chunk-TM2R67J3.ts +0 -52
  112. package/dist/chunks/chunk-TM2R67J3.ts.map +0 -7
  113. package/dist/chunks/chunk-TMZRHIIK.ts +0 -497
  114. package/dist/chunks/chunk-TMZRHIIK.ts.map +0 -7
  115. package/dist/chunks/chunk-TZ34IQ3M.ts +0 -59
  116. package/dist/chunks/chunk-TZ34IQ3M.ts.map +0 -7
  117. package/dist/chunks/chunk-UMBPMVJW.ts +0 -22
  118. package/dist/chunks/chunk-UMBPMVJW.ts.map +0 -7
  119. package/dist/chunks/chunk-VDG7LTYE.ts +0 -80
  120. package/dist/chunks/chunk-VDG7LTYE.ts.map +0 -7
  121. package/dist/chunks/chunk-X4NMONPE.ts +0 -73
  122. package/dist/chunks/chunk-X4NMONPE.ts.map +0 -7
  123. package/dist/chunks/chunk-YPJEN6NU.ts +0 -65
  124. package/dist/chunks/chunk-YPJEN6NU.ts.map +0 -7
  125. package/dist/chunks/chunk-YU53SHA7.ts +0 -328
  126. package/dist/chunks/chunk-YU53SHA7.ts.map +0 -7
  127. package/dist/chunks/completion-delivery-RSJU6BXL.ts +0 -17
  128. package/dist/chunks/completion-delivery-RSJU6BXL.ts.map +0 -7
  129. package/dist/chunks/config-status-FKGDECZ3.ts +0 -35
  130. package/dist/chunks/config-status-FKGDECZ3.ts.map +0 -7
  131. package/dist/chunks/config-ui-ABHYNGQ7.ts +0 -1212
  132. package/dist/chunks/config-ui-ABHYNGQ7.ts.map +0 -7
  133. package/dist/chunks/consult-LJU3IQY5.ts +0 -519
  134. package/dist/chunks/consult-LJU3IQY5.ts.map +0 -7
  135. package/dist/chunks/context-QDKLVQXE.ts +0 -11
  136. package/dist/chunks/context-QDKLVQXE.ts.map +0 -7
  137. package/dist/chunks/create-stateful-transport-JWC2EFYL.ts +0 -130
  138. package/dist/chunks/create-stateful-transport-JWC2EFYL.ts.map +0 -7
  139. package/dist/chunks/cwd-policy-NB6XZ5GF.ts +0 -17
  140. package/dist/chunks/cwd-policy-NB6XZ5GF.ts.map +0 -7
  141. package/dist/chunks/delegation-contract-LA56I5DT.ts +0 -24
  142. package/dist/chunks/delegation-contract-LA56I5DT.ts.map +0 -7
  143. package/dist/chunks/discovery-MIFB2U4Y.ts +0 -12
  144. package/dist/chunks/discovery-MIFB2U4Y.ts.map +0 -7
  145. package/dist/chunks/execution-Q2JZLKJA.ts +0 -4037
  146. package/dist/chunks/execution-Q2JZLKJA.ts.map +0 -7
  147. package/dist/chunks/in-process-transport-HJ6TZXC3.ts +0 -39
  148. package/dist/chunks/in-process-transport-HJ6TZXC3.ts.map +0 -7
  149. package/dist/chunks/inspect-UH2TKH6E.ts +0 -634
  150. package/dist/chunks/inspect-UH2TKH6E.ts.map +0 -7
  151. package/dist/chunks/peer-communication-KL36Z6CO.ts +0 -294
  152. package/dist/chunks/peer-communication-KL36Z6CO.ts.map +0 -7
  153. package/dist/chunks/persistence-UY3PY6E5.ts +0 -348
  154. package/dist/chunks/persistence-UY3PY6E5.ts.map +0 -7
  155. package/dist/chunks/registry-BT54L6CY.ts +0 -1445
  156. package/dist/chunks/registry-BT54L6CY.ts.map +0 -7
  157. package/dist/chunks/retained-semantic-state-GM75FZGE.ts +0 -81
  158. package/dist/chunks/retained-semantic-state-GM75FZGE.ts.map +0 -7
  159. package/dist/chunks/rpc-transport-7R7DVCEB.ts +0 -1222
  160. package/dist/chunks/rpc-transport-7R7DVCEB.ts.map +0 -7
  161. package/dist/chunks/runtime-policy-5YELCOVC.ts +0 -15
  162. package/dist/chunks/runtime-policy-5YELCOVC.ts.map +0 -7
  163. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts +0 -19
  164. package/dist/chunks/semantic-snapshot-WPJ3UAFW.ts.map +0 -7
  165. package/dist/chunks/spawn-idempotency-BNHOSMZW.ts +0 -13
  166. package/dist/chunks/spawn-idempotency-BNHOSMZW.ts.map +0 -7
  167. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts +0 -15
  168. package/dist/chunks/stateful-lifecycle-JAR6K55H.ts.map +0 -7
  169. package/dist/chunks/subprocess-transport-VHZJRBTW.ts +0 -160
  170. package/dist/chunks/subprocess-transport-VHZJRBTW.ts.map +0 -7
  171. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts +0 -164
  172. package/dist/chunks/usage-recording-store-CW3EH2SZ.ts.map +0 -7
  173. package/dist/chunks/workspace-WDKLN72J.ts +0 -11
  174. package/dist/chunks/workspace-WDKLN72J.ts.map +0 -7
  175. package/docs/async-runtime-protocol.md +0 -84
  176. package/docs/implementation-notes/pi-subagents-capability-matrix.md +0 -62
  177. package/docs/implementation-notes/pi-subagents-current-direction.md +0 -99
  178. package/docs/implementation-notes/pi-subagents-rpc-v1.md +0 -139
  179. package/docs/pi-subagents-diagrams.md +0 -183
  180. package/src/adaptive-scheduler.ts +0 -224
  181. package/src/admission-policy.ts +0 -78
  182. package/src/agent-projection.ts +0 -53
  183. package/src/agents/built-ins.ts +0 -71
  184. package/src/agents/catalog.ts +0 -241
  185. package/src/agents/discovery.ts +0 -265
  186. package/src/agents/types.ts +0 -100
  187. package/src/agents.ts +0 -51
  188. package/src/auto-transport.ts +0 -121
  189. package/src/blocking-status.ts +0 -63
  190. package/src/cached-module-loader.ts +0 -18
  191. package/src/capabilities.ts +0 -145
  192. package/src/capability-grant.ts +0 -115
  193. package/src/capability-router.ts +0 -107
  194. package/src/child-peer-bridge.ts +0 -124
  195. package/src/child-peer-tools.ts +0 -132
  196. package/src/completion-delivery.ts +0 -409
  197. package/src/completion-render.ts +0 -190
  198. package/src/completion-requirement.ts +0 -479
  199. package/src/completion-routing.ts +0 -24
  200. package/src/config-registration.ts +0 -114
  201. package/src/config-status.ts +0 -217
  202. package/src/config-ui.ts +0 -983
  203. package/src/consult-policy.ts +0 -15
  204. package/src/consult-registration.ts +0 -125
  205. package/src/consult-render.ts +0 -194
  206. package/src/consult-resources.ts +0 -51
  207. package/src/consult-tool.ts +0 -95
  208. package/src/consult.ts +0 -566
  209. package/src/context.ts +0 -126
  210. package/src/create-stateful-transport.ts +0 -157
  211. package/src/cwd-policy.ts +0 -183
  212. package/src/delegation-contract.ts +0 -463
  213. package/src/execution/budget.ts +0 -56
  214. package/src/execution/runtime-policy.ts +0 -19
  215. package/src/execution-plan.ts +0 -322
  216. package/src/execution-ui.ts +0 -259
  217. package/src/execution.ts +0 -1679
  218. package/src/in-process-transport.ts +0 -941
  219. package/src/inspect-registration.ts +0 -64
  220. package/src/inspect-render.ts +0 -334
  221. package/src/inspect-tool.ts +0 -45
  222. package/src/inspect.ts +0 -769
  223. package/src/integration-controller.ts +0 -98
  224. package/src/limits.ts +0 -75
  225. package/src/orchestration-metrics.ts +0 -116
  226. package/src/outcome.ts +0 -61
  227. package/src/panel-child-group.ts +0 -35
  228. package/src/panel-contract.ts +0 -343
  229. package/src/panel-evidence.ts +0 -59
  230. package/src/panel-execution.ts +0 -769
  231. package/src/panel-failure.ts +0 -56
  232. package/src/panel-planning.ts +0 -175
  233. package/src/panel-presets.ts +0 -3
  234. package/src/panel-prompts.ts +0 -132
  235. package/src/panel-reconciliation.ts +0 -57
  236. package/src/panel-render.ts +0 -103
  237. package/src/parallel-limit-ui.ts +0 -113
  238. package/src/params.ts +0 -278
  239. package/src/peer-communication.ts +0 -352
  240. package/src/peer-transport.ts +0 -49
  241. package/src/persistence.ts +0 -522
  242. package/src/pi-args.ts +0 -43
  243. package/src/pi-invocation.ts +0 -168
  244. package/src/process-control.ts +0 -43
  245. package/src/prompt-resources.ts +0 -38
  246. package/src/prompt-source-safety.ts +0 -48
  247. package/src/protocol.ts +0 -76
  248. package/src/registry-types.ts +0 -204
  249. package/src/registry.ts +0 -1698
  250. package/src/render-common.ts +0 -252
  251. package/src/render.ts +0 -704
  252. package/src/result-contract.ts +0 -431
  253. package/src/retained-semantic-state.ts +0 -100
  254. package/src/rpc-timeout-finalization.ts +0 -207
  255. package/src/rpc-transport-metadata.ts +0 -65
  256. package/src/rpc-transport.ts +0 -1035
  257. package/src/rpc-turn-capture.ts +0 -217
  258. package/src/runner-outcome.ts +0 -31
  259. package/src/runner-result.ts +0 -55
  260. package/src/runner-types.ts +0 -102
  261. package/src/runner-usage.ts +0 -48
  262. package/src/runner.ts +0 -866
  263. package/src/safe-text.ts +0 -67
  264. package/src/semantic-snapshot.ts +0 -214
  265. package/src/session-guidance-contract.ts +0 -399
  266. package/src/settings/inspection.ts +0 -302
  267. package/src/settings/schema.ts +0 -195
  268. package/src/settings-reader.ts +0 -215
  269. package/src/settings.ts +0 -452
  270. package/src/spawn-idempotency.ts +0 -68
  271. package/src/stateful-agent-view.ts +0 -85
  272. package/src/stateful-config.ts +0 -13
  273. package/src/stateful-guidance.ts +0 -29
  274. package/src/stateful-lifecycle.ts +0 -74
  275. package/src/stateful-limit-ui.ts +0 -249
  276. package/src/stateful-limits.ts +0 -96
  277. package/src/stateful-prompt.ts +0 -49
  278. package/src/stateful-registration.ts +0 -1320
  279. package/src/stateful-render.ts +0 -318
  280. package/src/stateful-safety.ts +0 -47
  281. package/src/stateful-tool-params.ts +0 -215
  282. package/src/stateful.ts +0 -12
  283. package/src/subagent-details.ts +0 -43
  284. package/src/subagents-extension.ts +0 -372
  285. package/src/subprocess-transport.ts +0 -145
  286. package/src/supervision.ts +0 -104
  287. package/src/task-path.ts +0 -65
  288. package/src/timeout-checkpoint.ts +0 -305
  289. package/src/timeout-finalization.ts +0 -75
  290. package/src/tool-schema-compatibility.ts +0 -73
  291. package/src/transport-types.ts +0 -74
  292. package/src/transport-ui.ts +0 -135
  293. package/src/transport.ts +0 -43
  294. package/src/turn-budget.ts +0 -109
  295. package/src/usage-format.ts +0 -42
  296. package/src/usage-recording-config.ts +0 -13
  297. package/src/usage-recording-store.ts +0 -183
  298. package/src/usage-recording.ts +0 -478
  299. package/src/verification-harness.ts +0 -516
  300. package/src/verification-policy.ts +0 -67
  301. package/src/verification-receipt.ts +0 -275
  302. package/src/verified-execution-benchmark.ts +0 -86
  303. package/src/verified-execution-contract.ts +0 -191
  304. package/src/verified-execution-schema.ts +0 -32
  305. package/src/work-item-ledger.ts +0 -1404
  306. package/src/work-item-persistence.ts +0 -254
  307. package/src/workflow-completion-controller.ts +0 -397
  308. package/src/workflow-planning.ts +0 -172
  309. package/src/workflow-tree-identity.ts +0 -289
  310. package/src/workflow-ui.ts +0 -69
  311. package/src/workflow-verification.ts +0 -296
  312. package/src/workspace.ts +0 -174
@@ -1,132 +0,0 @@
1
- import { defineTool, type ExtensionFactory } from "@earendil-works/pi-coding-agent";
2
- import { Type } from "typebox";
3
- import { redactPrivateText } from "./context.js";
4
- import { MAX_TOOL_MESSAGE_BYTES, truncateUtf8 } from "./limits.js";
5
- import type { AgentMailboxMessage } from "./registry.js";
6
-
7
- const MAX_PEER_MESSAGE_BYTES = 16 * 1024;
8
- const MAX_DEDUPLICATION_KEY_LENGTH = 256;
9
- const PEER_ENVELOPE_HEADER =
10
- /^Message Type: SUBAGENT_(?:COMPLETION|PEER_MESSAGE)\nProtocol: pi-subagents:v1\nMessage ID: (msg_[^\s]+)\n(?:Completion ID: (completion:[^\s]+)\n)?Sender ID: [^\n]+\n(?:Sender Path: [^\n]+\n)?Payload:\n/u;
11
-
12
- export interface ChildPeerClient {
13
- send(target: string, message: string, deduplicationKey?: string): Promise<AgentMailboxMessage>;
14
- list(): Promise<unknown>;
15
- acknowledge(messageIds: readonly string[], completionIds: readonly string[]): Promise<void>;
16
- }
17
-
18
- export function createChildPeerExtension(client: ChildPeerClient): ExtensionFactory {
19
- return (pi) => {
20
- pi.registerTool(
21
- defineTool({
22
- name: "subagent_peer_send",
23
- label: "Send Peer Message",
24
- description:
25
- "Send a bounded queue-only message to /root or another retained agent by canonical task path. The runtime binds your sender identity; this tool never starts an idle turn.",
26
- promptSnippet: "Send a queue-only message to another retained agent",
27
- parameters: Type.Object(
28
- {
29
- target: Type.String({ minLength: 1, maxLength: 2_048 }),
30
- message: Type.String({ minLength: 1, maxLength: MAX_PEER_MESSAGE_BYTES }),
31
- deduplicationKey: Type.Optional(
32
- Type.String({ minLength: 1, maxLength: MAX_DEDUPLICATION_KEY_LENGTH }),
33
- ),
34
- },
35
- { additionalProperties: false },
36
- ),
37
- async execute(_id, params) {
38
- const message = await client.send(params.target, params.message, params.deduplicationKey);
39
- return {
40
- content: [
41
- {
42
- type: "text" as const,
43
- text: `Queued ${message.id} for ${message.recipientId}; delivery does not start an idle turn.`,
44
- },
45
- ],
46
- details: {
47
- messageId: message.id,
48
- recipientId: message.recipientId,
49
- createdAt: message.createdAt,
50
- },
51
- };
52
- },
53
- }),
54
- );
55
- pi.registerTool(
56
- defineTool({
57
- name: "subagent_peer_list",
58
- label: "List Peers",
59
- description:
60
- "List bounded identity and lifecycle metadata for /root and retained agents in this session.",
61
- promptSnippet: "List retained peer task paths",
62
- parameters: Type.Object({}, { additionalProperties: false }),
63
- async execute() {
64
- const peers = await client.list();
65
- const text = truncateUtf8(JSON.stringify(peers, null, 2), MAX_TOOL_MESSAGE_BYTES).text;
66
- return { content: [{ type: "text" as const, text }], details: { peers } };
67
- },
68
- }),
69
- );
70
-
71
- const acknowledgedMessageIds = new Set<string>();
72
- const acknowledgedCompletionIds = new Set<string>();
73
- pi.on("context", async (event) => {
74
- const visible = visibleDeliveryIds(event.messages);
75
- const messageIds = [...visible.messageIds].filter((id) => !acknowledgedMessageIds.has(id));
76
- const completionIds = [...visible.completionIds].filter(
77
- (id) => !acknowledgedCompletionIds.has(id),
78
- );
79
- if (messageIds.length === 0 && completionIds.length === 0) return;
80
- await client.acknowledge(messageIds, completionIds);
81
- for (const id of messageIds) acknowledgedMessageIds.add(id);
82
- for (const id of completionIds) acknowledgedCompletionIds.add(id);
83
- });
84
- };
85
- }
86
-
87
- export function formatPeerMessage(message: AgentMailboxMessage, senderPath?: string): string {
88
- return truncateUtf8(
89
- [
90
- `Message Type: ${message.completionId ? "SUBAGENT_COMPLETION" : "SUBAGENT_PEER_MESSAGE"}`,
91
- "Protocol: pi-subagents:v1",
92
- `Message ID: ${message.id}`,
93
- ...(message.completionId ? [`Completion ID: ${message.completionId}`] : []),
94
- `Sender ID: ${message.senderId}`,
95
- ...(senderPath ? [`Sender Path: ${senderPath}`] : []),
96
- "Payload:",
97
- redactPrivateText(message.content),
98
- ].join("\n"),
99
- MAX_TOOL_MESSAGE_BYTES,
100
- ).text;
101
- }
102
-
103
- export function visibleDeliveryIds(messages: readonly unknown[]): {
104
- messageIds: Set<string>;
105
- completionIds: Set<string>;
106
- } {
107
- const messageIds = new Set<string>();
108
- const completionIds = new Set<string>();
109
- for (const message of messages) {
110
- for (const text of messageText(message)) {
111
- const match = PEER_ENVELOPE_HEADER.exec(text);
112
- if (!match) continue;
113
- messageIds.add(match[1]);
114
- if (match[2]) completionIds.add(match[2]);
115
- }
116
- }
117
- return { messageIds, completionIds };
118
- }
119
-
120
- function messageText(message: unknown): string[] {
121
- if (!message || typeof message !== "object" || Array.isArray(message)) return [];
122
- const candidate = message as Record<string, unknown>;
123
- if (candidate.role !== "user") return [];
124
- const content = candidate.content;
125
- if (typeof content === "string") return [content];
126
- if (!Array.isArray(content)) return [];
127
- return content.flatMap((part) => {
128
- if (!part || typeof part !== "object" || Array.isArray(part)) return [];
129
- const text = (part as Record<string, unknown>).text;
130
- return typeof text === "string" ? [text] : [];
131
- });
132
- }
@@ -1,409 +0,0 @@
1
- import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
- import type { CompletionDelivery } from "./agents/types.js";
3
- import { SUBAGENT_COMPLETION_MESSAGE_TYPE } from "./completion-render.js";
4
- import { requirementForCompletion } from "./completion-requirement.js";
5
- import { redactPrivateText } from "./context.js";
6
- import { DEFAULT_MAX_CONTEXT_BYTES, MAX_TOOL_MESSAGE_BYTES, truncateUtf8 } from "./limits.js";
7
- import type { AgentTurnCompletion, ManagedAgent } from "./registry.js";
8
- import { safeTerminalText } from "./safe-text.js";
9
- import { PI_SUBAGENTS_RPC_PROTOCOL } from "./transport-types.js";
10
-
11
- const MAX_COMPLETION_ERROR_BYTES = 512;
12
- const MAX_COMPLETIONS_PER_MESSAGE = 16;
13
- const MAX_ACKNOWLEDGED_COMPLETION_IDS = 2_048;
14
- const COMPLETION_BATCH_DELAY_MS = 10;
15
-
16
- interface CompletionMetadata {
17
- protocol: typeof PI_SUBAGENTS_RPC_PROTOCOL;
18
- completionId: string;
19
- runId: string;
20
- generation: number;
21
- agentId: string;
22
- taskPath?: string;
23
- recipientPath?: string;
24
- agent: string;
25
- task: string;
26
- state: string;
27
- transport?: string;
28
- structuredResult?: ManagedAgent["structuredResult"];
29
- outcome?: ManagedAgent["outcome"];
30
- capabilityGrant?: ManagedAgent["capabilityGrant"];
31
- completionRequirement?: NonNullable<ManagedAgent["completionRequirements"]>[number];
32
- }
33
-
34
- interface CompletionMessage {
35
- customType: typeof SUBAGENT_COMPLETION_MESSAGE_TYPE;
36
- content: string;
37
- display: true;
38
- details:
39
- | CompletionMetadata
40
- | {
41
- completionCount: number;
42
- completions: CompletionMetadata[];
43
- };
44
- }
45
-
46
- type CompletionContext = Pick<ExtensionContext, "hasPendingMessages" | "isIdle">;
47
- type CompletionPi = Pick<ExtensionAPI, "sendMessage">;
48
-
49
- export interface CompletionDeliveryBrokerOptions {
50
- onDeliveryError?: (error: unknown) => void;
51
- onDeliveryAttempt?: (
52
- completions: readonly AgentTurnCompletion[],
53
- input: {
54
- delivery: "steer" | "nextTurn";
55
- triggerTurn: boolean;
56
- outcome: "accepted" | "failed";
57
- },
58
- ) => void;
59
- onAcknowledged?: (completions: readonly AgentTurnCompletion[], acknowledgedAt: number) => void;
60
- now?: () => number;
61
- }
62
-
63
- /** Owns bounded completion batching and at most one idle-root wake for one parent session. */
64
- export class CompletionDeliveryBroker {
65
- private pending: AgentTurnCompletion[] = [];
66
- private readonly knownCompletionIds = new Set<string>();
67
- private readonly acknowledgedCompletionIds = new Set<string>();
68
- private awaitingParentAck: AgentTurnCompletion[] = [];
69
- private flushTimer?: NodeJS.Timeout;
70
- private wakeInFlight = false;
71
- private closed = false;
72
-
73
- constructor(
74
- private readonly pi: CompletionPi,
75
- private readonly ctx: CompletionContext,
76
- private delivery: CompletionDelivery,
77
- private readonly options: CompletionDeliveryBrokerOptions = {},
78
- ) {}
79
-
80
- enqueue(completion: AgentTurnCompletion): void {
81
- if (
82
- this.closed ||
83
- this.knownCompletionIds.has(completion.completionId) ||
84
- this.acknowledgedCompletionIds.has(completion.completionId)
85
- ) {
86
- return;
87
- }
88
- this.knownCompletionIds.add(completion.completionId);
89
- this.pending.push(completion);
90
- this.scheduleFlush();
91
- }
92
-
93
- setDelivery(value: CompletionDelivery): void {
94
- this.delivery = value;
95
- this.scheduleFlush();
96
- }
97
-
98
- onParentTurnStart(): void {
99
- this.wakeInFlight = false;
100
- this.scheduleFlush();
101
- }
102
-
103
- onParentContext(messages: readonly unknown[]): void {
104
- this.acknowledgeVisible(completionIdsFromContext(messages));
105
- if (this.awaitingParentAck.length > 0) {
106
- this.pending = [...this.awaitingParentAck.splice(0), ...this.pending];
107
- }
108
- this.scheduleFlush();
109
- }
110
-
111
- onParentSettled(): void {
112
- this.wakeInFlight = false;
113
- this.scheduleFlush();
114
- }
115
-
116
- flush(): void {
117
- if (this.closed || this.pending.length === 0) return;
118
- if (this.flushTimer) clearTimeout(this.flushTimer);
119
- this.flushTimer = undefined;
120
-
121
- const completions = this.pending.splice(0);
122
- const batches = chunkCompletions(completions);
123
- let canWake = this.shouldWakeRoot();
124
- for (let index = 0; index < batches.length; index++) {
125
- const triggerTurn = canWake && index === batches.length - 1;
126
- const batch = batches[index];
127
- const message = buildCompletionMessage(batch);
128
- if (triggerTurn) this.wakeInFlight = true;
129
- this.awaitingParentAck.push(...batch);
130
- try {
131
- // Pi treats explicit false as immediate insertion instead of queued steering while streaming.
132
- this.pi.sendMessage(message, {
133
- deliverAs: "steer",
134
- ...(triggerTurn ? { triggerTurn: true } : {}),
135
- });
136
- this.notifyDeliveryAttempt(batch, {
137
- delivery: "steer",
138
- triggerTurn,
139
- outcome: "accepted",
140
- });
141
- } catch (primaryError) {
142
- this.notifyDeliveryAttempt(batch, {
143
- delivery: "steer",
144
- triggerTurn,
145
- outcome: "failed",
146
- });
147
- this.removeAwaiting(batch);
148
- if (triggerTurn) this.wakeInFlight = false;
149
- canWake = false;
150
- this.awaitingParentAck.push(...batch);
151
- try {
152
- this.pi.sendMessage(message, { deliverAs: "nextTurn", triggerTurn: false });
153
- this.notifyDeliveryAttempt(batch, {
154
- delivery: "nextTurn",
155
- triggerTurn: false,
156
- outcome: "accepted",
157
- });
158
- } catch (fallbackError) {
159
- this.notifyDeliveryAttempt(batch, {
160
- delivery: "nextTurn",
161
- triggerTurn: false,
162
- outcome: "failed",
163
- });
164
- this.removeAwaiting(batch);
165
- this.pending = [...batches.slice(index).flat(), ...this.pending];
166
- try {
167
- this.options.onDeliveryError?.(
168
- new AggregateError(
169
- [primaryError, fallbackError],
170
- "Detached subagent completion delivery failed",
171
- ),
172
- );
173
- } catch {
174
- // Delivery retention must survive a failing observer.
175
- }
176
- return;
177
- }
178
- }
179
- }
180
- }
181
-
182
- close(): void {
183
- this.closed = true;
184
- if (this.flushTimer) clearTimeout(this.flushTimer);
185
- this.flushTimer = undefined;
186
- this.pending = [];
187
- this.awaitingParentAck = [];
188
- this.knownCompletionIds.clear();
189
- this.acknowledgedCompletionIds.clear();
190
- }
191
-
192
- private scheduleFlush(): void {
193
- if (this.closed || this.pending.length === 0 || this.flushTimer) return;
194
- this.flushTimer = setTimeout(() => {
195
- this.flushTimer = undefined;
196
- this.flush();
197
- }, COMPLETION_BATCH_DELAY_MS);
198
- }
199
-
200
- private acknowledgeVisible(visibleIds: ReadonlySet<string>): void {
201
- if (visibleIds.size === 0) return;
202
- const completions = [...this.awaitingParentAck, ...this.pending].filter((completion) =>
203
- visibleIds.has(completion.completionId),
204
- );
205
- if (completions.length === 0) return;
206
- const acknowledgedIds = new Set(completions.map((completion) => completion.completionId));
207
- this.awaitingParentAck = this.awaitingParentAck.filter(
208
- (completion) => !acknowledgedIds.has(completion.completionId),
209
- );
210
- this.pending = this.pending.filter(
211
- (completion) => !acknowledgedIds.has(completion.completionId),
212
- );
213
- for (const completion of completions) {
214
- this.knownCompletionIds.delete(completion.completionId);
215
- this.rememberAcknowledged(completion.completionId);
216
- }
217
- try {
218
- this.options.onAcknowledged?.(completions, (this.options.now ?? Date.now)());
219
- } catch {
220
- // Context assembly already observed the message, so observer failures cannot retract it.
221
- }
222
- }
223
-
224
- private rememberAcknowledged(completionId: string): void {
225
- this.acknowledgedCompletionIds.add(completionId);
226
- while (this.acknowledgedCompletionIds.size > MAX_ACKNOWLEDGED_COMPLETION_IDS) {
227
- const oldest = this.acknowledgedCompletionIds.values().next().value;
228
- if (typeof oldest !== "string") return;
229
- this.acknowledgedCompletionIds.delete(oldest);
230
- }
231
- }
232
-
233
- private removeAwaiting(completions: readonly AgentTurnCompletion[]): void {
234
- const removed = new Set(completions.map((completion) => completion.completionId));
235
- this.awaitingParentAck = this.awaitingParentAck.filter(
236
- (completion) => !removed.has(completion.completionId),
237
- );
238
- }
239
-
240
- private notifyDeliveryAttempt(
241
- completions: readonly AgentTurnCompletion[],
242
- input: {
243
- delivery: "steer" | "nextTurn";
244
- triggerTurn: boolean;
245
- outcome: "accepted" | "failed";
246
- },
247
- ): void {
248
- try {
249
- this.options.onDeliveryAttempt?.(completions, input);
250
- } catch {
251
- // Delivery already succeeded, so an observer cannot retract it.
252
- }
253
- }
254
-
255
- private isRootIdle(): boolean {
256
- try {
257
- return this.ctx.isIdle();
258
- } catch {
259
- return false;
260
- }
261
- }
262
-
263
- private shouldWakeRoot(): boolean {
264
- if (this.delivery !== "auto-resume" || this.wakeInFlight || !this.isRootIdle()) return false;
265
- try {
266
- return !this.ctx.hasPendingMessages();
267
- } catch {
268
- return false;
269
- }
270
- }
271
- }
272
-
273
- function completionIdsFromContext(messages: readonly unknown[]): Set<string> {
274
- const ids = new Set<string>();
275
- for (const message of messages) {
276
- if (!message || typeof message !== "object" || Array.isArray(message)) continue;
277
- const record = message as Record<string, unknown>;
278
- if (record.role !== "custom" || record.customType !== SUBAGENT_COMPLETION_MESSAGE_TYPE)
279
- continue;
280
- const details = record.details;
281
- if (!details || typeof details !== "object" || Array.isArray(details)) continue;
282
- const metadata = details as Record<string, unknown>;
283
- if (
284
- metadata.protocol === PI_SUBAGENTS_RPC_PROTOCOL &&
285
- typeof metadata.completionId === "string"
286
- ) {
287
- ids.add(metadata.completionId);
288
- }
289
- if (!Array.isArray(metadata.completions)) continue;
290
- for (const completion of metadata.completions) {
291
- if (!completion || typeof completion !== "object" || Array.isArray(completion)) continue;
292
- const item = completion as Record<string, unknown>;
293
- if (item.protocol === PI_SUBAGENTS_RPC_PROTOCOL && typeof item.completionId === "string") {
294
- ids.add(item.completionId);
295
- }
296
- }
297
- }
298
- return ids;
299
- }
300
-
301
- function chunkCompletions(completions: AgentTurnCompletion[]): AgentTurnCompletion[][] {
302
- const batches: AgentTurnCompletion[][] = [];
303
- for (let index = 0; index < completions.length; index += MAX_COMPLETIONS_PER_MESSAGE) {
304
- batches.push(completions.slice(index, index + MAX_COMPLETIONS_PER_MESSAGE));
305
- }
306
- return batches;
307
- }
308
-
309
- function buildCompletionMessage(completions: AgentTurnCompletion[]): CompletionMessage {
310
- if (completions.length === 1) {
311
- const completion = completions[0];
312
- return {
313
- customType: SUBAGENT_COMPLETION_MESSAGE_TYPE,
314
- content: buildDetachedCompletionMessage(completion),
315
- display: true,
316
- details: completionMetadata(completion),
317
- };
318
- }
319
- const content = truncateUtf8(
320
- [
321
- "Message Type: SUBAGENT_COMPLETION_BATCH",
322
- `Protocol: ${PI_SUBAGENTS_RPC_PROTOCOL}`,
323
- `Completion Count: ${completions.length}`,
324
- ...completions.flatMap((completion, index) => [
325
- "",
326
- `--- Completion ${index + 1} of ${completions.length} ---`,
327
- buildDetachedCompletionMessage(completion),
328
- ]),
329
- ].join("\n"),
330
- DEFAULT_MAX_CONTEXT_BYTES,
331
- ).text;
332
- return {
333
- customType: SUBAGENT_COMPLETION_MESSAGE_TYPE,
334
- content,
335
- display: true,
336
- details: {
337
- completionCount: completions.length,
338
- completions: completions.map(completionMetadata),
339
- },
340
- };
341
- }
342
-
343
- function completionMetadata(completion: AgentTurnCompletion): CompletionMetadata {
344
- const completionRequirement = requirementForCompletion(completion.agent, completion.completionId);
345
- return {
346
- protocol: PI_SUBAGENTS_RPC_PROTOCOL,
347
- completionId: completion.completionId,
348
- runId: completion.runId,
349
- generation: completion.generation,
350
- agentId: completion.agent.id,
351
- ...(completion.agent.taskPath ? { taskPath: completion.agent.taskPath } : {}),
352
- ...(completion.recipientPath ? { recipientPath: completion.recipientPath } : {}),
353
- agent: completion.agent.agent,
354
- task: sanitizeCompletionLine(completion.task, 256) || "(unknown task)",
355
- state: completion.agent.state,
356
- ...(completion.agent.telemetry?.transport
357
- ? { transport: completion.agent.telemetry.transport }
358
- : {}),
359
- ...(completion.agent.structuredResult
360
- ? { structuredResult: completion.agent.structuredResult }
361
- : {}),
362
- ...(completion.agent.outcome ? { outcome: completion.agent.outcome } : {}),
363
- ...(completion.agent.capabilityGrant
364
- ? { capabilityGrant: completion.agent.capabilityGrant }
365
- : {}),
366
- ...(completionRequirement ? { completionRequirement } : {}),
367
- };
368
- }
369
-
370
- export function buildDetachedCompletionMessage(completion: AgentTurnCompletion): string {
371
- const task = sanitizeCompletionLine(completion.task, 256) || "(unknown task)";
372
- const agentName = sanitizeCompletionLine(completion.agent.agent, 128) || "(unknown agent)";
373
- const output = safeTerminalText(redactPrivateText(completion.output));
374
- const error = completion.error
375
- ? truncateUtf8(
376
- safeTerminalText(redactPrivateText(completion.error)),
377
- MAX_COMPLETION_ERROR_BYTES,
378
- ).text
379
- : "";
380
- return truncateUtf8(
381
- [
382
- "Message Type: SUBAGENT_COMPLETION",
383
- `Protocol: ${PI_SUBAGENTS_RPC_PROTOCOL}`,
384
- `Completion ID: ${completion.completionId}`,
385
- `Run ID: ${completion.runId}`,
386
- `Generation: ${completion.generation}`,
387
- `Agent ID: ${completion.agent.id}`,
388
- ...(completion.agent.taskPath ? [`Agent Path: ${completion.agent.taskPath}`] : []),
389
- ...(completion.recipientPath ? [`Recipient Path: ${completion.recipientPath}`] : []),
390
- `Agent: ${agentName}`,
391
- `Task: ${task}`,
392
- `State: ${completion.agent.state}`,
393
- ...(error.trim() ? ["Error:", error] : []),
394
- "Payload:",
395
- output.trim() ? output : "(no output)",
396
- ].join("\n"),
397
- MAX_TOOL_MESSAGE_BYTES,
398
- ).text;
399
- }
400
-
401
- function sanitizeCompletionLine(value: string, maxBytes: number): string {
402
- return (
403
- truncateUtf8(redactPrivateText(value), maxBytes)
404
- // biome-ignore lint/suspicious/noControlCharactersInRegex: Strip untrusted terminal controls.
405
- .text.replace(/[\u0000-\u001f\u007f]+/g, " ")
406
- .replace(/\s+/g, " ")
407
- .trim()
408
- );
409
- }