@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,522 +0,0 @@
1
- import { createHash } from "node:crypto";
2
- import * as fs from "node:fs";
3
- import * as path from "node:path";
4
- import { getAgentDir, withFileMutationQueue } from "@earendil-works/pi-coding-agent";
5
- import { projectAgentRecords } from "./agent-projection.js";
6
- import { isThinkingLevel } from "./agents/types.js";
7
- import { isCapabilityGrant, revokeCapabilityGrant } from "./capability-grant.js";
8
- import { isCompletionRequirementRecord } from "./completion-requirement.js";
9
- import { redactPrivateText } from "./context.js";
10
- import { normalizeDelegationContract } from "./delegation-contract.js";
11
- import { copyExecutionPlan, isExecutionPlan } from "./execution-plan.js";
12
- import { MAX_SUBAGENT_TIMEOUT_MS } from "./limits.js";
13
- import type { ManagedAgent } from "./registry.js";
14
- import { parseAnyStructuredSubagentResult, SUBAGENT_RESULT_FORMATS } from "./result-contract.js";
15
- import { isSemanticSnapshot } from "./semantic-snapshot.js";
16
- import { resolveStatefulLimits } from "./stateful-limits.js";
17
- import { validateTaskName, validateTaskPath } from "./task-path.js";
18
- import { copyTurnTerminationReport, type TurnTerminationReport } from "./timeout-checkpoint.js";
19
- import { MAX_SUBAGENT_TOOL_CALLS, MAX_SUBAGENT_TURNS } from "./turn-budget.js";
20
-
21
- const STATE_VERSION = 3;
22
- const MAX_STORED_COMPLETIONS_PER_AGENT = 20;
23
- const DEFAULT_STATEFUL_LIMITS = resolveStatefulLimits();
24
- const MAX_STATE_BYTES = 5 * 1024 * 1024;
25
-
26
- interface StoredState {
27
- version: 3;
28
- updatedAt: number;
29
- agents: ManagedAgent[];
30
- }
31
-
32
- export interface PersistenceOptions {
33
- retentionDays?: number;
34
- maxStoredAgents?: number;
35
- stateDir?: string;
36
- }
37
-
38
- export class AgentPersistence {
39
- readonly filePath: string;
40
- private readonly retentionMs: number;
41
- private readonly maxStoredAgents: number;
42
-
43
- constructor(owner: string, options: PersistenceOptions = {}) {
44
- const retentionDays = options.retentionDays ?? 30;
45
- if (!Number.isFinite(retentionDays) || retentionDays <= 0) {
46
- throw new Error("Subagent retentionDays must be a positive finite number");
47
- }
48
- const retentionMs = retentionDays * 24 * 60 * 60 * 1000;
49
- if (!Number.isFinite(retentionMs)) {
50
- throw new Error("Subagent retentionDays is too large");
51
- }
52
- const maxStoredAgents = options.maxStoredAgents ?? DEFAULT_STATEFUL_LIMITS.maxStoredAgents;
53
- if (!Number.isSafeInteger(maxStoredAgents) || maxStoredAgents < 1) {
54
- throw new Error("Subagent maxStoredAgents must be a positive safe integer");
55
- }
56
- const safeOwner = createHash("sha256").update(owner).digest("hex").slice(0, 24);
57
- const stateDir = options.stateDir ?? path.join(getAgentDir(), "pi-subagents-state");
58
- this.filePath = path.join(stateDir, `${safeOwner}.json`);
59
- this.retentionMs = retentionMs;
60
- this.maxStoredAgents = maxStoredAgents;
61
- }
62
-
63
- load(): ManagedAgent[] {
64
- if (!fs.existsSync(this.filePath)) return [];
65
- try {
66
- const stat = fs.statSync(this.filePath);
67
- if (stat.size > MAX_STATE_BYTES) throw new Error("state exceeds size limit");
68
- const parsed = JSON.parse(fs.readFileSync(this.filePath, "utf8")) as unknown;
69
- if (!isStoredState(parsed)) throw new Error("unsupported or malformed state");
70
- const cutoff = Date.now() - this.retentionMs;
71
- return projectAgentRecords(
72
- parsed.agents.filter((agent) => agent.updatedAt >= cutoff && agent.state !== "closed"),
73
- { maxAgents: this.maxStoredAgents },
74
- ).map(sanitizeAgent);
75
- } catch {
76
- this.quarantine();
77
- return [];
78
- }
79
- }
80
-
81
- async save(agents: readonly ManagedAgent[]): Promise<void> {
82
- const cutoff = Date.now() - this.retentionMs;
83
- const eligible = agents.filter(
84
- (agent) => agent.state !== "closed" && agent.updatedAt >= cutoff,
85
- );
86
- const records = projectAgentRecords(eligible, {
87
- maxAgents: this.maxStoredAgents,
88
- }).map(sanitizeAgent);
89
- const state: StoredState = { version: STATE_VERSION, updatedAt: Date.now(), agents: records };
90
- let content = `${JSON.stringify(state, null, "\t")}\n`;
91
- while (Buffer.byteLength(content, "utf8") > MAX_STATE_BYTES && state.agents.length > 0) {
92
- const rootsWithPendingCompletions = new Set(
93
- state.agents
94
- .filter((agent) => (agent.pendingCompletions?.length ?? 0) > 0)
95
- .map((agent) => agent.rootId),
96
- );
97
- const droppableRoot = state.agents.find(
98
- (agent) => !rootsWithPendingCompletions.has(agent.rootId),
99
- )?.rootId;
100
- if (droppableRoot) {
101
- state.agents = state.agents.filter((agent) => agent.rootId !== droppableRoot);
102
- } else if (!trimOldestHistory(state.agents) && !clearOldestContext(state.agents)) {
103
- throw new Error("Subagent state exceeds its durable completion storage limit");
104
- }
105
- content = `${JSON.stringify(state, null, "\t")}\n`;
106
- }
107
- await fs.promises.mkdir(path.dirname(this.filePath), { recursive: true });
108
- await withFileMutationQueue(this.filePath, async () => {
109
- const tempPath = `${this.filePath}.${process.pid}.${Date.now()}.tmp`;
110
- await fs.promises.writeFile(tempPath, content, { encoding: "utf8", mode: 0o600 });
111
- await fs.promises.rename(tempPath, this.filePath);
112
- });
113
- }
114
-
115
- async delete(): Promise<void> {
116
- await withFileMutationQueue(this.filePath, async () => {
117
- await fs.promises.rm(this.filePath, { force: true });
118
- });
119
- }
120
-
121
- private quarantine(): void {
122
- try {
123
- fs.renameSync(this.filePath, `${this.filePath}.invalid-${Date.now()}`);
124
- } catch {
125
- // A concurrent process may already have moved or removed it.
126
- }
127
- }
128
- }
129
-
130
- function trimOldestHistory(agents: ManagedAgent[]): boolean {
131
- const candidate = agents
132
- .filter((agent) => agent.history.length > 0)
133
- .sort(
134
- (left, right) =>
135
- (left.history[0]?.completedAt ?? Number.POSITIVE_INFINITY) -
136
- (right.history[0]?.completedAt ?? Number.POSITIVE_INFINITY),
137
- )[0];
138
- if (!candidate) return false;
139
- candidate.history.shift();
140
- return true;
141
- }
142
-
143
- function clearOldestContext(agents: ManagedAgent[]): boolean {
144
- const candidate = agents.find((agent) => agent.context !== undefined);
145
- if (!candidate) return false;
146
- candidate.context = undefined;
147
- candidate.contextTruncated = true;
148
- return true;
149
- }
150
-
151
- function sanitizeAgent(agent: ManagedAgent): ManagedAgent {
152
- return {
153
- ...agent,
154
- rootId: agent.rootId ?? agent.id,
155
- depth: agent.depth ?? 0,
156
- children: [...(agent.children ?? [])],
157
- mailbox: (agent.mailbox ?? []).map((message) => ({
158
- ...message,
159
- recipientId: agent.id,
160
- content: redactPrivateText(message.content),
161
- })),
162
- state: agent.state === "running" || agent.state === "starting" ? "interrupted" : agent.state,
163
- currentTask: undefined,
164
- currentRunId: undefined,
165
- currentTurnGeneration: undefined,
166
- turnGeneration: agent.turnGeneration ?? 0,
167
- pendingCompletions: (agent.pendingCompletions ?? [])
168
- .slice(-MAX_STORED_COMPLETIONS_PER_AGENT)
169
- .map((completion) => ({
170
- ...completion,
171
- task: redactPrivateText(completion.task),
172
- output: redactPrivateText(completion.output),
173
- error: completion.error ? redactPrivateText(completion.error) : undefined,
174
- })),
175
- completionRequirements: (agent.completionRequirements ?? [])
176
- .filter(isCompletionRequirementRecord)
177
- .slice(-MAX_STORED_COMPLETIONS_PER_AGENT)
178
- .map((record) => ({ ...record })),
179
- currentTimeoutMs: undefined,
180
- currentIdleTimeoutMs: undefined,
181
- currentMaxTurns: undefined,
182
- currentMaxToolCalls: undefined,
183
- currentMailboxMessageIds: undefined,
184
- telemetry: undefined,
185
- contract: normalizeDelegationContract(agent.contract),
186
- structuredResult:
187
- agent.structuredResult && agent.resultFormat
188
- ? parseAnyStructuredSubagentResult(
189
- JSON.stringify(agent.structuredResult),
190
- agent.resultFormat,
191
- )
192
- : undefined,
193
- executionPlan: agent.executionPlan ? copyExecutionPlan(agent.executionPlan) : undefined,
194
- capabilityGrant: agent.capabilityGrant
195
- ? agent.capabilityGrant.state === "active"
196
- ? revokeCapabilityGrant(agent.capabilityGrant, "persistence-boundary", Date.now())
197
- : structuredClone(agent.capabilityGrant)
198
- : undefined,
199
- semanticSnapshot: agent.semanticSnapshot ? structuredClone(agent.semanticSnapshot) : undefined,
200
- semanticCompatibility: agent.semanticCompatibility
201
- ? structuredClone(agent.semanticCompatibility)
202
- : undefined,
203
- termination: agent.termination ? sanitizeTermination(agent.termination) : undefined,
204
- context: agent.context ? redactPrivateText(agent.context) : undefined,
205
- error: agent.error ? redactPrivateText(agent.error) : undefined,
206
- history: agent.history.map((turn) => ({
207
- ...turn,
208
- task: redactPrivateText(turn.task),
209
- output: redactPrivateText(turn.output),
210
- termination: turn.termination ? sanitizeTermination(turn.termination) : undefined,
211
- })),
212
- };
213
- }
214
-
215
- function sanitizeTermination(report: TurnTerminationReport): TurnTerminationReport {
216
- const copy = copyTurnTerminationReport(report);
217
- copy.checkpoint.task = redactPrivateText(copy.checkpoint.task);
218
- copy.checkpoint.partialOutput = copy.checkpoint.partialOutput
219
- ? redactPrivateText(copy.checkpoint.partialOutput)
220
- : undefined;
221
- copy.checkpoint.assistantNotes = copy.checkpoint.assistantNotes.map(redactPrivateText);
222
- copy.checkpoint.completedTools = copy.checkpoint.completedTools.map((item) => ({
223
- ...item,
224
- toolName: redactPrivateText(item.toolName),
225
- output: redactPrivateText(item.output),
226
- }));
227
- copy.checkpoint.changedFiles = copy.checkpoint.changedFiles.map(redactPrivateText);
228
- copy.finalization.error = copy.finalization.error
229
- ? redactPrivateText(copy.finalization.error)
230
- : undefined;
231
- return copy;
232
- }
233
-
234
- function isStoredState(value: unknown): value is StoredState {
235
- if (!value || typeof value !== "object") return false;
236
- const state = value as { version?: unknown; agents?: unknown };
237
- if (
238
- (state.version !== 1 && state.version !== 2 && state.version !== STATE_VERSION) ||
239
- !Array.isArray(state.agents)
240
- ) {
241
- return false;
242
- }
243
- return state.agents.every((agent) => {
244
- if (!agent || typeof agent !== "object") return false;
245
- const record = agent as Partial<ManagedAgent>;
246
- return (
247
- typeof record.id === "string" &&
248
- (record.taskName === undefined || isValidTaskName(record.taskName)) &&
249
- (record.taskPath === undefined || isValidTaskPath(record.taskPath)) &&
250
- typeof record.agent === "string" &&
251
- typeof record.cwd === "string" &&
252
- typeof record.createdAt === "number" &&
253
- Number.isFinite(record.createdAt) &&
254
- typeof record.updatedAt === "number" &&
255
- Number.isFinite(record.updatedAt) &&
256
- (record.parentId === undefined || typeof record.parentId === "string") &&
257
- (record.thinkingLevel === undefined || isThinkingLevel(record.thinkingLevel)) &&
258
- (record.timeoutMs === undefined || isTurnTimeout(record.timeoutMs)) &&
259
- (record.idleTimeoutMs === undefined || isTurnTimeout(record.idleTimeoutMs)) &&
260
- (record.maxTurns === undefined || isPositiveBounded(record.maxTurns, MAX_SUBAGENT_TURNS)) &&
261
- (record.maxToolCalls === undefined ||
262
- isPositiveBounded(record.maxToolCalls, MAX_SUBAGENT_TOOL_CALLS)) &&
263
- (record.termination === undefined || isTerminationReport(record.termination)) &&
264
- (record.contextTurns === undefined || isNonNegativeInteger(record.contextTurns)) &&
265
- (record.contextBytes === undefined || isNonNegativeInteger(record.contextBytes)) &&
266
- (record.turnGeneration === undefined || isNonNegativeInteger(record.turnGeneration)) &&
267
- (record.pendingCompletions === undefined ||
268
- isCompletionOutbox(record.pendingCompletions, record.turnGeneration ?? 0)) &&
269
- (record.completionRequirements === undefined ||
270
- (Array.isArray(record.completionRequirements) &&
271
- record.completionRequirements.length <= MAX_STORED_COMPLETIONS_PER_AGENT &&
272
- record.completionRequirements.every(isCompletionRequirementRecord))) &&
273
- (record.spawnIdempotencyKey === undefined ||
274
- (typeof record.spawnIdempotencyKey === "string" &&
275
- record.spawnIdempotencyKey.length > 0 &&
276
- record.spawnIdempotencyKey.length <= 256)) &&
277
- (record.spawnRequestHash === undefined || isSha256(record.spawnRequestHash)) &&
278
- (record.contract === undefined ||
279
- normalizeDelegationContract(record.contract) !== undefined) &&
280
- (record.resultFormat === undefined ||
281
- SUBAGENT_RESULT_FORMATS.includes(record.resultFormat)) &&
282
- (record.structuredResult === undefined ||
283
- (record.resultFormat !== undefined &&
284
- parseAnyStructuredSubagentResult(
285
- JSON.stringify(record.structuredResult),
286
- record.resultFormat,
287
- ) !== undefined)) &&
288
- (record.executionPlan === undefined || isExecutionPlan(record.executionPlan)) &&
289
- (record.capabilityGrant === undefined || isCapabilityGrant(record.capabilityGrant)) &&
290
- (record.semanticSnapshot === undefined || isSemanticSnapshot(record.semanticSnapshot)) &&
291
- (record.semanticCompatibility === undefined ||
292
- isSemanticCompatibility(record.semanticCompatibility)) &&
293
- (record.workspaceMode === undefined || record.workspaceMode === "worktree") &&
294
- (record.target === undefined || isTargetPolicyAudit(record.target)) &&
295
- (record.children === undefined ||
296
- (Array.isArray(record.children) &&
297
- record.children.every((id) => typeof id === "string"))) &&
298
- Array.isArray(record.history) &&
299
- record.history.every(isAgentTurn) &&
300
- (record.mailbox === undefined ||
301
- (Array.isArray(record.mailbox) && record.mailbox.every(isMailboxMessage)))
302
- );
303
- });
304
- }
305
-
306
- function isValidTaskName(value: unknown): value is string {
307
- if (typeof value !== "string") return false;
308
- try {
309
- return validateTaskName(value) === value;
310
- } catch {
311
- return false;
312
- }
313
- }
314
-
315
- function isValidTaskPath(value: unknown): value is string {
316
- if (typeof value !== "string") return false;
317
- try {
318
- return validateTaskPath(value) === value;
319
- } catch {
320
- return false;
321
- }
322
- }
323
-
324
- function isSemanticCompatibility(value: unknown): boolean {
325
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
326
- const compatibility = value as Record<string, unknown>;
327
- return (
328
- ["compatible", "warning", "needs-revalidation", "rejected"].includes(
329
- String(compatibility.status),
330
- ) &&
331
- Array.isArray(compatibility.changedComponents) &&
332
- compatibility.changedComponents.every((item) => typeof item === "string")
333
- );
334
- }
335
-
336
- function isNonNegativeInteger(value: unknown): value is number {
337
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
338
- }
339
-
340
- function isTurnTimeout(value: unknown): value is number {
341
- return (
342
- typeof value === "number" &&
343
- Number.isSafeInteger(value) &&
344
- value >= 1 &&
345
- value <= MAX_SUBAGENT_TIMEOUT_MS
346
- );
347
- }
348
-
349
- function isPositiveBounded(value: unknown, maximum: number): value is number {
350
- return typeof value === "number" && Number.isSafeInteger(value) && value >= 1 && value <= maximum;
351
- }
352
-
353
- function isTerminationReport(value: unknown): value is TurnTerminationReport {
354
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
355
- const report = value as Record<string, unknown>;
356
- if (
357
- report.version !== "pi-subagents:termination:v1" ||
358
- ![
359
- "work_timeout",
360
- "idle_timeout",
361
- "turn_limit",
362
- "tool_call_limit",
363
- "orchestration_timeout",
364
- ].includes(String(report.reason)) ||
365
- !isPositiveBounded(report.limit, MAX_SUBAGENT_TIMEOUT_MS)
366
- ) {
367
- return false;
368
- }
369
- const checkpoint = report.checkpoint;
370
- const finalization = report.finalization;
371
- if (!checkpoint || typeof checkpoint !== "object" || Array.isArray(checkpoint)) return false;
372
- if (!finalization || typeof finalization !== "object" || Array.isArray(finalization))
373
- return false;
374
- const checkpointValue = checkpoint as Record<string, unknown>;
375
- const finalizationValue = finalization as Record<string, unknown>;
376
- return (
377
- checkpointValue.version === "pi-subagents:checkpoint:v1" &&
378
- typeof checkpointValue.task === "string" &&
379
- (checkpointValue.partialOutput === undefined ||
380
- typeof checkpointValue.partialOutput === "string") &&
381
- Array.isArray(checkpointValue.assistantNotes) &&
382
- checkpointValue.assistantNotes.every((item) => typeof item === "string") &&
383
- Array.isArray(checkpointValue.completedTools) &&
384
- checkpointValue.completedTools.every(isCompletedToolEvidence) &&
385
- Array.isArray(checkpointValue.changedFiles) &&
386
- checkpointValue.changedFiles.every((item) => typeof item === "string") &&
387
- typeof checkpointValue.sideEffectsMayHaveOccurred === "boolean" &&
388
- typeof checkpointValue.truncated === "boolean" &&
389
- typeof finalizationValue.attempted === "boolean" &&
390
- ["completed", "failed", "timed_out", "skipped"].includes(String(finalizationValue.status)) &&
391
- typeof finalizationValue.durationMs === "number" &&
392
- Number.isFinite(finalizationValue.durationMs) &&
393
- finalizationValue.durationMs >= 0 &&
394
- (finalizationValue.error === undefined || typeof finalizationValue.error === "string")
395
- );
396
- }
397
-
398
- function isCompletedToolEvidence(value: unknown): boolean {
399
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
400
- const item = value as Record<string, unknown>;
401
- return (
402
- typeof item.toolName === "string" &&
403
- typeof item.output === "string" &&
404
- typeof item.isError === "boolean"
405
- );
406
- }
407
-
408
- function isSha256(value: unknown): value is string {
409
- return typeof value === "string" && /^[a-f0-9]{64}$/u.test(value);
410
- }
411
-
412
- function isTargetPolicyAudit(value: unknown): boolean {
413
- if (!value || typeof value !== "object") return false;
414
- const target = value as Record<string, unknown>;
415
- if (
416
- typeof target.cwd !== "string" ||
417
- (target.boundary !== "current-workspace" && target.boundary !== "external") ||
418
- !target.trust ||
419
- typeof target.trust !== "object"
420
- ) {
421
- return false;
422
- }
423
- const trust = target.trust as Record<string, unknown>;
424
- return (
425
- [
426
- "session-trusted",
427
- "session-untrusted",
428
- "saved-trusted",
429
- "saved-denied",
430
- "unsaved",
431
- "trust-error",
432
- ].includes(String(trust.kind)) &&
433
- typeof trust.projectTrusted === "boolean" &&
434
- (trust.sourcePath === undefined || typeof trust.sourcePath === "string") &&
435
- (trust.warning === undefined || typeof trust.warning === "string")
436
- );
437
- }
438
-
439
- function isCompletionOutbox(value: unknown, turnGeneration: number): boolean {
440
- if (!Array.isArray(value) || value.length > MAX_STORED_COMPLETIONS_PER_AGENT) return false;
441
- const ids = new Set<string>();
442
- let previousGeneration = 0;
443
- let previousCreatedAt = Number.NEGATIVE_INFINITY;
444
- for (const completion of value) {
445
- if (!isPersistedCompletion(completion, turnGeneration)) return false;
446
- if (ids.has(completion.completionId)) return false;
447
- if (completion.generation <= previousGeneration || completion.createdAt <= previousCreatedAt) {
448
- return false;
449
- }
450
- ids.add(completion.completionId);
451
- previousGeneration = completion.generation;
452
- previousCreatedAt = completion.createdAt;
453
- }
454
- return true;
455
- }
456
-
457
- function isPersistedCompletion(
458
- value: unknown,
459
- turnGeneration: number,
460
- ): value is import("./registry.js").PersistedAgentCompletion {
461
- if (!value || typeof value !== "object" || Array.isArray(value)) return false;
462
- const completion = value as Record<string, unknown>;
463
- return (
464
- typeof completion.completionId === "string" &&
465
- completion.completionId.length > 0 &&
466
- completion.completionId.length <= 256 &&
467
- (completion.recipientId === undefined ||
468
- (typeof completion.recipientId === "string" && completion.recipientId.length > 0)) &&
469
- (completion.recipientPath === undefined || isValidTaskPath(completion.recipientPath)) &&
470
- typeof completion.runId === "string" &&
471
- completion.runId.length > 0 &&
472
- completion.runId.length <= 256 &&
473
- typeof completion.generation === "number" &&
474
- Number.isSafeInteger(completion.generation) &&
475
- completion.generation >= 1 &&
476
- completion.generation <= turnGeneration &&
477
- typeof completion.task === "string" &&
478
- typeof completion.output === "string" &&
479
- (completion.error === undefined || typeof completion.error === "string") &&
480
- typeof completion.createdAt === "number" &&
481
- Number.isFinite(completion.createdAt)
482
- );
483
- }
484
-
485
- function isAgentTurn(value: unknown): boolean {
486
- if (!value || typeof value !== "object") return false;
487
- const turn = value as Record<string, unknown>;
488
- return (
489
- (turn.runId === undefined ||
490
- (typeof turn.runId === "string" && turn.runId.length > 0 && turn.runId.length <= 256)) &&
491
- (turn.generation === undefined ||
492
- (typeof turn.generation === "number" &&
493
- Number.isSafeInteger(turn.generation) &&
494
- turn.generation >= 1)) &&
495
- typeof turn.task === "string" &&
496
- typeof turn.output === "string" &&
497
- typeof turn.startedAt === "number" &&
498
- Number.isFinite(turn.startedAt) &&
499
- typeof turn.completedAt === "number" &&
500
- Number.isFinite(turn.completedAt) &&
501
- typeof turn.exitCode === "number" &&
502
- Number.isFinite(turn.exitCode) &&
503
- (turn.termination === undefined || isTerminationReport(turn.termination))
504
- );
505
- }
506
-
507
- function isMailboxMessage(value: unknown): boolean {
508
- if (!value || typeof value !== "object") return false;
509
- const message = value as Record<string, unknown>;
510
- return (
511
- typeof message.id === "string" &&
512
- typeof message.senderId === "string" &&
513
- typeof message.recipientId === "string" &&
514
- typeof message.content === "string" &&
515
- typeof message.createdAt === "number" &&
516
- Number.isFinite(message.createdAt) &&
517
- (message.readAt === undefined ||
518
- (typeof message.readAt === "number" && Number.isFinite(message.readAt))) &&
519
- (message.deduplicationKey === undefined || typeof message.deduplicationKey === "string") &&
520
- (message.completionId === undefined || typeof message.completionId === "string")
521
- );
522
- }
package/src/pi-args.ts DELETED
@@ -1,43 +0,0 @@
1
- import type { SubagentThinkingLevel } from "./agents/types.js";
2
-
3
- export interface PiArgsOptions {
4
- model?: string;
5
- thinkingLevel?: SubagentThinkingLevel;
6
- tools?: string[];
7
- disableExtensions?: boolean;
8
- disableSkills?: boolean;
9
- disablePromptTemplates?: boolean;
10
- disableContextFiles?: boolean;
11
- projectTrust?: boolean;
12
- baseSystemPromptPath?: string;
13
- appendSystemPromptPaths?: string[];
14
- extensionPaths?: string[];
15
- /** Existing single append prompt path retained for compatibility. */
16
- systemPromptPath?: string;
17
- task: string;
18
- }
19
-
20
- export function buildPiArgs(options: PiArgsOptions): string[] {
21
- const args: string[] = ["--mode", "json", "-p", "--no-session"];
22
- if (options.model) args.push("--model", options.model);
23
- if (options.thinkingLevel) args.push("--thinking", options.thinkingLevel);
24
- if (options.disableExtensions) args.push("--no-extensions");
25
- for (const extensionPath of options.extensionPaths ?? []) args.push("-e", extensionPath);
26
- if (options.disableSkills) args.push("--no-skills");
27
- if (options.disablePromptTemplates) args.push("--no-prompt-templates");
28
- if (options.disableContextFiles) args.push("--no-context-files");
29
- if (options.projectTrust !== undefined) {
30
- args.push(options.projectTrust ? "--approve" : "--no-approve");
31
- }
32
- if (Array.isArray(options.tools)) {
33
- if (options.tools.length > 0) args.push("--tools", options.tools.join(","));
34
- else args.push("--no-tools");
35
- }
36
- if (options.baseSystemPromptPath) args.push("--system-prompt", options.baseSystemPromptPath);
37
- for (const promptPath of options.appendSystemPromptPaths ?? []) {
38
- args.push("--append-system-prompt", promptPath);
39
- }
40
- if (options.systemPromptPath) args.push("--append-system-prompt", options.systemPromptPath);
41
- args.push(`Task: ${options.task}`);
42
- return args;
43
- }