muonroi-cli 1.2.3 → 1.3.2

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 (3302) hide show
  1. package/README.md +77 -316
  2. package/dist/packages/agent-harness-core/src/driver.d.ts +77 -0
  3. package/dist/packages/agent-harness-core/src/driver.js +311 -0
  4. package/dist/packages/agent-harness-core/src/driver.js.map +1 -0
  5. package/dist/packages/agent-harness-core/src/event-filter.d.ts +34 -0
  6. package/dist/packages/agent-harness-core/src/event-filter.js +70 -0
  7. package/dist/packages/agent-harness-core/src/event-filter.js.map +1 -0
  8. package/dist/packages/agent-harness-core/src/event-redact.d.ts +24 -0
  9. package/dist/packages/agent-harness-core/src/event-redact.js +150 -0
  10. package/dist/packages/agent-harness-core/src/event-redact.js.map +1 -0
  11. package/dist/packages/agent-harness-core/src/idle.d.ts +18 -0
  12. package/dist/packages/agent-harness-core/src/idle.js +57 -0
  13. package/dist/packages/agent-harness-core/src/idle.js.map +1 -0
  14. package/dist/packages/agent-harness-core/src/index.d.ts +10 -0
  15. package/dist/packages/agent-harness-core/src/index.js +12 -0
  16. package/dist/packages/agent-harness-core/src/index.js.map +1 -0
  17. package/dist/packages/agent-harness-core/src/mcp-server.d.ts +89 -0
  18. package/dist/packages/agent-harness-core/src/mcp-server.js +427 -0
  19. package/dist/packages/agent-harness-core/src/mcp-server.js.map +1 -0
  20. package/dist/packages/agent-harness-core/src/mock-llm.d.ts +75 -0
  21. package/dist/packages/agent-harness-core/src/mock-llm.js +116 -0
  22. package/dist/packages/agent-harness-core/src/mock-llm.js.map +1 -0
  23. package/dist/packages/agent-harness-core/src/predicate.d.ts +34 -0
  24. package/dist/packages/agent-harness-core/src/predicate.js +46 -0
  25. package/dist/packages/agent-harness-core/src/predicate.js.map +1 -0
  26. package/dist/packages/agent-harness-core/src/protocol.d.ts +198 -0
  27. package/dist/packages/agent-harness-core/src/protocol.js +2 -0
  28. package/dist/packages/agent-harness-core/src/protocol.js.map +1 -0
  29. package/dist/packages/agent-harness-core/src/registry.d.ts +30 -0
  30. package/dist/packages/agent-harness-core/src/registry.js +86 -0
  31. package/dist/packages/agent-harness-core/src/registry.js.map +1 -0
  32. package/dist/packages/agent-harness-core/src/selector.d.ts +14 -0
  33. package/dist/packages/agent-harness-core/src/selector.js +199 -0
  34. package/dist/packages/agent-harness-core/src/selector.js.map +1 -0
  35. package/dist/packages/agent-harness-core/src/spec-helpers.d.ts +24 -0
  36. package/dist/packages/agent-harness-core/src/spec-helpers.js +61 -0
  37. package/dist/packages/agent-harness-core/src/spec-helpers.js.map +1 -0
  38. package/dist/packages/agent-harness-core/src/transports/sidechannel.d.ts +11 -0
  39. package/dist/packages/agent-harness-core/src/transports/sidechannel.js +34 -0
  40. package/dist/packages/agent-harness-core/src/transports/sidechannel.js.map +1 -0
  41. package/dist/packages/agent-harness-core/src/transports/ws.d.ts +150 -0
  42. package/dist/packages/agent-harness-core/src/transports/ws.js +222 -0
  43. package/dist/packages/agent-harness-core/src/transports/ws.js.map +1 -0
  44. package/dist/packages/agent-harness-opentui/src/agent-mode.d.ts +46 -0
  45. package/dist/packages/agent-harness-opentui/src/agent-mode.js +178 -0
  46. package/dist/packages/agent-harness-opentui/src/agent-mode.js.map +1 -0
  47. package/dist/packages/agent-harness-opentui/src/index.d.ts +5 -0
  48. package/dist/packages/agent-harness-opentui/src/index.js +6 -0
  49. package/dist/packages/agent-harness-opentui/src/index.js.map +1 -0
  50. package/dist/packages/agent-harness-opentui/src/input-bridge.d.ts +27 -0
  51. package/dist/packages/agent-harness-opentui/src/input-bridge.js +126 -0
  52. package/dist/packages/agent-harness-opentui/src/input-bridge.js.map +1 -0
  53. package/dist/packages/agent-harness-opentui/src/install.d.ts +65 -0
  54. package/dist/packages/agent-harness-opentui/src/install.js +62 -0
  55. package/dist/packages/agent-harness-opentui/src/install.js.map +1 -0
  56. package/dist/packages/agent-harness-opentui/src/reconciler-hook.d.ts +15 -0
  57. package/dist/packages/agent-harness-opentui/src/reconciler-hook.js +52 -0
  58. package/dist/packages/agent-harness-opentui/src/reconciler-hook.js.map +1 -0
  59. package/dist/packages/agent-harness-opentui/src/semantic.d.ts +12 -0
  60. package/dist/packages/agent-harness-opentui/src/semantic.js +58 -0
  61. package/dist/packages/agent-harness-opentui/src/semantic.js.map +1 -0
  62. package/dist/src/__test-stubs__/ee-server.js.map +1 -0
  63. package/dist/src/__test-stubs__/vitest-setup.js +34 -0
  64. package/dist/src/__test-stubs__/vitest-setup.js.map +1 -0
  65. package/dist/src/__tests__/council/bubble-layout.test.js +39 -0
  66. package/dist/src/__tests__/council/bubble-layout.test.js.map +1 -0
  67. package/dist/src/__tests__/council/code-block-truncate.test.js +45 -0
  68. package/dist/src/__tests__/council/code-block-truncate.test.js.map +1 -0
  69. package/dist/src/__tests__/council/role-palette.test.js +59 -0
  70. package/dist/src/__tests__/council/role-palette.test.js.map +1 -0
  71. package/dist/src/__tests__/first-run-wizard.test.js +9 -0
  72. package/dist/src/__tests__/first-run-wizard.test.js.map +1 -0
  73. package/dist/src/agent-harness/__tests__/cli-flags.spec.js +33 -0
  74. package/dist/src/agent-harness/__tests__/cli-flags.spec.js.map +1 -0
  75. package/dist/src/agent-harness/__tests__/driver.spec.js +141 -0
  76. package/dist/src/agent-harness/__tests__/driver.spec.js.map +1 -0
  77. package/dist/src/agent-harness/__tests__/idle.spec.js +84 -0
  78. package/dist/src/agent-harness/__tests__/idle.spec.js.map +1 -0
  79. package/dist/src/agent-harness/__tests__/mock-llm.spec.js +91 -0
  80. package/dist/src/agent-harness/__tests__/mock-llm.spec.js.map +1 -0
  81. package/dist/src/agent-harness/__tests__/mock-model.spec.d.ts +5 -0
  82. package/dist/src/agent-harness/__tests__/mock-model.spec.js +169 -0
  83. package/dist/src/agent-harness/__tests__/mock-model.spec.js.map +1 -0
  84. package/dist/src/agent-harness/__tests__/predicate.spec.js +27 -0
  85. package/dist/src/agent-harness/__tests__/predicate.spec.js.map +1 -0
  86. package/dist/src/agent-harness/__tests__/protocol.spec.js +56 -0
  87. package/dist/src/agent-harness/__tests__/protocol.spec.js.map +1 -0
  88. package/dist/src/agent-harness/__tests__/schema.spec.js +76 -0
  89. package/dist/src/agent-harness/__tests__/schema.spec.js.map +1 -0
  90. package/dist/src/agent-harness/__tests__/selector.spec.js +70 -0
  91. package/dist/src/agent-harness/__tests__/selector.spec.js.map +1 -0
  92. package/dist/src/agent-harness/__tests__/sidechannel.spec.js +29 -0
  93. package/dist/src/agent-harness/__tests__/sidechannel.spec.js.map +1 -0
  94. package/dist/src/agent-harness/__tests__/spec-helpers.spec.js +68 -0
  95. package/dist/src/agent-harness/__tests__/spec-helpers.spec.js.map +1 -0
  96. package/dist/src/agent-harness/index.d.ts +2 -0
  97. package/dist/src/agent-harness/index.js +20 -0
  98. package/dist/src/agent-harness/index.js.map +1 -0
  99. package/dist/src/agent-harness/mock-model.d.ts +149 -0
  100. package/dist/src/agent-harness/mock-model.js +291 -0
  101. package/dist/src/agent-harness/mock-model.js.map +1 -0
  102. package/dist/src/agent-harness/test-spawn.d.ts +42 -0
  103. package/dist/src/agent-harness/test-spawn.js +165 -0
  104. package/dist/src/agent-harness/test-spawn.js.map +1 -0
  105. package/dist/src/billing/index.js.map +1 -0
  106. package/dist/src/chat/__tests__/broadcast-bus.test.js +81 -0
  107. package/dist/src/chat/__tests__/broadcast-bus.test.js.map +1 -0
  108. package/dist/src/chat/__tests__/channel-manager.test.js +133 -0
  109. package/dist/src/chat/__tests__/channel-manager.test.js.map +1 -0
  110. package/dist/src/chat/__tests__/client.test.js +109 -0
  111. package/dist/src/chat/__tests__/client.test.js.map +1 -0
  112. package/dist/src/chat/__tests__/discord-integration.test.js +153 -0
  113. package/dist/src/chat/__tests__/discord-integration.test.js.map +1 -0
  114. package/dist/src/chat/__tests__/intent-prompt.test.js +80 -0
  115. package/dist/src/chat/__tests__/intent-prompt.test.js.map +1 -0
  116. package/dist/src/chat/__tests__/verdict-resolver.test.js +308 -0
  117. package/dist/src/chat/__tests__/verdict-resolver.test.js.map +1 -0
  118. package/dist/src/chat/broadcast-bus.d.ts +10 -0
  119. package/dist/src/chat/broadcast-bus.js +52 -0
  120. package/dist/src/chat/broadcast-bus.js.map +1 -0
  121. package/dist/src/chat/channel-manager.d.ts +16 -0
  122. package/dist/src/chat/channel-manager.js +121 -0
  123. package/dist/src/chat/channel-manager.js.map +1 -0
  124. package/dist/src/chat/chat-keychain.d.ts +26 -0
  125. package/dist/src/chat/chat-keychain.js +113 -0
  126. package/dist/src/chat/chat-keychain.js.map +1 -0
  127. package/dist/src/chat/factory.d.ts +3 -0
  128. package/dist/src/chat/factory.js +29 -0
  129. package/dist/src/chat/factory.js.map +1 -0
  130. package/dist/src/chat/intent-prompt.d.ts +17 -0
  131. package/dist/src/chat/intent-prompt.js +52 -0
  132. package/dist/src/chat/intent-prompt.js.map +1 -0
  133. package/dist/src/chat/providers/discord/client.d.ts +28 -0
  134. package/dist/src/chat/providers/discord/client.js +77 -0
  135. package/dist/src/chat/providers/discord/client.js.map +1 -0
  136. package/dist/src/chat/types.d.ts +51 -0
  137. package/dist/src/chat/types.js +8 -0
  138. package/dist/src/chat/types.js.map +1 -0
  139. package/dist/src/chat/verdict-constants.d.ts +13 -0
  140. package/dist/src/chat/verdict-constants.js +18 -0
  141. package/dist/src/chat/verdict-constants.js.map +1 -0
  142. package/dist/src/chat/verdict-resolver.d.ts +28 -0
  143. package/dist/src/chat/verdict-resolver.js +181 -0
  144. package/dist/src/chat/verdict-resolver.js.map +1 -0
  145. package/dist/src/cli/__tests__/bw-vault.test.js +87 -0
  146. package/dist/src/cli/__tests__/bw-vault.test.js.map +1 -0
  147. package/dist/src/cli/__tests__/keys-bundle.test.js +40 -0
  148. package/dist/src/cli/__tests__/keys-bundle.test.js.map +1 -0
  149. package/dist/src/cli/__tests__/share-cmd.test.js +175 -0
  150. package/dist/src/cli/__tests__/share-cmd.test.js.map +1 -0
  151. package/dist/src/cli/bw-vault.d.ts +55 -0
  152. package/dist/src/cli/bw-vault.js +133 -0
  153. package/dist/src/cli/bw-vault.js.map +1 -0
  154. package/dist/src/cli/config/__tests__/model-picker.test.js +56 -0
  155. package/dist/src/cli/config/__tests__/model-picker.test.js.map +1 -0
  156. package/dist/src/cli/config/__tests__/provider-fetch.test.js +38 -0
  157. package/dist/src/cli/config/__tests__/provider-fetch.test.js.map +1 -0
  158. package/dist/src/cli/config/index.d.ts +2 -0
  159. package/dist/src/cli/config/index.js +106 -0
  160. package/dist/src/cli/config/index.js.map +1 -0
  161. package/dist/src/cli/config/model-picker.d.ts +17 -0
  162. package/dist/src/cli/config/model-picker.js +149 -0
  163. package/dist/src/cli/config/model-picker.js.map +1 -0
  164. package/dist/src/cli/config/provider-fetch.d.ts +8 -0
  165. package/dist/src/cli/config/provider-fetch.js +59 -0
  166. package/dist/src/cli/config/provider-fetch.js.map +1 -0
  167. package/dist/src/cli/config/screen-council.d.ts +1 -0
  168. package/dist/src/cli/config/screen-council.js +196 -0
  169. package/dist/src/cli/config/screen-council.js.map +1 -0
  170. package/dist/src/cli/config/screen-models.d.ts +1 -0
  171. package/dist/src/cli/config/screen-models.js +86 -0
  172. package/dist/src/cli/config/screen-models.js.map +1 -0
  173. package/dist/src/cli/config/screen-providers.d.ts +1 -0
  174. package/dist/src/cli/config/screen-providers.js +167 -0
  175. package/dist/src/cli/config/screen-providers.js.map +1 -0
  176. package/dist/src/cli/config/tui.d.ts +34 -0
  177. package/dist/src/cli/config/tui.js +145 -0
  178. package/dist/src/cli/config/tui.js.map +1 -0
  179. package/dist/src/cli/cost-forensics.d.ts +46 -0
  180. package/dist/src/cli/cost-forensics.js +188 -0
  181. package/dist/src/cli/cost-forensics.js.map +1 -0
  182. package/dist/src/cli/cost-forensics.test.js +99 -0
  183. package/dist/src/cli/cost-forensics.test.js.map +1 -0
  184. package/dist/src/cli/keys-bundle.d.ts +28 -0
  185. package/dist/src/cli/keys-bundle.js +77 -0
  186. package/dist/src/cli/keys-bundle.js.map +1 -0
  187. package/dist/src/cli/keys.d.ts +74 -0
  188. package/dist/src/cli/keys.js +709 -0
  189. package/dist/src/cli/keys.js.map +1 -0
  190. package/dist/src/cli/keys.test.js +86 -0
  191. package/dist/src/cli/keys.test.js.map +1 -0
  192. package/dist/src/cli/pil-report.d.ts +17 -0
  193. package/dist/src/cli/pil-report.js +163 -0
  194. package/dist/src/cli/pil-report.js.map +1 -0
  195. package/dist/src/cli/share-cmd.d.ts +31 -0
  196. package/dist/src/cli/share-cmd.js +110 -0
  197. package/dist/src/cli/share-cmd.js.map +1 -0
  198. package/dist/src/cli/usage-report.d.ts +17 -0
  199. package/dist/src/cli/usage-report.js +226 -0
  200. package/dist/src/cli/usage-report.js.map +1 -0
  201. package/dist/src/cloud/index.js.map +1 -0
  202. package/dist/src/council/__tests__/accounting.test.js +66 -0
  203. package/dist/src/council/__tests__/accounting.test.js.map +1 -0
  204. package/dist/src/council/__tests__/audit-replay.test.js +241 -0
  205. package/dist/src/council/__tests__/audit-replay.test.js.map +1 -0
  206. package/dist/src/council/__tests__/clarifier-max-rounds.test.js +46 -0
  207. package/dist/src/council/__tests__/clarifier-max-rounds.test.js.map +1 -0
  208. package/dist/src/council/__tests__/clarifier-options.test.js +54 -0
  209. package/dist/src/council/__tests__/clarifier-options.test.js.map +1 -0
  210. package/dist/src/council/__tests__/cost-aware.test.js +49 -0
  211. package/dist/src/council/__tests__/cost-aware.test.js.map +1 -0
  212. package/dist/src/council/__tests__/debate-planner-structured.test.js +209 -0
  213. package/dist/src/council/__tests__/debate-planner-structured.test.js.map +1 -0
  214. package/dist/src/council/__tests__/evaluator-metrics.test.js +460 -0
  215. package/dist/src/council/__tests__/evaluator-metrics.test.js.map +1 -0
  216. package/dist/src/council/__tests__/parse-outcome-fallback.test.js +103 -0
  217. package/dist/src/council/__tests__/parse-outcome-fallback.test.js.map +1 -0
  218. package/dist/src/council/__tests__/research-tools.test.js +210 -0
  219. package/dist/src/council/__tests__/research-tools.test.js.map +1 -0
  220. package/dist/src/council/__tests__/round-tools.test.js +300 -0
  221. package/dist/src/council/__tests__/round-tools.test.js.map +1 -0
  222. package/dist/src/council/__tests__/tool-trace.test.js +131 -0
  223. package/dist/src/council/__tests__/tool-trace.test.js.map +1 -0
  224. package/dist/src/council/__tests__/types-contract.test.d.ts +9 -0
  225. package/dist/src/council/__tests__/types-contract.test.js +82 -0
  226. package/dist/src/council/__tests__/types-contract.test.js.map +1 -0
  227. package/dist/src/council/clarifier.d.ts +42 -0
  228. package/dist/src/council/clarifier.js +332 -0
  229. package/dist/src/council/clarifier.js.map +1 -0
  230. package/dist/src/council/context.d.ts +18 -0
  231. package/dist/src/council/context.js +221 -0
  232. package/dist/src/council/context.js.map +1 -0
  233. package/dist/src/council/debate-planner.d.ts +8 -0
  234. package/dist/src/council/debate-planner.js +243 -0
  235. package/dist/src/council/debate-planner.js.map +1 -0
  236. package/dist/src/council/debate.d.ts +4 -0
  237. package/dist/src/council/debate.js +1014 -0
  238. package/dist/src/council/debate.js.map +1 -0
  239. package/dist/src/council/executor.d.ts +3 -0
  240. package/dist/src/council/executor.js +15 -0
  241. package/dist/src/council/executor.js.map +1 -0
  242. package/dist/src/council/index.d.ts +17 -0
  243. package/dist/src/council/index.js +747 -0
  244. package/dist/src/council/index.js.map +1 -0
  245. package/dist/src/council/leader.d.ts +60 -0
  246. package/dist/src/council/leader.js +216 -0
  247. package/dist/src/council/leader.js.map +1 -0
  248. package/dist/src/council/llm.d.ts +39 -0
  249. package/dist/src/council/llm.js +784 -0
  250. package/dist/src/council/llm.js.map +1 -0
  251. package/dist/src/council/phase-events.d.ts +26 -0
  252. package/dist/src/council/phase-events.js +37 -0
  253. package/dist/src/council/phase-events.js.map +1 -0
  254. package/dist/src/council/planner.d.ts +9 -0
  255. package/dist/src/council/planner.js +262 -0
  256. package/dist/src/council/planner.js.map +1 -0
  257. package/dist/src/council/preflight.d.ts +10 -0
  258. package/dist/src/council/preflight.js +66 -0
  259. package/dist/src/council/preflight.js.map +1 -0
  260. package/dist/src/council/prompts.d.ts +97 -0
  261. package/dist/src/council/prompts.js +491 -0
  262. package/dist/src/council/prompts.js.map +1 -0
  263. package/dist/src/council/types.d.ts +263 -0
  264. package/dist/src/council/types.js.map +1 -0
  265. package/dist/src/daemon/scheduler.d.ts +15 -0
  266. package/dist/src/daemon/scheduler.js +126 -0
  267. package/dist/src/daemon/scheduler.js.map +1 -0
  268. package/dist/src/daemon/scheduler.test.js +103 -0
  269. package/dist/src/daemon/scheduler.test.js.map +1 -0
  270. package/dist/src/ee/__tests__/bb-design.test.d.ts +14 -0
  271. package/dist/src/ee/__tests__/bb-design.test.js +180 -0
  272. package/dist/src/ee/__tests__/bb-design.test.js.map +1 -0
  273. package/dist/src/ee/__tests__/pil-context-bridge.test.js +54 -0
  274. package/dist/src/ee/__tests__/pil-context-bridge.test.js.map +1 -0
  275. package/dist/src/ee/__tests__/pipeline.integration.test.js +151 -0
  276. package/dist/src/ee/__tests__/pipeline.integration.test.js.map +1 -0
  277. package/dist/src/ee/__tests__/render-sink-wiring.test.js +74 -0
  278. package/dist/src/ee/__tests__/render-sink-wiring.test.js.map +1 -0
  279. package/dist/src/ee/auth.d.ts +21 -0
  280. package/dist/src/ee/auth.js +69 -0
  281. package/dist/src/ee/auth.js.map +1 -0
  282. package/dist/src/ee/auth.test.js.map +1 -0
  283. package/dist/src/ee/bb-design.d.ts +54 -0
  284. package/dist/src/ee/bb-design.js +213 -0
  285. package/dist/src/ee/bb-design.js.map +1 -0
  286. package/dist/src/ee/bb-retrieval.d.ts +107 -0
  287. package/dist/src/ee/bb-retrieval.js +341 -0
  288. package/dist/src/ee/bb-retrieval.js.map +1 -0
  289. package/dist/src/ee/bridge.d.ts +102 -0
  290. package/dist/src/ee/bridge.js +338 -0
  291. package/dist/src/ee/bridge.js.map +1 -0
  292. package/dist/src/ee/bridge.test.js.map +1 -0
  293. package/dist/src/ee/client-mode.d.ts +57 -0
  294. package/dist/src/ee/client-mode.js +140 -0
  295. package/dist/src/ee/client-mode.js.map +1 -0
  296. package/dist/src/ee/client.js +564 -0
  297. package/dist/src/ee/client.js.map +1 -0
  298. package/dist/src/ee/client.test.js.map +1 -0
  299. package/dist/src/ee/council-bridge.d.ts +27 -0
  300. package/dist/src/ee/council-bridge.js +60 -0
  301. package/dist/src/ee/council-bridge.js.map +1 -0
  302. package/dist/src/ee/embedding-cache.js.map +1 -0
  303. package/dist/src/ee/extract-session.js +55 -0
  304. package/dist/src/ee/extract-session.js.map +1 -0
  305. package/dist/src/ee/extract-session.test.js +192 -0
  306. package/dist/src/ee/extract-session.test.js.map +1 -0
  307. package/dist/src/ee/health.js +64 -0
  308. package/dist/src/ee/health.js.map +1 -0
  309. package/dist/src/ee/index.d.ts +10 -0
  310. package/dist/src/ee/index.js +9 -0
  311. package/dist/src/ee/index.js.map +1 -0
  312. package/dist/src/ee/intercept.js +122 -0
  313. package/dist/src/ee/intercept.js.map +1 -0
  314. package/dist/src/ee/intercept.test.js +171 -0
  315. package/dist/src/ee/intercept.test.js.map +1 -0
  316. package/dist/src/ee/judge.d.ts +55 -0
  317. package/dist/src/ee/judge.js +111 -0
  318. package/dist/src/ee/judge.js.map +1 -0
  319. package/dist/src/ee/judge.test.js +190 -0
  320. package/dist/src/ee/judge.test.js.map +1 -0
  321. package/dist/src/ee/mistake-detector.d.ts +129 -0
  322. package/dist/src/ee/mistake-detector.js +272 -0
  323. package/dist/src/ee/mistake-detector.js.map +1 -0
  324. package/dist/src/ee/mistake-detector.test.js +221 -0
  325. package/dist/src/ee/mistake-detector.test.js.map +1 -0
  326. package/dist/src/ee/offline-queue.js.map +1 -0
  327. package/dist/src/ee/offline-queue.test.js +246 -0
  328. package/dist/src/ee/offline-queue.test.js.map +1 -0
  329. package/dist/src/ee/phase-outcome.d.ts +83 -0
  330. package/dist/src/ee/phase-outcome.js +98 -0
  331. package/dist/src/ee/phase-outcome.js.map +1 -0
  332. package/dist/src/ee/phase-outcome.test.js +94 -0
  333. package/dist/src/ee/phase-outcome.test.js.map +1 -0
  334. package/dist/src/ee/phase-tracker.d.ts +91 -0
  335. package/dist/src/ee/phase-tracker.js +154 -0
  336. package/dist/src/ee/phase-tracker.js.map +1 -0
  337. package/dist/src/ee/phase-tracker.test.js +142 -0
  338. package/dist/src/ee/phase-tracker.test.js.map +1 -0
  339. package/dist/src/ee/posttool.js.map +1 -0
  340. package/dist/src/ee/posttool.test.js.map +1 -0
  341. package/dist/src/ee/prompt-stale.js.map +1 -0
  342. package/dist/src/ee/prompt-stale.test.js +76 -0
  343. package/dist/src/ee/prompt-stale.test.js.map +1 -0
  344. package/dist/src/ee/render.d.ts +25 -0
  345. package/dist/src/ee/render.js +62 -0
  346. package/dist/src/ee/render.js.map +1 -0
  347. package/dist/src/ee/render.test.js +63 -0
  348. package/dist/src/ee/render.test.js.map +1 -0
  349. package/dist/src/ee/scope.js.map +1 -0
  350. package/dist/src/ee/scope.test.js.map +1 -0
  351. package/dist/src/ee/session-trajectory.d.ts +81 -0
  352. package/dist/src/ee/session-trajectory.js +168 -0
  353. package/dist/src/ee/session-trajectory.js.map +1 -0
  354. package/dist/src/ee/session-trajectory.test.js +120 -0
  355. package/dist/src/ee/session-trajectory.test.js.map +1 -0
  356. package/dist/src/ee/tenant.js.map +1 -0
  357. package/dist/src/ee/touch.test.js +62 -0
  358. package/dist/src/ee/touch.test.js.map +1 -0
  359. package/dist/src/ee/types.d.ts +366 -0
  360. package/dist/src/ee/types.js.map +1 -0
  361. package/dist/src/flow/__tests__/migration.test.js.map +1 -0
  362. package/dist/src/flow/__tests__/parser.test.js.map +1 -0
  363. package/dist/src/flow/__tests__/run-manager-product.test.js +49 -0
  364. package/dist/src/flow/__tests__/run-manager-product.test.js.map +1 -0
  365. package/dist/src/flow/__tests__/run-manager.test.js.map +1 -0
  366. package/dist/src/flow/__tests__/scaffold-checkpoint.test.js +93 -0
  367. package/dist/src/flow/__tests__/scaffold-checkpoint.test.js.map +1 -0
  368. package/dist/src/flow/__tests__/scaffold.test.js.map +1 -0
  369. package/dist/src/flow/__tests__/warning-persist.test.js.map +1 -0
  370. package/dist/src/flow/artifact-io.js.map +1 -0
  371. package/dist/src/flow/compaction/__tests__/compress.test.js.map +1 -0
  372. package/dist/src/flow/compaction/__tests__/extract.test.js.map +1 -0
  373. package/dist/src/flow/compaction/__tests__/preserve.test.js.map +1 -0
  374. package/dist/src/flow/compaction/compress.js.map +1 -0
  375. package/dist/src/flow/compaction/extract.js.map +1 -0
  376. package/dist/src/flow/compaction/index.js.map +1 -0
  377. package/dist/src/flow/compaction/preserve.js.map +1 -0
  378. package/dist/src/flow/index.js.map +1 -0
  379. package/dist/src/flow/migration.js.map +1 -0
  380. package/dist/src/flow/parser.js.map +1 -0
  381. package/dist/src/flow/run-manager.d.ts +38 -0
  382. package/dist/src/flow/run-manager.js +139 -0
  383. package/dist/src/flow/run-manager.js.map +1 -0
  384. package/dist/src/flow/scaffold-checkpoint.d.ts +63 -0
  385. package/dist/src/flow/scaffold-checkpoint.js +101 -0
  386. package/dist/src/flow/scaffold-checkpoint.js.map +1 -0
  387. package/dist/src/flow/scaffold.js.map +1 -0
  388. package/dist/src/flow/warning-persist.js.map +1 -0
  389. package/dist/src/generated/version.d.ts +2 -0
  390. package/dist/src/generated/version.js +5 -0
  391. package/dist/src/generated/version.js.map +1 -0
  392. package/dist/src/gsd/__tests__/complexity.test.js +0 -0
  393. package/dist/src/gsd/__tests__/complexity.test.js.map +1 -0
  394. package/dist/src/gsd/__tests__/directives.test.js +44 -0
  395. package/dist/src/gsd/__tests__/directives.test.js.map +1 -0
  396. package/dist/src/gsd/__tests__/gray-areas.test.js +29 -0
  397. package/dist/src/gsd/__tests__/gray-areas.test.js.map +1 -0
  398. package/dist/src/gsd/__tests__/types.test.js +65 -0
  399. package/dist/src/gsd/__tests__/types.test.js.map +1 -0
  400. package/dist/src/gsd/complexity.d.ts +28 -0
  401. package/dist/src/gsd/complexity.js +103 -0
  402. package/dist/src/gsd/complexity.js.map +1 -0
  403. package/dist/src/gsd/directives.d.ts +31 -0
  404. package/dist/src/gsd/directives.js +73 -0
  405. package/dist/src/gsd/directives.js.map +1 -0
  406. package/dist/src/gsd/gray-areas.d.ts +30 -0
  407. package/dist/src/gsd/gray-areas.js +97 -0
  408. package/dist/src/gsd/gray-areas.js.map +1 -0
  409. package/dist/src/gsd/index.js.map +1 -0
  410. package/dist/src/gsd/types.d.ts +5 -0
  411. package/dist/src/gsd/types.js.map +1 -0
  412. package/dist/src/headless/__tests__/council-answers.test.js +226 -0
  413. package/dist/src/headless/__tests__/council-answers.test.js.map +1 -0
  414. package/dist/src/headless/council-answers.d.ts +53 -0
  415. package/dist/src/headless/council-answers.js +77 -0
  416. package/dist/src/headless/council-answers.js.map +1 -0
  417. package/dist/src/headless/output.d.ts +68 -0
  418. package/dist/src/headless/output.js.map +1 -0
  419. package/dist/src/headless/output.test.js +178 -0
  420. package/dist/src/headless/output.test.js.map +1 -0
  421. package/dist/src/hooks/config.js.map +1 -0
  422. package/dist/src/hooks/index.d.ts +44 -0
  423. package/dist/src/hooks/index.js +471 -0
  424. package/dist/src/hooks/index.js.map +1 -0
  425. package/dist/src/hooks/types.d.ts +175 -0
  426. package/dist/src/hooks/types.js.map +1 -0
  427. package/dist/src/index.d.ts +3 -0
  428. package/dist/src/index.js +1347 -0
  429. package/dist/src/index.js.map +1 -0
  430. package/dist/src/lsp/builtins.d.ts +9 -0
  431. package/dist/src/lsp/builtins.js +351 -0
  432. package/dist/src/lsp/builtins.js.map +1 -0
  433. package/dist/src/lsp/builtins.test.js +91 -0
  434. package/dist/src/lsp/builtins.test.js.map +1 -0
  435. package/dist/src/lsp/client.d.ts +20 -0
  436. package/dist/src/lsp/client.js +290 -0
  437. package/dist/src/lsp/client.js.map +1 -0
  438. package/dist/src/lsp/manager.d.ts +20 -0
  439. package/dist/src/lsp/manager.js +235 -0
  440. package/dist/src/lsp/manager.js.map +1 -0
  441. package/dist/src/lsp/manager.test.js +133 -0
  442. package/dist/src/lsp/manager.test.js.map +1 -0
  443. package/dist/src/lsp/npm-cache.js.map +1 -0
  444. package/dist/src/lsp/npm-cache.test.js +53 -0
  445. package/dist/src/lsp/npm-cache.test.js.map +1 -0
  446. package/dist/src/lsp/runtime.d.ts +6 -0
  447. package/dist/src/lsp/runtime.js +53 -0
  448. package/dist/src/lsp/runtime.js.map +1 -0
  449. package/dist/src/lsp/smoke.test.js.map +1 -0
  450. package/dist/src/lsp/types.js.map +1 -0
  451. package/dist/src/mcp/__tests__/auto-setup.test.js +81 -0
  452. package/dist/src/mcp/__tests__/auto-setup.test.js.map +1 -0
  453. package/dist/src/mcp/__tests__/harness-driver-action-tools.spec.js +101 -0
  454. package/dist/src/mcp/__tests__/harness-driver-action-tools.spec.js.map +1 -0
  455. package/dist/src/mcp/__tests__/harness-driver-async-tools.spec.js +110 -0
  456. package/dist/src/mcp/__tests__/harness-driver-async-tools.spec.js.map +1 -0
  457. package/dist/src/mcp/__tests__/harness-driver-read-tools.spec.js +124 -0
  458. package/dist/src/mcp/__tests__/harness-driver-read-tools.spec.js.map +1 -0
  459. package/dist/src/mcp/__tests__/harness-driver-security.spec.js +61 -0
  460. package/dist/src/mcp/__tests__/harness-driver-security.spec.js.map +1 -0
  461. package/dist/src/mcp/__tests__/harness-driver.spec.js +20 -0
  462. package/dist/src/mcp/__tests__/harness-driver.spec.js.map +1 -0
  463. package/dist/src/mcp/__tests__/lazy-schema.spec.js +152 -0
  464. package/dist/src/mcp/__tests__/lazy-schema.spec.js.map +1 -0
  465. package/dist/src/mcp/__tests__/mcp-keychain.test.js +40 -0
  466. package/dist/src/mcp/__tests__/mcp-keychain.test.js.map +1 -0
  467. package/dist/src/mcp/__tests__/research-onboarding.test.js +148 -0
  468. package/dist/src/mcp/__tests__/research-onboarding.test.js.map +1 -0
  469. package/dist/src/mcp/__tests__/runtime-hydration.test.js +78 -0
  470. package/dist/src/mcp/__tests__/runtime-hydration.test.js.map +1 -0
  471. package/dist/src/mcp/__tests__/runtime-sanitize.test.js +40 -0
  472. package/dist/src/mcp/__tests__/runtime-sanitize.test.js.map +1 -0
  473. package/dist/src/mcp/auto-setup.js +98 -0
  474. package/dist/src/mcp/auto-setup.js.map +1 -0
  475. package/dist/src/mcp/catalog.js +145 -0
  476. package/dist/src/mcp/catalog.js.map +1 -0
  477. package/dist/src/mcp/mcp-keychain.d.ts +13 -0
  478. package/dist/src/mcp/mcp-keychain.js +65 -0
  479. package/dist/src/mcp/mcp-keychain.js.map +1 -0
  480. package/dist/src/mcp/oauth-callback.d.ts +16 -0
  481. package/dist/src/mcp/oauth-callback.js +52 -0
  482. package/dist/src/mcp/oauth-callback.js.map +1 -0
  483. package/dist/src/mcp/oauth-provider.js.map +1 -0
  484. package/dist/src/mcp/opentui-spawn.d.ts +11 -0
  485. package/dist/src/mcp/opentui-spawn.js +58 -0
  486. package/dist/src/mcp/opentui-spawn.js.map +1 -0
  487. package/dist/src/mcp/parse-headers.js.map +1 -0
  488. package/dist/src/mcp/parse-headers.test.js +43 -0
  489. package/dist/src/mcp/parse-headers.test.js.map +1 -0
  490. package/dist/src/mcp/research-onboarding.d.ts +20 -0
  491. package/dist/src/mcp/research-onboarding.js +123 -0
  492. package/dist/src/mcp/research-onboarding.js.map +1 -0
  493. package/dist/src/mcp/runtime.js +148 -0
  494. package/dist/src/mcp/runtime.js.map +1 -0
  495. package/dist/src/mcp/smoke.test.js.map +1 -0
  496. package/dist/src/mcp/validate.d.ts +9 -0
  497. package/dist/src/mcp/validate.js.map +1 -0
  498. package/dist/src/models/__tests__/registry.test.js +74 -0
  499. package/dist/src/models/__tests__/registry.test.js.map +1 -0
  500. package/dist/src/models/catalog-client.js +104 -0
  501. package/dist/src/models/catalog-client.js.map +1 -0
  502. package/dist/src/models/catalog.json +177 -0
  503. package/dist/src/models/classify-tier.js +45 -0
  504. package/dist/src/models/classify-tier.js.map +1 -0
  505. package/dist/src/models/index.d.ts +1 -0
  506. package/dist/src/models/index.js +2 -0
  507. package/dist/src/models/index.js.map +1 -0
  508. package/dist/src/models/registry.d.ts +20 -0
  509. package/dist/src/models/registry.js +68 -0
  510. package/dist/src/models/registry.js.map +1 -0
  511. package/dist/src/ops/__tests__/doctor-council-mcp.test.js +139 -0
  512. package/dist/src/ops/__tests__/doctor-council-mcp.test.js.map +1 -0
  513. package/dist/src/ops/__tests__/doctor-ee-health.test.js +113 -0
  514. package/dist/src/ops/__tests__/doctor-ee-health.test.js.map +1 -0
  515. package/dist/src/ops/bug-report.js.map +1 -0
  516. package/dist/src/ops/bug-report.test.js.map +1 -0
  517. package/dist/src/ops/doctor.js +333 -0
  518. package/dist/src/ops/doctor.js.map +1 -0
  519. package/dist/src/ops/doctor.test.js +96 -0
  520. package/dist/src/ops/doctor.test.js.map +1 -0
  521. package/dist/src/orchestrator/__tests__/batch-turn-runner.test.js +154 -0
  522. package/dist/src/orchestrator/__tests__/batch-turn-runner.test.js.map +1 -0
  523. package/dist/src/orchestrator/__tests__/council-manager.test.js +148 -0
  524. package/dist/src/orchestrator/__tests__/council-manager.test.js.map +1 -0
  525. package/dist/src/orchestrator/__tests__/cross-turn-dedup.test.js +153 -0
  526. package/dist/src/orchestrator/__tests__/cross-turn-dedup.test.js.map +1 -0
  527. package/dist/src/orchestrator/__tests__/current-call-id.test.d.ts +16 -0
  528. package/dist/src/orchestrator/__tests__/current-call-id.test.js +138 -0
  529. package/dist/src/orchestrator/__tests__/current-call-id.test.js.map +1 -0
  530. package/dist/src/orchestrator/__tests__/flow-resume.test.js.map +1 -0
  531. package/dist/src/orchestrator/__tests__/message-processor.test.js +182 -0
  532. package/dist/src/orchestrator/__tests__/message-processor.test.js.map +1 -0
  533. package/dist/src/orchestrator/__tests__/message-write-ahead.test.d.ts +22 -0
  534. package/dist/src/orchestrator/__tests__/message-write-ahead.test.js +149 -0
  535. package/dist/src/orchestrator/__tests__/message-write-ahead.test.js.map +1 -0
  536. package/dist/src/orchestrator/__tests__/read-path-budget.test.js +98 -0
  537. package/dist/src/orchestrator/__tests__/read-path-budget.test.js.map +1 -0
  538. package/dist/src/orchestrator/__tests__/retry-classifier.test.js +102 -0
  539. package/dist/src/orchestrator/__tests__/retry-classifier.test.js.map +1 -0
  540. package/dist/src/orchestrator/__tests__/retry-stream.test.js +151 -0
  541. package/dist/src/orchestrator/__tests__/retry-stream.test.js.map +1 -0
  542. package/dist/src/orchestrator/__tests__/route-feedback.test.js +47 -0
  543. package/dist/src/orchestrator/__tests__/route-feedback.test.js.map +1 -0
  544. package/dist/src/orchestrator/__tests__/stream-runner.test.js +100 -0
  545. package/dist/src/orchestrator/__tests__/stream-runner.test.js.map +1 -0
  546. package/dist/src/orchestrator/__tests__/usage-events-shape.test.d.ts +8 -0
  547. package/dist/src/orchestrator/__tests__/usage-events-shape.test.js +58 -0
  548. package/dist/src/orchestrator/__tests__/usage-events-shape.test.js.map +1 -0
  549. package/dist/src/orchestrator/__tests__/usage-normalizer-c1.test.d.ts +21 -0
  550. package/dist/src/orchestrator/__tests__/usage-normalizer-c1.test.js +155 -0
  551. package/dist/src/orchestrator/__tests__/usage-normalizer-c1.test.js.map +1 -0
  552. package/dist/src/orchestrator/__tests__/write-ahead.test.d.ts +20 -0
  553. package/dist/src/orchestrator/__tests__/write-ahead.test.js +134 -0
  554. package/dist/src/orchestrator/__tests__/write-ahead.test.js.map +1 -0
  555. package/dist/src/orchestrator/abort.js.map +1 -0
  556. package/dist/src/orchestrator/abort.test.js.map +1 -0
  557. package/dist/src/orchestrator/agent-options.d.ts +144 -0
  558. package/dist/src/orchestrator/agent-options.js +15 -0
  559. package/dist/src/orchestrator/agent-options.js.map +1 -0
  560. package/dist/src/orchestrator/agent.test.js +160 -0
  561. package/dist/src/orchestrator/agent.test.js.map +1 -0
  562. package/dist/src/orchestrator/batch-turn-runner.d.ts +57 -0
  563. package/dist/src/orchestrator/batch-turn-runner.js +312 -0
  564. package/dist/src/orchestrator/batch-turn-runner.js.map +1 -0
  565. package/dist/src/orchestrator/batch-utils.d.ts +41 -0
  566. package/dist/src/orchestrator/batch-utils.js +268 -0
  567. package/dist/src/orchestrator/batch-utils.js.map +1 -0
  568. package/dist/src/orchestrator/cleanup.test.d.ts +1 -0
  569. package/dist/src/orchestrator/cleanup.test.js +67 -0
  570. package/dist/src/orchestrator/cleanup.test.js.map +1 -0
  571. package/dist/src/orchestrator/compaction.d.ts +47 -0
  572. package/dist/src/orchestrator/compaction.js +491 -0
  573. package/dist/src/orchestrator/compaction.js.map +1 -0
  574. package/dist/src/orchestrator/compaction.test.d.ts +1 -0
  575. package/dist/src/orchestrator/compaction.test.js +146 -0
  576. package/dist/src/orchestrator/compaction.test.js.map +1 -0
  577. package/dist/src/orchestrator/council-manager.d.ts +109 -0
  578. package/dist/src/orchestrator/council-manager.js +480 -0
  579. package/dist/src/orchestrator/council-manager.js.map +1 -0
  580. package/dist/src/orchestrator/cross-turn-dedup.d.ts +87 -0
  581. package/dist/src/orchestrator/cross-turn-dedup.js +153 -0
  582. package/dist/src/orchestrator/cross-turn-dedup.js.map +1 -0
  583. package/dist/src/orchestrator/delegations.d.ts +49 -0
  584. package/dist/src/orchestrator/delegations.js.map +1 -0
  585. package/dist/src/orchestrator/delegations.test.d.ts +1 -0
  586. package/dist/src/orchestrator/delegations.test.js +107 -0
  587. package/dist/src/orchestrator/delegations.test.js.map +1 -0
  588. package/dist/src/orchestrator/error-utils.d.ts +7 -0
  589. package/dist/src/orchestrator/error-utils.js +66 -0
  590. package/dist/src/orchestrator/error-utils.js.map +1 -0
  591. package/dist/src/orchestrator/flow-resume.d.ts +24 -0
  592. package/dist/src/orchestrator/flow-resume.js +52 -0
  593. package/dist/src/orchestrator/flow-resume.js.map +1 -0
  594. package/dist/src/orchestrator/message-processor.d.ts +132 -0
  595. package/dist/src/orchestrator/message-processor.js +1675 -0
  596. package/dist/src/orchestrator/message-processor.js.map +1 -0
  597. package/dist/src/orchestrator/message-seq.d.ts +13 -0
  598. package/dist/src/orchestrator/message-seq.js +21 -0
  599. package/dist/src/orchestrator/message-seq.js.map +1 -0
  600. package/dist/src/orchestrator/message-seq.test.d.ts +1 -0
  601. package/dist/src/orchestrator/message-seq.test.js +24 -0
  602. package/dist/src/orchestrator/message-seq.test.js.map +1 -0
  603. package/dist/src/orchestrator/orchestrator.d.ts +245 -0
  604. package/dist/src/orchestrator/orchestrator.js +2173 -0
  605. package/dist/src/orchestrator/orchestrator.js.map +1 -0
  606. package/dist/src/orchestrator/pending-calls.js.map +1 -0
  607. package/dist/src/orchestrator/pending-calls.test.d.ts +1 -0
  608. package/dist/src/orchestrator/pending-calls.test.js.map +1 -0
  609. package/dist/src/orchestrator/prompts.d.ts +31 -0
  610. package/dist/src/orchestrator/prompts.js +387 -0
  611. package/dist/src/orchestrator/prompts.js.map +1 -0
  612. package/dist/src/orchestrator/provider-options-shape.d.ts +23 -0
  613. package/dist/src/orchestrator/provider-options-shape.js +68 -0
  614. package/dist/src/orchestrator/provider-options-shape.js.map +1 -0
  615. package/dist/src/orchestrator/provider-options-shape.spec.d.ts +1 -0
  616. package/dist/src/orchestrator/provider-options-shape.spec.js +63 -0
  617. package/dist/src/orchestrator/provider-options-shape.spec.js.map +1 -0
  618. package/dist/src/orchestrator/read-path-budget.d.ts +57 -0
  619. package/dist/src/orchestrator/read-path-budget.js +103 -0
  620. package/dist/src/orchestrator/read-path-budget.js.map +1 -0
  621. package/dist/src/orchestrator/reasoning.js +57 -0
  622. package/dist/src/orchestrator/reasoning.js.map +1 -0
  623. package/dist/src/orchestrator/reasoning.test.d.ts +1 -0
  624. package/dist/src/orchestrator/reasoning.test.js +26 -0
  625. package/dist/src/orchestrator/reasoning.test.js.map +1 -0
  626. package/dist/src/orchestrator/retry-classifier.d.ts +26 -0
  627. package/dist/src/orchestrator/retry-classifier.js +103 -0
  628. package/dist/src/orchestrator/retry-classifier.js.map +1 -0
  629. package/dist/src/orchestrator/retry-stream.d.ts +43 -0
  630. package/dist/src/orchestrator/retry-stream.js +110 -0
  631. package/dist/src/orchestrator/retry-stream.js.map +1 -0
  632. package/dist/src/orchestrator/sandbox.test.d.ts +1 -0
  633. package/dist/src/orchestrator/sandbox.test.js +94 -0
  634. package/dist/src/orchestrator/sandbox.test.js.map +1 -0
  635. package/dist/src/orchestrator/stream-runner.d.ts +131 -0
  636. package/dist/src/orchestrator/stream-runner.js +549 -0
  637. package/dist/src/orchestrator/stream-runner.js.map +1 -0
  638. package/dist/src/orchestrator/sub-agent-cap.d.ts +98 -0
  639. package/dist/src/orchestrator/sub-agent-cap.js +146 -0
  640. package/dist/src/orchestrator/sub-agent-cap.js.map +1 -0
  641. package/dist/src/orchestrator/sub-agent-cap.test.d.ts +1 -0
  642. package/dist/src/orchestrator/sub-agent-cap.test.js +170 -0
  643. package/dist/src/orchestrator/sub-agent-cap.test.js.map +1 -0
  644. package/dist/src/orchestrator/subagent-compactor.d.ts +74 -0
  645. package/dist/src/orchestrator/subagent-compactor.js +218 -0
  646. package/dist/src/orchestrator/subagent-compactor.js.map +1 -0
  647. package/dist/src/orchestrator/subagent-compactor.spec.d.ts +1 -0
  648. package/dist/src/orchestrator/subagent-compactor.spec.js +131 -0
  649. package/dist/src/orchestrator/subagent-compactor.spec.js.map +1 -0
  650. package/dist/src/orchestrator/token-counter.d.ts +27 -0
  651. package/dist/src/orchestrator/token-counter.js +76 -0
  652. package/dist/src/orchestrator/token-counter.js.map +1 -0
  653. package/dist/src/orchestrator/token-counter.test.d.ts +1 -0
  654. package/dist/src/orchestrator/token-counter.test.js +57 -0
  655. package/dist/src/orchestrator/token-counter.test.js.map +1 -0
  656. package/dist/src/orchestrator/tool-utils.d.ts +38 -0
  657. package/dist/src/orchestrator/tool-utils.js +201 -0
  658. package/dist/src/orchestrator/tool-utils.js.map +1 -0
  659. package/dist/src/orchestrator/turn-runner-deps.d.ts +47 -0
  660. package/dist/src/orchestrator/turn-runner-deps.js +14 -0
  661. package/dist/src/orchestrator/turn-runner-deps.js.map +1 -0
  662. package/dist/src/pil/__tests__/budget.test.d.ts +1 -0
  663. package/dist/src/pil/__tests__/budget.test.js +33 -0
  664. package/dist/src/pil/__tests__/budget.test.js.map +1 -0
  665. package/dist/src/pil/__tests__/config.test.d.ts +1 -0
  666. package/dist/src/pil/__tests__/config.test.js +30 -0
  667. package/dist/src/pil/__tests__/config.test.js.map +1 -0
  668. package/dist/src/pil/__tests__/dual-run.test.d.ts +1 -0
  669. package/dist/src/pil/__tests__/dual-run.test.js +49 -0
  670. package/dist/src/pil/__tests__/dual-run.test.js.map +1 -0
  671. package/dist/src/pil/__tests__/layer1-intent-trace.test.d.ts +1 -0
  672. package/dist/src/pil/__tests__/layer1-intent-trace.test.js +128 -0
  673. package/dist/src/pil/__tests__/layer1-intent-trace.test.js.map +1 -0
  674. package/dist/src/pil/__tests__/layer1-intent.test.d.ts +1 -0
  675. package/dist/src/pil/__tests__/layer1-intent.test.js +305 -0
  676. package/dist/src/pil/__tests__/layer1-intent.test.js.map +1 -0
  677. package/dist/src/pil/__tests__/layer2-personality.test.d.ts +1 -0
  678. package/dist/src/pil/__tests__/layer2-personality.test.js +57 -0
  679. package/dist/src/pil/__tests__/layer2-personality.test.js.map +1 -0
  680. package/dist/src/pil/__tests__/layer3-ee-injection.test.d.ts +1 -0
  681. package/dist/src/pil/__tests__/layer3-ee-injection.test.js +153 -0
  682. package/dist/src/pil/__tests__/layer3-ee-injection.test.js.map +1 -0
  683. package/dist/src/pil/__tests__/layer3-injected-chunk.test.d.ts +1 -0
  684. package/dist/src/pil/__tests__/layer3-injected-chunk.test.js +91 -0
  685. package/dist/src/pil/__tests__/layer3-injected-chunk.test.js.map +1 -0
  686. package/dist/src/pil/__tests__/layer4-gsd.test.d.ts +1 -0
  687. package/dist/src/pil/__tests__/layer4-gsd.test.js +97 -0
  688. package/dist/src/pil/__tests__/layer4-gsd.test.js.map +1 -0
  689. package/dist/src/pil/__tests__/layer5-context.test.d.ts +1 -0
  690. package/dist/src/pil/__tests__/layer5-context.test.js +137 -0
  691. package/dist/src/pil/__tests__/layer5-context.test.js.map +1 -0
  692. package/dist/src/pil/__tests__/layer6-output.test.d.ts +1 -0
  693. package/dist/src/pil/__tests__/layer6-output.test.js +237 -0
  694. package/dist/src/pil/__tests__/layer6-output.test.js.map +1 -0
  695. package/dist/src/pil/__tests__/ollama-classify.test.d.ts +1 -0
  696. package/dist/src/pil/__tests__/ollama-classify.test.js.map +1 -0
  697. package/dist/src/pil/__tests__/orchestrator-integration.test.js.map +1 -0
  698. package/dist/src/pil/__tests__/pipeline.test.d.ts +1 -0
  699. package/dist/src/pil/__tests__/pipeline.test.js +167 -0
  700. package/dist/src/pil/__tests__/pipeline.test.js.map +1 -0
  701. package/dist/src/pil/__tests__/renderer-coverage.test.d.ts +7 -0
  702. package/dist/src/pil/__tests__/renderer-coverage.test.js +42 -0
  703. package/dist/src/pil/__tests__/renderer-coverage.test.js.map +1 -0
  704. package/dist/src/pil/__tests__/response-tools.test.d.ts +1 -0
  705. package/dist/src/pil/__tests__/response-tools.test.js +142 -0
  706. package/dist/src/pil/__tests__/response-tools.test.js.map +1 -0
  707. package/dist/src/pil/__tests__/schema.test.d.ts +1 -0
  708. package/dist/src/pil/__tests__/schema.test.js +202 -0
  709. package/dist/src/pil/__tests__/schema.test.js.map +1 -0
  710. package/dist/src/pil/__tests__/scoreComplexity.test.d.ts +1 -0
  711. package/dist/src/pil/__tests__/scoreComplexity.test.js +119 -0
  712. package/dist/src/pil/__tests__/scoreComplexity.test.js.map +1 -0
  713. package/dist/src/pil/__tests__/scoreSufficiency.test.d.ts +8 -0
  714. package/dist/src/pil/__tests__/scoreSufficiency.test.js +89 -0
  715. package/dist/src/pil/__tests__/scoreSufficiency.test.js.map +1 -0
  716. package/dist/src/pil/__tests__/store.test.d.ts +1 -0
  717. package/dist/src/pil/__tests__/store.test.js.map +1 -0
  718. package/dist/src/pil/__tests__/task-tier-map.test.d.ts +1 -0
  719. package/dist/src/pil/__tests__/task-tier-map.test.js.map +1 -0
  720. package/dist/src/pil/budget-log.d.ts +26 -0
  721. package/dist/src/pil/budget-log.js +59 -0
  722. package/dist/src/pil/budget-log.js.map +1 -0
  723. package/dist/src/pil/budget.js.map +1 -0
  724. package/dist/src/pil/config.d.ts +7 -0
  725. package/dist/src/pil/config.js +14 -0
  726. package/dist/src/pil/config.js.map +1 -0
  727. package/dist/src/pil/index.d.ts +11 -0
  728. package/dist/src/pil/index.js +11 -0
  729. package/dist/src/pil/index.js.map +1 -0
  730. package/dist/src/pil/layer1-intent.d.ts +49 -0
  731. package/dist/src/pil/layer1-intent.js +514 -0
  732. package/dist/src/pil/layer1-intent.js.map +1 -0
  733. package/dist/src/pil/layer1-intent.test.d.ts +1 -0
  734. package/dist/src/pil/layer1-intent.test.js +98 -0
  735. package/dist/src/pil/layer1-intent.test.js.map +1 -0
  736. package/dist/src/pil/layer2-personality.js +37 -0
  737. package/dist/src/pil/layer2-personality.js.map +1 -0
  738. package/dist/src/pil/layer3-ee-injection.d.ts +18 -0
  739. package/dist/src/pil/layer3-ee-injection.js +305 -0
  740. package/dist/src/pil/layer3-ee-injection.js.map +1 -0
  741. package/dist/src/pil/layer4-gsd.d.ts +20 -0
  742. package/dist/src/pil/layer4-gsd.js +108 -0
  743. package/dist/src/pil/layer4-gsd.js.map +1 -0
  744. package/dist/src/pil/layer5-context.js +151 -0
  745. package/dist/src/pil/layer5-context.js.map +1 -0
  746. package/dist/src/pil/layer6-output.d.ts +20 -0
  747. package/dist/src/pil/layer6-output.js +237 -0
  748. package/dist/src/pil/layer6-output.js.map +1 -0
  749. package/dist/src/pil/ollama-classify.js.map +1 -0
  750. package/dist/src/pil/pipeline.d.ts +23 -0
  751. package/dist/src/pil/pipeline.js +182 -0
  752. package/dist/src/pil/pipeline.js.map +1 -0
  753. package/dist/src/pil/response-tools.d.ts +63 -0
  754. package/dist/src/pil/response-tools.js +87 -0
  755. package/dist/src/pil/response-tools.js.map +1 -0
  756. package/dist/src/pil/schema.d.ts +160 -0
  757. package/dist/src/pil/schema.js +88 -0
  758. package/dist/src/pil/schema.js.map +1 -0
  759. package/dist/src/pil/store.js.map +1 -0
  760. package/dist/src/pil/task-tier-map.js.map +1 -0
  761. package/dist/src/pil/timeout.js.map +1 -0
  762. package/dist/src/pil/types.d.ts +149 -0
  763. package/dist/src/pil/types.js.map +1 -0
  764. package/dist/src/product-loop/__tests__/artifact-io.test.d.ts +1 -0
  765. package/dist/src/product-loop/__tests__/artifact-io.test.js +83 -0
  766. package/dist/src/product-loop/__tests__/artifact-io.test.js.map +1 -0
  767. package/dist/src/product-loop/__tests__/assumption-ledger.test.d.ts +1 -0
  768. package/dist/src/product-loop/__tests__/assumption-ledger.test.js +261 -0
  769. package/dist/src/product-loop/__tests__/assumption-ledger.test.js.map +1 -0
  770. package/dist/src/product-loop/__tests__/cb2-retry-bonus.test.d.ts +13 -0
  771. package/dist/src/product-loop/__tests__/cb2-retry-bonus.test.js +158 -0
  772. package/dist/src/product-loop/__tests__/cb2-retry-bonus.test.js.map +1 -0
  773. package/dist/src/product-loop/__tests__/circuit-breakers-coverage.test.d.ts +1 -0
  774. package/dist/src/product-loop/__tests__/circuit-breakers-coverage.test.js +67 -0
  775. package/dist/src/product-loop/__tests__/circuit-breakers-coverage.test.js.map +1 -0
  776. package/dist/src/product-loop/__tests__/circuit-breakers.test.d.ts +1 -0
  777. package/dist/src/product-loop/__tests__/circuit-breakers.test.js +79 -0
  778. package/dist/src/product-loop/__tests__/circuit-breakers.test.js.map +1 -0
  779. package/dist/src/product-loop/__tests__/complexity-routing.spec.d.ts +11 -0
  780. package/dist/src/product-loop/__tests__/complexity-routing.spec.js +134 -0
  781. package/dist/src/product-loop/__tests__/complexity-routing.spec.js.map +1 -0
  782. package/dist/src/product-loop/__tests__/context-policy.test.d.ts +1 -0
  783. package/dist/src/product-loop/__tests__/context-policy.test.js +266 -0
  784. package/dist/src/product-loop/__tests__/context-policy.test.js.map +1 -0
  785. package/dist/src/product-loop/__tests__/cost-preview.test.d.ts +1 -0
  786. package/dist/src/product-loop/__tests__/cost-preview.test.js +111 -0
  787. package/dist/src/product-loop/__tests__/cost-preview.test.js.map +1 -0
  788. package/dist/src/product-loop/__tests__/cost-scoper.test.d.ts +1 -0
  789. package/dist/src/product-loop/__tests__/cost-scoper.test.js +50 -0
  790. package/dist/src/product-loop/__tests__/cost-scoper.test.js.map +1 -0
  791. package/dist/src/product-loop/__tests__/cross-run-memory.test.d.ts +1 -0
  792. package/dist/src/product-loop/__tests__/cross-run-memory.test.js +168 -0
  793. package/dist/src/product-loop/__tests__/cross-run-memory.test.js.map +1 -0
  794. package/dist/src/product-loop/__tests__/design-output.spec.d.ts +1 -0
  795. package/dist/src/product-loop/__tests__/design-output.spec.js +36 -0
  796. package/dist/src/product-loop/__tests__/design-output.spec.js.map +1 -0
  797. package/dist/src/product-loop/__tests__/discover.test.d.ts +1 -0
  798. package/dist/src/product-loop/__tests__/discover.test.js +83 -0
  799. package/dist/src/product-loop/__tests__/discover.test.js.map +1 -0
  800. package/dist/src/product-loop/__tests__/discovery-council-runner.test.d.ts +1 -0
  801. package/dist/src/product-loop/__tests__/discovery-council-runner.test.js +13 -0
  802. package/dist/src/product-loop/__tests__/discovery-council-runner.test.js.map +1 -0
  803. package/dist/src/product-loop/__tests__/discovery-detection.test.d.ts +1 -0
  804. package/dist/src/product-loop/__tests__/discovery-detection.test.js +151 -0
  805. package/dist/src/product-loop/__tests__/discovery-detection.test.js.map +1 -0
  806. package/dist/src/product-loop/__tests__/discovery-ecosystem.test.d.ts +8 -0
  807. package/dist/src/product-loop/__tests__/discovery-ecosystem.test.js +110 -0
  808. package/dist/src/product-loop/__tests__/discovery-ecosystem.test.js.map +1 -0
  809. package/dist/src/product-loop/__tests__/discovery-integration.test.d.ts +1 -0
  810. package/dist/src/product-loop/__tests__/discovery-integration.test.js +126 -0
  811. package/dist/src/product-loop/__tests__/discovery-integration.test.js.map +1 -0
  812. package/dist/src/product-loop/__tests__/discovery-interview.test.d.ts +1 -0
  813. package/dist/src/product-loop/__tests__/discovery-interview.test.js +292 -0
  814. package/dist/src/product-loop/__tests__/discovery-interview.test.js.map +1 -0
  815. package/dist/src/product-loop/__tests__/discovery-migrations.test.d.ts +1 -0
  816. package/dist/src/product-loop/__tests__/discovery-migrations.test.js +69 -0
  817. package/dist/src/product-loop/__tests__/discovery-migrations.test.js.map +1 -0
  818. package/dist/src/product-loop/__tests__/discovery-persistence.test.d.ts +1 -0
  819. package/dist/src/product-loop/__tests__/discovery-persistence.test.js +146 -0
  820. package/dist/src/product-loop/__tests__/discovery-persistence.test.js.map +1 -0
  821. package/dist/src/product-loop/__tests__/discovery-prompt-parser.test.d.ts +1 -0
  822. package/dist/src/product-loop/__tests__/discovery-prompt-parser.test.js +65 -0
  823. package/dist/src/product-loop/__tests__/discovery-prompt-parser.test.js.map +1 -0
  824. package/dist/src/product-loop/__tests__/discovery-recommender-ecosystem.test.d.ts +9 -0
  825. package/dist/src/product-loop/__tests__/discovery-recommender-ecosystem.test.js +86 -0
  826. package/dist/src/product-loop/__tests__/discovery-recommender-ecosystem.test.js.map +1 -0
  827. package/dist/src/product-loop/__tests__/discovery-recommender.test.d.ts +1 -0
  828. package/dist/src/product-loop/__tests__/discovery-recommender.test.js +316 -0
  829. package/dist/src/product-loop/__tests__/discovery-recommender.test.js.map +1 -0
  830. package/dist/src/product-loop/__tests__/discovery-schema.test.d.ts +1 -0
  831. package/dist/src/product-loop/__tests__/discovery-schema.test.js +77 -0
  832. package/dist/src/product-loop/__tests__/discovery-schema.test.js.map +1 -0
  833. package/dist/src/product-loop/__tests__/done-gate-coverage.test.d.ts +1 -0
  834. package/dist/src/product-loop/__tests__/done-gate-coverage.test.js +135 -0
  835. package/dist/src/product-loop/__tests__/done-gate-coverage.test.js.map +1 -0
  836. package/dist/src/product-loop/__tests__/done-gate.test.d.ts +1 -0
  837. package/dist/src/product-loop/__tests__/done-gate.test.js +122 -0
  838. package/dist/src/product-loop/__tests__/done-gate.test.js.map +1 -0
  839. package/dist/src/product-loop/__tests__/ee-extract-wiring.test.d.ts +8 -0
  840. package/dist/src/product-loop/__tests__/ee-extract-wiring.test.js +181 -0
  841. package/dist/src/product-loop/__tests__/ee-extract-wiring.test.js.map +1 -0
  842. package/dist/src/product-loop/__tests__/extract-to-ee.test.d.ts +1 -0
  843. package/dist/src/product-loop/__tests__/extract-to-ee.test.js +161 -0
  844. package/dist/src/product-loop/__tests__/extract-to-ee.test.js.map +1 -0
  845. package/dist/src/product-loop/__tests__/feedback-routing.test.d.ts +1 -0
  846. package/dist/src/product-loop/__tests__/feedback-routing.test.js +83 -0
  847. package/dist/src/product-loop/__tests__/feedback-routing.test.js.map +1 -0
  848. package/dist/src/product-loop/__tests__/hot-path.spec.d.ts +11 -0
  849. package/dist/src/product-loop/__tests__/hot-path.spec.js +146 -0
  850. package/dist/src/product-loop/__tests__/hot-path.spec.js.map +1 -0
  851. package/dist/src/product-loop/__tests__/integration.test.d.ts +7 -0
  852. package/dist/src/product-loop/__tests__/integration.test.js +296 -0
  853. package/dist/src/product-loop/__tests__/integration.test.js.map +1 -0
  854. package/dist/src/product-loop/__tests__/loop-driver-audit.test.d.ts +1 -0
  855. package/dist/src/product-loop/__tests__/loop-driver-audit.test.js +264 -0
  856. package/dist/src/product-loop/__tests__/loop-driver-audit.test.js.map +1 -0
  857. package/dist/src/product-loop/__tests__/loop-driver.test.d.ts +1 -0
  858. package/dist/src/product-loop/__tests__/loop-driver.test.js +220 -0
  859. package/dist/src/product-loop/__tests__/loop-driver.test.js.map +1 -0
  860. package/dist/src/product-loop/__tests__/phase-budget.test.d.ts +1 -0
  861. package/dist/src/product-loop/__tests__/phase-budget.test.js +149 -0
  862. package/dist/src/product-loop/__tests__/phase-budget.test.js.map +1 -0
  863. package/dist/src/product-loop/__tests__/phase-orchestrator-integration.test.d.ts +1 -0
  864. package/dist/src/product-loop/__tests__/phase-orchestrator-integration.test.js +138 -0
  865. package/dist/src/product-loop/__tests__/phase-orchestrator-integration.test.js.map +1 -0
  866. package/dist/src/product-loop/__tests__/phase-plan.test.d.ts +1 -0
  867. package/dist/src/product-loop/__tests__/phase-plan.test.js +208 -0
  868. package/dist/src/product-loop/__tests__/phase-plan.test.js.map +1 -0
  869. package/dist/src/product-loop/__tests__/phase-rituals.test.d.ts +1 -0
  870. package/dist/src/product-loop/__tests__/phase-rituals.test.js +174 -0
  871. package/dist/src/product-loop/__tests__/phase-rituals.test.js.map +1 -0
  872. package/dist/src/product-loop/__tests__/phase-runner.test.d.ts +1 -0
  873. package/dist/src/product-loop/__tests__/phase-runner.test.js +414 -0
  874. package/dist/src/product-loop/__tests__/phase-runner.test.js.map +1 -0
  875. package/dist/src/product-loop/__tests__/phase-tracker-bridge.test.d.ts +1 -0
  876. package/dist/src/product-loop/__tests__/phase-tracker-bridge.test.js +67 -0
  877. package/dist/src/product-loop/__tests__/phase-tracker-bridge.test.js.map +1 -0
  878. package/dist/src/product-loop/__tests__/product-identity.test.d.ts +1 -0
  879. package/dist/src/product-loop/__tests__/product-identity.test.js +40 -0
  880. package/dist/src/product-loop/__tests__/product-identity.test.js.map +1 -0
  881. package/dist/src/product-loop/__tests__/reality-anchor.test.d.ts +1 -0
  882. package/dist/src/product-loop/__tests__/reality-anchor.test.js +49 -0
  883. package/dist/src/product-loop/__tests__/reality-anchor.test.js.map +1 -0
  884. package/dist/src/product-loop/__tests__/repo-audit.test.d.ts +1 -0
  885. package/dist/src/product-loop/__tests__/repo-audit.test.js +97 -0
  886. package/dist/src/product-loop/__tests__/repo-audit.test.js.map +1 -0
  887. package/dist/src/product-loop/__tests__/role-memory.test.d.ts +1 -0
  888. package/dist/src/product-loop/__tests__/role-memory.test.js +56 -0
  889. package/dist/src/product-loop/__tests__/role-memory.test.js.map +1 -0
  890. package/dist/src/product-loop/__tests__/role-registry.test.d.ts +1 -0
  891. package/dist/src/product-loop/__tests__/role-registry.test.js +222 -0
  892. package/dist/src/product-loop/__tests__/role-registry.test.js.map +1 -0
  893. package/dist/src/product-loop/__tests__/role-routing-ee.test.d.ts +1 -0
  894. package/dist/src/product-loop/__tests__/role-routing-ee.test.js +79 -0
  895. package/dist/src/product-loop/__tests__/role-routing-ee.test.js.map +1 -0
  896. package/dist/src/product-loop/__tests__/route-decision-emit.test.d.ts +10 -0
  897. package/dist/src/product-loop/__tests__/route-decision-emit.test.js +173 -0
  898. package/dist/src/product-loop/__tests__/route-decision-emit.test.js.map +1 -0
  899. package/dist/src/product-loop/__tests__/seed-questions.test.d.ts +1 -0
  900. package/dist/src/product-loop/__tests__/seed-questions.test.js +30 -0
  901. package/dist/src/product-loop/__tests__/seed-questions.test.js.map +1 -0
  902. package/dist/src/product-loop/__tests__/ship-polish.test.d.ts +1 -0
  903. package/dist/src/product-loop/__tests__/ship-polish.test.js +96 -0
  904. package/dist/src/product-loop/__tests__/ship-polish.test.js.map +1 -0
  905. package/dist/src/product-loop/__tests__/sprint-runner-emit.test.d.ts +14 -0
  906. package/dist/src/product-loop/__tests__/sprint-runner-emit.test.js +279 -0
  907. package/dist/src/product-loop/__tests__/sprint-runner-emit.test.js.map +1 -0
  908. package/dist/src/product-loop/__tests__/sprint-runner.test.d.ts +1 -0
  909. package/dist/src/product-loop/__tests__/sprint-runner.test.js +432 -0
  910. package/dist/src/product-loop/__tests__/sprint-runner.test.js.map +1 -0
  911. package/dist/src/product-loop/__tests__/stakeholder-acl.test.d.ts +1 -0
  912. package/dist/src/product-loop/__tests__/stakeholder-acl.test.js +83 -0
  913. package/dist/src/product-loop/__tests__/stakeholder-acl.test.js.map +1 -0
  914. package/dist/src/product-loop/__tests__/state-md-ee-injections.test.d.ts +8 -0
  915. package/dist/src/product-loop/__tests__/state-md-ee-injections.test.js +182 -0
  916. package/dist/src/product-loop/__tests__/state-md-ee-injections.test.js.map +1 -0
  917. package/dist/src/product-loop/__tests__/sufficiency-routing.spec.d.ts +12 -0
  918. package/dist/src/product-loop/__tests__/sufficiency-routing.spec.js +134 -0
  919. package/dist/src/product-loop/__tests__/sufficiency-routing.spec.js.map +1 -0
  920. package/dist/src/product-loop/__tests__/typed-artifacts.test.d.ts +1 -0
  921. package/dist/src/product-loop/__tests__/typed-artifacts.test.js +222 -0
  922. package/dist/src/product-loop/__tests__/typed-artifacts.test.js.map +1 -0
  923. package/dist/src/product-loop/__tests__/types.test.d.ts +1 -0
  924. package/dist/src/product-loop/__tests__/types.test.js +79 -0
  925. package/dist/src/product-loop/__tests__/types.test.js.map +1 -0
  926. package/dist/src/product-loop/__tests__/verify-failure-threshold.test.d.ts +9 -0
  927. package/dist/src/product-loop/__tests__/verify-failure-threshold.test.js +145 -0
  928. package/dist/src/product-loop/__tests__/verify-failure-threshold.test.js.map +1 -0
  929. package/dist/src/product-loop/__tests__/verify-failure-tracking.test.d.ts +4 -0
  930. package/dist/src/product-loop/__tests__/verify-failure-tracking.test.js +122 -0
  931. package/dist/src/product-loop/__tests__/verify-failure-tracking.test.js.map +1 -0
  932. package/dist/src/product-loop/__tests__/verify-result.test.d.ts +1 -0
  933. package/dist/src/product-loop/__tests__/verify-result.test.js +53 -0
  934. package/dist/src/product-loop/__tests__/verify-result.test.js.map +1 -0
  935. package/dist/src/product-loop/artifact-io.d.ts +41 -0
  936. package/dist/src/product-loop/artifact-io.js +223 -0
  937. package/dist/src/product-loop/artifact-io.js.map +1 -0
  938. package/dist/src/product-loop/assumption-ledger.d.ts +101 -0
  939. package/dist/src/product-loop/assumption-ledger.js +190 -0
  940. package/dist/src/product-loop/assumption-ledger.js.map +1 -0
  941. package/dist/src/product-loop/circuit-breakers.d.ts +34 -0
  942. package/dist/src/product-loop/circuit-breakers.js +54 -0
  943. package/dist/src/product-loop/circuit-breakers.js.map +1 -0
  944. package/dist/src/product-loop/context-policy.d.ts +29 -0
  945. package/dist/src/product-loop/context-policy.js +141 -0
  946. package/dist/src/product-loop/context-policy.js.map +1 -0
  947. package/dist/src/product-loop/cost-preview.d.ts +46 -0
  948. package/dist/src/product-loop/cost-preview.js +75 -0
  949. package/dist/src/product-loop/cost-preview.js.map +1 -0
  950. package/dist/src/product-loop/cost-scoper.d.ts +21 -0
  951. package/dist/src/product-loop/cost-scoper.js +33 -0
  952. package/dist/src/product-loop/cost-scoper.js.map +1 -0
  953. package/dist/src/product-loop/cross-run-memory.d.ts +73 -0
  954. package/dist/src/product-loop/cross-run-memory.js +390 -0
  955. package/dist/src/product-loop/cross-run-memory.js.map +1 -0
  956. package/dist/src/product-loop/design-output.d.ts +4 -0
  957. package/dist/src/product-loop/design-output.js +21 -0
  958. package/dist/src/product-loop/design-output.js.map +1 -0
  959. package/dist/src/product-loop/discover.d.ts +25 -0
  960. package/dist/src/product-loop/discover.js +113 -0
  961. package/dist/src/product-loop/discover.js.map +1 -0
  962. package/dist/src/product-loop/discovery-context-format.d.ts +2 -0
  963. package/dist/src/product-loop/discovery-context-format.js +22 -0
  964. package/dist/src/product-loop/discovery-context-format.js.map +1 -0
  965. package/dist/src/product-loop/discovery-council-runner.d.ts +25 -0
  966. package/dist/src/product-loop/discovery-council-runner.js +66 -0
  967. package/dist/src/product-loop/discovery-council-runner.js.map +1 -0
  968. package/dist/src/product-loop/discovery-detection.d.ts +2 -0
  969. package/dist/src/product-loop/discovery-detection.js +163 -0
  970. package/dist/src/product-loop/discovery-detection.js.map +1 -0
  971. package/dist/src/product-loop/discovery-ecosystem.d.ts +57 -0
  972. package/dist/src/product-loop/discovery-ecosystem.js +106 -0
  973. package/dist/src/product-loop/discovery-ecosystem.js.map +1 -0
  974. package/dist/src/product-loop/discovery-interview.d.ts +40 -0
  975. package/dist/src/product-loop/discovery-interview.js +176 -0
  976. package/dist/src/product-loop/discovery-interview.js.map +1 -0
  977. package/dist/src/product-loop/discovery-migrations.d.ts +5 -0
  978. package/dist/src/product-loop/discovery-migrations.js +39 -0
  979. package/dist/src/product-loop/discovery-migrations.js.map +1 -0
  980. package/dist/src/product-loop/discovery-persistence.d.ts +19 -0
  981. package/dist/src/product-loop/discovery-persistence.js +182 -0
  982. package/dist/src/product-loop/discovery-persistence.js.map +1 -0
  983. package/dist/src/product-loop/discovery-prompt-parser.d.ts +15 -0
  984. package/dist/src/product-loop/discovery-prompt-parser.js +64 -0
  985. package/dist/src/product-loop/discovery-prompt-parser.js.map +1 -0
  986. package/dist/src/product-loop/discovery-recommender.d.ts +50 -0
  987. package/dist/src/product-loop/discovery-recommender.js +288 -0
  988. package/dist/src/product-loop/discovery-recommender.js.map +1 -0
  989. package/dist/src/product-loop/discovery-schema.d.ts +33 -0
  990. package/dist/src/product-loop/discovery-schema.js +120 -0
  991. package/dist/src/product-loop/discovery-schema.js.map +1 -0
  992. package/dist/src/product-loop/done-gate.d.ts +6 -0
  993. package/dist/src/product-loop/done-gate.js +196 -0
  994. package/dist/src/product-loop/done-gate.js.map +1 -0
  995. package/dist/src/product-loop/feedback-routing.d.ts +27 -0
  996. package/dist/src/product-loop/feedback-routing.js +64 -0
  997. package/dist/src/product-loop/feedback-routing.js.map +1 -0
  998. package/dist/src/product-loop/gather.d.ts +17 -0
  999. package/dist/src/product-loop/gather.js +253 -0
  1000. package/dist/src/product-loop/gather.js.map +1 -0
  1001. package/dist/src/product-loop/index.d.ts +74 -0
  1002. package/dist/src/product-loop/index.js +1154 -0
  1003. package/dist/src/product-loop/index.js.map +1 -0
  1004. package/dist/src/product-loop/loop-driver.d.ts +4 -0
  1005. package/dist/src/product-loop/loop-driver.js +824 -0
  1006. package/dist/src/product-loop/loop-driver.js.map +1 -0
  1007. package/dist/src/product-loop/phase-budget.d.ts +65 -0
  1008. package/dist/src/product-loop/phase-budget.js +114 -0
  1009. package/dist/src/product-loop/phase-budget.js.map +1 -0
  1010. package/dist/src/product-loop/phase-plan.d.ts +21 -0
  1011. package/dist/src/product-loop/phase-plan.js +140 -0
  1012. package/dist/src/product-loop/phase-plan.js.map +1 -0
  1013. package/dist/src/product-loop/phase-rituals.d.ts +38 -0
  1014. package/dist/src/product-loop/phase-rituals.js +106 -0
  1015. package/dist/src/product-loop/phase-rituals.js.map +1 -0
  1016. package/dist/src/product-loop/phase-runner.d.ts +28 -0
  1017. package/dist/src/product-loop/phase-runner.js +383 -0
  1018. package/dist/src/product-loop/phase-runner.js.map +1 -0
  1019. package/dist/src/product-loop/phase-tracker-bridge.d.ts +27 -0
  1020. package/dist/src/product-loop/phase-tracker-bridge.js +37 -0
  1021. package/dist/src/product-loop/phase-tracker-bridge.js.map +1 -0
  1022. package/dist/src/product-loop/product-identity.d.ts +1 -0
  1023. package/dist/src/product-loop/product-identity.js +10 -0
  1024. package/dist/src/product-loop/product-identity.js.map +1 -0
  1025. package/dist/src/product-loop/reality-anchor.d.ts +19 -0
  1026. package/dist/src/product-loop/reality-anchor.js +39 -0
  1027. package/dist/src/product-loop/reality-anchor.js.map +1 -0
  1028. package/dist/src/product-loop/repo-audit.d.ts +46 -0
  1029. package/dist/src/product-loop/repo-audit.js +300 -0
  1030. package/dist/src/product-loop/repo-audit.js.map +1 -0
  1031. package/dist/src/product-loop/role-memory.d.ts +13 -0
  1032. package/dist/src/product-loop/role-memory.js +63 -0
  1033. package/dist/src/product-loop/role-memory.js.map +1 -0
  1034. package/dist/src/product-loop/role-registry.d.ts +22 -0
  1035. package/dist/src/product-loop/role-registry.js +146 -0
  1036. package/dist/src/product-loop/role-registry.js.map +1 -0
  1037. package/dist/src/product-loop/seed-questions.d.ts +7 -0
  1038. package/dist/src/product-loop/seed-questions.js +50 -0
  1039. package/dist/src/product-loop/seed-questions.js.map +1 -0
  1040. package/dist/src/product-loop/ship-polish.d.ts +29 -0
  1041. package/dist/src/product-loop/ship-polish.js +134 -0
  1042. package/dist/src/product-loop/ship-polish.js.map +1 -0
  1043. package/dist/src/product-loop/sprint-runner.d.ts +63 -0
  1044. package/dist/src/product-loop/sprint-runner.js +515 -0
  1045. package/dist/src/product-loop/sprint-runner.js.map +1 -0
  1046. package/dist/src/product-loop/stakeholder-acl.d.ts +16 -0
  1047. package/dist/src/product-loop/stakeholder-acl.js +66 -0
  1048. package/dist/src/product-loop/stakeholder-acl.js.map +1 -0
  1049. package/dist/src/product-loop/typed-artifacts.d.ts +77 -0
  1050. package/dist/src/product-loop/typed-artifacts.js +262 -0
  1051. package/dist/src/product-loop/typed-artifacts.js.map +1 -0
  1052. package/dist/src/product-loop/types.d.ts +395 -0
  1053. package/dist/src/product-loop/types.js +2 -0
  1054. package/dist/src/product-loop/types.js.map +1 -0
  1055. package/dist/src/product-loop/verify-failure-tracking.d.ts +76 -0
  1056. package/dist/src/product-loop/verify-failure-tracking.js +172 -0
  1057. package/dist/src/product-loop/verify-failure-tracking.js.map +1 -0
  1058. package/dist/src/product-loop/verify-result.d.ts +18 -0
  1059. package/dist/src/product-loop/verify-result.js +31 -0
  1060. package/dist/src/product-loop/verify-result.js.map +1 -0
  1061. package/dist/src/providers/__test-utils__/load-fixture.js.map +1 -0
  1062. package/dist/src/providers/__tests__/adapter-oauth-wiring.test.d.ts +8 -0
  1063. package/dist/src/providers/__tests__/adapter-oauth-wiring.test.js +109 -0
  1064. package/dist/src/providers/__tests__/adapter-oauth-wiring.test.js.map +1 -0
  1065. package/dist/src/providers/__tests__/capabilities-cosmetic.test.d.ts +1 -0
  1066. package/dist/src/providers/__tests__/capabilities-cosmetic.test.js +109 -0
  1067. package/dist/src/providers/__tests__/capabilities-cosmetic.test.js.map +1 -0
  1068. package/dist/src/providers/__tests__/capabilities-flags.test.d.ts +1 -0
  1069. package/dist/src/providers/__tests__/capabilities-flags.test.js +145 -0
  1070. package/dist/src/providers/__tests__/capabilities-flags.test.js.map +1 -0
  1071. package/dist/src/providers/__tests__/capabilities-provider-options.test.d.ts +1 -0
  1072. package/dist/src/providers/__tests__/capabilities-provider-options.test.js +179 -0
  1073. package/dist/src/providers/__tests__/capabilities-provider-options.test.js.map +1 -0
  1074. package/dist/src/providers/__tests__/capabilities-sanitize.test.d.ts +1 -0
  1075. package/dist/src/providers/__tests__/capabilities-sanitize.test.js +75 -0
  1076. package/dist/src/providers/__tests__/capabilities-sanitize.test.js.map +1 -0
  1077. package/dist/src/providers/__tests__/capabilities.test.d.ts +1 -0
  1078. package/dist/src/providers/__tests__/capabilities.test.js +41 -0
  1079. package/dist/src/providers/__tests__/capabilities.test.js.map +1 -0
  1080. package/dist/src/providers/__tests__/provider-coverage.test.d.ts +1 -0
  1081. package/dist/src/providers/__tests__/provider-coverage.test.js +45 -0
  1082. package/dist/src/providers/__tests__/provider-coverage.test.js.map +1 -0
  1083. package/dist/src/providers/__tests__/runtime-integration.test.d.ts +1 -0
  1084. package/dist/src/providers/__tests__/runtime-integration.test.js +86 -0
  1085. package/dist/src/providers/__tests__/runtime-integration.test.js.map +1 -0
  1086. package/dist/src/providers/__tests__/runtime.test.d.ts +1 -0
  1087. package/dist/src/providers/__tests__/runtime.test.js +83 -0
  1088. package/dist/src/providers/__tests__/runtime.test.js.map +1 -0
  1089. package/dist/src/providers/__tests__/siliconflow-history.test.d.ts +1 -0
  1090. package/dist/src/providers/__tests__/siliconflow-history.test.js +76 -0
  1091. package/dist/src/providers/__tests__/siliconflow-history.test.js.map +1 -0
  1092. package/dist/src/providers/__tests__/strategies-registry.test.d.ts +8 -0
  1093. package/dist/src/providers/__tests__/strategies-registry.test.js +49 -0
  1094. package/dist/src/providers/__tests__/strategies-registry.test.js.map +1 -0
  1095. package/dist/src/providers/__tests__/strategies-resolve.test.d.ts +12 -0
  1096. package/dist/src/providers/__tests__/strategies-resolve.test.js +128 -0
  1097. package/dist/src/providers/__tests__/strategies-resolve.test.js.map +1 -0
  1098. package/dist/src/providers/__tests__/wire-debug.test.d.ts +1 -0
  1099. package/dist/src/providers/__tests__/wire-debug.test.js +39 -0
  1100. package/dist/src/providers/__tests__/wire-debug.test.js.map +1 -0
  1101. package/dist/src/providers/adapter.d.ts +61 -0
  1102. package/dist/src/providers/adapter.js +127 -0
  1103. package/dist/src/providers/adapter.js.map +1 -0
  1104. package/dist/src/providers/adapter.test.d.ts +1 -0
  1105. package/dist/src/providers/adapter.test.js.map +1 -0
  1106. package/dist/src/providers/anthropic.js +146 -0
  1107. package/dist/src/providers/anthropic.js.map +1 -0
  1108. package/dist/src/providers/auth/__tests__/browser-flow.test.d.ts +8 -0
  1109. package/dist/src/providers/auth/__tests__/browser-flow.test.js +186 -0
  1110. package/dist/src/providers/auth/__tests__/browser-flow.test.js.map +1 -0
  1111. package/dist/src/providers/auth/__tests__/device-flow.test.d.ts +6 -0
  1112. package/dist/src/providers/auth/__tests__/device-flow.test.js +219 -0
  1113. package/dist/src/providers/auth/__tests__/device-flow.test.js.map +1 -0
  1114. package/dist/src/providers/auth/__tests__/gemini-oauth.test.d.ts +8 -0
  1115. package/dist/src/providers/auth/__tests__/gemini-oauth.test.js +310 -0
  1116. package/dist/src/providers/auth/__tests__/gemini-oauth.test.js.map +1 -0
  1117. package/dist/src/providers/auth/__tests__/openai-oauth.test.d.ts +7 -0
  1118. package/dist/src/providers/auth/__tests__/openai-oauth.test.js +309 -0
  1119. package/dist/src/providers/auth/__tests__/openai-oauth.test.js.map +1 -0
  1120. package/dist/src/providers/auth/__tests__/token-store.test.d.ts +7 -0
  1121. package/dist/src/providers/auth/__tests__/token-store.test.js +125 -0
  1122. package/dist/src/providers/auth/__tests__/token-store.test.js.map +1 -0
  1123. package/dist/src/providers/auth/browser-flow.d.ts +60 -0
  1124. package/dist/src/providers/auth/browser-flow.js +78 -0
  1125. package/dist/src/providers/auth/browser-flow.js.map +1 -0
  1126. package/dist/src/providers/auth/device-flow.d.ts +66 -0
  1127. package/dist/src/providers/auth/device-flow.js +147 -0
  1128. package/dist/src/providers/auth/device-flow.js.map +1 -0
  1129. package/dist/src/providers/auth/gemini-oauth.d.ts +55 -0
  1130. package/dist/src/providers/auth/gemini-oauth.js +294 -0
  1131. package/dist/src/providers/auth/gemini-oauth.js.map +1 -0
  1132. package/dist/src/providers/auth/openai-oauth.d.ts +60 -0
  1133. package/dist/src/providers/auth/openai-oauth.js +373 -0
  1134. package/dist/src/providers/auth/openai-oauth.js.map +1 -0
  1135. package/dist/src/providers/auth/registry.d.ts +65 -0
  1136. package/dist/src/providers/auth/registry.js +82 -0
  1137. package/dist/src/providers/auth/registry.js.map +1 -0
  1138. package/dist/src/providers/auth/token-store.d.ts +28 -0
  1139. package/dist/src/providers/auth/token-store.js +134 -0
  1140. package/dist/src/providers/auth/token-store.js.map +1 -0
  1141. package/dist/src/providers/auth/types.d.ts +77 -0
  1142. package/dist/src/providers/auth/types.js +30 -0
  1143. package/dist/src/providers/auth/types.js.map +1 -0
  1144. package/dist/src/providers/capabilities.d.ts +135 -0
  1145. package/dist/src/providers/capabilities.js +241 -0
  1146. package/dist/src/providers/capabilities.js.map +1 -0
  1147. package/dist/src/providers/endpoints.d.ts +25 -0
  1148. package/dist/src/providers/endpoints.js +58 -0
  1149. package/dist/src/providers/endpoints.js.map +1 -0
  1150. package/dist/src/providers/errors.js.map +1 -0
  1151. package/dist/src/providers/errors.test.d.ts +1 -0
  1152. package/dist/src/providers/errors.test.js.map +1 -0
  1153. package/dist/src/providers/gemini.js +38 -0
  1154. package/dist/src/providers/gemini.js.map +1 -0
  1155. package/dist/src/providers/gemini.test.d.ts +1 -0
  1156. package/dist/src/providers/gemini.test.js.map +1 -0
  1157. package/dist/src/providers/index.d.ts +11 -0
  1158. package/dist/src/providers/index.js +15 -0
  1159. package/dist/src/providers/index.js.map +1 -0
  1160. package/dist/src/providers/keychain.d.ts +66 -0
  1161. package/dist/src/providers/keychain.js +250 -0
  1162. package/dist/src/providers/keychain.js.map +1 -0
  1163. package/dist/src/providers/keychain.test.d.ts +1 -0
  1164. package/dist/src/providers/keychain.test.js +84 -0
  1165. package/dist/src/providers/keychain.test.js.map +1 -0
  1166. package/dist/src/providers/mcp-vision-bridge.d.ts +60 -0
  1167. package/dist/src/providers/mcp-vision-bridge.js +861 -0
  1168. package/dist/src/providers/mcp-vision-bridge.js.map +1 -0
  1169. package/dist/src/providers/mcp-vision-bridge.test.d.ts +1 -0
  1170. package/dist/src/providers/mcp-vision-bridge.test.js +381 -0
  1171. package/dist/src/providers/mcp-vision-bridge.test.js.map +1 -0
  1172. package/dist/src/providers/ollama.js.map +1 -0
  1173. package/dist/src/providers/ollama.test.d.ts +1 -0
  1174. package/dist/src/providers/ollama.test.js.map +1 -0
  1175. package/dist/src/providers/openai-compatible.js +54 -0
  1176. package/dist/src/providers/openai-compatible.js.map +1 -0
  1177. package/dist/src/providers/openai-compatible.test.d.ts +1 -0
  1178. package/dist/src/providers/openai-compatible.test.js +53 -0
  1179. package/dist/src/providers/openai-compatible.test.js.map +1 -0
  1180. package/dist/src/providers/openai.d.ts +22 -0
  1181. package/dist/src/providers/openai.js +46 -0
  1182. package/dist/src/providers/openai.js.map +1 -0
  1183. package/dist/src/providers/openai.test.d.ts +1 -0
  1184. package/dist/src/providers/openai.test.js.map +1 -0
  1185. package/dist/src/providers/patch-zod-schema.js +120 -0
  1186. package/dist/src/providers/patch-zod-schema.js.map +1 -0
  1187. package/dist/src/providers/pricing.d.ts +35 -0
  1188. package/dist/src/providers/pricing.js +92 -0
  1189. package/dist/src/providers/pricing.js.map +1 -0
  1190. package/dist/src/providers/pricing.test.d.ts +1 -0
  1191. package/dist/src/providers/pricing.test.js +55 -0
  1192. package/dist/src/providers/pricing.test.js.map +1 -0
  1193. package/dist/src/providers/prompt-cache-key.spec.d.ts +5 -0
  1194. package/dist/src/providers/prompt-cache-key.spec.js +24 -0
  1195. package/dist/src/providers/prompt-cache-key.spec.js.map +1 -0
  1196. package/dist/src/providers/runtime-mock.spec.d.ts +8 -0
  1197. package/dist/src/providers/runtime-mock.spec.js +69 -0
  1198. package/dist/src/providers/runtime-mock.spec.js.map +1 -0
  1199. package/dist/src/providers/runtime.d.ts +90 -0
  1200. package/dist/src/providers/runtime.js +226 -0
  1201. package/dist/src/providers/runtime.js.map +1 -0
  1202. package/dist/src/providers/siliconflow-history.d.ts +50 -0
  1203. package/dist/src/providers/siliconflow-history.js +64 -0
  1204. package/dist/src/providers/siliconflow-history.js.map +1 -0
  1205. package/dist/src/providers/strategies/anthropic.strategy.d.ts +15 -0
  1206. package/dist/src/providers/strategies/anthropic.strategy.js +21 -0
  1207. package/dist/src/providers/strategies/anthropic.strategy.js.map +1 -0
  1208. package/dist/src/providers/strategies/base.strategy.d.ts +52 -0
  1209. package/dist/src/providers/strategies/base.strategy.js +38 -0
  1210. package/dist/src/providers/strategies/base.strategy.js.map +1 -0
  1211. package/dist/src/providers/strategies/deepseek.strategy.d.ts +14 -0
  1212. package/dist/src/providers/strategies/deepseek.strategy.js +22 -0
  1213. package/dist/src/providers/strategies/deepseek.strategy.js.map +1 -0
  1214. package/dist/src/providers/strategies/google.strategy.d.ts +15 -0
  1215. package/dist/src/providers/strategies/google.strategy.js +24 -0
  1216. package/dist/src/providers/strategies/google.strategy.js.map +1 -0
  1217. package/dist/src/providers/strategies/ollama.strategy.d.ts +15 -0
  1218. package/dist/src/providers/strategies/ollama.strategy.js +18 -0
  1219. package/dist/src/providers/strategies/ollama.strategy.js.map +1 -0
  1220. package/dist/src/providers/strategies/openai.strategy.d.ts +23 -0
  1221. package/dist/src/providers/strategies/openai.strategy.js +48 -0
  1222. package/dist/src/providers/strategies/openai.strategy.js.map +1 -0
  1223. package/dist/src/providers/strategies/registry.d.ts +14 -0
  1224. package/dist/src/providers/strategies/registry.js +37 -0
  1225. package/dist/src/providers/strategies/registry.js.map +1 -0
  1226. package/dist/src/providers/strategies/siliconflow.strategy.d.ts +14 -0
  1227. package/dist/src/providers/strategies/siliconflow.strategy.js +22 -0
  1228. package/dist/src/providers/strategies/siliconflow.strategy.js.map +1 -0
  1229. package/dist/src/providers/strategies/xai.strategy.d.ts +14 -0
  1230. package/dist/src/providers/strategies/xai.strategy.js +22 -0
  1231. package/dist/src/providers/strategies/xai.strategy.js.map +1 -0
  1232. package/dist/src/providers/stream-loop.d.ts +20 -0
  1233. package/dist/src/providers/stream-loop.js +79 -0
  1234. package/dist/src/providers/stream-loop.js.map +1 -0
  1235. package/dist/src/providers/types.d.ts +128 -0
  1236. package/dist/src/providers/types.js +31 -0
  1237. package/dist/src/providers/types.js.map +1 -0
  1238. package/dist/src/providers/vision-proxy.js +256 -0
  1239. package/dist/src/providers/vision-proxy.js.map +1 -0
  1240. package/dist/src/providers/vision-proxy.test.d.ts +1 -0
  1241. package/dist/src/providers/vision-proxy.test.js +212 -0
  1242. package/dist/src/providers/vision-proxy.test.js.map +1 -0
  1243. package/dist/src/providers/wire-debug.d.ts +28 -0
  1244. package/dist/src/providers/wire-debug.js +146 -0
  1245. package/dist/src/providers/wire-debug.js.map +1 -0
  1246. package/dist/src/router/__tests__/step-router.test.d.ts +4 -0
  1247. package/dist/src/router/__tests__/step-router.test.js +131 -0
  1248. package/dist/src/router/__tests__/step-router.test.js.map +1 -0
  1249. package/dist/src/router/classifier/grammars.js.map +1 -0
  1250. package/dist/src/router/classifier/index.js.map +1 -0
  1251. package/dist/src/router/classifier/index.test.d.ts +1 -0
  1252. package/dist/src/router/classifier/index.test.js.map +1 -0
  1253. package/dist/src/router/classifier/regex.js +104 -0
  1254. package/dist/src/router/classifier/regex.js.map +1 -0
  1255. package/dist/src/router/classifier/regex.test.d.ts +1 -0
  1256. package/dist/src/router/classifier/regex.test.js.map +1 -0
  1257. package/dist/src/router/classifier/tree-sitter.js.map +1 -0
  1258. package/dist/src/router/classifier/tree-sitter.test.d.ts +1 -0
  1259. package/dist/src/router/classifier/tree-sitter.test.js.map +1 -0
  1260. package/dist/src/router/cold.js.map +1 -0
  1261. package/dist/src/router/cold.test.d.ts +1 -0
  1262. package/dist/src/router/cold.test.js +56 -0
  1263. package/dist/src/router/cold.test.js.map +1 -0
  1264. package/dist/src/router/decide.js +410 -0
  1265. package/dist/src/router/decide.js.map +1 -0
  1266. package/dist/src/router/decide.test.d.ts +1 -0
  1267. package/dist/src/router/decide.test.js +116 -0
  1268. package/dist/src/router/decide.test.js.map +1 -0
  1269. package/dist/src/router/health.js.map +1 -0
  1270. package/dist/src/router/health.test.d.ts +1 -0
  1271. package/dist/src/router/health.test.js.map +1 -0
  1272. package/dist/src/router/provider-sentinel.d.ts +16 -0
  1273. package/dist/src/router/provider-sentinel.js +18 -0
  1274. package/dist/src/router/provider-sentinel.js.map +1 -0
  1275. package/dist/src/router/provider-sentinel.test.d.ts +1 -0
  1276. package/dist/src/router/provider-sentinel.test.js +20 -0
  1277. package/dist/src/router/provider-sentinel.test.js.map +1 -0
  1278. package/dist/src/router/step-router.d.ts +57 -0
  1279. package/dist/src/router/step-router.js +143 -0
  1280. package/dist/src/router/step-router.js.map +1 -0
  1281. package/dist/src/router/store.js.map +1 -0
  1282. package/dist/src/router/types.js +2 -0
  1283. package/dist/src/router/types.js.map +1 -0
  1284. package/dist/src/router/warm.js +46 -0
  1285. package/dist/src/router/warm.js.map +1 -0
  1286. package/dist/src/router/warm.test.d.ts +1 -0
  1287. package/dist/src/router/warm.test.js +144 -0
  1288. package/dist/src/router/warm.test.js.map +1 -0
  1289. package/dist/src/scaffold/__tests__/continuation-prompt.test.d.ts +4 -0
  1290. package/dist/src/scaffold/__tests__/continuation-prompt.test.js +79 -0
  1291. package/dist/src/scaffold/__tests__/continuation-prompt.test.js.map +1 -0
  1292. package/dist/src/scaffold/__tests__/continue-as-council.spec.d.ts +10 -0
  1293. package/dist/src/scaffold/__tests__/continue-as-council.spec.js +102 -0
  1294. package/dist/src/scaffold/__tests__/continue-as-council.spec.js.map +1 -0
  1295. package/dist/src/scaffold/__tests__/dotnet-assembly-name.test.d.ts +1 -0
  1296. package/dist/src/scaffold/__tests__/dotnet-assembly-name.test.js +27 -0
  1297. package/dist/src/scaffold/__tests__/dotnet-assembly-name.test.js.map +1 -0
  1298. package/dist/src/scaffold/__tests__/fe-scaffold-contents.test.d.ts +1 -0
  1299. package/dist/src/scaffold/__tests__/fe-scaffold-contents.test.js +106 -0
  1300. package/dist/src/scaffold/__tests__/fe-scaffold-contents.test.js.map +1 -0
  1301. package/dist/src/scaffold/__tests__/init-new.smoke.spec.d.ts +15 -0
  1302. package/dist/src/scaffold/__tests__/init-new.smoke.spec.js +81 -0
  1303. package/dist/src/scaffold/__tests__/init-new.smoke.spec.js.map +1 -0
  1304. package/dist/src/scaffold/__tests__/init-new.spec.d.ts +5 -0
  1305. package/dist/src/scaffold/__tests__/init-new.spec.js +378 -0
  1306. package/dist/src/scaffold/__tests__/init-new.spec.js.map +1 -0
  1307. package/dist/src/scaffold/__tests__/install-bb-templates.spec.d.ts +1 -0
  1308. package/dist/src/scaffold/__tests__/install-bb-templates.spec.js +77 -0
  1309. package/dist/src/scaffold/__tests__/install-bb-templates.spec.js.map +1 -0
  1310. package/dist/src/scaffold/__tests__/point-to-existing.spec.d.ts +7 -0
  1311. package/dist/src/scaffold/__tests__/point-to-existing.spec.js +94 -0
  1312. package/dist/src/scaffold/__tests__/point-to-existing.spec.js.map +1 -0
  1313. package/dist/src/scaffold/bb-ecosystem-apply.d.ts +80 -0
  1314. package/dist/src/scaffold/bb-ecosystem-apply.js +315 -0
  1315. package/dist/src/scaffold/bb-ecosystem-apply.js.map +1 -0
  1316. package/dist/src/scaffold/bb-quality-gate.d.ts +59 -0
  1317. package/dist/src/scaffold/bb-quality-gate.js +185 -0
  1318. package/dist/src/scaffold/bb-quality-gate.js.map +1 -0
  1319. package/dist/src/scaffold/continuation-prompt.d.ts +12 -0
  1320. package/dist/src/scaffold/continuation-prompt.js +66 -0
  1321. package/dist/src/scaffold/continuation-prompt.js.map +1 -0
  1322. package/dist/src/scaffold/continue-as-council.d.ts +47 -0
  1323. package/dist/src/scaffold/continue-as-council.js +60 -0
  1324. package/dist/src/scaffold/continue-as-council.js.map +1 -0
  1325. package/dist/src/scaffold/init-new.d.ts +239 -0
  1326. package/dist/src/scaffold/init-new.js +1414 -0
  1327. package/dist/src/scaffold/init-new.js.map +1 -0
  1328. package/dist/src/scaffold/point-to-existing.d.ts +38 -0
  1329. package/dist/src/scaffold/point-to-existing.js +51 -0
  1330. package/dist/src/scaffold/point-to-existing.js.map +1 -0
  1331. package/dist/src/scaffold/resume-from-gate-failures.d.ts +48 -0
  1332. package/dist/src/scaffold/resume-from-gate-failures.js +113 -0
  1333. package/dist/src/scaffold/resume-from-gate-failures.js.map +1 -0
  1334. package/dist/src/storage/__tests__/migrations.test.js.map +1 -0
  1335. package/dist/src/storage/__tests__/ui-interaction-log.test.d.ts +7 -0
  1336. package/dist/src/storage/__tests__/ui-interaction-log.test.js +97 -0
  1337. package/dist/src/storage/__tests__/ui-interaction-log.test.js.map +1 -0
  1338. package/dist/src/storage/atomic-io.d.ts +30 -0
  1339. package/dist/src/storage/atomic-io.js +163 -0
  1340. package/dist/src/storage/atomic-io.js.map +1 -0
  1341. package/dist/src/storage/atomic-io.test.d.ts +1 -0
  1342. package/dist/src/storage/atomic-io.test.js +74 -0
  1343. package/dist/src/storage/atomic-io.test.js.map +1 -0
  1344. package/dist/src/storage/config.js +39 -0
  1345. package/dist/src/storage/config.js.map +1 -0
  1346. package/dist/src/storage/config.test.d.ts +1 -0
  1347. package/dist/src/storage/config.test.js.map +1 -0
  1348. package/dist/src/storage/db.js +143 -0
  1349. package/dist/src/storage/db.js.map +1 -0
  1350. package/dist/src/storage/index.d.ts +10 -0
  1351. package/dist/src/storage/index.js +12 -0
  1352. package/dist/src/storage/index.js.map +1 -0
  1353. package/dist/src/storage/interaction-log.d.ts +33 -0
  1354. package/dist/src/storage/interaction-log.js +73 -0
  1355. package/dist/src/storage/interaction-log.js.map +1 -0
  1356. package/dist/src/storage/migrations.d.ts +2 -0
  1357. package/dist/src/storage/migrations.js +200 -0
  1358. package/dist/src/storage/migrations.js.map +1 -0
  1359. package/dist/src/storage/session-dir.js.map +1 -0
  1360. package/dist/src/storage/sessions.d.ts +22 -0
  1361. package/dist/src/storage/sessions.js +168 -0
  1362. package/dist/src/storage/sessions.js.map +1 -0
  1363. package/dist/src/storage/tool-results.d.ts +4 -0
  1364. package/dist/src/storage/tool-results.js.map +1 -0
  1365. package/dist/src/storage/transcript-view.js +23 -0
  1366. package/dist/src/storage/transcript-view.js.map +1 -0
  1367. package/dist/src/storage/transcript.d.ts +85 -0
  1368. package/dist/src/storage/transcript.js +461 -0
  1369. package/dist/src/storage/transcript.js.map +1 -0
  1370. package/dist/src/storage/transcript.test.d.ts +1 -0
  1371. package/dist/src/storage/transcript.test.js +22 -0
  1372. package/dist/src/storage/transcript.test.js.map +1 -0
  1373. package/dist/src/storage/ui-interaction-log.d.ts +146 -0
  1374. package/dist/src/storage/ui-interaction-log.js +34 -0
  1375. package/dist/src/storage/ui-interaction-log.js.map +1 -0
  1376. package/dist/src/storage/usage-cap.js.map +1 -0
  1377. package/dist/src/storage/usage-cap.test.d.ts +1 -0
  1378. package/dist/src/storage/usage-cap.test.js.map +1 -0
  1379. package/dist/src/storage/usage.d.ts +11 -0
  1380. package/dist/src/storage/usage.js +65 -0
  1381. package/dist/src/storage/usage.js.map +1 -0
  1382. package/dist/src/storage/workspaces.d.ts +9 -0
  1383. package/dist/src/storage/workspaces.js +60 -0
  1384. package/dist/src/storage/workspaces.js.map +1 -0
  1385. package/dist/src/tools/bash.d.ts +53 -0
  1386. package/dist/src/tools/bash.js +593 -0
  1387. package/dist/src/tools/bash.js.map +1 -0
  1388. package/dist/src/tools/bash.test.d.ts +1 -0
  1389. package/dist/src/tools/bash.test.js +268 -0
  1390. package/dist/src/tools/bash.test.js.map +1 -0
  1391. package/dist/src/tools/computer.d.ts +88 -0
  1392. package/dist/src/tools/computer.js.map +1 -0
  1393. package/dist/src/tools/computer.test.d.ts +1 -0
  1394. package/dist/src/tools/computer.test.js +142 -0
  1395. package/dist/src/tools/computer.test.js.map +1 -0
  1396. package/dist/src/tools/file-tracker.d.ts +35 -0
  1397. package/dist/src/tools/file-tracker.js +40 -0
  1398. package/dist/src/tools/file-tracker.js.map +1 -0
  1399. package/dist/src/tools/file-tracker.test.d.ts +1 -0
  1400. package/dist/src/tools/file-tracker.test.js +77 -0
  1401. package/dist/src/tools/file-tracker.test.js.map +1 -0
  1402. package/dist/src/tools/file.d.ts +18 -0
  1403. package/dist/src/tools/file.js +135 -0
  1404. package/dist/src/tools/file.js.map +1 -0
  1405. package/dist/src/tools/file.test.d.ts +1 -0
  1406. package/dist/src/tools/file.test.js +58 -0
  1407. package/dist/src/tools/file.test.js.map +1 -0
  1408. package/dist/src/tools/grep.d.ts +8 -0
  1409. package/dist/src/tools/grep.js.map +1 -0
  1410. package/dist/src/tools/registry.d.ts +21 -0
  1411. package/dist/src/tools/registry.js +346 -0
  1412. package/dist/src/tools/registry.js.map +1 -0
  1413. package/dist/src/tools/registry.test.d.ts +1 -0
  1414. package/dist/src/tools/registry.test.js +34 -0
  1415. package/dist/src/tools/registry.test.js.map +1 -0
  1416. package/dist/src/tools/schedule.js +498 -0
  1417. package/dist/src/tools/schedule.js.map +1 -0
  1418. package/dist/src/tools/schedule.test.d.ts +1 -0
  1419. package/dist/src/tools/schedule.test.js +118 -0
  1420. package/dist/src/tools/schedule.test.js.map +1 -0
  1421. package/dist/src/types/index.d.ts +396 -0
  1422. package/dist/src/types/index.js.map +1 -0
  1423. package/dist/src/ui/agents-modal.d.ts +36 -0
  1424. package/dist/src/ui/agents-modal.js +55 -0
  1425. package/dist/src/ui/agents-modal.js.map +1 -0
  1426. package/dist/src/ui/app.d.ts +20 -0
  1427. package/dist/src/ui/app.js +5423 -0
  1428. package/dist/src/ui/app.js.map +1 -0
  1429. package/dist/src/ui/cards/__tests__/product-status-card.test.d.ts +1 -0
  1430. package/dist/src/ui/cards/__tests__/product-status-card.test.js +27 -0
  1431. package/dist/src/ui/cards/__tests__/product-status-card.test.js.map +1 -0
  1432. package/dist/src/ui/cards/product-status-card.d.ts +25 -0
  1433. package/dist/src/ui/cards/product-status-card.js +55 -0
  1434. package/dist/src/ui/cards/product-status-card.js.map +1 -0
  1435. package/dist/src/ui/components/SuggestionOverlay.js.map +1 -0
  1436. package/dist/src/ui/components/Toast.d.ts +23 -0
  1437. package/dist/src/ui/components/Toast.js +70 -0
  1438. package/dist/src/ui/components/Toast.js.map +1 -0
  1439. package/dist/src/ui/components/__tests__/council-leader-bubble.test.d.ts +1 -0
  1440. package/dist/src/ui/components/__tests__/council-leader-bubble.test.js +14 -0
  1441. package/dist/src/ui/components/__tests__/council-leader-bubble.test.js.map +1 -0
  1442. package/dist/src/ui/components/__tests__/council-message-bubble.test.d.ts +1 -0
  1443. package/dist/src/ui/components/__tests__/council-message-bubble.test.js +74 -0
  1444. package/dist/src/ui/components/__tests__/council-message-bubble.test.js.map +1 -0
  1445. package/dist/src/ui/components/__tests__/council-phase-timeline.test.d.ts +1 -0
  1446. package/dist/src/ui/components/__tests__/council-phase-timeline.test.js +51 -0
  1447. package/dist/src/ui/components/__tests__/council-phase-timeline.test.js.map +1 -0
  1448. package/dist/src/ui/components/__tests__/council-placeholder-bubble.test.d.ts +1 -0
  1449. package/dist/src/ui/components/__tests__/council-placeholder-bubble.test.js +14 -0
  1450. package/dist/src/ui/components/__tests__/council-placeholder-bubble.test.js.map +1 -0
  1451. package/dist/src/ui/components/__tests__/council-question-card.test.d.ts +1 -0
  1452. package/dist/src/ui/components/__tests__/council-question-card.test.js +121 -0
  1453. package/dist/src/ui/components/__tests__/council-question-card.test.js.map +1 -0
  1454. package/dist/src/ui/components/__tests__/council-synthesis-banner.test.d.ts +1 -0
  1455. package/dist/src/ui/components/__tests__/council-synthesis-banner.test.js +11 -0
  1456. package/dist/src/ui/components/__tests__/council-synthesis-banner.test.js.map +1 -0
  1457. package/dist/src/ui/components/__tests__/use-pair-quote-buffer.test.d.ts +1 -0
  1458. package/dist/src/ui/components/__tests__/use-pair-quote-buffer.test.js +37 -0
  1459. package/dist/src/ui/components/__tests__/use-pair-quote-buffer.test.js.map +1 -0
  1460. package/dist/src/ui/components/btw-overlay.js.map +1 -0
  1461. package/dist/src/ui/components/bubble-layout.d.ts +36 -0
  1462. package/dist/src/ui/components/bubble-layout.js +43 -0
  1463. package/dist/src/ui/components/bubble-layout.js.map +1 -0
  1464. package/dist/src/ui/components/code-block-truncate.d.ts +8 -0
  1465. package/dist/src/ui/components/code-block-truncate.js +22 -0
  1466. package/dist/src/ui/components/code-block-truncate.js.map +1 -0
  1467. package/dist/src/ui/components/copy-flash-banner.d.ts +5 -0
  1468. package/dist/src/ui/components/copy-flash-banner.js +5 -0
  1469. package/dist/src/ui/components/copy-flash-banner.js.map +1 -0
  1470. package/dist/src/ui/components/council-info-card.d.ts +9 -0
  1471. package/dist/src/ui/components/council-info-card.js +10 -0
  1472. package/dist/src/ui/components/council-info-card.js.map +1 -0
  1473. package/dist/src/ui/components/council-leader-bubble.d.ts +11 -0
  1474. package/dist/src/ui/components/council-leader-bubble.js +17 -0
  1475. package/dist/src/ui/components/council-leader-bubble.js.map +1 -0
  1476. package/dist/src/ui/components/council-message-bubble.d.ts +21 -0
  1477. package/dist/src/ui/components/council-message-bubble.js +47 -0
  1478. package/dist/src/ui/components/council-message-bubble.js.map +1 -0
  1479. package/dist/src/ui/components/council-phase-timeline.d.ts +14 -0
  1480. package/dist/src/ui/components/council-phase-timeline.js +64 -0
  1481. package/dist/src/ui/components/council-phase-timeline.js.map +1 -0
  1482. package/dist/src/ui/components/council-placeholder-bubble.d.ts +22 -0
  1483. package/dist/src/ui/components/council-placeholder-bubble.js +37 -0
  1484. package/dist/src/ui/components/council-placeholder-bubble.js.map +1 -0
  1485. package/dist/src/ui/components/council-question-card.d.ts +64 -0
  1486. package/dist/src/ui/components/council-question-card.js +135 -0
  1487. package/dist/src/ui/components/council-question-card.js.map +1 -0
  1488. package/dist/src/ui/components/council-status-list.d.ts +15 -0
  1489. package/dist/src/ui/components/council-status-list.js +83 -0
  1490. package/dist/src/ui/components/council-status-list.js.map +1 -0
  1491. package/dist/src/ui/components/council-synthesis-banner.d.ts +10 -0
  1492. package/dist/src/ui/components/council-synthesis-banner.js +15 -0
  1493. package/dist/src/ui/components/council-synthesis-banner.js.map +1 -0
  1494. package/dist/src/ui/components/diff-view.d.ts +31 -0
  1495. package/dist/src/ui/components/diff-view.js +109 -0
  1496. package/dist/src/ui/components/diff-view.js.map +1 -0
  1497. package/dist/src/ui/components/halt-recovery-card.d.ts +9 -0
  1498. package/dist/src/ui/components/halt-recovery-card.js +26 -0
  1499. package/dist/src/ui/components/halt-recovery-card.js.map +1 -0
  1500. package/dist/src/ui/components/hero-logo.d.ts +4 -0
  1501. package/dist/src/ui/components/hero-logo.js +41 -0
  1502. package/dist/src/ui/components/hero-logo.js.map +1 -0
  1503. package/dist/src/ui/components/init-new-form-card.d.ts +109 -0
  1504. package/dist/src/ui/components/init-new-form-card.js +106 -0
  1505. package/dist/src/ui/components/init-new-form-card.js.map +1 -0
  1506. package/dist/src/ui/components/lsp-views.d.ts +14 -0
  1507. package/dist/src/ui/components/lsp-views.js +34 -0
  1508. package/dist/src/ui/components/lsp-views.js.map +1 -0
  1509. package/dist/src/ui/components/media-views.d.ts +13 -0
  1510. package/dist/src/ui/components/media-views.js +29 -0
  1511. package/dist/src/ui/components/media-views.js.map +1 -0
  1512. package/dist/src/ui/components/message-view.d.ts +31 -0
  1513. package/dist/src/ui/components/message-view.js +174 -0
  1514. package/dist/src/ui/components/message-view.js.map +1 -0
  1515. package/dist/src/ui/components/point-to-existing-form-card.d.ts +33 -0
  1516. package/dist/src/ui/components/point-to-existing-form-card.js +34 -0
  1517. package/dist/src/ui/components/point-to-existing-form-card.js.map +1 -0
  1518. package/dist/src/ui/components/prompt-box.d.ts +50 -0
  1519. package/dist/src/ui/components/prompt-box.js +66 -0
  1520. package/dist/src/ui/components/prompt-box.js.map +1 -0
  1521. package/dist/src/ui/components/role-palette.d.ts +22 -0
  1522. package/dist/src/ui/components/role-palette.js +50 -0
  1523. package/dist/src/ui/components/role-palette.js.map +1 -0
  1524. package/dist/src/ui/components/session-header.d.ts +14 -0
  1525. package/dist/src/ui/components/session-header.js +24 -0
  1526. package/dist/src/ui/components/session-header.js.map +1 -0
  1527. package/dist/src/ui/components/slash-inline-menu.d.ts +7 -0
  1528. package/dist/src/ui/components/slash-inline-menu.js +14 -0
  1529. package/dist/src/ui/components/slash-inline-menu.js.map +1 -0
  1530. package/dist/src/ui/components/structured-response-view.d.ts +7 -0
  1531. package/dist/src/ui/components/structured-response-view.js +59 -0
  1532. package/dist/src/ui/components/structured-response-view.js.map +1 -0
  1533. package/dist/src/ui/components/tool-result-views.d.ts +60 -0
  1534. package/dist/src/ui/components/tool-result-views.js +83 -0
  1535. package/dist/src/ui/components/tool-result-views.js.map +1 -0
  1536. package/dist/src/ui/components/use-pair-quote-buffer.d.ts +11 -0
  1537. package/dist/src/ui/components/use-pair-quote-buffer.js +17 -0
  1538. package/dist/src/ui/components/use-pair-quote-buffer.js.map +1 -0
  1539. package/dist/src/ui/constants.d.ts +37 -0
  1540. package/dist/src/ui/constants.js +221 -0
  1541. package/dist/src/ui/constants.js.map +1 -0
  1542. package/dist/src/ui/hooks/use-agent-editor.d.ts +40 -0
  1543. package/dist/src/ui/hooks/use-agent-editor.js +54 -0
  1544. package/dist/src/ui/hooks/use-agent-editor.js.map +1 -0
  1545. package/dist/src/ui/hooks/use-mcp-editor.d.ts +24 -0
  1546. package/dist/src/ui/hooks/use-mcp-editor.js +38 -0
  1547. package/dist/src/ui/hooks/use-mcp-editor.js.map +1 -0
  1548. package/dist/src/ui/hooks/use-model-picker.d.ts +26 -0
  1549. package/dist/src/ui/hooks/use-model-picker.js +44 -0
  1550. package/dist/src/ui/hooks/use-model-picker.js.map +1 -0
  1551. package/dist/src/ui/hooks/useTypeahead.js +127 -0
  1552. package/dist/src/ui/hooks/useTypeahead.js.map +1 -0
  1553. package/dist/src/ui/markdown.d.ts +5 -0
  1554. package/dist/src/ui/markdown.js.map +1 -0
  1555. package/dist/src/ui/mcp-modal-types.d.ts +24 -0
  1556. package/dist/src/ui/mcp-modal-types.js.map +1 -0
  1557. package/dist/src/ui/mcp-modal.d.ts +33 -0
  1558. package/dist/src/ui/mcp-modal.js +95 -0
  1559. package/dist/src/ui/mcp-modal.js.map +1 -0
  1560. package/dist/src/ui/modals/api-key-modal.d.ts +11 -0
  1561. package/dist/src/ui/modals/api-key-modal.js +15 -0
  1562. package/dist/src/ui/modals/api-key-modal.js.map +1 -0
  1563. package/dist/src/ui/modals/connect-modal.d.ts +30 -0
  1564. package/dist/src/ui/modals/connect-modal.js +34 -0
  1565. package/dist/src/ui/modals/connect-modal.js.map +1 -0
  1566. package/dist/src/ui/modals/model-picker-modal.d.ts +50 -0
  1567. package/dist/src/ui/modals/model-picker-modal.js +57 -0
  1568. package/dist/src/ui/modals/model-picker-modal.js.map +1 -0
  1569. package/dist/src/ui/modals/sandbox-picker-modal.d.ts +12 -0
  1570. package/dist/src/ui/modals/sandbox-picker-modal.js +18 -0
  1571. package/dist/src/ui/modals/sandbox-picker-modal.js.map +1 -0
  1572. package/dist/src/ui/modals/update-modal.d.ts +8 -0
  1573. package/dist/src/ui/modals/update-modal.js +10 -0
  1574. package/dist/src/ui/modals/update-modal.js.map +1 -0
  1575. package/dist/src/ui/modals/wallet-picker-modal.d.ts +26 -0
  1576. package/dist/src/ui/modals/wallet-picker-modal.js +33 -0
  1577. package/dist/src/ui/modals/wallet-picker-modal.js.map +1 -0
  1578. package/dist/src/ui/plan.d.ts +24 -0
  1579. package/dist/src/ui/plan.js.map +1 -0
  1580. package/dist/src/ui/schedule-modal.d.ts +15 -0
  1581. package/dist/src/ui/schedule-modal.js +37 -0
  1582. package/dist/src/ui/schedule-modal.js.map +1 -0
  1583. package/dist/src/ui/slash/__tests__/clear.test.js.map +1 -0
  1584. package/dist/src/ui/slash/__tests__/compact.test.js.map +1 -0
  1585. package/dist/src/ui/slash/__tests__/cost.test.js.map +1 -0
  1586. package/dist/src/ui/slash/__tests__/discuss.test.d.ts +1 -0
  1587. package/dist/src/ui/slash/__tests__/discuss.test.js.map +1 -0
  1588. package/dist/src/ui/slash/__tests__/execute.test.d.ts +1 -0
  1589. package/dist/src/ui/slash/__tests__/execute.test.js.map +1 -0
  1590. package/dist/src/ui/slash/__tests__/expand.test.js.map +1 -0
  1591. package/dist/src/ui/slash/__tests__/ideal.test.d.ts +1 -0
  1592. package/dist/src/ui/slash/__tests__/ideal.test.js +117 -0
  1593. package/dist/src/ui/slash/__tests__/ideal.test.js.map +1 -0
  1594. package/dist/src/ui/slash/__tests__/menu-parity.test.d.ts +15 -0
  1595. package/dist/src/ui/slash/__tests__/menu-parity.test.js +41 -0
  1596. package/dist/src/ui/slash/__tests__/menu-parity.test.js.map +1 -0
  1597. package/dist/src/ui/slash/__tests__/optimize.test.js +130 -0
  1598. package/dist/src/ui/slash/__tests__/optimize.test.js.map +1 -0
  1599. package/dist/src/ui/slash/__tests__/pin.test.d.ts +1 -0
  1600. package/dist/src/ui/slash/__tests__/pin.test.js +38 -0
  1601. package/dist/src/ui/slash/__tests__/pin.test.js.map +1 -0
  1602. package/dist/src/ui/slash/__tests__/plan.test.d.ts +1 -0
  1603. package/dist/src/ui/slash/__tests__/plan.test.js.map +1 -0
  1604. package/dist/src/ui/slash/clear.js.map +1 -0
  1605. package/dist/src/ui/slash/compact.js.map +1 -0
  1606. package/dist/src/ui/slash/cost.js +55 -0
  1607. package/dist/src/ui/slash/cost.js.map +1 -0
  1608. package/dist/src/ui/slash/council-inspect.d.ts +9 -0
  1609. package/dist/src/ui/slash/council-inspect.js +146 -0
  1610. package/dist/src/ui/slash/council-inspect.js.map +1 -0
  1611. package/dist/src/ui/slash/council.js +23 -0
  1612. package/dist/src/ui/slash/council.js.map +1 -0
  1613. package/dist/src/ui/slash/debug.js +109 -0
  1614. package/dist/src/ui/slash/debug.js.map +1 -0
  1615. package/dist/src/ui/slash/discuss.js.map +1 -0
  1616. package/dist/src/ui/slash/ee.js +271 -0
  1617. package/dist/src/ui/slash/ee.js.map +1 -0
  1618. package/dist/src/ui/slash/execute.js.map +1 -0
  1619. package/dist/src/ui/slash/expand.js.map +1 -0
  1620. package/dist/src/ui/slash/export.d.ts +20 -0
  1621. package/dist/src/ui/slash/export.js +253 -0
  1622. package/dist/src/ui/slash/export.js.map +1 -0
  1623. package/dist/src/ui/slash/ideal.d.ts +60 -0
  1624. package/dist/src/ui/slash/ideal.js +198 -0
  1625. package/dist/src/ui/slash/ideal.js.map +1 -0
  1626. package/dist/src/ui/slash/menu-items.d.ts +42 -0
  1627. package/dist/src/ui/slash/menu-items.js +92 -0
  1628. package/dist/src/ui/slash/menu-items.js.map +1 -0
  1629. package/dist/src/ui/slash/optimize.js +37 -0
  1630. package/dist/src/ui/slash/optimize.js.map +1 -0
  1631. package/dist/src/ui/slash/pin.d.ts +15 -0
  1632. package/dist/src/ui/slash/pin.js +36 -0
  1633. package/dist/src/ui/slash/pin.js.map +1 -0
  1634. package/dist/src/ui/slash/plan.js.map +1 -0
  1635. package/dist/src/ui/slash/registry.d.ts +32 -0
  1636. package/dist/src/ui/slash/registry.js.map +1 -0
  1637. package/dist/src/ui/slash/route.js.map +1 -0
  1638. package/dist/src/ui/slash/route.test.js.map +1 -0
  1639. package/dist/src/ui/status-bar/index.d.ts +14 -0
  1640. package/dist/src/ui/status-bar/index.js +79 -0
  1641. package/dist/src/ui/status-bar/index.js.map +1 -0
  1642. package/dist/src/ui/status-bar/index.test.d.ts +1 -0
  1643. package/dist/src/ui/status-bar/index.test.js.map +1 -0
  1644. package/dist/src/ui/status-bar/store.js +161 -0
  1645. package/dist/src/ui/status-bar/store.js.map +1 -0
  1646. package/dist/src/ui/status-bar/store.test.d.ts +1 -0
  1647. package/dist/src/ui/status-bar/store.test.js.map +1 -0
  1648. package/dist/src/ui/status-bar/tier-badge.js.map +1 -0
  1649. package/dist/src/ui/status-bar/tier-badge.test.d.ts +1 -0
  1650. package/dist/src/ui/status-bar/tier-badge.test.js.map +1 -0
  1651. package/dist/src/ui/status-bar/usd-meter.js.map +1 -0
  1652. package/dist/src/ui/status-bar/usd-meter.test.d.ts +1 -0
  1653. package/dist/src/ui/status-bar/usd-meter.test.js.map +1 -0
  1654. package/dist/src/ui/syntax-highlight.d.ts +8 -0
  1655. package/dist/src/ui/syntax-highlight.js +623 -0
  1656. package/dist/src/ui/syntax-highlight.js.map +1 -0
  1657. package/dist/src/ui/terminal-selection-text.js.map +1 -0
  1658. package/dist/src/ui/theme.d.ts +91 -0
  1659. package/dist/src/ui/theme.js +94 -0
  1660. package/dist/src/ui/theme.js.map +1 -0
  1661. package/dist/src/ui/types.d.ts +82 -0
  1662. package/dist/src/ui/types.js +2 -0
  1663. package/dist/src/ui/types.js.map +1 -0
  1664. package/dist/src/ui/utils/color.d.ts +1 -0
  1665. package/dist/src/ui/utils/color.js +18 -0
  1666. package/dist/src/ui/utils/color.js.map +1 -0
  1667. package/dist/src/ui/utils/format.d.ts +21 -0
  1668. package/dist/src/ui/utils/format.js +75 -0
  1669. package/dist/src/ui/utils/format.js.map +1 -0
  1670. package/dist/src/ui/utils/modal.d.ts +3 -0
  1671. package/dist/src/ui/utils/modal.js +7 -0
  1672. package/dist/src/ui/utils/modal.js.map +1 -0
  1673. package/dist/src/ui/utils/text.d.ts +6 -0
  1674. package/dist/src/ui/utils/text.js +31 -0
  1675. package/dist/src/ui/utils/text.js.map +1 -0
  1676. package/dist/src/ui/utils/tools.d.ts +8 -0
  1677. package/dist/src/ui/utils/tools.js +123 -0
  1678. package/dist/src/ui/utils/tools.js.map +1 -0
  1679. package/dist/src/usage/__tests__/product-ledger.test.d.ts +1 -0
  1680. package/dist/src/usage/__tests__/product-ledger.test.js +59 -0
  1681. package/dist/src/usage/__tests__/product-ledger.test.js.map +1 -0
  1682. package/dist/src/usage/cost-log.d.ts +65 -0
  1683. package/dist/src/usage/cost-log.js +117 -0
  1684. package/dist/src/usage/cost-log.js.map +1 -0
  1685. package/dist/src/usage/decision-log.d.ts +32 -0
  1686. package/dist/src/usage/decision-log.js +70 -0
  1687. package/dist/src/usage/decision-log.js.map +1 -0
  1688. package/dist/src/usage/downgrade.js.map +1 -0
  1689. package/dist/src/usage/downgrade.test.d.ts +1 -0
  1690. package/dist/src/usage/downgrade.test.js.map +1 -0
  1691. package/dist/src/usage/estimator.d.ts +26 -0
  1692. package/dist/src/usage/estimator.js +46 -0
  1693. package/dist/src/usage/estimator.js.map +1 -0
  1694. package/dist/src/usage/estimator.test.d.ts +1 -0
  1695. package/dist/src/usage/estimator.test.js.map +1 -0
  1696. package/dist/src/usage/ledger.d.ts +48 -0
  1697. package/dist/src/usage/ledger.js +208 -0
  1698. package/dist/src/usage/ledger.js.map +1 -0
  1699. package/dist/src/usage/ledger.test.d.ts +1 -0
  1700. package/dist/src/usage/ledger.test.js.map +1 -0
  1701. package/dist/src/usage/midstream.js.map +1 -0
  1702. package/dist/src/usage/midstream.test.d.ts +1 -0
  1703. package/dist/src/usage/midstream.test.js.map +1 -0
  1704. package/dist/src/usage/product-ledger.d.ts +47 -0
  1705. package/dist/src/usage/product-ledger.js +73 -0
  1706. package/dist/src/usage/product-ledger.js.map +1 -0
  1707. package/dist/src/usage/thresholds.js.map +1 -0
  1708. package/dist/src/usage/thresholds.test.d.ts +1 -0
  1709. package/dist/src/usage/thresholds.test.js.map +1 -0
  1710. package/dist/src/usage/types.d.ts +31 -0
  1711. package/dist/src/usage/types.js.map +1 -0
  1712. package/dist/src/utils/__tests__/auto-council-settings.test.d.ts +1 -0
  1713. package/dist/src/utils/__tests__/auto-council-settings.test.js +41 -0
  1714. package/dist/src/utils/__tests__/auto-council-settings.test.js.map +1 -0
  1715. package/dist/src/utils/__tests__/ee-logger.test.d.ts +11 -0
  1716. package/dist/src/utils/__tests__/ee-logger.test.js +165 -0
  1717. package/dist/src/utils/__tests__/ee-logger.test.js.map +1 -0
  1718. package/dist/src/utils/__tests__/file-lock.test.d.ts +1 -0
  1719. package/dist/src/utils/__tests__/file-lock.test.js +66 -0
  1720. package/dist/src/utils/__tests__/file-lock.test.js.map +1 -0
  1721. package/dist/src/utils/__tests__/rate-limit.test.d.ts +1 -0
  1722. package/dist/src/utils/__tests__/rate-limit.test.js +38 -0
  1723. package/dist/src/utils/__tests__/rate-limit.test.js.map +1 -0
  1724. package/dist/src/utils/__tests__/settings-disabled-models.test.d.ts +7 -0
  1725. package/dist/src/utils/__tests__/settings-disabled-models.test.js +99 -0
  1726. package/dist/src/utils/__tests__/settings-disabled-models.test.js.map +1 -0
  1727. package/dist/src/utils/__tests__/settings-web-research.test.d.ts +1 -0
  1728. package/dist/src/utils/__tests__/settings-web-research.test.js +46 -0
  1729. package/dist/src/utils/__tests__/settings-web-research.test.js.map +1 -0
  1730. package/dist/src/utils/__tests__/slugify.test.d.ts +1 -0
  1731. package/dist/src/utils/__tests__/slugify.test.js +37 -0
  1732. package/dist/src/utils/__tests__/slugify.test.js.map +1 -0
  1733. package/dist/src/utils/__tests__/visible-retry.test.d.ts +1 -0
  1734. package/dist/src/utils/__tests__/visible-retry.test.js +143 -0
  1735. package/dist/src/utils/__tests__/visible-retry.test.js.map +1 -0
  1736. package/dist/src/utils/at-mentions.js.map +1 -0
  1737. package/dist/src/utils/clipboard-image.js +146 -0
  1738. package/dist/src/utils/clipboard-image.js.map +1 -0
  1739. package/dist/src/utils/ee-logger.d.ts +65 -0
  1740. package/dist/src/utils/ee-logger.js +150 -0
  1741. package/dist/src/utils/ee-logger.js.map +1 -0
  1742. package/dist/src/utils/file-index.js.map +1 -0
  1743. package/dist/src/utils/file-lock.d.ts +5 -0
  1744. package/dist/src/utils/file-lock.js +58 -0
  1745. package/dist/src/utils/file-lock.js.map +1 -0
  1746. package/dist/src/utils/git-root.js.map +1 -0
  1747. package/dist/src/utils/host-clipboard.d.ts +10 -0
  1748. package/dist/src/utils/host-clipboard.js +69 -0
  1749. package/dist/src/utils/host-clipboard.js.map +1 -0
  1750. package/dist/src/utils/install-manager.js.map +1 -0
  1751. package/dist/src/utils/install-manager.test.d.ts +1 -0
  1752. package/dist/src/utils/install-manager.test.js +127 -0
  1753. package/dist/src/utils/install-manager.test.js.map +1 -0
  1754. package/dist/src/utils/instructions.js +140 -0
  1755. package/dist/src/utils/instructions.js.map +1 -0
  1756. package/dist/src/utils/instructions.test.d.ts +1 -0
  1757. package/dist/src/utils/instructions.test.js +93 -0
  1758. package/dist/src/utils/instructions.test.js.map +1 -0
  1759. package/dist/src/utils/permission-mode.js.map +1 -0
  1760. package/dist/src/utils/permission-mode.test.d.ts +1 -0
  1761. package/dist/src/utils/permission-mode.test.js.map +1 -0
  1762. package/dist/src/utils/rate-limit.d.ts +4 -0
  1763. package/dist/src/utils/rate-limit.js +21 -0
  1764. package/dist/src/utils/rate-limit.js.map +1 -0
  1765. package/dist/src/utils/redactor.js.map +1 -0
  1766. package/dist/src/utils/redactor.test.d.ts +1 -0
  1767. package/dist/src/utils/redactor.test.js +84 -0
  1768. package/dist/src/utils/redactor.test.js.map +1 -0
  1769. package/dist/src/utils/settings.d.ts +346 -0
  1770. package/dist/src/utils/settings.js +791 -0
  1771. package/dist/src/utils/settings.js.map +1 -0
  1772. package/dist/src/utils/settings.test.d.ts +1 -0
  1773. package/dist/src/utils/settings.test.js +160 -0
  1774. package/dist/src/utils/settings.test.js.map +1 -0
  1775. package/dist/src/utils/shell.d.ts +34 -0
  1776. package/dist/src/utils/shell.js +171 -0
  1777. package/dist/src/utils/shell.js.map +1 -0
  1778. package/dist/src/utils/shell.test.d.ts +1 -0
  1779. package/dist/src/utils/shell.test.js +71 -0
  1780. package/dist/src/utils/shell.test.js.map +1 -0
  1781. package/dist/src/utils/side-question.js.map +1 -0
  1782. package/dist/src/utils/skills.js +194 -0
  1783. package/dist/src/utils/skills.js.map +1 -0
  1784. package/dist/src/utils/skills.test.d.ts +1 -0
  1785. package/dist/src/utils/skills.test.js +45 -0
  1786. package/dist/src/utils/skills.test.js.map +1 -0
  1787. package/dist/src/utils/slugify.d.ts +1 -0
  1788. package/dist/src/utils/slugify.js +10 -0
  1789. package/dist/src/utils/slugify.js.map +1 -0
  1790. package/dist/src/utils/subagent-display.js.map +1 -0
  1791. package/dist/src/utils/subagent-display.test.d.ts +1 -0
  1792. package/dist/src/utils/subagent-display.test.js +21 -0
  1793. package/dist/src/utils/subagent-display.test.js.map +1 -0
  1794. package/dist/src/utils/subagents-settings.test.d.ts +1 -0
  1795. package/dist/src/utils/subagents-settings.test.js +58 -0
  1796. package/dist/src/utils/subagents-settings.test.js.map +1 -0
  1797. package/dist/src/utils/telegram-audio-settings.test.d.ts +1 -0
  1798. package/dist/src/utils/telegram-audio-settings.test.js +39 -0
  1799. package/dist/src/utils/telegram-audio-settings.test.js.map +1 -0
  1800. package/dist/src/utils/update-checker.js +22 -0
  1801. package/dist/src/utils/update-checker.js.map +1 -0
  1802. package/dist/src/utils/update-checker.test.d.ts +1 -0
  1803. package/dist/src/utils/update-checker.test.js +125 -0
  1804. package/dist/src/utils/update-checker.test.js.map +1 -0
  1805. package/dist/src/utils/visible-retry.d.ts +20 -0
  1806. package/dist/src/utils/visible-retry.js +34 -0
  1807. package/dist/src/utils/visible-retry.js.map +1 -0
  1808. package/dist/src/verify/__tests__/coverage-parsers.test.d.ts +1 -0
  1809. package/dist/src/verify/__tests__/coverage-parsers.test.js +69 -0
  1810. package/dist/src/verify/__tests__/coverage-parsers.test.js.map +1 -0
  1811. package/dist/src/verify/__tests__/dotnet-recipe.test.d.ts +10 -0
  1812. package/dist/src/verify/__tests__/dotnet-recipe.test.js +70 -0
  1813. package/dist/src/verify/__tests__/dotnet-recipe.test.js.map +1 -0
  1814. package/dist/src/verify/checkpoint.d.ts +11 -0
  1815. package/dist/src/verify/checkpoint.js.map +1 -0
  1816. package/dist/src/verify/checkpoint.test.d.ts +1 -0
  1817. package/dist/src/verify/checkpoint.test.js +160 -0
  1818. package/dist/src/verify/checkpoint.test.js.map +1 -0
  1819. package/dist/src/verify/coverage-parsers.d.ts +29 -0
  1820. package/dist/src/verify/coverage-parsers.js +72 -0
  1821. package/dist/src/verify/coverage-parsers.js.map +1 -0
  1822. package/dist/src/verify/entrypoint.d.ts +30 -0
  1823. package/dist/src/verify/entrypoint.js +349 -0
  1824. package/dist/src/verify/entrypoint.js.map +1 -0
  1825. package/dist/src/verify/entrypoint.test.d.ts +1 -0
  1826. package/dist/src/verify/entrypoint.test.js +233 -0
  1827. package/dist/src/verify/entrypoint.test.js.map +1 -0
  1828. package/dist/src/verify/environment.d.ts +9 -0
  1829. package/dist/src/verify/environment.js +116 -0
  1830. package/dist/src/verify/environment.js.map +1 -0
  1831. package/dist/src/verify/environment.test.d.ts +1 -0
  1832. package/dist/src/verify/environment.test.js +94 -0
  1833. package/dist/src/verify/environment.test.js.map +1 -0
  1834. package/dist/src/verify/evidence.d.ts +10 -0
  1835. package/dist/src/verify/evidence.js.map +1 -0
  1836. package/dist/src/verify/orchestrator.d.ts +25 -0
  1837. package/dist/src/verify/orchestrator.js +87 -0
  1838. package/dist/src/verify/orchestrator.js.map +1 -0
  1839. package/dist/src/verify/orchestrator.test.d.ts +1 -0
  1840. package/dist/src/verify/orchestrator.test.js +126 -0
  1841. package/dist/src/verify/orchestrator.test.js.map +1 -0
  1842. package/dist/src/verify/recipes.d.ts +22 -0
  1843. package/dist/src/verify/recipes.js +528 -0
  1844. package/dist/src/verify/recipes.js.map +1 -0
  1845. package/dist/src/verify/retry.d.ts +4 -0
  1846. package/dist/src/verify/retry.js.map +1 -0
  1847. package/dist/src/verify/runtime-prep.test.d.ts +1 -0
  1848. package/dist/src/verify/runtime-prep.test.js +38 -0
  1849. package/dist/src/verify/runtime-prep.test.js.map +1 -0
  1850. package/package.json +38 -10
  1851. package/src/__test-stubs__/vitest-setup.ts +36 -0
  1852. package/src/__tests__/council/bubble-layout.test.ts +45 -0
  1853. package/src/__tests__/council/code-block-truncate.test.ts +50 -0
  1854. package/src/__tests__/council/role-palette.test.ts +66 -0
  1855. package/src/__tests__/first-run-wizard.test.ts +9 -0
  1856. package/src/agent-harness/__tests__/cli-flags.spec.ts +35 -0
  1857. package/src/agent-harness/__tests__/driver.spec.ts +154 -0
  1858. package/src/agent-harness/__tests__/idle.spec.ts +90 -0
  1859. package/src/agent-harness/__tests__/mock-llm.spec.ts +126 -0
  1860. package/src/agent-harness/__tests__/mock-model.spec.ts +195 -0
  1861. package/src/agent-harness/__tests__/predicate.spec.ts +33 -0
  1862. package/src/agent-harness/__tests__/protocol.spec.ts +62 -0
  1863. package/src/agent-harness/__tests__/schema.spec.ts +81 -0
  1864. package/src/agent-harness/__tests__/selector.spec.ts +82 -0
  1865. package/src/agent-harness/__tests__/sidechannel.spec.ts +40 -0
  1866. package/src/agent-harness/__tests__/spec-helpers.spec.ts +76 -0
  1867. package/src/agent-harness/index.ts +24 -0
  1868. package/src/agent-harness/mock-model.ts +394 -0
  1869. package/src/agent-harness/test-spawn.ts +200 -0
  1870. package/src/chat/__tests__/broadcast-bus.test.ts +90 -0
  1871. package/src/chat/__tests__/channel-manager.test.ts +149 -0
  1872. package/src/chat/__tests__/client.test.ts +118 -0
  1873. package/src/chat/__tests__/discord-integration.test.ts +162 -0
  1874. package/src/chat/__tests__/intent-prompt.test.ts +92 -0
  1875. package/src/chat/__tests__/verdict-resolver.test.ts +336 -0
  1876. package/src/chat/broadcast-bus.ts +53 -0
  1877. package/src/chat/channel-manager.ts +146 -0
  1878. package/src/chat/chat-keychain.ts +129 -0
  1879. package/src/chat/factory.ts +37 -0
  1880. package/src/chat/intent-prompt.ts +72 -0
  1881. package/src/chat/providers/discord/client.ts +91 -0
  1882. package/src/chat/types.ts +42 -0
  1883. package/src/chat/verdict-constants.ts +26 -0
  1884. package/src/chat/verdict-resolver.ts +231 -0
  1885. package/src/cli/__tests__/bw-vault.test.ts +97 -0
  1886. package/src/cli/__tests__/keys-bundle.test.ts +46 -0
  1887. package/src/cli/__tests__/share-cmd.test.ts +197 -0
  1888. package/src/cli/bw-vault.ts +184 -0
  1889. package/src/cli/config/__tests__/model-picker.test.ts +59 -0
  1890. package/src/cli/config/__tests__/provider-fetch.test.ts +38 -0
  1891. package/src/cli/config/index.ts +112 -0
  1892. package/src/cli/config/model-picker.ts +193 -0
  1893. package/src/cli/config/provider-fetch.ts +75 -0
  1894. package/src/cli/config/screen-council.ts +245 -0
  1895. package/src/cli/config/screen-models.ts +104 -0
  1896. package/src/cli/config/screen-providers.ts +197 -0
  1897. package/src/cli/config/tui.ts +153 -0
  1898. package/src/cli/cost-forensics.test.ts +128 -0
  1899. package/src/cli/cost-forensics.ts +264 -0
  1900. package/src/cli/keys-bundle.ts +91 -0
  1901. package/src/cli/keys.test.ts +104 -0
  1902. package/src/cli/keys.ts +787 -0
  1903. package/src/cli/pil-report.ts +202 -0
  1904. package/src/cli/share-cmd.ts +132 -0
  1905. package/src/cli/usage-report.ts +266 -0
  1906. package/src/council/__tests__/accounting.test.ts +72 -0
  1907. package/src/council/__tests__/audit-replay.test.ts +344 -0
  1908. package/src/council/__tests__/clarifier-max-rounds.test.ts +91 -0
  1909. package/src/council/__tests__/clarifier-options.test.ts +63 -0
  1910. package/src/council/__tests__/cost-aware.test.ts +60 -0
  1911. package/src/council/__tests__/debate-planner-structured.test.ts +236 -0
  1912. package/src/council/__tests__/evaluator-metrics.test.ts +513 -0
  1913. package/src/council/__tests__/parse-outcome-fallback.test.ts +125 -0
  1914. package/src/council/__tests__/research-tools.test.ts +239 -0
  1915. package/src/council/__tests__/round-tools.test.ts +334 -0
  1916. package/src/council/__tests__/tool-trace.test.ts +152 -0
  1917. package/src/council/__tests__/types-contract.test.ts +88 -0
  1918. package/src/council/clarifier.ts +409 -0
  1919. package/src/council/context.ts +250 -0
  1920. package/src/council/debate-planner.ts +264 -0
  1921. package/src/council/debate.ts +1179 -0
  1922. package/src/council/executor.ts +27 -0
  1923. package/src/council/index.ts +916 -0
  1924. package/src/council/leader.ts +262 -0
  1925. package/src/council/llm.ts +967 -0
  1926. package/src/council/phase-events.ts +58 -0
  1927. package/src/council/planner.ts +303 -0
  1928. package/src/council/preflight.ts +86 -0
  1929. package/src/council/prompts.ts +600 -0
  1930. package/src/council/types.ts +286 -0
  1931. package/src/daemon/scheduler.ts +1 -1
  1932. package/src/ee/__tests__/bb-design.test.ts +223 -0
  1933. package/src/ee/__tests__/pil-context-bridge.test.ts +59 -0
  1934. package/src/ee/__tests__/pipeline.integration.test.ts +6 -6
  1935. package/src/ee/__tests__/render-sink-wiring.test.ts +89 -0
  1936. package/src/ee/auth.ts +21 -0
  1937. package/src/ee/bb-design.ts +284 -0
  1938. package/src/ee/bb-retrieval.ts +467 -0
  1939. package/src/ee/bridge.test.ts +1 -8
  1940. package/src/ee/bridge.ts +201 -12
  1941. package/src/ee/client-mode.ts +161 -0
  1942. package/src/ee/client.test.ts +171 -171
  1943. package/src/ee/client.ts +127 -19
  1944. package/src/ee/council-bridge.ts +89 -0
  1945. package/src/ee/extract-session.test.ts +3 -8
  1946. package/src/ee/extract-session.ts +4 -2
  1947. package/src/ee/health.ts +1 -1
  1948. package/src/ee/index.ts +11 -10
  1949. package/src/ee/intercept.test.ts +197 -191
  1950. package/src/ee/intercept.ts +13 -2
  1951. package/src/ee/judge.test.ts +56 -0
  1952. package/src/ee/judge.ts +59 -1
  1953. package/src/ee/mistake-detector.test.ts +252 -0
  1954. package/src/ee/mistake-detector.ts +297 -0
  1955. package/src/ee/offline-queue.test.ts +14 -63
  1956. package/src/ee/offline-queue.ts +2 -9
  1957. package/src/ee/phase-outcome.test.ts +107 -0
  1958. package/src/ee/phase-outcome.ts +165 -0
  1959. package/src/ee/phase-tracker.test.ts +175 -0
  1960. package/src/ee/phase-tracker.ts +180 -0
  1961. package/src/ee/prompt-stale.test.ts +6 -1
  1962. package/src/ee/render.test.ts +7 -4
  1963. package/src/ee/render.ts +25 -4
  1964. package/src/ee/session-trajectory.test.ts +139 -0
  1965. package/src/ee/session-trajectory.ts +226 -0
  1966. package/src/ee/touch.test.ts +73 -71
  1967. package/src/ee/types.ts +72 -7
  1968. package/src/flow/__tests__/run-manager-product.test.ts +59 -0
  1969. package/src/flow/__tests__/scaffold-checkpoint.test.ts +113 -0
  1970. package/src/flow/run-manager.ts +35 -2
  1971. package/src/flow/scaffold-checkpoint.ts +132 -0
  1972. package/src/generated/version.ts +4 -0
  1973. package/src/gsd/__tests__/complexity.test.ts +0 -0
  1974. package/src/gsd/__tests__/directives.test.ts +49 -0
  1975. package/src/gsd/__tests__/gray-areas.test.ts +33 -0
  1976. package/src/gsd/complexity.ts +124 -0
  1977. package/src/gsd/directives.ts +94 -0
  1978. package/src/gsd/gray-areas.ts +144 -0
  1979. package/src/gsd/types.ts +2 -0
  1980. package/src/headless/__tests__/council-answers.test.ts +266 -0
  1981. package/src/headless/council-answers.ts +130 -0
  1982. package/src/headless/output.ts +1 -1
  1983. package/src/hooks/index.ts +316 -19
  1984. package/src/hooks/types.ts +42 -0
  1985. package/src/index.ts +1564 -677
  1986. package/src/lsp/client.ts +1 -1
  1987. package/src/lsp/smoke.test.ts +15 -13
  1988. package/src/mcp/__tests__/auto-setup.test.ts +88 -0
  1989. package/src/mcp/__tests__/harness-driver-action-tools.spec.ts +114 -0
  1990. package/src/mcp/__tests__/harness-driver-async-tools.spec.ts +127 -0
  1991. package/src/mcp/__tests__/harness-driver-read-tools.spec.ts +140 -0
  1992. package/src/mcp/__tests__/harness-driver-security.spec.ts +71 -0
  1993. package/src/mcp/__tests__/harness-driver.spec.ts +21 -0
  1994. package/src/mcp/__tests__/lazy-schema.spec.ts +173 -0
  1995. package/src/mcp/__tests__/mcp-keychain.test.ts +46 -0
  1996. package/src/mcp/__tests__/research-onboarding.test.ts +163 -0
  1997. package/src/mcp/__tests__/runtime-hydration.test.ts +86 -0
  1998. package/src/mcp/__tests__/runtime-sanitize.test.ts +44 -0
  1999. package/src/mcp/auto-setup.ts +26 -7
  2000. package/src/mcp/catalog.ts +31 -14
  2001. package/src/mcp/mcp-keychain.ts +77 -0
  2002. package/src/mcp/oauth-callback.ts +18 -6
  2003. package/src/mcp/oauth-provider.ts +1 -3
  2004. package/src/mcp/opentui-spawn.ts +64 -0
  2005. package/src/mcp/research-onboarding.ts +143 -0
  2006. package/src/mcp/runtime.ts +85 -27
  2007. package/src/models/__tests__/registry.test.ts +11 -11
  2008. package/src/models/catalog-client.ts +2 -2
  2009. package/src/models/catalog.README.md +136 -0
  2010. package/src/models/catalog.json +108 -245
  2011. package/src/models/classify-tier.ts +20 -9
  2012. package/src/models/registry.ts +5 -1
  2013. package/src/ops/__tests__/doctor-council-mcp.test.ts +161 -0
  2014. package/src/ops/__tests__/doctor-ee-health.test.ts +129 -0
  2015. package/src/ops/doctor.test.ts +6 -5
  2016. package/src/ops/doctor.ts +207 -13
  2017. package/src/orchestrator/__tests__/batch-turn-runner.test.ts +178 -0
  2018. package/src/orchestrator/__tests__/council-manager.test.ts +171 -0
  2019. package/src/orchestrator/__tests__/cross-turn-dedup.test.ts +174 -0
  2020. package/src/orchestrator/__tests__/current-call-id.test.ts +160 -0
  2021. package/src/orchestrator/__tests__/message-processor.test.ts +196 -0
  2022. package/src/orchestrator/__tests__/message-write-ahead.test.ts +170 -0
  2023. package/src/orchestrator/__tests__/read-path-budget.test.ts +107 -0
  2024. package/src/orchestrator/__tests__/retry-classifier.test.ts +120 -0
  2025. package/src/orchestrator/__tests__/retry-stream.test.ts +186 -0
  2026. package/src/orchestrator/__tests__/route-feedback.test.ts +1 -1
  2027. package/src/orchestrator/__tests__/stream-runner.test.ts +123 -0
  2028. package/src/orchestrator/__tests__/usage-events-shape.test.ts +80 -0
  2029. package/src/orchestrator/__tests__/usage-normalizer-c1.test.ts +172 -0
  2030. package/src/orchestrator/__tests__/write-ahead.test.ts +162 -0
  2031. package/src/orchestrator/agent-options.ts +168 -0
  2032. package/src/orchestrator/agent.test.ts +47 -1
  2033. package/src/orchestrator/batch-turn-runner.ts +425 -0
  2034. package/src/orchestrator/batch-utils.ts +340 -0
  2035. package/src/orchestrator/cleanup.test.ts +3 -5
  2036. package/src/orchestrator/compaction.test.ts +50 -3
  2037. package/src/orchestrator/compaction.ts +178 -52
  2038. package/src/orchestrator/council-manager.ts +580 -0
  2039. package/src/orchestrator/cross-turn-dedup.ts +187 -0
  2040. package/src/orchestrator/error-utils.ts +72 -0
  2041. package/src/orchestrator/flow-resume.ts +0 -1
  2042. package/src/orchestrator/message-processor.ts +1985 -0
  2043. package/src/orchestrator/message-seq.test.ts +29 -0
  2044. package/src/orchestrator/message-seq.ts +19 -0
  2045. package/src/orchestrator/orchestrator.ts +1244 -2593
  2046. package/src/orchestrator/prompts.ts +482 -0
  2047. package/src/orchestrator/provider-options-shape.spec.ts +67 -0
  2048. package/src/orchestrator/provider-options-shape.ts +70 -0
  2049. package/src/orchestrator/read-path-budget.ts +128 -0
  2050. package/src/orchestrator/reasoning.ts +5 -0
  2051. package/src/orchestrator/retry-classifier.ts +131 -0
  2052. package/src/orchestrator/retry-stream.ts +159 -0
  2053. package/src/orchestrator/sandbox.test.ts +1 -1
  2054. package/src/orchestrator/stream-runner.ts +729 -0
  2055. package/src/orchestrator/sub-agent-cap.test.ts +186 -0
  2056. package/src/orchestrator/sub-agent-cap.ts +218 -0
  2057. package/src/orchestrator/subagent-compactor.spec.ts +144 -0
  2058. package/src/orchestrator/subagent-compactor.ts +242 -0
  2059. package/src/orchestrator/token-counter.test.ts +69 -0
  2060. package/src/orchestrator/token-counter.ts +81 -0
  2061. package/src/orchestrator/tool-utils.ts +214 -0
  2062. package/src/orchestrator/turn-runner-deps.ts +83 -0
  2063. package/src/pil/__tests__/config.test.ts +32 -0
  2064. package/src/pil/__tests__/dual-run.test.ts +53 -0
  2065. package/src/pil/__tests__/layer1-intent-trace.test.ts +140 -0
  2066. package/src/pil/__tests__/layer1-intent.test.ts +130 -27
  2067. package/src/pil/__tests__/layer3-ee-injection.test.ts +94 -30
  2068. package/src/pil/__tests__/layer3-injected-chunk.test.ts +122 -0
  2069. package/src/pil/__tests__/layer4-gsd.test.ts +56 -23
  2070. package/src/pil/__tests__/layer5-context.test.ts +41 -0
  2071. package/src/pil/__tests__/layer6-output.test.ts +154 -9
  2072. package/src/pil/__tests__/ollama-classify.test.ts +81 -81
  2073. package/src/pil/__tests__/pipeline.test.ts +19 -2
  2074. package/src/pil/__tests__/renderer-coverage.test.ts +46 -0
  2075. package/src/pil/__tests__/response-tools.test.ts +12 -3
  2076. package/src/pil/__tests__/schema.test.ts +109 -4
  2077. package/src/pil/__tests__/scoreComplexity.test.ts +134 -0
  2078. package/src/pil/__tests__/scoreSufficiency.test.ts +104 -0
  2079. package/src/pil/budget-log.ts +86 -0
  2080. package/src/pil/config.ts +11 -0
  2081. package/src/pil/index.ts +1 -1
  2082. package/src/pil/layer1-intent.test.ts +127 -0
  2083. package/src/pil/layer1-intent.ts +468 -43
  2084. package/src/pil/layer2-personality.ts +9 -0
  2085. package/src/pil/layer3-ee-injection.ts +298 -32
  2086. package/src/pil/layer4-gsd.ts +73 -32
  2087. package/src/pil/layer5-context.ts +53 -18
  2088. package/src/pil/layer6-output.ts +157 -10
  2089. package/src/pil/pipeline.ts +114 -19
  2090. package/src/pil/response-tools.ts +2 -2
  2091. package/src/pil/schema.ts +56 -2
  2092. package/src/pil/types.ts +110 -2
  2093. package/src/product-loop/__tests__/artifact-io.test.ts +97 -0
  2094. package/src/product-loop/__tests__/assumption-ledger.test.ts +292 -0
  2095. package/src/product-loop/__tests__/cb2-retry-bonus.test.ts +182 -0
  2096. package/src/product-loop/__tests__/circuit-breakers-coverage.test.ts +82 -0
  2097. package/src/product-loop/__tests__/circuit-breakers.test.ts +90 -0
  2098. package/src/product-loop/__tests__/complexity-routing.spec.ts +169 -0
  2099. package/src/product-loop/__tests__/context-policy.test.ts +280 -0
  2100. package/src/product-loop/__tests__/cost-preview.test.ts +118 -0
  2101. package/src/product-loop/__tests__/cost-scoper.test.ts +76 -0
  2102. package/src/product-loop/__tests__/cross-run-memory.test.ts +195 -0
  2103. package/src/product-loop/__tests__/design-output.spec.ts +39 -0
  2104. package/src/product-loop/__tests__/discover.test.ts +98 -0
  2105. package/src/product-loop/__tests__/discovery-council-runner.test.ts +13 -0
  2106. package/src/product-loop/__tests__/discovery-detection.test.ts +180 -0
  2107. package/src/product-loop/__tests__/discovery-ecosystem.test.ts +132 -0
  2108. package/src/product-loop/__tests__/discovery-integration.test.ts +133 -0
  2109. package/src/product-loop/__tests__/discovery-interview.test.ts +305 -0
  2110. package/src/product-loop/__tests__/discovery-migrations.test.ts +75 -0
  2111. package/src/product-loop/__tests__/discovery-persistence.test.ts +171 -0
  2112. package/src/product-loop/__tests__/discovery-prompt-parser.test.ts +77 -0
  2113. package/src/product-loop/__tests__/discovery-recommender-ecosystem.test.ts +94 -0
  2114. package/src/product-loop/__tests__/discovery-recommender.test.ts +382 -0
  2115. package/src/product-loop/__tests__/discovery-schema.test.ts +102 -0
  2116. package/src/product-loop/__tests__/done-gate-coverage.test.ts +151 -0
  2117. package/src/product-loop/__tests__/done-gate.test.ts +140 -0
  2118. package/src/product-loop/__tests__/ee-extract-wiring.test.ts +216 -0
  2119. package/src/product-loop/__tests__/extract-to-ee.test.ts +205 -0
  2120. package/src/product-loop/__tests__/feedback-routing.test.ts +93 -0
  2121. package/src/product-loop/__tests__/hot-path.spec.ts +177 -0
  2122. package/src/product-loop/__tests__/integration.test.ts +344 -0
  2123. package/src/product-loop/__tests__/loop-driver-audit.test.ts +321 -0
  2124. package/src/product-loop/__tests__/loop-driver.test.ts +247 -0
  2125. package/src/product-loop/__tests__/phase-budget.test.ts +172 -0
  2126. package/src/product-loop/__tests__/phase-orchestrator-integration.test.ts +143 -0
  2127. package/src/product-loop/__tests__/phase-plan.test.ts +241 -0
  2128. package/src/product-loop/__tests__/phase-rituals.test.ts +211 -0
  2129. package/src/product-loop/__tests__/phase-runner.test.ts +454 -0
  2130. package/src/product-loop/__tests__/phase-tracker-bridge.test.ts +85 -0
  2131. package/src/product-loop/__tests__/product-identity.test.ts +47 -0
  2132. package/src/product-loop/__tests__/reality-anchor.test.ts +58 -0
  2133. package/src/product-loop/__tests__/repo-audit.test.ts +103 -0
  2134. package/src/product-loop/__tests__/role-memory.test.ts +70 -0
  2135. package/src/product-loop/__tests__/role-registry.test.ts +235 -0
  2136. package/src/product-loop/__tests__/role-routing-ee.test.ts +90 -0
  2137. package/src/product-loop/__tests__/route-decision-emit.test.ts +207 -0
  2138. package/src/product-loop/__tests__/seed-questions.test.ts +33 -0
  2139. package/src/product-loop/__tests__/ship-polish.test.ts +109 -0
  2140. package/src/product-loop/__tests__/sprint-runner-emit.test.ts +324 -0
  2141. package/src/product-loop/__tests__/sprint-runner.test.ts +501 -0
  2142. package/src/product-loop/__tests__/stakeholder-acl.test.ts +94 -0
  2143. package/src/product-loop/__tests__/state-md-ee-injections.test.ts +229 -0
  2144. package/src/product-loop/__tests__/sufficiency-routing.spec.ts +177 -0
  2145. package/src/product-loop/__tests__/typed-artifacts.test.ts +261 -0
  2146. package/src/product-loop/__tests__/types.test.ts +103 -0
  2147. package/src/product-loop/__tests__/verify-failure-threshold.test.ts +177 -0
  2148. package/src/product-loop/__tests__/verify-failure-tracking.test.ts +154 -0
  2149. package/src/product-loop/__tests__/verify-result.test.ts +60 -0
  2150. package/src/product-loop/artifact-io.ts +239 -0
  2151. package/src/product-loop/assumption-ledger.ts +270 -0
  2152. package/src/product-loop/circuit-breakers.ts +76 -0
  2153. package/src/product-loop/context-policy.ts +180 -0
  2154. package/src/product-loop/cost-preview.ts +124 -0
  2155. package/src/product-loop/cost-scoper.ts +49 -0
  2156. package/src/product-loop/cross-run-memory.ts +450 -0
  2157. package/src/product-loop/design-output.ts +24 -0
  2158. package/src/product-loop/discover.ts +159 -0
  2159. package/src/product-loop/discovery-context-format.ts +32 -0
  2160. package/src/product-loop/discovery-council-runner.ts +82 -0
  2161. package/src/product-loop/discovery-detection.ts +161 -0
  2162. package/src/product-loop/discovery-ecosystem.ts +124 -0
  2163. package/src/product-loop/discovery-interview.ts +237 -0
  2164. package/src/product-loop/discovery-migrations.ts +40 -0
  2165. package/src/product-loop/discovery-persistence.ts +219 -0
  2166. package/src/product-loop/discovery-prompt-parser.ts +80 -0
  2167. package/src/product-loop/discovery-recommender.ts +366 -0
  2168. package/src/product-loop/discovery-schema.ts +143 -0
  2169. package/src/product-loop/done-gate.ts +224 -0
  2170. package/src/product-loop/feedback-routing.ts +82 -0
  2171. package/src/product-loop/gather.ts +304 -0
  2172. package/src/product-loop/index.ts +1305 -0
  2173. package/src/product-loop/loop-driver.ts +901 -0
  2174. package/src/product-loop/phase-budget.ts +182 -0
  2175. package/src/product-loop/phase-plan.ts +158 -0
  2176. package/src/product-loop/phase-rituals.ts +158 -0
  2177. package/src/product-loop/phase-runner.ts +455 -0
  2178. package/src/product-loop/phase-tracker-bridge.ts +60 -0
  2179. package/src/product-loop/product-identity.ts +11 -0
  2180. package/src/product-loop/reality-anchor.ts +45 -0
  2181. package/src/product-loop/repo-audit.ts +314 -0
  2182. package/src/product-loop/role-memory.ts +72 -0
  2183. package/src/product-loop/role-registry.ts +175 -0
  2184. package/src/product-loop/seed-questions.ts +51 -0
  2185. package/src/product-loop/ship-polish.ts +164 -0
  2186. package/src/product-loop/sprint-runner.ts +610 -0
  2187. package/src/product-loop/stakeholder-acl.ts +82 -0
  2188. package/src/product-loop/typed-artifacts.ts +332 -0
  2189. package/src/product-loop/types.ts +443 -0
  2190. package/src/product-loop/verify-failure-tracking.ts +225 -0
  2191. package/src/product-loop/verify-result.ts +39 -0
  2192. package/src/providers/__tests__/adapter-oauth-wiring.test.ts +129 -0
  2193. package/src/providers/__tests__/capabilities-cosmetic.test.ts +119 -0
  2194. package/src/providers/__tests__/capabilities-flags.test.ts +166 -0
  2195. package/src/providers/__tests__/capabilities-provider-options.test.ts +203 -0
  2196. package/src/providers/__tests__/capabilities-sanitize.test.ts +82 -0
  2197. package/src/providers/__tests__/capabilities.test.ts +44 -0
  2198. package/src/providers/__tests__/provider-coverage.test.ts +48 -0
  2199. package/src/providers/__tests__/runtime-integration.test.ts +41 -24
  2200. package/src/providers/__tests__/runtime.test.ts +23 -13
  2201. package/src/providers/__tests__/siliconflow-history.test.ts +82 -0
  2202. package/src/providers/__tests__/strategies-registry.test.ts +55 -0
  2203. package/src/providers/__tests__/strategies-resolve.test.ts +137 -0
  2204. package/src/providers/__tests__/wire-debug.test.ts +42 -0
  2205. package/src/providers/adapter.ts +135 -27
  2206. package/src/providers/anthropic.ts +7 -2
  2207. package/src/providers/auth/__tests__/browser-flow.test.ts +235 -0
  2208. package/src/providers/auth/__tests__/device-flow.test.ts +263 -0
  2209. package/src/providers/auth/__tests__/gemini-oauth.test.ts +387 -0
  2210. package/src/providers/auth/__tests__/openai-oauth.test.ts +378 -0
  2211. package/src/providers/auth/__tests__/token-store.test.ts +152 -0
  2212. package/src/providers/auth/browser-flow.ts +140 -0
  2213. package/src/providers/auth/device-flow.ts +221 -0
  2214. package/src/providers/auth/gemini-oauth.ts +351 -0
  2215. package/src/providers/auth/openai-oauth.ts +455 -0
  2216. package/src/providers/auth/registry.ts +121 -0
  2217. package/src/providers/auth/token-store.ts +154 -0
  2218. package/src/providers/auth/types.ts +111 -0
  2219. package/src/providers/capabilities.ts +351 -0
  2220. package/src/providers/endpoints.ts +68 -0
  2221. package/src/providers/gemini.ts +7 -2
  2222. package/src/providers/index.ts +5 -9
  2223. package/src/providers/keychain.test.ts +5 -0
  2224. package/src/providers/keychain.ts +137 -3
  2225. package/src/providers/mcp-vision-bridge.test.ts +513 -0
  2226. package/src/providers/mcp-vision-bridge.ts +1020 -0
  2227. package/src/providers/openai-compatible.test.ts +2 -2
  2228. package/src/providers/openai-compatible.ts +16 -8
  2229. package/src/providers/openai.ts +21 -2
  2230. package/src/providers/patch-zod-schema.ts +10 -13
  2231. package/src/providers/pricing.test.ts +11 -2
  2232. package/src/providers/pricing.ts +66 -10
  2233. package/src/providers/prompt-cache-key.spec.ts +28 -0
  2234. package/src/providers/runtime-mock.spec.ts +86 -0
  2235. package/src/providers/runtime.ts +227 -55
  2236. package/src/providers/siliconflow-history.ts +74 -0
  2237. package/src/providers/strategies/anthropic.strategy.ts +25 -0
  2238. package/src/providers/strategies/base.strategy.ts +76 -0
  2239. package/src/providers/strategies/deepseek.strategy.ts +26 -0
  2240. package/src/providers/strategies/google.strategy.ts +28 -0
  2241. package/src/providers/strategies/ollama.strategy.ts +22 -0
  2242. package/src/providers/strategies/openai.strategy.ts +55 -0
  2243. package/src/providers/strategies/registry.ts +43 -0
  2244. package/src/providers/strategies/siliconflow.strategy.ts +26 -0
  2245. package/src/providers/strategies/xai.strategy.ts +26 -0
  2246. package/src/providers/stream-loop.ts +15 -1
  2247. package/src/providers/types.ts +34 -0
  2248. package/src/providers/vision-proxy.test.ts +96 -11
  2249. package/src/providers/vision-proxy.ts +153 -45
  2250. package/src/providers/wire-debug.ts +163 -0
  2251. package/src/router/__tests__/step-router.test.ts +150 -0
  2252. package/src/router/classifier/regex.test.ts +3 -1
  2253. package/src/router/classifier/regex.ts +71 -12
  2254. package/src/router/cold.test.ts +5 -5
  2255. package/src/router/decide.test.ts +17 -5
  2256. package/src/router/decide.ts +144 -26
  2257. package/src/router/provider-sentinel.test.ts +22 -0
  2258. package/src/router/provider-sentinel.ts +20 -0
  2259. package/src/router/step-router.ts +194 -0
  2260. package/src/router/warm.test.ts +3 -2
  2261. package/src/router/warm.ts +7 -1
  2262. package/src/scaffold/__tests__/continuation-prompt.test.ts +93 -0
  2263. package/src/scaffold/__tests__/continue-as-council.spec.ts +124 -0
  2264. package/src/scaffold/__tests__/dotnet-assembly-name.test.ts +28 -0
  2265. package/src/scaffold/__tests__/fe-scaffold-contents.test.ts +127 -0
  2266. package/src/scaffold/__tests__/init-new.smoke.spec.ts +99 -0
  2267. package/src/scaffold/__tests__/init-new.spec.ts +450 -0
  2268. package/src/scaffold/__tests__/install-bb-templates.spec.ts +86 -0
  2269. package/src/scaffold/__tests__/point-to-existing.spec.ts +114 -0
  2270. package/src/scaffold/bb-ecosystem-apply.ts +454 -0
  2271. package/src/scaffold/bb-quality-gate.ts +287 -0
  2272. package/src/scaffold/continuation-prompt.ts +80 -0
  2273. package/src/scaffold/continue-as-council.ts +99 -0
  2274. package/src/scaffold/init-new.ts +1691 -0
  2275. package/src/scaffold/point-to-existing.ts +83 -0
  2276. package/src/scaffold/resume-from-gate-failures.ts +167 -0
  2277. package/src/storage/__tests__/ui-interaction-log.test.ts +105 -0
  2278. package/src/storage/atomic-io.test.ts +32 -1
  2279. package/src/storage/atomic-io.ts +107 -9
  2280. package/src/storage/config.ts +5 -1
  2281. package/src/storage/db.ts +93 -4
  2282. package/src/storage/index.ts +8 -1
  2283. package/src/storage/interaction-log.ts +121 -0
  2284. package/src/storage/migrations.ts +66 -4
  2285. package/src/storage/sessions.ts +28 -0
  2286. package/src/storage/transcript.ts +207 -4
  2287. package/src/storage/ui-interaction-log.ts +160 -0
  2288. package/src/storage/usage.ts +4 -2
  2289. package/src/tools/bash.test.ts +27 -0
  2290. package/src/tools/bash.ts +60 -4
  2291. package/src/tools/file-tracker.test.ts +99 -0
  2292. package/src/tools/file-tracker.ts +70 -0
  2293. package/src/tools/file.ts +59 -5
  2294. package/src/tools/registry.test.ts +38 -0
  2295. package/src/tools/registry.ts +133 -27
  2296. package/src/types/index.ts +166 -3
  2297. package/src/ui/agents-modal.tsx +164 -144
  2298. package/src/ui/app.tsx +6464 -6277
  2299. package/src/ui/cards/__tests__/product-status-card.test.ts +30 -0
  2300. package/src/ui/cards/product-status-card.tsx +117 -0
  2301. package/src/ui/components/Toast.tsx +100 -0
  2302. package/src/ui/components/__tests__/council-leader-bubble.test.ts +16 -0
  2303. package/src/ui/components/__tests__/council-message-bubble.test.ts +85 -0
  2304. package/src/ui/components/__tests__/council-phase-timeline.test.ts +57 -0
  2305. package/src/ui/components/__tests__/council-placeholder-bubble.test.ts +16 -0
  2306. package/src/ui/components/__tests__/council-question-card.test.ts +133 -0
  2307. package/src/ui/components/__tests__/council-synthesis-banner.test.ts +12 -0
  2308. package/src/ui/components/__tests__/use-pair-quote-buffer.test.ts +41 -0
  2309. package/src/ui/components/bubble-layout.ts +66 -0
  2310. package/src/ui/components/code-block-truncate.ts +24 -0
  2311. package/src/ui/components/copy-flash-banner.tsx +31 -0
  2312. package/src/ui/components/council-info-card.tsx +45 -0
  2313. package/src/ui/components/council-leader-bubble.tsx +41 -0
  2314. package/src/ui/components/council-message-bubble.tsx +111 -0
  2315. package/src/ui/components/council-phase-timeline.tsx +91 -0
  2316. package/src/ui/components/council-placeholder-bubble.tsx +65 -0
  2317. package/src/ui/components/council-question-card.tsx +253 -0
  2318. package/src/ui/components/council-status-list.tsx +111 -0
  2319. package/src/ui/components/council-synthesis-banner.tsx +37 -0
  2320. package/src/ui/components/diff-view.tsx +225 -0
  2321. package/src/ui/components/halt-recovery-card.tsx +83 -0
  2322. package/src/ui/components/hero-logo.tsx +62 -0
  2323. package/src/ui/components/init-new-form-card.tsx +470 -0
  2324. package/src/ui/components/lsp-views.tsx +104 -0
  2325. package/src/ui/components/media-views.tsx +66 -0
  2326. package/src/ui/components/message-view.tsx +343 -0
  2327. package/src/ui/components/point-to-existing-form-card.tsx +136 -0
  2328. package/src/ui/components/prompt-box.tsx +306 -0
  2329. package/src/ui/components/role-palette.ts +62 -0
  2330. package/src/ui/components/session-header.tsx +68 -0
  2331. package/src/ui/components/slash-inline-menu.tsx +63 -0
  2332. package/src/ui/components/structured-response-view.tsx +191 -0
  2333. package/src/ui/components/tool-result-views.tsx +258 -0
  2334. package/src/ui/components/use-pair-quote-buffer.ts +23 -0
  2335. package/src/ui/constants.ts +242 -0
  2336. package/src/ui/hooks/use-agent-editor.ts +64 -0
  2337. package/src/ui/hooks/use-mcp-editor.ts +39 -0
  2338. package/src/ui/hooks/use-model-picker.ts +50 -0
  2339. package/src/ui/hooks/useTypeahead.ts +17 -3
  2340. package/src/ui/mcp-modal.tsx +306 -278
  2341. package/src/ui/modals/api-key-modal.tsx +99 -0
  2342. package/src/ui/modals/connect-modal.tsx +259 -0
  2343. package/src/ui/modals/model-picker-modal.tsx +323 -0
  2344. package/src/ui/modals/sandbox-picker-modal.tsx +99 -0
  2345. package/src/ui/modals/update-modal.tsx +67 -0
  2346. package/src/ui/modals/wallet-picker-modal.tsx +186 -0
  2347. package/src/ui/schedule-modal.tsx +75 -63
  2348. package/src/ui/slash/__tests__/ideal.test.ts +134 -0
  2349. package/src/ui/slash/__tests__/menu-parity.test.ts +43 -0
  2350. package/src/ui/slash/__tests__/optimize.test.ts +2 -2
  2351. package/src/ui/slash/__tests__/pin.test.ts +47 -0
  2352. package/src/ui/slash/cost.ts +7 -3
  2353. package/src/ui/slash/council-inspect.ts +188 -0
  2354. package/src/ui/slash/council.ts +11 -8
  2355. package/src/ui/slash/debug.ts +5 -5
  2356. package/src/ui/slash/ee.ts +43 -10
  2357. package/src/ui/slash/export.ts +281 -0
  2358. package/src/ui/slash/ideal.ts +254 -0
  2359. package/src/ui/slash/menu-items.ts +106 -0
  2360. package/src/ui/slash/optimize.ts +1 -1
  2361. package/src/ui/slash/pin.ts +41 -0
  2362. package/src/ui/slash/registry.ts +9 -0
  2363. package/src/ui/status-bar/index.tsx +22 -18
  2364. package/src/ui/status-bar/store.ts +19 -3
  2365. package/src/ui/syntax-highlight.ts +627 -0
  2366. package/src/ui/theme.ts +41 -0
  2367. package/src/ui/types.ts +83 -0
  2368. package/src/ui/utils/color.ts +19 -0
  2369. package/src/ui/utils/format.ts +86 -0
  2370. package/src/ui/utils/modal.ts +9 -0
  2371. package/src/ui/utils/text.ts +31 -0
  2372. package/src/ui/utils/tools.ts +95 -0
  2373. package/src/usage/__tests__/product-ledger.test.ts +85 -0
  2374. package/src/usage/cost-log.ts +158 -0
  2375. package/src/usage/decision-log.ts +86 -0
  2376. package/src/usage/estimator.ts +24 -0
  2377. package/src/usage/ledger.ts +40 -0
  2378. package/src/usage/product-ledger.ts +111 -0
  2379. package/src/usage/types.ts +1 -0
  2380. package/src/utils/__tests__/auto-council-settings.test.ts +46 -0
  2381. package/src/utils/__tests__/ee-logger.test.ts +197 -0
  2382. package/src/utils/__tests__/file-lock.test.ts +74 -0
  2383. package/src/utils/__tests__/rate-limit.test.ts +42 -0
  2384. package/src/utils/__tests__/settings-disabled-models.test.ts +113 -0
  2385. package/src/utils/__tests__/settings-web-research.test.ts +45 -0
  2386. package/src/utils/__tests__/slugify.test.ts +45 -0
  2387. package/src/utils/__tests__/visible-retry.test.ts +195 -0
  2388. package/src/utils/clipboard-image.ts +31 -11
  2389. package/src/utils/ee-logger.ts +163 -0
  2390. package/src/utils/file-lock.ts +66 -0
  2391. package/src/utils/host-clipboard.ts +38 -0
  2392. package/src/utils/instructions.test.ts +28 -0
  2393. package/src/utils/instructions.ts +37 -4
  2394. package/src/utils/rate-limit.ts +21 -0
  2395. package/src/utils/settings.test.ts +4 -4
  2396. package/src/utils/settings.ts +1108 -795
  2397. package/src/utils/shell.test.ts +72 -0
  2398. package/src/utils/shell.ts +193 -0
  2399. package/src/utils/slugify.ts +9 -0
  2400. package/src/utils/visible-retry.ts +56 -0
  2401. package/src/verify/__tests__/coverage-parsers.test.ts +86 -0
  2402. package/src/verify/__tests__/dotnet-recipe.test.ts +88 -0
  2403. package/src/verify/coverage-parsers.ts +76 -0
  2404. package/src/verify/recipes.ts +76 -0
  2405. package/dist/__test-stubs__/ee-server.js.map +0 -1
  2406. package/dist/billing/index.js.map +0 -1
  2407. package/dist/cloud/index.js.map +0 -1
  2408. package/dist/daemon/scheduler.d.ts +0 -15
  2409. package/dist/daemon/scheduler.js +0 -126
  2410. package/dist/daemon/scheduler.js.map +0 -1
  2411. package/dist/daemon/scheduler.test.js +0 -103
  2412. package/dist/daemon/scheduler.test.js.map +0 -1
  2413. package/dist/ee/__tests__/pipeline.integration.test.js +0 -151
  2414. package/dist/ee/__tests__/pipeline.integration.test.js.map +0 -1
  2415. package/dist/ee/auth.d.ts +0 -19
  2416. package/dist/ee/auth.js +0 -48
  2417. package/dist/ee/auth.js.map +0 -1
  2418. package/dist/ee/auth.test.js.map +0 -1
  2419. package/dist/ee/bridge.d.ts +0 -68
  2420. package/dist/ee/bridge.js +0 -177
  2421. package/dist/ee/bridge.js.map +0 -1
  2422. package/dist/ee/bridge.test.js.map +0 -1
  2423. package/dist/ee/client.js +0 -464
  2424. package/dist/ee/client.js.map +0 -1
  2425. package/dist/ee/client.test.js.map +0 -1
  2426. package/dist/ee/embedding-cache.js.map +0 -1
  2427. package/dist/ee/extract-session.js +0 -53
  2428. package/dist/ee/extract-session.js.map +0 -1
  2429. package/dist/ee/extract-session.test.js +0 -197
  2430. package/dist/ee/extract-session.test.js.map +0 -1
  2431. package/dist/ee/health.js +0 -64
  2432. package/dist/ee/health.js.map +0 -1
  2433. package/dist/ee/index.d.ts +0 -10
  2434. package/dist/ee/index.js +0 -9
  2435. package/dist/ee/index.js.map +0 -1
  2436. package/dist/ee/intercept.js +0 -117
  2437. package/dist/ee/intercept.js.map +0 -1
  2438. package/dist/ee/intercept.test.js +0 -170
  2439. package/dist/ee/intercept.test.js.map +0 -1
  2440. package/dist/ee/judge.d.ts +0 -36
  2441. package/dist/ee/judge.js +0 -56
  2442. package/dist/ee/judge.js.map +0 -1
  2443. package/dist/ee/judge.test.js +0 -139
  2444. package/dist/ee/judge.test.js.map +0 -1
  2445. package/dist/ee/offline-queue.js.map +0 -1
  2446. package/dist/ee/offline-queue.test.js +0 -246
  2447. package/dist/ee/offline-queue.test.js.map +0 -1
  2448. package/dist/ee/posttool.js.map +0 -1
  2449. package/dist/ee/posttool.test.js.map +0 -1
  2450. package/dist/ee/prompt-stale.js.map +0 -1
  2451. package/dist/ee/prompt-stale.test.js +0 -76
  2452. package/dist/ee/prompt-stale.test.js.map +0 -1
  2453. package/dist/ee/render.d.ts +0 -20
  2454. package/dist/ee/render.js +0 -30
  2455. package/dist/ee/render.js.map +0 -1
  2456. package/dist/ee/render.test.js +0 -61
  2457. package/dist/ee/render.test.js.map +0 -1
  2458. package/dist/ee/scope.js.map +0 -1
  2459. package/dist/ee/scope.test.js.map +0 -1
  2460. package/dist/ee/tenant.js.map +0 -1
  2461. package/dist/ee/touch.test.js +0 -60
  2462. package/dist/ee/touch.test.js.map +0 -1
  2463. package/dist/ee/types.d.ts +0 -300
  2464. package/dist/ee/types.js.map +0 -1
  2465. package/dist/flow/__tests__/migration.test.js.map +0 -1
  2466. package/dist/flow/__tests__/parser.test.js.map +0 -1
  2467. package/dist/flow/__tests__/run-manager.test.js.map +0 -1
  2468. package/dist/flow/__tests__/scaffold.test.js.map +0 -1
  2469. package/dist/flow/__tests__/warning-persist.test.js.map +0 -1
  2470. package/dist/flow/artifact-io.js.map +0 -1
  2471. package/dist/flow/compaction/__tests__/compress.test.js.map +0 -1
  2472. package/dist/flow/compaction/__tests__/extract.test.js.map +0 -1
  2473. package/dist/flow/compaction/__tests__/preserve.test.js.map +0 -1
  2474. package/dist/flow/compaction/compress.js.map +0 -1
  2475. package/dist/flow/compaction/extract.js.map +0 -1
  2476. package/dist/flow/compaction/index.js.map +0 -1
  2477. package/dist/flow/compaction/preserve.js.map +0 -1
  2478. package/dist/flow/index.js.map +0 -1
  2479. package/dist/flow/migration.js.map +0 -1
  2480. package/dist/flow/parser.js.map +0 -1
  2481. package/dist/flow/run-manager.d.ts +0 -36
  2482. package/dist/flow/run-manager.js +0 -110
  2483. package/dist/flow/run-manager.js.map +0 -1
  2484. package/dist/flow/scaffold.js.map +0 -1
  2485. package/dist/flow/warning-persist.js.map +0 -1
  2486. package/dist/gsd/__tests__/types.test.js +0 -65
  2487. package/dist/gsd/__tests__/types.test.js.map +0 -1
  2488. package/dist/gsd/index.js.map +0 -1
  2489. package/dist/gsd/types.d.ts +0 -4
  2490. package/dist/gsd/types.js.map +0 -1
  2491. package/dist/headless/output.d.ts +0 -68
  2492. package/dist/headless/output.js.map +0 -1
  2493. package/dist/headless/output.test.js +0 -178
  2494. package/dist/headless/output.test.js.map +0 -1
  2495. package/dist/hooks/config.js.map +0 -1
  2496. package/dist/hooks/index.d.ts +0 -44
  2497. package/dist/hooks/index.js +0 -187
  2498. package/dist/hooks/index.js.map +0 -1
  2499. package/dist/hooks/types.d.ts +0 -130
  2500. package/dist/hooks/types.js.map +0 -1
  2501. package/dist/index.d.ts +0 -2
  2502. package/dist/index.js +0 -531
  2503. package/dist/index.js.map +0 -1
  2504. package/dist/lsp/builtins.d.ts +0 -9
  2505. package/dist/lsp/builtins.js +0 -351
  2506. package/dist/lsp/builtins.js.map +0 -1
  2507. package/dist/lsp/builtins.test.js +0 -91
  2508. package/dist/lsp/builtins.test.js.map +0 -1
  2509. package/dist/lsp/client.d.ts +0 -20
  2510. package/dist/lsp/client.js +0 -290
  2511. package/dist/lsp/client.js.map +0 -1
  2512. package/dist/lsp/manager.d.ts +0 -20
  2513. package/dist/lsp/manager.js +0 -235
  2514. package/dist/lsp/manager.js.map +0 -1
  2515. package/dist/lsp/manager.test.js +0 -133
  2516. package/dist/lsp/manager.test.js.map +0 -1
  2517. package/dist/lsp/npm-cache.js.map +0 -1
  2518. package/dist/lsp/npm-cache.test.js +0 -53
  2519. package/dist/lsp/npm-cache.test.js.map +0 -1
  2520. package/dist/lsp/runtime.d.ts +0 -6
  2521. package/dist/lsp/runtime.js +0 -53
  2522. package/dist/lsp/runtime.js.map +0 -1
  2523. package/dist/lsp/smoke.test.js.map +0 -1
  2524. package/dist/lsp/types.js.map +0 -1
  2525. package/dist/mcp/auto-setup.js +0 -76
  2526. package/dist/mcp/auto-setup.js.map +0 -1
  2527. package/dist/mcp/catalog.js +0 -121
  2528. package/dist/mcp/catalog.js.map +0 -1
  2529. package/dist/mcp/oauth-callback.d.ts +0 -9
  2530. package/dist/mcp/oauth-callback.js +0 -49
  2531. package/dist/mcp/oauth-callback.js.map +0 -1
  2532. package/dist/mcp/oauth-provider.js.map +0 -1
  2533. package/dist/mcp/parse-headers.js.map +0 -1
  2534. package/dist/mcp/parse-headers.test.js +0 -43
  2535. package/dist/mcp/parse-headers.test.js.map +0 -1
  2536. package/dist/mcp/runtime.js +0 -81
  2537. package/dist/mcp/runtime.js.map +0 -1
  2538. package/dist/mcp/smoke.test.js.map +0 -1
  2539. package/dist/mcp/validate.d.ts +0 -9
  2540. package/dist/mcp/validate.js.map +0 -1
  2541. package/dist/models/__tests__/registry.test.js +0 -74
  2542. package/dist/models/__tests__/registry.test.js.map +0 -1
  2543. package/dist/models/catalog-client.js +0 -104
  2544. package/dist/models/catalog-client.js.map +0 -1
  2545. package/dist/models/catalog.json +0 -314
  2546. package/dist/models/classify-tier.js +0 -34
  2547. package/dist/models/classify-tier.js.map +0 -1
  2548. package/dist/models/index.d.ts +0 -1
  2549. package/dist/models/index.js +0 -2
  2550. package/dist/models/index.js.map +0 -1
  2551. package/dist/models/registry.d.ts +0 -19
  2552. package/dist/models/registry.js +0 -65
  2553. package/dist/models/registry.js.map +0 -1
  2554. package/dist/ops/bug-report.js.map +0 -1
  2555. package/dist/ops/bug-report.test.js.map +0 -1
  2556. package/dist/ops/doctor.js +0 -162
  2557. package/dist/ops/doctor.js.map +0 -1
  2558. package/dist/ops/doctor.test.js +0 -95
  2559. package/dist/ops/doctor.test.js.map +0 -1
  2560. package/dist/orchestrator/__tests__/flow-resume.test.js.map +0 -1
  2561. package/dist/orchestrator/__tests__/route-feedback.test.js +0 -47
  2562. package/dist/orchestrator/__tests__/route-feedback.test.js.map +0 -1
  2563. package/dist/orchestrator/abort.js.map +0 -1
  2564. package/dist/orchestrator/abort.test.js.map +0 -1
  2565. package/dist/orchestrator/agent.test.js +0 -126
  2566. package/dist/orchestrator/agent.test.js.map +0 -1
  2567. package/dist/orchestrator/cleanup.test.js +0 -67
  2568. package/dist/orchestrator/cleanup.test.js.map +0 -1
  2569. package/dist/orchestrator/compaction.d.ts +0 -36
  2570. package/dist/orchestrator/compaction.js +0 -375
  2571. package/dist/orchestrator/compaction.js.map +0 -1
  2572. package/dist/orchestrator/compaction.test.js +0 -105
  2573. package/dist/orchestrator/compaction.test.js.map +0 -1
  2574. package/dist/orchestrator/delegations.d.ts +0 -49
  2575. package/dist/orchestrator/delegations.js.map +0 -1
  2576. package/dist/orchestrator/delegations.test.js +0 -107
  2577. package/dist/orchestrator/delegations.test.js.map +0 -1
  2578. package/dist/orchestrator/flow-resume.d.ts +0 -25
  2579. package/dist/orchestrator/flow-resume.js +0 -53
  2580. package/dist/orchestrator/flow-resume.js.map +0 -1
  2581. package/dist/orchestrator/orchestrator.d.ts +0 -245
  2582. package/dist/orchestrator/orchestrator.js +0 -3229
  2583. package/dist/orchestrator/orchestrator.js.map +0 -1
  2584. package/dist/orchestrator/pending-calls.js.map +0 -1
  2585. package/dist/orchestrator/pending-calls.test.js.map +0 -1
  2586. package/dist/orchestrator/reasoning.js +0 -53
  2587. package/dist/orchestrator/reasoning.js.map +0 -1
  2588. package/dist/orchestrator/reasoning.test.js +0 -26
  2589. package/dist/orchestrator/reasoning.test.js.map +0 -1
  2590. package/dist/orchestrator/sandbox.test.js +0 -94
  2591. package/dist/orchestrator/sandbox.test.js.map +0 -1
  2592. package/dist/pil/__tests__/budget.test.js +0 -33
  2593. package/dist/pil/__tests__/budget.test.js.map +0 -1
  2594. package/dist/pil/__tests__/layer1-intent.test.js +0 -199
  2595. package/dist/pil/__tests__/layer1-intent.test.js.map +0 -1
  2596. package/dist/pil/__tests__/layer2-personality.test.js +0 -57
  2597. package/dist/pil/__tests__/layer2-personality.test.js.map +0 -1
  2598. package/dist/pil/__tests__/layer3-ee-injection.test.js +0 -96
  2599. package/dist/pil/__tests__/layer3-ee-injection.test.js.map +0 -1
  2600. package/dist/pil/__tests__/layer4-gsd.test.js +0 -68
  2601. package/dist/pil/__tests__/layer4-gsd.test.js.map +0 -1
  2602. package/dist/pil/__tests__/layer5-context.test.js +0 -100
  2603. package/dist/pil/__tests__/layer5-context.test.js.map +0 -1
  2604. package/dist/pil/__tests__/layer6-output.test.js +0 -115
  2605. package/dist/pil/__tests__/layer6-output.test.js.map +0 -1
  2606. package/dist/pil/__tests__/ollama-classify.test.js.map +0 -1
  2607. package/dist/pil/__tests__/orchestrator-integration.test.js.map +0 -1
  2608. package/dist/pil/__tests__/pipeline.test.js +0 -150
  2609. package/dist/pil/__tests__/pipeline.test.js.map +0 -1
  2610. package/dist/pil/__tests__/response-tools.test.js +0 -133
  2611. package/dist/pil/__tests__/response-tools.test.js.map +0 -1
  2612. package/dist/pil/__tests__/schema.test.js +0 -112
  2613. package/dist/pil/__tests__/schema.test.js.map +0 -1
  2614. package/dist/pil/__tests__/store.test.js.map +0 -1
  2615. package/dist/pil/__tests__/task-tier-map.test.js.map +0 -1
  2616. package/dist/pil/budget.js.map +0 -1
  2617. package/dist/pil/index.d.ts +0 -11
  2618. package/dist/pil/index.js +0 -11
  2619. package/dist/pil/index.js.map +0 -1
  2620. package/dist/pil/layer1-intent.d.ts +0 -13
  2621. package/dist/pil/layer1-intent.js +0 -142
  2622. package/dist/pil/layer1-intent.js.map +0 -1
  2623. package/dist/pil/layer2-personality.js +0 -29
  2624. package/dist/pil/layer2-personality.js.map +0 -1
  2625. package/dist/pil/layer3-ee-injection.d.ts +0 -10
  2626. package/dist/pil/layer3-ee-injection.js +0 -72
  2627. package/dist/pil/layer3-ee-injection.js.map +0 -1
  2628. package/dist/pil/layer4-gsd.d.ts +0 -2
  2629. package/dist/pil/layer4-gsd.js +0 -64
  2630. package/dist/pil/layer4-gsd.js.map +0 -1
  2631. package/dist/pil/layer5-context.js +0 -124
  2632. package/dist/pil/layer5-context.js.map +0 -1
  2633. package/dist/pil/layer6-output.d.ts +0 -18
  2634. package/dist/pil/layer6-output.js +0 -105
  2635. package/dist/pil/layer6-output.js.map +0 -1
  2636. package/dist/pil/ollama-classify.js.map +0 -1
  2637. package/dist/pil/pipeline.d.ts +0 -16
  2638. package/dist/pil/pipeline.js +0 -96
  2639. package/dist/pil/pipeline.js.map +0 -1
  2640. package/dist/pil/response-tools.d.ts +0 -63
  2641. package/dist/pil/response-tools.js +0 -87
  2642. package/dist/pil/response-tools.js.map +0 -1
  2643. package/dist/pil/schema.d.ts +0 -80
  2644. package/dist/pil/schema.js +0 -43
  2645. package/dist/pil/schema.js.map +0 -1
  2646. package/dist/pil/store.js.map +0 -1
  2647. package/dist/pil/task-tier-map.js.map +0 -1
  2648. package/dist/pil/timeout.js.map +0 -1
  2649. package/dist/pil/types.d.ts +0 -39
  2650. package/dist/pil/types.js.map +0 -1
  2651. package/dist/providers/__test-utils__/load-fixture.js.map +0 -1
  2652. package/dist/providers/__tests__/runtime-integration.test.js +0 -71
  2653. package/dist/providers/__tests__/runtime-integration.test.js.map +0 -1
  2654. package/dist/providers/__tests__/runtime.test.js +0 -76
  2655. package/dist/providers/__tests__/runtime.test.js.map +0 -1
  2656. package/dist/providers/adapter.d.ts +0 -15
  2657. package/dist/providers/adapter.js +0 -45
  2658. package/dist/providers/adapter.js.map +0 -1
  2659. package/dist/providers/adapter.test.js.map +0 -1
  2660. package/dist/providers/anthropic.js +0 -141
  2661. package/dist/providers/anthropic.js.map +0 -1
  2662. package/dist/providers/errors.js.map +0 -1
  2663. package/dist/providers/errors.test.js.map +0 -1
  2664. package/dist/providers/gemini.js +0 -33
  2665. package/dist/providers/gemini.js.map +0 -1
  2666. package/dist/providers/gemini.test.js.map +0 -1
  2667. package/dist/providers/index.d.ts +0 -11
  2668. package/dist/providers/index.js +0 -15
  2669. package/dist/providers/index.js.map +0 -1
  2670. package/dist/providers/keychain.d.ts +0 -32
  2671. package/dist/providers/keychain.js +0 -127
  2672. package/dist/providers/keychain.js.map +0 -1
  2673. package/dist/providers/keychain.test.js +0 -80
  2674. package/dist/providers/keychain.test.js.map +0 -1
  2675. package/dist/providers/ollama.js.map +0 -1
  2676. package/dist/providers/ollama.test.js.map +0 -1
  2677. package/dist/providers/openai-compatible.js +0 -45
  2678. package/dist/providers/openai-compatible.js.map +0 -1
  2679. package/dist/providers/openai-compatible.test.js +0 -53
  2680. package/dist/providers/openai-compatible.test.js.map +0 -1
  2681. package/dist/providers/openai.d.ts +0 -11
  2682. package/dist/providers/openai.js +0 -33
  2683. package/dist/providers/openai.js.map +0 -1
  2684. package/dist/providers/openai.test.js.map +0 -1
  2685. package/dist/providers/patch-zod-schema.js +0 -121
  2686. package/dist/providers/patch-zod-schema.js.map +0 -1
  2687. package/dist/providers/pricing.d.ts +0 -21
  2688. package/dist/providers/pricing.js +0 -50
  2689. package/dist/providers/pricing.js.map +0 -1
  2690. package/dist/providers/pricing.test.js +0 -47
  2691. package/dist/providers/pricing.test.js.map +0 -1
  2692. package/dist/providers/runtime.d.ts +0 -21
  2693. package/dist/providers/runtime.js +0 -83
  2694. package/dist/providers/runtime.js.map +0 -1
  2695. package/dist/providers/stream-loop.d.ts +0 -16
  2696. package/dist/providers/stream-loop.js +0 -63
  2697. package/dist/providers/stream-loop.js.map +0 -1
  2698. package/dist/providers/types.d.ts +0 -106
  2699. package/dist/providers/types.js +0 -12
  2700. package/dist/providers/types.js.map +0 -1
  2701. package/dist/providers/vision-proxy.js +0 -152
  2702. package/dist/providers/vision-proxy.js.map +0 -1
  2703. package/dist/providers/vision-proxy.test.js +0 -136
  2704. package/dist/providers/vision-proxy.test.js.map +0 -1
  2705. package/dist/router/classifier/grammars.js.map +0 -1
  2706. package/dist/router/classifier/index.js.map +0 -1
  2707. package/dist/router/classifier/index.test.js.map +0 -1
  2708. package/dist/router/classifier/regex.js +0 -45
  2709. package/dist/router/classifier/regex.js.map +0 -1
  2710. package/dist/router/classifier/regex.test.js.map +0 -1
  2711. package/dist/router/classifier/tree-sitter.js.map +0 -1
  2712. package/dist/router/classifier/tree-sitter.test.js.map +0 -1
  2713. package/dist/router/cold.js.map +0 -1
  2714. package/dist/router/cold.test.js +0 -56
  2715. package/dist/router/cold.test.js.map +0 -1
  2716. package/dist/router/decide.js +0 -300
  2717. package/dist/router/decide.js.map +0 -1
  2718. package/dist/router/decide.test.js +0 -116
  2719. package/dist/router/decide.test.js.map +0 -1
  2720. package/dist/router/health.js.map +0 -1
  2721. package/dist/router/health.test.js.map +0 -1
  2722. package/dist/router/store.js.map +0 -1
  2723. package/dist/router/types.js.map +0 -1
  2724. package/dist/router/warm.js +0 -40
  2725. package/dist/router/warm.js.map +0 -1
  2726. package/dist/router/warm.test.js +0 -144
  2727. package/dist/router/warm.test.js.map +0 -1
  2728. package/dist/storage/__tests__/migrations.test.js.map +0 -1
  2729. package/dist/storage/atomic-io.d.ts +0 -18
  2730. package/dist/storage/atomic-io.js +0 -65
  2731. package/dist/storage/atomic-io.js.map +0 -1
  2732. package/dist/storage/atomic-io.test.js +0 -49
  2733. package/dist/storage/atomic-io.test.js.map +0 -1
  2734. package/dist/storage/config.js +0 -35
  2735. package/dist/storage/config.js.map +0 -1
  2736. package/dist/storage/config.test.js.map +0 -1
  2737. package/dist/storage/db.js +0 -71
  2738. package/dist/storage/db.js.map +0 -1
  2739. package/dist/storage/index.d.ts +0 -8
  2740. package/dist/storage/index.js +0 -10
  2741. package/dist/storage/index.js.map +0 -1
  2742. package/dist/storage/migrations.d.ts +0 -2
  2743. package/dist/storage/migrations.js +0 -138
  2744. package/dist/storage/migrations.js.map +0 -1
  2745. package/dist/storage/session-dir.js.map +0 -1
  2746. package/dist/storage/sessions.d.ts +0 -16
  2747. package/dist/storage/sessions.js +0 -142
  2748. package/dist/storage/sessions.js.map +0 -1
  2749. package/dist/storage/tool-results.d.ts +0 -4
  2750. package/dist/storage/tool-results.js.map +0 -1
  2751. package/dist/storage/transcript-view.js +0 -23
  2752. package/dist/storage/transcript-view.js.map +0 -1
  2753. package/dist/storage/transcript.d.ts +0 -12
  2754. package/dist/storage/transcript.js +0 -269
  2755. package/dist/storage/transcript.js.map +0 -1
  2756. package/dist/storage/transcript.test.js +0 -22
  2757. package/dist/storage/transcript.test.js.map +0 -1
  2758. package/dist/storage/usage-cap.js.map +0 -1
  2759. package/dist/storage/usage-cap.test.js.map +0 -1
  2760. package/dist/storage/usage.d.ts +0 -11
  2761. package/dist/storage/usage.js +0 -65
  2762. package/dist/storage/usage.js.map +0 -1
  2763. package/dist/storage/workspaces.d.ts +0 -9
  2764. package/dist/storage/workspaces.js +0 -60
  2765. package/dist/storage/workspaces.js.map +0 -1
  2766. package/dist/tools/bash.d.ts +0 -46
  2767. package/dist/tools/bash.js +0 -541
  2768. package/dist/tools/bash.js.map +0 -1
  2769. package/dist/tools/bash.test.js +0 -240
  2770. package/dist/tools/bash.test.js.map +0 -1
  2771. package/dist/tools/computer.d.ts +0 -88
  2772. package/dist/tools/computer.js.map +0 -1
  2773. package/dist/tools/computer.test.js +0 -142
  2774. package/dist/tools/computer.test.js.map +0 -1
  2775. package/dist/tools/file.d.ts +0 -17
  2776. package/dist/tools/file.js +0 -101
  2777. package/dist/tools/file.js.map +0 -1
  2778. package/dist/tools/file.test.js +0 -58
  2779. package/dist/tools/file.test.js.map +0 -1
  2780. package/dist/tools/grep.d.ts +0 -8
  2781. package/dist/tools/grep.js.map +0 -1
  2782. package/dist/tools/registry.d.ts +0 -19
  2783. package/dist/tools/registry.js +0 -245
  2784. package/dist/tools/registry.js.map +0 -1
  2785. package/dist/tools/schedule.js +0 -498
  2786. package/dist/tools/schedule.js.map +0 -1
  2787. package/dist/tools/schedule.test.js +0 -118
  2788. package/dist/tools/schedule.test.js.map +0 -1
  2789. package/dist/types/index.d.ts +0 -279
  2790. package/dist/types/index.js.map +0 -1
  2791. package/dist/ui/agents-modal.d.ts +0 -36
  2792. package/dist/ui/agents-modal.js +0 -54
  2793. package/dist/ui/agents-modal.js.map +0 -1
  2794. package/dist/ui/app.d.ts +0 -31
  2795. package/dist/ui/app.js +0 -3957
  2796. package/dist/ui/app.js.map +0 -1
  2797. package/dist/ui/components/SuggestionOverlay.js.map +0 -1
  2798. package/dist/ui/components/btw-overlay.js.map +0 -1
  2799. package/dist/ui/hooks/useTypeahead.js +0 -111
  2800. package/dist/ui/hooks/useTypeahead.js.map +0 -1
  2801. package/dist/ui/markdown.d.ts +0 -5
  2802. package/dist/ui/markdown.js.map +0 -1
  2803. package/dist/ui/mcp-modal-types.d.ts +0 -24
  2804. package/dist/ui/mcp-modal-types.js.map +0 -1
  2805. package/dist/ui/mcp-modal.d.ts +0 -33
  2806. package/dist/ui/mcp-modal.js +0 -94
  2807. package/dist/ui/mcp-modal.js.map +0 -1
  2808. package/dist/ui/plan.d.ts +0 -24
  2809. package/dist/ui/plan.js.map +0 -1
  2810. package/dist/ui/schedule-modal.d.ts +0 -15
  2811. package/dist/ui/schedule-modal.js +0 -36
  2812. package/dist/ui/schedule-modal.js.map +0 -1
  2813. package/dist/ui/slash/__tests__/clear.test.js.map +0 -1
  2814. package/dist/ui/slash/__tests__/compact.test.js.map +0 -1
  2815. package/dist/ui/slash/__tests__/cost.test.js.map +0 -1
  2816. package/dist/ui/slash/__tests__/discuss.test.js.map +0 -1
  2817. package/dist/ui/slash/__tests__/execute.test.js.map +0 -1
  2818. package/dist/ui/slash/__tests__/expand.test.js.map +0 -1
  2819. package/dist/ui/slash/__tests__/optimize.test.js +0 -130
  2820. package/dist/ui/slash/__tests__/optimize.test.js.map +0 -1
  2821. package/dist/ui/slash/__tests__/plan.test.js.map +0 -1
  2822. package/dist/ui/slash/clear.js.map +0 -1
  2823. package/dist/ui/slash/compact.js.map +0 -1
  2824. package/dist/ui/slash/cost.js +0 -55
  2825. package/dist/ui/slash/cost.js.map +0 -1
  2826. package/dist/ui/slash/council.js +0 -22
  2827. package/dist/ui/slash/council.js.map +0 -1
  2828. package/dist/ui/slash/debug.js +0 -111
  2829. package/dist/ui/slash/debug.js.map +0 -1
  2830. package/dist/ui/slash/discuss.js.map +0 -1
  2831. package/dist/ui/slash/ee.js +0 -247
  2832. package/dist/ui/slash/ee.js.map +0 -1
  2833. package/dist/ui/slash/execute.js.map +0 -1
  2834. package/dist/ui/slash/expand.js.map +0 -1
  2835. package/dist/ui/slash/optimize.js +0 -37
  2836. package/dist/ui/slash/optimize.js.map +0 -1
  2837. package/dist/ui/slash/plan.js.map +0 -1
  2838. package/dist/ui/slash/registry.d.ts +0 -23
  2839. package/dist/ui/slash/registry.js.map +0 -1
  2840. package/dist/ui/slash/route.js.map +0 -1
  2841. package/dist/ui/slash/route.test.js.map +0 -1
  2842. package/dist/ui/status-bar/index.d.ts +0 -14
  2843. package/dist/ui/status-bar/index.js +0 -74
  2844. package/dist/ui/status-bar/index.js.map +0 -1
  2845. package/dist/ui/status-bar/index.test.js.map +0 -1
  2846. package/dist/ui/status-bar/store.js +0 -146
  2847. package/dist/ui/status-bar/store.js.map +0 -1
  2848. package/dist/ui/status-bar/store.test.js.map +0 -1
  2849. package/dist/ui/status-bar/tier-badge.js.map +0 -1
  2850. package/dist/ui/status-bar/tier-badge.test.js.map +0 -1
  2851. package/dist/ui/status-bar/usd-meter.js.map +0 -1
  2852. package/dist/ui/status-bar/usd-meter.test.js.map +0 -1
  2853. package/dist/ui/terminal-selection-text.js.map +0 -1
  2854. package/dist/ui/theme.d.ts +0 -53
  2855. package/dist/ui/theme.js +0 -53
  2856. package/dist/ui/theme.js.map +0 -1
  2857. package/dist/usage/downgrade.js.map +0 -1
  2858. package/dist/usage/downgrade.test.js.map +0 -1
  2859. package/dist/usage/estimator.d.ts +0 -17
  2860. package/dist/usage/estimator.js +0 -28
  2861. package/dist/usage/estimator.js.map +0 -1
  2862. package/dist/usage/estimator.test.js.map +0 -1
  2863. package/dist/usage/ledger.d.ts +0 -42
  2864. package/dist/usage/ledger.js +0 -181
  2865. package/dist/usage/ledger.js.map +0 -1
  2866. package/dist/usage/ledger.test.js.map +0 -1
  2867. package/dist/usage/midstream.js.map +0 -1
  2868. package/dist/usage/midstream.test.js.map +0 -1
  2869. package/dist/usage/thresholds.js.map +0 -1
  2870. package/dist/usage/thresholds.test.js.map +0 -1
  2871. package/dist/usage/types.d.ts +0 -30
  2872. package/dist/usage/types.js.map +0 -1
  2873. package/dist/utils/at-mentions.js.map +0 -1
  2874. package/dist/utils/clipboard-image.js +0 -127
  2875. package/dist/utils/clipboard-image.js.map +0 -1
  2876. package/dist/utils/file-index.js.map +0 -1
  2877. package/dist/utils/git-root.js.map +0 -1
  2878. package/dist/utils/host-clipboard.d.ts +0 -4
  2879. package/dist/utils/host-clipboard.js +0 -32
  2880. package/dist/utils/host-clipboard.js.map +0 -1
  2881. package/dist/utils/install-manager.js.map +0 -1
  2882. package/dist/utils/install-manager.test.js +0 -127
  2883. package/dist/utils/install-manager.test.js.map +0 -1
  2884. package/dist/utils/instructions.js +0 -107
  2885. package/dist/utils/instructions.js.map +0 -1
  2886. package/dist/utils/instructions.test.js +0 -68
  2887. package/dist/utils/instructions.test.js.map +0 -1
  2888. package/dist/utils/permission-mode.js.map +0 -1
  2889. package/dist/utils/permission-mode.test.js.map +0 -1
  2890. package/dist/utils/redactor.js.map +0 -1
  2891. package/dist/utils/redactor.test.js +0 -84
  2892. package/dist/utils/redactor.test.js.map +0 -1
  2893. package/dist/utils/settings.d.ts +0 -182
  2894. package/dist/utils/settings.js +0 -585
  2895. package/dist/utils/settings.js.map +0 -1
  2896. package/dist/utils/settings.test.js +0 -160
  2897. package/dist/utils/settings.test.js.map +0 -1
  2898. package/dist/utils/side-question.js.map +0 -1
  2899. package/dist/utils/skills.js +0 -194
  2900. package/dist/utils/skills.js.map +0 -1
  2901. package/dist/utils/skills.test.js +0 -45
  2902. package/dist/utils/skills.test.js.map +0 -1
  2903. package/dist/utils/subagent-display.js.map +0 -1
  2904. package/dist/utils/subagent-display.test.js +0 -21
  2905. package/dist/utils/subagent-display.test.js.map +0 -1
  2906. package/dist/utils/subagents-settings.test.js +0 -58
  2907. package/dist/utils/subagents-settings.test.js.map +0 -1
  2908. package/dist/utils/telegram-audio-settings.test.js +0 -39
  2909. package/dist/utils/telegram-audio-settings.test.js.map +0 -1
  2910. package/dist/utils/update-checker.js +0 -22
  2911. package/dist/utils/update-checker.js.map +0 -1
  2912. package/dist/utils/update-checker.test.js +0 -125
  2913. package/dist/utils/update-checker.test.js.map +0 -1
  2914. package/dist/verify/checkpoint.d.ts +0 -11
  2915. package/dist/verify/checkpoint.js.map +0 -1
  2916. package/dist/verify/checkpoint.test.js +0 -160
  2917. package/dist/verify/checkpoint.test.js.map +0 -1
  2918. package/dist/verify/entrypoint.d.ts +0 -30
  2919. package/dist/verify/entrypoint.js +0 -349
  2920. package/dist/verify/entrypoint.js.map +0 -1
  2921. package/dist/verify/entrypoint.test.js +0 -233
  2922. package/dist/verify/entrypoint.test.js.map +0 -1
  2923. package/dist/verify/environment.d.ts +0 -9
  2924. package/dist/verify/environment.js +0 -116
  2925. package/dist/verify/environment.js.map +0 -1
  2926. package/dist/verify/environment.test.js +0 -94
  2927. package/dist/verify/environment.test.js.map +0 -1
  2928. package/dist/verify/evidence.d.ts +0 -10
  2929. package/dist/verify/evidence.js.map +0 -1
  2930. package/dist/verify/orchestrator.d.ts +0 -25
  2931. package/dist/verify/orchestrator.js +0 -87
  2932. package/dist/verify/orchestrator.js.map +0 -1
  2933. package/dist/verify/orchestrator.test.js +0 -126
  2934. package/dist/verify/orchestrator.test.js.map +0 -1
  2935. package/dist/verify/recipes.d.ts +0 -20
  2936. package/dist/verify/recipes.js +0 -451
  2937. package/dist/verify/recipes.js.map +0 -1
  2938. package/dist/verify/retry.d.ts +0 -4
  2939. package/dist/verify/retry.js.map +0 -1
  2940. package/dist/verify/runtime-prep.test.js +0 -38
  2941. package/dist/verify/runtime-prep.test.js.map +0 -1
  2942. /package/dist/{__test-stubs__ → src/__test-stubs__}/ee-server.d.ts +0 -0
  2943. /package/dist/{__test-stubs__ → src/__test-stubs__}/ee-server.js +0 -0
  2944. /package/dist/{daemon/scheduler.test.d.ts → src/__test-stubs__/vitest-setup.d.ts} +0 -0
  2945. /package/dist/{ee/auth.test.d.ts → src/__tests__/council/bubble-layout.test.d.ts} +0 -0
  2946. /package/dist/{ee/bridge.test.d.ts → src/__tests__/council/code-block-truncate.test.d.ts} +0 -0
  2947. /package/dist/{ee/client.test.d.ts → src/__tests__/council/role-palette.test.d.ts} +0 -0
  2948. /package/dist/{ee/extract-session.test.d.ts → src/__tests__/first-run-wizard.test.d.ts} +0 -0
  2949. /package/dist/{ee/intercept.test.d.ts → src/agent-harness/__tests__/cli-flags.spec.d.ts} +0 -0
  2950. /package/dist/{ee/judge.test.d.ts → src/agent-harness/__tests__/driver.spec.d.ts} +0 -0
  2951. /package/dist/{ee/offline-queue.test.d.ts → src/agent-harness/__tests__/idle.spec.d.ts} +0 -0
  2952. /package/dist/{ee/posttool.test.d.ts → src/agent-harness/__tests__/mock-llm.spec.d.ts} +0 -0
  2953. /package/dist/{ee/render.test.d.ts → src/agent-harness/__tests__/predicate.spec.d.ts} +0 -0
  2954. /package/dist/{ee/scope.test.d.ts → src/agent-harness/__tests__/protocol.spec.d.ts} +0 -0
  2955. /package/dist/{ee/touch.test.d.ts → src/agent-harness/__tests__/schema.spec.d.ts} +0 -0
  2956. /package/dist/{flow/__tests__/migration.test.d.ts → src/agent-harness/__tests__/selector.spec.d.ts} +0 -0
  2957. /package/dist/{flow/__tests__/parser.test.d.ts → src/agent-harness/__tests__/sidechannel.spec.d.ts} +0 -0
  2958. /package/dist/{flow/__tests__/run-manager.test.d.ts → src/agent-harness/__tests__/spec-helpers.spec.d.ts} +0 -0
  2959. /package/dist/{billing → src/billing}/index.d.ts +0 -0
  2960. /package/dist/{billing → src/billing}/index.js +0 -0
  2961. /package/dist/{flow/__tests__/scaffold.test.d.ts → src/chat/__tests__/broadcast-bus.test.d.ts} +0 -0
  2962. /package/dist/{flow/compaction/__tests__/compress.test.d.ts → src/chat/__tests__/channel-manager.test.d.ts} +0 -0
  2963. /package/dist/{flow/compaction/__tests__/extract.test.d.ts → src/chat/__tests__/client.test.d.ts} +0 -0
  2964. /package/dist/{flow/compaction/__tests__/preserve.test.d.ts → src/chat/__tests__/discord-integration.test.d.ts} +0 -0
  2965. /package/dist/{gsd/__tests__/types.test.d.ts → src/chat/__tests__/intent-prompt.test.d.ts} +0 -0
  2966. /package/dist/{headless/output.test.d.ts → src/chat/__tests__/verdict-resolver.test.d.ts} +0 -0
  2967. /package/dist/{lsp/builtins.test.d.ts → src/cli/__tests__/bw-vault.test.d.ts} +0 -0
  2968. /package/dist/{lsp/manager.test.d.ts → src/cli/__tests__/keys-bundle.test.d.ts} +0 -0
  2969. /package/dist/{lsp/npm-cache.test.d.ts → src/cli/__tests__/share-cmd.test.d.ts} +0 -0
  2970. /package/dist/{lsp/smoke.test.d.ts → src/cli/config/__tests__/model-picker.test.d.ts} +0 -0
  2971. /package/dist/{mcp/parse-headers.test.d.ts → src/cli/config/__tests__/provider-fetch.test.d.ts} +0 -0
  2972. /package/dist/{mcp/smoke.test.d.ts → src/cli/cost-forensics.test.d.ts} +0 -0
  2973. /package/dist/{models/__tests__/registry.test.d.ts → src/cli/keys.test.d.ts} +0 -0
  2974. /package/dist/{cloud → src/cloud}/index.d.ts +0 -0
  2975. /package/dist/{cloud → src/cloud}/index.js +0 -0
  2976. /package/dist/{ops/bug-report.test.d.ts → src/council/__tests__/accounting.test.d.ts} +0 -0
  2977. /package/dist/{ops/doctor.test.d.ts → src/council/__tests__/audit-replay.test.d.ts} +0 -0
  2978. /package/dist/{orchestrator/__tests__/route-feedback.test.d.ts → src/council/__tests__/clarifier-max-rounds.test.d.ts} +0 -0
  2979. /package/dist/{orchestrator/abort.test.d.ts → src/council/__tests__/clarifier-options.test.d.ts} +0 -0
  2980. /package/dist/{orchestrator/agent.test.d.ts → src/council/__tests__/cost-aware.test.d.ts} +0 -0
  2981. /package/dist/{orchestrator/cleanup.test.d.ts → src/council/__tests__/debate-planner-structured.test.d.ts} +0 -0
  2982. /package/dist/{orchestrator/compaction.test.d.ts → src/council/__tests__/evaluator-metrics.test.d.ts} +0 -0
  2983. /package/dist/{orchestrator/delegations.test.d.ts → src/council/__tests__/parse-outcome-fallback.test.d.ts} +0 -0
  2984. /package/dist/{orchestrator/pending-calls.test.d.ts → src/council/__tests__/research-tools.test.d.ts} +0 -0
  2985. /package/dist/{orchestrator/reasoning.test.d.ts → src/council/__tests__/round-tools.test.d.ts} +0 -0
  2986. /package/dist/{orchestrator/sandbox.test.d.ts → src/council/__tests__/tool-trace.test.d.ts} +0 -0
  2987. /package/dist/{router → src/council}/types.js +0 -0
  2988. /package/dist/{pil/__tests__/budget.test.d.ts → src/daemon/scheduler.test.d.ts} +0 -0
  2989. /package/dist/{pil/__tests__/layer1-intent.test.d.ts → src/ee/__tests__/pil-context-bridge.test.d.ts} +0 -0
  2990. /package/dist/{ee → src/ee}/__tests__/pipeline.integration.test.d.ts +0 -0
  2991. /package/dist/{pil/__tests__/layer2-personality.test.d.ts → src/ee/__tests__/render-sink-wiring.test.d.ts} +0 -0
  2992. /package/dist/{pil/__tests__/layer3-ee-injection.test.d.ts → src/ee/auth.test.d.ts} +0 -0
  2993. /package/dist/{ee → src/ee}/auth.test.js +0 -0
  2994. /package/dist/{pil/__tests__/layer4-gsd.test.d.ts → src/ee/bridge.test.d.ts} +0 -0
  2995. /package/dist/{ee → src/ee}/bridge.test.js +0 -0
  2996. /package/dist/{ee → src/ee}/client.d.ts +0 -0
  2997. /package/dist/{pil/__tests__/layer5-context.test.d.ts → src/ee/client.test.d.ts} +0 -0
  2998. /package/dist/{ee → src/ee}/client.test.js +0 -0
  2999. /package/dist/{ee → src/ee}/embedding-cache.d.ts +0 -0
  3000. /package/dist/{ee → src/ee}/embedding-cache.js +0 -0
  3001. /package/dist/{ee → src/ee}/extract-session.d.ts +0 -0
  3002. /package/dist/{pil/__tests__/layer6-output.test.d.ts → src/ee/extract-session.test.d.ts} +0 -0
  3003. /package/dist/{ee → src/ee}/health.d.ts +0 -0
  3004. /package/dist/{ee → src/ee}/intercept.d.ts +0 -0
  3005. /package/dist/{pil/__tests__/ollama-classify.test.d.ts → src/ee/intercept.test.d.ts} +0 -0
  3006. /package/dist/{pil/__tests__/pipeline.test.d.ts → src/ee/judge.test.d.ts} +0 -0
  3007. /package/dist/{pil/__tests__/response-tools.test.d.ts → src/ee/mistake-detector.test.d.ts} +0 -0
  3008. /package/dist/{ee → src/ee}/offline-queue.d.ts +0 -0
  3009. /package/dist/{ee → src/ee}/offline-queue.js +0 -0
  3010. /package/dist/{pil/__tests__/schema.test.d.ts → src/ee/offline-queue.test.d.ts} +0 -0
  3011. /package/dist/{pil/__tests__/store.test.d.ts → src/ee/phase-outcome.test.d.ts} +0 -0
  3012. /package/dist/{pil/__tests__/task-tier-map.test.d.ts → src/ee/phase-tracker.test.d.ts} +0 -0
  3013. /package/dist/{ee → src/ee}/posttool.d.ts +0 -0
  3014. /package/dist/{ee → src/ee}/posttool.js +0 -0
  3015. /package/dist/{providers/__tests__/runtime-integration.test.d.ts → src/ee/posttool.test.d.ts} +0 -0
  3016. /package/dist/{ee → src/ee}/posttool.test.js +0 -0
  3017. /package/dist/{ee → src/ee}/prompt-stale.d.ts +0 -0
  3018. /package/dist/{ee → src/ee}/prompt-stale.js +0 -0
  3019. /package/dist/{ee → src/ee}/prompt-stale.test.d.ts +0 -0
  3020. /package/dist/{providers/__tests__/runtime.test.d.ts → src/ee/render.test.d.ts} +0 -0
  3021. /package/dist/{ee → src/ee}/scope.d.ts +0 -0
  3022. /package/dist/{ee → src/ee}/scope.js +0 -0
  3023. /package/dist/{providers/adapter.test.d.ts → src/ee/scope.test.d.ts} +0 -0
  3024. /package/dist/{ee → src/ee}/scope.test.js +0 -0
  3025. /package/dist/{providers/errors.test.d.ts → src/ee/session-trajectory.test.d.ts} +0 -0
  3026. /package/dist/{ee → src/ee}/tenant.d.ts +0 -0
  3027. /package/dist/{ee → src/ee}/tenant.js +0 -0
  3028. /package/dist/{providers/gemini.test.d.ts → src/ee/touch.test.d.ts} +0 -0
  3029. /package/dist/{ee → src/ee}/types.js +0 -0
  3030. /package/dist/{providers/keychain.test.d.ts → src/flow/__tests__/migration.test.d.ts} +0 -0
  3031. /package/dist/{flow → src/flow}/__tests__/migration.test.js +0 -0
  3032. /package/dist/{providers/ollama.test.d.ts → src/flow/__tests__/parser.test.d.ts} +0 -0
  3033. /package/dist/{flow → src/flow}/__tests__/parser.test.js +0 -0
  3034. /package/dist/{providers/openai-compatible.test.d.ts → src/flow/__tests__/run-manager-product.test.d.ts} +0 -0
  3035. /package/dist/{providers/openai.test.d.ts → src/flow/__tests__/run-manager.test.d.ts} +0 -0
  3036. /package/dist/{flow → src/flow}/__tests__/run-manager.test.js +0 -0
  3037. /package/dist/{providers/pricing.test.d.ts → src/flow/__tests__/scaffold-checkpoint.test.d.ts} +0 -0
  3038. /package/dist/{providers/vision-proxy.test.d.ts → src/flow/__tests__/scaffold.test.d.ts} +0 -0
  3039. /package/dist/{flow → src/flow}/__tests__/scaffold.test.js +0 -0
  3040. /package/dist/{flow → src/flow}/__tests__/warning-persist.test.d.ts +0 -0
  3041. /package/dist/{flow → src/flow}/__tests__/warning-persist.test.js +0 -0
  3042. /package/dist/{flow → src/flow}/artifact-io.d.ts +0 -0
  3043. /package/dist/{flow → src/flow}/artifact-io.js +0 -0
  3044. /package/dist/{router/classifier/index.test.d.ts → src/flow/compaction/__tests__/compress.test.d.ts} +0 -0
  3045. /package/dist/{flow → src/flow}/compaction/__tests__/compress.test.js +0 -0
  3046. /package/dist/{router/classifier/regex.test.d.ts → src/flow/compaction/__tests__/extract.test.d.ts} +0 -0
  3047. /package/dist/{flow → src/flow}/compaction/__tests__/extract.test.js +0 -0
  3048. /package/dist/{router/classifier/tree-sitter.test.d.ts → src/flow/compaction/__tests__/preserve.test.d.ts} +0 -0
  3049. /package/dist/{flow → src/flow}/compaction/__tests__/preserve.test.js +0 -0
  3050. /package/dist/{flow → src/flow}/compaction/compress.d.ts +0 -0
  3051. /package/dist/{flow → src/flow}/compaction/compress.js +0 -0
  3052. /package/dist/{flow → src/flow}/compaction/extract.d.ts +0 -0
  3053. /package/dist/{flow → src/flow}/compaction/extract.js +0 -0
  3054. /package/dist/{flow → src/flow}/compaction/index.d.ts +0 -0
  3055. /package/dist/{flow → src/flow}/compaction/index.js +0 -0
  3056. /package/dist/{flow → src/flow}/compaction/preserve.d.ts +0 -0
  3057. /package/dist/{flow → src/flow}/compaction/preserve.js +0 -0
  3058. /package/dist/{flow → src/flow}/index.d.ts +0 -0
  3059. /package/dist/{flow → src/flow}/index.js +0 -0
  3060. /package/dist/{flow → src/flow}/migration.d.ts +0 -0
  3061. /package/dist/{flow → src/flow}/migration.js +0 -0
  3062. /package/dist/{flow → src/flow}/parser.d.ts +0 -0
  3063. /package/dist/{flow → src/flow}/parser.js +0 -0
  3064. /package/dist/{flow → src/flow}/scaffold.d.ts +0 -0
  3065. /package/dist/{flow → src/flow}/scaffold.js +0 -0
  3066. /package/dist/{flow → src/flow}/warning-persist.d.ts +0 -0
  3067. /package/dist/{flow → src/flow}/warning-persist.js +0 -0
  3068. /package/dist/{router/cold.test.d.ts → src/gsd/__tests__/complexity.test.d.ts} +0 -0
  3069. /package/dist/{router/decide.test.d.ts → src/gsd/__tests__/directives.test.d.ts} +0 -0
  3070. /package/dist/{router/health.test.d.ts → src/gsd/__tests__/gray-areas.test.d.ts} +0 -0
  3071. /package/dist/{router/warm.test.d.ts → src/gsd/__tests__/types.test.d.ts} +0 -0
  3072. /package/dist/{gsd → src/gsd}/index.d.ts +0 -0
  3073. /package/dist/{gsd → src/gsd}/index.js +0 -0
  3074. /package/dist/{gsd → src/gsd}/types.js +0 -0
  3075. /package/dist/{storage/atomic-io.test.d.ts → src/headless/__tests__/council-answers.test.d.ts} +0 -0
  3076. /package/dist/{headless → src/headless}/output.js +0 -0
  3077. /package/dist/{storage/config.test.d.ts → src/headless/output.test.d.ts} +0 -0
  3078. /package/dist/{hooks → src/hooks}/config.d.ts +0 -0
  3079. /package/dist/{hooks → src/hooks}/config.js +0 -0
  3080. /package/dist/{hooks → src/hooks}/types.js +0 -0
  3081. /package/dist/{storage/transcript.test.d.ts → src/lsp/builtins.test.d.ts} +0 -0
  3082. /package/dist/{storage/usage-cap.test.d.ts → src/lsp/manager.test.d.ts} +0 -0
  3083. /package/dist/{lsp → src/lsp}/npm-cache.d.ts +0 -0
  3084. /package/dist/{lsp → src/lsp}/npm-cache.js +0 -0
  3085. /package/dist/{tools/bash.test.d.ts → src/lsp/npm-cache.test.d.ts} +0 -0
  3086. /package/dist/{tools/computer.test.d.ts → src/lsp/smoke.test.d.ts} +0 -0
  3087. /package/dist/{lsp → src/lsp}/smoke.test.js +0 -0
  3088. /package/dist/{lsp → src/lsp}/types.d.ts +0 -0
  3089. /package/dist/{lsp → src/lsp}/types.js +0 -0
  3090. /package/dist/{tools/file.test.d.ts → src/mcp/__tests__/auto-setup.test.d.ts} +0 -0
  3091. /package/dist/{tools/schedule.test.d.ts → src/mcp/__tests__/harness-driver-action-tools.spec.d.ts} +0 -0
  3092. /package/dist/{ui/slash/__tests__/discuss.test.d.ts → src/mcp/__tests__/harness-driver-async-tools.spec.d.ts} +0 -0
  3093. /package/dist/{ui/slash/__tests__/execute.test.d.ts → src/mcp/__tests__/harness-driver-read-tools.spec.d.ts} +0 -0
  3094. /package/dist/{ui/slash/__tests__/plan.test.d.ts → src/mcp/__tests__/harness-driver-security.spec.d.ts} +0 -0
  3095. /package/dist/{ui/status-bar/index.test.d.ts → src/mcp/__tests__/harness-driver.spec.d.ts} +0 -0
  3096. /package/dist/{ui/status-bar/store.test.d.ts → src/mcp/__tests__/lazy-schema.spec.d.ts} +0 -0
  3097. /package/dist/{ui/status-bar/tier-badge.test.d.ts → src/mcp/__tests__/mcp-keychain.test.d.ts} +0 -0
  3098. /package/dist/{ui/status-bar/usd-meter.test.d.ts → src/mcp/__tests__/research-onboarding.test.d.ts} +0 -0
  3099. /package/dist/{usage/downgrade.test.d.ts → src/mcp/__tests__/runtime-hydration.test.d.ts} +0 -0
  3100. /package/dist/{usage/estimator.test.d.ts → src/mcp/__tests__/runtime-sanitize.test.d.ts} +0 -0
  3101. /package/dist/{mcp → src/mcp}/auto-setup.d.ts +0 -0
  3102. /package/dist/{mcp → src/mcp}/catalog.d.ts +0 -0
  3103. /package/dist/{mcp → src/mcp}/oauth-provider.d.ts +0 -0
  3104. /package/dist/{mcp → src/mcp}/oauth-provider.js +0 -0
  3105. /package/dist/{mcp → src/mcp}/parse-headers.d.ts +0 -0
  3106. /package/dist/{mcp → src/mcp}/parse-headers.js +0 -0
  3107. /package/dist/{usage/ledger.test.d.ts → src/mcp/parse-headers.test.d.ts} +0 -0
  3108. /package/dist/{mcp → src/mcp}/runtime.d.ts +0 -0
  3109. /package/dist/{usage/midstream.test.d.ts → src/mcp/smoke.test.d.ts} +0 -0
  3110. /package/dist/{mcp → src/mcp}/smoke.test.js +0 -0
  3111. /package/dist/{mcp → src/mcp}/validate.js +0 -0
  3112. /package/dist/{usage/thresholds.test.d.ts → src/models/__tests__/registry.test.d.ts} +0 -0
  3113. /package/dist/{models → src/models}/catalog-client.d.ts +0 -0
  3114. /package/dist/{models → src/models}/classify-tier.d.ts +0 -0
  3115. /package/dist/{utils/install-manager.test.d.ts → src/ops/__tests__/doctor-council-mcp.test.d.ts} +0 -0
  3116. /package/dist/{utils/instructions.test.d.ts → src/ops/__tests__/doctor-ee-health.test.d.ts} +0 -0
  3117. /package/dist/{ops → src/ops}/bug-report.d.ts +0 -0
  3118. /package/dist/{ops → src/ops}/bug-report.js +0 -0
  3119. /package/dist/{utils/permission-mode.test.d.ts → src/ops/bug-report.test.d.ts} +0 -0
  3120. /package/dist/{ops → src/ops}/bug-report.test.js +0 -0
  3121. /package/dist/{ops → src/ops}/doctor.d.ts +0 -0
  3122. /package/dist/{utils/redactor.test.d.ts → src/ops/doctor.test.d.ts} +0 -0
  3123. /package/dist/{utils/settings.test.d.ts → src/orchestrator/__tests__/batch-turn-runner.test.d.ts} +0 -0
  3124. /package/dist/{utils/skills.test.d.ts → src/orchestrator/__tests__/council-manager.test.d.ts} +0 -0
  3125. /package/dist/{utils/subagent-display.test.d.ts → src/orchestrator/__tests__/cross-turn-dedup.test.d.ts} +0 -0
  3126. /package/dist/{orchestrator → src/orchestrator}/__tests__/flow-resume.test.d.ts +0 -0
  3127. /package/dist/{orchestrator → src/orchestrator}/__tests__/flow-resume.test.js +0 -0
  3128. /package/dist/{utils/subagents-settings.test.d.ts → src/orchestrator/__tests__/message-processor.test.d.ts} +0 -0
  3129. /package/dist/{utils/telegram-audio-settings.test.d.ts → src/orchestrator/__tests__/read-path-budget.test.d.ts} +0 -0
  3130. /package/dist/{utils/update-checker.test.d.ts → src/orchestrator/__tests__/retry-classifier.test.d.ts} +0 -0
  3131. /package/dist/{verify/checkpoint.test.d.ts → src/orchestrator/__tests__/retry-stream.test.d.ts} +0 -0
  3132. /package/dist/{verify/entrypoint.test.d.ts → src/orchestrator/__tests__/route-feedback.test.d.ts} +0 -0
  3133. /package/dist/{verify/environment.test.d.ts → src/orchestrator/__tests__/stream-runner.test.d.ts} +0 -0
  3134. /package/dist/{orchestrator → src/orchestrator}/abort.d.ts +0 -0
  3135. /package/dist/{orchestrator → src/orchestrator}/abort.js +0 -0
  3136. /package/dist/{verify/orchestrator.test.d.ts → src/orchestrator/abort.test.d.ts} +0 -0
  3137. /package/dist/{orchestrator → src/orchestrator}/abort.test.js +0 -0
  3138. /package/dist/{verify/runtime-prep.test.d.ts → src/orchestrator/agent.test.d.ts} +0 -0
  3139. /package/dist/{orchestrator → src/orchestrator}/delegations.js +0 -0
  3140. /package/dist/{orchestrator → src/orchestrator}/pending-calls.d.ts +0 -0
  3141. /package/dist/{orchestrator → src/orchestrator}/pending-calls.js +0 -0
  3142. /package/dist/{orchestrator → src/orchestrator}/pending-calls.test.js +0 -0
  3143. /package/dist/{orchestrator → src/orchestrator}/reasoning.d.ts +0 -0
  3144. /package/dist/{pil → src/pil}/__tests__/ollama-classify.test.js +0 -0
  3145. /package/dist/{pil → src/pil}/__tests__/orchestrator-integration.test.d.ts +0 -0
  3146. /package/dist/{pil → src/pil}/__tests__/orchestrator-integration.test.js +0 -0
  3147. /package/dist/{pil → src/pil}/__tests__/store.test.js +0 -0
  3148. /package/dist/{pil → src/pil}/__tests__/task-tier-map.test.js +0 -0
  3149. /package/dist/{pil → src/pil}/budget.d.ts +0 -0
  3150. /package/dist/{pil → src/pil}/budget.js +0 -0
  3151. /package/dist/{pil → src/pil}/layer2-personality.d.ts +0 -0
  3152. /package/dist/{pil → src/pil}/layer5-context.d.ts +0 -0
  3153. /package/dist/{pil → src/pil}/ollama-classify.d.ts +0 -0
  3154. /package/dist/{pil → src/pil}/ollama-classify.js +0 -0
  3155. /package/dist/{pil → src/pil}/store.d.ts +0 -0
  3156. /package/dist/{pil → src/pil}/store.js +0 -0
  3157. /package/dist/{pil → src/pil}/task-tier-map.d.ts +0 -0
  3158. /package/dist/{pil → src/pil}/task-tier-map.js +0 -0
  3159. /package/dist/{pil → src/pil}/timeout.d.ts +0 -0
  3160. /package/dist/{pil → src/pil}/timeout.js +0 -0
  3161. /package/dist/{pil → src/pil}/types.js +0 -0
  3162. /package/dist/{providers → src/providers}/__test-utils__/load-fixture.d.ts +0 -0
  3163. /package/dist/{providers → src/providers}/__test-utils__/load-fixture.js +0 -0
  3164. /package/dist/{providers → src/providers}/adapter.test.js +0 -0
  3165. /package/dist/{providers → src/providers}/anthropic.d.ts +0 -0
  3166. /package/dist/{providers → src/providers}/errors.d.ts +0 -0
  3167. /package/dist/{providers → src/providers}/errors.js +0 -0
  3168. /package/dist/{providers → src/providers}/errors.test.js +0 -0
  3169. /package/dist/{providers → src/providers}/gemini.d.ts +0 -0
  3170. /package/dist/{providers → src/providers}/gemini.test.js +0 -0
  3171. /package/dist/{providers → src/providers}/ollama.d.ts +0 -0
  3172. /package/dist/{providers → src/providers}/ollama.js +0 -0
  3173. /package/dist/{providers → src/providers}/ollama.test.js +0 -0
  3174. /package/dist/{providers → src/providers}/openai-compatible.d.ts +0 -0
  3175. /package/dist/{providers → src/providers}/openai.test.js +0 -0
  3176. /package/dist/{providers → src/providers}/patch-zod-schema.d.ts +0 -0
  3177. /package/dist/{providers → src/providers}/vision-proxy.d.ts +0 -0
  3178. /package/dist/{router → src/router}/classifier/grammars.d.ts +0 -0
  3179. /package/dist/{router → src/router}/classifier/grammars.js +0 -0
  3180. /package/dist/{router → src/router}/classifier/index.d.ts +0 -0
  3181. /package/dist/{router → src/router}/classifier/index.js +0 -0
  3182. /package/dist/{router → src/router}/classifier/index.test.js +0 -0
  3183. /package/dist/{router → src/router}/classifier/regex.d.ts +0 -0
  3184. /package/dist/{router → src/router}/classifier/regex.test.js +0 -0
  3185. /package/dist/{router → src/router}/classifier/tree-sitter.d.ts +0 -0
  3186. /package/dist/{router → src/router}/classifier/tree-sitter.js +0 -0
  3187. /package/dist/{router → src/router}/classifier/tree-sitter.test.js +0 -0
  3188. /package/dist/{router → src/router}/cold.d.ts +0 -0
  3189. /package/dist/{router → src/router}/cold.js +0 -0
  3190. /package/dist/{router → src/router}/decide.d.ts +0 -0
  3191. /package/dist/{router → src/router}/health.d.ts +0 -0
  3192. /package/dist/{router → src/router}/health.js +0 -0
  3193. /package/dist/{router → src/router}/health.test.js +0 -0
  3194. /package/dist/{router → src/router}/store.d.ts +0 -0
  3195. /package/dist/{router → src/router}/store.js +0 -0
  3196. /package/dist/{router → src/router}/types.d.ts +0 -0
  3197. /package/dist/{router → src/router}/warm.d.ts +0 -0
  3198. /package/dist/{storage → src/storage}/__tests__/migrations.test.d.ts +0 -0
  3199. /package/dist/{storage → src/storage}/__tests__/migrations.test.js +0 -0
  3200. /package/dist/{storage → src/storage}/config.d.ts +0 -0
  3201. /package/dist/{storage → src/storage}/config.test.js +0 -0
  3202. /package/dist/{storage → src/storage}/db.d.ts +0 -0
  3203. /package/dist/{storage → src/storage}/session-dir.d.ts +0 -0
  3204. /package/dist/{storage → src/storage}/session-dir.js +0 -0
  3205. /package/dist/{storage → src/storage}/tool-results.js +0 -0
  3206. /package/dist/{storage → src/storage}/transcript-view.d.ts +0 -0
  3207. /package/dist/{storage → src/storage}/usage-cap.d.ts +0 -0
  3208. /package/dist/{storage → src/storage}/usage-cap.js +0 -0
  3209. /package/dist/{storage → src/storage}/usage-cap.test.js +0 -0
  3210. /package/dist/{tools → src/tools}/computer.js +0 -0
  3211. /package/dist/{tools → src/tools}/grep.js +0 -0
  3212. /package/dist/{tools → src/tools}/schedule.d.ts +0 -0
  3213. /package/dist/{types → src/types}/index.js +0 -0
  3214. /package/dist/{ui → src/ui}/components/SuggestionOverlay.d.ts +0 -0
  3215. /package/dist/{ui → src/ui}/components/SuggestionOverlay.js +0 -0
  3216. /package/dist/{ui → src/ui}/components/btw-overlay.d.ts +0 -0
  3217. /package/dist/{ui → src/ui}/components/btw-overlay.js +0 -0
  3218. /package/dist/{ui → src/ui}/hooks/useTypeahead.d.ts +0 -0
  3219. /package/dist/{ui → src/ui}/markdown.js +0 -0
  3220. /package/dist/{ui → src/ui}/mcp-modal-types.js +0 -0
  3221. /package/dist/{ui → src/ui}/plan.js +0 -0
  3222. /package/dist/{ui → src/ui}/slash/__tests__/clear.test.d.ts +0 -0
  3223. /package/dist/{ui → src/ui}/slash/__tests__/clear.test.js +0 -0
  3224. /package/dist/{ui → src/ui}/slash/__tests__/compact.test.d.ts +0 -0
  3225. /package/dist/{ui → src/ui}/slash/__tests__/compact.test.js +0 -0
  3226. /package/dist/{ui → src/ui}/slash/__tests__/cost.test.d.ts +0 -0
  3227. /package/dist/{ui → src/ui}/slash/__tests__/cost.test.js +0 -0
  3228. /package/dist/{ui → src/ui}/slash/__tests__/discuss.test.js +0 -0
  3229. /package/dist/{ui → src/ui}/slash/__tests__/execute.test.js +0 -0
  3230. /package/dist/{ui → src/ui}/slash/__tests__/expand.test.d.ts +0 -0
  3231. /package/dist/{ui → src/ui}/slash/__tests__/expand.test.js +0 -0
  3232. /package/dist/{ui → src/ui}/slash/__tests__/optimize.test.d.ts +0 -0
  3233. /package/dist/{ui → src/ui}/slash/__tests__/plan.test.js +0 -0
  3234. /package/dist/{ui → src/ui}/slash/clear.d.ts +0 -0
  3235. /package/dist/{ui → src/ui}/slash/clear.js +0 -0
  3236. /package/dist/{ui → src/ui}/slash/compact.d.ts +0 -0
  3237. /package/dist/{ui → src/ui}/slash/compact.js +0 -0
  3238. /package/dist/{ui → src/ui}/slash/cost.d.ts +0 -0
  3239. /package/dist/{ui → src/ui}/slash/council.d.ts +0 -0
  3240. /package/dist/{ui → src/ui}/slash/debug.d.ts +0 -0
  3241. /package/dist/{ui → src/ui}/slash/discuss.d.ts +0 -0
  3242. /package/dist/{ui → src/ui}/slash/discuss.js +0 -0
  3243. /package/dist/{ui → src/ui}/slash/ee.d.ts +0 -0
  3244. /package/dist/{ui → src/ui}/slash/execute.d.ts +0 -0
  3245. /package/dist/{ui → src/ui}/slash/execute.js +0 -0
  3246. /package/dist/{ui → src/ui}/slash/expand.d.ts +0 -0
  3247. /package/dist/{ui → src/ui}/slash/expand.js +0 -0
  3248. /package/dist/{ui → src/ui}/slash/optimize.d.ts +0 -0
  3249. /package/dist/{ui → src/ui}/slash/plan.d.ts +0 -0
  3250. /package/dist/{ui → src/ui}/slash/plan.js +0 -0
  3251. /package/dist/{ui → src/ui}/slash/registry.js +0 -0
  3252. /package/dist/{ui → src/ui}/slash/route.d.ts +0 -0
  3253. /package/dist/{ui → src/ui}/slash/route.js +0 -0
  3254. /package/dist/{ui → src/ui}/slash/route.test.d.ts +0 -0
  3255. /package/dist/{ui → src/ui}/slash/route.test.js +0 -0
  3256. /package/dist/{ui → src/ui}/status-bar/index.test.js +0 -0
  3257. /package/dist/{ui → src/ui}/status-bar/store.d.ts +0 -0
  3258. /package/dist/{ui → src/ui}/status-bar/store.test.js +0 -0
  3259. /package/dist/{ui → src/ui}/status-bar/tier-badge.d.ts +0 -0
  3260. /package/dist/{ui → src/ui}/status-bar/tier-badge.js +0 -0
  3261. /package/dist/{ui → src/ui}/status-bar/tier-badge.test.js +0 -0
  3262. /package/dist/{ui → src/ui}/status-bar/usd-meter.d.ts +0 -0
  3263. /package/dist/{ui → src/ui}/status-bar/usd-meter.js +0 -0
  3264. /package/dist/{ui → src/ui}/status-bar/usd-meter.test.js +0 -0
  3265. /package/dist/{ui → src/ui}/terminal-selection-text.d.ts +0 -0
  3266. /package/dist/{ui → src/ui}/terminal-selection-text.js +0 -0
  3267. /package/dist/{usage → src/usage}/downgrade.d.ts +0 -0
  3268. /package/dist/{usage → src/usage}/downgrade.js +0 -0
  3269. /package/dist/{usage → src/usage}/downgrade.test.js +0 -0
  3270. /package/dist/{usage → src/usage}/estimator.test.js +0 -0
  3271. /package/dist/{usage → src/usage}/ledger.test.js +0 -0
  3272. /package/dist/{usage → src/usage}/midstream.d.ts +0 -0
  3273. /package/dist/{usage → src/usage}/midstream.js +0 -0
  3274. /package/dist/{usage → src/usage}/midstream.test.js +0 -0
  3275. /package/dist/{usage → src/usage}/thresholds.d.ts +0 -0
  3276. /package/dist/{usage → src/usage}/thresholds.js +0 -0
  3277. /package/dist/{usage → src/usage}/thresholds.test.js +0 -0
  3278. /package/dist/{usage → src/usage}/types.js +0 -0
  3279. /package/dist/{utils → src/utils}/at-mentions.d.ts +0 -0
  3280. /package/dist/{utils → src/utils}/at-mentions.js +0 -0
  3281. /package/dist/{utils → src/utils}/clipboard-image.d.ts +0 -0
  3282. /package/dist/{utils → src/utils}/file-index.d.ts +0 -0
  3283. /package/dist/{utils → src/utils}/file-index.js +0 -0
  3284. /package/dist/{utils → src/utils}/git-root.d.ts +0 -0
  3285. /package/dist/{utils → src/utils}/git-root.js +0 -0
  3286. /package/dist/{utils → src/utils}/install-manager.d.ts +0 -0
  3287. /package/dist/{utils → src/utils}/install-manager.js +0 -0
  3288. /package/dist/{utils → src/utils}/instructions.d.ts +0 -0
  3289. /package/dist/{utils → src/utils}/permission-mode.d.ts +0 -0
  3290. /package/dist/{utils → src/utils}/permission-mode.js +0 -0
  3291. /package/dist/{utils → src/utils}/permission-mode.test.js +0 -0
  3292. /package/dist/{utils → src/utils}/redactor.d.ts +0 -0
  3293. /package/dist/{utils → src/utils}/redactor.js +0 -0
  3294. /package/dist/{utils → src/utils}/side-question.d.ts +0 -0
  3295. /package/dist/{utils → src/utils}/side-question.js +0 -0
  3296. /package/dist/{utils → src/utils}/skills.d.ts +0 -0
  3297. /package/dist/{utils → src/utils}/subagent-display.d.ts +0 -0
  3298. /package/dist/{utils → src/utils}/subagent-display.js +0 -0
  3299. /package/dist/{utils → src/utils}/update-checker.d.ts +0 -0
  3300. /package/dist/{verify → src/verify}/checkpoint.js +0 -0
  3301. /package/dist/{verify → src/verify}/evidence.js +0 -0
  3302. /package/dist/{verify → src/verify}/retry.js +0 -0
@@ -1,44 +1,35 @@
1
1
  // Multi-provider wired — runtime dispatch via providers/runtime.ts.
2
2
 
3
- import { APICallError } from "@ai-sdk/provider";
4
- import { convertToBase64 } from "@ai-sdk/provider-utils";
5
- import { generateText, type ModelMessage, stepCountIs, streamText, type ToolSet } from "ai";
3
+ import type { ModelMessage, ToolSet } from "ai";
4
+ import { extractSession } from "../ee/extract-session.js";
5
+ import { bootstrapEEClient, getDefaultEEClient, getLastSurfacedState } from "../ee/intercept.js";
6
+ import { getTenantId } from "../ee/tenant.js";
6
7
  import { createRun, getActiveRunId, setActiveRunId } from "../flow/run-manager.js";
7
8
  import { ensureFlowDir } from "../flow/scaffold.js";
8
9
  import { executeEventHooks } from "../hooks/index";
9
- import type { PreToolUseHookInput, PostToolUseHookInput } from "../hooks/types";
10
- import { bootstrapEEClient, getDefaultEEClient, getLastSurfacedState } from "../ee/intercept.js";
11
- import { getTenantId } from "../ee/tenant.js";
12
- import { routeFeedback, routeModel } from "../ee/bridge.js";
13
- import { reportRouteOutcome } from "../router/decide.js";
14
- import { routerStore } from "../router/store.js";
15
- import { statusBarStore } from "../ui/status-bar/store.js";
16
- import { taskTypeToTier, taskTypeToMaxTokens, taskTypeToReasoningEffort } from "../pil/task-tier-map.js";
17
10
  import type {
18
11
  NotificationHookInput,
19
12
  PostCompactHookInput,
20
13
  PreCompactHookInput,
21
14
  SessionEndHookInput,
22
- SessionStartHookInput,
23
- StopFailureHookInput,
24
- StopHookInput,
25
15
  SubagentStartHookInput,
26
16
  SubagentStopHookInput,
27
17
  TaskCompletedHookInput,
28
18
  TaskCreatedHookInput,
29
- UserPromptSubmitHookInput,
30
19
  } from "../hooks/types";
31
20
  import { shutdownWorkspaceLspManager } from "../lsp/runtime";
32
- import { extractSession } from "../ee/extract-session.js";
33
21
  import { ensureDefaultMcpServers } from "../mcp/auto-setup.js";
34
- import { buildMcpToolSet } from "../mcp/runtime";
35
- import { createBuiltinTools } from "../tools/registry.js";
22
+ import { getModelByTier, getModelInfo, normalizeModelId } from "../models/registry.js";
23
+ import { getProviderCapabilities } from "../providers/capabilities.js";
24
+ import { apiBaseFor } from "../providers/endpoints.js";
36
25
  import { loadKeyForProvider } from "../providers/keychain.js";
37
- import { captureToolSchemas } from "../providers/patch-zod-schema.js";
38
- import { getModelInfo, normalizeModelId } from "../models/registry.js";
39
- import { needsVisionProxy, proxyVision } from "../providers/vision-proxy.js";
40
- import { isDebugEnabled, recordTurnTrace, type PipelineStep, type TurnTrace } from "../ui/slash/debug.js";
41
- import { applyPilSuffix, getResponseToolSet, isResponseTool, getResponseTaskType, runPipeline } from "../pil/index.js";
26
+ import {
27
+ createProviderFactory,
28
+ createProviderFactoryAsync,
29
+ detectProviderForModel,
30
+ resolveModelRuntime as resolveRuntime,
31
+ } from "../providers/runtime.js";
32
+ import type { ProviderId } from "../providers/types.js";
42
33
  import {
43
34
  appendCompaction,
44
35
  appendMessages,
@@ -48,16 +39,17 @@ import {
48
39
  getSessionTotalTokens,
49
40
  loadTranscript,
50
41
  loadTranscriptState,
42
+ logInteraction,
43
+ markMessageCompleted,
51
44
  recordUsageEvent,
52
45
  SessionStore,
53
46
  } from "../storage/index";
54
47
  import { BashTool } from "../tools/bash";
48
+ import { createBuiltinTools } from "../tools/registry.js";
55
49
  import { type ScheduleDaemonStatus, ScheduleManager, type StoredSchedule } from "../tools/schedule";
56
50
  import type {
57
51
  AgentMode,
58
52
  ChatEntry,
59
- ModelInfo,
60
- Plan,
61
53
  SessionInfo,
62
54
  SessionSnapshot,
63
55
  StreamChunk,
@@ -69,115 +61,82 @@ import type {
69
61
  VerifyRecipe,
70
62
  WorkspaceInfo,
71
63
  } from "../types/index";
72
- import { loadCustomInstructions } from "../utils/instructions";
73
- import { type PermissionMode, toolNeedsApproval } from "../utils/permission-mode.js";
64
+ import { statusBarStore } from "../ui/status-bar/store.js";
65
+ import { appendCostLog } from "../usage/cost-log.js";
66
+ import { appendDecisionLog } from "../usage/decision-log.js";
67
+ import { projectCostUSD } from "../usage/estimator.js";
68
+ import type { PermissionMode } from "../utils/permission-mode.js";
74
69
  import {
75
70
  type CustomSubagentConfig,
71
+ getAutoCompactThresholdPct,
72
+ getCouncilRounds,
76
73
  getCurrentModel,
74
+ getCurrentShellSettings,
77
75
  getModeSpecificModel,
78
- getCouncilRounds,
79
76
  getRoleModel,
80
77
  getRoleModels,
81
- getAutoCompactThresholdPct,
82
78
  isAutoCompactAfterTurnEnabled,
83
- isAutoCouncilEnabled,
84
- loadMcpServers,
85
- loadValidSubAgents,
79
+ isCouncilMultiProviderPreferred,
80
+ isProviderDisabled,
86
81
  type ModelRole,
87
82
  type SandboxMode,
88
83
  type SandboxSettings,
89
84
  } from "../utils/settings";
90
85
  import { runSideQuestion, type SideQuestionResult } from "../utils/side-question";
91
- import { discoverSkills, formatSkillsForPrompt } from "../utils/skills";
92
- import { buildVerifyDetectPrompt, normalizeVerifyRecipe, prepareVerifySandbox } from "../verify/entrypoint";
86
+ import { buildVerifyDetectPrompt, normalizeVerifyRecipe } from "../verify/entrypoint";
93
87
  import { runVerifyOrchestration } from "../verify/orchestrator";
88
+ import {
89
+ type AgentOptions,
90
+ type BatchChatCompletionResponse,
91
+ type BatchClientOptions,
92
+ type BatchFunctionTool,
93
+ COUNCIL_COLOR_BG,
94
+ COUNCIL_COLOR_RESET,
95
+ COUNCIL_ROLE_COLORS,
96
+ type LegacyProvider,
97
+ type ProcessMessageObserver,
98
+ type ProcessMessageUsage,
99
+ type ResolvedModelRuntime,
100
+ } from "./agent-options";
101
+ import { BatchTurnRunner, type BatchTurnRunnerDeps } from "./batch-turn-runner.js";
102
+ import {
103
+ accumulateUsage,
104
+ buildAssistantBatchMessage,
105
+ buildBatchChatCompletionRequest,
106
+ buildBatchName,
107
+ buildToolBatchMessage,
108
+ type ExecutedBatchTool,
109
+ extractJsonObject,
110
+ getBatchFinishReason,
111
+ getBatchUsage,
112
+ hasUsage,
113
+ parseToolArgumentsOrRaw,
114
+ toLocalToolCall,
115
+ } from "./batch-utils";
94
116
  import {
95
117
  type CompactionSettings,
96
118
  createCompactionSummaryMessage,
97
119
  DEFAULT_KEEP_RECENT_TOKENS,
98
120
  DEFAULT_RESERVE_TOKENS,
99
- POST_TURN_MIN_TOKENS,
100
121
  estimateConversationTokens,
122
+ extractUserContent,
101
123
  generateCompactionSummary,
124
+ POST_TURN_MIN_TOKENS,
102
125
  prepareCompaction,
103
- relaxCompactionSettings,
104
126
  shouldCompactContext,
105
127
  } from "./compaction";
128
+ import { CouncilManager } from "./council-manager.js";
129
+ import { CrossTurnDedup, isCrossTurnDedupEnabled } from "./cross-turn-dedup.js";
106
130
  import { DelegationManager } from "./delegations";
107
131
  import { loadFlowResumeDigest } from "./flow-resume.js";
108
- import { stableCallId } from "./pending-calls.js";
109
- import { containsEncryptedReasoning, sanitizeModelMessages } from "./reasoning";
110
- import {
111
- createProviderFactory,
112
- resolveModelRuntime as resolveRuntime,
113
- detectProviderForModel,
114
- type ProviderFactory,
115
- type ResolvedModelRuntime as RuntimeResult,
116
- } from "../providers/runtime.js";
117
- import type { ProviderId } from "../providers/types.js";
118
-
119
- // ---------------------------------------------------------------------------
120
- // Re-export types from shared runtime module for back-compat
121
- // ---------------------------------------------------------------------------
122
-
123
- export type { ProviderFactory as LegacyProvider, ResolvedModelRuntime } from "../providers/runtime.js";
124
- type LegacyProvider = ProviderFactory;
125
- type ResolvedModelRuntime = RuntimeResult;
126
-
127
- /** @deprecated Use ModelInfo from "../types/index" instead. */
128
- export type ModelInfoStub = ModelInfo;
129
-
130
- // Batch API type stubs
131
- export interface BatchClientOptions {
132
- apiKey: string;
133
- baseURL?: string;
134
- signal?: AbortSignal;
135
- }
136
-
137
- export interface BatchChatMessage {
138
- role: string;
139
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
140
- content: any;
141
- tool_call_id?: string;
142
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
143
- tool_calls?: any[];
144
- name?: string;
145
- }
146
-
147
- export interface BatchFunctionTool {
148
- type: "function";
149
- function: { name: string; description?: string; parameters?: unknown };
150
- }
151
-
152
- export interface BatchToolCall {
153
- id: string;
154
- type: "function";
155
- function: { name: string; arguments: string };
156
- }
157
-
158
- export interface BatchChatCompletionRequest {
159
- model: string;
160
- messages: BatchChatMessage[];
161
- tools?: BatchFunctionTool[];
162
- temperature?: number;
163
- max_tokens?: number;
164
- reasoning_effort?: string;
165
- }
166
-
167
- export interface BatchChatCompletionResponse {
168
- choices: Array<{
169
- message: { role: string; content: string | null; tool_calls?: BatchToolCall[] };
170
- finish_reason: string;
171
- }>;
172
- usage?: {
173
- prompt_tokens: number;
174
- completion_tokens: number;
175
- total_tokens: number;
176
- input_tokens?: number;
177
- output_tokens?: number;
178
- cost_in_usd_ticks?: number;
179
- };
180
- }
132
+ import { MessageProcessor, type MessageProcessorDeps } from "./message-processor.js";
133
+ import { lastPersistedSeq } from "./message-seq.js";
134
+ import { buildSystemPrompt, MAX_TOOL_ROUNDS } from "./prompts";
135
+ import { getReadPathBudgetCap, ReadPathBudget } from "./read-path-budget.js";
136
+ import { withStreamRetry } from "./retry-stream.js";
137
+ import { StreamRunner, type StreamRunnerDeps } from "./stream-runner.js";
138
+ import { setProviderHint } from "./token-counter.js";
139
+ import { firstLine, formatSubagentActivity, toToolResult } from "./tool-utils";
181
140
 
182
141
  // ---------------------------------------------------------------------------
183
142
  // Provider implementations
@@ -252,514 +211,27 @@ function createTools(
252
211
  subagents?: unknown[];
253
212
  sendTelegramFile?: (filePath: string) => Promise<ToolResult>;
254
213
  sessionId?: string;
214
+ modelId?: string;
255
215
  },
256
216
  ): ToolSet {
257
- return createBuiltinTools(
258
- _bash as BashTool,
259
- (_mode ?? "agent") as AgentMode,
260
- {
261
- runTask: _opts?.runTask,
262
- runDelegation: _opts?.runDelegation,
263
- readDelegation: _opts?.readDelegation,
264
- listDelegations: _opts?.listDelegations,
265
- },
266
- );
267
- }
268
-
269
- async function buildVisionUserMessages(_prompt: string, _cwd: string, _signal?: AbortSignal): Promise<ModelMessage[]> {
270
- // Vision input is an anti-feature per PROJECT.md Out-of-Scope. Always throws.
271
- throw new Error("Vision input is not supported in muonroi-cli (anti-feature per PROJECT.md).");
217
+ return createBuiltinTools(_bash as BashTool, (_mode ?? "agent") as AgentMode, {
218
+ runTask: _opts?.runTask,
219
+ runDelegation: _opts?.runDelegation,
220
+ readDelegation: _opts?.readDelegation,
221
+ listDelegations: _opts?.listDelegations,
222
+ modelId: _opts?.modelId,
223
+ });
272
224
  }
273
225
 
274
226
  // ---------------------------------------------------------------------------
275
227
  // END Plan 00-05 provider implementations
228
+ // (Phase 12.3 — `buildVisionUserMessages` was inlined into StreamRunner;
229
+ // vision is an anti-feature per PROJECT.md Out-of-Scope so the helper is gone.)
276
230
  // ---------------------------------------------------------------------------
277
231
 
278
- const MAX_TOOL_ROUNDS = 75;
279
- const VISION_MODEL = "grok-4-1-fast-reasoning";
280
- const COMPUTER_MODEL = "grok-4.20-0309-reasoning";
281
-
282
- interface AgentOptions {
283
- persistSession?: boolean;
284
- session?: string;
285
- sandboxMode?: SandboxMode;
286
- sandboxSettings?: SandboxSettings;
287
- batchApi?: boolean;
288
- /** Optional external AbortContext (from src/index.ts SIGINT handler). When provided,
289
- * the orchestrator uses its signal instead of creating a new AbortController per turn.
290
- * TUI-04: Ctrl+C mid-tool-call abort safety. */
291
- abortContext?: import("./abort.js").AbortContext;
292
- /** Optional PendingCallsLog for Pitfall 9 staged-write tracking per tool call. */
293
- pendingCalls?: import("./pending-calls.js").PendingCallsLog;
294
- /** Permission mode controlling which tool calls require manual approval.
295
- * safe (default) = confirm all; auto-edit = auto-approve file ops; yolo = auto-approve all. */
296
- permissionMode?: PermissionMode;
297
- }
298
-
299
- type ProcessMessageFinishReason = "stop" | "length" | "content-filter" | "tool-calls" | "error" | "other";
300
-
301
- export interface ProcessMessageUsage {
302
- inputTokens?: number;
303
- outputTokens?: number;
304
- totalTokens?: number;
305
- costUsdTicks?: number;
306
- cacheReadTokens?: number;
307
- cacheCreationTokens?: number;
308
- }
309
-
310
- export interface ProcessMessageStepStart {
311
- stepNumber: number;
312
- timestamp: number;
313
- }
314
-
315
- export interface ProcessMessageStepFinish {
316
- stepNumber: number;
317
- timestamp: number;
318
- finishReason: ProcessMessageFinishReason;
319
- usage: ProcessMessageUsage;
320
- }
321
-
322
- export interface ProcessMessageToolStart {
323
- toolCall: ToolCall;
324
- timestamp: number;
325
- }
326
-
327
- export interface ProcessMessageToolFinish {
328
- toolCall: ToolCall;
329
- toolResult: ToolResult;
330
- timestamp: number;
331
- }
332
-
333
- export interface ProcessMessageError {
334
- message: string;
335
- timestamp: number;
336
- }
337
-
338
- export interface ProcessMessageObserver {
339
- onStepStart?(info: ProcessMessageStepStart): void;
340
- onStepFinish?(info: ProcessMessageStepFinish): void;
341
- onToolStart?(info: ProcessMessageToolStart): void;
342
- onToolFinish?(info: ProcessMessageToolFinish): void;
343
- onError?(info: ProcessMessageError): void;
344
- }
345
-
346
- const ENVIRONMENT = `ENVIRONMENT:
347
- You are running inside a terminal (CLI). Your text output is rendered in a plain terminal — not a browser, not a rich text editor.
348
- - Use plain text only. No markdown tables, no HTML, no images, no colored text.
349
- - Use simple markers like dashes (-) or asterisks (*) for lists.
350
- - Use indentation and blank lines for structure.
351
- - Keep lines under 100 characters when possible.
352
- - Use backticks for inline code and triple backticks for code blocks — these are rendered.
353
- - Never use unicode box-drawing, fancy borders, or ASCII art in your responses.`;
354
-
355
- const MODE_PROMPTS: Record<AgentMode, string> = {
356
- agent: `You are muonroi-cli in Agent mode — a powerful AI coding agent. You execute tasks directly using tools.
357
-
358
- ${ENVIRONMENT}
359
-
360
- TOOLS:
361
- - read_file: Read file contents with start_line/end_line for iterative reading. Use for examining code.
362
- - grep: Fast regex content search across the codebase. Prefer this over bash for finding patterns in files. Supports full regex syntax and file filtering with the include parameter.
363
- - lsp: Experimental semantic code intelligence for definitions, references, hover, symbols, implementations, and call hierarchy when a matching language server is available.
364
- - write_file: Create new files or overwrite existing ones with full content.
365
- - edit_file: Replace a unique string in a file with new content. The old_string must be unique — include enough context lines.
366
- - bash: Execute shell commands. Set background=true for long-running processes (dev servers, watchers, builds). Returns a process ID immediately.
367
- - process_logs: View recent output from a background process by ID.
368
- - process_stop: Stop a background process by ID.
369
- - process_list: List all background processes with status and uptime.
370
- - wallet_info: Check the local wallet address, chain, and current ETH/USDC balances.
371
- - wallet_history: Show recent x402 payment history from the audit log.
372
- - fetch_payment_info: Inspect a URL for x402 payment requirements without paying. Returns payment options and a brin security score. Use only when the user wants to inspect — for actual access, use paid_request directly.
373
- - paid_request: Access an x402-protected URL using the local wallet. Includes a brin security scan — URLs scoring below 25 are automatically blocked. The user will be prompted to approve the payment before it executes. Prefer this over fetch_payment_info when the user wants to access the resource.
374
- - task: Delegate a focused foreground task to a sub-agent. Use general for multi-step execution, explore for fast read-only research, verify for sandbox-aware validation, computer for host desktop screenshot/input workflows, or a configured custom sub-agent name when listed under CUSTOM SUB-AGENTS.
375
- - delegate: Launch a read-only background agent for longer research while you continue working.
376
- - delegation_read: Retrieve a completed background delegation result by ID.
377
- - delegation_list: List running and completed background delegations. Do not poll it repeatedly.
378
- - schedule_create: Create a recurring or one-time scheduled headless run.
379
- - schedule_list: List saved schedules and their status.
380
- - schedule_remove: Remove a saved schedule.
381
- - schedule_read_log: Read recent log output from a schedule.
382
- - schedule_daemon_status: Check whether the schedule daemon is running.
383
- - schedule_daemon_start: Start the schedule daemon in the background.
384
- - schedule_daemon_stop: Stop the schedule daemon.
385
- - search_web: Search the web for current information, documentation, APIs, tutorials, etc.
386
- - search_x: Search X/Twitter for real-time posts, discussions, opinions, and trends.
387
- - generate_image: Generate a new image or edit an existing image. It saves image files locally and returns their paths.
388
- - generate_video: Generate a new video or animate an existing image. It saves video files locally and returns their paths.
389
- - computer_snapshot: Capture an accessibility-tree snapshot with stable refs like @e1 for desktop interaction.
390
- - computer_screenshot: Capture a host desktop screenshot for visual confirmation or fallback inspection.
391
- - computer_click: Click a desktop element by ref, or coordinates as a fallback.
392
- - computer_mouse_move: Hover a desktop element by ref, or coordinates as a fallback.
393
- - computer_type: Type text into a specific desktop element ref.
394
- - computer_press: Press a key or key chord in the focused host application.
395
- - computer_scroll: Scroll a desktop element by ref.
396
- - computer_launch: Launch an application and wait for its window to appear.
397
- - computer_list_windows: List visible windows and their ids.
398
- - computer_focus_window: Bring a target window to the front.
399
- - computer_wait: Wait for time, elements, windows, or text during desktop workflows.
400
- - computer_get: Read a property from a desktop element ref.
401
- - MCP tools: Enabled servers appear as tools named like mcp_<server>__<tool>.
402
-
403
- WORKFLOW:
404
- 1. Understand the request
405
- 2. Decide whether a sub-agent should handle the first investigation pass
406
- 3. Use read_file, grep, lsp, and bash to explore the codebase directly when the task is small or tightly scoped
407
- 4. Use bash with background=true for dev servers, watchers, or any long-running process — then continue working
408
- 5. Use delegate for read-only work that can run in parallel, then continue productive work
409
- 6. Use edit_file for targeted changes, write_file for new files or full rewrites
410
- 7. Verify changes by reading modified files
411
- 8. Run tests or builds with bash to confirm correctness
412
- 9. Use search_web or search_x when you need up-to-date information
413
-
414
- DEFAULT DELEGATION POLICY:
415
- - Prefer the task tool by default for code review, code quality analysis, architecture research, root-cause investigation, bug triage, verification, or any request that likely needs reading multiple files before acting.
416
- - Prefer delegate for longer-running read-only exploration when you can keep making progress without blocking.
417
- - Use the explore sub-agent for read-only investigation, reviews, research, and "how does this work?" tasks.
418
- - Use the general sub-agent for delegated work that may need editing files, running commands, or producing a concrete implementation.
419
- - Use the verify sub-agent for sandbox-aware build, test, app boot, and smoke validation work.
420
- - Use the computer sub-agent for host desktop interaction workflows that need screenshots, clicks, typing, keypresses, or scrolling.
421
- - Use a matching custom sub-agent when the task fits one of the configured specializations.
422
- - Never use delegate for tasks that should edit files or make shell changes.
423
- - When a background delegation is running, do not wait idly and do not spam delegation_list(). Continue useful work.
424
- - Do not wait for the user to explicitly ask for a sub-agent when delegation would clearly help.
425
- - Skip delegation only when the task is trivial, single-file, or you already have the exact answer.
426
-
427
- EXAMPLES:
428
- - "review this change" -> delegate to explore first
429
- - "research how auth works" -> delegate to explore first
430
- - "investigate why this test fails" -> delegate to explore first, then continue with findings
431
- - "refactor this module" -> delegate a focused part to general when helpful
432
- - "verify this feature locally" -> use verify
433
- - "open the host app and click through it" -> use computer
434
- - "generate a logo" -> use generate_image
435
- - "animate this still image" -> use generate_video
436
- - Recurring specialized workflows -> use the matching custom sub-agent via task
437
- - "every weekday at 9am run this check" -> use schedule_create with a cron expression
438
- - "run this once automatically" -> use schedule_create with the right timing
439
- - "make sure scheduled jobs keep running" -> use schedule_daemon_status and schedule_daemon_start
440
-
441
- IMPORTANT:
442
- - Prefer edit_file for surgical changes to existing files — it shows a clean diff.
443
- - Prefer grep over bash for searching file contents. Use bash only for find, ls, git, and other shell commands.
444
- - Prefer lsp over text search when you need exact definitions, references, implementations, or call hierarchy and a server is available.
445
- - Use write_file only for new files or when most of the file is changing.
446
- - Use read_file instead of cat/head/tail for reading files.
447
- - When the user asks for an automated recurring or one-time run, use the schedule tools instead of only describing the setup.
448
- - After creating a recurring schedule, check the daemon status and start it with \`schedule_daemon_start\` if needed.
449
-
450
- Be direct. Execute, don't just describe. Show results, not plans.`,
451
-
452
- plan: `You are muonroi-cli in Plan mode — you analyze and plan but DO NOT execute changes.
453
-
454
- ${ENVIRONMENT}
455
-
456
- TOOLS:
457
- - read_file: Read file contents for analysis.
458
- - grep: Fast regex content search across the codebase. Prefer this over bash for finding patterns in files.
459
- - lsp: Experimental semantic code intelligence for read-only planning and research.
460
- - bash: ONLY for searching (find, ls), git inspection — NEVER modify files.
461
- - task: Delegate a focused task to a sub-agent when deeper research or specialized analysis would help.
462
- - generate_plan: ALWAYS use this to present your plan. Creates an interactive UI with steps and questions.
463
-
464
- BEHAVIOR:
465
- - Explore the codebase first using read_file, grep, and bash to understand the current state
466
- - Prefer lsp for exact symbol navigation when a matching server is available
467
- - ALWAYS call generate_plan to present your plan — never just describe it in text
468
- - Include clear, ordered steps with affected file paths
469
- - Include questions when you need user input on approach, trade-offs, or preferences
470
- - Use "select" questions for single-choice decisions, "multiselect" for picking multiple options, and "text" for free-form input
471
- - Highlight potential risks, edge cases, and dependencies in the plan summary
472
- - NEVER create, modify, or delete files — only read and analyze`,
473
-
474
- ask: `You are muonroi-cli in Ask mode — you answer questions clearly and thoroughly.
475
-
476
- ${ENVIRONMENT}
477
-
478
- TOOLS:
479
- - read_file: Read file contents for context.
480
- - grep: Fast regex content search across the codebase. Prefer this over bash for finding patterns in files.
481
- - lsp: Experimental semantic code intelligence for definitions, references, hover, and symbols.
482
- - bash: ONLY for searching (find, ls), git inspection — NEVER modify.
483
- - task: Delegate a focused task to a sub-agent when specialized analysis or deeper investigation would help.
484
-
485
- BEHAVIOR:
486
- - Answer the user's question directly and thoroughly
487
- - Use tools to gather context when needed, preferring lsp for exact symbol questions when available
488
- - Provide code examples when helpful
489
- - NEVER create, modify, or delete files
490
- - Focus on explanation, not execution`,
491
- };
492
-
493
- function findCustomSubagent(
494
- agent: string,
495
- subagents: CustomSubagentConfig[] = loadValidSubAgents(),
496
- ): CustomSubagentConfig | undefined {
497
- return (
498
- subagents.find((item) => item.name === agent) ??
499
- subagents.find((item) => item.name.toLowerCase() === agent.toLowerCase())
500
- );
501
- }
502
-
503
- function formatCustomSubagentsPromptSection(subagents: CustomSubagentConfig[]): string {
504
- if (subagents.length === 0) return "";
505
-
506
- const lines = subagents.map((agent) => {
507
- const instruction = agent.instruction.trim() || "(none)";
508
- return `### ${agent.name}\n- model: ${agent.model}\n- instruction:\n${instruction}`;
509
- });
510
-
511
- return `\n\nCUSTOM SUB-AGENTS:\nUser-defined foreground sub-agents from ~/.muonroi-cli/user-settings.json. When one matches the task, call the task tool with agent set to the exact name.\n\n${lines.join("\n\n")}\n`;
512
- }
513
-
514
- interface SystemPromptParts {
515
- staticPrefix: string;
516
- dynamicSuffix: string;
517
- }
518
-
519
- const NON_ANTHROPIC_TOOL_PREAMBLE = `\n\nIMPORTANT — TOOL CALLING:
520
- You MUST invoke tools ONLY via the structured function calling API provided to you.
521
- NEVER output XML tags like <tool_name>, <bash>, <read_file>, or <delegate> as text.
522
- If you want to call a tool, use the function calling mechanism — do NOT write tool invocations as text in your response.
523
- Any XML-like tool invocation in your text output will be ignored by the system.\n`;
524
-
525
- /**
526
- * Strip the TOOLS: listing section from system prompt.
527
- * Non-Anthropic models receive tool definitions via the API's structured `tools` parameter;
528
- * keeping the text listing causes them to output raw XML instead of structured tool calls.
529
- */
530
- function stripToolsSection(text: string): string {
531
- return text.replace(/\nTOOLS:\n[\s\S]*?\n(?=WORKFLOW:|BEHAVIOR:|IMPORTANT:|DEFAULT DELEGATION|EXAMPLES:|$)/g, "\n");
532
- }
533
-
534
- function buildSystemPromptParts(
535
- cwd: string,
536
- mode: AgentMode,
537
- sandboxMode: SandboxMode,
538
- planContext?: string | null,
539
- subagents?: CustomSubagentConfig[],
540
- sandboxSettings?: SandboxSettings,
541
- providerId?: string,
542
- ): SystemPromptParts {
543
- const custom = loadCustomInstructions(cwd);
544
- const customSection = custom
545
- ? `\n\nCUSTOM INSTRUCTIONS:\n${custom}\n\nFollow the above alongside standard instructions.\n`
546
- : "";
547
-
548
- const skillsText = formatSkillsForPrompt(discoverSkills(cwd));
549
- const skillsSection = skillsText ? `\n\n${skillsText}\n` : "";
550
- const subagentsSection = formatCustomSubagentsPromptSection(subagents ?? loadValidSubAgents());
551
- const sandboxSection = formatSandboxPromptSection(sandboxMode, sandboxSettings);
552
-
553
- let modePrompt = MODE_PROMPTS[mode];
554
- if (providerId && providerId !== "anthropic") {
555
- modePrompt = stripToolsSection(modePrompt) + NON_ANTHROPIC_TOOL_PREAMBLE;
556
- }
557
-
558
- const staticPrefix = `${modePrompt}${sandboxSection}${customSection}${skillsSection}${subagentsSection}`;
559
-
560
- const planSection = planContext
561
- ? `\n\nAPPROVED PLAN:\nThe following plan has been approved by the user. Execute it now.\n${planContext}\n`
562
- : "";
563
-
564
- const dynamicSuffix = `${planSection}\n\nCurrent working directory: ${cwd}`;
565
-
566
- return { staticPrefix, dynamicSuffix };
567
- }
568
-
569
- function buildSystemPrompt(
570
- cwd: string,
571
- mode: AgentMode,
572
- sandboxMode: SandboxMode,
573
- planContext?: string | null,
574
- subagents?: CustomSubagentConfig[],
575
- sandboxSettings?: SandboxSettings,
576
- providerId?: string,
577
- ): string {
578
- const { staticPrefix, dynamicSuffix } = buildSystemPromptParts(cwd, mode, sandboxMode, planContext, subagents, sandboxSettings, providerId);
579
- return `${staticPrefix}${dynamicSuffix}`;
580
- }
581
-
582
- function buildSubagentPrompt(
583
- request: TaskRequest,
584
- cwd: string,
585
- custom: CustomSubagentConfig | null,
586
- sandboxMode: SandboxMode,
587
- subagents?: CustomSubagentConfig[],
588
- sandboxSettings?: SandboxSettings,
589
- providerId?: string,
590
- ): string {
591
- const isExplore = request.agent === "explore";
592
- const isVision = request.agent === "vision";
593
- const isVerify = request.agent === "verify";
594
- const isVerifyDetect = request.agent === "verify-detect";
595
- const isVerifyManifest = request.agent === "verify-manifest";
596
- const isComputer = request.agent === "computer";
597
- const mode: AgentMode = isExplore || isVerifyDetect ? "ask" : "agent";
598
- const role = custom
599
- ? `You are the custom sub-agent "${custom.name}". You can investigate, edit files, and run commands unless the delegated task says otherwise.`
600
- : request.agent === "explore"
601
- ? "You are the Explore sub-agent. You are read-only and focus on fast codebase research."
602
- : isVision
603
- ? "You are the Vision sub-agent."
604
- : isVerifyDetect
605
- ? "You are the Verify Detect sub-agent. You inspect a repository to produce a structured verification recipe. You are read-only."
606
- : isVerifyManifest
607
- ? "You are the Verify Manifest sub-agent. You inspect a repository and create or update .muonroi-cli/environment.json so verification can run reproducibly."
608
- : isVerify
609
- ? "You are the Verify sub-agent. You specialize in sandbox-aware local verification using builds, tests, app boot checks, and optional browser smoke tests."
610
- : isComputer
611
- ? "You are the Computer sub-agent. You specialize in host desktop automation using accessibility snapshots, semantic element refs, screenshots, and careful mouse and keyboard actions."
612
- : "You are the General sub-agent. You can investigate, edit files, and run commands to complete delegated work.";
613
-
614
- const rules = isExplore
615
- ? [
616
- "Do not create, modify, or delete files.",
617
- "Prefer `read_file` and search commands over broad shell exploration.",
618
- "Return concise findings for the parent agent.",
619
- ]
620
- : isVerifyDetect
621
- ? [
622
- "Do not create, modify, or delete files.",
623
- "Read config files, package manifests, scripts, and source layout to understand the project.",
624
- "Return ONLY a valid JSON object with the VerifyRecipe schema. No markdown, no prose, no explanation outside the JSON.",
625
- ]
626
- : isVerifyManifest
627
- ? [
628
- "Focus on creating or updating .muonroi-cli/environment.json as the primary verification contract for this repository.",
629
- "Read package.json and key config files to understand the project, then write .muonroi-cli/environment.json.",
630
- "Prefer editing only .muonroi-cli/environment.json unless the delegated task explicitly requires something else.",
631
- "",
632
- "SANDBOX ENVIRONMENT (Shuru):",
633
- "- OS: Debian GNU/Linux 13 (trixie)",
634
- "- Architecture: aarch64 (ARM64)",
635
- "- Pre-installed: NOTHING. No node, npm, npx, bun, python3, pip, go, cargo, java, or any runtime.",
636
- "- Only basic system tools exist (sh, apt-get, curl, etc).",
637
- "- Network access is available during bootstrap and install.",
638
- "- The workspace is mounted at /workspace.",
639
- "",
640
- "MANIFEST REQUIREMENTS:",
641
- "- bootstrapCommands: MUST install every runtime and build tool the project needs from scratch via apt-get or curl.",
642
- "- For Node.js/Next.js/Vite/etc: `apt-get update && apt-get install -y curl unzip ca-certificates git python3 make g++ pkg-config nodejs npm`",
643
- "- For Bun projects: also `curl -fsSL https://bun.sh/install | bash` and shellInitCommands with BUN_INSTALL/PATH exports.",
644
- "- For Python: `apt-get update && apt-get install -y python3 python3-pip python3-venv ca-certificates git`",
645
- "- For Go: `apt-get update && apt-get install -y golang ca-certificates git`",
646
- "- For Rust: `apt-get update && apt-get install -y curl ca-certificates git build-essential && curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh -s -- -y`",
647
- "- installCommands: The package install command (npm install, pip install, etc).",
648
- "- buildCommands: Build commands if applicable.",
649
- "- testCommands: Test/lint commands if applicable.",
650
- "- startCommand + startPort: How to start the app for smoke testing.",
651
- "- smokeKind: 'http' if the app has a web UI, 'cli' for CLI tools, 'none' otherwise.",
652
- "- Do NOT leave bootstrapCommands empty. The sandbox has nothing.",
653
- "",
654
- "Return a concise summary of what you wrote and why.",
655
- ]
656
- : isVision
657
- ? ["Validate the image."]
658
- : isComputer
659
- ? [
660
- "Operate carefully on the HOST desktop, not inside the shell sandbox.",
661
- "Start with `computer_snapshot` when possible. It returns stable refs like @e1 that remain valid until the next snapshot.",
662
- "Prefer accessibility refs over coordinates. Use `computer_click`, `computer_type`, `computer_scroll`, and `computer_get` with refs from the latest snapshot.",
663
- "After any meaningful UI transition, launch, dialog open, or menu change, take another `computer_snapshot` before reusing old refs.",
664
- "Use `computer_launch`, `computer_list_windows`, `computer_focus_window`, and `computer_wait` to manage apps and window state.",
665
- "Use `computer_press` for shortcuts like Enter or cmd+k. Use `computer_screenshot` only for visual confirmation or when the accessibility tree is insufficient.",
666
- "If `agent-desktop` is unavailable, permissions are missing, refs go stale, or the state is ambiguous, stop and return the blocker clearly to the parent agent.",
667
- "Do not perform destructive or high-risk desktop actions unless the delegated task explicitly requires them.",
668
- ]
669
- : isVerify
670
- ? [
671
- "You are a QA engineer. Your job is to prove the app works end-to-end, not just that it builds.",
672
- "Do not make durable source edits unless the delegated task explicitly asks for fixes.",
673
- "",
674
- "MANDATORY VERIFICATION STEPS (do ALL of these in order):",
675
- "1. Install dependencies (run installCommands from the recipe).",
676
- "2. Build the project (run buildCommands from the recipe).",
677
- "3. Run tests/lint if available (run testCommands from the recipe).",
678
- "4. Start the app (run startCommand from the recipe in the background).",
679
- "5. Wait for the app to be ready (curl readiness check or agent-browser wait).",
680
- "6. Run browser smoke tests like a real human QA tester:",
681
- " - Open the app in the browser, record a video, take screenshots.",
682
- " - Navigate the app: click links, buttons, menus. Verify pages load.",
683
- " - Check for JavaScript console errors.",
684
- " - Spend 3-5 interactions testing the critical path.",
685
- "7. Stop recording, close browser, then stop the dev server.",
686
- "",
687
- "Do NOT stop after build/lint. Starting the app and testing it in the browser is the most important part.",
688
- "agent-browser commands run on the HOST, not inside the sandbox. They WILL work. Do not skip them.",
689
- "Return a concise verification report. Keep it compact but always include Evidence with artifact file paths.",
690
- ]
691
- : [
692
- "Work only on the delegated task below.",
693
- "Use tools directly instead of narrating your intent.",
694
- "Return a concise summary for the parent agent with key outcomes and any open risks.",
695
- ];
696
-
697
- const instructionLines = custom?.instruction.trim() ? ["", "SUB-AGENT INSTRUCTIONS:", custom.instruction.trim()] : [];
698
-
699
- return [
700
- role,
701
- ...instructionLines,
702
- "",
703
- "You are helping a parent agent. Do not address the end user directly.",
704
- "Focus tightly on the delegated scope and summarize what matters back to the parent agent.",
705
- "",
706
- ...rules,
707
- "",
708
- `Delegated task: ${request.description}`,
709
- "",
710
- buildSystemPrompt(cwd, mode, sandboxMode, undefined, subagents, sandboxSettings, providerId),
711
- ].join("\n");
712
- }
713
-
714
- function formatSandboxPromptSection(sandboxMode: SandboxMode, settings?: SandboxSettings): string {
715
- if (sandboxMode === "off") return "";
716
-
717
- const s = settings ?? {};
718
- let networkLine: string;
719
- if (s.allowNet) {
720
- networkLine = s.allowedHosts?.length
721
- ? `- Network access is restricted to: ${s.allowedHosts.join(", ")}.`
722
- : "- Network access is enabled.";
723
- } else {
724
- networkLine = "- Network is disabled.";
725
- }
726
-
727
- const lines = [
728
- "",
729
- "SANDBOX MODE:",
730
- "- Bash commands run inside a Shuru sandbox.",
731
- networkLine,
732
- "- The current workspace is mounted inside the sandbox at `/workspace`.",
733
- "- Shell-side workspace file changes do not persist back to the host in this version.",
734
- "- Use `read_file`, `edit_file`, and `write_file` for durable source edits.",
735
- "- If a task needs a host-persistent shell mutation, explain that sandbox mode blocks that workflow and ask whether to disable sandbox mode.",
736
- ];
737
-
738
- if (s.ports?.length) {
739
- lines.push(`- Port forwards: ${s.ports.join(", ")}.`);
740
- }
741
- if (s.from) {
742
- lines.push(`- Starting from checkpoint: ${s.from}.`);
743
- }
744
-
745
- return lines.join("\n");
746
- }
747
-
748
- function applyModelConstraints(system: string, modelId: string): string {
749
- const modelInfo = getModelInfo(modelId);
750
- if (modelInfo?.supportsClientTools !== false) {
751
- return system;
752
- }
753
-
754
- return [
755
- system,
756
- "",
757
- "MODEL CONSTRAINTS:",
758
- "- The selected model does not support client-side CLI tool calls in this environment.",
759
- "- Do not call bash, read_file, lsp, write_file, edit_file, task, delegate, delegation, or MCP tools.",
760
- "- Answer directly using only the conversation context already provided.",
761
- ].join("\n");
762
- }
232
+ // ============================================================================
233
+ // Agent class — fields, constructor, session management, core processing loop
234
+ // ============================================================================
763
235
 
764
236
  export class Agent {
765
237
  private provider: LegacyProvider | null = null;
@@ -787,6 +259,20 @@ export class Agent {
787
259
  /** PIL context for current turn — set after runPipeline, cleared after recordUsage. */
788
260
  private _pilActive = false;
789
261
  private _pilEnrichmentDelta = 0;
262
+ /**
263
+ * Breakdown of the system prompt + messages + tools sent on the last call.
264
+ * Captured immediately before streamText and consumed by recordUsage to
265
+ * attach to the cost-log entry. Cleared after recordUsage so subsequent
266
+ * non-message calls don't reuse stale data.
267
+ */
268
+ private _lastPromptBreakdown: Record<string, number> | null = null;
269
+ /**
270
+ * Phase O1 — JSON-shape of the providerOptions object on the most
271
+ * recent streamText call. Captured immediately before streamText and
272
+ * consumed by recordUsage; cleared after. Cost-leak forensics surfaces
273
+ * this so we can answer "did this billed call carry store=true?" etc.
274
+ */
275
+ private _lastProviderOptionsShape: string | null = null;
790
276
  /** External abort context from src/index.ts SIGINT handler (TUI-04). */
791
277
  private externalAbortContext: import("./abort.js").AbortContext | null = null;
792
278
  /** Pending calls log for Pitfall 9 staged-write tracking. */
@@ -799,10 +285,50 @@ export class Agent {
799
285
  private _activeRunId: string | null = null;
800
286
  /** Resume digest loaded from active flow run state.md. */
801
287
  private _resumeDigest: string | null = null;
288
+ /**
289
+ * Phase 12.1-02: All council state (synthesis/continuation flags, resolver
290
+ * + buffer maps, stats) lives inside CouncilManager. Agent holds one ref.
291
+ */
292
+ private councilManager: CouncilManager;
802
293
  /** Whether compaction already ran during the current turn (prevents double-compact). */
803
294
  private _compactedThisTurn = false;
295
+ /** Guard: OAuth provider init runs at most once per Agent instance. */
296
+ private _oauthInitDone = false;
297
+ /** P0 native observation: warning IDs surfaced earlier in this session — sent as intent_context.priorWarningIdsInSession. */
298
+ private _priorWarningIdsInSession = new Set<string>();
299
+ /** EE session guidance: structured warnings accumulated across turns — injected into model context at turn start. Keyed by principle_uuid to deduplicate. */
300
+ private _sessionEEGuidance = new Map<
301
+ string,
302
+ { toolName: string; message: string; why: string; confidence: number }
303
+ >();
304
+ /** P0 native observation: rolling buffer of assistant reasoning text in current turn — last 200 chars sent as intent_context.assistantReasoningExcerpt. */
305
+ private _turnAssistantReasoning = "";
306
+ /** Per-call correlation id for top-level streamText; set in MessageProcessor, consumed by recordUsage / onFinish llm-done. */
307
+ private _currentCallId = "";
308
+ /** P0 native observation: first 200 chars of the user's current turn — sent as intent_context.userGoalExcerpt to PreToolUse. */
309
+ private _turnUserGoalExcerpt = "";
804
310
  /** Compaction statistics tracking count and total tokens saved. */
805
311
  private _compactionStats: { count: number; totalSaved: number } = { count: 0, totalSaved: 0 };
312
+ /**
313
+ * Pinned message sequences. A pinned user message is preserved verbatim across
314
+ * compaction — it is re-injected as a system note immediately after the
315
+ * compaction summary, so the model still sees the original wording.
316
+ * V1 only supports user messages (avoids splitting tool-call/result pairs).
317
+ */
318
+ private _pinnedSeqs = new Set<number>();
319
+ /** One-shot cwd note injected at the start of the next processMessage turn after setCwd(). Cleared after injection. */
320
+ private _pendingCwdNote: string | null = null;
321
+
322
+ // Phase C3: cross-turn tool-output dedup. One instance per session; bumped
323
+ // on each user turn. Lazily initialized so disabled-via-env path stays cheap.
324
+ private _crossTurnDedup: CrossTurnDedup | null = isCrossTurnDedupEnabled() ? new CrossTurnDedup() : null;
325
+ // Phase C4 — input-keyed read-path budget. Complements C3 (output hash) by
326
+ // catching re-reads of files the agent edited between rounds. Disabled
327
+ // when MUONROI_MAX_READS_PER_PATH=0.
328
+ private _readBudget: ReadPathBudget | null = (() => {
329
+ const cap = getReadPathBudgetCap();
330
+ return cap > 0 ? new ReadPathBudget(cap) : null;
331
+ })();
806
332
 
807
333
  constructor(
808
334
  apiKey: string | undefined,
@@ -815,12 +341,25 @@ export class Agent {
815
341
  this.bash = new BashTool(process.cwd(), {
816
342
  sandboxMode: options.sandboxMode ?? "off",
817
343
  sandboxSettings: options.sandboxSettings,
344
+ shellSettings: options.shellSettings ?? getCurrentShellSettings(),
818
345
  });
819
346
  this.delegations = new DelegationManager(() => this.bash.getCwd());
347
+ // Phase 12.1-02: council state + helpers live in CouncilManager. DI via
348
+ // getter callbacks so the manager reads live Agent state without holding
349
+ // a circular reference to the Agent instance.
350
+ this.councilManager = new CouncilManager({
351
+ getModelId: () => this.modelId,
352
+ getSessionId: () => this.session?.id ?? null,
353
+ hasSessionStore: () => this.sessionStore !== null,
354
+ getMessages: () => this.messages,
355
+ getBash: () => this.bash,
356
+ getMode: () => this.mode,
357
+ });
820
358
 
821
359
  const initialMode: AgentMode = "agent";
822
360
  this.modelId = normalizeModelId(model || getCurrentModel(initialMode));
823
361
  this.providerId = detectProviderForModel(this.modelId);
362
+ setProviderHint(this.providerId);
824
363
  if (apiKey) {
825
364
  this.setApiKey(apiKey, baseURL);
826
365
  }
@@ -858,7 +397,7 @@ export class Agent {
858
397
  * Fail-open: any error sets _activeRunId = null silently.
859
398
  */
860
399
  private async _initFlow(): Promise<void> {
861
- bootstrapEEClient().catch(() => {});
400
+ await bootstrapEEClient().catch(() => {});
862
401
  try {
863
402
  const flowDir = await ensureFlowDir(this.bash.getCwd());
864
403
  const existing = await getActiveRunId(flowDir);
@@ -894,9 +433,11 @@ export class Agent {
894
433
  const newProviderId = detectProviderForModel(this.modelId);
895
434
  if (newProviderId !== this.providerId && this.apiKey) {
896
435
  this.providerId = newProviderId;
897
- const effectiveBaseURL = this.providerId !== "anthropic" && this.baseURL === "https://api.anthropic.com"
898
- ? undefined
899
- : (this.baseURL ?? undefined);
436
+ setProviderHint(this.providerId);
437
+ const effectiveBaseURL =
438
+ this.providerId !== "anthropic" && this.baseURL === apiBaseFor("anthropic")
439
+ ? undefined
440
+ : (this.baseURL ?? undefined);
900
441
  this.provider = createProvider(this.providerId, this.apiKey, effectiveBaseURL);
901
442
  }
902
443
  if (this.sessionStore && this.session) {
@@ -957,14 +498,14 @@ export class Agent {
957
498
  this.baseURL = baseURL || null;
958
499
  // Only pass baseURL to provider factory if it's an explicit override,
959
500
  // not the default Anthropic URL (which would break non-Anthropic providers).
960
- const effectiveBaseURL = this.providerId !== "anthropic" && baseURL === "https://api.anthropic.com"
961
- ? undefined
962
- : baseURL;
501
+ const effectiveBaseURL =
502
+ this.providerId !== "anthropic" && baseURL === apiBaseFor("anthropic") ? undefined : baseURL;
963
503
  this.provider = createProvider(this.providerId, apiKey, effectiveBaseURL);
964
504
  }
965
505
 
966
506
  setProviderAndKey(providerId: ProviderId, apiKey: string, baseURL?: string): void {
967
507
  this.providerId = providerId;
508
+ setProviderHint(this.providerId);
968
509
  this.setApiKey(apiKey, baseURL);
969
510
  }
970
511
 
@@ -976,6 +517,11 @@ export class Agent {
976
517
  return this.bash.getCwd();
977
518
  }
978
519
 
520
+ setCwd(dir: string): void {
521
+ this.bash.setCwd(dir);
522
+ this._pendingCwdNote = `(system: working directory has been changed to ${dir} — subsequent shell commands run from there; do NOT cd to that path again)`;
523
+ }
524
+
979
525
  getMessages(): ModelMessage[] {
980
526
  return this.messages;
981
527
  }
@@ -1100,8 +646,7 @@ export class Agent {
1100
646
 
1101
647
  async clearHistory(): Promise<void> {
1102
648
  // D-09: Extract messages accumulated since last clear BEFORE reset
1103
- await extractSession(this.messages, this.bash.getCwd(), "cli-clear", this.getSessionId())
1104
- .catch(() => {}); // D-05: redundant safety — extractSession already swallows
649
+ await extractSession(this.messages, this.bash.getCwd(), "cli-clear", this.getSessionId()).catch(() => {}); // D-05: redundant safety — extractSession already swallows
1105
650
  this.startNewSession();
1106
651
  }
1107
652
 
@@ -1128,6 +673,7 @@ export class Agent {
1128
673
  });
1129
674
 
1130
675
  this._compactionStats = { count: 0, totalSaved: 0 };
676
+ this._pinnedSeqs.clear();
1131
677
 
1132
678
  if (!this.sessionStore) {
1133
679
  this.messages = [];
@@ -1159,6 +705,40 @@ export class Agent {
1159
705
  return { ...this._compactionStats };
1160
706
  }
1161
707
 
708
+ /**
709
+ * Pin a user message by its sequence number. Pinned messages survive
710
+ * compaction verbatim — re-injected as a system note after the summary.
711
+ * Returns true if the message was found, is a user message, and got pinned.
712
+ */
713
+ pinMessageBySeq(seq: number): boolean {
714
+ const idx = this.messageSeqs.indexOf(seq);
715
+ if (idx < 0) return false;
716
+ if (this.messages[idx]?.role !== "user") return false;
717
+ this._pinnedSeqs.add(seq);
718
+ return true;
719
+ }
720
+
721
+ /** Pin the most recent user message in the live conversation. Returns its seq, or null. */
722
+ pinLastUserMessage(): number | null {
723
+ for (let i = this.messages.length - 1; i >= 0; i--) {
724
+ if (this.messages[i]?.role !== "user") continue;
725
+ const seq = this.messageSeqs[i];
726
+ if (typeof seq === "number") {
727
+ this._pinnedSeqs.add(seq);
728
+ return seq;
729
+ }
730
+ }
731
+ return null;
732
+ }
733
+
734
+ unpinMessageBySeq(seq: number): boolean {
735
+ return this._pinnedSeqs.delete(seq);
736
+ }
737
+
738
+ getPinnedSeqs(): number[] {
739
+ return [...this._pinnedSeqs].sort((a, b) => a - b);
740
+ }
741
+
1162
742
  getChatEntries(): ChatEntry[] {
1163
743
  if (!this.session) return [];
1164
744
  return buildChatEntries(this.session.id);
@@ -1191,13 +771,24 @@ export class Agent {
1191
771
  private discardAbortedTurn(userMessage: ModelMessage): void {
1192
772
  const idx = this.messages.lastIndexOf(userMessage);
1193
773
  if (idx >= 0) {
1194
- this.messages.splice(idx, 1);
1195
- this.messageSeqs.splice(idx, 1);
774
+ // Keep the user message but add a stub assistant response so the
775
+ // conversation remains valid for follow-up messages after ESC.
776
+ const alreadyHasResponse = idx < this.messages.length - 1 && this.messages[idx + 1]?.role === "assistant";
777
+ if (!alreadyHasResponse) {
778
+ this.messages.splice(idx + 1, 0, { role: "assistant", content: "[Interrupted]" });
779
+ this.messageSeqs.splice(idx + 1, 0, null);
780
+ }
1196
781
  }
1197
782
  }
1198
783
 
1199
784
  private recordUsage(
1200
- usage?: { totalTokens?: number; inputTokens?: number; outputTokens?: number; cacheReadTokens?: number; cacheCreationTokens?: number },
785
+ usage?: {
786
+ totalTokens?: number;
787
+ inputTokens?: number;
788
+ outputTokens?: number;
789
+ cacheReadTokens?: number;
790
+ cacheCreationTokens?: number;
791
+ },
1201
792
  source: UsageSource = "message",
1202
793
  model = this.modelId,
1203
794
  ): void {
@@ -1205,11 +796,54 @@ export class Agent {
1205
796
  if (this.session) {
1206
797
  const pilActive = source === "message" ? this._pilActive : false;
1207
798
  const enrichmentDelta = source === "message" ? this._pilEnrichmentDelta : 0;
1208
- recordUsageEvent(this.session.id, source, model, usage, null, pilActive, enrichmentDelta);
799
+ // Attribute usage to the most recent persisted message — this lets
800
+ // per-prompt cost analysis work (was null hardcoded → impossible).
801
+ const lastSeq = lastPersistedSeq(this.messageSeqs);
802
+ // Phase O1 — providerOptions shape (types only, no values) attached
803
+ // to every usage event so post-mortem can answer "what provider
804
+ // options did this billed call carry?". Cleared below for "message"
805
+ // sources so non-message calls don't reuse stale data.
806
+ const providerOptionsShape = this._lastProviderOptionsShape;
807
+ recordUsageEvent(
808
+ this.session.id,
809
+ source,
810
+ model,
811
+ usage,
812
+ lastSeq,
813
+ pilActive,
814
+ enrichmentDelta,
815
+ providerOptionsShape,
816
+ );
1209
817
  if (source === "message") {
1210
818
  this._pilActive = false;
1211
819
  this._pilEnrichmentDelta = 0;
820
+ this._lastProviderOptionsShape = null;
821
+ }
822
+ }
823
+ // Phase D — surfaced for harness E2E verification. Mirror the recorded usage
824
+ // event onto the agent-mode sidechannel so spec processes can assert on
825
+ // cacheReadTokens / cacheCreationTokens normalization without poking at the
826
+ // child's sqlite. Best-effort, only fires when agent-mode runtime is set.
827
+ try {
828
+ const rt = (globalThis as Record<string, unknown>).__muonroiAgentRuntime as
829
+ | { emitEvent?: (e: unknown) => void }
830
+ | undefined;
831
+ if (rt?.emitEvent) {
832
+ const lastSeqForEvent = this.session ? lastPersistedSeq(this.messageSeqs) : null;
833
+ rt.emitEvent({
834
+ t: "event",
835
+ kind: "usage",
836
+ source,
837
+ model,
838
+ inputTokens: usage.inputTokens,
839
+ outputTokens: usage.outputTokens,
840
+ cacheReadTokens: usage.cacheReadTokens,
841
+ cacheCreationTokens: usage.cacheCreationTokens,
842
+ messageSeq: lastSeqForEvent,
843
+ });
1212
844
  }
845
+ } catch {
846
+ // best-effort: do not let sidechannel failures interrupt usage recording
1213
847
  }
1214
848
  // Update status bar token counters + provider/model + cache metrics + cost
1215
849
  const prev = statusBarStore.getState();
@@ -1223,7 +857,8 @@ export class Agent {
1223
857
  const priceOut = info?.outputPrice ?? 0;
1224
858
  // API inputTokens includes cacheRead — subtract to get non-cached portion
1225
859
  const nonCachedInput = Math.max(0, totalInput - cacheRead - cacheCreate);
1226
- const turnCostMicros = nonCachedInput * priceIn + cacheRead * priceCached + cacheCreate * priceIn + output * priceOut;
860
+ const turnCostMicros =
861
+ nonCachedInput * priceIn + cacheRead * priceCached + cacheCreate * priceIn + output * priceOut;
1227
862
  statusBarStore.setState({
1228
863
  in_tokens: prev.in_tokens + totalInput,
1229
864
  out_tokens: prev.out_tokens + output,
@@ -1233,6 +868,28 @@ export class Agent {
1233
868
  provider: this.providerId,
1234
869
  model,
1235
870
  });
871
+
872
+ // Append to cost-log JSONL so `usage report --by callsite` can surface
873
+ // where orchestrator/task/title traffic is actually spending.
874
+ // Best-effort: failures inside appendCostLog are swallowed (see cost-log.ts).
875
+ const breakdown = source === "message" ? (this._lastPromptBreakdown ?? undefined) : undefined;
876
+ appendCostLog({
877
+ ts: Date.now(),
878
+ provider: this.providerId,
879
+ model,
880
+ estimatedUsd: turnCostMicros / 1_000_000,
881
+ callsite: `orchestrator.${source}`,
882
+ phase: source,
883
+ actualInputTokens: totalInput,
884
+ actualOutputTokens: output,
885
+ cachedInputTokens: cacheRead,
886
+ systemChars: breakdown?.systemChars,
887
+ promptChars: breakdown?.messagesChars,
888
+ breakdown,
889
+ }).catch(() => undefined);
890
+ // Don't clear breakdown — onStepFinish fires recordUsage per step within
891
+ // the same streamText call, and they all share the same prompt structure.
892
+ // It is overwritten on the next streamText setup, which is the right scope.
1236
893
  }
1237
894
 
1238
895
  async consumeBackgroundNotifications(): Promise<string[]> {
@@ -1351,12 +1008,14 @@ export class Agent {
1351
1008
  signal,
1352
1009
  } = args;
1353
1010
 
1354
- if (childRuntime.modelInfo?.responsesOnly) {
1011
+ const childCaps = getProviderCapabilities(childRuntime.modelInfo?.provider ?? "anthropic");
1012
+ if (childCaps.usesResponsesAPI(childRuntime.modelInfo)) {
1355
1013
  throw new Error("Batch mode currently supports chat-completions models only.");
1356
1014
  }
1357
1015
 
1358
- const batchTools =
1359
- childRuntime.modelInfo?.supportsClientTools === false ? [] : await toolSetToBatchTools(childTools);
1016
+ const batchTools = !childCaps.supportsClientTools(childRuntime.modelInfo)
1017
+ ? []
1018
+ : await toolSetToBatchTools(childTools);
1360
1019
  const batch = await createBatch({
1361
1020
  ...this.getBatchClientOptions(signal),
1362
1021
  name: buildBatchName(`task-${request.agent}`, request.description),
@@ -1381,10 +1040,9 @@ export class Agent {
1381
1040
  system: childSystem,
1382
1041
  messages: [...childMessages, ...turnMessages],
1383
1042
  temperature: request.agent === "explore" ? 0.2 : 0.5,
1384
- maxOutputTokens:
1385
- childRuntime.modelInfo?.supportsMaxOutputTokens === false
1386
- ? undefined
1387
- : Math.min(this.maxTokens, 8_192),
1043
+ maxOutputTokens: !childCaps.acceptsParam("maxOutputTokens", childRuntime.modelInfo)
1044
+ ? undefined
1045
+ : Math.min(this.maxTokens, 8_192),
1388
1046
  reasoningEffort: childRuntime.providerOptions?.xai.reasoningEffort,
1389
1047
  tools: batchTools,
1390
1048
  }),
@@ -1473,244 +1131,42 @@ export class Agent {
1473
1131
  };
1474
1132
  }
1475
1133
 
1134
+ /**
1135
+ * Run a sub-agent task by spawning a child `streamText` session.
1136
+ *
1137
+ * Phase 12.3 — body extracted to `StreamRunner` (`./stream-runner.ts`).
1138
+ * This method now builds the DI dep set and delegates to
1139
+ * `StreamRunner.run()`. Public signature is unchanged so all callers
1140
+ * (`runTask`, `tools/registry`, batch path, council path) work as before.
1141
+ */
1476
1142
  async runTaskRequest(
1477
1143
  request: TaskRequest,
1478
1144
  onActivity?: (detail: string) => void,
1479
1145
  abortSignal?: AbortSignal,
1480
1146
  ): Promise<ToolResult> {
1481
1147
  const provider = this.requireProvider();
1482
- const signal = abortSignal;
1483
- const agentKey = String(request.agent);
1484
- const isExplore = agentKey === "explore";
1485
- const isGeneral = agentKey === "general";
1486
- const isVision = agentKey === "vision";
1487
- const isVerify = agentKey === "verify";
1488
- const isVerifyDetect = agentKey === "verify-detect";
1489
- const isVerifyManifest = agentKey === "verify-manifest";
1490
- const isComputer = agentKey === "computer";
1491
- const subagents = loadValidSubAgents();
1492
- const custom =
1493
- !isExplore && !isGeneral && !isVision && !isVerify && !isVerifyDetect && !isVerifyManifest && !isComputer
1494
- ? findCustomSubagent(agentKey, subagents)
1495
- : undefined;
1496
-
1497
- if (
1498
- !isExplore &&
1499
- !isGeneral &&
1500
- !isVision &&
1501
- !isVerify &&
1502
- !isVerifyDetect &&
1503
- !isVerifyManifest &&
1504
- !isComputer &&
1505
- !custom
1506
- ) {
1507
- const message = `Unknown sub-agent "${agentKey}". Use general, explore, vision, verify, verify-detect, verify-manifest, computer, or a configured name from ~/.muonroi-cli/user-settings.json.`;
1508
- return {
1509
- success: false,
1510
- output: message,
1511
- task: {
1512
- agent: agentKey,
1513
- description: request.description,
1514
- summary: message,
1515
- },
1516
- };
1517
- }
1518
-
1519
- const childMode: AgentMode = isExplore || isVerifyDetect ? "ask" : "agent";
1520
- const verifySandboxOverrides: SandboxSettings = isVerify
1521
- ? { allowNet: true, allowedHosts: undefined, allowEphemeralInstall: true, hostBrowserCommandsOnHost: true }
1522
- : {};
1523
- let verifyPreparedSettings: SandboxSettings | null = null;
1524
- let verifyPreparedRecipe: VerifyRecipe | null = null;
1525
- if (isVerify) {
1526
- const prepared = await prepareVerifySandbox(
1527
- this.bash.getCwd(),
1528
- { ...this.bash.getSandboxSettings(), ...verifySandboxOverrides },
1529
- undefined,
1530
- onActivity,
1531
- );
1532
- verifyPreparedSettings = prepared.sandboxSettings;
1533
- verifyPreparedRecipe = prepared.profile.recipe;
1534
- }
1535
- const childBash = new BashTool(this.bash.getCwd(), {
1536
- sandboxMode: isVerify ? "shuru" : this.bash.getSandboxMode(),
1537
- sandboxSettings: isVerify
1538
- ? (verifyPreparedSettings ?? { ...this.bash.getSandboxSettings(), ...verifySandboxOverrides })
1539
- : this.bash.getSandboxSettings(),
1540
- });
1541
- const childBaseTools = createTools(childBash, provider, childMode);
1542
- const initialDetail = isExplore
1543
- ? "Scanning the codebase"
1544
- : isVerifyDetect
1545
- ? "Detecting verification recipe"
1546
- : isVerifyManifest
1547
- ? "Creating verification manifest"
1548
- : isVerify
1549
- ? "Preparing verification pass"
1550
- : isComputer
1551
- ? "Preparing computer control pass"
1552
- : "Planning delegated work";
1553
- let assistantText = "";
1554
- let lastActivity = initialDetail;
1555
- let childTools: ToolSet = childBaseTools;
1556
- let closeMcp: (() => Promise<void>) | undefined;
1557
- const childModelId = normalizeModelId(
1558
- isVision
1559
- ? VISION_MODEL
1560
- : isComputer
1561
- ? COMPUTER_MODEL
1562
- : isExplore
1563
- ? DEFAULT_MODEL
1564
- : custom
1565
- ? custom.model
1566
- : this.modelId,
1567
- );
1568
- const childRuntime = isVision
1569
- ? { ...resolveModelRuntime(provider, childModelId), model: provider.responses?.(childModelId) ?? provider(childModelId) }
1570
- : resolveModelRuntime(provider, childModelId);
1571
- if (isComputer && childRuntime.modelInfo?.supportsClientTools === false) {
1572
- return {
1573
- success: false,
1574
- output:
1575
- "Computer sub-agent requires a tool-capable model, but the selected runtime does not support client tools.",
1576
- task: {
1577
- agent: agentKey,
1578
- description: request.description,
1579
- summary: "Computer sub-agent could not start because the chosen model does not support tools.",
1580
- },
1581
- };
1582
- }
1583
- const childSystem = applyModelConstraints(
1584
- buildSubagentPrompt(
1585
- request,
1586
- childBash.getCwd(),
1587
- custom ?? null,
1588
- childBash.getSandboxMode(),
1589
- subagents,
1590
- childBash.getSandboxSettings(),
1591
- childRuntime.modelInfo?.provider ?? this.providerId,
1592
- ),
1593
- childRuntime.modelId,
1594
- );
1595
-
1596
- onActivity?.(initialDetail);
1597
-
1598
- try {
1599
- if (childMode === "agent" && childRuntime.modelInfo?.supportsClientTools !== false) {
1600
- const mcpBundle = await buildMcpToolSet(loadMcpServers(), {
1601
- onOAuthRequired: (_serverId, url) => {
1602
- const urlStr = url.toString();
1603
- import("child_process").then(({ exec }) => {
1604
- const cmd = process.platform === "win32" ? `start "" "${urlStr}"`
1605
- : process.platform === "darwin" ? `open "${urlStr}"`
1606
- : `xdg-open "${urlStr}"`;
1607
- exec(cmd);
1608
- });
1609
- },
1610
- });
1611
- closeMcp = mcpBundle.close;
1612
- childTools = { ...childBaseTools, ...mcpBundle.tools };
1613
- captureToolSchemas(childTools);
1614
- if (mcpBundle.errors.length > 0) {
1615
- lastActivity = `MCP unavailable: ${mcpBundle.errors.join(" | ")}`;
1616
- onActivity?.(lastActivity);
1617
- }
1618
- }
1619
-
1620
- const childPrompt =
1621
- isVerify && verifyPreparedRecipe
1622
- ? `${request.prompt}\n\nPrepared verify recipe JSON (use this as the primary execution recipe and keep .muonroi-cli/environment.json aligned with it if present):\n${JSON.stringify(verifyPreparedRecipe, null, 2)}`
1623
- : request.prompt;
1624
-
1625
- const childMessages = isVision
1626
- ? await buildVisionUserMessages(request.prompt, childBash.getCwd(), signal)
1627
- : [{ role: "user" as const, content: childPrompt }];
1628
-
1629
- if (this.batchApi) {
1630
- return await this.runTaskRequestBatch({
1631
- request,
1632
- childMessages,
1633
- childSystem,
1634
- childRuntime,
1635
- childTools,
1636
- maxSteps: Math.min(this.maxToolRounds, isExplore ? 60 : 120),
1637
- initialDetail,
1638
- onActivity,
1639
- signal,
1640
- });
1641
- }
1642
-
1643
- const result = streamText({
1644
- model: childRuntime.model,
1645
- system: childSystem,
1646
- messages: childMessages,
1647
- tools: childRuntime.modelInfo?.supportsClientTools === false ? {} : childTools,
1648
- stopWhen: stepCountIs(Math.min(this.maxToolRounds, isExplore ? 60 : 120)),
1649
- maxRetries: 0,
1650
- abortSignal: signal,
1651
- temperature: isExplore ? 0.2 : 0.5,
1652
- ...(childRuntime.modelInfo?.supportsMaxOutputTokens === false
1653
- ? {}
1654
- : { maxOutputTokens: Math.min(this.maxTokens, 8_192) }),
1655
- ...(childRuntime.providerOptions ? { providerOptions: childRuntime.providerOptions } : {}),
1656
- onFinish: ({ totalUsage, providerMetadata }) => {
1657
- const anthropicMeta = providerMetadata?.anthropic as Record<string, unknown> | undefined;
1658
- const cacheReadTokens = asNumber(anthropicMeta?.cacheReadInputTokens) ?? 0;
1659
- const cacheCreationTokens = asNumber(anthropicMeta?.cacheCreationInputTokens) ?? 0;
1660
- this.recordUsage({ ...totalUsage, cacheReadTokens, cacheCreationTokens }, "task", childRuntime.modelId);
1661
- },
1662
- });
1663
-
1664
- for await (const part of result.fullStream) {
1665
- if (signal?.aborted) {
1666
- break;
1667
- }
1668
-
1669
- if (part.type === "text-delta") {
1670
- assistantText += part.text;
1671
- continue;
1672
- }
1673
-
1674
- if (part.type === "tool-call") {
1675
- lastActivity = formatSubagentActivity(part.toolName, part.input);
1676
- onActivity?.(lastActivity);
1677
- }
1678
- }
1679
-
1680
- if (signal?.aborted) {
1681
- return { success: false, output: "[Cancelled]" };
1682
- }
1683
-
1684
- await result.response;
1685
-
1686
- const output = assistantText.trim() || `Task completed. Last action: ${lastActivity}`;
1687
- return {
1688
- success: true,
1689
- output,
1690
- task: {
1691
- agent: request.agent,
1692
- description: request.description,
1693
- summary: firstLine(output),
1694
- activity: lastActivity,
1695
- },
1696
- };
1697
- } catch (err: unknown) {
1698
- if (signal?.aborted) throw err;
1699
- const msg = err instanceof Error ? err.message : String(err);
1700
- const output = `Task failed: ${msg}`;
1701
- return {
1702
- success: false,
1703
- output,
1704
- task: {
1705
- agent: request.agent,
1706
- description: request.description,
1707
- summary: output,
1708
- activity: lastActivity,
1709
- },
1710
- };
1711
- } finally {
1712
- await closeMcp?.().catch(() => {});
1713
- }
1148
+ const deps: StreamRunnerDeps = {
1149
+ getProvider: () => provider,
1150
+ resolveModelForTask: (task) => this._resolveModelForTask(task),
1151
+ getModelId: () => this.modelId,
1152
+ getProviderId: () => this.providerId,
1153
+ getBash: () => this.bash,
1154
+ getMaxToolRounds: () => this.maxToolRounds,
1155
+ getMaxTokens: () => this.maxTokens,
1156
+ isBatchApiEnabled: () => this.batchApi,
1157
+ getCrossTurnDedup: () => this._crossTurnDedup,
1158
+ getReadBudget: () => this._readBudget,
1159
+ recordUsage: (usage, source, model) => this.recordUsage(usage, source, model),
1160
+ setCurrentCallId: (id) => {
1161
+ this._currentCallId = id;
1162
+ },
1163
+ setLastProviderOptionsShape: (shape) => {
1164
+ this._lastProviderOptionsShape = shape;
1165
+ },
1166
+ runTaskRequestBatch: (args) => this.runTaskRequestBatch(args),
1167
+ };
1168
+ const runner = new StreamRunner(deps);
1169
+ return runner.run(request, onActivity, abortSignal);
1714
1170
  }
1715
1171
 
1716
1172
  private async runTask(request: TaskRequest, abortSignal?: AbortSignal): Promise<ToolResult> {
@@ -1725,17 +1181,53 @@ export class Agent {
1725
1181
 
1726
1182
  let result: ToolResult;
1727
1183
  try {
1728
- result = await this.runTaskRequest(
1729
- request,
1730
- (detail) => {
1731
- if (abortSignal?.aborted) return;
1732
- this.emitSubagentStatus({
1733
- agent: request.agent,
1734
- description: request.description,
1735
- detail,
1736
- });
1184
+ result = await withStreamRetry(
1185
+ () =>
1186
+ this.runTaskRequest(
1187
+ request,
1188
+ (detail) => {
1189
+ if (abortSignal?.aborted) return;
1190
+ this.emitSubagentStatus({
1191
+ agent: request.agent,
1192
+ description: request.description,
1193
+ detail,
1194
+ });
1195
+ },
1196
+ abortSignal,
1197
+ ),
1198
+ {
1199
+ signal: abortSignal,
1200
+ onRetry: (info) => {
1201
+ // Emit harness telemetry
1202
+ try {
1203
+ const _ar = (globalThis as Record<string, unknown>).__muonroiAgentRuntime as
1204
+ | { emitEvent: (e: unknown) => void }
1205
+ | undefined;
1206
+ _ar?.emitEvent({
1207
+ t: "event",
1208
+ kind: "stream-retry",
1209
+ ...info,
1210
+ });
1211
+ } catch {
1212
+ /* best-effort */
1213
+ }
1214
+ try {
1215
+ if (this.session) {
1216
+ logInteraction(this.session.id, "stream_retry", {
1217
+ data: {
1218
+ attempt: info.attempt,
1219
+ maxAttempts: info.maxAttempts,
1220
+ errorName: info.errorName,
1221
+ errorMessage: info.errorMessage.slice(0, 200),
1222
+ nextDelayMs: info.nextDelayMs,
1223
+ },
1224
+ });
1225
+ }
1226
+ } catch {
1227
+ /* fail-open */
1228
+ }
1229
+ },
1737
1230
  },
1738
- abortSignal,
1739
1231
  );
1740
1232
  } finally {
1741
1233
  this.emitSubagentStatus(null);
@@ -1843,11 +1335,41 @@ export class Agent {
1843
1335
  }
1844
1336
  }
1845
1337
 
1846
- private getCompactionSettings(): CompactionSettings {
1338
+ private getCompactionSettings(contextWindow?: number): CompactionSettings {
1339
+ let keepRecentTokens = DEFAULT_KEEP_RECENT_TOKENS;
1340
+
1341
+ // For models with very large context windows, keep more recent tokens
1342
+ if (contextWindow && contextWindow > 200_000) {
1343
+ keepRecentTokens = Math.min(100_000, Math.max(20_000, Math.floor(contextWindow * 0.1)));
1344
+ }
1345
+
1346
+ // Compact more aggressively for long sessions to prevent runaway token growth
1347
+ if (this._compactionStats.count >= 2) {
1348
+ keepRecentTokens = Math.floor(keepRecentTokens * 0.75);
1349
+ }
1350
+
1847
1351
  return {
1848
1352
  reserveTokens: Math.max(this.maxTokens, DEFAULT_RESERVE_TOKENS),
1849
- keepRecentTokens: DEFAULT_KEEP_RECENT_TOKENS,
1353
+ keepRecentTokens,
1354
+ };
1355
+ }
1356
+
1357
+ private _resolveCompactModel(): string {
1358
+ return this._resolveModelForTask("compact");
1359
+ }
1360
+
1361
+ private _resolveModelForTask(task: "compact" | "explore" | "general" | "title"): string {
1362
+ const tierPrefs: Record<string, Array<"fast" | "balanced" | "premium">> = {
1363
+ compact: ["fast", "balanced"],
1364
+ title: ["fast", "balanced"],
1365
+ explore: ["balanced", "fast"],
1366
+ general: ["premium", "balanced"],
1850
1367
  };
1368
+ for (const tier of tierPrefs[task] ?? ["balanced"]) {
1369
+ const m = getModelByTier(tier, this.providerId);
1370
+ if (m?.provider === this.providerId) return m.id;
1371
+ }
1372
+ return this.modelId;
1851
1373
  }
1852
1374
 
1853
1375
  private async compactForContext(
@@ -1855,7 +1377,7 @@ export class Agent {
1855
1377
  system: string,
1856
1378
  contextWindow: number,
1857
1379
  signal: AbortSignal,
1858
- settings = this.getCompactionSettings(),
1380
+ settings = this.getCompactionSettings(contextWindow),
1859
1381
  force = false,
1860
1382
  ): Promise<boolean> {
1861
1383
  if (!this.session) return false;
@@ -1889,22 +1411,83 @@ export class Agent {
1889
1411
 
1890
1412
  const keptSeqs = this.messageSeqs.slice(preparation.firstKeptIndex);
1891
1413
  const firstKeptSeq = keptSeqs.find((seq): seq is number => seq !== null) ?? getNextMessageSequence(this.session.id);
1892
- const summary = await generateCompactionSummary(provider, this.modelId, preparation, undefined, signal);
1414
+ const compactModelId = this._resolveCompactModel();
1415
+ const compactStartedAt = Date.now();
1416
+ const { summary, usage: compactUsage } = await generateCompactionSummary(
1417
+ provider,
1418
+ compactModelId,
1419
+ preparation,
1420
+ undefined,
1421
+ signal,
1422
+ );
1423
+
1424
+ // Record compaction call in cost-log — bypasses recordUsage because
1425
+ // compaction returns usage separately and isn't routed through the
1426
+ // status-bar / usage event pipeline (intentional: it's overhead, not user spend).
1427
+ const compactProvider = detectProviderForModel(compactModelId);
1428
+ appendCostLog({
1429
+ ts: compactStartedAt,
1430
+ provider: compactProvider,
1431
+ model: compactModelId,
1432
+ estimatedUsd: projectCostUSD(
1433
+ compactProvider,
1434
+ compactModelId,
1435
+ compactUsage.promptTokens,
1436
+ compactUsage.completionTokens,
1437
+ ),
1438
+ callsite: "orchestrator.compaction",
1439
+ phase: "compaction",
1440
+ iteration: this._compactionStats.count + 1,
1441
+ actualInputTokens: compactUsage.promptTokens,
1442
+ actualOutputTokens: compactUsage.completionTokens,
1443
+ durationMs: Date.now() - compactStartedAt,
1444
+ }).catch(() => undefined);
1893
1445
 
1894
1446
  appendCompaction(this.session.id, firstKeptSeq, summary, preparation.tokensBefore);
1895
- this.messages = [createCompactionSummaryMessage(summary), ...preparation.keptMessages];
1896
- this.messageSeqs = [null, ...keptSeqs];
1897
1447
 
1898
- // Track compaction stats
1448
+ // Re-inject pinned user messages that were about to be summarized away.
1449
+ // Pinned seqs that are still inside keptMessages don't need re-injection.
1450
+ const keptSeqSet = new Set(keptSeqs.filter((s): s is number => s !== null));
1451
+ const pinnedReinjections: ModelMessage[] = [];
1452
+ const pinnedReinjectionSeqs: Array<number | null> = [];
1453
+ for (const seq of [...this._pinnedSeqs].sort((a, b) => a - b)) {
1454
+ if (keptSeqSet.has(seq)) continue;
1455
+ const idx = this.messageSeqs.indexOf(seq);
1456
+ if (idx < 0) {
1457
+ // Pinned seq no longer present (shouldn't happen, but stay defensive).
1458
+ this._pinnedSeqs.delete(seq);
1459
+ continue;
1460
+ }
1461
+ const original = this.messages[idx];
1462
+ if (!original || original.role !== "user") continue;
1463
+ const text = extractUserContent(original.content).trim();
1464
+ if (!text) continue;
1465
+ pinnedReinjections.push({
1466
+ role: "system",
1467
+ content: `[Pinned user message — kept verbatim across compaction]\n${text}`,
1468
+ });
1469
+ pinnedReinjectionSeqs.push(null);
1470
+ }
1471
+
1472
+ this.messages = [createCompactionSummaryMessage(summary), ...pinnedReinjections, ...preparation.keptMessages];
1473
+ this.messageSeqs = [null, ...pinnedReinjectionSeqs, ...keptSeqs];
1474
+
1475
+ // Track compaction stats — net of the tokens spent ON compaction itself.
1899
1476
  const tokensAfter = estimateConversationTokens(system, this.messages);
1900
- const saved = Math.max(0, preparation.tokensBefore - tokensAfter);
1477
+ const grossSaved = Math.max(0, preparation.tokensBefore - tokensAfter);
1478
+ const compactCost = compactUsage.promptTokens + compactUsage.completionTokens;
1479
+ const saved = Math.max(0, grossSaved - compactCost);
1901
1480
  const pct = preparation.tokensBefore > 0 ? ((saved / preparation.tokensBefore) * 100).toFixed(1) : "0.0";
1902
1481
  this._compactionStats.count++;
1903
1482
  this._compactionStats.totalSaved += saved;
1904
1483
 
1905
1484
  // Update status bar with current context size and compaction summary
1906
- const fmtCompact = (n: number) => n >= 1000 ? `${(n / 1000).toFixed(1)}K` : String(n);
1907
- const compactLabel = `${this._compactionStats.count} cmp, ${fmtCompact(this._compactionStats.totalSaved)} saved`;
1485
+ const fmtCompact = (n: number) => (n >= 1000 ? `${(n / 1000).toFixed(1)}K` : String(n));
1486
+ const modelSuffix = compactModelId !== this.modelId ? ` via ${compactModelId}` : "";
1487
+ const userMsgCount = this.messages.filter((m) => m.role === "user").length;
1488
+ const isLongSession = this._compactionStats.count >= 3 || userMsgCount >= 200;
1489
+ const sessionHint = isLongSession ? " ⚠ long session — consider /clear" : "";
1490
+ const compactLabel = `${this._compactionStats.count} cmp, ${fmtCompact(this._compactionStats.totalSaved)} saved${modelSuffix}${sessionHint}`;
1908
1491
  statusBarStore.setState({ ctx_tokens: tokensAfter, compaction_summary: compactLabel });
1909
1492
 
1910
1493
  const postCompactInput: PostCompactHookInput = {
@@ -1915,6 +1498,26 @@ export class Agent {
1915
1498
  };
1916
1499
  await this.fireHook(postCompactInput, signal).catch(() => {});
1917
1500
 
1501
+ // Interaction log: compaction
1502
+ try {
1503
+ if (this.session) {
1504
+ logInteraction(this.session.id, "compaction", {
1505
+ data: {
1506
+ count: this._compactionStats.count,
1507
+ tokensBefore: preparation.tokensBefore,
1508
+ tokensAfter,
1509
+ saved,
1510
+ grossSaved,
1511
+ compactCost,
1512
+ pct,
1513
+ isLongSession,
1514
+ },
1515
+ });
1516
+ }
1517
+ } catch {
1518
+ /* fail-open */
1519
+ }
1520
+
1918
1521
  this._compactedThisTurn = true;
1919
1522
  return true;
1920
1523
  }
@@ -1925,137 +1528,330 @@ export class Agent {
1925
1528
  contextWindow: number,
1926
1529
  signal: AbortSignal,
1927
1530
  ): Promise<void> {
1928
- if (this._compactedThisTurn) return;
1929
- if (!isAutoCompactAfterTurnEnabled()) return;
1531
+ const log = (taken: boolean, reason: string, extra?: Record<string, unknown>): void => {
1532
+ appendDecisionLog({
1533
+ ts: Date.now(),
1534
+ sessionId: this.session?.id ?? null,
1535
+ kind: "post-turn-compact",
1536
+ taken,
1537
+ reason,
1538
+ meta: { contextWindow, ...extra },
1539
+ }).catch(() => undefined);
1540
+ };
1541
+
1542
+ if (this._compactedThisTurn) return log(false, "already-compacted-this-turn");
1543
+ if (!isAutoCompactAfterTurnEnabled()) return log(false, "feature-disabled");
1930
1544
  const tokens = estimateConversationTokens(system, this.messages);
1931
1545
  const thresholdPct = getAutoCompactThresholdPct();
1932
1546
  const minMeaningfulTokens = Math.max(POST_TURN_MIN_TOKENS, Math.floor(contextWindow * thresholdPct));
1933
- if (tokens < minMeaningfulTokens) return;
1934
- await this.compactForContext(provider, system, contextWindow, signal, this.getCompactionSettings(), true).catch(
1935
- (err) => console.warn("[compact] failed:", (err as Error)?.message),
1936
- );
1547
+ if (tokens < minMeaningfulTokens) {
1548
+ return log(false, `under-threshold (${tokens} < ${minMeaningfulTokens})`, {
1549
+ tokens,
1550
+ thresholdPct,
1551
+ minMeaningfulTokens,
1552
+ });
1553
+ }
1554
+ log(true, `over-threshold (${tokens} >= ${minMeaningfulTokens})`, { tokens, thresholdPct, minMeaningfulTokens });
1555
+ await this.compactForContext(
1556
+ provider,
1557
+ system,
1558
+ contextWindow,
1559
+ signal,
1560
+ this.getCompactionSettings(contextWindow),
1561
+ true,
1562
+ ).catch((err) => console.warn("[compact] failed:", (err as Error)?.message));
1937
1563
  }
1938
1564
 
1939
- private _councilStats = { calls: 0, startMs: 0 };
1565
+ // ========================================================================
1566
+ // Council system — delegated to CouncilManager (Phase 12.1-02)
1567
+ //
1568
+ // All council state + sub-call helpers (generate/research/prompt builders/
1569
+ // outcome parser/executor/candidate resolution) live in CouncilManager.
1570
+ // The thin facade below preserves the public API the UI + tests rely on
1571
+ // (respondToCouncilQuestion/Preflight + the internal _create*Responder
1572
+ // hooks used by orchestrator.agent.test.ts).
1573
+ // ========================================================================
1940
1574
 
1941
- private async _councilGenerate(
1942
- modelId: string,
1943
- system: string,
1944
- prompt: string,
1945
- maxTokens = 2048,
1946
- ): Promise<string> {
1947
- const providerId = detectProviderForModel(modelId);
1948
- const key = await loadKeyForProvider(providerId);
1949
- const provider = createProvider(providerId, key);
1950
- const runtime = resolveModelRuntime(provider, modelId);
1951
- const { text } = await generateText({
1952
- model: runtime.model,
1953
- system,
1954
- prompt,
1955
- maxOutputTokens: maxTokens,
1956
- temperature: 0.7,
1957
- ...(runtime.providerOptions ? { providerOptions: runtime.providerOptions } : {}),
1958
- });
1959
- this._councilStats.calls++;
1960
- return text;
1961
- }
1962
-
1963
- private _buildDiscussPrompt(
1964
- phase: "open" | "respond" | "followup" | "convergence-check",
1965
- ctx: {
1966
- speakerRole: string;
1967
- partnerRole: string;
1968
- topic: string;
1969
- speakerPosition?: string;
1970
- partnerPosition?: string;
1971
- exchangeHistory?: string;
1972
- round?: number;
1575
+ respondToCouncilQuestion(questionId: string, answer: string): void {
1576
+ this.councilManager.respondToQuestion(questionId, answer);
1577
+ }
1578
+
1579
+ respondToCouncilPreflight(preflightId: string, approved: boolean): void {
1580
+ this.councilManager.respondToPreflight(preflightId, approved);
1581
+ }
1582
+
1583
+ // Internal hooks used by orchestrator.agent.test.ts to exercise buffered
1584
+ // question / preflight delivery through CouncilManager. They are reached
1585
+ // through `as unknown as` casts in the test; keep them private but stable.
1586
+ private _createQuestionResponder(): (questionId: string) => Promise<string> {
1587
+ return this.councilManager.createQuestionResponder();
1588
+ }
1589
+
1590
+ private _createPreflightResponder(): (preflightId: string) => Promise<boolean> {
1591
+ return this.councilManager.createPreflightResponder();
1592
+ }
1593
+
1594
+ // ========================================================================
1595
+ // Council v2 — Clarify → Confirm → Debate → Plan → Execute
1596
+ // ========================================================================
1597
+
1598
+ async *runCouncilV2(
1599
+ topic: string,
1600
+ options?: {
1601
+ skipClarification?: boolean;
1602
+ observer?: ProcessMessageObserver;
1603
+ userModelMessage?: ModelMessage;
1973
1604
  },
1974
- ): { system: string; prompt: string } {
1975
- switch (phase) {
1976
- case "open":
1977
- return {
1978
- system:
1979
- `You are a ${ctx.speakerRole} specialist. You are entering a discussion with a ${ctx.partnerRole} specialist about a technical topic.\n\n` +
1980
- `Share your analysis naturally explain your reasoning, the trade-offs you see, and what concerns you.\n` +
1981
- `End by asking the ${ctx.partnerRole} for their perspective on your analysis. What do they see differently?`,
1982
- prompt: `Topic for discussion:\n${ctx.topic}`,
1983
- };
1605
+ ): AsyncGenerator<StreamChunk, void, unknown> {
1606
+ const { runCouncil } = await import("../council/index.js");
1607
+ const { createCouncilLLM } = await import("../council/llm.js");
1608
+ const councilStats = { calls: 0, startMs: Date.now(), phases: [] as Array<{ name: string; durationMs: number }> };
1609
+ const llm = createCouncilLLM(this.bash, this.mode, this.session?.id, councilStats);
1610
+
1611
+ const processMessageFn = (message: string) => this.processMessage(message, options?.observer);
1612
+
1613
+ const gen = runCouncil(
1614
+ topic,
1615
+ this.modelId,
1616
+ this.messages as Array<{ role: string; content: string | unknown }>,
1617
+ this.session?.id,
1618
+ llm,
1619
+ this.councilManager.createQuestionResponder(),
1620
+ this.councilManager.createPreflightResponder(),
1621
+ processMessageFn,
1622
+ {
1623
+ skipClarification: options?.skipClarification,
1624
+ userModelMessage: options?.userModelMessage,
1625
+ cwd: this.bash.getCwd(),
1626
+ councilStats, // NEW — share orchestrator's stats object with runCouncil (Phase 14 CQ-01)
1627
+ },
1628
+ );
1984
1629
 
1985
- case "respond":
1986
- return {
1987
- system:
1988
- `You are a ${ctx.speakerRole} specialist in a discussion with a ${ctx.partnerRole} specialist.\n\n` +
1989
- `A colleague shared their analysis below. Give your honest take:\n` +
1990
- `- Where you agree, say so briefly and build on it\n` +
1991
- `- Where you disagree, explain why with your own reasoning — not to attack, but to offer a different lens\n` +
1992
- `- Share what you think they might be missing from your ${ctx.speakerRole} perspective\n\n` +
1993
- `End with a question back to them: based on your analysis, what's their view? Do they agree, or do they see it differently?`,
1994
- prompt:
1995
- `Their analysis (${ctx.partnerRole}):\n${ctx.partnerPosition}\n\n` +
1996
- `Your own analysis for context:\n${ctx.speakerPosition}`,
1997
- };
1630
+ let result: IteratorResult<StreamChunk, string | null>;
1631
+ do {
1632
+ result = await gen.next();
1633
+ if (!result.done && result.value) {
1634
+ yield result.value;
1635
+ }
1636
+ } while (!result.done);
1998
1637
 
1999
- case "followup":
2000
- return {
2001
- system:
2002
- `You are a ${ctx.speakerRole} specialist continuing a discussion (round ${ctx.round}) with a ${ctx.partnerRole} specialist.\n\n` +
2003
- `Read their latest response and the exchange so far. Then:\n` +
2004
- `- If they raised valid points, acknowledge them and update your thinking\n` +
2005
- `- If you still disagree on something, explain why — bring new evidence or a different angle, not the same argument again\n` +
2006
- `- If you've changed your mind on something, say so explicitly\n\n` +
2007
- `End with: do you agree with where we've landed? Or is there something we're still seeing differently?`,
2008
- prompt:
2009
- `Discussion so far:\n${ctx.exchangeHistory}\n\n` +
2010
- `Their latest response (${ctx.partnerRole}):\n${ctx.partnerPosition}`,
2011
- };
1638
+ const synthesis = result.value;
1639
+ this.councilManager.setLastSynthesis(synthesis);
2012
1640
 
2013
- case "convergence-check":
2014
- return {
2015
- system:
2016
- `Analyze this discussion between a ${ctx.speakerRole} and a ${ctx.partnerRole}. ` +
2017
- `Respond with ONLY a JSON object, no other text:\n` +
2018
- `{"converged": true/false, "reason": "one sentence explaining why"}`,
2019
- prompt: `Discussion:\n${ctx.exchangeHistory}`,
2020
- };
1641
+ if (options?.userModelMessage && synthesis) {
1642
+ this.appendCompletedTurn(options.userModelMessage, [{ role: "assistant", content: synthesis }]);
1643
+ }
1644
+ }
1645
+
1646
+ // ========================================================================
1647
+ // Product Ideal Loop (Phase 13) — mirror of runCouncilV2 wiring.
1648
+ // ========================================================================
1649
+
1650
+ async *runProductLoopV1(
1651
+ payload: {
1652
+ subcommand: "start" | "status" | "resume" | "abort" | "ship";
1653
+ idea?: string;
1654
+ runId?: string;
1655
+ flags: {
1656
+ maxCost: number;
1657
+ maxSprints: number;
1658
+ doneThreshold: number;
1659
+ stack?: string;
1660
+ noCustomerDebate?: boolean;
1661
+ noPriorContext?: boolean;
1662
+ forceCouncil?: boolean;
1663
+ };
1664
+ },
1665
+ options?: {
1666
+ observer?: ProcessMessageObserver;
1667
+ userModelMessage?: ModelMessage;
1668
+ },
1669
+ ): AsyncGenerator<StreamChunk, void, unknown> {
1670
+ const { runProductLoop } = await import("../product-loop/index.js");
1671
+ const { createCouncilLLM } = await import("../council/llm.js");
1672
+ const nodePath = await import("node:path");
1673
+
1674
+ const productStats = {
1675
+ calls: 0,
1676
+ startMs: Date.now(),
1677
+ phases: [] as Array<{ name: string; durationMs: number }>,
1678
+ };
1679
+ const llm = createCouncilLLM(this.bash, this.mode, this.session?.id, productStats);
1680
+ const processMessageFn = (m: string) => this.processMessage(m, options?.observer);
1681
+ const flowDir = nodePath.join(this.bash.getCwd(), ".muonroi-flow");
1682
+
1683
+ // P2.7: compute complexity from the idea using PIL Layer 1 heuristics (cheap,
1684
+ // no LLM calls). Only meaningful for "start"; other subcommands ignore it.
1685
+ let complexity: "low" | "medium" | "high" | undefined;
1686
+ let sufficiencyMissing: readonly import("../pil/layer1-intent.js").SufficiencyMissing[] | undefined;
1687
+ if (payload.subcommand === "start" && payload.idea) {
1688
+ const { scoreComplexity, scoreSufficiency } = await import("../pil/layer1-intent.js");
1689
+ const result = scoreComplexity({
1690
+ rawText: payload.idea,
1691
+ taskType: null,
1692
+ t0HitCount: 0,
1693
+ hasMaxSprintsOne: payload.flags.maxSprints === 1,
1694
+ });
1695
+ complexity = result.complexity;
1696
+ // Sufficiency gate — vague briefs ("todo app") force Council so the
1697
+ // discovery AskCard can fill in persona/MVP/architecture/verify before
1698
+ // any code is scaffolded.
1699
+ const suff = scoreSufficiency({ rawText: payload.idea });
1700
+ sufficiencyMissing = suff.sufficient ? undefined : suff.missing;
1701
+ }
1702
+
1703
+ const gen = runProductLoop({
1704
+ subcommand: payload.subcommand,
1705
+ idea: payload.idea ?? "",
1706
+ runId: payload.runId,
1707
+ flowDir,
1708
+ sessionModelId: this.modelId,
1709
+ llm,
1710
+ flags: {
1711
+ maxCost: payload.flags.maxCost,
1712
+ maxSprints: payload.flags.maxSprints,
1713
+ doneThreshold: payload.flags.doneThreshold,
1714
+ stack: payload.flags.stack,
1715
+ forceCouncil: payload.flags.forceCouncil,
1716
+ },
1717
+ respondToQuestion: this.councilManager.createQuestionResponder(),
1718
+ respondToPreflight: this.councilManager.createPreflightResponder(),
1719
+ cwd: this.bash.getCwd(),
1720
+ processMessageFn,
1721
+ skipPriorContext: payload.flags.noPriorContext === true,
1722
+ complexity,
1723
+ sufficiencyMissing,
1724
+ // Chat session id — used as the FK key for interaction_logs telemetry.
1725
+ // The /ideal runId is NOT a sessions.id and would silently fail FK insert.
1726
+ sessionId: this.session?.id,
1727
+ } as Parameters<typeof runProductLoop>[0]);
1728
+
1729
+ for await (const chunk of gen) {
1730
+ yield chunk;
2021
1731
  }
2022
1732
  }
2023
1733
 
1734
+ // ========================================================================
1735
+ // Legacy council — kept for backward compatibility, will be removed
1736
+ // ========================================================================
1737
+
2024
1738
  async *runCouncilRound(
2025
1739
  topic: string,
2026
- observer?: ProcessMessageObserver,
1740
+ _observer?: ProcessMessageObserver,
2027
1741
  rounds?: number,
1742
+ userModelMessage?: ModelMessage,
2028
1743
  ): AsyncGenerator<StreamChunk, void, unknown> {
2029
1744
  const maxRounds = rounds ?? getCouncilRounds();
2030
1745
  const ALL_ROLES: ModelRole[] = ["implement", "verify", "research"];
2031
- this._councilStats = { calls: 0, startMs: Date.now() };
1746
+ this.councilManager.resetStats(Date.now());
2032
1747
 
2033
- // Resolve available role models upfront
1748
+ // Resolve council participants: same-provider by default, multi-provider only when configured
2034
1749
  const candidates: Array<{ role: ModelRole; model: string }> = [];
2035
- for (const role of ALL_ROLES) {
2036
- const modelId = getRoleModel(role);
2037
- if (!modelId) continue;
2038
- const canReach = await loadKeyForProvider(detectProviderForModel(modelId)).then(() => true).catch(() => false);
2039
- if (canReach) candidates.push({ role, model: modelId });
1750
+ const configuredRoleModels = getRoleModels();
1751
+ const hasExplicitMultiProvider = this.councilManager.hasMultiProviderConfig(configuredRoleModels);
1752
+
1753
+ if (hasExplicitMultiProvider && isCouncilMultiProviderPreferred()) {
1754
+ // Multi-provider path: use explicitly configured role models across providers
1755
+ for (const role of ALL_ROLES) {
1756
+ const modelId = getRoleModel(role);
1757
+ if (!modelId) continue;
1758
+ const provider = detectProviderForModel(modelId);
1759
+ if (isProviderDisabled(provider as ProviderId)) continue;
1760
+ const canReach = await loadKeyForProvider(provider)
1761
+ .then(() => true)
1762
+ .catch(() => false);
1763
+ if (canReach) candidates.push({ role, model: modelId });
1764
+ }
1765
+ if (candidates.length >= 2) {
1766
+ const providers = new Set(candidates.map((c) => detectProviderForModel(c.model)));
1767
+ yield {
1768
+ type: "content",
1769
+ content: `\n[Multi-provider mode: ${candidates.length} roles across ${providers.size} provider(s)]\n`,
1770
+ };
1771
+ }
1772
+ }
1773
+
1774
+ // Default: same-provider mode — pick diverse models from the session's provider
1775
+ if (candidates.length < 2) {
1776
+ const mainProviderId = detectProviderForModel(this.modelId);
1777
+ // Skip same-provider resolution if the session's provider is disabled
1778
+ if (!isProviderDisabled(mainProviderId as ProviderId)) {
1779
+ const sameCandidates = await this.councilManager.resolveSameProviderCandidates(mainProviderId, ALL_ROLES);
1780
+ if (sameCandidates.length >= 2) {
1781
+ candidates.length = 0;
1782
+ candidates.push(...sameCandidates);
1783
+ const uniqueModels = new Set(sameCandidates.map((c) => c.model));
1784
+ yield {
1785
+ type: "content",
1786
+ content: `\n[Same-provider mode: ${uniqueModels.size} ${mainProviderId} model(s) for ${sameCandidates.length} roles]\n`,
1787
+ };
1788
+ }
1789
+ }
1790
+ }
1791
+
1792
+ // Final fallback: use main model for all roles
1793
+ if (candidates.length < 2) {
1794
+ const mainProviderId = detectProviderForModel(this.modelId);
1795
+ const mainDisabled = isProviderDisabled(mainProviderId as ProviderId);
1796
+ const mainCanReach =
1797
+ !mainDisabled &&
1798
+ (await loadKeyForProvider(mainProviderId)
1799
+ .then(() => true)
1800
+ .catch(() => false));
1801
+ if (mainCanReach) {
1802
+ candidates.length = 0;
1803
+ for (const role of ALL_ROLES) {
1804
+ candidates.push({ role, model: this.modelId });
1805
+ }
1806
+ yield {
1807
+ type: "content",
1808
+ content: `\n[Fallback: using \x1b[36m${this.modelId}\x1b[0m for all roles]\n`,
1809
+ };
1810
+ }
2040
1811
  }
2041
1812
 
2042
1813
  if (candidates.length < 2) {
2043
- yield { type: "content", content: "\nNeed at least 2 reachable role models. Configure `roleModels` + provider keys in user-settings.json.\n" };
1814
+ yield {
1815
+ type: "content",
1816
+ content: "\nNo reachable provider. Check API keys in user-settings.json or environment.\n",
1817
+ };
2044
1818
  yield { type: "done" };
2045
1819
  return;
2046
1820
  }
2047
1821
 
1822
+ // Build conversation context for all participants
1823
+ const conversationContext = this.councilManager.buildContext();
1824
+
1825
+ // ── Phase 0: Research — gather facts from codebase before discussion ──
1826
+ const p0Start = Date.now();
1827
+ yield { type: "content", content: `\n## Phase 0 — Codebase Research\n` };
1828
+
1829
+ // Find the research candidate (prefer configured research role, fallback to first available)
1830
+ const researchCandidate = candidates.find((c) => c.role === "research") ?? candidates[0];
1831
+ yield { type: "content", content: `\n### \x1b[35m[research]\x1b[0m ${researchCandidate.model}\n` };
1832
+
1833
+ const researchFindings = await this.councilManager.research(researchCandidate.model, topic, conversationContext);
1834
+ yield { type: "content", content: `${researchFindings}\n` };
1835
+ yield { type: "content", content: `\n> Phase 0: ${((Date.now() - p0Start) / 1000).toFixed(1)}s\n` };
1836
+
1837
+ // Inject research findings into conversation context for subsequent phases
1838
+ const enrichedContext = conversationContext
1839
+ ? `${conversationContext}\n\n---\n\n## Research Findings (Phase 0)\n${researchFindings}`
1840
+ : `## Research Findings (Phase 0)\n${researchFindings}`;
1841
+
2048
1842
  // ── Phase 1: Parallel opening statements ──
2049
1843
  const p1Start = Date.now();
2050
1844
  yield { type: "content", content: "\n## Phase 1 — Opening Analysis\n" };
2051
1845
 
2052
1846
  const openingPromises = candidates.map(({ role, model }) => {
2053
- const { system, prompt } = this._buildDiscussPrompt("open", {
1847
+ const { system, prompt } = this.councilManager.buildDiscussPrompt("open", {
2054
1848
  speakerRole: role,
2055
1849
  partnerRole: candidates.find((c) => c.role !== role)?.role ?? "colleague",
2056
1850
  topic,
1851
+ conversationContext: enrichedContext,
2057
1852
  });
2058
- return this._councilGenerate(model, system, prompt)
1853
+ return this.councilManager
1854
+ .generate(model, system, prompt)
2059
1855
  .then((text) => ({ role, model, position: text, error: null as string | null }))
2060
1856
  .catch((err: unknown) => ({
2061
1857
  role,
@@ -2069,16 +1865,21 @@ export class Agent {
2069
1865
  const active: Array<{ role: ModelRole; model: string; position: string }> = [];
2070
1866
 
2071
1867
  for (const o of openings) {
2072
- yield { type: "content", content: `\n### [${o.role}] ${o.model}\n` };
1868
+ const roleColor = COUNCIL_ROLE_COLORS[o.role] ?? "";
1869
+ yield { type: "content", content: `\n### ${roleColor}[${o.role}]${COUNCIL_COLOR_RESET} ${o.model}\n` };
2073
1870
  if (o.error) {
2074
1871
  yield { type: "content", content: `[Error: ${o.error}]\n` };
2075
1872
  } else {
2076
1873
  active.push({ role: o.role, model: o.model, position: o.position });
2077
- yield { type: "content", content: o.position + "\n" };
1874
+ const bgColor = COUNCIL_COLOR_BG[o.role] ?? "";
1875
+ yield { type: "content", content: `${bgColor} ${o.role.toUpperCase()} ${COUNCIL_COLOR_RESET} ${o.position}\n` };
2078
1876
  }
2079
1877
  }
2080
1878
 
2081
- yield { type: "content", content: `\n> Phase 1: ${active.length} participants, ${((Date.now() - p1Start) / 1000).toFixed(1)}s (parallel)\n` };
1879
+ yield {
1880
+ type: "content",
1881
+ content: `\n> Phase 1: ${active.length} participants, ${((Date.now() - p1Start) / 1000).toFixed(1)}s (parallel)\n`,
1882
+ };
2082
1883
 
2083
1884
  if (active.length < 2) {
2084
1885
  yield { type: "content", content: "\nNot enough successful openings for discussion.\n" };
@@ -2089,6 +1890,7 @@ export class Agent {
2089
1890
  // ── Phase 2: Discussion rounds with parallel pair debates ──
2090
1891
  const exchangeLogs: Map<string, string[]> = new Map();
2091
1892
  const pairConverged: Map<string, boolean> = new Map();
1893
+ let runningSummary = "";
2092
1894
 
2093
1895
  for (let round = 1; round <= maxRounds; round++) {
2094
1896
  const p2Start = Date.now();
@@ -2118,36 +1920,56 @@ export class Agent {
2118
1920
  let bResponse: string;
2119
1921
 
2120
1922
  if (round === 1) {
2121
- const aPrompt = this._buildDiscussPrompt("respond", {
2122
- speakerRole: a.role, partnerRole: b.role, topic,
2123
- speakerPosition: a.position, partnerPosition: b.position,
1923
+ const aPrompt = this.councilManager.buildDiscussPrompt("respond", {
1924
+ speakerRole: a.role,
1925
+ partnerRole: b.role,
1926
+ topic,
1927
+ speakerPosition: a.position,
1928
+ partnerPosition: b.position,
1929
+ conversationContext: enrichedContext,
2124
1930
  });
2125
- aResponse = await this._councilGenerate(a.model, aPrompt.system, aPrompt.prompt);
1931
+ aResponse = await this.councilManager.generate(a.model, aPrompt.system, aPrompt.prompt);
2126
1932
  log.push(`[${a.role}]: ${aResponse}`);
2127
1933
  chunks.push({ label: `[${a.role}] → [${b.role}]`, text: aResponse });
2128
1934
 
2129
- const bPrompt = this._buildDiscussPrompt("respond", {
2130
- speakerRole: b.role, partnerRole: a.role, topic,
2131
- speakerPosition: b.position, partnerPosition: aResponse,
1935
+ const bPrompt = this.councilManager.buildDiscussPrompt("respond", {
1936
+ speakerRole: b.role,
1937
+ partnerRole: a.role,
1938
+ topic,
1939
+ speakerPosition: b.position,
1940
+ partnerPosition: aResponse,
1941
+ conversationContext: enrichedContext,
2132
1942
  });
2133
- bResponse = await this._councilGenerate(b.model, bPrompt.system, bPrompt.prompt);
1943
+ bResponse = await this.councilManager.generate(b.model, bPrompt.system, bPrompt.prompt);
2134
1944
  log.push(`[${b.role}]: ${bResponse}`);
2135
1945
  chunks.push({ label: `[${b.role}] → [${a.role}]`, text: bResponse });
2136
1946
  } else {
2137
1947
  const historyText = log.join("\n\n");
2138
- const aPrompt = this._buildDiscussPrompt("followup", {
2139
- speakerRole: a.role, partnerRole: b.role, topic,
2140
- partnerPosition: b.position, exchangeHistory: historyText, round,
1948
+ const aPrompt = this.councilManager.buildDiscussPrompt("followup", {
1949
+ speakerRole: a.role,
1950
+ partnerRole: b.role,
1951
+ topic,
1952
+ partnerPosition: b.position,
1953
+ exchangeHistory: historyText,
1954
+ round,
1955
+ conversationContext: enrichedContext,
1956
+ runningSummary,
2141
1957
  });
2142
- aResponse = await this._councilGenerate(a.model, aPrompt.system, aPrompt.prompt);
1958
+ aResponse = await this.councilManager.generate(a.model, aPrompt.system, aPrompt.prompt, 1024);
2143
1959
  log.push(`[${a.role}] (round ${round}): ${aResponse}`);
2144
1960
  chunks.push({ label: `[${a.role}] → [${b.role}]`, text: aResponse });
2145
1961
 
2146
- const bPrompt = this._buildDiscussPrompt("followup", {
2147
- speakerRole: b.role, partnerRole: a.role, topic,
2148
- partnerPosition: aResponse, exchangeHistory: historyText, round,
1962
+ const bPrompt = this.councilManager.buildDiscussPrompt("followup", {
1963
+ speakerRole: b.role,
1964
+ partnerRole: a.role,
1965
+ topic,
1966
+ partnerPosition: aResponse,
1967
+ exchangeHistory: historyText,
1968
+ round,
1969
+ conversationContext: enrichedContext,
1970
+ runningSummary,
2149
1971
  });
2150
- bResponse = await this._councilGenerate(b.model, bPrompt.system, bPrompt.prompt);
1972
+ bResponse = await this.councilManager.generate(b.model, bPrompt.system, bPrompt.prompt, 1024);
2151
1973
  log.push(`[${b.role}] (round ${round}): ${bResponse}`);
2152
1974
  chunks.push({ label: `[${b.role}] → [${a.role}]`, text: bResponse });
2153
1975
  }
@@ -2156,26 +1978,34 @@ export class Agent {
2156
1978
  a.position = aResponse;
2157
1979
 
2158
1980
  // Convergence check
2159
- const convPrompt = this._buildDiscussPrompt("convergence-check", {
2160
- speakerRole: a.role, partnerRole: b.role, topic,
1981
+ const convPrompt = this.councilManager.buildDiscussPrompt("convergence-check", {
1982
+ speakerRole: a.role,
1983
+ partnerRole: b.role,
1984
+ topic,
2161
1985
  exchangeHistory: log.slice(-4).join("\n\n"),
1986
+ conversationContext: enrichedContext,
2162
1987
  });
2163
1988
  let converged = false;
2164
1989
  let convReason = "";
2165
1990
  try {
2166
- const raw = await this._councilGenerate(a.model, convPrompt.system, convPrompt.prompt, 256);
1991
+ const raw = await this.councilManager.generate(a.model, convPrompt.system, convPrompt.prompt, 256);
2167
1992
  const match = raw.match(/\{[\s\S]*\}/);
2168
1993
  if (match) {
2169
1994
  const parsed = JSON.parse(match[0]) as { converged?: boolean; reason?: string };
2170
1995
  converged = parsed.converged === true;
2171
1996
  convReason = parsed.reason ?? "";
2172
1997
  }
2173
- } catch { /* not converged */ }
1998
+ } catch {
1999
+ /* not converged */
2000
+ }
2174
2001
 
2175
2002
  return { key, chunks, converged, convReason, error: null as string | null };
2176
2003
  } catch (err: unknown) {
2177
2004
  return {
2178
- key, chunks, converged: false, convReason: "",
2005
+ key,
2006
+ chunks,
2007
+ converged: false,
2008
+ convReason: "",
2179
2009
  error: err instanceof Error ? err.message : String(err),
2180
2010
  };
2181
2011
  }
@@ -2186,7 +2016,14 @@ export class Agent {
2186
2016
  let allConverged = true;
2187
2017
  for (const pr of pairResults) {
2188
2018
  for (const chunk of pr.chunks) {
2189
- yield { type: "content", content: `\n### ${chunk.label}\n${chunk.text}\n` };
2019
+ const labelParts = chunk.label.match(/\[(\w+)\] → \[(\w+)\]/);
2020
+ let coloredLabel = chunk.label;
2021
+ if (labelParts) {
2022
+ const fromColor = COUNCIL_ROLE_COLORS[labelParts[1]] ?? "";
2023
+ const toColor = COUNCIL_ROLE_COLORS[labelParts[2]] ?? "";
2024
+ coloredLabel = `${fromColor}[${labelParts[1]}]${COUNCIL_COLOR_RESET} → ${toColor}[${labelParts[2]}]${COUNCIL_COLOR_RESET}`;
2025
+ }
2026
+ yield { type: "content", content: `\n### ${coloredLabel}\n${chunk.text}\n` };
2190
2027
  }
2191
2028
  if (pr.error) {
2192
2029
  yield { type: "content", content: `[Discussion error: ${pr.error}]\n` };
@@ -2199,12 +2036,32 @@ export class Agent {
2199
2036
  }
2200
2037
  }
2201
2038
 
2202
- yield { type: "content", content: `\n> Round ${round}: ${((Date.now() - p2Start) / 1000).toFixed(1)}s (${pairs.length} pairs parallel)\n` };
2039
+ yield {
2040
+ type: "content",
2041
+ content: `\n> Round ${round}: ${((Date.now() - p2Start) / 1000).toFixed(1)}s (${pairs.length} pairs parallel)\n`,
2042
+ };
2203
2043
 
2204
2044
  if (allConverged) {
2205
2045
  yield { type: "content", content: `\n> All pairs converged at round ${round}. Moving to synthesis.\n` };
2206
2046
  break;
2207
2047
  }
2048
+
2049
+ // Generate inter-round summary for next round's focus
2050
+ if (round < maxRounds) {
2051
+ try {
2052
+ runningSummary = await this.councilManager.generateRoundSummary(exchangeLogs, topic, round, active[0].model);
2053
+ yield {
2054
+ type: "content",
2055
+ content: `\n> **Discussion state:** ${runningSummary
2056
+ .split("\n")
2057
+ .filter((l) => l.trim())
2058
+ .slice(0, 3)
2059
+ .join(" | ")}\n`,
2060
+ };
2061
+ } catch {
2062
+ // Non-critical — continue without summary
2063
+ }
2064
+ }
2208
2065
  }
2209
2066
 
2210
2067
  // ── Phase 3: Leader synthesis ──
@@ -2212,41 +2069,78 @@ export class Agent {
2212
2069
  yield { type: "content", content: "\n## Phase 3 — Leader Synthesis\n" };
2213
2070
 
2214
2071
  const leaderModelId = getRoleModel("leader") ?? this.modelId;
2215
- yield { type: "content", content: `\n### [leader] ${leaderModelId}\n` };
2072
+ yield { type: "content", content: `\n### \x1b[32m[leader]\x1b[0m ${leaderModelId}\n` };
2216
2073
 
2217
2074
  const allExchanges = [...exchangeLogs.entries()]
2218
2075
  .map(([pair, log]) => `### Discussion: ${pair}\n${log.join("\n\n")}`)
2219
2076
  .join("\n\n---\n\n");
2220
2077
 
2221
- const finalPositions = active
2222
- .map((p) => `**${p.role}** (${p.model}): ${p.position.slice(0, 500)}...`)
2223
- .join("\n\n");
2078
+ const finalPositions = active.map((p) => `**${p.role}** (${p.model}): ${p.position.slice(0, 500)}...`).join("\n\n");
2224
2079
 
2225
2080
  let synthesisText = "";
2226
2081
  try {
2227
- synthesisText = await this._councilGenerate(
2082
+ synthesisText = await this.councilManager.generate(
2228
2083
  leaderModelId,
2229
- "You are the team lead. Multiple specialists just had a structured discussion. Synthesize:\n" +
2230
- "1. What everyone agreed on these are your strongest foundations\n" +
2231
- "2. Where genuine disagreement remains these are real trade-offs, not resolvable by more discussion\n" +
2232
- "3. Your decisive recommendation based on the full discussion\n" +
2233
- "4. Specific next steps and risks to watch\n\n" +
2234
- "Be decisive. The discussion has happened — now it's time to decide.",
2084
+ "You are the team lead. Multiple specialists just had a structured discussion about a topic.\n\n" +
2085
+ "Output TWO parts separated by the exact line `---READABLE---`:\n\n" +
2086
+ "**Part 1: JSON**a single JSON object:\n" +
2087
+ "```\n" +
2088
+ '{ "type": "decision"|"action_items"|"plan_update"|"resolve_question",\n' +
2089
+ ' "summary": "1-2 sentence executive summary",\n' +
2090
+ ' "agreed": ["point 1", "point 2"],\n' +
2091
+ ' "tradeoffs": ["trade-off 1"],\n' +
2092
+ ' "recommendation": "Your decisive recommendation",\n' +
2093
+ ' "actionItems": ["step 1", "step 2"],\n' +
2094
+ ' "planUpdate": "paragraph for plan update (only if type=plan_update)",\n' +
2095
+ ' "resolvedQuestion": {"question": "...", "answer": "..."} }\n' +
2096
+ "```\n" +
2097
+ "Choose type: decision (general), action_items (concrete steps), plan_update (modify active plan), resolve_question (answer a specific question).\n\n" +
2098
+ "**Part 2: Human-readable** — after `---READABLE---`, write the synthesis in markdown:\n" +
2099
+ "## AGREED\n## TRADE-OFFS\n## RECOMMENDATION\n## NEXT STEPS\n\n" +
2100
+ "Be decisive. Output Part 1 JSON first, then ---READABLE---, then Part 2.",
2235
2101
  `Topic: ${topic}\n\nFinal positions:\n${finalPositions}\n\nFull discussion:\n${allExchanges}`,
2236
2102
  4096,
2237
2103
  );
2238
- yield { type: "content", content: synthesisText + "\n" };
2104
+
2105
+ // Display human-readable part
2106
+ const readablePart = synthesisText.includes("---READABLE---")
2107
+ ? synthesisText.split("---READABLE---")[1]?.trim()
2108
+ : synthesisText;
2109
+ yield { type: "content", content: `${readablePart || synthesisText}\n` };
2110
+
2111
+ // Parse structured outcome and execute actions
2112
+ const structuredOutcome = this.councilManager.parseOutcome(synthesisText, topic);
2113
+ if (structuredOutcome) {
2114
+ yield* this.councilManager.executeOutcome(structuredOutcome, topic);
2115
+ if (this.session) {
2116
+ try {
2117
+ appendSystemMessage(this.session.id, `[Council Outcome]\n${JSON.stringify(structuredOutcome)}`);
2118
+ } catch {
2119
+ /* non-critical */
2120
+ }
2121
+ }
2122
+ } else {
2123
+ // Fallback: store text-only outcome (backward compatible)
2124
+ if (this.session) {
2125
+ try {
2126
+ appendSystemMessage(this.session.id, `[Council Outcome]\nTopic: ${topic}\n${synthesisText.slice(0, 2000)}`);
2127
+ } catch {
2128
+ /* non-critical */
2129
+ }
2130
+ }
2131
+ }
2239
2132
  } catch (err: unknown) {
2240
2133
  yield { type: "content", content: `[Synthesis error: ${err instanceof Error ? err.message : err}]\n` };
2241
2134
  }
2242
2135
 
2243
2136
  // ── Stats + Memory ──
2244
- const totalMs = Date.now() - this._councilStats.startMs;
2137
+ const councilStats = this.councilManager.stats;
2138
+ const totalMs = Date.now() - councilStats.startMs;
2245
2139
  yield {
2246
2140
  type: "content",
2247
2141
  content:
2248
2142
  `\n---\n` +
2249
- `> Council stats: ${this._councilStats.calls} API calls, ${(totalMs / 1000).toFixed(1)}s total, ` +
2143
+ `> Council stats: ${councilStats.calls} API calls, ${(totalMs / 1000).toFixed(1)}s total, ` +
2250
2144
  `${active.length} participants, synthesis ${((Date.now() - p3Start) / 1000).toFixed(1)}s\n`,
2251
2145
  };
2252
2146
 
@@ -2258,17 +2152,34 @@ export class Agent {
2258
2152
  finalPositions: active.map((a) => ({ role: a.role, position: a.position.slice(0, 1000) })),
2259
2153
  synthesis: synthesisText.slice(0, 2000),
2260
2154
  convergedPairs: [...pairConverged.entries()].filter(([, v]) => v).map(([k]) => k),
2261
- stats: { calls: this._councilStats.calls, durationMs: totalMs },
2155
+ stats: { calls: councilStats.calls, durationMs: totalMs },
2262
2156
  timestamp: new Date().toISOString(),
2263
2157
  };
2264
2158
  try {
2265
2159
  appendSystemMessage(this.session.id, `[Council Memory] ${JSON.stringify(councilRecord)}`);
2266
- } catch { /* non-critical */ }
2160
+ } catch {
2161
+ /* non-critical */
2162
+ }
2267
2163
  }
2268
2164
 
2165
+ // Store council output as assistant message so the conversation history
2166
+ // stays valid (user→assistant alternation required by most APIs).
2167
+ const councilResponse = synthesisText || "[Council completed — see discussion above]";
2168
+ if (userModelMessage) {
2169
+ this.appendCompletedTurn(userModelMessage, [{ role: "assistant", content: councilResponse }]);
2170
+ }
2171
+ this.councilManager.setLastSynthesis(councilResponse);
2172
+
2269
2173
  yield { type: "done" };
2270
2174
  }
2271
2175
 
2176
+ // ========================================================================
2177
+ // processMessageBatchTurn — batch API message processing loop.
2178
+ // Body extracted into BatchTurnRunner (Phase 12.5). Thin wrapper preserved
2179
+ // so MessageProcessorDeps' `processMessageBatchTurn` callback continues to
2180
+ // dispatch through `Agent.processMessageBatchTurn` unchanged.
2181
+ // ========================================================================
2182
+
2272
2183
  private async *processMessageBatchTurn(args: {
2273
2184
  userModelMessage: ModelMessage;
2274
2185
  observer?: ProcessMessageObserver;
@@ -2279,226 +2190,65 @@ export class Agent {
2279
2190
  modelInfo: ReturnType<typeof getModelInfo>;
2280
2191
  signal: AbortSignal;
2281
2192
  }): AsyncGenerator<StreamChunk, void, unknown> {
2282
- const { userModelMessage, observer, provider, subagents, system, runtime, modelInfo, signal } = args;
2283
- let attemptedOverflowRecovery = false;
2284
-
2285
- while (true) {
2286
- this._compactedThisTurn = false;
2287
- let closeMcp: (() => Promise<void>) | undefined;
2288
- const turnMessages: ModelMessage[] = [];
2289
- const totalUsage: ProcessMessageUsage = {};
2290
-
2291
- try {
2292
- const settings = attemptedOverflowRecovery
2293
- ? relaxCompactionSettings(this.getCompactionSettings())
2294
- : this.getCompactionSettings();
2295
- if (modelInfo?.contextWindow) {
2296
- await this.compactForContext(
2297
- provider,
2298
- system,
2299
- modelInfo.contextWindow,
2300
- signal,
2301
- settings,
2302
- attemptedOverflowRecovery,
2303
- );
2304
- }
2305
-
2306
- if (runtime.modelInfo?.responsesOnly) {
2307
- throw new Error("Batch mode currently supports chat-completions models only.");
2308
- }
2309
-
2310
- const baseTools = createTools(this.bash, provider, this.mode, {
2311
- runTask: (request, abortSignal) => this.runTask(request, combineAbortSignals(signal, abortSignal)),
2312
- runDelegation: (request, abortSignal) =>
2313
- this.runDelegation(request, combineAbortSignals(signal, abortSignal)),
2314
- readDelegation: (id) => this.readDelegation(id),
2315
- listDelegations: () => this.listDelegations(),
2316
- scheduleManager: this.schedules,
2317
- subagents,
2318
- sendTelegramFile: this.sendTelegramFile ?? undefined,
2319
- sessionId: this.session?.id ?? undefined,
2320
- });
2321
- let tools: ToolSet = runtime.modelInfo?.supportsClientTools === false ? {} : baseTools;
2322
- if (this.mode === "agent" && runtime.modelInfo?.supportsClientTools !== false) {
2323
- const mcpBundle = await buildMcpToolSet(loadMcpServers(), {
2324
- onOAuthRequired: (_serverId, url) => {
2325
- const urlStr = url.toString();
2326
- import("child_process").then(({ exec }) => {
2327
- const cmd = process.platform === "win32" ? `start "" "${urlStr}"`
2328
- : process.platform === "darwin" ? `open "${urlStr}"`
2329
- : `xdg-open "${urlStr}"`;
2330
- exec(cmd);
2331
- });
2332
- },
2333
- });
2334
- closeMcp = mcpBundle.close;
2335
- tools = { ...baseTools, ...mcpBundle.tools };
2336
- if (mcpBundle.errors.length > 0) {
2337
- yield { type: "content", content: `MCP unavailable: ${mcpBundle.errors.join(" | ")}\n\n` };
2338
- }
2339
- }
2340
-
2341
- const batchTools = runtime.modelInfo?.supportsClientTools === false ? [] : await toolSetToBatchTools(tools);
2342
- const batch = await createBatch({
2343
- ...this.getBatchClientOptions(signal),
2344
- name: buildBatchName("session", this.getSessionId() || runtime.modelId),
2345
- });
2346
-
2347
- for (let round = 0; round < this.maxToolRounds; round++) {
2348
- const stepNumber = round + 1;
2349
- notifyObserver(observer?.onStepStart, {
2350
- stepNumber,
2351
- timestamp: Date.now(),
2352
- });
2353
-
2354
- const batchRequestId = `turn-${Date.now()}-${stepNumber}`;
2355
- await addBatchRequests({
2356
- ...this.getBatchClientOptions(signal),
2357
- batchId: batch.batch_id,
2358
- batchRequests: [
2359
- {
2360
- batch_request_id: batchRequestId,
2361
- batch_request: {
2362
- chat_get_completion: buildBatchChatCompletionRequest({
2363
- modelId: runtime.modelId,
2364
- system,
2365
- messages: [...this.messages, ...turnMessages],
2366
- temperature: 0.7,
2367
- maxOutputTokens: runtime.modelInfo?.supportsMaxOutputTokens === false ? undefined : this.maxTokens,
2368
- reasoningEffort: runtime.providerOptions?.xai.reasoningEffort,
2369
- tools: batchTools,
2370
- }),
2371
- },
2372
- },
2373
- ],
2374
- });
2375
-
2376
- const result = await pollBatchRequestResult({
2377
- ...this.getBatchClientOptions(signal),
2378
- batchId: batch.batch_id,
2379
- batchRequestId,
2380
- });
2381
- const response = getBatchChatCompletion(result);
2382
- const choice = response.choices[0];
2383
- if (!choice) {
2384
- throw new Error("Batch response did not contain any choices.");
2385
- }
2386
-
2387
- const usage = getBatchUsage(response);
2388
- accumulateUsage(totalUsage, usage);
2389
- const finishReason = getBatchFinishReason(choice.finish_reason);
2390
-
2391
- const content = choice.message.content ?? "";
2392
- if (content) {
2393
- yield { type: "content", content };
2394
- }
2395
-
2396
- const requestMessages = [...this.messages, ...turnMessages];
2397
- const toolCalls = (choice.message.tool_calls ?? []).map(toLocalToolCall);
2398
- const assistantMessage = buildAssistantBatchMessage(content, toolCalls);
2399
- if (assistantMessage) {
2400
- turnMessages.push(assistantMessage);
2401
- }
2402
-
2403
- if (toolCalls.length === 0) {
2404
- notifyObserver(observer?.onStepFinish, {
2405
- stepNumber,
2406
- timestamp: Date.now(),
2407
- finishReason,
2408
- usage,
2409
- });
2410
- if (hasUsage(totalUsage)) {
2411
- this.recordUsage(totalUsage, "message", runtime.modelId);
2412
- }
2413
- this.appendCompletedTurn(userModelMessage, turnMessages);
2414
- if (modelInfo?.contextWindow) {
2415
- await this.postTurnCompact(provider, system, modelInfo.contextWindow, signal);
2416
- }
2417
- yield { type: "done" };
2418
- return;
2419
- }
2420
-
2421
- yield { type: "tool_calls", toolCalls };
2422
-
2423
- const toolParts: ExecutedBatchTool[] = [];
2424
- for (const toolCall of toolCalls) {
2425
- notifyObserver(observer?.onToolStart, {
2426
- toolCall,
2427
- timestamp: Date.now(),
2428
- });
2429
-
2430
- const executed = await this.executeBatchToolCall(tools, toolCall, requestMessages, signal);
2431
- notifyObserver(observer?.onToolFinish, {
2432
- toolCall,
2433
- toolResult: executed.result,
2434
- timestamp: Date.now(),
2435
- });
2436
- yield { type: "tool_result", toolCall, toolResult: executed.result };
2437
- toolParts.push({
2438
- toolCall,
2439
- input: executed.input,
2440
- toolResult: executed.result,
2441
- });
2442
- }
2443
-
2444
- const toolMessage = buildToolBatchMessage(toolParts);
2445
- if (toolMessage) {
2446
- turnMessages.push(toolMessage);
2447
- }
2448
- notifyObserver(observer?.onStepFinish, {
2449
- stepNumber,
2450
- timestamp: Date.now(),
2451
- finishReason,
2452
- usage,
2453
- });
2454
- }
2455
-
2456
- const message = `Error: Reached max tool rounds (${this.maxToolRounds}) in batch mode.`;
2457
- notifyObserver(observer?.onError, {
2458
- message,
2459
- timestamp: Date.now(),
2460
- });
2461
- if (hasUsage(totalUsage)) {
2462
- this.recordUsage(totalUsage, "message", runtime.modelId);
2463
- }
2464
- this.appendCompletedTurn(userModelMessage, turnMessages);
2465
- yield { type: "error", content: message };
2466
- yield { type: "done" };
2467
- return;
2468
- } catch (err: unknown) {
2469
- if (signal.aborted) {
2470
- this.discardAbortedTurn(userModelMessage);
2471
- yield { type: "content", content: "\n\n[Cancelled]" };
2472
- yield { type: "done" };
2473
- return;
2474
- }
2475
-
2476
- if (!attemptedOverflowRecovery && turnMessages.length === 0 && modelInfo && isContextLimitError(err)) {
2477
- attemptedOverflowRecovery = true;
2478
- continue;
2479
- }
2193
+ const runner = new BatchTurnRunner(this._buildBatchTurnRunnerDeps());
2194
+ yield* runner.run(args);
2195
+ }
2480
2196
 
2481
- const authError = isAuthenticationError(err);
2482
- const friendly = humanizeApiError(err);
2483
- notifyObserver(observer?.onError, {
2484
- message: friendly,
2485
- timestamp: Date.now(),
2486
- });
2487
- if (hasUsage(totalUsage)) {
2488
- this.recordUsage(totalUsage, "message", runtime.modelId);
2489
- }
2490
- this.appendCompletedTurn(userModelMessage, turnMessages);
2491
- yield {
2492
- type: "error",
2493
- content: friendly,
2494
- isAuthError: authError,
2495
- };
2496
- yield { type: "done" };
2497
- return;
2498
- } finally {
2499
- await closeMcp?.().catch(() => {});
2500
- }
2501
- }
2197
+ /**
2198
+ * Build the DI surface BatchTurnRunner (Phase 12.5) needs to reach back
2199
+ * into Agent state without holding a circular reference. Callback names
2200
+ * align with `MessageProcessorDeps` where the signature matches so a
2201
+ * future `TurnRunnerDepsBase` hoist is mechanical. Built per call —
2202
+ * allocation cost is negligible against the batch polling spend.
2203
+ */
2204
+ private _buildBatchTurnRunnerDeps(): BatchTurnRunnerDeps {
2205
+ const self = this;
2206
+ return {
2207
+ get messages() {
2208
+ return self.messages;
2209
+ },
2210
+ get bash() {
2211
+ return self.bash;
2212
+ },
2213
+ get mode() {
2214
+ return self.mode;
2215
+ },
2216
+ get maxToolRounds() {
2217
+ return self.maxToolRounds;
2218
+ },
2219
+ get maxTokens() {
2220
+ return self.maxTokens;
2221
+ },
2222
+ get schedules() {
2223
+ return self.schedules;
2224
+ },
2225
+ get sendTelegramFile() {
2226
+ return self.sendTelegramFile;
2227
+ },
2228
+ getSessionId: () => self.session?.id ?? null,
2229
+ getCompactedThisTurn: () => self._compactedThisTurn,
2230
+ setCompactedThisTurn: (v) => {
2231
+ self._compactedThisTurn = v;
2232
+ },
2233
+ setLastProviderOptionsShape: (shape) => {
2234
+ self._lastProviderOptionsShape = shape;
2235
+ },
2236
+ getBatchClientOptions: (signal) => self.getBatchClientOptions(signal),
2237
+ getCompactionSettings: (cw) => self.getCompactionSettings(cw),
2238
+ compactForContext: (provider, system, cw, signal, settings, overflow) =>
2239
+ self.compactForContext(provider, system, cw, signal, settings, overflow),
2240
+ postTurnCompact: (provider, system, cw, signal) => self.postTurnCompact(provider, system, cw, signal),
2241
+ createTools: (bash, provider, mode, opts) => createTools(bash, provider, mode, opts),
2242
+ runTask: (request, signal) => self.runTask(request, signal),
2243
+ runDelegation: (request, signal) => self.runDelegation(request, signal),
2244
+ readDelegation: (id) => self.readDelegation(id),
2245
+ listDelegations: () => self.listDelegations(),
2246
+ executeBatchToolCall: (tools, toolCall, messages, signal) =>
2247
+ self.executeBatchToolCall(tools, toolCall, messages, signal),
2248
+ appendCompletedTurn: (user, asst) => self.appendCompletedTurn(user, asst),
2249
+ discardAbortedTurn: (user) => self.discardAbortedTurn(user),
2250
+ recordUsage: (usage, source, model) => self.recordUsage(usage, source, model),
2251
+ };
2502
2252
  }
2503
2253
 
2504
2254
  private appendCompletedTurn(userMessage: ModelMessage, newMessages: ModelMessage[]): void {
@@ -2514,6 +2264,28 @@ export class Agent {
2514
2264
  return;
2515
2265
  }
2516
2266
 
2267
+ // Phase A5 — if the user message already has a persisted seq (set by
2268
+ // the write-ahead path), skip re-inserting it. The write-ahead row
2269
+ // will be upserted to status='completed' on the next `appendMessages`
2270
+ // call that sees it via ON CONFLICT, but here we only need to insert
2271
+ // the *new* assistant/tool messages so they get fresh sequence
2272
+ // numbers contiguous with the user row.
2273
+ const existingUserSeq = userIndex >= 0 ? this.messageSeqs[userIndex] : null;
2274
+ if (typeof existingUserSeq === "number") {
2275
+ // User row is already persisted (write-ahead). Insert only the new
2276
+ // assistant/tool messages so they get fresh sequence numbers
2277
+ // contiguous with the user row. Then flip the user row's status
2278
+ // from 'pending' to 'completed' so forensics + replay tooling can
2279
+ // tell the turn settled cleanly.
2280
+ const insertedSeqs = appendMessages(this.session.id, newMessages);
2281
+ markMessageCompleted(this.session.id, existingUserSeq);
2282
+ this.messages.push(...newMessages);
2283
+ this.messageSeqs.push(...insertedSeqs);
2284
+ this.sessionStore.touchSession(this.session.id, this.bash.getCwd());
2285
+ this.session = this.sessionStore.getRequiredSession(this.session.id);
2286
+ return;
2287
+ }
2288
+
2517
2289
  const insertedSeqs = appendMessages(this.session.id, [userMessage, ...newMessages]);
2518
2290
  if (userIndex >= 0) {
2519
2291
  this.messageSeqs[userIndex] = insertedSeqs[0] ?? this.messageSeqs[userIndex];
@@ -2531,844 +2303,212 @@ export class Agent {
2531
2303
  return executeEventHooks(input, this.bash.getCwd(), signal);
2532
2304
  }
2533
2305
 
2306
+ // ========================================================================
2307
+ // processMessage — main streaming turn loop (PIL enrichment, routing, LLM
2308
+ // stream, tool execution, compaction, hooks, observer notifications)
2309
+ // ========================================================================
2310
+
2534
2311
  async *processMessage(
2535
2312
  userMessage: string,
2536
2313
  observer?: ProcessMessageObserver,
2537
2314
  images?: Array<{ path: string; mediaType: string; base64: string }>,
2538
2315
  ): AsyncGenerator<StreamChunk, void, unknown> {
2539
- // TUI-04: prefer the external AbortContext (from SIGINT handler) so that
2540
- // Ctrl+C mid-tool-call triggers a single, unified abort across all I/O.
2541
- // If no external context, fall back to creating a local AbortController.
2542
- if (this.externalAbortContext) {
2543
- // Wrap the external signal in a local controller so existing cleanup
2544
- // paths (this.abortController = null) still work without side-effects.
2545
- this.abortController = new AbortController();
2546
- // Forward external abort to the local controller.
2547
- this.externalAbortContext.signal.addEventListener(
2548
- "abort",
2549
- () => {
2550
- this.abortController?.abort(this.externalAbortContext?.reason());
2551
- },
2552
- { once: true },
2553
- );
2554
- } else {
2555
- this.abortController = new AbortController();
2556
- }
2557
- const signal = this.abortController.signal;
2558
- this.emitSubagentStatus(null);
2316
+ const processor = new MessageProcessor(this._buildMessageProcessorDeps());
2317
+ yield* processor.run(userMessage, observer, images);
2318
+ }
2319
+
2320
+ /**
2321
+ * Build the DI surface MessageProcessor (Phase 12.4) needs to reach back
2322
+ * into Agent state without holding a circular reference. Exposes array
2323
+ * references for in-place mutation (messages/messageSeqs) and bound
2324
+ * callbacks for behavior. Built per call — allocation cost is negligible
2325
+ * against the streamText spend.
2326
+ */
2327
+ private _buildMessageProcessorDeps(): MessageProcessorDeps {
2328
+ const self = this;
2329
+ return {
2330
+ get messages() {
2331
+ return self.messages;
2332
+ },
2333
+ get messageSeqs() {
2334
+ return self.messageSeqs;
2335
+ },
2336
+ get session() {
2337
+ return self.session;
2338
+ },
2339
+ get sessionStore() {
2340
+ return self.sessionStore;
2341
+ },
2342
+ get bash() {
2343
+ return self.bash;
2344
+ },
2345
+ get mode() {
2346
+ return self.mode;
2347
+ },
2348
+ get modelId() {
2349
+ return self.modelId;
2350
+ },
2351
+ get providerId() {
2352
+ return self.providerId;
2353
+ },
2354
+ get maxToolRounds() {
2355
+ return self.maxToolRounds;
2356
+ },
2357
+ get batchApi() {
2358
+ return self.batchApi;
2359
+ },
2360
+ get permissionMode() {
2361
+ return self.permissionMode;
2362
+ },
2363
+ get schedules() {
2364
+ return self.schedules;
2365
+ },
2366
+ get sendTelegramFile() {
2367
+ return self.sendTelegramFile;
2368
+ },
2369
+ get externalAbortContext() {
2370
+ return self.externalAbortContext;
2371
+ },
2372
+ get pendingCalls() {
2373
+ return self.pendingCalls;
2374
+ },
2375
+ get councilManager() {
2376
+ return self.councilManager;
2377
+ },
2378
+ get crossTurnDedup() {
2379
+ return self._crossTurnDedup;
2380
+ },
2381
+ get readBudget() {
2382
+ return self._readBudget;
2383
+ },
2384
+ get priorWarningIdsInSession() {
2385
+ return self._priorWarningIdsInSession;
2386
+ },
2387
+ get sessionEEGuidance() {
2388
+ return self._sessionEEGuidance;
2389
+ },
2390
+ get flowReady() {
2391
+ return self._flowReady;
2392
+ },
2393
+ getAbortController: () => self.abortController,
2394
+ setAbortController: (c) => {
2395
+ self.abortController = c;
2396
+ },
2397
+ getSessionStartHookFired: () => self.sessionStartHookFired,
2398
+ setSessionStartHookFired: (v) => {
2399
+ self.sessionStartHookFired = v;
2400
+ },
2401
+ getPlanContext: () => self.planContext,
2402
+ setPlanContext: (v) => {
2403
+ self.planContext = v;
2404
+ },
2405
+ getResumeDigest: () => self._resumeDigest,
2406
+ setResumeDigest: (v) => {
2407
+ self._resumeDigest = v;
2408
+ },
2409
+ getActiveRunId: () => self._activeRunId,
2410
+ getPendingCwdNote: () => self._pendingCwdNote,
2411
+ setPendingCwdNote: (v) => {
2412
+ self._pendingCwdNote = v;
2413
+ },
2414
+ setPilActive: (v) => {
2415
+ self._pilActive = v;
2416
+ },
2417
+ setPilEnrichmentDelta: (n) => {
2418
+ self._pilEnrichmentDelta = n;
2419
+ },
2420
+ setCurrentCallId: (id) => {
2421
+ self._currentCallId = id;
2422
+ },
2423
+ setLastProviderOptionsShape: (shape) => {
2424
+ self._lastProviderOptionsShape = shape;
2425
+ },
2426
+ setLastPromptBreakdown: (b) => {
2427
+ self._lastPromptBreakdown = b;
2428
+ },
2429
+ setCompactedThisTurn: (v) => {
2430
+ self._compactedThisTurn = v;
2431
+ },
2432
+ getCompactedThisTurn: () => self._compactedThisTurn,
2433
+ setTurnUserGoalExcerpt: (v) => {
2434
+ self._turnUserGoalExcerpt = v;
2435
+ },
2436
+ setTurnAssistantReasoning: (v) => {
2437
+ self._turnAssistantReasoning = v;
2438
+ },
2439
+ appendTurnAssistantReasoning: (delta) => {
2440
+ self._turnAssistantReasoning = (self._turnAssistantReasoning + delta).slice(-400);
2441
+ },
2442
+ getTurnAssistantReasoning: () => self._turnAssistantReasoning,
2443
+ setPriorWarningIdsInSession: (s) => {
2444
+ self._priorWarningIdsInSession = s;
2445
+ },
2446
+ setMessages: (m) => {
2447
+ self.messages = m;
2448
+ },
2449
+ requireProvider: () => self.requireProvider(),
2450
+ emitSubagentStatus: (s) => self.emitSubagentStatus(s),
2451
+ fireHook: (input, signal) =>
2452
+ self.fireHook(input as Parameters<Agent["fireHook"]>[0], signal) as ReturnType<
2453
+ MessageProcessorDeps["fireHook"]
2454
+ >,
2455
+ consumeBackgroundNotifications: () => self.consumeBackgroundNotifications(),
2456
+ initOAuthProvider: () => self._initOAuthProvider(),
2457
+ buildRecentTurnsSummary: () => self._buildRecentTurnsSummary(),
2458
+ estimateProjectSize: () => self._estimateProjectSize(),
2459
+ countFilesTouched: () => self._countFilesTouched(),
2460
+ getCompactionSettings: (cw) => self.getCompactionSettings(cw),
2461
+ compactForContext: (provider, system, cw, signal, settings, overflow) =>
2462
+ self.compactForContext(provider, system, cw, signal, settings, overflow),
2463
+ postTurnCompact: (provider, system, cw, signal) => self.postTurnCompact(provider, system, cw, signal),
2464
+ runTask: (request, signal) => self.runTask(request, signal),
2465
+ runDelegation: (request, signal) => self.runDelegation(request, signal),
2466
+ readDelegation: (id) => self.readDelegation(id),
2467
+ listDelegations: () => self.listDelegations(),
2468
+ appendCompletedTurn: (user, asst) => self.appendCompletedTurn(user, asst),
2469
+ discardAbortedTurn: (user) => self.discardAbortedTurn(user),
2470
+ recordUsage: (usage, source, model) => self.recordUsage(usage, source, model),
2471
+ respondToToolApproval: (id, ok) => self.respondToToolApproval(id, ok),
2472
+ runCouncilV2: (msg, opts) => self.runCouncilV2(msg, opts),
2473
+ processMessage: (msg, obs, imgs) => self.processMessage(msg, obs, imgs),
2474
+ processMessageBatchTurn: (args) => self.processMessageBatchTurn(args),
2475
+ };
2476
+ }
2559
2477
 
2560
- // Ensure flow run is ready before processing (fail-open).
2561
- await this._flowReady?.catch(() => {});
2478
+ // ========================================================================
2479
+ // processMessage body extracted into MessageProcessor (Phase 12.4).
2480
+ // The single original implementation now lives in
2481
+ // `src/orchestrator/message-processor.ts`. The thin wrapper above is the
2482
+ // only entry point.
2483
+ // ========================================================================
2562
2484
 
2563
- if (!this.sessionStartHookFired) {
2564
- this.sessionStartHookFired = true;
2565
- const isResume = this.messages.length > 0;
2566
- const sessionStartInput: SessionStartHookInput = {
2567
- hook_event_name: "SessionStart",
2568
- source: isResume ? "resume" : "startup",
2569
- session_id: this.session?.id,
2570
- cwd: this.bash.getCwd(),
2571
- };
2572
- await this.fireHook(sessionStartInput, signal).catch(() => {});
2573
- }
2485
+ // ========================================================================
2486
+ // Private helper methods — summary, estimation, verify
2487
+ // ========================================================================
2574
2488
 
2575
- const promptInput: UserPromptSubmitHookInput = {
2576
- hook_event_name: "UserPromptSubmit",
2577
- user_prompt: userMessage,
2578
- session_id: this.session?.id,
2579
- cwd: this.bash.getCwd(),
2580
- };
2581
- await this.fireHook(promptInput, signal).catch(() => {});
2582
-
2583
- await this.consumeBackgroundNotifications();
2584
-
2585
- const _debugOn = isDebugEnabled();
2586
- const _debugSteps: PipelineStep[] = [];
2587
- const _debugTurnId = this.messages.filter((m) => m.role === "user").length + 1;
2588
-
2589
- // PIL: enrich prompt before pushing to messages (D-01, D-03, D-04)
2590
- // Promise.race timeout of 200ms is inside runPipeline — fail-open guaranteed
2591
- const _pilStart = Date.now();
2592
- const pilCtx = await runPipeline(userMessage, {
2593
- resumeDigest: this._resumeDigest,
2594
- activeRunId: this._activeRunId,
2595
- }).catch(() => ({
2596
- raw: userMessage,
2597
- enriched: userMessage,
2598
- taskType: null,
2599
- domain: null,
2600
- confidence: 0,
2601
- outputStyle: null,
2602
- tokenBudget: 500,
2603
- metrics: null,
2604
- layers: [],
2605
- gsdPhase: null,
2606
- activeRunId: null,
2607
- }));
2608
- const enrichedMessage = pilCtx.enriched;
2609
- this._pilActive = pilCtx.taskType !== null;
2610
- this._pilEnrichmentDelta =
2611
- pilCtx.metrics?.estimatedTokensSaved ?? Math.round((enrichedMessage.length - userMessage.length) / 4);
2612
-
2613
- if (_debugOn) {
2614
- const appliedLayers = pilCtx.layers?.filter((l) => l.applied).map((l) => l.name) ?? [];
2615
- _debugSteps.push({
2616
- name: "PIL Pipeline",
2617
- duration_ms: Date.now() - _pilStart,
2618
- input_summary: `"${userMessage.slice(0, 60)}${userMessage.length > 60 ? "..." : ""}"`,
2619
- output_summary: `task=${pilCtx.taskType ?? "none"} domain=${pilCtx.domain ?? "none"} layers=[${appliedLayers.join(",")}]`,
2620
- tokens_saved: this._pilEnrichmentDelta > 0 ? this._pilEnrichmentDelta : undefined,
2621
- });
2489
+ private _buildRecentTurnsSummary(): string | null {
2490
+ if (this.messages.length < 2) return null;
2491
+ const recent = this.messages.slice(-6);
2492
+ const parts: string[] = [];
2493
+ for (const msg of recent) {
2494
+ if (msg.role !== "user" && msg.role !== "assistant") continue;
2495
+ const text =
2496
+ typeof msg.content === "string"
2497
+ ? msg.content
2498
+ : Array.isArray(msg.content)
2499
+ ? msg.content
2500
+ .filter((p: { type: string }) => p.type === "text")
2501
+ .map((p: { type: string; text?: string }) => p.text ?? "")
2502
+ .join("")
2503
+ : "";
2504
+ if (!text) continue;
2505
+ const snippet = text.length > 80 ? `${text.slice(0, 77)}...` : text;
2506
+ parts.push(`[${msg.role}]: ${snippet}`);
2622
2507
  }
2508
+ return parts.length > 0 ? parts.join(" | ") : null;
2509
+ }
2623
2510
 
2624
- // ROUTE-11: Per-turn model routing via decide() picks cheapest capable model
2625
- const turnStartMs = Date.now();
2626
- let turnModelId = this.modelId;
2627
- let taskHash: string | null = null;
2628
- const _routeStart = Date.now();
2629
- try {
2630
- const { decide } = await import("../router/decide.js");
2631
- const routeDecision = await decide(userMessage, {
2632
- tenantId: "local",
2633
- cwd: this.bash.getCwd(),
2634
- defaultModel: this.modelId,
2635
- defaultProvider: this.providerId,
2636
- pil: {
2637
- domain: pilCtx.domain,
2638
- taskType: pilCtx.taskType,
2639
- confidence: pilCtx.confidence,
2640
- gsdPhase: pilCtx.gsdPhase ?? null,
2641
- activeRunId: pilCtx.activeRunId ?? null,
2642
- recentTurnsSummary: this._buildRecentTurnsSummary(),
2643
- projectSize: this._estimateProjectSize(),
2644
- filesTouched: this._countFilesTouched(),
2645
- mode: this.mode,
2646
- },
2647
- });
2648
- if (routeDecision.model && routeDecision.model !== "HALT") {
2649
- turnModelId = routeDecision.model;
2650
- }
2651
- taskHash = routeDecision.taskHash ?? null;
2652
- // Update status bar with router switch info
2653
- if (turnModelId !== this.modelId) {
2654
- statusBarStore.setState({ routed_from: this.modelId, model: turnModelId });
2655
- }
2656
- if (_debugOn) {
2657
- _debugSteps.push({
2658
- name: "Router",
2659
- duration_ms: Date.now() - _routeStart,
2660
- input_summary: `default=${this.modelId}`,
2661
- output_summary: turnModelId !== this.modelId ? `routed→${turnModelId}` : `kept ${turnModelId}`,
2662
- });
2663
- }
2664
- } catch {
2665
- // Router unavailable — use session default model
2666
- const eeRoute = await routeModel(userMessage, {}, "claude").catch(() => null);
2667
- taskHash = eeRoute?.taskHash ?? null;
2668
- }
2669
-
2670
- // Re-detect provider if router picked a model from a different provider
2671
- const turnProviderId = detectProviderForModel(turnModelId);
2672
- let turnProvider: LegacyProvider;
2673
- if (turnProviderId !== this.providerId) {
2674
- const turnKey = await loadKeyForProvider(turnProviderId).catch(() => null);
2675
- if (turnKey) {
2676
- turnProvider = createProvider(turnProviderId, turnKey);
2677
- } else {
2678
- turnModelId = this.modelId;
2679
- turnProvider = this.requireProvider();
2680
- }
2681
- } else {
2682
- turnProvider = this.requireProvider();
2683
- }
2684
-
2685
- let userModelMessage: ModelMessage;
2686
- if (images?.length) {
2687
- const parts: Array<{ type: "text"; text: string } | { type: "image"; image: string; mediaType: string }> = [
2688
- { type: "text", text: enrichedMessage },
2689
- ];
2690
- for (const img of images) {
2691
- parts.push({ type: "image", image: img.base64, mediaType: img.mediaType });
2692
- }
2693
- userModelMessage = { role: "user", content: parts };
2694
- } else {
2695
- userModelMessage = { role: "user", content: enrichedMessage };
2696
- }
2697
-
2698
- // Vision proxy: convert images to text for models that don't support vision
2699
- if (images?.length && needsVisionProxy(turnModelId)) {
2700
- try {
2701
- const proxyResult = await proxyVision([userModelMessage], turnModelId, signal);
2702
- if (proxyResult.proxied) {
2703
- userModelMessage = proxyResult.messages[0];
2704
- yield { type: "content", content: `[Vision proxy: ${proxyResult.imageCount} image(s) → ${turnModelId} via SiliconFlow]\n` };
2705
- }
2706
- } catch {
2707
- yield { type: "content", content: "[Vision proxy: failed, images dropped]\n" };
2708
- userModelMessage = { role: "user", content: enrichedMessage };
2709
- }
2710
- }
2711
-
2712
- this.messages.push(userModelMessage);
2713
- this.messageSeqs.push(null);
2714
-
2715
- const provider = turnProvider;
2716
- const subagents = loadValidSubAgents();
2717
- const _pilResponseTools = getResponseToolSet(pilCtx);
2718
- const _hasResponseTools = Object.keys(_pilResponseTools).length > 0;
2719
- const systemParts = buildSystemPromptParts(
2720
- this.bash.getCwd(),
2721
- this.mode,
2722
- this.bash.getSandboxMode(),
2723
- this.planContext,
2724
- subagents,
2725
- this.bash.getSandboxSettings(),
2726
- this.providerId,
2727
- );
2728
- const system = applyModelConstraints(
2729
- applyPilSuffix(
2730
- `${systemParts.staticPrefix}${systemParts.dynamicSuffix}`,
2731
- pilCtx,
2732
- _hasResponseTools,
2733
- ),
2734
- turnModelId,
2735
- );
2736
- const runtime = resolveModelRuntime(provider, turnModelId);
2737
- const modelInfo = runtime.modelInfo;
2738
- this.planContext = null;
2739
- let attemptedOverflowRecovery = false;
2740
-
2741
- // Auto-council: for plan/analyze tasks with high confidence, run multi-model debate
2742
- const autoCouncilTypes = new Set(["plan", "analyze"]);
2743
- const councilRoles = getRoleModels();
2744
- const configuredRoleCount = Object.values(councilRoles).filter(Boolean).length;
2745
- if (
2746
- isAutoCouncilEnabled() &&
2747
- pilCtx.taskType &&
2748
- autoCouncilTypes.has(pilCtx.taskType) &&
2749
- pilCtx.confidence >= 0.75 &&
2750
- configuredRoleCount >= 2
2751
- ) {
2752
- yield { type: "content", content: `\n[Auto-council triggered: ${pilCtx.taskType} task detected with ${(pilCtx.confidence * 100).toFixed(0)}% confidence]\n` };
2753
- yield* this.runCouncilRound(userMessage, observer);
2754
- return;
2755
- }
2756
-
2757
- if (this.batchApi) {
2758
- try {
2759
- yield* this.processMessageBatchTurn({
2760
- userModelMessage,
2761
- observer,
2762
- provider,
2763
- subagents,
2764
- system,
2765
- runtime,
2766
- modelInfo,
2767
- signal,
2768
- });
2769
- } finally {
2770
- if (this.abortController?.signal === signal) {
2771
- this.abortController = null;
2772
- }
2773
- }
2774
- return;
2775
- }
2776
-
2777
- try {
2778
- while (true) {
2779
- this._compactedThisTurn = false;
2780
- let assistantText = "";
2781
- let reasoningPreview = "";
2782
- let encryptedReasoningHidden = false;
2783
- let streamOk = false;
2784
- let closeMcp: (() => Promise<void>) | undefined;
2785
- let stepNumber = -1;
2786
- const activeToolCalls: ToolCall[] = [];
2787
-
2788
- try {
2789
- const settings = attemptedOverflowRecovery
2790
- ? relaxCompactionSettings(this.getCompactionSettings())
2791
- : this.getCompactionSettings();
2792
- if (modelInfo?.contextWindow) {
2793
- await this.compactForContext(
2794
- provider,
2795
- system,
2796
- modelInfo.contextWindow,
2797
- signal,
2798
- settings,
2799
- attemptedOverflowRecovery,
2800
- );
2801
- }
2802
-
2803
- const baseTools = createTools(this.bash, provider, this.mode, {
2804
- runTask: (request, abortSignal) => this.runTask(request, combineAbortSignals(signal, abortSignal)),
2805
- runDelegation: (request, abortSignal) =>
2806
- this.runDelegation(request, combineAbortSignals(signal, abortSignal)),
2807
- readDelegation: (id) => this.readDelegation(id),
2808
- listDelegations: () => this.listDelegations(),
2809
- scheduleManager: this.schedules,
2810
- subagents,
2811
- sendTelegramFile: this.sendTelegramFile ?? undefined,
2812
- sessionId: this.session?.id ?? undefined,
2813
- });
2814
- let tools: ToolSet = runtime.modelInfo?.supportsClientTools === false ? {} : baseTools;
2815
- if (this.mode === "agent" && runtime.modelInfo?.supportsClientTools !== false) {
2816
- const mcpBundle = await buildMcpToolSet(loadMcpServers(), {
2817
- onOAuthRequired: (_serverId, url) => {
2818
- const urlStr = url.toString();
2819
- import("child_process").then(({ exec }) => {
2820
- const cmd = process.platform === "win32" ? `start "" "${urlStr}"`
2821
- : process.platform === "darwin" ? `open "${urlStr}"`
2822
- : `xdg-open "${urlStr}"`;
2823
- exec(cmd);
2824
- });
2825
- },
2826
- });
2827
- closeMcp = mcpBundle.close;
2828
- tools = { ...baseTools, ...mcpBundle.tools };
2829
- captureToolSchemas(tools);
2830
- if (mcpBundle.errors.length > 0) {
2831
- yield { type: "content", content: `MCP unavailable: ${mcpBundle.errors.join(" | ")}\n\n` };
2832
- }
2833
- }
2834
-
2835
- // PIL response tools: inject structured output tool when taskType detected
2836
- if (_hasResponseTools && runtime.modelInfo?.supportsClientTools !== false) {
2837
- tools = { ...tools, ..._pilResponseTools };
2838
- captureToolSchemas(_pilResponseTools);
2839
- }
2840
- let responseToolCalled = false;
2841
-
2842
- // Build provider options, optionally adding reasoning budget for capable models
2843
- const baseProviderOpts = runtime.providerOptions ?? {};
2844
- const providerOpts = runtime.modelInfo?.reasoning
2845
- ? {
2846
- ...baseProviderOpts,
2847
- anthropic: {
2848
- ...(baseProviderOpts.anthropic ?? {}),
2849
- thinking: {
2850
- type: "enabled" as const,
2851
- budgetTokens:
2852
- taskTypeToReasoningEffort(pilCtx.taskType) === "high"
2853
- ? 32_768
2854
- : taskTypeToReasoningEffort(pilCtx.taskType) === "medium"
2855
- ? 8_192
2856
- : 2_048,
2857
- },
2858
- },
2859
- }
2860
- : baseProviderOpts;
2861
- // Use catalog's thinkingType field instead of regex matching
2862
- const thinkingModelInfo = getModelInfo(runtime.modelId);
2863
- if (providerOpts.anthropic?.thinking?.type === "enabled" && thinkingModelInfo?.thinkingType === "adaptive") {
2864
- providerOpts.anthropic.thinking = { type: "adaptive" as any };
2865
- }
2866
-
2867
- // Multi-provider caching: OpenAI stored completions, DeepSeek prefix cache
2868
- const turnProvider = runtime.modelInfo?.provider ?? this.providerId;
2869
- if (turnProvider === "openai") {
2870
- providerOpts.openai = { ...(providerOpts.openai ?? {}), store: true };
2871
- }
2872
-
2873
- const systemForModel = runtime.modelId.startsWith("claude")
2874
- ? [
2875
- { role: "system" as const, content: systemParts.staticPrefix, providerOptions: { anthropic: { cacheControl: { type: "ephemeral" as const } } } },
2876
- { role: "system" as const, content: system.slice(systemParts.staticPrefix.length) },
2877
- ]
2878
- : system;
2879
-
2880
- const result = streamText({
2881
- model: runtime.model,
2882
- system: systemForModel,
2883
- messages: this.messages,
2884
- tools,
2885
- toolChoice:
2886
- _hasResponseTools && runtime.modelInfo?.supportsClientTools !== false
2887
- ? "auto"
2888
- : undefined,
2889
- stopWhen: stepCountIs(this.maxToolRounds),
2890
- maxRetries: 0,
2891
- abortSignal: signal,
2892
- temperature: 0.7,
2893
- ...(runtime.modelInfo?.supportsMaxOutputTokens === false ? {} : { maxOutputTokens: taskTypeToMaxTokens(pilCtx.taskType) }),
2894
- ...(Object.keys(providerOpts).length > 0 ? { providerOptions: providerOpts } : {}),
2895
- experimental_onStepStart: (event: unknown) => {
2896
- stepNumber = getStepNumber(event, stepNumber + 1);
2897
- notifyObserver(observer?.onStepStart, {
2898
- stepNumber,
2899
- timestamp: Date.now(),
2900
- });
2901
- },
2902
- onStepFinish: (event: unknown) => {
2903
- const currentStep = getStepNumber(event, Math.max(stepNumber, 0));
2904
- stepNumber = Math.max(stepNumber, currentStep);
2905
- const stepUsage = getUsage(event);
2906
- notifyObserver(observer?.onStepFinish, {
2907
- stepNumber: currentStep,
2908
- timestamp: Date.now(),
2909
- finishReason: getFinishReason(event),
2910
- usage: stepUsage,
2911
- });
2912
- // Realtime status bar update per step
2913
- if (stepUsage.inputTokens || stepUsage.outputTokens) {
2914
- this.recordUsage(stepUsage, "message", runtime.modelId);
2915
- }
2916
- },
2917
- onFinish: ({ providerMetadata }) => {
2918
- // Cache metrics only available in onFinish (Anthropic provider metadata)
2919
- const anthropicMeta = providerMetadata?.anthropic as Record<string, unknown> | undefined;
2920
- const cacheReadTokens = asNumber(anthropicMeta?.cacheReadInputTokens) ?? 0;
2921
- const cacheCreationTokens = asNumber(anthropicMeta?.cacheCreationInputTokens) ?? 0;
2922
- if (cacheReadTokens || cacheCreationTokens) {
2923
- const prev = statusBarStore.getState();
2924
- statusBarStore.setState({
2925
- cache_read_tokens: (prev.cache_read_tokens ?? 0) + cacheReadTokens,
2926
- cache_creation_tokens: (prev.cache_creation_tokens ?? 0) + cacheCreationTokens,
2927
- });
2928
- }
2929
- },
2930
- });
2931
-
2932
- for await (const part of result.fullStream) {
2933
- if (signal.aborted) {
2934
- yield { type: "content", content: "\n\n[Cancelled]" };
2935
- break;
2936
- }
2937
-
2938
- switch (part.type) {
2939
- case "text-delta":
2940
- assistantText += part.text;
2941
- yield { type: "content", content: part.text };
2942
- break;
2943
-
2944
- case "reasoning-delta":
2945
- reasoningPreview = `${reasoningPreview}${part.text}`.slice(-256);
2946
- if (containsEncryptedReasoning(reasoningPreview)) {
2947
- if (!encryptedReasoningHidden) {
2948
- encryptedReasoningHidden = true;
2949
- yield { type: "reasoning", content: "[Encrypted reasoning hidden]" };
2950
- }
2951
- break;
2952
- }
2953
- yield { type: "reasoning", content: part.text };
2954
- break;
2955
-
2956
- case "tool-call": {
2957
- const tc = toToolCall(part);
2958
- activeToolCalls.push(tc);
2959
-
2960
- // EE PreToolUse hook: fire intercept before tool execution.
2961
- {
2962
- const preInput: PreToolUseHookInput = {
2963
- hook_event_name: "PreToolUse",
2964
- tool_name: tc.function.name,
2965
- tool_input: JSON.parse(tc.function.arguments || "{}"),
2966
- session_id: this.session?.id,
2967
- cwd: this.bash.getCwd(),
2968
- };
2969
- const preResult = await this.fireHook(preInput, signal).catch(() => ({
2970
- blocked: false,
2971
- blockingErrors: [],
2972
- preventContinuation: false,
2973
- additionalContexts: [] as string[],
2974
- results: [],
2975
- }));
2976
- for (const ctx of preResult.additionalContexts ?? []) {
2977
- yield { type: "content", content: `${ctx}\n` };
2978
- }
2979
- }
2980
-
2981
- // Pitfall 9: log the pending call so reconcile() can recover any
2982
- // staged .tmp files if the process is killed before tool-result.
2983
- if (this.pendingCalls) {
2984
- const turnId = this.session?.id ?? "anon";
2985
- const callId = stableCallId(turnId, tc.function.name, tc.function.arguments);
2986
- // Phase 0: predictStagedPaths = [] for all tools (refined in Phase 1).
2987
- void this.pendingCalls.begin({ call_id: callId, tool_name: tc.function.name }).catch(() => {});
2988
- // Attach callId to the ToolCall so tool-result can end it.
2989
- (tc as ToolCall & { _pendingCallId?: string })._pendingCallId = callId;
2990
- }
2991
- notifyObserver(observer?.onToolStart, {
2992
- toolCall: tc,
2993
- timestamp: Date.now(),
2994
- });
2995
- yield { type: "tool_calls", toolCalls: [tc] };
2996
- break;
2997
- }
2998
-
2999
- case "tool-result": {
3000
- const tc: ToolCall = {
3001
- id: part.toolCallId,
3002
- type: "function",
3003
- function: { name: part.toolName, arguments: JSON.stringify(part.input ?? {}) },
3004
- };
3005
- const tr = toToolResult(part.output);
3006
- // Pitfall 9: settle the pending call log entry.
3007
- if (this.pendingCalls) {
3008
- const pending = activeToolCalls.find((t) => t.id === part.toolCallId);
3009
- const callId = (pending as ToolCall & { _pendingCallId?: string })?._pendingCallId;
3010
- if (callId) {
3011
- const endStatus = signal.aborted ? "aborted" : "settled";
3012
- void this.pendingCalls.end(callId, endStatus).catch(() => {});
3013
- }
3014
- }
3015
- // EE PostToolUse hook: fire-and-forget after tool execution.
3016
- {
3017
- const postInput: PostToolUseHookInput = {
3018
- hook_event_name: "PostToolUse",
3019
- tool_name: part.toolName,
3020
- tool_input: (part.input as Record<string, unknown>) ?? {},
3021
- tool_output: typeof tr.output === "string" ? { text: tr.output } : ((tr.output as unknown as Record<string, unknown>) ?? {}),
3022
- session_id: this.session?.id,
3023
- cwd: this.bash.getCwd(),
3024
- };
3025
- await this.fireHook(postInput, signal).catch(() => {});
3026
- }
3027
-
3028
- // Response tool: yield as structured_response instead of tool_result
3029
- if (isResponseTool(part.toolName)) {
3030
- responseToolCalled = true;
3031
- const taskType = getResponseTaskType(part.toolName);
3032
- yield {
3033
- type: "structured_response" as StreamChunk["type"],
3034
- structuredResponse: {
3035
- taskType: taskType ?? part.toolName,
3036
- data: (part.output ?? {}) as Record<string, unknown>,
3037
- },
3038
- };
3039
- notifyObserver(observer?.onToolFinish, { toolCall: tc, toolResult: tr, timestamp: Date.now() });
3040
- break;
3041
- }
3042
-
3043
- notifyObserver(observer?.onToolFinish, {
3044
- toolCall: tc,
3045
- toolResult: tr,
3046
- timestamp: Date.now(),
3047
- });
3048
- yield { type: "tool_result", toolCall: tc, toolResult: tr };
3049
- break;
3050
- }
3051
-
3052
- case "tool-approval-request": {
3053
- const approvalPart = part as unknown as {
3054
- approvalId: string;
3055
- toolCall: { toolCallId: string; toolName: string; input: unknown };
3056
- };
3057
- const toolCallId = approvalPart.toolCall?.toolCallId ?? "";
3058
- const pendingTc = activeToolCalls.find((tc) => tc.id === toolCallId);
3059
- const tcForChunk = pendingTc ?? {
3060
- id: toolCallId,
3061
- type: "function" as const,
3062
- function: {
3063
- name: approvalPart.toolCall?.toolName ?? "paid_request",
3064
- arguments: JSON.stringify(approvalPart.toolCall?.input ?? {}),
3065
- },
3066
- };
3067
-
3068
- // Payment pre-check disabled — Stripe billing pending.
3069
- const paymentPrecheck: import("../types/index").PaymentPrecheck | undefined = undefined;
3070
-
3071
- // Plan 03-01: check permission mode before yielding approval request to UI.
3072
- // auto-edit auto-approves file ops; yolo auto-approves everything.
3073
- const toolName = approvalPart.toolCall?.toolName ?? "";
3074
- if (!toolNeedsApproval(toolName, this.permissionMode)) {
3075
- // Auto-approve: respond directly without surfacing to UI.
3076
- this.respondToToolApproval(approvalPart.approvalId, true);
3077
- break;
3078
- }
3079
-
3080
- yield {
3081
- type: "tool_approval_request",
3082
- approvalId: approvalPart.approvalId,
3083
- toolCall: tcForChunk,
3084
- paymentPrecheck,
3085
- };
3086
- break;
3087
- }
3088
-
3089
- case "error": {
3090
- const authError = isAuthenticationError(part.error);
3091
- const friendly = humanizeApiError(part.error);
3092
- notifyObserver(observer?.onError, {
3093
- message: friendly,
3094
- timestamp: Date.now(),
3095
- });
3096
- yield {
3097
- type: "error",
3098
- content: friendly,
3099
- isAuthError: authError,
3100
- };
3101
- break;
3102
- }
3103
-
3104
- case "abort":
3105
- yield { type: "content", content: "\n\n[Cancelled]" };
3106
- break;
3107
- }
3108
- }
3109
-
3110
- if (signal.aborted) {
3111
- this.discardAbortedTurn(userModelMessage);
3112
- yield { type: "done" };
3113
- return;
3114
- }
3115
-
3116
- try {
3117
- const response = await result.response;
3118
- if (!signal.aborted) {
3119
- this.appendCompletedTurn(userModelMessage, sanitizeModelMessages(response.messages));
3120
- streamOk = true;
3121
- }
3122
- } catch (responseError: unknown) {
3123
- if (
3124
- !attemptedOverflowRecovery &&
3125
- !assistantText.trim() &&
3126
- modelInfo &&
3127
- isContextLimitError(responseError)
3128
- ) {
3129
- attemptedOverflowRecovery = true;
3130
- continue;
3131
- }
3132
- }
3133
-
3134
- if (signal.aborted) {
3135
- this.discardAbortedTurn(userModelMessage);
3136
- yield { type: "done" };
3137
- return;
3138
- }
3139
-
3140
- if (!streamOk && assistantText.trim()) {
3141
- this.appendCompletedTurn(userModelMessage, [{ role: "assistant", content: assistantText }]);
3142
- }
3143
-
3144
- // Fallback: model responded in text despite tool_choice=required
3145
- // Attempt JSON extraction from assistant text → yield as structured_response
3146
- if (_hasResponseTools && !responseToolCalled && pilCtx.taskType && assistantText.trim()) {
3147
- try {
3148
- const jsonMatch = assistantText.match(/\{[\s\S]*\}/);
3149
- if (jsonMatch) {
3150
- const parsed = JSON.parse(jsonMatch[0]) as Record<string, unknown>;
3151
- if (Object.keys(parsed).length > 0) {
3152
- responseToolCalled = true;
3153
- yield {
3154
- type: "structured_response" as StreamChunk["type"],
3155
- structuredResponse: {
3156
- taskType: pilCtx.taskType,
3157
- data: parsed,
3158
- },
3159
- };
3160
- }
3161
- }
3162
- } catch {
3163
- // JSON parse failed — leave as text-fallback
3164
- }
3165
- }
3166
-
3167
- // Track PIL output mode for /optimize metrics
3168
- {
3169
- const { setLastOutputMode } = await import("../pil/store.js");
3170
- if (!_hasResponseTools) setLastOutputMode("conversational");
3171
- else if (responseToolCalled) setLastOutputMode("structured");
3172
- else setLastOutputMode("text-fallback");
3173
- }
3174
-
3175
- // ROUTE-11: Fire routeFeedback after turn completes (success path).
3176
- // Must come AFTER posttool calls (posttool fires during tool-result processing above).
3177
- // Fire-and-forget — no await. Skipped when taskHash is null (bridge absent).
3178
- {
3179
- const turnDuration = Date.now() - turnStartMs;
3180
- if (taskHash) {
3181
- const tier = taskTypeToTier(pilCtx.taskType);
3182
- void routeFeedback(
3183
- taskHash,
3184
- tier,
3185
- runtime.modelId,
3186
- "success", // Phase 6: all normal completions = 'success'
3187
- 0, // retryCount: 0 for first attempt
3188
- turnDuration,
3189
- );
3190
- }
3191
- // HTTP path: also report via router store taskHash (covers warm/cold EE routes)
3192
- const storeHash = routerStore.getState().taskHash;
3193
- if (storeHash) {
3194
- reportRouteOutcome(storeHash, "success", turnDuration);
3195
- }
3196
- }
3197
-
3198
- const stopInput: StopHookInput = {
3199
- hook_event_name: "Stop",
3200
- session_id: this.session?.id,
3201
- cwd: this.bash.getCwd(),
3202
- };
3203
- await this.fireHook(stopInput, signal).catch(() => {});
3204
-
3205
- // Debug trace: emit pipeline summary
3206
- if (_debugOn) {
3207
- const sb = statusBarStore.getState();
3208
- const defaultInfo = getModelInfo(this.modelId);
3209
- const usedInfo = getModelInfo(turnModelId);
3210
- const routerSaved = (defaultInfo && usedInfo && defaultInfo.outputPrice > usedInfo.outputPrice)
3211
- ? (sb.out_tokens * (defaultInfo.outputPrice - usedInfo.outputPrice)) / 1_000_000
3212
- : 0;
3213
- const cacheSaved = sb.cache_read_tokens > 0 && defaultInfo
3214
- ? (sb.cache_read_tokens * (defaultInfo.inputPrice - (defaultInfo.cachedInputPrice ?? defaultInfo.inputPrice * 0.1))) / 1_000_000
3215
- : 0;
3216
- const trace: TurnTrace = {
3217
- turn_id: _debugTurnId,
3218
- timestamp: turnStartMs,
3219
- raw_prompt: userMessage,
3220
- steps: _debugSteps,
3221
- model_requested: this.modelId,
3222
- model_used: turnModelId,
3223
- routed: turnModelId !== this.modelId,
3224
- input_tokens: sb.in_tokens,
3225
- output_tokens: sb.out_tokens,
3226
- cache_read_tokens: sb.cache_read_tokens,
3227
- cost_usd: sb.session_usd,
3228
- estimated_savings: {
3229
- pil_tokens_saved: this._pilEnrichmentDelta > 0 ? this._pilEnrichmentDelta : 0,
3230
- cache_tokens_saved: sb.cache_read_tokens,
3231
- router_cost_saved_usd: routerSaved,
3232
- total_tokens_saved: (this._pilEnrichmentDelta > 0 ? this._pilEnrichmentDelta : 0) + sb.cache_read_tokens,
3233
- total_cost_saved_usd: routerSaved + cacheSaved,
3234
- },
3235
- };
3236
- recordTurnTrace(trace);
3237
-
3238
- const traceLines: string[] = [];
3239
- traceLines.push("\n┌─ Pipeline Trace ─────────────────────────");
3240
- for (const step of _debugSteps) {
3241
- const dur = step.duration_ms < 1 ? "<1ms" : `${step.duration_ms}ms`;
3242
- const saved = step.tokens_saved ? ` (saved ~${step.tokens_saved} tok)` : "";
3243
- traceLines.push(`│ ▸ ${step.name} [${dur}]${saved}`);
3244
- traceLines.push(`│ ${step.output_summary}`);
3245
- }
3246
- const routeLabel = trace.routed ? `${trace.model_requested}→${trace.model_used}` : trace.model_used;
3247
- traceLines.push(`│ Model: ${routeLabel} | ↑${sb.in_tokens} ↓${sb.out_tokens} | $${sb.session_usd.toFixed(4)}`);
3248
- if (trace.estimated_savings.total_cost_saved_usd > 0) {
3249
- traceLines.push(`│ Savings: ~${trace.estimated_savings.total_tokens_saved} tok, ~$${trace.estimated_savings.total_cost_saved_usd.toFixed(4)}`);
3250
- }
3251
- traceLines.push("└──────────────────────────────────────────\n");
3252
- yield { type: "content", content: traceLines.join("\n") };
3253
- }
3254
-
3255
- if (modelInfo?.contextWindow) {
3256
- await this.postTurnCompact(provider, system, modelInfo.contextWindow, signal);
3257
- }
3258
- yield { type: "done" };
3259
- return;
3260
- } catch (err: unknown) {
3261
- if (signal.aborted) {
3262
- this.discardAbortedTurn(userModelMessage);
3263
- // ROUTE-11: Fire routeFeedback for cancelled turns (abort path).
3264
- // Fire-and-forget — no await. Skipped when taskHash is null.
3265
- {
3266
- const turnDuration = Date.now() - turnStartMs;
3267
- if (taskHash) {
3268
- const tier = taskTypeToTier(pilCtx.taskType);
3269
- void routeFeedback(
3270
- taskHash,
3271
- tier,
3272
- runtime.modelId,
3273
- "cancelled",
3274
- 0,
3275
- turnDuration,
3276
- );
3277
- }
3278
- const storeHash = routerStore.getState().taskHash;
3279
- if (storeHash) {
3280
- reportRouteOutcome(storeHash, "cancelled", turnDuration);
3281
- }
3282
- }
3283
- yield { type: "content", content: "\n\n[Cancelled]" };
3284
- yield { type: "done" };
3285
- return;
3286
- }
3287
-
3288
- if (!attemptedOverflowRecovery && !assistantText.trim() && modelInfo && isContextLimitError(err)) {
3289
- attemptedOverflowRecovery = true;
3290
- continue;
3291
- }
3292
-
3293
- const authError = isAuthenticationError(err);
3294
- const friendly = humanizeApiError(err);
3295
- notifyObserver(observer?.onError, {
3296
- message: friendly,
3297
- timestamp: Date.now(),
3298
- });
3299
- yield {
3300
- type: "error",
3301
- content: friendly,
3302
- isAuthError: authError,
3303
- };
3304
- if (assistantText.trim()) {
3305
- this.appendCompletedTurn(userModelMessage, [{ role: "assistant", content: assistantText }]);
3306
- }
3307
-
3308
- // ROUTE-11: Fire routeFeedback for failed turns (error path).
3309
- // Must come AFTER posttool calls. Fire-and-forget — no await.
3310
- {
3311
- const turnDuration = Date.now() - turnStartMs;
3312
- if (taskHash) {
3313
- const tier = taskTypeToTier(pilCtx.taskType);
3314
- void routeFeedback(
3315
- taskHash,
3316
- tier,
3317
- runtime.modelId,
3318
- "fail",
3319
- 0,
3320
- turnDuration,
3321
- );
3322
- }
3323
- const storeHash = routerStore.getState().taskHash;
3324
- if (storeHash) {
3325
- reportRouteOutcome(storeHash, "fail", turnDuration);
3326
- }
3327
- }
3328
-
3329
- const stopFailureInput: StopFailureHookInput = {
3330
- hook_event_name: "StopFailure",
3331
- error: friendly,
3332
- session_id: this.session?.id,
3333
- cwd: this.bash.getCwd(),
3334
- };
3335
- await this.fireHook(stopFailureInput, signal).catch(() => {});
3336
-
3337
- if (modelInfo?.contextWindow) {
3338
- await this.postTurnCompact(provider, system, modelInfo.contextWindow, signal);
3339
- }
3340
- yield { type: "done" };
3341
- return;
3342
- } finally {
3343
- await closeMcp?.().catch(() => {});
3344
- }
3345
- }
3346
- } finally {
3347
- if (this.abortController?.signal === signal) {
3348
- this.abortController = null;
3349
- }
3350
- }
3351
- }
3352
-
3353
- private _buildRecentTurnsSummary(): string | null {
3354
- if (this.messages.length < 2) return null;
3355
- const recent = this.messages.slice(-6);
3356
- const parts: string[] = [];
3357
- for (const msg of recent) {
3358
- if (msg.role !== "user" && msg.role !== "assistant") continue;
3359
- const text = typeof msg.content === "string"
3360
- ? msg.content
3361
- : Array.isArray(msg.content)
3362
- ? msg.content.filter((p: { type: string }) => p.type === "text").map((p: { type: string; text?: string }) => p.text ?? "").join("")
3363
- : "";
3364
- if (!text) continue;
3365
- const snippet = text.length > 80 ? `${text.slice(0, 77)}...` : text;
3366
- parts.push(`[${msg.role}]: ${snippet}`);
3367
- }
3368
- return parts.length > 0 ? parts.join(" | ") : null;
3369
- }
3370
-
3371
- private _estimateProjectSize(): "small" | "medium" | "large" | null {
2511
+ private _estimateProjectSize(): "small" | "medium" | "large" | null {
3372
2512
  try {
3373
2513
  const fs = require("fs");
3374
2514
  const path = require("path");
@@ -3415,6 +2555,45 @@ export class Agent {
3415
2555
  return this.provider;
3416
2556
  }
3417
2557
 
2558
+ /**
2559
+ * One-shot async init: upgrades the OpenAI provider to use OAuth tokens when
2560
+ * stored tokens are available and no explicit API key was supplied by the user.
2561
+ * Called at the start of processMessage so the first real LLM call benefits
2562
+ * from OAuth without requiring a sync constructor change.
2563
+ *
2564
+ * Idempotent: skips on second call and for non-OpenAI providers.
2565
+ * Fail-open: any error leaves the existing provider untouched.
2566
+ */
2567
+ private async _initOAuthProvider(): Promise<void> {
2568
+ if (this._oauthInitDone) return;
2569
+ this._oauthInitDone = true;
2570
+
2571
+ // Only upgrade when there is no explicit API key — OAuth is an alternative
2572
+ // auth path, not an override when the user deliberately passed a key.
2573
+ // The boot wizard in src/index.ts uses the literal "oauth" as a sentinel
2574
+ // to signal "no API key but OAuth tokens exist", so treat that as "no
2575
+ // key" here.
2576
+ if (this.apiKey && this.apiKey !== "oauth") return;
2577
+
2578
+ try {
2579
+ const { listOAuthProviderIds } = await import("../providers/auth/registry.js");
2580
+ const ids = await listOAuthProviderIds();
2581
+ if (!ids.includes(this.providerId)) return;
2582
+
2583
+ const effectiveBaseURL =
2584
+ this.baseURL &&
2585
+ this.baseURL !== (await import("../providers/endpoints.js").then((m) => m.apiBaseFor("anthropic")))
2586
+ ? this.baseURL
2587
+ : undefined;
2588
+ const result = await createProviderFactoryAsync(this.providerId, {
2589
+ baseURL: effectiveBaseURL ?? undefined,
2590
+ });
2591
+ this.provider = result.factory;
2592
+ } catch {
2593
+ // Fail-open — provider remains null; requireProvider() will surface the error
2594
+ }
2595
+ }
2596
+
3418
2597
  async detectVerifyRecipe(settings?: SandboxSettings, abortSignal?: AbortSignal): Promise<VerifyRecipe | null> {
3419
2598
  try {
3420
2599
  const result = await this.runTaskRequest(
@@ -3460,531 +2639,3 @@ export class Agent {
3460
2639
  }
3461
2640
  }
3462
2641
  }
3463
-
3464
- interface ExecutedBatchTool {
3465
- toolCall: ToolCall;
3466
- input: unknown;
3467
- toolResult: ToolResult;
3468
- }
3469
-
3470
- type JsonValue = string | number | boolean | null | JsonValue[] | { [key: string]: JsonValue };
3471
-
3472
- function extractJsonObject(text: string): string | null {
3473
- const start = text.indexOf("{");
3474
- const end = text.lastIndexOf("}");
3475
- if (start < 0 || end < start) return null;
3476
- return text.slice(start, end + 1);
3477
- }
3478
-
3479
- function buildBatchName(prefix: string, label: string): string {
3480
- const compact =
3481
- label
3482
- .replace(/\s+/g, "-")
3483
- .replace(/[^a-zA-Z0-9._-]+/g, "")
3484
- .slice(0, 48) || "run";
3485
- return `muonroi-cli-${prefix}-${compact}`;
3486
- }
3487
-
3488
- function buildBatchChatCompletionRequest(args: {
3489
- modelId: string;
3490
- system: string;
3491
- messages: ModelMessage[];
3492
- temperature: number;
3493
- maxOutputTokens?: number;
3494
- reasoningEffort?: BatchChatCompletionRequest["reasoning_effort"];
3495
- tools: BatchFunctionTool[];
3496
- }): BatchChatCompletionRequest {
3497
- return {
3498
- model: args.modelId,
3499
- messages: toBatchChatMessages(args.system, args.messages),
3500
- temperature: args.temperature,
3501
- ...(args.maxOutputTokens != null ? { max_completion_tokens: args.maxOutputTokens } : {}),
3502
- ...(args.reasoningEffort ? { reasoning_effort: args.reasoningEffort } : {}),
3503
- ...(args.tools.length > 0 ? { tools: args.tools } : {}),
3504
- };
3505
- }
3506
-
3507
- function toBatchChatMessages(system: string, messages: ModelMessage[]): BatchChatMessage[] {
3508
- const batchMessages: BatchChatMessage[] = [{ role: "system", content: system }];
3509
-
3510
- for (const message of messages) {
3511
- const { role, content } = message;
3512
-
3513
- switch (role) {
3514
- case "system":
3515
- batchMessages.push({ role: "system", content });
3516
- break;
3517
-
3518
- case "user": {
3519
- if (typeof content === "string") {
3520
- batchMessages.push({ role: "user", content });
3521
- break;
3522
- }
3523
-
3524
- if (!Array.isArray(content)) {
3525
- break;
3526
- }
3527
-
3528
- if (content.length === 1 && content[0]?.type === "text") {
3529
- batchMessages.push({ role: "user", content: content[0].text });
3530
- break;
3531
- }
3532
-
3533
- const userContent: Array<{ type: "text"; text: string } | { type: "image_url"; image_url: { url: string } }> =
3534
- [];
3535
- for (const part of content) {
3536
- switch (part.type) {
3537
- case "text":
3538
- userContent.push({ type: "text", text: part.text });
3539
- break;
3540
-
3541
- case "image": {
3542
- const mediaType = part.mediaType === "image/*" || !part.mediaType ? "image/jpeg" : part.mediaType;
3543
- const data =
3544
- part.image instanceof URL
3545
- ? part.image.toString()
3546
- : `data:${mediaType};base64,${toBase64DataContent(part.image)}`;
3547
- userContent.push({ type: "image_url", image_url: { url: data } });
3548
- break;
3549
- }
3550
-
3551
- case "file": {
3552
- if (!part.mediaType.startsWith("image/")) {
3553
- break;
3554
- }
3555
- const mediaType = part.mediaType === "image/*" ? "image/jpeg" : part.mediaType;
3556
- const data =
3557
- part.data instanceof URL
3558
- ? part.data.toString()
3559
- : `data:${mediaType};base64,${toBase64DataContent(part.data)}`;
3560
- userContent.push({ type: "image_url", image_url: { url: data } });
3561
- break;
3562
- }
3563
- }
3564
- }
3565
- batchMessages.push({
3566
- role: "user",
3567
- content: userContent,
3568
- });
3569
- break;
3570
- }
3571
-
3572
- case "assistant": {
3573
- if (typeof content === "string") {
3574
- batchMessages.push({ role: "assistant", content });
3575
- break;
3576
- }
3577
-
3578
- if (!Array.isArray(content)) {
3579
- break;
3580
- }
3581
-
3582
- let assistantText = "";
3583
- const toolCalls: BatchToolCall[] = [];
3584
- for (const part of content) {
3585
- if (part.type === "text") {
3586
- assistantText += part.text;
3587
- } else if (part.type === "tool-call") {
3588
- toolCalls.push({
3589
- id: part.toolCallId,
3590
- type: "function",
3591
- function: {
3592
- name: part.toolName,
3593
- arguments: JSON.stringify(part.input),
3594
- },
3595
- });
3596
- }
3597
- }
3598
-
3599
- if (assistantText || toolCalls.length > 0) {
3600
- batchMessages.push({
3601
- role: "assistant",
3602
- content: assistantText,
3603
- ...(toolCalls.length > 0 ? { tool_calls: toolCalls } : {}),
3604
- });
3605
- }
3606
- break;
3607
- }
3608
-
3609
- case "tool":
3610
- for (const part of content) {
3611
- if (part.type === "tool-approval-response") {
3612
- continue;
3613
- }
3614
- batchMessages.push({
3615
- role: "tool",
3616
- tool_call_id: part.toolCallId,
3617
- content: toolOutputToText(part.output),
3618
- });
3619
- }
3620
- break;
3621
- }
3622
- }
3623
-
3624
- return batchMessages;
3625
- }
3626
-
3627
- function toBase64DataContent(value: string | Uint8Array | ArrayBuffer): string {
3628
- return convertToBase64(value instanceof ArrayBuffer ? new Uint8Array(value) : value);
3629
- }
3630
-
3631
- function toolOutputToText(output: {
3632
- type: "text" | "json" | "execution-denied" | "error-text" | "error-json" | "content";
3633
- value?: unknown;
3634
- reason?: string;
3635
- }): string {
3636
- switch (output.type) {
3637
- case "text":
3638
- case "error-text":
3639
- return String(output.value ?? "");
3640
- case "execution-denied":
3641
- return output.reason ?? "Tool execution denied.";
3642
- case "json":
3643
- case "error-json":
3644
- case "content":
3645
- return JSON.stringify(output.value ?? null);
3646
- }
3647
- }
3648
-
3649
- function getBatchUsage(response: BatchChatCompletionResponse): ProcessMessageUsage {
3650
- const usage = response.usage as BatchChatCompletionResponse["usage"] | undefined;
3651
- const inputTokens = asNumber(usage?.input_tokens) ?? asNumber(usage?.prompt_tokens);
3652
- const outputTokens = asNumber(usage?.output_tokens) ?? asNumber(usage?.completion_tokens);
3653
- const totalTokens = asNumber(usage?.total_tokens) ?? sumDefined(inputTokens, outputTokens);
3654
- const u = usage as Record<string, unknown> | undefined;
3655
- return {
3656
- inputTokens,
3657
- outputTokens,
3658
- totalTokens,
3659
- costUsdTicks: asNumber(usage?.cost_in_usd_ticks),
3660
- cacheReadTokens: asNumber(u?.cache_read_input_tokens),
3661
- cacheCreationTokens: asNumber(u?.cache_creation_input_tokens),
3662
- };
3663
- }
3664
-
3665
- function accumulateUsage(target: ProcessMessageUsage, usage: ProcessMessageUsage): void {
3666
- target.inputTokens = (target.inputTokens ?? 0) + (usage.inputTokens ?? 0);
3667
- target.outputTokens = (target.outputTokens ?? 0) + (usage.outputTokens ?? 0);
3668
- target.totalTokens = (target.totalTokens ?? 0) + (usage.totalTokens ?? 0);
3669
- target.costUsdTicks = (target.costUsdTicks ?? 0) + (usage.costUsdTicks ?? 0);
3670
- target.cacheReadTokens = (target.cacheReadTokens ?? 0) + (usage.cacheReadTokens ?? 0);
3671
- target.cacheCreationTokens = (target.cacheCreationTokens ?? 0) + (usage.cacheCreationTokens ?? 0);
3672
- }
3673
-
3674
- function hasUsage(usage: ProcessMessageUsage): boolean {
3675
- return Boolean(
3676
- (usage.inputTokens ?? 0) || (usage.outputTokens ?? 0) || (usage.totalTokens ?? 0) || (usage.costUsdTicks ?? 0),
3677
- );
3678
- }
3679
-
3680
- function getBatchFinishReason(finishReason: string | null | undefined): ProcessMessageFinishReason {
3681
- switch (finishReason) {
3682
- case "stop":
3683
- case "length":
3684
- case "content-filter":
3685
- case "tool-calls":
3686
- case "error":
3687
- case "other":
3688
- return finishReason;
3689
- case "tool_calls":
3690
- return "tool-calls";
3691
- default:
3692
- return "other";
3693
- }
3694
- }
3695
-
3696
- function toLocalToolCall(toolCall: BatchToolCall): ToolCall {
3697
- return {
3698
- id: toolCall.id,
3699
- type: "function",
3700
- function: {
3701
- name: toolCall.function.name,
3702
- arguments: toolCall.function.arguments,
3703
- },
3704
- };
3705
- }
3706
-
3707
- function buildAssistantBatchMessage(content: string, toolCalls: ToolCall[]): ModelMessage | null {
3708
- if (toolCalls.length === 0) {
3709
- return content ? { role: "assistant", content } : null;
3710
- }
3711
-
3712
- const parts: Array<
3713
- { type: "text"; text: string } | { type: "tool-call"; toolCallId: string; toolName: string; input: unknown }
3714
- > = [];
3715
- if (content) {
3716
- parts.push({ type: "text", text: content });
3717
- }
3718
- for (const toolCall of toolCalls) {
3719
- parts.push({
3720
- type: "tool-call",
3721
- toolCallId: toolCall.id,
3722
- toolName: toolCall.function.name,
3723
- input: parseToolArgumentsOrRaw(toolCall.function.arguments),
3724
- });
3725
- }
3726
- return { role: "assistant", content: parts };
3727
- }
3728
-
3729
- function buildToolBatchMessage(toolParts: ExecutedBatchTool[]): ModelMessage | null {
3730
- if (toolParts.length === 0) {
3731
- return null;
3732
- }
3733
-
3734
- return {
3735
- role: "tool",
3736
- content: toolParts.map((part) => ({
3737
- type: "tool-result" as const,
3738
- toolCallId: part.toolCall.id,
3739
- toolName: part.toolCall.function.name,
3740
- output: part.toolResult.success
3741
- ? ({ type: "json", value: toSerializableValue(part.toolResult) } as const)
3742
- : ({ type: "error-json", value: toSerializableValue(part.toolResult) } as const),
3743
- })),
3744
- };
3745
- }
3746
-
3747
- function parseToolArgumentsOrRaw(raw: string): unknown {
3748
- try {
3749
- return raw.trim() ? JSON.parse(raw) : {};
3750
- } catch {
3751
- return raw;
3752
- }
3753
- }
3754
-
3755
- function toSerializableValue(value: unknown): JsonValue {
3756
- try {
3757
- return JSON.parse(JSON.stringify(value ?? null)) as JsonValue;
3758
- } catch {
3759
- return String(value);
3760
- }
3761
- }
3762
-
3763
- function asNumber(value: unknown): number | undefined {
3764
- return typeof value === "number" ? value : undefined;
3765
- }
3766
-
3767
- function sumDefined(left?: number, right?: number): number | undefined {
3768
- if (left == null && right == null) {
3769
- return undefined;
3770
- }
3771
- return (left ?? 0) + (right ?? 0);
3772
- }
3773
-
3774
- function toToolCall(part: { toolCallId: string; toolName: string; args?: unknown; input?: unknown }): ToolCall {
3775
- return {
3776
- id: part.toolCallId,
3777
- type: "function",
3778
- function: {
3779
- name: part.toolName,
3780
- arguments: JSON.stringify(part.input ?? part.args ?? {}),
3781
- },
3782
- };
3783
- }
3784
-
3785
- function notifyObserver<T>(listener: ((payload: T) => void) | undefined, payload: T): void {
3786
- if (!listener) {
3787
- return;
3788
- }
3789
-
3790
- try {
3791
- listener(payload);
3792
- } catch {
3793
- // Observer failures should never break generation.
3794
- }
3795
- }
3796
-
3797
- function getStepNumber(event: unknown, fallback: number): number {
3798
- if (event && typeof event === "object" && "stepNumber" in event && typeof event.stepNumber === "number") {
3799
- return event.stepNumber;
3800
- }
3801
-
3802
- return fallback;
3803
- }
3804
-
3805
- function getFinishReason(event: unknown): ProcessMessageFinishReason {
3806
- if (event && typeof event === "object" && "finishReason" in event) {
3807
- switch (event.finishReason) {
3808
- case "stop":
3809
- case "length":
3810
- case "content-filter":
3811
- case "tool-calls":
3812
- case "error":
3813
- case "other":
3814
- return event.finishReason;
3815
- }
3816
- }
3817
-
3818
- return "other";
3819
- }
3820
-
3821
- function getUsage(event: unknown): ProcessMessageUsage {
3822
- if (!(event && typeof event === "object" && "usage" in event)) {
3823
- return {};
3824
- }
3825
-
3826
- const usage = event.usage;
3827
- if (!usage || typeof usage !== "object") {
3828
- return {};
3829
- }
3830
-
3831
- const u = usage as Record<string, unknown>;
3832
- return {
3833
- inputTokens: typeof u.inputTokens === "number" ? u.inputTokens : undefined,
3834
- outputTokens: typeof u.outputTokens === "number" ? u.outputTokens : undefined,
3835
- totalTokens: typeof u.totalTokens === "number" ? u.totalTokens : undefined,
3836
- cacheReadTokens: typeof u.cacheReadTokens === "number" ? u.cacheReadTokens : undefined,
3837
- cacheCreationTokens: typeof u.cacheCreationTokens === "number" ? u.cacheCreationTokens : undefined,
3838
- };
3839
- }
3840
-
3841
- function toToolResult(output: unknown): ToolResult {
3842
- if (output && typeof output === "object" && "success" in output) {
3843
- const r = output as {
3844
- success: boolean;
3845
- output?: string;
3846
- error?: string;
3847
- diff?: ToolResult["diff"];
3848
- plan?: Plan;
3849
- task?: ToolResult["task"];
3850
- delegation?: ToolResult["delegation"];
3851
- backgroundProcess?: ToolResult["backgroundProcess"];
3852
- media?: ToolResult["media"];
3853
- computer?: ToolResult["computer"];
3854
- lspDiagnostics?: ToolResult["lspDiagnostics"];
3855
- };
3856
- return {
3857
- success: r.success,
3858
- output: r.output,
3859
- error: r.error ?? (r.success ? undefined : r.output),
3860
- diff: r.diff,
3861
- plan: r.plan,
3862
- task: r.task,
3863
- delegation: r.delegation,
3864
- backgroundProcess: r.backgroundProcess,
3865
- media: r.media,
3866
- computer: r.computer,
3867
- lspDiagnostics: r.lspDiagnostics,
3868
- };
3869
- }
3870
- return { success: true, output: String(output) };
3871
- }
3872
-
3873
- function formatSubagentActivity(toolName: string, args?: unknown): string {
3874
- const parsed = parseToolArgs(args);
3875
- if (toolName === "read_file") return `Read ${parsed.path || "file"}`;
3876
- if (toolName === "lsp") return `LSP ${parsed.operation || "query"} ${parsed.filePath || ""}`.trim();
3877
- if (toolName === "write_file") return `Write ${parsed.path || "file"}`;
3878
- if (toolName === "edit_file") return `Edit ${parsed.path || "file"}`;
3879
- if (toolName === "search_web") return `Web search "${truncate(parsed.query || "", 50)}"`;
3880
- if (toolName === "search_x") return `X search "${truncate(parsed.query || "", 50)}"`;
3881
- if (toolName === "generate_image") return `Generate image "${truncate(parsed.prompt || "", 50)}"`;
3882
- if (toolName === "generate_video") return `Generate video "${truncate(parsed.prompt || "", 50)}"`;
3883
- if (toolName === "computer_snapshot") return `Snapshot ${parsed.app || "desktop"}`;
3884
- if (toolName === "computer_screenshot") return "Capture desktop screenshot";
3885
- if (toolName === "computer_click")
3886
- return parsed.ref ? `Click ${parsed.ref}` : `Click at ${parsed.x || "?"},${parsed.y || "?"}`;
3887
- if (toolName === "computer_mouse_move")
3888
- return parsed.ref ? `Hover ${parsed.ref}` : `Move mouse to ${parsed.x || "?"},${parsed.y || "?"}`;
3889
- if (toolName === "computer_type") return `Type into ${parsed.ref || "element"}`;
3890
- if (toolName === "computer_press") return `Press ${parsed.key || "key"}`;
3891
- if (toolName === "computer_scroll") return `Scroll ${parsed.ref || "element"} ${parsed.direction || "down"}`;
3892
- if (toolName === "computer_launch") return `Launch ${parsed.app || "app"}`;
3893
- if (toolName === "computer_list_windows") return `List windows${parsed.app ? ` for ${parsed.app}` : ""}`;
3894
- if (toolName === "computer_focus_window")
3895
- return `Focus window ${parsed.window_id || parsed.title || parsed.app || ""}`.trim();
3896
- if (toolName === "computer_wait") return "Wait for desktop state";
3897
- if (toolName === "computer_get") return `Read ${parsed.property || "text"} from ${parsed.ref || "element"}`;
3898
- if (toolName === "bash") return truncate(parsed.command || "Run command", 70);
3899
- return truncate(`${toolName}`, 70);
3900
- }
3901
-
3902
- function parseToolArgs(args: unknown): Record<string, string> {
3903
- if (!args || typeof args !== "object") return {};
3904
- const result: Record<string, string> = {};
3905
- for (const [key, value] of Object.entries(args)) {
3906
- result[key] = typeof value === "string" ? value : JSON.stringify(value);
3907
- }
3908
- return result;
3909
- }
3910
-
3911
- function firstLine(text: string): string {
3912
- return text.trim().split("\n").find(Boolean)?.trim() || "Task completed.";
3913
- }
3914
-
3915
- function truncate(text: string, max: number): string {
3916
- return text.length <= max ? text : `${text.slice(0, max - 1)}…`;
3917
- }
3918
-
3919
- function combineAbortSignals(...signals: Array<AbortSignal | undefined>): AbortSignal | undefined {
3920
- const activeSignals = signals.filter((signal): signal is AbortSignal => Boolean(signal));
3921
- if (activeSignals.length === 0) return undefined;
3922
- if (activeSignals.length === 1) return activeSignals[0];
3923
-
3924
- if (typeof AbortSignal.any === "function") {
3925
- return AbortSignal.any(activeSignals);
3926
- }
3927
-
3928
- const controller = new AbortController();
3929
- for (const signal of activeSignals) {
3930
- if (signal.aborted) {
3931
- controller.abort();
3932
- break;
3933
- }
3934
-
3935
- signal.addEventListener("abort", () => controller.abort(), { once: true });
3936
- }
3937
-
3938
- return controller.signal;
3939
- }
3940
-
3941
- function isContextLimitError(error: unknown): boolean {
3942
- const message = error instanceof Error ? error.message : String(error);
3943
- return /(context|token|prompt).*(limit|length|large|window|overflow)|too many tokens|maximum context/i.test(message);
3944
- }
3945
-
3946
- function isAuthenticationError(error: unknown): boolean {
3947
- const message = error instanceof Error ? error.message : String(error);
3948
- return /\b(401|403)\b|unauthori[sz]ed|invalid.*(api[_ ]?key|token|credential)|authentication failed|forbidden|access denied/i.test(
3949
- message,
3950
- );
3951
- }
3952
-
3953
- const STATUS_MESSAGES: Record<number, string> = {
3954
- 400: "The request was invalid. This may be caused by an unsupported parameter or model.",
3955
- 401: "Authentication failed. Your API key may be invalid or expired.",
3956
- 403: "Access denied. Your API key does not have permission for this request.",
3957
- 404: "The requested model or endpoint was not found. Check your model name and base URL.",
3958
- 408: "The request timed out. Please try again.",
3959
- 422: "The request could not be processed. Check your message format or parameters.",
3960
- 429: "Rate limit exceeded. Please wait a moment and try again.",
3961
- 500: "The API server encountered an internal error. Please try again later.",
3962
- 502: "The API server is temporarily unavailable. Please try again later.",
3963
- 503: "The API service is temporarily overloaded. Please try again later.",
3964
- 529: "The API service is overloaded. Please try again later.",
3965
- };
3966
-
3967
- function humanizeApiError(error: unknown): string {
3968
- if (APICallError.isInstance(error)) {
3969
- const detail = extractResponseDetail(error.responseBody);
3970
- if (detail) return detail;
3971
- if (error.statusCode && STATUS_MESSAGES[error.statusCode]) {
3972
- return STATUS_MESSAGES[error.statusCode];
3973
- }
3974
- }
3975
-
3976
- const raw = error instanceof Error ? error.message : String(error);
3977
- return raw.replace(/^AI_\w+Error:\s*/i, "").trim() || raw;
3978
- }
3979
-
3980
- function extractResponseDetail(body: string | undefined): string | null {
3981
- if (!body) return null;
3982
- try {
3983
- const parsed = JSON.parse(body);
3984
- const msg = parsed?.error?.message ?? parsed?.message ?? parsed?.detail;
3985
- if (typeof msg === "string" && msg.trim()) return msg.trim();
3986
- } catch {
3987
- /* not JSON */
3988
- }
3989
- return null;
3990
- }