@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,372 +0,0 @@
1
- /**
2
- * Subagent Tool - Delegate tasks to specialized agents
3
- *
4
- * Spawns a separate `pi` process for each subagent invocation,
5
- * giving it an isolated context window.
6
- *
7
- * Supports blocking single, parallel, chain, workflow, and panel modes.
8
- *
9
- * Uses JSON mode to capture structured output from subagents.
10
- */
11
-
12
- import {
13
- CONFIG_DIR_NAME,
14
- type ExtensionAPI,
15
- type ToolDefinition,
16
- } from "@earendil-works/pi-coding-agent";
17
- import { discoverAgentCatalog, formatAgentCatalog } from "./agents/catalog.js";
18
- import type {
19
- ConsultationCwdPolicy,
20
- ConsultResourcePolicy,
21
- DelegationCwdPolicy,
22
- SubagentSettings,
23
- } from "./agents/types.js";
24
- import { cachedModuleLoader, throwIfAborted } from "./cached-module-loader.js";
25
- import { renderCompletionMessage, SUBAGENT_COMPLETION_MESSAGE_TYPE } from "./completion-render.js";
26
- import {
27
- type ConfigRegistrationDependencies,
28
- registerSubagentConfigCommand,
29
- registerSubagentConfigLifecycle,
30
- } from "./config-registration.js";
31
- import {
32
- type ConsultRegistrationDependencies,
33
- registerSubagentConsult,
34
- } from "./consult-registration.js";
35
- import {
36
- type InspectRegistrationDependencies,
37
- registerSubagentInspect,
38
- } from "./inspect-registration.js";
39
- import { MAX_BLOCKING_PARALLEL_CONCURRENCY } from "./limits.js";
40
- import { SubagentParams } from "./params.js";
41
- import { renderSubagentCall, renderSubagentResult } from "./render.js";
42
- import {
43
- registerSubagentSessionGuidance,
44
- type SubagentSessionGuidanceSnapshot,
45
- } from "./session-guidance-contract.js";
46
- import {
47
- consumeSubagentSettingsNotice,
48
- DEFAULT_CONSULT_RESOURCE_POLICY,
49
- DEFAULT_CONSULTATION_CWD_POLICY,
50
- DEFAULT_DELEGATION_CWD_POLICY,
51
- inspectSubagentSettings,
52
- readSubagentSettings,
53
- resolveBlockingMaxParallelTasks,
54
- } from "./settings-reader.js";
55
- import { registerStatefulSubagents } from "./stateful-registration.js";
56
- import type { SubagentDetails } from "./subagent-details.js";
57
- import type { SubagentTransport } from "./transport.js";
58
- import {
59
- registerUsageRecording,
60
- type UsageRecordingDependencies,
61
- type UsageSurfaceArm,
62
- } from "./usage-recording.js";
63
- import { resolveUsageRecordingEnabled } from "./usage-recording-config.js";
64
-
65
- type BlockingExecutionModule = Pick<typeof import("./execution.js"), "executeSubagent">;
66
-
67
- export interface SubagentsDependencies {
68
- loadBlockingExecution?: () => Promise<BlockingExecutionModule>;
69
- loadStatefulTransport?: () => Promise<SubagentTransport>;
70
- config?: ConfigRegistrationDependencies;
71
- consult?: ConsultRegistrationDependencies;
72
- inspect?: InspectRegistrationDependencies;
73
- usageRecording?: Partial<UsageRecordingDependencies>;
74
- }
75
-
76
- const VERSION_3_MIGRATION_WARNING = [
77
- "pi-subagents 3.0.0 will replace this runtime with the bounded-job design currently developed as pi-subagents-v3.",
78
- "The release will remove:",
79
- "• /subagents, extension settings, and local usage recording;",
80
- "• the current subagent tool and underscore-named lifecycle and consultation tools;",
81
- "• custom agent catalogs, per-agent model settings, and custom agent prompts;",
82
- "• retained conversations, follow-up turns, mailboxes, peer and nested messaging, persisted recovery, and auto-resume completion;",
83
- "• chains, fan-in, panels, workflow DAGs, dynamic scheduling, structured result contracts, and verification orchestration;",
84
- "• alternate transports, trust-aware cwd policy, and extension-owned worktree isolation.",
85
- "3.0.0 will instead expose subagent-spawn, subagent-inspect, subagent-cancel, subagent-wait, and subagent-reply for bounded background jobs.",
86
- ].join("\n");
87
-
88
- export default function (pi: ExtensionAPI, dependencies: SubagentsDependencies = {}) {
89
- pi.registerMessageRenderer(SUBAGENT_COMPLETION_MESSAGE_TYPE, renderCompletionMessage);
90
- const loadBlockingExecution = cachedModuleLoader(
91
- dependencies.loadBlockingExecution ?? (() => import("./execution.js")),
92
- );
93
- const configOwner = registerSubagentConfigLifecycle(pi);
94
- const usageRecording = registerUsageRecording(pi, dependencies.usageRecording);
95
- const settings = readSubagentSettings();
96
- let currentSettings: SubagentSettings | undefined = settings;
97
- let currentCatalog = "";
98
- let migrationWarningShown = false;
99
- const blockingEnabled = settings?.blocking?.enabled !== false;
100
- const statefulEnabled = settings?.stateful?.enabled !== false;
101
- if (blockingEnabled) {
102
- registerBlockingSubagent(pi, () => currentSettings, statefulEnabled, loadBlockingExecution);
103
- }
104
-
105
- pi.on("session_start", async (event, ctx) => {
106
- // Preserve a one-shot migration notice from extension load while refreshing
107
- // validation against settings that may have changed before this session.
108
- const loadNotice = consumeSubagentSettingsNotice();
109
- const refreshedSettings = readSubagentSettings();
110
- const refreshedNotice = consumeSubagentSettingsNotice();
111
- if (!inspectSubagentSettings().error) currentSettings = refreshedSettings;
112
- const notice = [
113
- ...new Set([loadNotice, refreshedNotice].filter((value) => value !== undefined)),
114
- ].join("\n");
115
- if (notice) ctx.ui.notify(notice, "warning");
116
- if (ctx.hasUI && !migrationWarningShown) {
117
- migrationWarningShown = true;
118
- ctx.ui.notify(VERSION_3_MIGRATION_WARNING, "warning");
119
- }
120
-
121
- currentCatalog = formatAgentCatalog(
122
- discoverAgentCatalog(ctx.cwd, ctx.isProjectTrusted(), refreshedSettings),
123
- ).text;
124
- await usageRecording.startSession({
125
- enabled: resolveUsageRecordingEnabled(currentSettings?.usageRecording),
126
- surfaceArm: usageSurfaceArm(blockingEnabled, statefulRuntime.getRuntimeStatus().enabled),
127
- reason: event.reason,
128
- onWarning: (message) => {
129
- if (ctx.hasUI) ctx.ui.notify(message, "warning");
130
- },
131
- });
132
- });
133
-
134
- const statefulRuntime = registerStatefulSubagents(pi, {
135
- blockingEnabled,
136
- settings: settings?.stateful,
137
- getSettings: () => currentSettings,
138
- loadTransport: dependencies.loadStatefulTransport,
139
- usageRecording,
140
- });
141
- const getBlockingEnabled = () => blockingEnabled;
142
- const getMaxParallelTasks = () => resolveBlockingMaxParallelTasks(currentSettings);
143
- const getConsultResourcePolicy = () =>
144
- currentSettings?.consult?.resources ?? DEFAULT_CONSULT_RESOURCE_POLICY;
145
- const getConsultationCwdPolicy = () =>
146
- currentSettings?.cwdPolicy?.consultation ?? DEFAULT_CONSULTATION_CWD_POLICY;
147
- const getDelegationCwdPolicy = () =>
148
- currentSettings?.cwdPolicy?.delegation ?? DEFAULT_DELEGATION_CWD_POLICY;
149
- registerSubagentInspect(
150
- pi,
151
- {
152
- ...statefulRuntime,
153
- getBlockingEnabled,
154
- getMaxParallelTasks,
155
- getConsultResourcePolicy,
156
- getConsultationCwdPolicy,
157
- getDelegationCwdPolicy,
158
- getUsageRecordingStatus: () => usageRecording.getStatus(),
159
- },
160
- dependencies.inspect,
161
- );
162
- if (blockingEnabled) {
163
- registerSubagentConsult(pi, { getSettings: () => currentSettings }, dependencies.consult);
164
- }
165
- const sessionGuidance = registerSubagentSessionGuidance(
166
- pi,
167
- (): SubagentSessionGuidanceSnapshot => {
168
- const runtimeStatus = statefulRuntime.getRuntimeStatus();
169
- return {
170
- blockingEnabled,
171
- statefulEnabled: runtimeStatus.enabled,
172
- completionDelivery: runtimeStatus.completionDelivery,
173
- blockingMaxParallelTasks: resolveBlockingMaxParallelTasks(currentSettings),
174
- statefulLimits: runtimeStatus.limits,
175
- consultationCwdPolicy: getConsultationCwdPolicy(),
176
- delegationCwdPolicy: getDelegationCwdPolicy(),
177
- consultResourcePolicy: getConsultResourcePolicy(),
178
- agentCatalog: currentCatalog,
179
- };
180
- },
181
- () => statefulRuntime.listAgents(),
182
- );
183
- registerSubagentConfigCommand(
184
- pi,
185
- {
186
- ...statefulRuntime,
187
- setCompletionDelivery(value) {
188
- statefulRuntime.setCompletionDelivery(value);
189
- sessionGuidance.publish();
190
- },
191
- getBlockingEnabled,
192
- getMaxParallelTasks,
193
- getConsultResourcePolicy,
194
- getConsultationCwdPolicy,
195
- getDelegationCwdPolicy,
196
- getUsageRecordingEnabled: () => usageRecording.getStatus().enabled,
197
- getUsageRecordingStatus: () => usageRecording.getStatus(),
198
- setUsageRecordingEnabled: async (value: boolean) => {
199
- await usageRecording.setEnabled(value);
200
- currentSettings = {
201
- ...(currentSettings ?? {}),
202
- usageRecording: { ...(currentSettings?.usageRecording ?? {}), enabled: value },
203
- };
204
- },
205
- setMaxParallelTasks(value: number) {
206
- currentSettings = {
207
- ...(currentSettings ?? {}),
208
- blocking: { ...(currentSettings?.blocking ?? {}), maxParallelTasks: value },
209
- };
210
- sessionGuidance.publish();
211
- },
212
- setConsultResourcePolicy(value: ConsultResourcePolicy) {
213
- currentSettings = {
214
- ...(currentSettings ?? {}),
215
- consult: { ...(currentSettings?.consult ?? {}), resources: value },
216
- };
217
- sessionGuidance.publish();
218
- },
219
- setConsultationCwdPolicy(value: ConsultationCwdPolicy) {
220
- currentSettings = {
221
- ...(currentSettings ?? {}),
222
- cwdPolicy: { ...(currentSettings?.cwdPolicy ?? {}), consultation: value },
223
- };
224
- sessionGuidance.publish();
225
- },
226
- setDelegationCwdPolicy(value: DelegationCwdPolicy) {
227
- currentSettings = {
228
- ...(currentSettings ?? {}),
229
- cwdPolicy: { ...(currentSettings?.cwdPolicy ?? {}), delegation: value },
230
- };
231
- sessionGuidance.publish();
232
- },
233
- },
234
- configOwner,
235
- dependencies.config,
236
- );
237
- pi.on("session_shutdown", (event) => usageRecording.shutdown(event.reason));
238
- }
239
-
240
- function usageSurfaceArm(blockingEnabled: boolean, statefulEnabled: boolean): UsageSurfaceArm {
241
- if (blockingEnabled && statefulEnabled) return "all";
242
- if (statefulEnabled) return "async-only";
243
- if (blockingEnabled) return "blocking-only";
244
- return "disabled";
245
- }
246
-
247
- function registerBlockingSubagent(
248
- pi: ExtensionAPI,
249
- getSettings: () => SubagentSettings | undefined,
250
- statefulEnabled: boolean,
251
- loadExecution: () => Promise<BlockingExecutionModule>,
252
- ): void {
253
- let deprecationWarningShown = false;
254
- const activeControllers = new Set<AbortController>();
255
- const activeWork = new Set<Promise<unknown>>();
256
- const cancelAndWaitForWork = async (reason: string) => {
257
- for (const controller of activeControllers) {
258
- controller.abort(new DOMException(reason, "AbortError"));
259
- }
260
- await Promise.allSettled([...activeWork]);
261
- };
262
- pi.on("session_start", () => {
263
- deprecationWarningShown = false;
264
- return cancelAndWaitForWork("Blocking subagent session replaced");
265
- });
266
- pi.on("session_shutdown", () => cancelAndWaitForWork("Blocking subagent session shut down"));
267
- const deprecationAlternatives = () =>
268
- statefulEnabled
269
- ? "Prefer the main agent for tightly coupled work, subagent_spawn for detached work, subagent_await for an intentional retained-agent join, or subagent_consult for bounded synchronous read-only evidence."
270
- : "Prefer the main agent for tightly coupled work or subagent_consult for bounded synchronous read-only evidence; enable the background workflow before using detached alternatives.";
271
- const baseDescription = [
272
- "Deprecated compatibility tool: do not choose subagent for new work.",
273
- deprecationAlternatives(),
274
- "Run specialized subagents as a blocking operation with isolated contexts.",
275
- "The call blocks the main agent until every worker and optional aggregator finishes, so queued steering waits.",
276
- "Modes: single (agent + task), parallel (tasks array), chain (sequential with {previous} placeholder), workflow (named dependency tasks with optional capability routing), or panel (independent reviewers plus evidence-preserving synthesis).",
277
- "Parallel mode may include an aggregator fan-in step; workflow mode validates dependencies, authority, artifacts, scope conflicts, retries, and hedging before scheduling. Use subagent_consult instead for one synchronous child that must be executor-constrained to read-only tools.",
278
- 'Default agent scope is "user" (from ~/.pi/agent/agents).',
279
- `To enable project-local agents in ${CONFIG_DIR_NAME}/agents, pass agentScope: "both" (or "project") as a top-level argument for that call.`,
280
- `Configured parallel limits never exceed ${MAX_BLOCKING_PARALLEL_CONCURRENCY} concurrently started workers. The current call limit, working-directory policy, and available agent definitions are published in the pi-subagents session-guidance message.`,
281
- "Working-directory policy controls launch targets and protected project resources, not filesystem access or sandboxing.",
282
- ].join(" ");
283
- const promptGuidelines = [
284
- statefulEnabled
285
- ? "The subagent tool is deprecated for new work; prefer the main agent, subagent_spawn with supported completion delivery, subagent_await for an intentional retained-agent join, or subagent_consult for bounded synchronous read-only evidence."
286
- : "The subagent tool is deprecated for new work; prefer the main agent or subagent_consult for bounded synchronous read-only evidence, and enable the background workflow before using detached alternatives.",
287
- "Use deprecated subagent only for an existing caller or an explicit user request whose blocking chain, fan-in, panel, or workflow semantics do not yet have a detached replacement.",
288
- "When compatibility requires subagent, decide how many subagents to spawn from task shape instead of waiting for the user to specify a count.",
289
- "The main agent retains overall planning, immediate critical-path work, integration, final verification, and the final answer.",
290
- "Use no subagent for simple answers, quick targeted edits, latency-sensitive one-step work, tasks requiring frequent user back-and-forth, or critical-path work the main agent can perform directly.",
291
- "One ordinary implementation worker should not replace work the main agent can perform directly; use a blocking single only when intentional synchronous isolation or a user-requested specialist justifies waiting.",
292
- "Keep ordinary planning in the main agent, or use explicit workflow mode when a genuine dependency graph requires caller-authored orchestration.",
293
- "Keep ordinary review in the main agent with a review skill and deterministic checks; reserve panel mode or custom verifier agents for consequential independent verification.",
294
- "A compatibility subagent call blocks the main agent from processing queued steering until it returns; use it only when the explicit legacy workflow justifies making Pi unavailable.",
295
- "If a blocking parallel subagent call is genuinely required, keep tasks independent, stay within the configured maximum from the current pi-subagents session-guidance message, and avoid write-heavy implementation touching the same files or shared state.",
296
- "For parallel subagent calls, omit the aggregator key entirely unless a fan-in step is required; do not send null, empty strings, or an empty object for unused optional fields.",
297
- "Use workflow mode for explicit dependencies or capability routing; declare read/write or ownership scopes, require structured-v2 artifacts when downstream tasks consume them, and use retry or hedging only with the required side-effect contract.",
298
- "Use panel mode only for consequential review or research that benefits from at least two independent reviewers and one bounded synthesis; agreement is not proof, dissent and blocking objections remain visible, and simple or latency-sensitive work should not use a panel.",
299
- 'Do not use subagent with project-local agents unless the user explicitly wants project agents or sets agentScope to "project" or "both"; keep confirmation enabled for untrusted repositories.',
300
- "When using subagent, write self-contained tasks with file paths, context, expected output, and whether the subagent may edit files.",
301
- "Set subagent timeoutMs to the shortest realistic work deadline for the task difficulty, just as thinkingLevel should match reasoning difficulty; split oversized tasks instead of extending the deadline merely to compensate for broad scope. Use totalTimeoutMs to cap an entire blocking workflow, idleTimeoutMs for stalled work, and maxTurns or maxToolCalls to stop repeated work without progress. Every budget stop preserves a bounded checkpoint and may make one separately bounded summary attempt.",
302
- ];
303
- const definition: ToolDefinition<typeof SubagentParams, SubagentDetails> = {
304
- name: "subagent",
305
- label: "Blocking Subagent · Deprecated",
306
- description: baseDescription,
307
- promptSnippet:
308
- "Deprecated blocking subagent compatibility tool; prefer detached or read-only alternatives.",
309
- promptGuidelines,
310
- parameters: SubagentParams,
311
-
312
- async execute(toolCallId, params, signal, onUpdate, ctx) {
313
- const lifecycleController = new AbortController();
314
- activeControllers.add(lifecycleController);
315
- const effectiveSignal = signal
316
- ? AbortSignal.any([signal, lifecycleController.signal])
317
- : lifecycleController.signal;
318
- const work = (async () => {
319
- throwIfAborted(effectiveSignal, "Blocking subagent execution was cancelled");
320
- if (!deprecationWarningShown && ctx.hasUI) {
321
- deprecationWarningShown = true;
322
- ctx.ui.notify(
323
- statefulEnabled
324
- ? "subagent is deprecated for new work. Prefer the main agent, subagent_spawn with completion delivery, subagent_await for an intentional join, or subagent_consult for synchronous read-only evidence."
325
- : "subagent is deprecated for new work. Prefer the main agent or subagent_consult; enable the background workflow before using detached alternatives.",
326
- "warning",
327
- );
328
- }
329
- let executionModule: BlockingExecutionModule;
330
- try {
331
- executionModule = await loadExecution();
332
- } catch (error) {
333
- throwIfAborted(
334
- effectiveSignal,
335
- "Blocking subagent execution was cancelled while loading",
336
- );
337
- throw error;
338
- }
339
- throwIfAborted(effectiveSignal, "Blocking subagent execution was cancelled while loading");
340
- return executionModule.executeSubagent(
341
- toolCallId,
342
- params,
343
- effectiveSignal,
344
- onUpdate,
345
- ctx,
346
- getSettings(),
347
- );
348
- })();
349
- activeWork.add(work);
350
- try {
351
- return await work;
352
- } finally {
353
- activeControllers.delete(lifecycleController);
354
- activeWork.delete(work);
355
- }
356
- },
357
-
358
- renderCall(args, theme) {
359
- return renderSubagentCall(args, theme);
360
- },
361
-
362
- renderResult(result, options, theme) {
363
- return renderSubagentResult(result, options, theme);
364
- },
365
- };
366
- pi.registerTool<typeof SubagentParams, SubagentDetails>(definition);
367
- pi.on("tool_result", (event) => {
368
- if (event.toolName !== "subagent") return;
369
- if ((event.details as (SubagentDetails & { isError?: boolean }) | undefined)?.isError)
370
- return { isError: true };
371
- });
372
- }
@@ -1,145 +0,0 @@
1
- import { discoverAgents } from "./agents/discovery.js";
2
- import type { AgentConfig, SubagentSettings, SubagentThinkingLevel } from "./agents/types.js";
3
- import {
4
- CHILD_PEER_TOOL_NAMES,
5
- childPeerBridgePath,
6
- type PeerTransportRuntime,
7
- peerBridgeEnvironment,
8
- } from "./peer-transport.js";
9
- import { resolvePiPromptResources } from "./prompt-resources.js";
10
- import type { ManagedAgent, TurnOutcome } from "./registry.js";
11
- import { getResultFinalOutput, runSingleAgent } from "./runner.js";
12
- import { readSubagentSettings, resolveSubagentThinkingLevel } from "./settings.js";
13
- import { buildStatefulTurnPrompt, resolveStatefulTurnTimeout } from "./stateful-prompt.js";
14
- import type { SubagentDetails } from "./subagent-details.js";
15
- import type { SubagentTransport } from "./transport.js";
16
- import type { TransportProgressCallback, TransportTelemetry } from "./transport-types.js";
17
-
18
- export function resolveStatefulSubprocessThinkingLevel(
19
- agents: readonly Pick<AgentConfig, "name" | "thinkingLevel">[],
20
- record: Pick<ManagedAgent, "agent" | "thinkingLevel">,
21
- ): SubagentThinkingLevel | undefined {
22
- return resolveSubagentThinkingLevel(agents, record.agent, record.thinkingLevel);
23
- }
24
-
25
- export interface SubprocessTransportOptions {
26
- getSettings?: () => SubagentSettings | undefined;
27
- peerRuntime?: PeerTransportRuntime;
28
- }
29
-
30
- export class SubprocessTransport implements SubagentTransport {
31
- readonly kind = "subprocess" as const;
32
-
33
- constructor(private readonly options: SubprocessTransportOptions = {}) {}
34
-
35
- async runTurn(
36
- record: ManagedAgent,
37
- task: string,
38
- signal: AbortSignal,
39
- onProgress?: TransportProgressCallback,
40
- ): Promise<TurnOutcome> {
41
- const startedAt = Date.now();
42
- const starting: TransportTelemetry = {
43
- transport: "subprocess",
44
- phase: "starting",
45
- updatedAt: startedAt,
46
- timing: { startedAt, transportStartedAt: startedAt },
47
- };
48
- onProgress?.(starting);
49
- const settings = this.options.getSettings ? this.options.getSettings() : readSubagentSettings();
50
- const discovery = discoverAgents(record.cwd, record.agentScope ?? "user", settings);
51
- const agent = discovery.agents.find((candidate) => candidate.name === record.agent);
52
- const boundedTask = buildStatefulTurnPrompt(record, task);
53
- const projectTrust =
54
- record.target?.trust.projectTrusted ??
55
- (record.agentScope === "project" || record.agentScope === "both");
56
- const promptResources = agent?.systemPrompt.trim()
57
- ? await resolvePiPromptResources(record.cwd, projectTrust)
58
- : undefined;
59
- const makeDetails = (results: SubagentDetails["results"]): SubagentDetails => ({
60
- mode: "single",
61
- agentScope: record.agentScope ?? "user",
62
- projectAgentsDir: discovery.projectAgentsDir,
63
- results,
64
- });
65
- const credentials = this.options.peerRuntime
66
- ? await this.options.peerRuntime.issueCredentials(
67
- record.id,
68
- record.currentTurnGeneration ?? record.turnGeneration ?? 1,
69
- )
70
- : undefined;
71
- let single: Awaited<ReturnType<typeof runSingleAgent>>;
72
- try {
73
- single = await runSingleAgent(
74
- record.cwd,
75
- discovery.agents,
76
- record.agent,
77
- boundedTask.text,
78
- undefined,
79
- undefined,
80
- signal,
81
- resolveStatefulSubprocessThinkingLevel(discovery.agents, record),
82
- record.currentTimeoutMs ?? record.timeoutMs ?? resolveStatefulTurnTimeout(agent),
83
- undefined,
84
- makeDetails,
85
- undefined,
86
- {
87
- projectTrust,
88
- ...(record.executionPlan ? { tools: record.executionPlan.effectiveTools } : {}),
89
- appendSystemPromptPaths: promptResources?.appendSystemPromptPaths,
90
- extensionPaths: credentials ? [childPeerBridgePath()] : undefined,
91
- additionalTools: credentials ? [...CHILD_PEER_TOOL_NAMES] : undefined,
92
- env: credentials ? peerBridgeEnvironment(credentials) : undefined,
93
- timeoutResultFormat: record.resultFormat,
94
- turnLimits: {
95
- idleTimeoutMs: record.currentIdleTimeoutMs ?? record.idleTimeoutMs,
96
- maxTurns: record.currentMaxTurns ?? record.maxTurns,
97
- maxToolCalls: record.currentMaxToolCalls ?? record.maxToolCalls,
98
- },
99
- resultFormat: record.resultFormat,
100
- contract: record.contract,
101
- executionPlan: record.executionPlan,
102
- displayTask: task,
103
- },
104
- );
105
- } finally {
106
- this.options.peerRuntime?.revoke(record.id);
107
- }
108
- const settledAt = Date.now();
109
- const telemetry: TransportTelemetry = {
110
- ...starting,
111
- phase: single.aborted ? "interrupted" : single.exitCode === 0 ? "settled" : "failed",
112
- failurePhase: single.exitCode === 0 ? undefined : "running",
113
- updatedAt: settledAt,
114
- timing: {
115
- ...starting.timing,
116
- promptAcceptedAt: single.processStarted ? startedAt : undefined,
117
- firstActivityAt: single.messages.length > 0 ? settledAt : undefined,
118
- settledAt,
119
- },
120
- provider: single.actualProvider,
121
- model: single.actualModel ?? single.model,
122
- thinkingLevel: single.thinkingLevel,
123
- usage: {
124
- input: single.usage.input,
125
- output: single.usage.output,
126
- cacheRead: single.usage.cacheRead,
127
- cacheWrite: single.usage.cacheWrite,
128
- totalTokens: single.usage.totalTokens ?? 0,
129
- cost: single.usage.cost,
130
- turns: single.usage.turns,
131
- },
132
- };
133
- onProgress?.(telemetry);
134
- return {
135
- output: getResultFinalOutput(single),
136
- exitCode: single.exitCode,
137
- aborted: single.aborted,
138
- truncated: single.truncated || boundedTask.truncated,
139
- error: single.errorMessage || single.stderr || undefined,
140
- policy: single.policy,
141
- termination: single.termination,
142
- telemetry,
143
- };
144
- }
145
- }
@@ -1,104 +0,0 @@
1
- import { isResultError } from "./runner-outcome.js";
2
- import type { SingleResult } from "./runner-types.js";
3
-
4
- const HEDGE_LOSER_GRACE_MS = 5_000;
5
-
6
- export async function runHedgedAttempt(
7
- run: (signal: AbortSignal | undefined) => Promise<SingleResult>,
8
- parentSignal: AbortSignal | undefined,
9
- hedgeAfterMs: number | undefined,
10
- loserGraceMs = HEDGE_LOSER_GRACE_MS,
11
- ): Promise<{ result: SingleResult; hedged: boolean }> {
12
- if (hedgeAfterMs === undefined) return { result: await run(parentSignal), hedged: false };
13
- const primaryLink = linkedAbortController(parentSignal);
14
- const hedgeLink = linkedAbortController(parentSignal);
15
- const primaryController = primaryLink.controller;
16
- const hedgeController = hedgeLink.controller;
17
- let hedgeStarted = false;
18
- let hedgePromise: Promise<SingleResult> | undefined;
19
- let timer: ReturnType<typeof setTimeout> | undefined;
20
- const primaryPromise = run(primaryController.signal);
21
- const primaryTagged = primaryPromise.then((result) => ({ source: "primary" as const, result }));
22
- const delayedHedge = new Promise<{ source: "hedge"; result: SingleResult }>((resolve, reject) => {
23
- timer = setTimeout(() => {
24
- hedgeStarted = true;
25
- hedgePromise = run(hedgeController.signal);
26
- hedgePromise.then((result) => resolve({ source: "hedge", result }), reject);
27
- }, hedgeAfterMs);
28
- });
29
- try {
30
- const first = await Promise.race([primaryTagged, delayedHedge]);
31
- if (!isResultError(first.result) || !hedgeStarted || !hedgePromise) {
32
- return { result: first.result, hedged: hedgeStarted };
33
- }
34
- const other = first.source === "primary" ? await hedgePromise : await primaryPromise;
35
- return {
36
- result: isResultError(other) ? first.result : other,
37
- hedged: true,
38
- };
39
- } finally {
40
- if (timer) clearTimeout(timer);
41
- primaryController.abort();
42
- hedgeController.abort();
43
- primaryLink.dispose();
44
- hedgeLink.dispose();
45
- await settleWithin(
46
- [primaryPromise, hedgePromise].filter(
47
- (value): value is Promise<SingleResult> => value !== undefined,
48
- ),
49
- loserGraceMs,
50
- );
51
- }
52
- }
53
-
54
- export function isRetryableResult(result: SingleResult): boolean {
55
- if (!isResultError(result)) return false;
56
- if (result.outcome) return result.outcome.retryable;
57
- return result.aborted === true || result.exitCode !== 0;
58
- }
59
-
60
- export async function supervisionDelay(
61
- milliseconds: number,
62
- signal: AbortSignal | undefined,
63
- ): Promise<void> {
64
- if (milliseconds <= 0 || signal?.aborted) return;
65
- await new Promise<void>((resolve) => {
66
- let timer: ReturnType<typeof setTimeout>;
67
- const finish = () => {
68
- clearTimeout(timer);
69
- signal?.removeEventListener("abort", finish);
70
- resolve();
71
- };
72
- timer = setTimeout(finish, milliseconds);
73
- signal?.addEventListener("abort", finish, { once: true });
74
- });
75
- }
76
-
77
- async function settleWithin(promises: Promise<unknown>[], timeoutMs: number): Promise<void> {
78
- let timer: ReturnType<typeof setTimeout> | undefined;
79
- try {
80
- await Promise.race([
81
- Promise.allSettled(promises),
82
- new Promise<void>((resolve) => {
83
- timer = setTimeout(resolve, timeoutMs);
84
- timer.unref();
85
- }),
86
- ]);
87
- } finally {
88
- if (timer) clearTimeout(timer);
89
- }
90
- }
91
-
92
- function linkedAbortController(parentSignal: AbortSignal | undefined): {
93
- controller: AbortController;
94
- dispose(): void;
95
- } {
96
- const controller = new AbortController();
97
- const abort = () => controller.abort();
98
- if (parentSignal?.aborted) controller.abort();
99
- else parentSignal?.addEventListener("abort", abort, { once: true });
100
- return {
101
- controller,
102
- dispose: () => parentSignal?.removeEventListener("abort", abort),
103
- };
104
- }
package/src/task-path.ts DELETED
@@ -1,65 +0,0 @@
1
- import { createHash } from "node:crypto";
2
-
3
- export const ROOT_TASK_PATH = "/root";
4
- export const MAX_TASK_NAME_LENGTH = 128;
5
- export const MAX_TASK_PATH_LENGTH = 2_048;
6
-
7
- const TASK_NAME_PATTERN = /^[a-z0-9_]+$/u;
8
-
9
- export function validateTaskName(value: string): string {
10
- if (!value) throw new Error("Subagent taskName must not be empty");
11
- if (value === "root" || value === "." || value === "..") {
12
- throw new Error(`Subagent taskName ${JSON.stringify(value)} is reserved`);
13
- }
14
- if (value.length > MAX_TASK_NAME_LENGTH) {
15
- throw new Error(`Subagent taskName cannot exceed ${MAX_TASK_NAME_LENGTH} characters`);
16
- }
17
- if (value.includes("/")) throw new Error("Subagent taskName must not contain `/`");
18
- if (!TASK_NAME_PATTERN.test(value)) {
19
- throw new Error(
20
- "Subagent taskName must use only lowercase ASCII letters, digits, and underscores",
21
- );
22
- }
23
- return value;
24
- }
25
-
26
- export function validateTaskPath(value: string): string {
27
- if (!value.startsWith(`${ROOT_TASK_PATH}/`) && value !== ROOT_TASK_PATH) {
28
- throw new Error("Canonical subagent task paths must start with `/root`");
29
- }
30
- if (value.length > MAX_TASK_PATH_LENGTH) {
31
- throw new Error(
32
- `Canonical subagent task paths cannot exceed ${MAX_TASK_PATH_LENGTH} characters`,
33
- );
34
- }
35
- if (value.endsWith("/") || value.includes("//")) {
36
- throw new Error("Canonical subagent task paths must not contain empty segments");
37
- }
38
- for (const segment of value.slice(ROOT_TASK_PATH.length + 1).split("/")) {
39
- if (segment) validateTaskName(segment);
40
- }
41
- return value;
42
- }
43
-
44
- export function joinTaskPath(parentPath: string, taskName: string): string {
45
- const parent = validateTaskPath(parentPath);
46
- const name = validateTaskName(taskName);
47
- return validateTaskPath(`${parent}/${name}`);
48
- }
49
-
50
- export function resolveTaskPath(senderPath: string, reference: string): string {
51
- if (!reference) throw new Error("Subagent task path reference must not be empty");
52
- if (reference.startsWith("/")) return validateTaskPath(reference);
53
- const sender = validateTaskPath(senderPath);
54
- if (reference.endsWith("/")) {
55
- throw new Error("Relative subagent task paths must not end with `/`");
56
- }
57
- let path = sender;
58
- for (const segment of reference.split("/")) path = joinTaskPath(path, segment);
59
- return path;
60
- }
61
-
62
- export function deriveTaskName(agentId: string): string {
63
- const digest = createHash("sha256").update(agentId).digest("hex").slice(0, 32);
64
- return `agent_${digest}`;
65
- }