@draht/coding-agent 2026.10.4 → 2026.10.8-1

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 (282) hide show
  1. package/CHANGELOG.md +13 -0
  2. package/README.md +32 -6
  3. package/dist/bundle/chunks/{anthropic-messages-GAKYXF65.js → anthropic-messages-E2P6C3P7.js} +1 -1
  4. package/dist/bundle/chunks/anthropic.js +1 -1
  5. package/dist/bundle/chunks/{azure-openai-responses-ZIXMK6JO.js → azure-openai-responses-JZMSTDIM.js} +1 -1
  6. package/dist/bundle/chunks/bedrock-converse-stream.js +20 -20
  7. package/dist/bundle/chunks/chunk-2JZLKNZ4.js +3 -0
  8. package/dist/bundle/chunks/chunk-5QJFWTKA.js +4 -0
  9. package/dist/bundle/chunks/{chunk-XKDTJ4YR.js → chunk-6QIFWMDF.js} +1 -1
  10. package/dist/bundle/chunks/{chunk-5VZWYVZB.js → chunk-AHGUOQPH.js} +2 -2
  11. package/dist/bundle/chunks/{chunk-H6FT43VC.js → chunk-BOGY4QVF.js} +4 -4
  12. package/dist/bundle/chunks/{chunk-RZKPFWMH.js → chunk-D3HO453P.js} +2 -2
  13. package/dist/bundle/chunks/{chunk-KVH4HR57.js → chunk-FHX2S5IG.js} +1 -1
  14. package/dist/bundle/chunks/chunk-GBFVS2SF.js +12 -0
  15. package/dist/bundle/chunks/chunk-GD2WVXWT.js +65 -0
  16. package/dist/bundle/chunks/{chunk-Z2INEV2J.js → chunk-KJJJSTND.js} +307 -168
  17. package/dist/bundle/chunks/{chunk-BXSHCX3G.js → chunk-KY2BG6BC.js} +1 -1
  18. package/dist/bundle/chunks/chunk-LO6CVU2L.js +6 -0
  19. package/dist/bundle/chunks/chunk-PGJAHC3R.js +107 -0
  20. package/dist/bundle/chunks/chunk-QVFELZW2.js +312 -0
  21. package/dist/bundle/chunks/{chunk-COF5JT7R.js → chunk-QVTLBSTH.js} +1 -1
  22. package/dist/bundle/chunks/{chunk-DPE4ALPU.js → chunk-U6LDZZGM.js} +10 -10
  23. package/dist/bundle/chunks/{chunk-D6TMD5Q2.js → chunk-UTRX2VHB.js} +8 -8
  24. package/dist/bundle/chunks/{chunk-LDAOC5RB.js → chunk-VQOV5VFH.js} +1 -1
  25. package/dist/bundle/chunks/chunk-VXUJMEMO.js +2 -0
  26. package/dist/bundle/chunks/{cli-SR5QBZH4.js → cli-O6OWCY7N.js} +1 -1
  27. package/dist/bundle/chunks/execute-4JU5WQXP.js +18 -0
  28. package/dist/bundle/chunks/google-antigravity.js +1 -1
  29. package/dist/bundle/chunks/google-gemini-cli.js +1 -1
  30. package/dist/bundle/chunks/{google-generative-ai-RPUPQ6PM.js → google-generative-ai-HPNDIAZD.js} +1 -1
  31. package/dist/bundle/chunks/{google-vertex-EZES5QVQ.js → google-vertex-KPAWJ4SP.js} +1 -1
  32. package/dist/bundle/chunks/https-proxy-agent-WQIRL24U.js +13 -0
  33. package/dist/bundle/chunks/lib-ULKZYRGD.js +9 -0
  34. package/dist/bundle/chunks/{mistral-conversations-AOYGU43Y.js → mistral-conversations-FMSPWQ7A.js} +1 -1
  35. package/dist/bundle/chunks/{multipart-parser-AZP5BX2W.js → multipart-parser-HMCXZ4BD.js} +1 -1
  36. package/dist/bundle/chunks/{node-LQ52KV6B.js → node-4JNG6XQO.js} +1 -1
  37. package/dist/bundle/chunks/{node-C2JGH2OB.js → node-6IIDYB3K.js} +1 -1
  38. package/dist/bundle/chunks/openai-chatgpt.js +1 -1
  39. package/dist/bundle/chunks/{openai-codex-responses-M2Y77JEQ.js → openai-codex-responses-TU7NGPXE.js} +1 -1
  40. package/dist/bundle/chunks/openai-codex.js +1 -1
  41. package/dist/bundle/chunks/{openai-completions-A4OKYOYV.js → openai-completions-GANCQQO5.js} +1 -1
  42. package/dist/bundle/chunks/{openai-responses-6IXV53T3.js → openai-responses-ASDPAX3E.js} +1 -1
  43. package/dist/bundle/chunks/{openrouter-images-LYV4NKFM.js → openrouter-images-NROSQXMZ.js} +1 -1
  44. package/dist/bundle/chunks/openrouter.js +1 -1
  45. package/dist/bundle/chunks/{pi-messages-KKMEUT3Z.js → pi-messages-2QEJYOAO.js} +1 -1
  46. package/dist/bundle/chunks/radius.js +1 -1
  47. package/dist/bundle/chunks/{runtime-6YJPGSP7.js → runtime-FIGQHW75.js} +1 -1
  48. package/dist/bundle/chunks/runtime-TJ3EAMJK.js +3 -0
  49. package/dist/bundle/chunks/{settings-manager-D2EG7WDO.js → settings-manager-HC5RR36T.js} +1 -1
  50. package/dist/bundle/chunks/src-KDGO7EGF.js +4 -0
  51. package/dist/bundle/chunks/virtual-modules-UIGTRGHQ.js +2 -0
  52. package/dist/bundle/chunks/xai.js +1 -1
  53. package/dist/bundle/cli-runtime.js +1 -1
  54. package/dist/bundle/index.js +1 -1
  55. package/dist/bundle/rpc-entry.js +1 -1
  56. package/dist/cli/args.js +3 -3
  57. package/dist/cli/args.js.map +1 -1
  58. package/dist/core/builtins/duet.d.ts +5 -2
  59. package/dist/core/builtins/duet.d.ts.map +1 -1
  60. package/dist/core/builtins/duet.js +65 -27
  61. package/dist/core/builtins/duet.js.map +1 -1
  62. package/dist/core/builtins/index.d.ts.map +1 -1
  63. package/dist/core/builtins/index.js +2 -0
  64. package/dist/core/builtins/index.js.map +1 -1
  65. package/dist/core/builtins/polyphase.d.ts +15 -0
  66. package/dist/core/builtins/polyphase.d.ts.map +1 -0
  67. package/dist/core/builtins/polyphase.js +196 -0
  68. package/dist/core/builtins/polyphase.js.map +1 -0
  69. package/dist/core/builtins/subagent.d.ts +44 -34
  70. package/dist/core/builtins/subagent.d.ts.map +1 -1
  71. package/dist/core/builtins/subagent.js +827 -560
  72. package/dist/core/builtins/subagent.js.map +1 -1
  73. package/dist/core/extensions/types.d.ts +17 -2
  74. package/dist/core/extensions/types.d.ts.map +1 -1
  75. package/dist/core/extensions/types.js.map +1 -1
  76. package/dist/core/keybindings.d.ts +30 -0
  77. package/dist/core/keybindings.d.ts.map +1 -1
  78. package/dist/core/keybindings.js +24 -0
  79. package/dist/core/keybindings.js.map +1 -1
  80. package/dist/core/model-resolver.js +4 -4
  81. package/dist/core/model-resolver.js.map +1 -1
  82. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  83. package/dist/core/multi-agent/permission-gate.js +4 -1
  84. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  85. package/dist/core/polyphase/approval.d.ts +35 -0
  86. package/dist/core/polyphase/approval.d.ts.map +1 -0
  87. package/dist/core/polyphase/approval.js +184 -0
  88. package/dist/core/polyphase/approval.js.map +1 -0
  89. package/dist/core/polyphase/child-events.d.ts +107 -0
  90. package/dist/core/polyphase/child-events.d.ts.map +1 -0
  91. package/dist/core/polyphase/child-events.js +862 -0
  92. package/dist/core/polyphase/child-events.js.map +1 -0
  93. package/dist/core/polyphase/child-process.d.ts +65 -0
  94. package/dist/core/polyphase/child-process.d.ts.map +1 -0
  95. package/dist/core/polyphase/child-process.js +361 -0
  96. package/dist/core/polyphase/child-process.js.map +1 -0
  97. package/dist/core/polyphase/commands.d.ts +44 -0
  98. package/dist/core/polyphase/commands.d.ts.map +1 -0
  99. package/dist/core/polyphase/commands.js +244 -0
  100. package/dist/core/polyphase/commands.js.map +1 -0
  101. package/dist/core/polyphase/details.d.ts +40 -0
  102. package/dist/core/polyphase/details.d.ts.map +1 -0
  103. package/dist/core/polyphase/details.js +538 -0
  104. package/dist/core/polyphase/details.js.map +1 -0
  105. package/dist/core/polyphase/emitter.d.ts +20 -0
  106. package/dist/core/polyphase/emitter.d.ts.map +1 -0
  107. package/dist/core/polyphase/emitter.js +90 -0
  108. package/dist/core/polyphase/emitter.js.map +1 -0
  109. package/dist/core/polyphase/jsonl-reader.d.ts +31 -0
  110. package/dist/core/polyphase/jsonl-reader.d.ts.map +1 -0
  111. package/dist/core/polyphase/jsonl-reader.js +161 -0
  112. package/dist/core/polyphase/jsonl-reader.js.map +1 -0
  113. package/dist/core/polyphase/keyword.d.ts +27 -0
  114. package/dist/core/polyphase/keyword.d.ts.map +1 -0
  115. package/dist/core/polyphase/keyword.js +97 -0
  116. package/dist/core/polyphase/keyword.js.map +1 -0
  117. package/dist/core/polyphase/limiter.d.ts +38 -0
  118. package/dist/core/polyphase/limiter.d.ts.map +1 -0
  119. package/dist/core/polyphase/limiter.js +129 -0
  120. package/dist/core/polyphase/limiter.js.map +1 -0
  121. package/dist/core/polyphase/model-selection.d.ts +35 -0
  122. package/dist/core/polyphase/model-selection.d.ts.map +1 -0
  123. package/dist/core/polyphase/model-selection.js +72 -0
  124. package/dist/core/polyphase/model-selection.js.map +1 -0
  125. package/dist/core/polyphase/render/format.d.ts +52 -0
  126. package/dist/core/polyphase/render/format.d.ts.map +1 -0
  127. package/dist/core/polyphase/render/format.js +169 -0
  128. package/dist/core/polyphase/render/format.js.map +1 -0
  129. package/dist/core/polyphase/render/renderers.d.ts +63 -0
  130. package/dist/core/polyphase/render/renderers.d.ts.map +1 -0
  131. package/dist/core/polyphase/render/renderers.js +277 -0
  132. package/dist/core/polyphase/render/renderers.js.map +1 -0
  133. package/dist/core/polyphase/render/run-block.d.ts +45 -0
  134. package/dist/core/polyphase/render/run-block.d.ts.map +1 -0
  135. package/dist/core/polyphase/render/run-block.js +843 -0
  136. package/dist/core/polyphase/render/run-block.js.map +1 -0
  137. package/dist/core/polyphase/render/snapshot.d.ts +106 -0
  138. package/dist/core/polyphase/render/snapshot.d.ts.map +1 -0
  139. package/dist/core/polyphase/render/snapshot.js +292 -0
  140. package/dist/core/polyphase/render/snapshot.js.map +1 -0
  141. package/dist/core/polyphase/result-text.d.ts +41 -0
  142. package/dist/core/polyphase/result-text.d.ts.map +1 -0
  143. package/dist/core/polyphase/result-text.js +326 -0
  144. package/dist/core/polyphase/result-text.js.map +1 -0
  145. package/dist/core/polyphase/session.d.ts +33 -0
  146. package/dist/core/polyphase/session.d.ts.map +1 -0
  147. package/dist/core/polyphase/session.js +106 -0
  148. package/dist/core/polyphase/session.js.map +1 -0
  149. package/dist/core/polyphase/settings.d.ts +18 -0
  150. package/dist/core/polyphase/settings.d.ts.map +1 -0
  151. package/dist/core/polyphase/settings.js +93 -0
  152. package/dist/core/polyphase/settings.js.map +1 -0
  153. package/dist/core/polyphase/store.d.ts +197 -0
  154. package/dist/core/polyphase/store.d.ts.map +1 -0
  155. package/dist/core/polyphase/store.js +558 -0
  156. package/dist/core/polyphase/store.js.map +1 -0
  157. package/dist/core/polyphase/types.d.ts +371 -0
  158. package/dist/core/polyphase/types.d.ts.map +1 -0
  159. package/dist/core/polyphase/types.js +36 -0
  160. package/dist/core/polyphase/types.js.map +1 -0
  161. package/dist/core/polyphase/ui/controller.d.ts +28 -0
  162. package/dist/core/polyphase/ui/controller.d.ts.map +1 -0
  163. package/dist/core/polyphase/ui/controller.js +150 -0
  164. package/dist/core/polyphase/ui/controller.js.map +1 -0
  165. package/dist/core/polyphase/ui/dock.d.ts +27 -0
  166. package/dist/core/polyphase/ui/dock.d.ts.map +1 -0
  167. package/dist/core/polyphase/ui/dock.js +121 -0
  168. package/dist/core/polyphase/ui/dock.js.map +1 -0
  169. package/dist/core/polyphase/ui/inspector.d.ts +117 -0
  170. package/dist/core/polyphase/ui/inspector.d.ts.map +1 -0
  171. package/dist/core/polyphase/ui/inspector.js +1016 -0
  172. package/dist/core/polyphase/ui/inspector.js.map +1 -0
  173. package/dist/core/polyphase/ui/transcript-layout.d.ts +55 -0
  174. package/dist/core/polyphase/ui/transcript-layout.d.ts.map +1 -0
  175. package/dist/core/polyphase/ui/transcript-layout.js +210 -0
  176. package/dist/core/polyphase/ui/transcript-layout.js.map +1 -0
  177. package/dist/core/polyphase/update-pump.d.ts +18 -0
  178. package/dist/core/polyphase/update-pump.d.ts.map +1 -0
  179. package/dist/core/polyphase/update-pump.js +132 -0
  180. package/dist/core/polyphase/update-pump.js.map +1 -0
  181. package/dist/core/polyphase/workflow/agent-host.d.ts +26 -0
  182. package/dist/core/polyphase/workflow/agent-host.d.ts.map +1 -0
  183. package/dist/core/polyphase/workflow/agent-host.js +187 -0
  184. package/dist/core/polyphase/workflow/agent-host.js.map +1 -0
  185. package/dist/core/polyphase/workflow/guidance.d.ts +19 -0
  186. package/dist/core/polyphase/workflow/guidance.d.ts.map +1 -0
  187. package/dist/core/polyphase/workflow/guidance.js +119 -0
  188. package/dist/core/polyphase/workflow/guidance.js.map +1 -0
  189. package/dist/core/polyphase/workflow/launch.d.ts +41 -0
  190. package/dist/core/polyphase/workflow/launch.d.ts.map +1 -0
  191. package/dist/core/polyphase/workflow/launch.js +173 -0
  192. package/dist/core/polyphase/workflow/launch.js.map +1 -0
  193. package/dist/core/polyphase/workflow/meta.d.ts +43 -0
  194. package/dist/core/polyphase/workflow/meta.d.ts.map +1 -0
  195. package/dist/core/polyphase/workflow/meta.js +529 -0
  196. package/dist/core/polyphase/workflow/meta.js.map +1 -0
  197. package/dist/core/polyphase/workflow/prelude.d.ts +24 -0
  198. package/dist/core/polyphase/workflow/prelude.d.ts.map +1 -0
  199. package/dist/core/polyphase/workflow/prelude.js +93 -0
  200. package/dist/core/polyphase/workflow/prelude.js.map +1 -0
  201. package/dist/core/polyphase/workflow/runtime.d.ts +79 -0
  202. package/dist/core/polyphase/workflow/runtime.d.ts.map +1 -0
  203. package/dist/core/polyphase/workflow/runtime.js +217 -0
  204. package/dist/core/polyphase/workflow/runtime.js.map +1 -0
  205. package/dist/core/polyphase/workflow/runtime.lazy.d.ts +3 -0
  206. package/dist/core/polyphase/workflow/runtime.lazy.d.ts.map +1 -0
  207. package/dist/core/polyphase/workflow/runtime.lazy.js +3 -0
  208. package/dist/core/polyphase/workflow/runtime.lazy.js.map +1 -0
  209. package/dist/core/polyphase/workflow/saved.d.ts +55 -0
  210. package/dist/core/polyphase/workflow/saved.d.ts.map +1 -0
  211. package/dist/core/polyphase/workflow/saved.js +299 -0
  212. package/dist/core/polyphase/workflow/saved.js.map +1 -0
  213. package/dist/core/polyphase/workflow/structured-output.d.ts +22 -0
  214. package/dist/core/polyphase/workflow/structured-output.d.ts.map +1 -0
  215. package/dist/core/polyphase/workflow/structured-output.js +66 -0
  216. package/dist/core/polyphase/workflow/structured-output.js.map +1 -0
  217. package/dist/core/polyphase/workflow/tool.d.ts +24 -0
  218. package/dist/core/polyphase/workflow/tool.d.ts.map +1 -0
  219. package/dist/core/polyphase/workflow/tool.js +139 -0
  220. package/dist/core/polyphase/workflow/tool.js.map +1 -0
  221. package/dist/core/sdk.d.ts +1 -1
  222. package/dist/core/sdk.js +1 -1
  223. package/dist/core/sdk.js.map +1 -1
  224. package/dist/core/settings-manager.d.ts +27 -0
  225. package/dist/core/settings-manager.d.ts.map +1 -1
  226. package/dist/core/settings-manager.js.map +1 -1
  227. package/dist/core/socket-server/permission-relay.js +4 -0
  228. package/dist/core/socket-server/permission-relay.js.map +1 -1
  229. package/dist/core/trust-manager.d.ts +3 -2
  230. package/dist/core/trust-manager.d.ts.map +1 -1
  231. package/dist/core/trust-manager.js +5 -2
  232. package/dist/core/trust-manager.js.map +1 -1
  233. package/dist/experimental/micro/runtime.js +1 -1
  234. package/dist/experimental/micro/runtime.js.map +1 -1
  235. package/dist/modes/interactive/components/keybinding-hints.d.ts +7 -0
  236. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  237. package/dist/modes/interactive/components/keybinding-hints.js +18 -0
  238. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  239. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  240. package/dist/modes/interactive/interactive-mode.js +11 -2
  241. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  242. package/dist/modes/rpc/rpc-types.d.ts +9 -0
  243. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  244. package/dist/modes/rpc/rpc-types.js.map +1 -1
  245. package/dist/prompts/commands/orchestrate.md +1 -1
  246. package/dist/utils/shell.d.ts.map +1 -1
  247. package/dist/utils/shell.js +7 -1
  248. package/dist/utils/shell.js.map +1 -1
  249. package/docs/docs.json +4 -0
  250. package/docs/duet.md +3 -3
  251. package/docs/environment-variables.md +11 -0
  252. package/docs/json.md +7 -0
  253. package/docs/keybindings.md +20 -0
  254. package/docs/polyphase.md +391 -0
  255. package/docs/rpc-commands.md +9 -9
  256. package/docs/settings.md +12 -0
  257. package/docs/virtual-models.md +3 -3
  258. package/examples/extensions/preset.ts +3 -3
  259. package/examples/extensions/subagent/README.md +1 -1
  260. package/examples/extensions/subagent/agents/planner.md +1 -1
  261. package/examples/extensions/subagent/agents/reviewer.md +1 -1
  262. package/examples/extensions/subagent/agents/scout.md +1 -1
  263. package/examples/extensions/subagent/agents/worker.md +1 -1
  264. package/examples/extensions/summarize.ts +3 -3
  265. package/examples/sdk/02-custom-model.ts +1 -1
  266. package/examples/sdk/12-full-control.ts +1 -1
  267. package/examples/sdk/README.md +1 -1
  268. package/package.json +10 -10
  269. package/prompts/commands/orchestrate.md +1 -1
  270. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +0 -6
  271. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +0 -2
  272. package/dist/bundle/chunks/chunk-736QBNUZ.js +0 -12
  273. package/dist/bundle/chunks/chunk-CEJJ5XF2.js +0 -170
  274. package/dist/bundle/chunks/chunk-IWTUBX6V.js +0 -4
  275. package/dist/bundle/chunks/chunk-TIA2T6EO.js +0 -3
  276. package/dist/bundle/chunks/execute-VCYDHEYA.js +0 -328
  277. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +0 -13
  278. package/dist/bundle/chunks/lib-XOG5PI3Y.js +0 -9
  279. package/dist/bundle/chunks/src-TIBHS42X.js +0 -4
  280. package/dist/bundle/chunks/virtual-modules-JTCGDL2Z.js +0 -2
  281. /package/dist/bundle/chunks/{chunk-ZZD35WKM.js → chunk-FBU742QF.js} +0 -0
  282. /package/dist/bundle/chunks/{chunk-SVNWI7EV.js → chunk-XHCO4PPH.js} +0 -0
@@ -0,0 +1,558 @@
1
+ /**
2
+ * Session-scoped live state for polyphase runs: `LiveAgent` wraps a child's `ChildEventReducer`
3
+ * with lifecycle/cancellation, `PolyphaseRun` groups agents into one subagent/workflow run, and
4
+ * `PolyphaseStore` owns every run plus the pump flush cycle and retention.
5
+ */
6
+ import { billableTokens, ChildEventReducer } from "./child-events.js";
7
+ import { DEFAULT_CHILD_STATE_LIMITS, } from "./types.js";
8
+ const TERMINAL_STATUSES = ["done", "failed", "cancelled", "skipped"];
9
+ /**
10
+ * Meta caps declared phases at 20 (`meta.ts`); this caps the dynamic ones a script can add by
11
+ * calling `phase()` with a new title each time. Without a cap, every new title grows `phasesList`
12
+ * forever, so each later `phase()` call's `findIndex` scan gets more expensive and the run keeps
13
+ * broadcasting a coarse update for each one.
14
+ */
15
+ const MAX_PHASES = 100;
16
+ /** Finished runs newest-first, by `endedAt` then the store-assigned `finishSeq` tiebreak. */
17
+ function finishedNewestFirst(a, b) {
18
+ return (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt) || (b.finishSeq ?? 0) - (a.finishSeq ?? 0);
19
+ }
20
+ function isTerminal(status) {
21
+ return TERMINAL_STATUSES.includes(status);
22
+ }
23
+ /** Live state of one child agent, wired into its owning run's dirty/cancel machinery. */
24
+ export class LiveAgent {
25
+ key;
26
+ index;
27
+ label;
28
+ agentType;
29
+ task;
30
+ phase;
31
+ step;
32
+ createdAt;
33
+ reducer;
34
+ /** `AbortSignal.any([run.signal, own controller])`. */
35
+ signal;
36
+ run;
37
+ controller = new AbortController();
38
+ _cancelReason;
39
+ _result;
40
+ _skipped = false;
41
+ constructor(run, index, init, now) {
42
+ this.run = run;
43
+ this.index = index;
44
+ this.key = `${run.id}#${index}`;
45
+ this.label = init.label;
46
+ this.agentType = init.agentType;
47
+ this.task = init.task;
48
+ this.phase = init.phase;
49
+ this.step = init.step;
50
+ this.createdAt = now();
51
+ this.reducer = new ChildEventReducer({ model: init.model, now });
52
+ this.signal = AbortSignal.any([run.signal, this.controller.signal]);
53
+ }
54
+ get state() {
55
+ return this.reducer.state;
56
+ }
57
+ get result() {
58
+ return this._result;
59
+ }
60
+ get cancelReason() {
61
+ return this._cancelReason;
62
+ }
63
+ get status() {
64
+ if (this._result) {
65
+ if (this._result.cancelled)
66
+ return "cancelled";
67
+ return this._result.exitCode === 0 ? "done" : "failed";
68
+ }
69
+ if (this._skipped)
70
+ return "skipped";
71
+ switch (this.reducer.state.lifecycle) {
72
+ case "running":
73
+ case "settled":
74
+ case "exited":
75
+ return "running";
76
+ case "spawning":
77
+ return "starting";
78
+ case "queued":
79
+ return "queued";
80
+ default:
81
+ return "pending";
82
+ }
83
+ }
84
+ /** Sets `cancelReason` once and aborts this agent's own controller. False when already finished. */
85
+ cancel(reason) {
86
+ if (isTerminal(this.status))
87
+ return false;
88
+ if (this._cancelReason === undefined)
89
+ this._cancelReason = reason;
90
+ if (!this.controller.signal.aborted)
91
+ this.controller.abort();
92
+ return true;
93
+ }
94
+ createRunContext(base = {}) {
95
+ return {
96
+ ...base,
97
+ reducer: this.reducer,
98
+ onQueued: () => {
99
+ this.reducer.markQueued();
100
+ this.run.markDirty("coarse");
101
+ },
102
+ onStart: () => {
103
+ this.run.markDirty("coarse");
104
+ },
105
+ onChange: (change) => {
106
+ this.run.markDirty(change);
107
+ },
108
+ onFinish: (result) => {
109
+ this.complete(result);
110
+ },
111
+ };
112
+ }
113
+ complete(result) {
114
+ if (this._result !== undefined || this._skipped)
115
+ return;
116
+ this._result = result;
117
+ if (this.run.status !== "running") {
118
+ // The run already ran retention when it finished. An agent that settles afterwards
119
+ // (e.g. still being SIGTERM'd) would otherwise keep growing under the running-time
120
+ // transcript cap until the next unrelated run finishes and sweeps it.
121
+ if (this.run.transcriptsDropped)
122
+ this.reducer.dropTranscript();
123
+ else
124
+ this.reducer.trimForRetention(DEFAULT_CHILD_STATE_LIMITS.finishedMaxChars);
125
+ }
126
+ this.run.markDirty("coarse");
127
+ }
128
+ markSkipped() {
129
+ if (this._result !== undefined || this._skipped)
130
+ return;
131
+ this._skipped = true;
132
+ this.run.markDirty("coarse");
133
+ }
134
+ }
135
+ /** One subagent/duet/workflow run: its agents, phases, log and budget. */
136
+ export class PolyphaseRun {
137
+ id;
138
+ kind;
139
+ origin;
140
+ mode;
141
+ title;
142
+ workflow;
143
+ startedAt;
144
+ /** Monotonic store-assigned sequence, for tie-breaking same-timestamp ordering. */
145
+ createSeq;
146
+ /** Aborted by `cancel()` and by `parentSignal` (via `cancel("parent")`). */
147
+ signal;
148
+ version = 0;
149
+ coarseVersion = 0;
150
+ deps;
151
+ controller = new AbortController();
152
+ agentsList = [];
153
+ phasesList;
154
+ logList = [];
155
+ flushListeners = new Set();
156
+ budgetTotal;
157
+ parentSignal;
158
+ parentAbortHandler;
159
+ currentPhaseValue;
160
+ statusValue = "running";
161
+ endedAtValue;
162
+ finishSeqValue;
163
+ resultPreviewValue;
164
+ errorValue;
165
+ logDroppedValue = 0;
166
+ budgetExhausted = false;
167
+ warnedDynamicPhase = false;
168
+ warnedPhaseCap = false;
169
+ cancelReasonValue;
170
+ transcriptsDroppedValue = false;
171
+ constructor(init, deps) {
172
+ this.deps = deps;
173
+ this.id = init.id;
174
+ this.kind = init.kind;
175
+ this.origin = init.origin;
176
+ this.mode = init.mode;
177
+ this.title = init.title;
178
+ this.workflow = init.workflow;
179
+ this.phasesList = (init.phases ?? []).map((phase) => ({ ...phase, dynamic: false }));
180
+ this.budgetTotal = init.budgetTokens;
181
+ this.startedAt = deps.now();
182
+ this.createSeq = deps.nextSeq();
183
+ this.signal = this.controller.signal;
184
+ if (init.parentSignal) {
185
+ this.parentSignal = init.parentSignal;
186
+ if (init.parentSignal.aborted) {
187
+ this.cancel("parent");
188
+ }
189
+ else {
190
+ this.parentAbortHandler = () => this.cancel("parent");
191
+ init.parentSignal.addEventListener("abort", this.parentAbortHandler, { once: true });
192
+ }
193
+ }
194
+ }
195
+ get phases() {
196
+ return this.phasesList;
197
+ }
198
+ get currentPhase() {
199
+ return this.currentPhaseValue;
200
+ }
201
+ get status() {
202
+ return this.statusValue;
203
+ }
204
+ get endedAt() {
205
+ return this.endedAtValue;
206
+ }
207
+ /** Monotonic store-assigned sequence set in `finish()`, for tie-breaking same-timestamp ordering. */
208
+ get finishSeq() {
209
+ return this.finishSeqValue;
210
+ }
211
+ get agents() {
212
+ return this.agentsList;
213
+ }
214
+ get log() {
215
+ return this.logList;
216
+ }
217
+ get logDropped() {
218
+ return this.logDroppedValue;
219
+ }
220
+ get budget() {
221
+ return { totalTokens: this.budgetTotal, spentTokens: this.spentTokens(), exhausted: this.budgetExhausted };
222
+ }
223
+ get resultPreview() {
224
+ return this.resultPreviewValue;
225
+ }
226
+ get error() {
227
+ return this.errorValue;
228
+ }
229
+ addAgent(init) {
230
+ const agent = new LiveAgent(this, this.agentsList.length, init, this.deps.now);
231
+ this.agentsList.push(agent);
232
+ // The agent's own signal is already aborted (AbortSignal.any includes this.signal), but it
233
+ // carries no cancelReason yet: inherit the run's, so it matches its siblings.
234
+ if (this.signal.aborted && this.cancelReasonValue !== undefined)
235
+ agent.cancel(this.cancelReasonValue);
236
+ this.markDirty("coarse");
237
+ return agent;
238
+ }
239
+ /** Index of an existing phase with this title, or a new dynamic phase (one-time warning). `undefined` title returns `currentPhase`. */
240
+ resolvePhase(title) {
241
+ if (title === undefined)
242
+ return this.currentPhaseValue;
243
+ return this.phaseIndexFor(title);
244
+ }
245
+ enterPhase(title) {
246
+ const index = this.phaseIndexFor(title);
247
+ this.currentPhaseValue = index;
248
+ this.markDirty("coarse");
249
+ return index;
250
+ }
251
+ phaseIndexFor(title) {
252
+ const existing = this.phasesList.findIndex((phase) => phase.title === title);
253
+ if (existing !== -1)
254
+ return existing;
255
+ if (this.phasesList.length >= MAX_PHASES) {
256
+ if (!this.warnedPhaseCap) {
257
+ this.warnedPhaseCap = true;
258
+ this.appendLog(`workflow reached the ${MAX_PHASES}-phase cap; new phase titles are ignored`, "warning");
259
+ }
260
+ throw new Error(`phase cap reached: a run may have at most ${MAX_PHASES} phases`);
261
+ }
262
+ this.phasesList.push({ title, dynamic: true });
263
+ if (!this.warnedDynamicPhase) {
264
+ this.warnedDynamicPhase = true;
265
+ this.appendLog("workflow entered a phase not declared in meta.phases", "warning");
266
+ }
267
+ return this.phasesList.length - 1;
268
+ }
269
+ appendLog(text, level = "info") {
270
+ const capped = text.length > 2000 ? text.slice(0, 2000) : text;
271
+ this.logList.push({ at: this.deps.now(), level, text: capped, phase: this.currentPhaseValue });
272
+ if (this.logList.length > 200) {
273
+ this.logList.shift();
274
+ this.logDroppedValue++;
275
+ }
276
+ this.markDirty("coarse");
277
+ }
278
+ setResultPreview(text) {
279
+ this.resultPreviewValue = text;
280
+ this.markDirty("coarse");
281
+ }
282
+ markDirty(change) {
283
+ this.deps.pump.schedule(this.id, change);
284
+ this.checkBudget();
285
+ }
286
+ spentTokens() {
287
+ let total = 0;
288
+ for (const agent of this.agentsList) {
289
+ total += billableTokens(agent.state.usage) + billableTokens(agent.state.liveUsage);
290
+ }
291
+ return total;
292
+ }
293
+ counts() {
294
+ const result = {
295
+ pending: 0,
296
+ queued: 0,
297
+ starting: 0,
298
+ running: 0,
299
+ done: 0,
300
+ failed: 0,
301
+ cancelled: 0,
302
+ skipped: 0,
303
+ };
304
+ for (const agent of this.agentsList)
305
+ result[agent.status]++;
306
+ return result;
307
+ }
308
+ cancel(reason) {
309
+ if (this.cancelReasonValue === undefined)
310
+ this.cancelReasonValue = reason;
311
+ for (const agent of this.agentsList)
312
+ agent.cancel(reason);
313
+ if (!this.controller.signal.aborted)
314
+ this.controller.abort();
315
+ this.markDirty("coarse");
316
+ }
317
+ /** Pending agents become skipped; the heartbeat stops; retention runs. */
318
+ finish(status, error) {
319
+ if (this.statusValue !== "running")
320
+ return;
321
+ for (const agent of this.agentsList) {
322
+ if (agent.status === "pending")
323
+ agent.markSkipped();
324
+ }
325
+ this.statusValue = status;
326
+ this.endedAtValue = this.deps.now();
327
+ this.finishSeqValue = this.deps.nextSeq();
328
+ if (error !== undefined)
329
+ this.errorValue = error;
330
+ this.deps.pump.stopHeartbeat(this.id);
331
+ this.detachParentSignal();
332
+ for (const agent of this.agentsList) {
333
+ agent.reducer.trimForRetention(DEFAULT_CHILD_STATE_LIMITS.finishedMaxChars);
334
+ }
335
+ this.markDirty("coarse");
336
+ this.deps.onFinished(this);
337
+ }
338
+ /** Store-internal: detaches the `parentSignal` abort listener (idempotent). */
339
+ detachParentSignal() {
340
+ if (this.parentSignal && this.parentAbortHandler) {
341
+ this.parentSignal.removeEventListener("abort", this.parentAbortHandler);
342
+ }
343
+ }
344
+ onFlush(listener) {
345
+ this.flushListeners.add(listener);
346
+ return () => this.flushListeners.delete(listener);
347
+ }
348
+ /** Store-internal: drops every agent's transcript (retention beyond `keepTranscriptRuns`). Idempotent:
349
+ * `handleRunFinished` calls this again on every old finished run each time any run finishes. */
350
+ dropTranscripts() {
351
+ if (this.transcriptsDroppedValue)
352
+ return;
353
+ this.transcriptsDroppedValue = true;
354
+ for (const agent of this.agentsList)
355
+ agent.reducer.dropTranscript();
356
+ }
357
+ /** Store-internal: whether `dropTranscripts()` has already run, so a late-completing agent is
358
+ * dropped rather than re-trimmed to the finished bound. */
359
+ get transcriptsDropped() {
360
+ return this.transcriptsDroppedValue;
361
+ }
362
+ /** Store-internal: called once per dirty run during a pump flush. */
363
+ bumpVersion(coarse) {
364
+ this.version++;
365
+ if (coarse)
366
+ this.coarseVersion++;
367
+ }
368
+ /** Store-internal: notifies this run's own flush listeners. */
369
+ emitFlush(coarse) {
370
+ for (const listener of this.flushListeners) {
371
+ try {
372
+ listener(this, coarse);
373
+ }
374
+ catch {
375
+ // A renderer's flush listener must not stall the pump's flush cycle.
376
+ }
377
+ }
378
+ }
379
+ checkBudget() {
380
+ if (this.budgetTotal === null || this.budgetExhausted)
381
+ return;
382
+ if (this.spentTokens() < this.budgetTotal)
383
+ return;
384
+ this.budgetExhausted = true;
385
+ for (const agent of this.agentsList)
386
+ agent.cancel("budget");
387
+ this.appendLog(`budget of ${this.budgetTotal} tokens reached; remaining agents are skipped`, "warning");
388
+ }
389
+ }
390
+ export class PolyphaseStore {
391
+ pump;
392
+ retainRuns;
393
+ keepTranscriptRuns;
394
+ now;
395
+ runsById = new Map();
396
+ listeners = new Set();
397
+ seqCounter = 0;
398
+ constructor(options) {
399
+ this.pump = options.pump;
400
+ this.retainRuns = options.retainRuns;
401
+ this.keepTranscriptRuns = options.keepTranscriptRuns ?? 5;
402
+ this.now = options.now ?? Date.now;
403
+ this.pump.setFlushHandler((dirty) => this.handleFlush(dirty));
404
+ }
405
+ createRun(init) {
406
+ const run = new PolyphaseRun(init, {
407
+ pump: this.pump,
408
+ now: this.now,
409
+ nextSeq: () => this.nextSeq(),
410
+ onFinished: (finished) => this.handleRunFinished(finished),
411
+ });
412
+ this.runsById.set(run.id, run);
413
+ this.pump.startHeartbeat(run.id);
414
+ return run;
415
+ }
416
+ getRun(id) {
417
+ return this.runsById.get(id);
418
+ }
419
+ /** Running runs newest-first, then finished runs newest-first. */
420
+ runs() {
421
+ const all = [...this.runsById.values()];
422
+ const running = all
423
+ .filter((run) => run.status === "running")
424
+ .sort((a, b) => b.startedAt - a.startedAt || b.createSeq - a.createSeq);
425
+ const finished = all.filter((run) => run.status !== "running").sort(finishedNewestFirst);
426
+ return [...running, ...finished];
427
+ }
428
+ /** Newest running run with origin "tool" and kind "subagent" | "workflow". */
429
+ focusRunId() {
430
+ let focus;
431
+ for (const run of this.runsById.values()) {
432
+ if (run.status !== "running" || run.origin !== "tool")
433
+ continue;
434
+ if (run.kind !== "subagent" && run.kind !== "workflow")
435
+ continue;
436
+ if (!focus ||
437
+ run.startedAt > focus.startedAt ||
438
+ (run.startedAt === focus.startedAt && run.createSeq > focus.createSeq)) {
439
+ focus = run;
440
+ }
441
+ }
442
+ return focus?.id;
443
+ }
444
+ nextSeq() {
445
+ return this.seqCounter++;
446
+ }
447
+ totals() {
448
+ const totals = {
449
+ runs: 0,
450
+ running: 0,
451
+ queued: 0,
452
+ active: 0,
453
+ done: 0,
454
+ failed: 0,
455
+ cancelled: 0,
456
+ tokens: 0,
457
+ cost: 0,
458
+ };
459
+ for (const run of this.runsById.values()) {
460
+ totals.runs++;
461
+ switch (run.status) {
462
+ case "running":
463
+ totals.running++;
464
+ break;
465
+ case "done":
466
+ totals.done++;
467
+ break;
468
+ case "failed":
469
+ totals.failed++;
470
+ break;
471
+ case "cancelled":
472
+ totals.cancelled++;
473
+ break;
474
+ }
475
+ totals.tokens += run.spentTokens();
476
+ for (const agent of run.agents) {
477
+ if (agent.status === "queued")
478
+ totals.queued++;
479
+ if (agent.status === "starting" || agent.status === "running")
480
+ totals.active++;
481
+ totals.cost += agent.state.usage?.cost.total ?? 0;
482
+ totals.cost += agent.state.liveUsage?.cost.total ?? 0;
483
+ }
484
+ }
485
+ return totals;
486
+ }
487
+ subscribe(listener) {
488
+ this.listeners.add(listener);
489
+ return () => this.listeners.delete(listener);
490
+ }
491
+ cancelAgent(runId, index, reason = "user") {
492
+ const run = this.runsById.get(runId);
493
+ const agent = run?.agents[index];
494
+ if (!run || !agent)
495
+ return false;
496
+ const cancelled = agent.cancel(reason);
497
+ if (cancelled)
498
+ run.markDirty("coarse");
499
+ return cancelled;
500
+ }
501
+ cancelRun(runId, reason = "user") {
502
+ const run = this.runsById.get(runId);
503
+ if (!run)
504
+ return false;
505
+ run.cancel(reason);
506
+ return true;
507
+ }
508
+ dispose() {
509
+ for (const run of this.runsById.values()) {
510
+ run.cancel("shutdown");
511
+ run.detachParentSignal();
512
+ }
513
+ this.pump.dispose();
514
+ this.notify({ type: "disposed" });
515
+ this.listeners.clear();
516
+ }
517
+ handleFlush(dirty) {
518
+ const runIds = [];
519
+ let anyCoarse = false;
520
+ for (const [runId, coarse] of dirty) {
521
+ const run = this.runsById.get(runId);
522
+ if (!run)
523
+ continue;
524
+ run.bumpVersion(coarse);
525
+ run.emitFlush(coarse);
526
+ runIds.push(runId);
527
+ if (coarse)
528
+ anyCoarse = true;
529
+ }
530
+ if (runIds.length > 0)
531
+ this.notify({ type: "runs", runIds, coarse: anyCoarse });
532
+ }
533
+ handleRunFinished(_run) {
534
+ const finished = [...this.runsById.values()].filter((run) => run.status !== "running").sort(finishedNewestFirst);
535
+ for (let i = this.keepTranscriptRuns; i < finished.length; i++) {
536
+ finished[i]?.dropTranscripts();
537
+ }
538
+ while (finished.length > this.retainRuns) {
539
+ const oldest = finished.pop();
540
+ if (!oldest)
541
+ break;
542
+ oldest.detachParentSignal();
543
+ this.runsById.delete(oldest.id);
544
+ this.pump.stopHeartbeat(oldest.id);
545
+ }
546
+ }
547
+ notify(change) {
548
+ for (const listener of this.listeners) {
549
+ try {
550
+ listener(change);
551
+ }
552
+ catch {
553
+ // A store subscriber (dock/inspector rendering) must not stall the flush cycle.
554
+ }
555
+ }
556
+ }
557
+ }
558
+ //# sourceMappingURL=store.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"store.js","sourceRoot":"","sources":["../../../src/core/polyphase/store.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAEH,OAAO,EAAE,cAAc,EAAE,iBAAiB,EAAE,MAAM,mBAAmB,CAAC;AACtE,OAAO,EAON,0BAA0B,GAU1B,MAAM,YAAY,CAAC;AAwBpB,MAAM,iBAAiB,GAA2B,CAAC,MAAM,EAAE,QAAQ,EAAE,WAAW,EAAE,SAAS,CAAC,CAAC;AAE7F;;;;;GAKG;AACH,MAAM,UAAU,GAAG,GAAG,CAAC;AAEvB,6FAA6F;AAC7F,SAAS,mBAAmB,CAAC,CAAe,EAAE,CAAe;IAC5D,OAAO,CAAC,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,SAAS,CAAC,GAAG,CAAC,CAAC,CAAC,OAAO,IAAI,CAAC,CAAC,SAAS,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,SAAS,IAAI,CAAC,CAAC,CAAC;AAC3G,CAAC;AAED,SAAS,UAAU,CAAC,MAAmB;IACtC,OAAO,iBAAiB,CAAC,QAAQ,CAAC,MAAM,CAAC,CAAC;AAC3C,CAAC;AAED,yFAAyF;AACzF,MAAM,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iBAAiB,CAAC,IAAkB;QAC3C,MAAM,QAAQ,GAAG,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,GAAG,EAAE,EAAE,CAAC,GAAG,CAAC,MAAM,KAAK,SAAS,CAAC,CAAC,IAAI,CAAC,mBAAmB,CAAC,CAAC;QACjH,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAAC,GAAG,QAAQ,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE,CAAC;YAChE,QAAQ,CAAC,CAAC,CAAC,EAAE,eAAe,EAAE,CAAC;QAChC,CAAC;QACD,OAAO,QAAQ,CAAC,MAAM,GAAG,IAAI,CAAC,UAAU,EAAE,CAAC;YAC1C,MAAM,MAAM,GAAG,QAAQ,CAAC,GAAG,EAAE,CAAC;YAC9B,IAAI,CAAC,MAAM;gBAAE,MAAM;YACnB,MAAM,CAAC,kBAAkB,EAAE,CAAC;YAC5B,IAAI,CAAC,QAAQ,CAAC,MAAM,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;YAChC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC;QACpC,CAAC;IACF,CAAC;IAEO,MAAM,CAAC,MAAmB;QACjC,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,SAAS,EAAE,CAAC;YACvC,IAAI,CAAC;gBACJ,QAAQ,CAAC,MAAM,CAAC,CAAC;YAClB,CAAC;YAAC,MAAM,CAAC;gBACR,gFAAgF;YACjF,CAAC;QACF,CAAC;IACF,CAAC;CACD","sourcesContent":["/**\n * Session-scoped live state for polyphase runs: `LiveAgent` wraps a child's `ChildEventReducer`\n * with lifecycle/cancellation, `PolyphaseRun` groups agents into one subagent/workflow run, and\n * `PolyphaseStore` owns every run plus the pump flush cycle and retention.\n */\n\nimport { billableTokens, ChildEventReducer } from \"./child-events.ts\";\nimport {\n\ttype AgentModelInfo,\n\ttype AgentRunContext,\n\ttype AgentStatus,\n\ttype AgentView,\n\ttype CancelReason,\n\ttype ChildAgentState,\n\tDEFAULT_CHILD_STATE_LIMITS,\n\ttype LogLine,\n\ttype PhaseInfo,\n\ttype RunKind,\n\ttype RunOrigin,\n\ttype RunResult,\n\ttype RunStatus,\n\ttype RunView,\n\ttype SubagentMode,\n\ttype WorkflowRunInfo,\n} from \"./types.ts\";\nimport type { UpdatePump } from \"./update-pump.ts\";\n\nexport interface RunInit {\n\tid: string;\n\tkind: RunKind;\n\torigin: RunOrigin;\n\ttitle: string;\n\tmode?: SubagentMode;\n\tworkflow?: WorkflowRunInfo;\n\tphases?: readonly { title: string; detail?: string; model?: string }[];\n\tbudgetTokens: number | null;\n\tparentSignal?: AbortSignal;\n}\n\nexport interface AgentInit {\n\tlabel: string;\n\tagentType: string;\n\ttask: string;\n\tphase?: number;\n\tstep?: number;\n\tmodel: AgentModelInfo;\n}\n\nconst TERMINAL_STATUSES: readonly AgentStatus[] = [\"done\", \"failed\", \"cancelled\", \"skipped\"];\n\n/**\n * Meta caps declared phases at 20 (`meta.ts`); this caps the dynamic ones a script can add by\n * calling `phase()` with a new title each time. Without a cap, every new title grows `phasesList`\n * forever, so each later `phase()` call's `findIndex` scan gets more expensive and the run keeps\n * broadcasting a coarse update for each one.\n */\nconst MAX_PHASES = 100;\n\n/** Finished runs newest-first, by `endedAt` then the store-assigned `finishSeq` tiebreak. */\nfunction finishedNewestFirst(a: PolyphaseRun, b: PolyphaseRun): number {\n\treturn (b.endedAt ?? b.startedAt) - (a.endedAt ?? a.startedAt) || (b.finishSeq ?? 0) - (a.finishSeq ?? 0);\n}\n\nfunction isTerminal(status: AgentStatus): boolean {\n\treturn TERMINAL_STATUSES.includes(status);\n}\n\n/** Live state of one child agent, wired into its owning run's dirty/cancel machinery. */\nexport class LiveAgent implements AgentView {\n\treadonly key: string;\n\treadonly index: number;\n\treadonly label: string;\n\treadonly agentType: string;\n\treadonly task: string;\n\treadonly phase?: number;\n\treadonly step?: number;\n\treadonly createdAt: number;\n\treadonly reducer: ChildEventReducer;\n\t/** `AbortSignal.any([run.signal, own controller])`. */\n\treadonly signal: AbortSignal;\n\n\tprivate readonly run: PolyphaseRun;\n\tprivate readonly controller = new AbortController();\n\tprivate _cancelReason: CancelReason | undefined;\n\tprivate _result: RunResult | undefined;\n\tprivate _skipped = false;\n\n\tconstructor(run: PolyphaseRun, index: number, init: AgentInit, now: () => number) {\n\t\tthis.run = run;\n\t\tthis.index = index;\n\t\tthis.key = `${run.id}#${index}`;\n\t\tthis.label = init.label;\n\t\tthis.agentType = init.agentType;\n\t\tthis.task = init.task;\n\t\tthis.phase = init.phase;\n\t\tthis.step = init.step;\n\t\tthis.createdAt = now();\n\t\tthis.reducer = new ChildEventReducer({ model: init.model, now });\n\t\tthis.signal = AbortSignal.any([run.signal, this.controller.signal]);\n\t}\n\n\tget state(): Readonly<ChildAgentState> {\n\t\treturn this.reducer.state;\n\t}\n\n\tget result(): Readonly<RunResult> | undefined {\n\t\treturn this._result;\n\t}\n\n\tget cancelReason(): CancelReason | undefined {\n\t\treturn this._cancelReason;\n\t}\n\n\tget status(): AgentStatus {\n\t\tif (this._result) {\n\t\t\tif (this._result.cancelled) return \"cancelled\";\n\t\t\treturn this._result.exitCode === 0 ? \"done\" : \"failed\";\n\t\t}\n\t\tif (this._skipped) return \"skipped\";\n\t\tswitch (this.reducer.state.lifecycle) {\n\t\t\tcase \"running\":\n\t\t\tcase \"settled\":\n\t\t\tcase \"exited\":\n\t\t\t\treturn \"running\";\n\t\t\tcase \"spawning\":\n\t\t\t\treturn \"starting\";\n\t\t\tcase \"queued\":\n\t\t\t\treturn \"queued\";\n\t\t\tdefault:\n\t\t\t\treturn \"pending\";\n\t\t}\n\t}\n\n\t/** Sets `cancelReason` once and aborts this agent's own controller. False when already finished. */\n\tcancel(reason: CancelReason): boolean {\n\t\tif (isTerminal(this.status)) return false;\n\t\tif (this._cancelReason === undefined) this._cancelReason = reason;\n\t\tif (!this.controller.signal.aborted) this.controller.abort();\n\t\treturn true;\n\t}\n\n\tcreateRunContext(\n\t\tbase: Omit<AgentRunContext, \"reducer\" | \"onQueued\" | \"onStart\" | \"onChange\" | \"onFinish\"> = {},\n\t): AgentRunContext {\n\t\treturn {\n\t\t\t...base,\n\t\t\treducer: this.reducer,\n\t\t\tonQueued: () => {\n\t\t\t\tthis.reducer.markQueued();\n\t\t\t\tthis.run.markDirty(\"coarse\");\n\t\t\t},\n\t\t\tonStart: () => {\n\t\t\t\tthis.run.markDirty(\"coarse\");\n\t\t\t},\n\t\t\tonChange: (change) => {\n\t\t\t\tthis.run.markDirty(change);\n\t\t\t},\n\t\t\tonFinish: (result) => {\n\t\t\t\tthis.complete(result);\n\t\t\t},\n\t\t};\n\t}\n\n\tcomplete(result: RunResult): void {\n\t\tif (this._result !== undefined || this._skipped) return;\n\t\tthis._result = result;\n\t\tif (this.run.status !== \"running\") {\n\t\t\t// The run already ran retention when it finished. An agent that settles afterwards\n\t\t\t// (e.g. still being SIGTERM'd) would otherwise keep growing under the running-time\n\t\t\t// transcript cap until the next unrelated run finishes and sweeps it.\n\t\t\tif (this.run.transcriptsDropped) this.reducer.dropTranscript();\n\t\t\telse this.reducer.trimForRetention(DEFAULT_CHILD_STATE_LIMITS.finishedMaxChars);\n\t\t}\n\t\tthis.run.markDirty(\"coarse\");\n\t}\n\n\tmarkSkipped(): void {\n\t\tif (this._result !== undefined || this._skipped) return;\n\t\tthis._skipped = true;\n\t\tthis.run.markDirty(\"coarse\");\n\t}\n}\n\nexport type StoreChange = { type: \"runs\"; runIds: readonly string[]; coarse: boolean } | { type: \"disposed\" };\n\nexport interface StoreTotals {\n\truns: number;\n\trunning: number;\n\tqueued: number;\n\tactive: number;\n\tdone: number;\n\tfailed: number;\n\tcancelled: number;\n\ttokens: number;\n\tcost: number;\n}\n\ninterface RunDeps {\n\tpump: UpdatePump;\n\tnow: () => number;\n\tnextSeq: () => number;\n\tonFinished: (run: PolyphaseRun) => void;\n}\n\n/** One subagent/duet/workflow run: its agents, phases, log and budget. */\nexport class PolyphaseRun implements RunView {\n\treadonly id: string;\n\treadonly kind: RunKind;\n\treadonly origin: RunOrigin;\n\treadonly mode?: SubagentMode;\n\treadonly title: string;\n\treadonly workflow?: Readonly<WorkflowRunInfo>;\n\treadonly startedAt: number;\n\t/** Monotonic store-assigned sequence, for tie-breaking same-timestamp ordering. */\n\treadonly createSeq: number;\n\t/** Aborted by `cancel()` and by `parentSignal` (via `cancel(\"parent\")`). */\n\treadonly signal: AbortSignal;\n\tversion = 0;\n\tcoarseVersion = 0;\n\n\tprivate readonly deps: RunDeps;\n\tprivate readonly controller = new AbortController();\n\tprivate readonly agentsList: LiveAgent[] = [];\n\tprivate readonly phasesList: PhaseInfo[];\n\tprivate readonly logList: LogLine[] = [];\n\tprivate readonly flushListeners = new Set<(run: PolyphaseRun, coarse: boolean) => void>();\n\tprivate readonly budgetTotal: number | null;\n\tprivate readonly parentSignal: AbortSignal | undefined;\n\tprivate readonly parentAbortHandler: (() => void) | undefined;\n\n\tprivate currentPhaseValue: number | undefined;\n\tprivate statusValue: RunStatus = \"running\";\n\tprivate endedAtValue: number | undefined;\n\tprivate finishSeqValue: number | undefined;\n\tprivate resultPreviewValue: string | undefined;\n\tprivate errorValue: string | undefined;\n\tprivate logDroppedValue = 0;\n\tprivate budgetExhausted = false;\n\tprivate warnedDynamicPhase = false;\n\tprivate warnedPhaseCap = false;\n\tprivate cancelReasonValue: CancelReason | undefined;\n\tprivate transcriptsDroppedValue = false;\n\n\tconstructor(init: RunInit, deps: RunDeps) {\n\t\tthis.deps = deps;\n\t\tthis.id = init.id;\n\t\tthis.kind = init.kind;\n\t\tthis.origin = init.origin;\n\t\tthis.mode = init.mode;\n\t\tthis.title = init.title;\n\t\tthis.workflow = init.workflow;\n\t\tthis.phasesList = (init.phases ?? []).map((phase) => ({ ...phase, dynamic: false }));\n\t\tthis.budgetTotal = init.budgetTokens;\n\t\tthis.startedAt = deps.now();\n\t\tthis.createSeq = deps.nextSeq();\n\t\tthis.signal = this.controller.signal;\n\n\t\tif (init.parentSignal) {\n\t\t\tthis.parentSignal = init.parentSignal;\n\t\t\tif (init.parentSignal.aborted) {\n\t\t\t\tthis.cancel(\"parent\");\n\t\t\t} else {\n\t\t\t\tthis.parentAbortHandler = () => this.cancel(\"parent\");\n\t\t\t\tinit.parentSignal.addEventListener(\"abort\", this.parentAbortHandler, { once: true });\n\t\t\t}\n\t\t}\n\t}\n\n\tget phases(): readonly PhaseInfo[] {\n\t\treturn this.phasesList;\n\t}\n\n\tget currentPhase(): number | undefined {\n\t\treturn this.currentPhaseValue;\n\t}\n\n\tget status(): RunStatus {\n\t\treturn this.statusValue;\n\t}\n\n\tget endedAt(): number | undefined {\n\t\treturn this.endedAtValue;\n\t}\n\n\t/** Monotonic store-assigned sequence set in `finish()`, for tie-breaking same-timestamp ordering. */\n\tget finishSeq(): number | undefined {\n\t\treturn this.finishSeqValue;\n\t}\n\n\tget agents(): readonly LiveAgent[] {\n\t\treturn this.agentsList;\n\t}\n\n\tget log(): readonly LogLine[] {\n\t\treturn this.logList;\n\t}\n\n\tget logDropped(): number {\n\t\treturn this.logDroppedValue;\n\t}\n\n\tget budget(): Readonly<{ totalTokens: number | null; spentTokens: number; exhausted: boolean }> {\n\t\treturn { totalTokens: this.budgetTotal, spentTokens: this.spentTokens(), exhausted: this.budgetExhausted };\n\t}\n\n\tget resultPreview(): string | undefined {\n\t\treturn this.resultPreviewValue;\n\t}\n\n\tget error(): string | undefined {\n\t\treturn this.errorValue;\n\t}\n\n\taddAgent(init: AgentInit): LiveAgent {\n\t\tconst agent = new LiveAgent(this, this.agentsList.length, init, this.deps.now);\n\t\tthis.agentsList.push(agent);\n\t\t// The agent's own signal is already aborted (AbortSignal.any includes this.signal), but it\n\t\t// carries no cancelReason yet: inherit the run's, so it matches its siblings.\n\t\tif (this.signal.aborted && this.cancelReasonValue !== undefined) agent.cancel(this.cancelReasonValue);\n\t\tthis.markDirty(\"coarse\");\n\t\treturn agent;\n\t}\n\n\t/** Index of an existing phase with this title, or a new dynamic phase (one-time warning). `undefined` title returns `currentPhase`. */\n\tresolvePhase(title: string | undefined): number | undefined {\n\t\tif (title === undefined) return this.currentPhaseValue;\n\t\treturn this.phaseIndexFor(title);\n\t}\n\n\tenterPhase(title: string): number {\n\t\tconst index = this.phaseIndexFor(title);\n\t\tthis.currentPhaseValue = index;\n\t\tthis.markDirty(\"coarse\");\n\t\treturn index;\n\t}\n\n\tprivate phaseIndexFor(title: string): number {\n\t\tconst existing = this.phasesList.findIndex((phase) => phase.title === title);\n\t\tif (existing !== -1) return existing;\n\t\tif (this.phasesList.length >= MAX_PHASES) {\n\t\t\tif (!this.warnedPhaseCap) {\n\t\t\t\tthis.warnedPhaseCap = true;\n\t\t\t\tthis.appendLog(`workflow reached the ${MAX_PHASES}-phase cap; new phase titles are ignored`, \"warning\");\n\t\t\t}\n\t\t\tthrow new Error(`phase cap reached: a run may have at most ${MAX_PHASES} phases`);\n\t\t}\n\t\tthis.phasesList.push({ title, dynamic: true });\n\t\tif (!this.warnedDynamicPhase) {\n\t\t\tthis.warnedDynamicPhase = true;\n\t\t\tthis.appendLog(\"workflow entered a phase not declared in meta.phases\", \"warning\");\n\t\t}\n\t\treturn this.phasesList.length - 1;\n\t}\n\n\tappendLog(text: string, level: \"info\" | \"warning\" = \"info\"): void {\n\t\tconst capped = text.length > 2000 ? text.slice(0, 2000) : text;\n\t\tthis.logList.push({ at: this.deps.now(), level, text: capped, phase: this.currentPhaseValue });\n\t\tif (this.logList.length > 200) {\n\t\t\tthis.logList.shift();\n\t\t\tthis.logDroppedValue++;\n\t\t}\n\t\tthis.markDirty(\"coarse\");\n\t}\n\n\tsetResultPreview(text: string): void {\n\t\tthis.resultPreviewValue = text;\n\t\tthis.markDirty(\"coarse\");\n\t}\n\n\tmarkDirty(change: \"fine\" | \"coarse\"): void {\n\t\tthis.deps.pump.schedule(this.id, change);\n\t\tthis.checkBudget();\n\t}\n\n\tspentTokens(): number {\n\t\tlet total = 0;\n\t\tfor (const agent of this.agentsList) {\n\t\t\ttotal += billableTokens(agent.state.usage) + billableTokens(agent.state.liveUsage);\n\t\t}\n\t\treturn total;\n\t}\n\n\tcounts(): Record<AgentStatus, number> {\n\t\tconst result: Record<AgentStatus, number> = {\n\t\t\tpending: 0,\n\t\t\tqueued: 0,\n\t\t\tstarting: 0,\n\t\t\trunning: 0,\n\t\t\tdone: 0,\n\t\t\tfailed: 0,\n\t\t\tcancelled: 0,\n\t\t\tskipped: 0,\n\t\t};\n\t\tfor (const agent of this.agentsList) result[agent.status]++;\n\t\treturn result;\n\t}\n\n\tcancel(reason: CancelReason): void {\n\t\tif (this.cancelReasonValue === undefined) this.cancelReasonValue = reason;\n\t\tfor (const agent of this.agentsList) agent.cancel(reason);\n\t\tif (!this.controller.signal.aborted) this.controller.abort();\n\t\tthis.markDirty(\"coarse\");\n\t}\n\n\t/** Pending agents become skipped; the heartbeat stops; retention runs. */\n\tfinish(status: RunStatus, error?: string): void {\n\t\tif (this.statusValue !== \"running\") return;\n\t\tfor (const agent of this.agentsList) {\n\t\t\tif (agent.status === \"pending\") agent.markSkipped();\n\t\t}\n\t\tthis.statusValue = status;\n\t\tthis.endedAtValue = this.deps.now();\n\t\tthis.finishSeqValue = this.deps.nextSeq();\n\t\tif (error !== undefined) this.errorValue = error;\n\t\tthis.deps.pump.stopHeartbeat(this.id);\n\t\tthis.detachParentSignal();\n\t\tfor (const agent of this.agentsList) {\n\t\t\tagent.reducer.trimForRetention(DEFAULT_CHILD_STATE_LIMITS.finishedMaxChars);\n\t\t}\n\t\tthis.markDirty(\"coarse\");\n\t\tthis.deps.onFinished(this);\n\t}\n\n\t/** Store-internal: detaches the `parentSignal` abort listener (idempotent). */\n\tdetachParentSignal(): void {\n\t\tif (this.parentSignal && this.parentAbortHandler) {\n\t\t\tthis.parentSignal.removeEventListener(\"abort\", this.parentAbortHandler);\n\t\t}\n\t}\n\n\tonFlush(listener: (run: PolyphaseRun, coarse: boolean) => void): () => void {\n\t\tthis.flushListeners.add(listener);\n\t\treturn () => this.flushListeners.delete(listener);\n\t}\n\n\t/** Store-internal: drops every agent's transcript (retention beyond `keepTranscriptRuns`). Idempotent:\n\t * `handleRunFinished` calls this again on every old finished run each time any run finishes. */\n\tdropTranscripts(): void {\n\t\tif (this.transcriptsDroppedValue) return;\n\t\tthis.transcriptsDroppedValue = true;\n\t\tfor (const agent of this.agentsList) agent.reducer.dropTranscript();\n\t}\n\n\t/** Store-internal: whether `dropTranscripts()` has already run, so a late-completing agent is\n\t * dropped rather than re-trimmed to the finished bound. */\n\tget transcriptsDropped(): boolean {\n\t\treturn this.transcriptsDroppedValue;\n\t}\n\n\t/** Store-internal: called once per dirty run during a pump flush. */\n\tbumpVersion(coarse: boolean): void {\n\t\tthis.version++;\n\t\tif (coarse) this.coarseVersion++;\n\t}\n\n\t/** Store-internal: notifies this run's own flush listeners. */\n\temitFlush(coarse: boolean): void {\n\t\tfor (const listener of this.flushListeners) {\n\t\t\ttry {\n\t\t\t\tlistener(this, coarse);\n\t\t\t} catch {\n\t\t\t\t// A renderer's flush listener must not stall the pump's flush cycle.\n\t\t\t}\n\t\t}\n\t}\n\n\tprivate checkBudget(): void {\n\t\tif (this.budgetTotal === null || this.budgetExhausted) return;\n\t\tif (this.spentTokens() < this.budgetTotal) return;\n\t\tthis.budgetExhausted = true;\n\t\tfor (const agent of this.agentsList) agent.cancel(\"budget\");\n\t\tthis.appendLog(`budget of ${this.budgetTotal} tokens reached; remaining agents are skipped`, \"warning\");\n\t}\n}\n\nexport class PolyphaseStore {\n\tprivate readonly pump: UpdatePump;\n\tprivate readonly retainRuns: number;\n\tprivate readonly keepTranscriptRuns: number;\n\tprivate readonly now: () => number;\n\tprivate readonly runsById = new Map<string, PolyphaseRun>();\n\tprivate readonly listeners = new Set<(change: StoreChange) => void>();\n\tprivate seqCounter = 0;\n\n\tconstructor(options: { pump: UpdatePump; retainRuns: number; keepTranscriptRuns?: number; now?: () => number }) {\n\t\tthis.pump = options.pump;\n\t\tthis.retainRuns = options.retainRuns;\n\t\tthis.keepTranscriptRuns = options.keepTranscriptRuns ?? 5;\n\t\tthis.now = options.now ?? Date.now;\n\t\tthis.pump.setFlushHandler((dirty) => this.handleFlush(dirty));\n\t}\n\n\tcreateRun(init: RunInit): PolyphaseRun {\n\t\tconst run = new PolyphaseRun(init, {\n\t\t\tpump: this.pump,\n\t\t\tnow: this.now,\n\t\t\tnextSeq: () => this.nextSeq(),\n\t\t\tonFinished: (finished) => this.handleRunFinished(finished),\n\t\t});\n\t\tthis.runsById.set(run.id, run);\n\t\tthis.pump.startHeartbeat(run.id);\n\t\treturn run;\n\t}\n\n\tgetRun(id: string): PolyphaseRun | undefined {\n\t\treturn this.runsById.get(id);\n\t}\n\n\t/** Running runs newest-first, then finished runs newest-first. */\n\truns(): readonly PolyphaseRun[] {\n\t\tconst all = [...this.runsById.values()];\n\t\tconst running = all\n\t\t\t.filter((run) => run.status === \"running\")\n\t\t\t.sort((a, b) => b.startedAt - a.startedAt || b.createSeq - a.createSeq);\n\t\tconst finished = all.filter((run) => run.status !== \"running\").sort(finishedNewestFirst);\n\t\treturn [...running, ...finished];\n\t}\n\n\t/** Newest running run with origin \"tool\" and kind \"subagent\" | \"workflow\". */\n\tfocusRunId(): string | undefined {\n\t\tlet focus: PolyphaseRun | undefined;\n\t\tfor (const run of this.runsById.values()) {\n\t\t\tif (run.status !== \"running\" || run.origin !== \"tool\") continue;\n\t\t\tif (run.kind !== \"subagent\" && run.kind !== \"workflow\") continue;\n\t\t\tif (\n\t\t\t\t!focus ||\n\t\t\t\trun.startedAt > focus.startedAt ||\n\t\t\t\t(run.startedAt === focus.startedAt && run.createSeq > focus.createSeq)\n\t\t\t) {\n\t\t\t\tfocus = run;\n\t\t\t}\n\t\t}\n\t\treturn focus?.id;\n\t}\n\n\tprivate nextSeq(): number {\n\t\treturn this.seqCounter++;\n\t}\n\n\ttotals(): StoreTotals {\n\t\tconst totals: StoreTotals = {\n\t\t\truns: 0,\n\t\t\trunning: 0,\n\t\t\tqueued: 0,\n\t\t\tactive: 0,\n\t\t\tdone: 0,\n\t\t\tfailed: 0,\n\t\t\tcancelled: 0,\n\t\t\ttokens: 0,\n\t\t\tcost: 0,\n\t\t};\n\t\tfor (const run of this.runsById.values()) {\n\t\t\ttotals.runs++;\n\t\t\tswitch (run.status) {\n\t\t\t\tcase \"running\":\n\t\t\t\t\ttotals.running++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"done\":\n\t\t\t\t\ttotals.done++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"failed\":\n\t\t\t\t\ttotals.failed++;\n\t\t\t\t\tbreak;\n\t\t\t\tcase \"cancelled\":\n\t\t\t\t\ttotals.cancelled++;\n\t\t\t\t\tbreak;\n\t\t\t}\n\t\t\ttotals.tokens += run.spentTokens();\n\t\t\tfor (const agent of run.agents) {\n\t\t\t\tif (agent.status === \"queued\") totals.queued++;\n\t\t\t\tif (agent.status === \"starting\" || agent.status === \"running\") totals.active++;\n\t\t\t\ttotals.cost += agent.state.usage?.cost.total ?? 0;\n\t\t\t\ttotals.cost += agent.state.liveUsage?.cost.total ?? 0;\n\t\t\t}\n\t\t}\n\t\treturn totals;\n\t}\n\n\tsubscribe(listener: (change: StoreChange) => void): () => void {\n\t\tthis.listeners.add(listener);\n\t\treturn () => this.listeners.delete(listener);\n\t}\n\n\tcancelAgent(runId: string, index: number, reason: CancelReason = \"user\"): boolean {\n\t\tconst run = this.runsById.get(runId);\n\t\tconst agent = run?.agents[index];\n\t\tif (!run || !agent) return false;\n\t\tconst cancelled = agent.cancel(reason);\n\t\tif (cancelled) run.markDirty(\"coarse\");\n\t\treturn cancelled;\n\t}\n\n\tcancelRun(runId: string, reason: CancelReason = \"user\"): boolean {\n\t\tconst run = this.runsById.get(runId);\n\t\tif (!run) return false;\n\t\trun.cancel(reason);\n\t\treturn true;\n\t}\n\n\tdispose(): void {\n\t\tfor (const run of this.runsById.values()) {\n\t\t\trun.cancel(\"shutdown\");\n\t\t\trun.detachParentSignal();\n\t\t}\n\t\tthis.pump.dispose();\n\t\tthis.notify({ type: \"disposed\" });\n\t\tthis.listeners.clear();\n\t}\n\n\tprivate handleFlush(dirty: ReadonlyMap<string, boolean>): void {\n\t\tconst runIds: string[] = [];\n\t\tlet anyCoarse = false;\n\t\tfor (const [runId, coarse] of dirty) {\n\t\t\tconst run = this.runsById.get(runId);\n\t\t\tif (!run) continue;\n\t\t\trun.bumpVersion(coarse);\n\t\t\trun.emitFlush(coarse);\n\t\t\trunIds.push(runId);\n\t\t\tif (coarse) anyCoarse = true;\n\t\t}\n\t\tif (runIds.length > 0) this.notify({ type: \"runs\", runIds, coarse: anyCoarse });\n\t}\n\n\tprivate handleRunFinished(_run: PolyphaseRun): void {\n\t\tconst finished = [...this.runsById.values()].filter((run) => run.status !== \"running\").sort(finishedNewestFirst);\n\t\tfor (let i = this.keepTranscriptRuns; i < finished.length; i++) {\n\t\t\tfinished[i]?.dropTranscripts();\n\t\t}\n\t\twhile (finished.length > this.retainRuns) {\n\t\t\tconst oldest = finished.pop();\n\t\t\tif (!oldest) break;\n\t\t\toldest.detachParentSignal();\n\t\t\tthis.runsById.delete(oldest.id);\n\t\t\tthis.pump.stopHeartbeat(oldest.id);\n\t\t}\n\t}\n\n\tprivate notify(change: StoreChange): void {\n\t\tfor (const listener of this.listeners) {\n\t\t\ttry {\n\t\t\t\tlistener(change);\n\t\t\t} catch {\n\t\t\t\t// A store subscriber (dock/inspector rendering) must not stall the flush cycle.\n\t\t\t}\n\t\t}\n\t}\n}\n"]}