@hansjm10/volt-coding-agent 0.0.0-bootstrap.0 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (1364) hide show
  1. package/BINARY-CAPABILITIES.md +28 -0
  2. package/CHANGELOG.md +4845 -0
  3. package/LICENSE +1 -1
  4. package/README.md +716 -3
  5. package/THIRD-PARTY-NOTICES.md +55 -0
  6. package/dist/LICENSES/clipboard-image-MIT.txt +9 -0
  7. package/dist/LICENSES/highlight.js-10.7.3-BSD-3-Clause.txt +29 -0
  8. package/dist/LICENSES/highlight.js-11.9.0-BSD-3-Clause.txt +29 -0
  9. package/dist/LICENSES/marked-18.0.5-LICENSE.txt +44 -0
  10. package/dist/LICENSES/run-jxa-MIT.txt +9 -0
  11. package/dist/cli/args.d.ts +60 -0
  12. package/dist/cli/args.d.ts.map +1 -0
  13. package/dist/cli/args.js +414 -0
  14. package/dist/cli/args.js.map +1 -0
  15. package/dist/cli/config-selector.d.ts +14 -0
  16. package/dist/cli/config-selector.d.ts.map +1 -0
  17. package/dist/cli/config-selector.js +31 -0
  18. package/dist/cli/config-selector.js.map +1 -0
  19. package/dist/cli/file-processor.d.ts +15 -0
  20. package/dist/cli/file-processor.d.ts.map +1 -0
  21. package/dist/cli/file-processor.js +85 -0
  22. package/dist/cli/file-processor.js.map +1 -0
  23. package/dist/cli/initial-message.d.ts +18 -0
  24. package/dist/cli/initial-message.d.ts.map +1 -0
  25. package/dist/cli/initial-message.js +22 -0
  26. package/dist/cli/initial-message.js.map +1 -0
  27. package/dist/cli/list-models.d.ts +9 -0
  28. package/dist/cli/list-models.d.ts.map +1 -0
  29. package/dist/cli/list-models.js +98 -0
  30. package/dist/cli/list-models.js.map +1 -0
  31. package/dist/cli/project-trust.d.ts +10 -0
  32. package/dist/cli/project-trust.d.ts.map +1 -0
  33. package/dist/cli/project-trust.js +48 -0
  34. package/dist/cli/project-trust.js.map +1 -0
  35. package/dist/cli/session-picker.d.ts +9 -0
  36. package/dist/cli/session-picker.d.ts.map +1 -0
  37. package/dist/cli/session-picker.js +35 -0
  38. package/dist/cli/session-picker.js.map +1 -0
  39. package/dist/cli/startup-ui.d.ts +17 -0
  40. package/dist/cli/startup-ui.d.ts.map +1 -0
  41. package/dist/cli/startup-ui.js +133 -0
  42. package/dist/cli/startup-ui.js.map +1 -0
  43. package/dist/cli.d.ts +3 -0
  44. package/dist/cli.d.ts.map +1 -0
  45. package/dist/cli.js +18 -0
  46. package/dist/cli.js.map +1 -0
  47. package/dist/config.d.ts +85 -0
  48. package/dist/config.d.ts.map +1 -0
  49. package/dist/config.js +487 -0
  50. package/dist/config.js.map +1 -0
  51. package/dist/core/agent-session-runtime.d.ts +160 -0
  52. package/dist/core/agent-session-runtime.d.ts.map +1 -0
  53. package/dist/core/agent-session-runtime.js +397 -0
  54. package/dist/core/agent-session-runtime.js.map +1 -0
  55. package/dist/core/agent-session-services.d.ts +98 -0
  56. package/dist/core/agent-session-services.d.ts.map +1 -0
  57. package/dist/core/agent-session-services.js +125 -0
  58. package/dist/core/agent-session-services.js.map +1 -0
  59. package/dist/core/agent-session.d.ts +739 -0
  60. package/dist/core/agent-session.d.ts.map +1 -0
  61. package/dist/core/agent-session.js +3158 -0
  62. package/dist/core/agent-session.js.map +1 -0
  63. package/dist/core/auth-guidance.d.ts +5 -0
  64. package/dist/core/auth-guidance.d.ts.map +1 -0
  65. package/dist/core/auth-guidance.js +21 -0
  66. package/dist/core/auth-guidance.js.map +1 -0
  67. package/dist/core/auth-storage.d.ts +159 -0
  68. package/dist/core/auth-storage.d.ts.map +1 -0
  69. package/dist/core/auth-storage.js +509 -0
  70. package/dist/core/auth-storage.js.map +1 -0
  71. package/dist/core/bash-executor.d.ts +32 -0
  72. package/dist/core/bash-executor.d.ts.map +1 -0
  73. package/dist/core/bash-executor.js +111 -0
  74. package/dist/core/bash-executor.js.map +1 -0
  75. package/dist/core/compaction/branch-summarization.d.ts +92 -0
  76. package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
  77. package/dist/core/compaction/branch-summarization.js +257 -0
  78. package/dist/core/compaction/branch-summarization.js.map +1 -0
  79. package/dist/core/compaction/compaction.d.ts +121 -0
  80. package/dist/core/compaction/compaction.d.ts.map +1 -0
  81. package/dist/core/compaction/compaction.js +658 -0
  82. package/dist/core/compaction/compaction.js.map +1 -0
  83. package/dist/core/compaction/index.d.ts +7 -0
  84. package/dist/core/compaction/index.d.ts.map +1 -0
  85. package/dist/core/compaction/index.js +7 -0
  86. package/dist/core/compaction/index.js.map +1 -0
  87. package/dist/core/compaction/utils.d.ts +56 -0
  88. package/dist/core/compaction/utils.d.ts.map +1 -0
  89. package/dist/core/compaction/utils.js +271 -0
  90. package/dist/core/compaction/utils.js.map +1 -0
  91. package/dist/core/defaults.d.ts +3 -0
  92. package/dist/core/defaults.d.ts.map +1 -0
  93. package/dist/core/defaults.js +2 -0
  94. package/dist/core/defaults.js.map +1 -0
  95. package/dist/core/diagnostics.d.ts +15 -0
  96. package/dist/core/diagnostics.d.ts.map +1 -0
  97. package/dist/core/diagnostics.js +2 -0
  98. package/dist/core/diagnostics.js.map +1 -0
  99. package/dist/core/event-bus.d.ts +9 -0
  100. package/dist/core/event-bus.d.ts.map +1 -0
  101. package/dist/core/event-bus.js +25 -0
  102. package/dist/core/event-bus.js.map +1 -0
  103. package/dist/core/exec.d.ts +29 -0
  104. package/dist/core/exec.d.ts.map +1 -0
  105. package/dist/core/exec.js +75 -0
  106. package/dist/core/exec.js.map +1 -0
  107. package/dist/core/experimental.d.ts +2 -0
  108. package/dist/core/experimental.d.ts.map +1 -0
  109. package/dist/core/experimental.js +4 -0
  110. package/dist/core/experimental.js.map +1 -0
  111. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  112. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  113. package/dist/core/export-html/ansi-to-html.js +249 -0
  114. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  115. package/dist/core/export-html/index.d.ts +37 -0
  116. package/dist/core/export-html/index.d.ts.map +1 -0
  117. package/dist/core/export-html/index.js +234 -0
  118. package/dist/core/export-html/index.js.map +1 -0
  119. package/dist/core/export-html/template.css +1066 -0
  120. package/dist/core/export-html/template.html +55 -0
  121. package/dist/core/export-html/template.js +1864 -0
  122. package/dist/core/export-html/tool-renderer.d.ts +34 -0
  123. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  124. package/dist/core/export-html/tool-renderer.js +108 -0
  125. package/dist/core/export-html/tool-renderer.js.map +1 -0
  126. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  127. package/dist/core/export-html/vendor/marked.min.js +78 -0
  128. package/dist/core/extensions/index.d.ts +12 -0
  129. package/dist/core/extensions/index.d.ts.map +1 -0
  130. package/dist/core/extensions/index.js +9 -0
  131. package/dist/core/extensions/index.js.map +1 -0
  132. package/dist/core/extensions/loader.d.ts +25 -0
  133. package/dist/core/extensions/loader.d.ts.map +1 -0
  134. package/dist/core/extensions/loader.js +516 -0
  135. package/dist/core/extensions/loader.js.map +1 -0
  136. package/dist/core/extensions/runner.d.ts +180 -0
  137. package/dist/core/extensions/runner.d.ts.map +1 -0
  138. package/dist/core/extensions/runner.js +938 -0
  139. package/dist/core/extensions/runner.js.map +1 -0
  140. package/dist/core/extensions/types.d.ts +1215 -0
  141. package/dist/core/extensions/types.d.ts.map +1 -0
  142. package/dist/core/extensions/types.js +48 -0
  143. package/dist/core/extensions/types.js.map +1 -0
  144. package/dist/core/extensions/wrapper.d.ts +20 -0
  145. package/dist/core/extensions/wrapper.d.ts.map +1 -0
  146. package/dist/core/extensions/wrapper.js +22 -0
  147. package/dist/core/extensions/wrapper.js.map +1 -0
  148. package/dist/core/footer-data-provider.d.ts +54 -0
  149. package/dist/core/footer-data-provider.d.ts.map +1 -0
  150. package/dist/core/footer-data-provider.js +338 -0
  151. package/dist/core/footer-data-provider.js.map +1 -0
  152. package/dist/core/host-actions.d.ts +107 -0
  153. package/dist/core/host-actions.d.ts.map +1 -0
  154. package/dist/core/host-actions.js +632 -0
  155. package/dist/core/host-actions.js.map +1 -0
  156. package/dist/core/host-interaction.d.ts +35 -0
  157. package/dist/core/host-interaction.d.ts.map +1 -0
  158. package/dist/core/host-interaction.js +2 -0
  159. package/dist/core/host-interaction.js.map +1 -0
  160. package/dist/core/http-dispatcher.d.ts +22 -0
  161. package/dist/core/http-dispatcher.d.ts.map +1 -0
  162. package/dist/core/http-dispatcher.js +64 -0
  163. package/dist/core/http-dispatcher.js.map +1 -0
  164. package/dist/core/index.d.ts +18 -0
  165. package/dist/core/index.d.ts.map +1 -0
  166. package/dist/core/index.js +17 -0
  167. package/dist/core/index.js.map +1 -0
  168. package/dist/core/keybindings.d.ts +373 -0
  169. package/dist/core/keybindings.d.ts.map +1 -0
  170. package/dist/core/keybindings.js +303 -0
  171. package/dist/core/keybindings.js.map +1 -0
  172. package/dist/core/lsp/client.d.ts +119 -0
  173. package/dist/core/lsp/client.d.ts.map +1 -0
  174. package/dist/core/lsp/client.js +711 -0
  175. package/dist/core/lsp/client.js.map +1 -0
  176. package/dist/core/lsp/config.d.ts +96 -0
  177. package/dist/core/lsp/config.d.ts.map +1 -0
  178. package/dist/core/lsp/config.js +206 -0
  179. package/dist/core/lsp/config.js.map +1 -0
  180. package/dist/core/lsp/index.d.ts +6 -0
  181. package/dist/core/lsp/index.d.ts.map +1 -0
  182. package/dist/core/lsp/index.js +6 -0
  183. package/dist/core/lsp/index.js.map +1 -0
  184. package/dist/core/lsp/manager.d.ts +122 -0
  185. package/dist/core/lsp/manager.d.ts.map +1 -0
  186. package/dist/core/lsp/manager.js +1136 -0
  187. package/dist/core/lsp/manager.js.map +1 -0
  188. package/dist/core/lsp/trace.d.ts +26 -0
  189. package/dist/core/lsp/trace.d.ts.map +1 -0
  190. package/dist/core/lsp/trace.js +98 -0
  191. package/dist/core/lsp/trace.js.map +1 -0
  192. package/dist/core/lsp/workspace-edit.d.ts +60 -0
  193. package/dist/core/lsp/workspace-edit.d.ts.map +1 -0
  194. package/dist/core/lsp/workspace-edit.js +71 -0
  195. package/dist/core/lsp/workspace-edit.js.map +1 -0
  196. package/dist/core/mcp/audit.d.ts +39 -0
  197. package/dist/core/mcp/audit.d.ts.map +1 -0
  198. package/dist/core/mcp/audit.js +35 -0
  199. package/dist/core/mcp/audit.js.map +1 -0
  200. package/dist/core/mcp/auth.d.ts +7 -0
  201. package/dist/core/mcp/auth.d.ts.map +1 -0
  202. package/dist/core/mcp/auth.js +56 -0
  203. package/dist/core/mcp/auth.js.map +1 -0
  204. package/dist/core/mcp/client-factory.d.ts +20 -0
  205. package/dist/core/mcp/client-factory.d.ts.map +1 -0
  206. package/dist/core/mcp/client-factory.js +200 -0
  207. package/dist/core/mcp/client-factory.js.map +1 -0
  208. package/dist/core/mcp/config-loader.d.ts +9 -0
  209. package/dist/core/mcp/config-loader.d.ts.map +1 -0
  210. package/dist/core/mcp/config-loader.js +104 -0
  211. package/dist/core/mcp/config-loader.js.map +1 -0
  212. package/dist/core/mcp/config-writer.d.ts +21 -0
  213. package/dist/core/mcp/config-writer.d.ts.map +1 -0
  214. package/dist/core/mcp/config-writer.js +124 -0
  215. package/dist/core/mcp/config-writer.js.map +1 -0
  216. package/dist/core/mcp/config.d.ts +32 -0
  217. package/dist/core/mcp/config.d.ts.map +1 -0
  218. package/dist/core/mcp/config.js +385 -0
  219. package/dist/core/mcp/config.js.map +1 -0
  220. package/dist/core/mcp/direct-tools.d.ts +11 -0
  221. package/dist/core/mcp/direct-tools.d.ts.map +1 -0
  222. package/dist/core/mcp/direct-tools.js +47 -0
  223. package/dist/core/mcp/direct-tools.js.map +1 -0
  224. package/dist/core/mcp/gateway-tool.d.ts +29 -0
  225. package/dist/core/mcp/gateway-tool.d.ts.map +1 -0
  226. package/dist/core/mcp/gateway-tool.js +108 -0
  227. package/dist/core/mcp/gateway-tool.js.map +1 -0
  228. package/dist/core/mcp/index.d.ts +19 -0
  229. package/dist/core/mcp/index.d.ts.map +1 -0
  230. package/dist/core/mcp/index.js +18 -0
  231. package/dist/core/mcp/index.js.map +1 -0
  232. package/dist/core/mcp/manager.d.ts +117 -0
  233. package/dist/core/mcp/manager.d.ts.map +1 -0
  234. package/dist/core/mcp/manager.js +819 -0
  235. package/dist/core/mcp/manager.js.map +1 -0
  236. package/dist/core/mcp/metadata-cache.d.ts +27 -0
  237. package/dist/core/mcp/metadata-cache.d.ts.map +1 -0
  238. package/dist/core/mcp/metadata-cache.js +152 -0
  239. package/dist/core/mcp/metadata-cache.js.map +1 -0
  240. package/dist/core/mcp/oauth-flow.d.ts +94 -0
  241. package/dist/core/mcp/oauth-flow.d.ts.map +1 -0
  242. package/dist/core/mcp/oauth-flow.js +473 -0
  243. package/dist/core/mcp/oauth-flow.js.map +1 -0
  244. package/dist/core/mcp/oauth-provider.d.ts +39 -0
  245. package/dist/core/mcp/oauth-provider.d.ts.map +1 -0
  246. package/dist/core/mcp/oauth-provider.js +149 -0
  247. package/dist/core/mcp/oauth-provider.js.map +1 -0
  248. package/dist/core/mcp/oauth-store.d.ts +27 -0
  249. package/dist/core/mcp/oauth-store.d.ts.map +1 -0
  250. package/dist/core/mcp/oauth-store.js +111 -0
  251. package/dist/core/mcp/oauth-store.js.map +1 -0
  252. package/dist/core/mcp/output-store.d.ts +55 -0
  253. package/dist/core/mcp/output-store.d.ts.map +1 -0
  254. package/dist/core/mcp/output-store.js +206 -0
  255. package/dist/core/mcp/output-store.js.map +1 -0
  256. package/dist/core/mcp/rpc.d.ts +13 -0
  257. package/dist/core/mcp/rpc.d.ts.map +1 -0
  258. package/dist/core/mcp/rpc.js +29 -0
  259. package/dist/core/mcp/rpc.js.map +1 -0
  260. package/dist/core/mcp/safety.d.ts +6 -0
  261. package/dist/core/mcp/safety.d.ts.map +1 -0
  262. package/dist/core/mcp/safety.js +65 -0
  263. package/dist/core/mcp/safety.js.map +1 -0
  264. package/dist/core/mcp/search.d.ts +8 -0
  265. package/dist/core/mcp/search.d.ts.map +1 -0
  266. package/dist/core/mcp/search.js +85 -0
  267. package/dist/core/mcp/search.js.map +1 -0
  268. package/dist/core/mcp/server-supervisor.d.ts +59 -0
  269. package/dist/core/mcp/server-supervisor.d.ts.map +1 -0
  270. package/dist/core/mcp/server-supervisor.js +331 -0
  271. package/dist/core/mcp/server-supervisor.js.map +1 -0
  272. package/dist/core/mcp/types.d.ts +321 -0
  273. package/dist/core/mcp/types.d.ts.map +1 -0
  274. package/dist/core/mcp/types.js +2 -0
  275. package/dist/core/mcp/types.js.map +1 -0
  276. package/dist/core/messages.d.ts +78 -0
  277. package/dist/core/messages.d.ts.map +1 -0
  278. package/dist/core/messages.js +138 -0
  279. package/dist/core/messages.js.map +1 -0
  280. package/dist/core/model-catalog-watcher.d.ts +36 -0
  281. package/dist/core/model-catalog-watcher.d.ts.map +1 -0
  282. package/dist/core/model-catalog-watcher.js +101 -0
  283. package/dist/core/model-catalog-watcher.js.map +1 -0
  284. package/dist/core/model-registry.d.ts +160 -0
  285. package/dist/core/model-registry.d.ts.map +1 -0
  286. package/dist/core/model-registry.js +754 -0
  287. package/dist/core/model-registry.js.map +1 -0
  288. package/dist/core/model-resolver.d.ts +111 -0
  289. package/dist/core/model-resolver.d.ts.map +1 -0
  290. package/dist/core/model-resolver.js +534 -0
  291. package/dist/core/model-resolver.js.map +1 -0
  292. package/dist/core/output-guard.d.ts +7 -0
  293. package/dist/core/output-guard.d.ts.map +1 -0
  294. package/dist/core/output-guard.js +89 -0
  295. package/dist/core/output-guard.js.map +1 -0
  296. package/dist/core/package-manager.d.ts +220 -0
  297. package/dist/core/package-manager.d.ts.map +1 -0
  298. package/dist/core/package-manager.js +2217 -0
  299. package/dist/core/package-manager.js.map +1 -0
  300. package/dist/core/project-trust.d.ts +15 -0
  301. package/dist/core/project-trust.d.ts.map +1 -0
  302. package/dist/core/project-trust.js +58 -0
  303. package/dist/core/project-trust.js.map +1 -0
  304. package/dist/core/prompt-templates.d.ts +53 -0
  305. package/dist/core/prompt-templates.d.ts.map +1 -0
  306. package/dist/core/prompt-templates.js +236 -0
  307. package/dist/core/prompt-templates.js.map +1 -0
  308. package/dist/core/provider-attribution.d.ts +4 -0
  309. package/dist/core/provider-attribution.d.ts.map +1 -0
  310. package/dist/core/provider-attribution.js +81 -0
  311. package/dist/core/provider-attribution.js.map +1 -0
  312. package/dist/core/provider-display-names.d.ts +2 -0
  313. package/dist/core/provider-display-names.d.ts.map +1 -0
  314. package/dist/core/provider-display-names.js +36 -0
  315. package/dist/core/provider-display-names.js.map +1 -0
  316. package/dist/core/remote/iroh/access-grant.d.ts +40 -0
  317. package/dist/core/remote/iroh/access-grant.d.ts.map +1 -0
  318. package/dist/core/remote/iroh/access-grant.js +199 -0
  319. package/dist/core/remote/iroh/access-grant.js.map +1 -0
  320. package/dist/core/remote/iroh/active-stream-registry.d.ts +39 -0
  321. package/dist/core/remote/iroh/active-stream-registry.d.ts.map +1 -0
  322. package/dist/core/remote/iroh/active-stream-registry.js +109 -0
  323. package/dist/core/remote/iroh/active-stream-registry.js.map +1 -0
  324. package/dist/core/remote/iroh/audit.d.ts +67 -0
  325. package/dist/core/remote/iroh/audit.d.ts.map +1 -0
  326. package/dist/core/remote/iroh/audit.js +274 -0
  327. package/dist/core/remote/iroh/audit.js.map +1 -0
  328. package/dist/core/remote/iroh/authorization.d.ts +46 -0
  329. package/dist/core/remote/iroh/authorization.d.ts.map +1 -0
  330. package/dist/core/remote/iroh/authorization.js +327 -0
  331. package/dist/core/remote/iroh/authorization.js.map +1 -0
  332. package/dist/core/remote/iroh/control.d.ts +64 -0
  333. package/dist/core/remote/iroh/control.d.ts.map +1 -0
  334. package/dist/core/remote/iroh/control.js +326 -0
  335. package/dist/core/remote/iroh/control.js.map +1 -0
  336. package/dist/core/remote/iroh/device-log-rpc.d.ts +22 -0
  337. package/dist/core/remote/iroh/device-log-rpc.d.ts.map +1 -0
  338. package/dist/core/remote/iroh/device-log-rpc.js +152 -0
  339. package/dist/core/remote/iroh/device-log-rpc.js.map +1 -0
  340. package/dist/core/remote/iroh/engine.d.ts +148 -0
  341. package/dist/core/remote/iroh/engine.d.ts.map +1 -0
  342. package/dist/core/remote/iroh/engine.js +499 -0
  343. package/dist/core/remote/iroh/engine.js.map +1 -0
  344. package/dist/core/remote/iroh/handshake-reader.d.ts +19 -0
  345. package/dist/core/remote/iroh/handshake-reader.d.ts.map +1 -0
  346. package/dist/core/remote/iroh/handshake-reader.js +91 -0
  347. package/dist/core/remote/iroh/handshake-reader.js.map +1 -0
  348. package/dist/core/remote/iroh/handshake.d.ts +119 -0
  349. package/dist/core/remote/iroh/handshake.d.ts.map +1 -0
  350. package/dist/core/remote/iroh/handshake.js +621 -0
  351. package/dist/core/remote/iroh/handshake.js.map +1 -0
  352. package/dist/core/remote/iroh/host-policy.d.ts +13 -0
  353. package/dist/core/remote/iroh/host-policy.d.ts.map +1 -0
  354. package/dist/core/remote/iroh/host-policy.js +15 -0
  355. package/dist/core/remote/iroh/host-policy.js.map +1 -0
  356. package/dist/core/remote/iroh/index.d.ts +25 -0
  357. package/dist/core/remote/iroh/index.d.ts.map +1 -0
  358. package/dist/core/remote/iroh/index.js +25 -0
  359. package/dist/core/remote/iroh/index.js.map +1 -0
  360. package/dist/core/remote/iroh/metadata.d.ts +28 -0
  361. package/dist/core/remote/iroh/metadata.d.ts.map +1 -0
  362. package/dist/core/remote/iroh/metadata.js +16 -0
  363. package/dist/core/remote/iroh/metadata.js.map +1 -0
  364. package/dist/core/remote/iroh/outbound-filter.d.ts +29 -0
  365. package/dist/core/remote/iroh/outbound-filter.d.ts.map +1 -0
  366. package/dist/core/remote/iroh/outbound-filter.js +692 -0
  367. package/dist/core/remote/iroh/outbound-filter.js.map +1 -0
  368. package/dist/core/remote/iroh/protocol.d.ts +60 -0
  369. package/dist/core/remote/iroh/protocol.d.ts.map +1 -0
  370. package/dist/core/remote/iroh/protocol.js +204 -0
  371. package/dist/core/remote/iroh/protocol.js.map +1 -0
  372. package/dist/core/remote/iroh/push.d.ts +179 -0
  373. package/dist/core/remote/iroh/push.d.ts.map +1 -0
  374. package/dist/core/remote/iroh/push.js +662 -0
  375. package/dist/core/remote/iroh/push.js.map +1 -0
  376. package/dist/core/remote/iroh/qr.d.ts +12 -0
  377. package/dist/core/remote/iroh/qr.d.ts.map +1 -0
  378. package/dist/core/remote/iroh/qr.js +27 -0
  379. package/dist/core/remote/iroh/qr.js.map +1 -0
  380. package/dist/core/remote/iroh/rpc-command-filter.d.ts +47 -0
  381. package/dist/core/remote/iroh/rpc-command-filter.d.ts.map +1 -0
  382. package/dist/core/remote/iroh/rpc-command-filter.js +188 -0
  383. package/dist/core/remote/iroh/rpc-command-filter.js.map +1 -0
  384. package/dist/core/remote/iroh/rpc-transport.d.ts +21 -0
  385. package/dist/core/remote/iroh/rpc-transport.d.ts.map +1 -0
  386. package/dist/core/remote/iroh/rpc-transport.js +106 -0
  387. package/dist/core/remote/iroh/rpc-transport.js.map +1 -0
  388. package/dist/core/remote/iroh/state-manager.d.ts +141 -0
  389. package/dist/core/remote/iroh/state-manager.d.ts.map +1 -0
  390. package/dist/core/remote/iroh/state-manager.js +744 -0
  391. package/dist/core/remote/iroh/state-manager.js.map +1 -0
  392. package/dist/core/remote/iroh/state.d.ts +141 -0
  393. package/dist/core/remote/iroh/state.d.ts.map +1 -0
  394. package/dist/core/remote/iroh/state.js +433 -0
  395. package/dist/core/remote/iroh/state.js.map +1 -0
  396. package/dist/core/remote/iroh/ticket.d.ts +46 -0
  397. package/dist/core/remote/iroh/ticket.d.ts.map +1 -0
  398. package/dist/core/remote/iroh/ticket.js +267 -0
  399. package/dist/core/remote/iroh/ticket.js.map +1 -0
  400. package/dist/core/remote/iroh/transcript-text.d.ts +8 -0
  401. package/dist/core/remote/iroh/transcript-text.d.ts.map +1 -0
  402. package/dist/core/remote/iroh/transcript-text.js +26 -0
  403. package/dist/core/remote/iroh/transcript-text.js.map +1 -0
  404. package/dist/core/remote/iroh/workspace-rpc.d.ts +31 -0
  405. package/dist/core/remote/iroh/workspace-rpc.d.ts.map +1 -0
  406. package/dist/core/remote/iroh/workspace-rpc.js +73 -0
  407. package/dist/core/remote/iroh/workspace-rpc.js.map +1 -0
  408. package/dist/core/remote/iroh/workspace.d.ts +16 -0
  409. package/dist/core/remote/iroh/workspace.d.ts.map +1 -0
  410. package/dist/core/remote/iroh/workspace.js +104 -0
  411. package/dist/core/remote/iroh/workspace.js.map +1 -0
  412. package/dist/core/remote/iroh/worktree-rpc.d.ts +83 -0
  413. package/dist/core/remote/iroh/worktree-rpc.d.ts.map +1 -0
  414. package/dist/core/remote/iroh/worktree-rpc.js +148 -0
  415. package/dist/core/remote/iroh/worktree-rpc.js.map +1 -0
  416. package/dist/core/resolve-config-value.d.ts +30 -0
  417. package/dist/core/resolve-config-value.d.ts.map +1 -0
  418. package/dist/core/resolve-config-value.js +245 -0
  419. package/dist/core/resolve-config-value.js.map +1 -0
  420. package/dist/core/resource-loader.d.ts +214 -0
  421. package/dist/core/resource-loader.d.ts.map +1 -0
  422. package/dist/core/resource-loader.js +824 -0
  423. package/dist/core/resource-loader.js.map +1 -0
  424. package/dist/core/review.d.ts +318 -0
  425. package/dist/core/review.d.ts.map +1 -0
  426. package/dist/core/review.js +1271 -0
  427. package/dist/core/review.js.map +1 -0
  428. package/dist/core/rpc/duplex-write-gate.d.ts +29 -0
  429. package/dist/core/rpc/duplex-write-gate.d.ts.map +1 -0
  430. package/dist/core/rpc/duplex-write-gate.js +124 -0
  431. package/dist/core/rpc/duplex-write-gate.js.map +1 -0
  432. package/dist/core/rpc/index.d.ts +6 -0
  433. package/dist/core/rpc/index.d.ts.map +1 -0
  434. package/dist/core/rpc/index.js +5 -0
  435. package/dist/core/rpc/index.js.map +1 -0
  436. package/dist/core/rpc/iroh-transport.d.ts +58 -0
  437. package/dist/core/rpc/iroh-transport.d.ts.map +1 -0
  438. package/dist/core/rpc/iroh-transport.js +278 -0
  439. package/dist/core/rpc/iroh-transport.js.map +1 -0
  440. package/dist/core/rpc/jsonl.d.ts +17 -0
  441. package/dist/core/rpc/jsonl.d.ts.map +1 -0
  442. package/dist/core/rpc/jsonl.js +49 -0
  443. package/dist/core/rpc/jsonl.js.map +1 -0
  444. package/dist/core/rpc/loopback-transport.d.ts +14 -0
  445. package/dist/core/rpc/loopback-transport.d.ts.map +1 -0
  446. package/dist/core/rpc/loopback-transport.js +120 -0
  447. package/dist/core/rpc/loopback-transport.js.map +1 -0
  448. package/dist/core/rpc/transcript.d.ts +37 -0
  449. package/dist/core/rpc/transcript.d.ts.map +1 -0
  450. package/dist/core/rpc/transcript.js +624 -0
  451. package/dist/core/rpc/transcript.js.map +1 -0
  452. package/dist/core/rpc/transport.d.ts +41 -0
  453. package/dist/core/rpc/transport.d.ts.map +1 -0
  454. package/dist/core/rpc/transport.js +155 -0
  455. package/dist/core/rpc/transport.js.map +1 -0
  456. package/dist/core/rpc/types.d.ts +1254 -0
  457. package/dist/core/rpc/types.d.ts.map +1 -0
  458. package/dist/core/rpc/types.js +8 -0
  459. package/dist/core/rpc/types.js.map +1 -0
  460. package/dist/core/rpc/ui-action-args.d.ts +3 -0
  461. package/dist/core/rpc/ui-action-args.d.ts.map +1 -0
  462. package/dist/core/rpc/ui-action-args.js +66 -0
  463. package/dist/core/rpc/ui-action-args.js.map +1 -0
  464. package/dist/core/rpc/ui-actions.d.ts +43 -0
  465. package/dist/core/rpc/ui-actions.d.ts.map +1 -0
  466. package/dist/core/rpc/ui-actions.js +362 -0
  467. package/dist/core/rpc/ui-actions.js.map +1 -0
  468. package/dist/core/sdk.d.ts +138 -0
  469. package/dist/core/sdk.d.ts.map +1 -0
  470. package/dist/core/sdk.js +324 -0
  471. package/dist/core/sdk.js.map +1 -0
  472. package/dist/core/session-cwd.d.ts +19 -0
  473. package/dist/core/session-cwd.d.ts.map +1 -0
  474. package/dist/core/session-cwd.js +38 -0
  475. package/dist/core/session-cwd.js.map +1 -0
  476. package/dist/core/session-manager.d.ts +346 -0
  477. package/dist/core/session-manager.d.ts.map +1 -0
  478. package/dist/core/session-manager.js +1280 -0
  479. package/dist/core/session-manager.js.map +1 -0
  480. package/dist/core/settings-manager.d.ts +359 -0
  481. package/dist/core/settings-manager.d.ts.map +1 -0
  482. package/dist/core/settings-manager.js +1277 -0
  483. package/dist/core/settings-manager.js.map +1 -0
  484. package/dist/core/skills.d.ts +60 -0
  485. package/dist/core/skills.d.ts.map +1 -0
  486. package/dist/core/skills.js +387 -0
  487. package/dist/core/skills.js.map +1 -0
  488. package/dist/core/slash-commands.d.ts +14 -0
  489. package/dist/core/slash-commands.d.ts.map +1 -0
  490. package/dist/core/slash-commands.js +51 -0
  491. package/dist/core/slash-commands.js.map +1 -0
  492. package/dist/core/source-info.d.ts +18 -0
  493. package/dist/core/source-info.d.ts.map +1 -0
  494. package/dist/core/source-info.js +19 -0
  495. package/dist/core/source-info.js.map +1 -0
  496. package/dist/core/subagents/delegation-scope.d.ts +47 -0
  497. package/dist/core/subagents/delegation-scope.d.ts.map +1 -0
  498. package/dist/core/subagents/delegation-scope.js +134 -0
  499. package/dist/core/subagents/delegation-scope.js.map +1 -0
  500. package/dist/core/subagents/index.d.ts +46 -0
  501. package/dist/core/subagents/index.d.ts.map +1 -0
  502. package/dist/core/subagents/index.js +369 -0
  503. package/dist/core/subagents/index.js.map +1 -0
  504. package/dist/core/subagents/manager.d.ts +183 -0
  505. package/dist/core/subagents/manager.d.ts.map +1 -0
  506. package/dist/core/subagents/manager.js +820 -0
  507. package/dist/core/subagents/manager.js.map +1 -0
  508. package/dist/core/system-prompt.d.ts +28 -0
  509. package/dist/core/system-prompt.d.ts.map +1 -0
  510. package/dist/core/system-prompt.js +180 -0
  511. package/dist/core/system-prompt.js.map +1 -0
  512. package/dist/core/telemetry.d.ts +3 -0
  513. package/dist/core/telemetry.d.ts.map +1 -0
  514. package/dist/core/telemetry.js +9 -0
  515. package/dist/core/telemetry.js.map +1 -0
  516. package/dist/core/theme/dark.json +86 -0
  517. package/dist/core/theme/discovery.d.ts +48 -0
  518. package/dist/core/theme/discovery.d.ts.map +1 -0
  519. package/dist/core/theme/discovery.js +239 -0
  520. package/dist/core/theme/discovery.js.map +1 -0
  521. package/dist/core/theme/index.d.ts +6 -0
  522. package/dist/core/theme/index.d.ts.map +1 -0
  523. package/dist/core/theme/index.js +5 -0
  524. package/dist/core/theme/index.js.map +1 -0
  525. package/dist/core/theme/light.json +85 -0
  526. package/dist/core/theme/runtime.d.ts +55 -0
  527. package/dist/core/theme/runtime.d.ts.map +1 -0
  528. package/dist/core/theme/runtime.js +555 -0
  529. package/dist/core/theme/runtime.js.map +1 -0
  530. package/dist/core/theme/theme-schema.json +335 -0
  531. package/dist/core/theme/theme-service.d.ts +37 -0
  532. package/dist/core/theme/theme-service.d.ts.map +1 -0
  533. package/dist/core/theme/theme-service.js +222 -0
  534. package/dist/core/theme/theme-service.js.map +1 -0
  535. package/dist/core/theme/theme.d.ts +100 -0
  536. package/dist/core/theme/theme.d.ts.map +1 -0
  537. package/dist/core/theme/theme.js +243 -0
  538. package/dist/core/theme/theme.js.map +1 -0
  539. package/dist/core/theme/tokens.d.ts +20 -0
  540. package/dist/core/theme/tokens.d.ts.map +1 -0
  541. package/dist/core/theme/tokens.js +178 -0
  542. package/dist/core/theme/tokens.js.map +1 -0
  543. package/dist/core/theme/types.d.ts +21 -0
  544. package/dist/core/theme/types.d.ts.map +1 -0
  545. package/dist/core/theme/types.js +2 -0
  546. package/dist/core/theme/types.js.map +1 -0
  547. package/dist/core/timings.d.ts +8 -0
  548. package/dist/core/timings.d.ts.map +1 -0
  549. package/dist/core/timings.js +31 -0
  550. package/dist/core/timings.js.map +1 -0
  551. package/dist/core/tools/bash.d.ts +68 -0
  552. package/dist/core/tools/bash.d.ts.map +1 -0
  553. package/dist/core/tools/bash.js +345 -0
  554. package/dist/core/tools/bash.js.map +1 -0
  555. package/dist/core/tools/diagnostics-provider.d.ts +12 -0
  556. package/dist/core/tools/diagnostics-provider.d.ts.map +1 -0
  557. package/dist/core/tools/diagnostics-provider.js +2 -0
  558. package/dist/core/tools/diagnostics-provider.js.map +1 -0
  559. package/dist/core/tools/edit-diff.d.ts +77 -0
  560. package/dist/core/tools/edit-diff.d.ts.map +1 -0
  561. package/dist/core/tools/edit-diff.js +506 -0
  562. package/dist/core/tools/edit-diff.js.map +1 -0
  563. package/dist/core/tools/edit.d.ts +56 -0
  564. package/dist/core/tools/edit.d.ts.map +1 -0
  565. package/dist/core/tools/edit.js +300 -0
  566. package/dist/core/tools/edit.js.map +1 -0
  567. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  568. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  569. package/dist/core/tools/file-mutation-queue.js +52 -0
  570. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  571. package/dist/core/tools/find.d.ts +35 -0
  572. package/dist/core/tools/find.d.ts.map +1 -0
  573. package/dist/core/tools/find.js +337 -0
  574. package/dist/core/tools/find.js.map +1 -0
  575. package/dist/core/tools/grep.d.ts +37 -0
  576. package/dist/core/tools/grep.d.ts.map +1 -0
  577. package/dist/core/tools/grep.js +305 -0
  578. package/dist/core/tools/grep.js.map +1 -0
  579. package/dist/core/tools/index.d.ts +56 -0
  580. package/dist/core/tools/index.d.ts.map +1 -0
  581. package/dist/core/tools/index.js +174 -0
  582. package/dist/core/tools/index.js.map +1 -0
  583. package/dist/core/tools/ls.d.ts +37 -0
  584. package/dist/core/tools/ls.d.ts.map +1 -0
  585. package/dist/core/tools/ls.js +167 -0
  586. package/dist/core/tools/ls.js.map +1 -0
  587. package/dist/core/tools/lsp.d.ts +59 -0
  588. package/dist/core/tools/lsp.d.ts.map +1 -0
  589. package/dist/core/tools/lsp.js +157 -0
  590. package/dist/core/tools/lsp.js.map +1 -0
  591. package/dist/core/tools/output-accumulator.d.ts +52 -0
  592. package/dist/core/tools/output-accumulator.d.ts.map +1 -0
  593. package/dist/core/tools/output-accumulator.js +184 -0
  594. package/dist/core/tools/output-accumulator.js.map +1 -0
  595. package/dist/core/tools/path-utils.d.ts +10 -0
  596. package/dist/core/tools/path-utils.d.ts.map +1 -0
  597. package/dist/core/tools/path-utils.js +99 -0
  598. package/dist/core/tools/path-utils.js.map +1 -0
  599. package/dist/core/tools/read.d.ts +35 -0
  600. package/dist/core/tools/read.d.ts.map +1 -0
  601. package/dist/core/tools/read.js +292 -0
  602. package/dist/core/tools/read.js.map +1 -0
  603. package/dist/core/tools/render-utils.d.ts +26 -0
  604. package/dist/core/tools/render-utils.d.ts.map +1 -0
  605. package/dist/core/tools/render-utils.js +69 -0
  606. package/dist/core/tools/render-utils.js.map +1 -0
  607. package/dist/core/tools/subagent.d.ts +219 -0
  608. package/dist/core/tools/subagent.d.ts.map +1 -0
  609. package/dist/core/tools/subagent.js +1445 -0
  610. package/dist/core/tools/subagent.js.map +1 -0
  611. package/dist/core/tools/tool-definition-wrapper.d.ts +14 -0
  612. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -0
  613. package/dist/core/tools/tool-definition-wrapper.js +34 -0
  614. package/dist/core/tools/tool-definition-wrapper.js.map +1 -0
  615. package/dist/core/tools/truncate.d.ts +70 -0
  616. package/dist/core/tools/truncate.d.ts.map +1 -0
  617. package/dist/core/tools/truncate.js +215 -0
  618. package/dist/core/tools/truncate.js.map +1 -0
  619. package/dist/core/tools/web-search.d.ts +69 -0
  620. package/dist/core/tools/web-search.d.ts.map +1 -0
  621. package/dist/core/tools/web-search.js +634 -0
  622. package/dist/core/tools/web-search.js.map +1 -0
  623. package/dist/core/tools/write.d.ts +33 -0
  624. package/dist/core/tools/write.d.ts.map +1 -0
  625. package/dist/core/tools/write.js +210 -0
  626. package/dist/core/tools/write.js.map +1 -0
  627. package/dist/core/trust-manager.d.ts +36 -0
  628. package/dist/core/trust-manager.d.ts.map +1 -0
  629. package/dist/core/trust-manager.js +220 -0
  630. package/dist/core/trust-manager.js.map +1 -0
  631. package/dist/daemon/cli.d.ts +8 -0
  632. package/dist/daemon/cli.d.ts.map +1 -0
  633. package/dist/daemon/cli.js +468 -0
  634. package/dist/daemon/cli.js.map +1 -0
  635. package/dist/daemon/control-client.d.ts +60 -0
  636. package/dist/daemon/control-client.d.ts.map +1 -0
  637. package/dist/daemon/control-client.js +411 -0
  638. package/dist/daemon/control-client.js.map +1 -0
  639. package/dist/daemon/control-protocol.d.ts +507 -0
  640. package/dist/daemon/control-protocol.d.ts.map +1 -0
  641. package/dist/daemon/control-protocol.js +395 -0
  642. package/dist/daemon/control-protocol.js.map +1 -0
  643. package/dist/daemon/control-server.d.ts +77 -0
  644. package/dist/daemon/control-server.d.ts.map +1 -0
  645. package/dist/daemon/control-server.js +327 -0
  646. package/dist/daemon/control-server.js.map +1 -0
  647. package/dist/daemon/conversation-commands.d.ts +176 -0
  648. package/dist/daemon/conversation-commands.d.ts.map +1 -0
  649. package/dist/daemon/conversation-commands.js +1268 -0
  650. package/dist/daemon/conversation-commands.js.map +1 -0
  651. package/dist/daemon/daemon-lock.d.ts +27 -0
  652. package/dist/daemon/daemon-lock.d.ts.map +1 -0
  653. package/dist/daemon/daemon-lock.js +238 -0
  654. package/dist/daemon/daemon-lock.js.map +1 -0
  655. package/dist/daemon/handshake-responses.d.ts +47 -0
  656. package/dist/daemon/handshake-responses.d.ts.map +1 -0
  657. package/dist/daemon/handshake-responses.js +113 -0
  658. package/dist/daemon/handshake-responses.js.map +1 -0
  659. package/dist/daemon/integrated-runtimes.d.ts +137 -0
  660. package/dist/daemon/integrated-runtimes.d.ts.map +1 -0
  661. package/dist/daemon/integrated-runtimes.js +763 -0
  662. package/dist/daemon/integrated-runtimes.js.map +1 -0
  663. package/dist/daemon/iroh-native.d.ts +76 -0
  664. package/dist/daemon/iroh-native.d.ts.map +1 -0
  665. package/dist/daemon/iroh-native.js +18 -0
  666. package/dist/daemon/iroh-native.js.map +1 -0
  667. package/dist/daemon/iroh-resource-guard.d.ts +57 -0
  668. package/dist/daemon/iroh-resource-guard.d.ts.map +1 -0
  669. package/dist/daemon/iroh-resource-guard.js +134 -0
  670. package/dist/daemon/iroh-resource-guard.js.map +1 -0
  671. package/dist/daemon/iroh-service.d.ts +51 -0
  672. package/dist/daemon/iroh-service.d.ts.map +1 -0
  673. package/dist/daemon/iroh-service.js +2604 -0
  674. package/dist/daemon/iroh-service.js.map +1 -0
  675. package/dist/daemon/keep-awake.d.ts +62 -0
  676. package/dist/daemon/keep-awake.d.ts.map +1 -0
  677. package/dist/daemon/keep-awake.js +190 -0
  678. package/dist/daemon/keep-awake.js.map +1 -0
  679. package/dist/daemon/lease-broker.d.ts +139 -0
  680. package/dist/daemon/lease-broker.d.ts.map +1 -0
  681. package/dist/daemon/lease-broker.js +504 -0
  682. package/dist/daemon/lease-broker.js.map +1 -0
  683. package/dist/daemon/log.d.ts +16 -0
  684. package/dist/daemon/log.d.ts.map +1 -0
  685. package/dist/daemon/log.js +40 -0
  686. package/dist/daemon/log.js.map +1 -0
  687. package/dist/daemon/main.d.ts +70 -0
  688. package/dist/daemon/main.d.ts.map +1 -0
  689. package/dist/daemon/main.js +781 -0
  690. package/dist/daemon/main.js.map +1 -0
  691. package/dist/daemon/paths.d.ts +32 -0
  692. package/dist/daemon/paths.d.ts.map +1 -0
  693. package/dist/daemon/paths.js +208 -0
  694. package/dist/daemon/paths.js.map +1 -0
  695. package/dist/daemon/process-identity.d.ts +58 -0
  696. package/dist/daemon/process-identity.d.ts.map +1 -0
  697. package/dist/daemon/process-identity.js +185 -0
  698. package/dist/daemon/process-identity.js.map +1 -0
  699. package/dist/daemon/relay-stream.d.ts +89 -0
  700. package/dist/daemon/relay-stream.d.ts.map +1 -0
  701. package/dist/daemon/relay-stream.js +202 -0
  702. package/dist/daemon/relay-stream.js.map +1 -0
  703. package/dist/daemon/remote-cli.d.ts +7 -0
  704. package/dist/daemon/remote-cli.d.ts.map +1 -0
  705. package/dist/daemon/remote-cli.js +774 -0
  706. package/dist/daemon/remote-cli.js.map +1 -0
  707. package/dist/daemon/service-install.d.ts +43 -0
  708. package/dist/daemon/service-install.d.ts.map +1 -0
  709. package/dist/daemon/service-install.js +198 -0
  710. package/dist/daemon/service-install.js.map +1 -0
  711. package/dist/daemon/session-target.d.ts +62 -0
  712. package/dist/daemon/session-target.d.ts.map +1 -0
  713. package/dist/daemon/session-target.js +66 -0
  714. package/dist/daemon/session-target.js.map +1 -0
  715. package/dist/daemon/spawn.d.ts +53 -0
  716. package/dist/daemon/spawn.d.ts.map +1 -0
  717. package/dist/daemon/spawn.js +205 -0
  718. package/dist/daemon/spawn.js.map +1 -0
  719. package/dist/daemon/state.d.ts +145 -0
  720. package/dist/daemon/state.d.ts.map +1 -0
  721. package/dist/daemon/state.js +454 -0
  722. package/dist/daemon/state.js.map +1 -0
  723. package/dist/daemon/theme-push.d.ts +23 -0
  724. package/dist/daemon/theme-push.d.ts.map +1 -0
  725. package/dist/daemon/theme-push.js +30 -0
  726. package/dist/daemon/theme-push.js.map +1 -0
  727. package/dist/daemon/viewer-feed.d.ts +42 -0
  728. package/dist/daemon/viewer-feed.d.ts.map +1 -0
  729. package/dist/daemon/viewer-feed.js +138 -0
  730. package/dist/daemon/viewer-feed.js.map +1 -0
  731. package/dist/daemon/workspace-directory.d.ts +35 -0
  732. package/dist/daemon/workspace-directory.d.ts.map +1 -0
  733. package/dist/daemon/workspace-directory.js +105 -0
  734. package/dist/daemon/workspace-directory.js.map +1 -0
  735. package/dist/daemon/workspace-streams.d.ts +70 -0
  736. package/dist/daemon/workspace-streams.d.ts.map +1 -0
  737. package/dist/daemon/workspace-streams.js +289 -0
  738. package/dist/daemon/workspace-streams.js.map +1 -0
  739. package/dist/daemon/worktree-manager.d.ts +219 -0
  740. package/dist/daemon/worktree-manager.d.ts.map +1 -0
  741. package/dist/daemon/worktree-manager.js +1204 -0
  742. package/dist/daemon/worktree-manager.js.map +1 -0
  743. package/dist/index.d.ts +44 -0
  744. package/dist/index.d.ts.map +1 -0
  745. package/dist/index.js +57 -0
  746. package/dist/index.js.map +1 -0
  747. package/dist/main.d.ts +12 -0
  748. package/dist/main.d.ts.map +1 -0
  749. package/dist/main.js +773 -0
  750. package/dist/main.js.map +1 -0
  751. package/dist/mcp-cli.d.ts +6 -0
  752. package/dist/mcp-cli.d.ts.map +1 -0
  753. package/dist/mcp-cli.js +347 -0
  754. package/dist/mcp-cli.js.map +1 -0
  755. package/dist/migrations.d.ts +33 -0
  756. package/dist/migrations.d.ts.map +1 -0
  757. package/dist/migrations.js +281 -0
  758. package/dist/migrations.js.map +1 -0
  759. package/dist/modes/index.d.ts +13 -0
  760. package/dist/modes/index.d.ts.map +1 -0
  761. package/dist/modes/index.js +12 -0
  762. package/dist/modes/index.js.map +1 -0
  763. package/dist/modes/interactive/components/armin.d.ts +34 -0
  764. package/dist/modes/interactive/components/armin.d.ts.map +1 -0
  765. package/dist/modes/interactive/components/armin.js +333 -0
  766. package/dist/modes/interactive/components/armin.js.map +1 -0
  767. package/dist/modes/interactive/components/assistant-message.d.ts +22 -0
  768. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
  769. package/dist/modes/interactive/components/assistant-message.js +129 -0
  770. package/dist/modes/interactive/components/assistant-message.js.map +1 -0
  771. package/dist/modes/interactive/components/bash-execution.d.ts +39 -0
  772. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
  773. package/dist/modes/interactive/components/bash-execution.js +212 -0
  774. package/dist/modes/interactive/components/bash-execution.js.map +1 -0
  775. package/dist/modes/interactive/components/bordered-loader.d.ts +17 -0
  776. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  777. package/dist/modes/interactive/components/bordered-loader.js +57 -0
  778. package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
  779. package/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
  780. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  781. package/dist/modes/interactive/components/branch-summary-message.js +44 -0
  782. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
  783. package/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  784. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  785. package/dist/modes/interactive/components/compaction-summary-message.js +45 -0
  786. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
  787. package/dist/modes/interactive/components/config-selector.d.ts +71 -0
  788. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
  789. package/dist/modes/interactive/components/config-selector.js +510 -0
  790. package/dist/modes/interactive/components/config-selector.js.map +1 -0
  791. package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  792. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  793. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  794. package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
  795. package/dist/modes/interactive/components/custom-editor.d.ts +21 -0
  796. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
  797. package/dist/modes/interactive/components/custom-editor.js +70 -0
  798. package/dist/modes/interactive/components/custom-editor.js.map +1 -0
  799. package/dist/modes/interactive/components/custom-message.d.ts +20 -0
  800. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
  801. package/dist/modes/interactive/components/custom-message.js +76 -0
  802. package/dist/modes/interactive/components/custom-message.js.map +1 -0
  803. package/dist/modes/interactive/components/daxnuts.d.ts +23 -0
  804. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -0
  805. package/dist/modes/interactive/components/daxnuts.js +140 -0
  806. package/dist/modes/interactive/components/daxnuts.js.map +1 -0
  807. package/dist/modes/interactive/components/diff.d.ts +12 -0
  808. package/dist/modes/interactive/components/diff.d.ts.map +1 -0
  809. package/dist/modes/interactive/components/diff.js +133 -0
  810. package/dist/modes/interactive/components/diff.js.map +1 -0
  811. package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  812. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  813. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  814. package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
  815. package/dist/modes/interactive/components/extension-editor.d.ts +20 -0
  816. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
  817. package/dist/modes/interactive/components/extension-editor.js +116 -0
  818. package/dist/modes/interactive/components/extension-editor.js.map +1 -0
  819. package/dist/modes/interactive/components/extension-input.d.ts +23 -0
  820. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
  821. package/dist/modes/interactive/components/extension-input.js +61 -0
  822. package/dist/modes/interactive/components/extension-input.js.map +1 -0
  823. package/dist/modes/interactive/components/extension-selector.d.ts +27 -0
  824. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
  825. package/dist/modes/interactive/components/extension-selector.js +98 -0
  826. package/dist/modes/interactive/components/extension-selector.js.map +1 -0
  827. package/dist/modes/interactive/components/first-time-setup.d.ts +25 -0
  828. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -0
  829. package/dist/modes/interactive/components/first-time-setup.js +103 -0
  830. package/dist/modes/interactive/components/first-time-setup.js.map +1 -0
  831. package/dist/modes/interactive/components/footer.d.ts +27 -0
  832. package/dist/modes/interactive/components/footer.d.ts.map +1 -0
  833. package/dist/modes/interactive/components/footer.js +180 -0
  834. package/dist/modes/interactive/components/footer.js.map +1 -0
  835. package/dist/modes/interactive/components/hotkeys.d.ts +24 -0
  836. package/dist/modes/interactive/components/hotkeys.d.ts.map +1 -0
  837. package/dist/modes/interactive/components/hotkeys.js +97 -0
  838. package/dist/modes/interactive/components/hotkeys.js.map +1 -0
  839. package/dist/modes/interactive/components/index.d.ts +35 -0
  840. package/dist/modes/interactive/components/index.d.ts.map +1 -0
  841. package/dist/modes/interactive/components/index.js +36 -0
  842. package/dist/modes/interactive/components/index.js.map +1 -0
  843. package/dist/modes/interactive/components/keybinding-hints.d.ts +19 -0
  844. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  845. package/dist/modes/interactive/components/keybinding-hints.js +48 -0
  846. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
  847. package/dist/modes/interactive/components/login-dialog.d.ts +52 -0
  848. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
  849. package/dist/modes/interactive/components/login-dialog.js +179 -0
  850. package/dist/modes/interactive/components/login-dialog.js.map +1 -0
  851. package/dist/modes/interactive/components/logo.d.ts +25 -0
  852. package/dist/modes/interactive/components/logo.d.ts.map +1 -0
  853. package/dist/modes/interactive/components/logo.js +89 -0
  854. package/dist/modes/interactive/components/logo.js.map +1 -0
  855. package/dist/modes/interactive/components/model-selector.d.ts +47 -0
  856. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
  857. package/dist/modes/interactive/components/model-selector.js +278 -0
  858. package/dist/modes/interactive/components/model-selector.js.map +1 -0
  859. package/dist/modes/interactive/components/oauth-selector.d.ts +31 -0
  860. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  861. package/dist/modes/interactive/components/oauth-selector.js +165 -0
  862. package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
  863. package/dist/modes/interactive/components/remote-control-center.d.ts +110 -0
  864. package/dist/modes/interactive/components/remote-control-center.d.ts.map +1 -0
  865. package/dist/modes/interactive/components/remote-control-center.js +1217 -0
  866. package/dist/modes/interactive/components/remote-control-center.js.map +1 -0
  867. package/dist/modes/interactive/components/review-tools-selector.d.ts +24 -0
  868. package/dist/modes/interactive/components/review-tools-selector.d.ts.map +1 -0
  869. package/dist/modes/interactive/components/review-tools-selector.js +93 -0
  870. package/dist/modes/interactive/components/review-tools-selector.js.map +1 -0
  871. package/dist/modes/interactive/components/scoped-models-selector.d.ts +42 -0
  872. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  873. package/dist/modes/interactive/components/scoped-models-selector.js +290 -0
  874. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
  875. package/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
  876. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  877. package/dist/modes/interactive/components/session-selector-search.js +155 -0
  878. package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
  879. package/dist/modes/interactive/components/session-selector.d.ts +95 -0
  880. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
  881. package/dist/modes/interactive/components/session-selector.js +856 -0
  882. package/dist/modes/interactive/components/session-selector.js.map +1 -0
  883. package/dist/modes/interactive/components/settings-selector.d.ts +77 -0
  884. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
  885. package/dist/modes/interactive/components/settings-selector.js +484 -0
  886. package/dist/modes/interactive/components/settings-selector.js.map +1 -0
  887. package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  888. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  889. package/dist/modes/interactive/components/show-images-selector.js +39 -0
  890. package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
  891. package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  892. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  893. package/dist/modes/interactive/components/skill-invocation-message.js +47 -0
  894. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
  895. package/dist/modes/interactive/components/streaming-render-coalescer.d.ts +29 -0
  896. package/dist/modes/interactive/components/streaming-render-coalescer.d.ts.map +1 -0
  897. package/dist/modes/interactive/components/streaming-render-coalescer.js +98 -0
  898. package/dist/modes/interactive/components/streaming-render-coalescer.js.map +1 -0
  899. package/dist/modes/interactive/components/subagent-inspector.d.ts +32 -0
  900. package/dist/modes/interactive/components/subagent-inspector.d.ts.map +1 -0
  901. package/dist/modes/interactive/components/subagent-inspector.js +439 -0
  902. package/dist/modes/interactive/components/subagent-inspector.js.map +1 -0
  903. package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  904. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
  905. package/dist/modes/interactive/components/theme-selector.js +50 -0
  906. package/dist/modes/interactive/components/theme-selector.js.map +1 -0
  907. package/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
  908. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  909. package/dist/modes/interactive/components/thinking-selector.js +52 -0
  910. package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
  911. package/dist/modes/interactive/components/tool-execution.d.ts +83 -0
  912. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
  913. package/dist/modes/interactive/components/tool-execution.js +421 -0
  914. package/dist/modes/interactive/components/tool-execution.js.map +1 -0
  915. package/dist/modes/interactive/components/tree-selector.d.ts +89 -0
  916. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
  917. package/dist/modes/interactive/components/tree-selector.js +1208 -0
  918. package/dist/modes/interactive/components/tree-selector.js.map +1 -0
  919. package/dist/modes/interactive/components/trust-selector.d.ts +23 -0
  920. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -0
  921. package/dist/modes/interactive/components/trust-selector.js +91 -0
  922. package/dist/modes/interactive/components/trust-selector.js.map +1 -0
  923. package/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
  924. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  925. package/dist/modes/interactive/components/user-message-selector.js +114 -0
  926. package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
  927. package/dist/modes/interactive/components/user-message.d.ts +9 -0
  928. package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
  929. package/dist/modes/interactive/components/user-message.js +42 -0
  930. package/dist/modes/interactive/components/user-message.js.map +1 -0
  931. package/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
  932. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  933. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  934. package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
  935. package/dist/modes/interactive/components/volt-announcement.d.ts +5 -0
  936. package/dist/modes/interactive/components/volt-announcement.d.ts.map +1 -0
  937. package/dist/modes/interactive/components/volt-announcement.js +15 -0
  938. package/dist/modes/interactive/components/volt-announcement.js.map +1 -0
  939. package/dist/modes/interactive/daemon-attach.d.ts +154 -0
  940. package/dist/modes/interactive/daemon-attach.d.ts.map +1 -0
  941. package/dist/modes/interactive/daemon-attach.js +552 -0
  942. package/dist/modes/interactive/daemon-attach.js.map +1 -0
  943. package/dist/modes/interactive/drain-viewer.d.ts +31 -0
  944. package/dist/modes/interactive/drain-viewer.d.ts.map +1 -0
  945. package/dist/modes/interactive/drain-viewer.js +166 -0
  946. package/dist/modes/interactive/drain-viewer.js.map +1 -0
  947. package/dist/modes/interactive/interactive-mode.d.ts +502 -0
  948. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
  949. package/dist/modes/interactive/interactive-mode.js +7007 -0
  950. package/dist/modes/interactive/interactive-mode.js.map +1 -0
  951. package/dist/modes/interactive/prompt-image-attachments.d.ts +34 -0
  952. package/dist/modes/interactive/prompt-image-attachments.d.ts.map +1 -0
  953. package/dist/modes/interactive/prompt-image-attachments.js +120 -0
  954. package/dist/modes/interactive/prompt-image-attachments.js.map +1 -0
  955. package/dist/modes/interactive/relay-stream-adapter.d.ts +19 -0
  956. package/dist/modes/interactive/relay-stream-adapter.d.ts.map +1 -0
  957. package/dist/modes/interactive/relay-stream-adapter.js +107 -0
  958. package/dist/modes/interactive/relay-stream-adapter.js.map +1 -0
  959. package/dist/modes/print-mode.d.ts +28 -0
  960. package/dist/modes/print-mode.d.ts.map +1 -0
  961. package/dist/modes/print-mode.js +132 -0
  962. package/dist/modes/print-mode.js.map +1 -0
  963. package/dist/modes/rpc/in-process-rpc-client.d.ts +31 -0
  964. package/dist/modes/rpc/in-process-rpc-client.d.ts.map +1 -0
  965. package/dist/modes/rpc/in-process-rpc-client.js +63 -0
  966. package/dist/modes/rpc/in-process-rpc-client.js.map +1 -0
  967. package/dist/modes/rpc/iroh-remote-agent-runtime.d.ts +61 -0
  968. package/dist/modes/rpc/iroh-remote-agent-runtime.d.ts.map +1 -0
  969. package/dist/modes/rpc/iroh-remote-agent-runtime.js +155 -0
  970. package/dist/modes/rpc/iroh-remote-agent-runtime.js.map +1 -0
  971. package/dist/modes/rpc/iroh-remote-rpc-mode.d.ts +69 -0
  972. package/dist/modes/rpc/iroh-remote-rpc-mode.d.ts.map +1 -0
  973. package/dist/modes/rpc/iroh-remote-rpc-mode.js +1223 -0
  974. package/dist/modes/rpc/iroh-remote-rpc-mode.js.map +1 -0
  975. package/dist/modes/rpc/jsonl.d.ts +2 -0
  976. package/dist/modes/rpc/jsonl.d.ts.map +1 -0
  977. package/dist/modes/rpc/jsonl.js +2 -0
  978. package/dist/modes/rpc/jsonl.js.map +1 -0
  979. package/dist/modes/rpc/rpc-client-base.d.ts +209 -0
  980. package/dist/modes/rpc/rpc-client-base.d.ts.map +1 -0
  981. package/dist/modes/rpc/rpc-client-base.js +530 -0
  982. package/dist/modes/rpc/rpc-client-base.js.map +1 -0
  983. package/dist/modes/rpc/rpc-client.d.ts +50 -0
  984. package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
  985. package/dist/modes/rpc/rpc-client.js +190 -0
  986. package/dist/modes/rpc/rpc-client.js.map +1 -0
  987. package/dist/modes/rpc/rpc-command-dispatcher.d.ts +43 -0
  988. package/dist/modes/rpc/rpc-command-dispatcher.d.ts.map +1 -0
  989. package/dist/modes/rpc/rpc-command-dispatcher.js +613 -0
  990. package/dist/modes/rpc/rpc-command-dispatcher.js.map +1 -0
  991. package/dist/modes/rpc/rpc-command-validation.d.ts +2 -0
  992. package/dist/modes/rpc/rpc-command-validation.d.ts.map +1 -0
  993. package/dist/modes/rpc/rpc-command-validation.js +207 -0
  994. package/dist/modes/rpc/rpc-command-validation.js.map +1 -0
  995. package/dist/modes/rpc/rpc-mode.d.ts +48 -0
  996. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
  997. package/dist/modes/rpc/rpc-mode.js +1089 -0
  998. package/dist/modes/rpc/rpc-mode.js.map +1 -0
  999. package/dist/modes/rpc/rpc-transport-client.d.ts +26 -0
  1000. package/dist/modes/rpc/rpc-transport-client.d.ts.map +1 -0
  1001. package/dist/modes/rpc/rpc-transport-client.js +76 -0
  1002. package/dist/modes/rpc/rpc-transport-client.js.map +1 -0
  1003. package/dist/modes/rpc/rpc-types.d.ts +2 -0
  1004. package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
  1005. package/dist/modes/rpc/rpc-types.js +2 -0
  1006. package/dist/modes/rpc/rpc-types.js.map +1 -0
  1007. package/dist/package-manager-cli.d.ts +28 -0
  1008. package/dist/package-manager-cli.d.ts.map +1 -0
  1009. package/dist/package-manager-cli.js +667 -0
  1010. package/dist/package-manager-cli.js.map +1 -0
  1011. package/dist/remote/integrated-runtime-retention.d.ts +17 -0
  1012. package/dist/remote/integrated-runtime-retention.d.ts.map +1 -0
  1013. package/dist/remote/integrated-runtime-retention.js +62 -0
  1014. package/dist/remote/integrated-runtime-retention.js.map +1 -0
  1015. package/dist/remote/iroh-native-adapter.cjs +19 -0
  1016. package/dist/sea/cli.d.ts +4 -0
  1017. package/dist/sea/cli.d.ts.map +1 -0
  1018. package/dist/sea/cli.js +4 -0
  1019. package/dist/sea/cli.js.map +1 -0
  1020. package/dist/sea/register-bedrock.d.ts +2 -0
  1021. package/dist/sea/register-bedrock.d.ts.map +1 -0
  1022. package/dist/sea/register-bedrock.js +4 -0
  1023. package/dist/sea/register-bedrock.js.map +1 -0
  1024. package/dist/store/catalog.d.ts +57 -0
  1025. package/dist/store/catalog.d.ts.map +1 -0
  1026. package/dist/store/catalog.js +331 -0
  1027. package/dist/store/catalog.js.map +1 -0
  1028. package/dist/store/inspector.d.ts +36 -0
  1029. package/dist/store/inspector.d.ts.map +1 -0
  1030. package/dist/store/inspector.js +578 -0
  1031. package/dist/store/inspector.js.map +1 -0
  1032. package/dist/store/install-plan.d.ts +26 -0
  1033. package/dist/store/install-plan.d.ts.map +1 -0
  1034. package/dist/store/install-plan.js +80 -0
  1035. package/dist/store/install-plan.js.map +1 -0
  1036. package/dist/store/render.d.ts +11 -0
  1037. package/dist/store/render.d.ts.map +1 -0
  1038. package/dist/store/render.js +153 -0
  1039. package/dist/store/render.js.map +1 -0
  1040. package/dist/store/resolver.d.ts +22 -0
  1041. package/dist/store/resolver.d.ts.map +1 -0
  1042. package/dist/store/resolver.js +207 -0
  1043. package/dist/store/resolver.js.map +1 -0
  1044. package/dist/store/store-cli.d.ts +7 -0
  1045. package/dist/store/store-cli.d.ts.map +1 -0
  1046. package/dist/store/store-cli.js +636 -0
  1047. package/dist/store/store-cli.js.map +1 -0
  1048. package/dist/store/targets.d.ts +21 -0
  1049. package/dist/store/targets.d.ts.map +1 -0
  1050. package/dist/store/targets.js +55 -0
  1051. package/dist/store/targets.js.map +1 -0
  1052. package/dist/utils/ansi.d.ts +2 -0
  1053. package/dist/utils/ansi.d.ts.map +1 -0
  1054. package/dist/utils/ansi.js +52 -0
  1055. package/dist/utils/ansi.js.map +1 -0
  1056. package/dist/utils/changelog.d.ts +22 -0
  1057. package/dist/utils/changelog.d.ts.map +1 -0
  1058. package/dist/utils/changelog.js +165 -0
  1059. package/dist/utils/changelog.js.map +1 -0
  1060. package/dist/utils/child-process.d.ts +18 -0
  1061. package/dist/utils/child-process.d.ts.map +1 -0
  1062. package/dist/utils/child-process.js +106 -0
  1063. package/dist/utils/child-process.js.map +1 -0
  1064. package/dist/utils/clipboard-image.d.ts +11 -0
  1065. package/dist/utils/clipboard-image.d.ts.map +1 -0
  1066. package/dist/utils/clipboard-image.js +245 -0
  1067. package/dist/utils/clipboard-image.js.map +1 -0
  1068. package/dist/utils/clipboard.d.ts +2 -0
  1069. package/dist/utils/clipboard.d.ts.map +1 -0
  1070. package/dist/utils/clipboard.js +94 -0
  1071. package/dist/utils/clipboard.js.map +1 -0
  1072. package/dist/utils/deprecation.d.ts +4 -0
  1073. package/dist/utils/deprecation.d.ts.map +1 -0
  1074. package/dist/utils/deprecation.js +13 -0
  1075. package/dist/utils/deprecation.js.map +1 -0
  1076. package/dist/utils/durable-atomic-write.d.ts +46 -0
  1077. package/dist/utils/durable-atomic-write.d.ts.map +1 -0
  1078. package/dist/utils/durable-atomic-write.js +104 -0
  1079. package/dist/utils/durable-atomic-write.js.map +1 -0
  1080. package/dist/utils/frontmatter.d.ts +8 -0
  1081. package/dist/utils/frontmatter.d.ts.map +1 -0
  1082. package/dist/utils/frontmatter.js +26 -0
  1083. package/dist/utils/frontmatter.js.map +1 -0
  1084. package/dist/utils/fs-watch.d.ts +5 -0
  1085. package/dist/utils/fs-watch.d.ts.map +1 -0
  1086. package/dist/utils/fs-watch.js +25 -0
  1087. package/dist/utils/fs-watch.js.map +1 -0
  1088. package/dist/utils/git.d.ts +26 -0
  1089. package/dist/utils/git.d.ts.map +1 -0
  1090. package/dist/utils/git.js +195 -0
  1091. package/dist/utils/git.js.map +1 -0
  1092. package/dist/utils/html.d.ts +7 -0
  1093. package/dist/utils/html.d.ts.map +1 -0
  1094. package/dist/utils/html.js +40 -0
  1095. package/dist/utils/html.js.map +1 -0
  1096. package/dist/utils/ignore-files.d.ts +5 -0
  1097. package/dist/utils/ignore-files.d.ts.map +1 -0
  1098. package/dist/utils/ignore-files.js +58 -0
  1099. package/dist/utils/ignore-files.js.map +1 -0
  1100. package/dist/utils/image-codec.d.ts +22 -0
  1101. package/dist/utils/image-codec.d.ts.map +1 -0
  1102. package/dist/utils/image-codec.js +35 -0
  1103. package/dist/utils/image-codec.js.map +1 -0
  1104. package/dist/utils/image-convert.d.ts +9 -0
  1105. package/dist/utils/image-convert.d.ts.map +1 -0
  1106. package/dist/utils/image-convert.js +26 -0
  1107. package/dist/utils/image-convert.js.map +1 -0
  1108. package/dist/utils/image-resize-core.d.ts +31 -0
  1109. package/dist/utils/image-resize-core.d.ts.map +1 -0
  1110. package/dist/utils/image-resize-core.js +181 -0
  1111. package/dist/utils/image-resize-core.js.map +1 -0
  1112. package/dist/utils/image-resize-worker.d.ts +2 -0
  1113. package/dist/utils/image-resize-worker.d.ts.map +1 -0
  1114. package/dist/utils/image-resize-worker.js +31 -0
  1115. package/dist/utils/image-resize-worker.js.map +1 -0
  1116. package/dist/utils/image-resize.d.ts +15 -0
  1117. package/dist/utils/image-resize.d.ts.map +1 -0
  1118. package/dist/utils/image-resize.js +92 -0
  1119. package/dist/utils/image-resize.js.map +1 -0
  1120. package/dist/utils/json.d.ts +3 -0
  1121. package/dist/utils/json.d.ts.map +1 -0
  1122. package/dist/utils/json.js +7 -0
  1123. package/dist/utils/json.js.map +1 -0
  1124. package/dist/utils/mime.d.ts +3 -0
  1125. package/dist/utils/mime.d.ts.map +1 -0
  1126. package/dist/utils/mime.js +69 -0
  1127. package/dist/utils/mime.js.map +1 -0
  1128. package/dist/utils/npm-spec.d.ts +9 -0
  1129. package/dist/utils/npm-spec.d.ts.map +1 -0
  1130. package/dist/utils/npm-spec.js +15 -0
  1131. package/dist/utils/npm-spec.js.map +1 -0
  1132. package/dist/utils/open-browser.d.ts +9 -0
  1133. package/dist/utils/open-browser.d.ts.map +1 -0
  1134. package/dist/utils/open-browser.js +22 -0
  1135. package/dist/utils/open-browser.js.map +1 -0
  1136. package/dist/utils/paths.d.ts +31 -0
  1137. package/dist/utils/paths.d.ts.map +1 -0
  1138. package/dist/utils/paths.js +92 -0
  1139. package/dist/utils/paths.js.map +1 -0
  1140. package/dist/utils/private-files.d.ts +21 -0
  1141. package/dist/utils/private-files.d.ts.map +1 -0
  1142. package/dist/utils/private-files.js +103 -0
  1143. package/dist/utils/private-files.js.map +1 -0
  1144. package/dist/utils/process-env.d.ts +2 -0
  1145. package/dist/utils/process-env.d.ts.map +1 -0
  1146. package/dist/utils/process-env.js +31 -0
  1147. package/dist/utils/process-env.js.map +1 -0
  1148. package/dist/utils/shell.d.ts +30 -0
  1149. package/dist/utils/shell.d.ts.map +1 -0
  1150. package/dist/utils/shell.js +195 -0
  1151. package/dist/utils/shell.js.map +1 -0
  1152. package/dist/utils/sleep.d.ts +5 -0
  1153. package/dist/utils/sleep.d.ts.map +1 -0
  1154. package/dist/utils/sleep.js +17 -0
  1155. package/dist/utils/sleep.js.map +1 -0
  1156. package/dist/utils/syntax-highlight.d.ts +18 -0
  1157. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  1158. package/dist/utils/syntax-highlight.js +139 -0
  1159. package/dist/utils/syntax-highlight.js.map +1 -0
  1160. package/dist/utils/tools-manager.d.ts +3 -0
  1161. package/dist/utils/tools-manager.d.ts.map +1 -0
  1162. package/dist/utils/tools-manager.js +328 -0
  1163. package/dist/utils/tools-manager.js.map +1 -0
  1164. package/dist/utils/version-check.d.ts +15 -0
  1165. package/dist/utils/version-check.d.ts.map +1 -0
  1166. package/dist/utils/version-check.js +61 -0
  1167. package/dist/utils/version-check.js.map +1 -0
  1168. package/dist/utils/volt-user-agent.d.ts +2 -0
  1169. package/dist/utils/volt-user-agent.d.ts.map +1 -0
  1170. package/dist/utils/volt-user-agent.js +5 -0
  1171. package/dist/utils/volt-user-agent.js.map +1 -0
  1172. package/dist/utils/windows-self-update.d.ts +3 -0
  1173. package/dist/utils/windows-self-update.d.ts.map +1 -0
  1174. package/dist/utils/windows-self-update.js +77 -0
  1175. package/dist/utils/windows-self-update.js.map +1 -0
  1176. package/docs/compaction.md +394 -0
  1177. package/docs/containerization.md +111 -0
  1178. package/docs/custom-provider.md +737 -0
  1179. package/docs/daemon.md +190 -0
  1180. package/docs/development.md +70 -0
  1181. package/docs/docs.json +176 -0
  1182. package/docs/extensions.md +2692 -0
  1183. package/docs/images/exy.png +0 -0
  1184. package/docs/images/interactive-mode.png +0 -0
  1185. package/docs/images/tree-view.png +0 -0
  1186. package/docs/index.md +82 -0
  1187. package/docs/iroh-remote-access-design.md +340 -0
  1188. package/docs/iroh-remote-protocol.md +431 -0
  1189. package/docs/json.md +87 -0
  1190. package/docs/keybindings.md +200 -0
  1191. package/docs/live-shared-session-daemon-design.md +1090 -0
  1192. package/docs/lsp.md +143 -0
  1193. package/docs/mcp.md +1044 -0
  1194. package/docs/models.md +495 -0
  1195. package/docs/packages.md +230 -0
  1196. package/docs/prompt-templates.md +108 -0
  1197. package/docs/providers.md +274 -0
  1198. package/docs/quickstart.md +165 -0
  1199. package/docs/rpc.md +2050 -0
  1200. package/docs/sdk.md +1267 -0
  1201. package/docs/security.md +139 -0
  1202. package/docs/session-format.md +412 -0
  1203. package/docs/sessions.md +145 -0
  1204. package/docs/settings.md +371 -0
  1205. package/docs/shell-aliases.md +13 -0
  1206. package/docs/skills.md +243 -0
  1207. package/docs/subagents-design.md +419 -0
  1208. package/docs/terminal-setup.md +148 -0
  1209. package/docs/termux.md +127 -0
  1210. package/docs/themes.md +295 -0
  1211. package/docs/tla/ClientAuth.cfg +16 -0
  1212. package/docs/tla/ClientAuth.tla +205 -0
  1213. package/docs/tla/ClientConn.cfg +16 -0
  1214. package/docs/tla/ClientConn.tla +265 -0
  1215. package/docs/tla/LeaseBroker.cfg +43 -0
  1216. package/docs/tla/LeaseBroker.tla +563 -0
  1217. package/docs/tla/PLAN.md +240 -0
  1218. package/docs/tla/PushOrdering.cfg +17 -0
  1219. package/docs/tla/PushOrdering.tla +183 -0
  1220. package/docs/tla/README.md +205 -0
  1221. package/docs/tla/RelayViewer.cfg +26 -0
  1222. package/docs/tla/RelayViewer.tla +299 -0
  1223. package/docs/tla/SessionTarget.cfg +18 -0
  1224. package/docs/tla/SessionTarget.tla +192 -0
  1225. package/docs/tla/check.sh +34 -0
  1226. package/docs/tmux.md +63 -0
  1227. package/docs/tui.md +949 -0
  1228. package/docs/usage.md +482 -0
  1229. package/docs/windows.md +17 -0
  1230. package/docs/worktrees-design.md +605 -0
  1231. package/examples/README.md +28 -0
  1232. package/examples/extensions/README.md +211 -0
  1233. package/examples/extensions/auto-commit-on-exit.ts +49 -0
  1234. package/examples/extensions/bash-spawn-hook.ts +30 -0
  1235. package/examples/extensions/bookmark.ts +50 -0
  1236. package/examples/extensions/border-status-editor.ts +150 -0
  1237. package/examples/extensions/built-in-tool-renderer.ts +249 -0
  1238. package/examples/extensions/claude-rules.ts +86 -0
  1239. package/examples/extensions/commands.ts +72 -0
  1240. package/examples/extensions/confirm-destructive.ts +59 -0
  1241. package/examples/extensions/custom-compaction.ts +127 -0
  1242. package/examples/extensions/custom-footer.ts +64 -0
  1243. package/examples/extensions/custom-header.ts +72 -0
  1244. package/examples/extensions/custom-provider-anthropic/index.ts +604 -0
  1245. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  1246. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  1247. package/examples/extensions/custom-provider-gitlab-duo/index.ts +400 -0
  1248. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  1249. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
  1250. package/examples/extensions/dirty-repo-guard.ts +56 -0
  1251. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  1252. package/examples/extensions/dynamic-resources/dynamic.json +79 -0
  1253. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  1254. package/examples/extensions/dynamic-resources/index.ts +15 -0
  1255. package/examples/extensions/dynamic-tools.ts +74 -0
  1256. package/examples/extensions/event-bus.ts +43 -0
  1257. package/examples/extensions/file-trigger.ts +41 -0
  1258. package/examples/extensions/git-checkpoint.ts +53 -0
  1259. package/examples/extensions/git-merge-and-resolve.ts +115 -0
  1260. package/examples/extensions/github-issue-autocomplete.ts +185 -0
  1261. package/examples/extensions/gondolin/index.ts +531 -0
  1262. package/examples/extensions/gondolin/package-lock.json +185 -0
  1263. package/examples/extensions/gondolin/package.json +19 -0
  1264. package/examples/extensions/handoff.ts +191 -0
  1265. package/examples/extensions/hello.ts +26 -0
  1266. package/examples/extensions/hidden-thinking-label.ts +53 -0
  1267. package/examples/extensions/inline-bash.ts +94 -0
  1268. package/examples/extensions/input-transform-streaming.ts +39 -0
  1269. package/examples/extensions/input-transform.ts +43 -0
  1270. package/examples/extensions/interactive-shell.ts +196 -0
  1271. package/examples/extensions/mac-system-theme.ts +47 -0
  1272. package/examples/extensions/message-renderer.ts +59 -0
  1273. package/examples/extensions/minimal-mode.ts +426 -0
  1274. package/examples/extensions/modal-editor.ts +85 -0
  1275. package/examples/extensions/model-status.ts +31 -0
  1276. package/examples/extensions/notify.ts +55 -0
  1277. package/examples/extensions/overlay-qa-tests.ts +1450 -0
  1278. package/examples/extensions/overlay-test.ts +153 -0
  1279. package/examples/extensions/permission-gate.ts +34 -0
  1280. package/examples/extensions/pirate.ts +47 -0
  1281. package/examples/extensions/plan-mode/README.md +65 -0
  1282. package/examples/extensions/plan-mode/index.ts +340 -0
  1283. package/examples/extensions/plan-mode/utils.ts +168 -0
  1284. package/examples/extensions/preset.ts +436 -0
  1285. package/examples/extensions/project-trust.ts +64 -0
  1286. package/examples/extensions/prompt-customizer.ts +97 -0
  1287. package/examples/extensions/protected-paths.ts +30 -0
  1288. package/examples/extensions/provider-payload.ts +18 -0
  1289. package/examples/extensions/qna.ts +122 -0
  1290. package/examples/extensions/question.ts +277 -0
  1291. package/examples/extensions/questionnaire.ts +440 -0
  1292. package/examples/extensions/rainbow-editor.ts +88 -0
  1293. package/examples/extensions/reload-runtime.ts +37 -0
  1294. package/examples/extensions/rpc-demo.ts +118 -0
  1295. package/examples/extensions/sandbox/index.ts +321 -0
  1296. package/examples/extensions/sandbox/package-lock.json +92 -0
  1297. package/examples/extensions/sandbox/package.json +19 -0
  1298. package/examples/extensions/send-user-message.ts +97 -0
  1299. package/examples/extensions/session-name.ts +27 -0
  1300. package/examples/extensions/shutdown-command.ts +63 -0
  1301. package/examples/extensions/snake.ts +343 -0
  1302. package/examples/extensions/space-invaders.ts +560 -0
  1303. package/examples/extensions/ssh.ts +220 -0
  1304. package/examples/extensions/status-line.ts +32 -0
  1305. package/examples/extensions/structured-output.ts +65 -0
  1306. package/examples/extensions/subagent/README.md +175 -0
  1307. package/examples/extensions/subagent/agents/planner.md +37 -0
  1308. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  1309. package/examples/extensions/subagent/agents/scout.md +50 -0
  1310. package/examples/extensions/subagent/agents/worker.md +24 -0
  1311. package/examples/extensions/subagent/agents.ts +126 -0
  1312. package/examples/extensions/subagent/index.ts +1009 -0
  1313. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  1314. package/examples/extensions/subagent/prompts/implement.md +10 -0
  1315. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  1316. package/examples/extensions/summarize.ts +206 -0
  1317. package/examples/extensions/system-prompt-header.ts +17 -0
  1318. package/examples/extensions/tic-tac-toe.ts +1008 -0
  1319. package/examples/extensions/timed-confirm.ts +70 -0
  1320. package/examples/extensions/titlebar-spinner.ts +58 -0
  1321. package/examples/extensions/todo.ts +297 -0
  1322. package/examples/extensions/tool-override.ts +144 -0
  1323. package/examples/extensions/tools.ts +146 -0
  1324. package/examples/extensions/trigger-compact.ts +50 -0
  1325. package/examples/extensions/truncated-tool.ts +195 -0
  1326. package/examples/extensions/widget-placement.ts +9 -0
  1327. package/examples/extensions/with-deps/index.ts +32 -0
  1328. package/examples/extensions/with-deps/package-lock.json +31 -0
  1329. package/examples/extensions/with-deps/package.json +22 -0
  1330. package/examples/extensions/working-indicator.ts +123 -0
  1331. package/examples/extensions/working-message-test.ts +25 -0
  1332. package/examples/remote/firebase-push-relay/README.md +79 -0
  1333. package/examples/remote/firebase-push-relay/firebase.json +12 -0
  1334. package/examples/remote/firebase-push-relay/firestore.indexes.json +11 -0
  1335. package/examples/remote/firebase-push-relay/firestore.rules +9 -0
  1336. package/examples/remote/firebase-push-relay/functions/core.js +511 -0
  1337. package/examples/remote/firebase-push-relay/functions/core.test.js +273 -0
  1338. package/examples/remote/firebase-push-relay/functions/index.js +413 -0
  1339. package/examples/remote/firebase-push-relay/functions/package-lock.json +2974 -0
  1340. package/examples/remote/firebase-push-relay/functions/package.json +18 -0
  1341. package/examples/remote/iroh-sidecar/README.md +211 -0
  1342. package/examples/remote/iroh-sidecar/client.mjs +554 -0
  1343. package/examples/remote/iroh-sidecar/common.mjs +195 -0
  1344. package/examples/remote/iroh-sidecar/host.mjs +4 -0
  1345. package/examples/remote/iroh-sidecar/package-lock.json +213 -0
  1346. package/examples/remote/iroh-sidecar/package.json +13 -0
  1347. package/examples/remote/iroh-sidecar/source-aware-run.mjs +41 -0
  1348. package/examples/rpc-extension-ui.ts +632 -0
  1349. package/examples/sdk/01-minimal.ts +26 -0
  1350. package/examples/sdk/02-custom-model.ts +53 -0
  1351. package/examples/sdk/03-custom-prompt.ts +70 -0
  1352. package/examples/sdk/04-skills.ts +55 -0
  1353. package/examples/sdk/05-tools.ts +48 -0
  1354. package/examples/sdk/06-extensions.ts +94 -0
  1355. package/examples/sdk/07-context-files.ts +42 -0
  1356. package/examples/sdk/08-prompt-templates.ts +51 -0
  1357. package/examples/sdk/09-api-keys-and-oauth.ts +52 -0
  1358. package/examples/sdk/10-settings.ts +53 -0
  1359. package/examples/sdk/11-sessions.ts +52 -0
  1360. package/examples/sdk/12-full-control.ts +78 -0
  1361. package/examples/sdk/13-session-runtime.ts +67 -0
  1362. package/examples/sdk/README.md +147 -0
  1363. package/npm-shrinkwrap.json +3442 -0
  1364. package/package.json +125 -19
@@ -0,0 +1,3158 @@
1
+ /**
2
+ * AgentSession - Core abstraction for agent lifecycle and session management.
3
+ *
4
+ * This class is shared between all run modes (interactive, print, rpc).
5
+ * It encapsulates:
6
+ * - Agent state access
7
+ * - Event subscription with automatic session persistence
8
+ * - Model and thinking level management
9
+ * - Compaction (manual and auto)
10
+ * - Bash execution
11
+ * - Session switching and branching
12
+ *
13
+ * Modes use this class and add their own I/O layer on top.
14
+ */
15
+ import { readFileSync } from "node:fs";
16
+ import { basename, dirname } from "node:path";
17
+ import { clampThinkingLevel, cleanupSessionResources, completeSimple, getSupportedThinkingLevels, isContextOverflow, modelsAreEqual, streamSimple, } from "@hansjm10/volt-ai";
18
+ import { writeDurableAtomicFileSync } from "../utils/durable-atomic-write.js";
19
+ import { stripFrontmatter } from "../utils/frontmatter.js";
20
+ import { resolvePath } from "../utils/paths.js";
21
+ import { PRIVATE_DIRECTORY_MODE, PRIVATE_FILE_MODE } from "../utils/private-files.js";
22
+ import { sleep } from "../utils/sleep.js";
23
+ import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
24
+ import { executeBashWithOperations } from "./bash-executor.js";
25
+ import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
26
+ import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
27
+ import { exportSessionToHtml } from "./export-html/index.js";
28
+ import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
29
+ import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
30
+ import { emitSessionShutdownEvent } from "./extensions/runner.js";
31
+ import { resolveLspConfig } from "./lsp/config.js";
32
+ import { LspManager } from "./lsp/manager.js";
33
+ import { createMcpDirectToolDefinitions } from "./mcp/direct-tools.js";
34
+ import { expandPromptTemplate } from "./prompt-templates.js";
35
+ import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
36
+ import { createSyntheticSourceInfo } from "./source-info.js";
37
+ import { buildSystemPrompt } from "./system-prompt.js";
38
+ import { getThemeByName, theme } from "./theme/runtime.js";
39
+ import { createLocalBashOperations } from "./tools/bash.js";
40
+ import { BRAVE_SEARCH_AUTH_PROVIDER, createAllToolDefinitions, createDefaultWebSearchOperations, DEFAULT_ACTIVE_TOOL_NAMES, } from "./tools/index.js";
41
+ import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
42
+ /**
43
+ * Parse a skill block from message text.
44
+ * Returns null if the text doesn't contain a skill block.
45
+ */
46
+ export function parseSkillBlock(text) {
47
+ const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
48
+ if (!match)
49
+ return null;
50
+ return {
51
+ name: match[1],
52
+ location: match[2],
53
+ content: match[3],
54
+ userMessage: match[4]?.trim() || undefined,
55
+ };
56
+ }
57
+ // ============================================================================
58
+ // Constants
59
+ // ============================================================================
60
+ /** Standard thinking levels */
61
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
62
+ // ============================================================================
63
+ // AgentSession Class
64
+ // ============================================================================
65
+ export class AgentSession {
66
+ agent;
67
+ sessionManager;
68
+ settingsManager;
69
+ _scopedModels;
70
+ // Event subscription state
71
+ _unsubscribeAgent;
72
+ _eventListeners = [];
73
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
74
+ _steeringMessages = [];
75
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
76
+ _followUpMessages = [];
77
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
78
+ _pendingNextTurnMessages = [];
79
+ /** Tracks core agent runs, including retry and compaction continuations. */
80
+ _activePromptRuns = new Set();
81
+ /** Tracks complete prompt calls, including pre-prompt recovery and message construction. */
82
+ _activePromptTransactions = new Map();
83
+ /** Tracks standalone session operations such as manual compaction and tree navigation. */
84
+ _activeSessionOperations = new Set();
85
+ _extensionCommandTransactions = new Set();
86
+ _activeExtensionCommandHandlers = 0;
87
+ // Compaction state
88
+ _compactionAbortController = undefined;
89
+ _autoCompactionAbortController = undefined;
90
+ _activeCompaction = undefined;
91
+ _overflowRecoveryAttempted = false;
92
+ /** Set when shouldStopAfterTurn interrupted the run for a threshold compaction. */
93
+ _proactiveCompactionStopped = false;
94
+ /**
95
+ * Guards against repeated proactive stops when compaction cannot make progress.
96
+ * Re-armed by a successful compaction or the next user prompt.
97
+ */
98
+ _proactiveCompactionAttempted = false;
99
+ _drainFollowUpsOnNextContinuation = false;
100
+ // Branch summarization state
101
+ _branchSummaryAbortController = undefined;
102
+ // Retry state
103
+ _retryAbortController = undefined;
104
+ _retryAttempt = 0;
105
+ /** Incremented by abort() so in-flight session continuations cannot start a new core run. */
106
+ _abortGeneration = 0;
107
+ _abortPromise;
108
+ // Bash execution state
109
+ _bashAbortController = undefined;
110
+ _pendingBashMessages = [];
111
+ // Extension system
112
+ _extensionRunner;
113
+ _turnIndex = 0;
114
+ _resourceLoader;
115
+ _customTools;
116
+ _baseToolDefinitions = new Map();
117
+ _cwd;
118
+ _extensionRunnerRef;
119
+ _initialActiveToolNames;
120
+ _allowedToolNames;
121
+ _allowUnlistedExtensionTools;
122
+ _excludedToolNames;
123
+ _baseToolsOverride;
124
+ _sessionStartEvent;
125
+ _extensionUIContext;
126
+ _extensionMode = "print";
127
+ _extensionCommandContextActions;
128
+ _extensionAbortHandler;
129
+ _extensionShutdownHandler;
130
+ _extensionErrorListener;
131
+ _extensionErrorUnsubscriber;
132
+ _disposed = false;
133
+ // Model registry for API key resolution
134
+ _modelRegistry;
135
+ _fastModeRestoreThinkingLevel;
136
+ // LSP diagnostics manager (created unless lsp.enabled is false)
137
+ _lspManager;
138
+ _hostInteraction;
139
+ _subagentToolManager;
140
+ _mcpManager;
141
+ _mcpManagerFactory;
142
+ _unsubscribeMcpManager;
143
+ // Tool registry for extension getTools/setTools
144
+ _toolRegistry = new Map();
145
+ _toolDefinitions = new Map();
146
+ _toolPromptSnippets = new Map();
147
+ _toolPromptGuidelines = new Map();
148
+ // Base system prompt (without extension appends) - used to apply fresh appends each turn
149
+ _baseSystemPrompt = "";
150
+ _baseSystemPromptOptions;
151
+ constructor(config) {
152
+ this.agent = config.agent;
153
+ this.sessionManager = config.sessionManager;
154
+ this.settingsManager = config.settingsManager;
155
+ this._scopedModels = config.scopedModels ?? [];
156
+ this._resourceLoader = config.resourceLoader;
157
+ this._customTools = config.customTools ?? [];
158
+ this._cwd = config.cwd;
159
+ this._modelRegistry = config.modelRegistry;
160
+ this._extensionRunnerRef = config.extensionRunnerRef;
161
+ this._initialActiveToolNames = config.initialActiveToolNames;
162
+ this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
163
+ this._allowUnlistedExtensionTools = config.allowUnlistedExtensionTools ?? false;
164
+ this._excludedToolNames = config.excludedToolNames ? new Set(config.excludedToolNames) : undefined;
165
+ this._baseToolsOverride = config.baseToolsOverride;
166
+ this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
167
+ this._hostInteraction = config.hostInteraction;
168
+ this._subagentToolManager = config.subagentToolManager;
169
+ this._mcpManager = config.mcpManager;
170
+ this._mcpManagerFactory = config.mcpManagerFactory;
171
+ this._attachMcpManagerEvents();
172
+ // Always subscribe to agent events for internal handling
173
+ // (session persistence, extensions, auto-compaction, retry logic)
174
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
175
+ this._installAgentToolHooks();
176
+ this.agent.shouldStopAfterTurn = (context) => this._shouldStopForProactiveCompaction(context);
177
+ this._buildRuntime({
178
+ activeToolNames: this._initialActiveToolNames,
179
+ includeAllExtensionTools: true,
180
+ });
181
+ }
182
+ /** Model registry for API key resolution and model discovery */
183
+ get modelRegistry() {
184
+ return this._modelRegistry;
185
+ }
186
+ setHostInteraction(hostInteraction) {
187
+ this._hostInteraction = hostInteraction;
188
+ this._lspManager?.setHostInteraction(hostInteraction);
189
+ }
190
+ /** LSP status for the /lsp command. */
191
+ getLspStatus() {
192
+ return {
193
+ enabled: this._lspManager !== undefined,
194
+ servers: this._lspManager?.getStatus() ?? [],
195
+ traceFile: this._lspManager?.getTraceFile(),
196
+ };
197
+ }
198
+ /** Enable or disable LSP protocol tracing at runtime. */
199
+ setLspTraceFile(filePath) {
200
+ return this._lspManager?.setTraceFile(filePath) ?? Promise.resolve();
201
+ }
202
+ /** Stop LSP tracing from a synchronous process teardown path. */
203
+ closeLspTraceSync() {
204
+ this._lspManager?.closeTraceSync();
205
+ }
206
+ /** Stop all running language servers; they respawn lazily on next use. Returns the number stopped. */
207
+ restartLspServers() {
208
+ return this._lspManager?.restart() ?? 0;
209
+ }
210
+ async _getRequiredRequestAuth(model) {
211
+ const result = await this._modelRegistry.getApiKeyAndHeaders(model);
212
+ if (!result.ok) {
213
+ if (result.error.startsWith("No API key found")) {
214
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
215
+ }
216
+ throw new Error(result.error);
217
+ }
218
+ if (result.apiKey) {
219
+ return { apiKey: result.apiKey, headers: result.headers, env: result.env };
220
+ }
221
+ const isOAuth = this._modelRegistry.isUsingOAuth(model);
222
+ if (isOAuth) {
223
+ throw new Error(`Authentication failed for "${model.provider}". ` +
224
+ `Credentials may have expired or network is unavailable. ` +
225
+ `Run '/login ${model.provider}' to re-authenticate.`);
226
+ }
227
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
228
+ }
229
+ async _getCompactionRequestAuth(model) {
230
+ if (this.agent.streamFn === streamSimple) {
231
+ return this._getRequiredRequestAuth(model);
232
+ }
233
+ const result = await this._modelRegistry.getApiKeyAndHeaders(model);
234
+ return result.ok ? { apiKey: result.apiKey, headers: result.headers, env: result.env } : {};
235
+ }
236
+ /**
237
+ * Install tool hooks once on the Agent instance.
238
+ *
239
+ * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
240
+ * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
241
+ * registered tool execution to the extension context. Tool call and tool result interception now
242
+ * happens here instead of in wrappers.
243
+ */
244
+ _installAgentToolHooks() {
245
+ this.agent.beforeToolCall = async ({ toolCall, args }) => {
246
+ const runner = this._extensionRunner;
247
+ if (!runner.hasHandlers("tool_call")) {
248
+ return undefined;
249
+ }
250
+ try {
251
+ return await runner.emitToolCall({
252
+ type: "tool_call",
253
+ toolName: toolCall.name,
254
+ toolCallId: toolCall.id,
255
+ input: args,
256
+ });
257
+ }
258
+ catch (err) {
259
+ if (err instanceof Error) {
260
+ throw err;
261
+ }
262
+ throw new Error(`Extension failed, blocking execution: ${String(err)}`);
263
+ }
264
+ };
265
+ this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
266
+ const runner = this._extensionRunner;
267
+ if (!runner.hasHandlers("tool_result")) {
268
+ return undefined;
269
+ }
270
+ const hookResult = await runner.emitToolResult({
271
+ type: "tool_result",
272
+ toolName: toolCall.name,
273
+ toolCallId: toolCall.id,
274
+ input: args,
275
+ content: result.content,
276
+ details: result.details,
277
+ isError,
278
+ });
279
+ if (!hookResult) {
280
+ return undefined;
281
+ }
282
+ return {
283
+ content: hookResult.content,
284
+ details: hookResult.details,
285
+ isError: hookResult.isError ?? isError,
286
+ };
287
+ };
288
+ }
289
+ // =========================================================================
290
+ // Event Subscription
291
+ // =========================================================================
292
+ /** Emit an event to all listeners */
293
+ _emit(event) {
294
+ for (const l of this._eventListeners) {
295
+ l(event);
296
+ }
297
+ }
298
+ _emitQueueUpdate() {
299
+ this._emit({
300
+ type: "queue_update",
301
+ steering: [...this._steeringMessages],
302
+ followUp: [...this._followUpMessages],
303
+ });
304
+ }
305
+ // Track last assistant message for auto-compaction check
306
+ _lastAssistantMessage = undefined;
307
+ /** Internal handler for agent events - shared by subscribe and reconnect */
308
+ _handleAgentEvent = async (event) => {
309
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
310
+ // This ensures the UI sees the updated queue state
311
+ if (event.type === "message_start" && event.message.role === "user") {
312
+ this._overflowRecoveryAttempted = false;
313
+ this._proactiveCompactionAttempted = false;
314
+ const messageText = this._getUserMessageText(event.message);
315
+ if (messageText) {
316
+ // Check steering queue first
317
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
318
+ if (steeringIndex !== -1) {
319
+ this._steeringMessages.splice(steeringIndex, 1);
320
+ this._emitQueueUpdate();
321
+ }
322
+ else {
323
+ // Check follow-up queue
324
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
325
+ if (followUpIndex !== -1) {
326
+ this._followUpMessages.splice(followUpIndex, 1);
327
+ this._emitQueueUpdate();
328
+ }
329
+ }
330
+ }
331
+ }
332
+ // Emit to extensions first
333
+ await this._emitExtensionEvent(event);
334
+ // Notify all listeners
335
+ this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
336
+ // Handle session persistence
337
+ if (event.type === "message_end") {
338
+ // Check if this is a custom message from extensions
339
+ if (event.message.role === "custom") {
340
+ // Persist as CustomMessageEntry
341
+ this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
342
+ }
343
+ else if (event.message.role === "user" ||
344
+ event.message.role === "assistant" ||
345
+ event.message.role === "toolResult") {
346
+ // Regular LLM message - persist as SessionMessageEntry
347
+ this.sessionManager.appendMessage(event.message);
348
+ }
349
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
350
+ // Track assistant message for auto-compaction (checked on agent_end)
351
+ if (event.message.role === "assistant") {
352
+ this._lastAssistantMessage = event.message;
353
+ const assistantMsg = event.message;
354
+ if (assistantMsg.stopReason !== "error") {
355
+ this._overflowRecoveryAttempted = false;
356
+ }
357
+ // Reset retry state immediately when the retry response completes.
358
+ if (assistantMsg.stopReason !== "error" && assistantMsg.stopReason !== "aborted") {
359
+ this._settleRetry(true);
360
+ }
361
+ else if (assistantMsg.stopReason === "aborted") {
362
+ this._settleRetry(false, "Retry cancelled");
363
+ }
364
+ }
365
+ }
366
+ };
367
+ _willRetryAfterAgentEnd(event) {
368
+ const settings = this.settingsManager.getRetrySettings();
369
+ if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
370
+ return false;
371
+ }
372
+ for (let i = event.messages.length - 1; i >= 0; i--) {
373
+ const message = event.messages[i];
374
+ if (message.role === "assistant") {
375
+ return this._isRetryableError(message);
376
+ }
377
+ }
378
+ return false;
379
+ }
380
+ _settleRetry(success, finalError) {
381
+ if (this._retryAttempt === 0) {
382
+ return;
383
+ }
384
+ const attempt = this._retryAttempt;
385
+ this._retryAttempt = 0;
386
+ this._emit({
387
+ type: "auto_retry_end",
388
+ success,
389
+ attempt,
390
+ ...(finalError ? { finalError } : {}),
391
+ });
392
+ }
393
+ /** Extract text content from a message */
394
+ _getUserMessageText(message) {
395
+ if (message.role !== "user")
396
+ return "";
397
+ const content = message.content;
398
+ if (typeof content === "string")
399
+ return content;
400
+ const textBlocks = content.filter((c) => c.type === "text");
401
+ return textBlocks.map((c) => c.text).join("");
402
+ }
403
+ /** Find the last assistant message in agent state (including aborted ones) */
404
+ _findLastAssistantMessage() {
405
+ const messages = this.agent.state.messages;
406
+ for (let i = messages.length - 1; i >= 0; i--) {
407
+ const msg = messages[i];
408
+ if (msg.role === "assistant") {
409
+ return msg;
410
+ }
411
+ }
412
+ return undefined;
413
+ }
414
+ _replaceMessageInPlace(target, replacement) {
415
+ // Agent-core stores the finalized message object in its state before emitting message_end.
416
+ // SessionManager persistence happens later in _handleAgentEvent() with event.message.
417
+ // Mutating this object in place keeps agent state, later turn/agent events, listeners,
418
+ // and the eventual SessionManager.appendMessage(event.message) persistence in sync.
419
+ if (target === replacement) {
420
+ return;
421
+ }
422
+ const targetRecord = target;
423
+ for (const key of Object.keys(targetRecord)) {
424
+ delete targetRecord[key];
425
+ }
426
+ Object.assign(targetRecord, replacement);
427
+ }
428
+ /** Emit extension events based on agent events */
429
+ async _emitExtensionEvent(event) {
430
+ if (event.type === "agent_start") {
431
+ this._turnIndex = 0;
432
+ await this._extensionRunner.emit({ type: "agent_start" });
433
+ }
434
+ else if (event.type === "agent_end") {
435
+ await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
436
+ }
437
+ else if (event.type === "turn_start") {
438
+ const extensionEvent = {
439
+ type: "turn_start",
440
+ turnIndex: this._turnIndex,
441
+ timestamp: Date.now(),
442
+ };
443
+ await this._extensionRunner.emit(extensionEvent);
444
+ }
445
+ else if (event.type === "turn_end") {
446
+ const extensionEvent = {
447
+ type: "turn_end",
448
+ turnIndex: this._turnIndex,
449
+ message: event.message,
450
+ toolResults: event.toolResults,
451
+ };
452
+ await this._extensionRunner.emit(extensionEvent);
453
+ this._turnIndex++;
454
+ }
455
+ else if (event.type === "message_start") {
456
+ const extensionEvent = {
457
+ type: "message_start",
458
+ message: event.message,
459
+ };
460
+ await this._extensionRunner.emit(extensionEvent);
461
+ }
462
+ else if (event.type === "message_update") {
463
+ const extensionEvent = {
464
+ type: "message_update",
465
+ message: event.message,
466
+ assistantMessageEvent: event.assistantMessageEvent,
467
+ };
468
+ await this._extensionRunner.emit(extensionEvent);
469
+ }
470
+ else if (event.type === "message_end") {
471
+ const extensionEvent = {
472
+ type: "message_end",
473
+ message: event.message,
474
+ };
475
+ const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
476
+ if (replacement) {
477
+ this._replaceMessageInPlace(event.message, replacement);
478
+ }
479
+ }
480
+ else if (event.type === "tool_execution_start") {
481
+ const extensionEvent = {
482
+ type: "tool_execution_start",
483
+ toolCallId: event.toolCallId,
484
+ toolName: event.toolName,
485
+ args: event.args,
486
+ };
487
+ await this._extensionRunner.emit(extensionEvent);
488
+ }
489
+ else if (event.type === "tool_execution_update") {
490
+ const extensionEvent = {
491
+ type: "tool_execution_update",
492
+ toolCallId: event.toolCallId,
493
+ toolName: event.toolName,
494
+ args: event.args,
495
+ partialResult: event.partialResult,
496
+ };
497
+ await this._extensionRunner.emit(extensionEvent);
498
+ }
499
+ else if (event.type === "tool_execution_end") {
500
+ const extensionEvent = {
501
+ type: "tool_execution_end",
502
+ toolCallId: event.toolCallId,
503
+ toolName: event.toolName,
504
+ result: event.result,
505
+ isError: event.isError,
506
+ };
507
+ await this._extensionRunner.emit(extensionEvent);
508
+ }
509
+ }
510
+ /**
511
+ * Subscribe to agent events.
512
+ * Session persistence is handled internally (saves messages on message_end).
513
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
514
+ */
515
+ subscribe(listener) {
516
+ this._eventListeners.push(listener);
517
+ // Return unsubscribe function for this specific listener
518
+ return () => {
519
+ const index = this._eventListeners.indexOf(listener);
520
+ if (index !== -1) {
521
+ this._eventListeners.splice(index, 1);
522
+ }
523
+ };
524
+ }
525
+ /**
526
+ * Temporarily disconnect from agent events.
527
+ * User listeners are preserved and will receive events again after resubscribe().
528
+ * Used internally during operations that need to pause event processing.
529
+ */
530
+ _disconnectFromAgent() {
531
+ if (this._unsubscribeAgent) {
532
+ this._unsubscribeAgent();
533
+ this._unsubscribeAgent = undefined;
534
+ }
535
+ }
536
+ /**
537
+ * Reconnect to agent events after _disconnectFromAgent().
538
+ * Preserves all existing listeners.
539
+ */
540
+ _reconnectToAgent() {
541
+ if (this._unsubscribeAgent)
542
+ return; // Already connected
543
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
544
+ }
545
+ /**
546
+ * Remove all listeners and disconnect from agent.
547
+ * Call this when completely done with the session.
548
+ */
549
+ dispose() {
550
+ if (this._disposed) {
551
+ return;
552
+ }
553
+ this._disposed = true;
554
+ try {
555
+ // Persist terminal markers for in-flight tool calls FIRST: dispose
556
+ // disconnects listeners synchronously below, so the aborted tool
557
+ // results the agent loop synthesizes after agent.abort() are never
558
+ // observed or persisted. Without this, a session disposed mid-tool-call
559
+ // (e.g. a daemon runtime torn down for a lease handoff) leaves a
560
+ // dangling toolCall in the transcript.
561
+ this._persistAbortedResultsForDanglingToolCalls();
562
+ this.abortRetry();
563
+ this.abortCompaction();
564
+ this.abortBranchSummary();
565
+ this.abortBash();
566
+ this.agent.abort();
567
+ // Drain queued steering/follow-up messages so a run that settles after
568
+ // dispose cannot restart via the queued-message continuation path.
569
+ this.agent.clearAllQueues();
570
+ this._lspManager?.dispose();
571
+ this._unsubscribeMcpManager?.();
572
+ this._unsubscribeMcpManager = undefined;
573
+ void this._subagentToolManager?.dispose?.().catch(() => undefined);
574
+ void this._mcpManager?.dispose();
575
+ }
576
+ catch {
577
+ // Dispose must succeed even if an abort hook throws.
578
+ }
579
+ this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured volt or command ctx after ctx.newSession(), ctx.fork(), ctx.switchSession(), or ctx.reload(). For newSession, fork, and switchSession, move post-replacement work into withSession and use the ctx passed to withSession. For reload, do not use the old ctx after await ctx.reload().");
580
+ // Unsubscribe the extension error listener: it may be wired to a live
581
+ // transport (RPC extension_error stream), and this session's generation
582
+ // must not surface anything there after dispose.
583
+ this._extensionErrorUnsubscriber?.();
584
+ this._extensionErrorUnsubscriber = undefined;
585
+ // Detach the Agent's payload/context hooks from this generation's runner.
586
+ // Guarded so a replacement generation's runner is never cleared.
587
+ if (this._extensionRunnerRef?.current === this._extensionRunner) {
588
+ this._extensionRunnerRef.current = undefined;
589
+ }
590
+ this._disconnectFromAgent();
591
+ this._eventListeners = [];
592
+ cleanupSessionResources(this.sessionId);
593
+ }
594
+ /**
595
+ * Append an aborted toolResult for every persisted toolCall on the current
596
+ * session path that has no persisted result, so a transcript closed mid-call
597
+ * resumes coherently instead of with a dangling call. Persistence-only: no
598
+ * events are emitted (dispose is tearing the listeners down), and the agent
599
+ * loop's own late aborted results are dropped by the _disposed guard.
600
+ */
601
+ _persistAbortedResultsForDanglingToolCalls() {
602
+ if (!this.isBusy) {
603
+ return;
604
+ }
605
+ try {
606
+ const context = this.sessionManager.buildSessionContext();
607
+ const resolvedToolCallIds = new Set();
608
+ for (const message of context.messages) {
609
+ if (message.role === "toolResult") {
610
+ resolvedToolCallIds.add(message.toolCallId);
611
+ }
612
+ }
613
+ for (const message of context.messages) {
614
+ if (message.role !== "assistant") {
615
+ continue;
616
+ }
617
+ const toolCalls = message.content.filter((block) => block.type === "toolCall");
618
+ for (const toolCall of toolCalls) {
619
+ if (resolvedToolCallIds.has(toolCall.id)) {
620
+ continue;
621
+ }
622
+ const abortedResult = {
623
+ role: "toolResult",
624
+ toolCallId: toolCall.id,
625
+ toolName: toolCall.name,
626
+ content: [
627
+ { type: "text", text: "Operation aborted: the session closed before this tool call completed." },
628
+ ],
629
+ isError: true,
630
+ timestamp: Date.now(),
631
+ };
632
+ this.sessionManager.appendMessage(abortedResult);
633
+ }
634
+ }
635
+ }
636
+ catch {
637
+ // Best-effort: a persistence failure must not block dispose.
638
+ }
639
+ }
640
+ // =========================================================================
641
+ // Read-only State Access
642
+ // =========================================================================
643
+ /** Full agent state */
644
+ get state() {
645
+ return this.agent.state;
646
+ }
647
+ /** Current model (may be undefined if not yet selected) */
648
+ get model() {
649
+ return this.agent.state.model;
650
+ }
651
+ /** Current thinking level */
652
+ get thinkingLevel() {
653
+ return this.agent.state.thinkingLevel;
654
+ }
655
+ /** Thinking level to restore when session-local Fast mode is disabled. */
656
+ get fastModeRestoreThinkingLevel() {
657
+ return this._fastModeRestoreThinkingLevel;
658
+ }
659
+ /** Set the session-local Fast mode restore marker. */
660
+ setFastModeRestoreThinkingLevel(level) {
661
+ this._fastModeRestoreThinkingLevel = level;
662
+ }
663
+ /** Whether the session is processing a response or a session-level continuation. */
664
+ get isStreaming() {
665
+ return this.agent.state.isStreaming || this._activePromptRuns.size > 0;
666
+ }
667
+ /** Whether any tracked prompt or standalone session operation is still active. */
668
+ get isBusy() {
669
+ return this.isStreaming || this._activePromptTransactions.size > 0 || this._activeSessionOperations.size > 0;
670
+ }
671
+ /** Current effective system prompt (includes any per-turn extension modifications) */
672
+ get systemPrompt() {
673
+ return this.agent.state.systemPrompt;
674
+ }
675
+ /**
676
+ * Append fixed context to this session's base system prompt.
677
+ * Used by subagent runtimes to apply a selected definition before any turns run.
678
+ */
679
+ appendSystemPromptContext(context) {
680
+ const trimmed = context.trim();
681
+ if (!trimmed) {
682
+ return;
683
+ }
684
+ this._baseSystemPrompt = [this._baseSystemPrompt, trimmed].filter(Boolean).join("\n\n");
685
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
686
+ }
687
+ /** Current retry attempt (0 if not retrying) */
688
+ get retryAttempt() {
689
+ return this._retryAttempt;
690
+ }
691
+ /**
692
+ * Get the names of currently active tools.
693
+ * Returns the names of tools currently set on the agent.
694
+ */
695
+ getActiveToolNames() {
696
+ return this.agent.state.tools.map((t) => t.name);
697
+ }
698
+ getSubagentToolManager() {
699
+ return this._subagentToolManager;
700
+ }
701
+ getMcpManager() {
702
+ return this._mcpManager;
703
+ }
704
+ /**
705
+ * Get all configured tools with name, description, parameter schema, prompt guidelines, and source metadata.
706
+ */
707
+ getAllTools() {
708
+ return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
709
+ name: definition.name,
710
+ description: definition.description,
711
+ parameters: definition.parameters,
712
+ promptGuidelines: definition.promptGuidelines,
713
+ sourceInfo,
714
+ }));
715
+ }
716
+ getToolDefinition(name) {
717
+ return this._toolDefinitions.get(name)?.definition;
718
+ }
719
+ /**
720
+ * Set active tools by name.
721
+ * Only tools in the registry can be enabled. Unknown tool names are ignored.
722
+ * Also rebuilds the system prompt to reflect the new tool set.
723
+ * Changes take effect on the next agent turn.
724
+ */
725
+ setActiveToolsByName(toolNames) {
726
+ const tools = [];
727
+ const validToolNames = [];
728
+ for (const name of toolNames) {
729
+ const tool = this._toolRegistry.get(name);
730
+ if (tool) {
731
+ tools.push(tool);
732
+ validToolNames.push(name);
733
+ }
734
+ }
735
+ this.agent.state.tools = tools;
736
+ // Rebuild base system prompt with new tool set
737
+ this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
738
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
739
+ }
740
+ /** Whether compaction or branch summarization is currently running */
741
+ get isCompacting() {
742
+ return (this._autoCompactionAbortController !== undefined ||
743
+ this._compactionAbortController !== undefined ||
744
+ this._branchSummaryAbortController !== undefined);
745
+ }
746
+ /** Active context compaction metadata, if compaction is currently running. */
747
+ get activeCompaction() {
748
+ return this._activeCompaction ? { ...this._activeCompaction } : undefined;
749
+ }
750
+ /** All messages including custom types like BashExecutionMessage */
751
+ get messages() {
752
+ return this.agent.state.messages;
753
+ }
754
+ /** Current steering mode */
755
+ get steeringMode() {
756
+ return this.agent.steeringMode;
757
+ }
758
+ /** Current follow-up mode */
759
+ get followUpMode() {
760
+ return this.agent.followUpMode;
761
+ }
762
+ /** Current session file path, or undefined if sessions are disabled */
763
+ get sessionFile() {
764
+ return this.sessionManager.getSessionFile();
765
+ }
766
+ /** Current session ID */
767
+ get sessionId() {
768
+ return this.sessionManager.getSessionId();
769
+ }
770
+ /** Current session display name, if set */
771
+ get sessionName() {
772
+ return this.sessionManager.getSessionName();
773
+ }
774
+ /** Scoped models for cycling (from --models flag) */
775
+ get scopedModels() {
776
+ return this._scopedModels;
777
+ }
778
+ /** Update scoped models for cycling */
779
+ setScopedModels(scopedModels) {
780
+ this._clearFastModeUnlessPreserved();
781
+ this._scopedModels = scopedModels;
782
+ }
783
+ /** File-based prompt templates */
784
+ get promptTemplates() {
785
+ return this._resourceLoader.getPrompts().prompts;
786
+ }
787
+ _normalizePromptSnippet(text) {
788
+ if (!text)
789
+ return undefined;
790
+ const oneLine = text
791
+ .replace(/[\r\n]+/g, " ")
792
+ .replace(/\s+/g, " ")
793
+ .trim();
794
+ return oneLine.length > 0 ? oneLine : undefined;
795
+ }
796
+ _normalizePromptGuidelines(guidelines) {
797
+ if (!guidelines || guidelines.length === 0) {
798
+ return [];
799
+ }
800
+ const unique = new Set();
801
+ for (const guideline of guidelines) {
802
+ const normalized = guideline.trim();
803
+ if (normalized.length > 0) {
804
+ unique.add(normalized);
805
+ }
806
+ }
807
+ return Array.from(unique);
808
+ }
809
+ _rebuildSystemPrompt(toolNames) {
810
+ const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
811
+ const toolSnippets = {};
812
+ const promptGuidelines = [];
813
+ for (const name of validToolNames) {
814
+ const snippet = this._toolPromptSnippets.get(name);
815
+ if (snippet) {
816
+ toolSnippets[name] = snippet;
817
+ }
818
+ const toolGuidelines = this._toolPromptGuidelines.get(name);
819
+ if (toolGuidelines) {
820
+ promptGuidelines.push(...toolGuidelines);
821
+ }
822
+ }
823
+ const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
824
+ const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
825
+ const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
826
+ const loadedSkills = this._resourceLoader.getSkills().skills;
827
+ const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
828
+ this._baseSystemPromptOptions = {
829
+ cwd: this._cwd,
830
+ skills: loadedSkills,
831
+ contextFiles: loadedContextFiles,
832
+ customPrompt: loaderSystemPrompt,
833
+ appendSystemPrompt,
834
+ selectedTools: validToolNames,
835
+ toolSnippets,
836
+ promptGuidelines,
837
+ };
838
+ return buildSystemPrompt(this._baseSystemPromptOptions);
839
+ }
840
+ // =========================================================================
841
+ // Prompting
842
+ // =========================================================================
843
+ async _runAgentPrompt(messages, abortGeneration = this._abortGeneration) {
844
+ if (this._disposed || abortGeneration !== this._abortGeneration) {
845
+ return;
846
+ }
847
+ this._proactiveCompactionStopped = false;
848
+ this._drainFollowUpsOnNextContinuation = false;
849
+ const run = (async () => {
850
+ try {
851
+ await this.agent.prompt(messages);
852
+ while (await this._handlePostAgentRun(abortGeneration)) {
853
+ await this._continueAgent();
854
+ }
855
+ }
856
+ finally {
857
+ this._flushPendingBashMessages();
858
+ }
859
+ })();
860
+ this._activePromptRuns.add(run);
861
+ try {
862
+ await run;
863
+ }
864
+ finally {
865
+ this._activePromptRuns.delete(run);
866
+ this._emitAgentSettledIfIdle();
867
+ }
868
+ }
869
+ async _continueAgent() {
870
+ const drainFollowUps = this._drainFollowUpsOnNextContinuation;
871
+ this._drainFollowUpsOnNextContinuation = false;
872
+ await this.agent.continue({ drainFollowUps });
873
+ }
874
+ _trackPromptTransaction(operation) {
875
+ const transactionId = Symbol("promptTransaction");
876
+ const transaction = Promise.resolve().then(() => operation(transactionId));
877
+ this._activePromptTransactions.set(transactionId, transaction);
878
+ return transaction.finally(() => {
879
+ this._activePromptTransactions.delete(transactionId);
880
+ this._extensionCommandTransactions.delete(transactionId);
881
+ this._emitAgentSettledIfIdle();
882
+ });
883
+ }
884
+ _trackSessionOperation(operation) {
885
+ const tracked = Promise.resolve().then(operation);
886
+ this._activeSessionOperations.add(tracked);
887
+ return tracked.finally(() => {
888
+ this._activeSessionOperations.delete(tracked);
889
+ this._emitAgentSettledIfIdle();
890
+ });
891
+ }
892
+ _emitAgentSettledIfIdle() {
893
+ if (this._activePromptRuns.size === 0 &&
894
+ this._activePromptTransactions.size === 0 &&
895
+ this._activeSessionOperations.size === 0) {
896
+ this._emit({ type: "agent_settled" });
897
+ }
898
+ }
899
+ /** Wait for the agent and any session-level prompt work to settle. */
900
+ async waitForIdle() {
901
+ await this._waitForIdle();
902
+ }
903
+ async _waitForIdle(excludeExtensionCommands = false) {
904
+ while (true) {
905
+ const promptTransactions = [...this._activePromptTransactions.entries()]
906
+ .filter(([transactionId]) => !excludeExtensionCommands || !this._extensionCommandTransactions.has(transactionId))
907
+ .map(([, transaction]) => transaction);
908
+ const sessionWork = [...this._activePromptRuns, ...promptTransactions, ...this._activeSessionOperations];
909
+ if (sessionWork.length > 0) {
910
+ await Promise.allSettled(sessionWork);
911
+ continue;
912
+ }
913
+ await this.agent.waitForIdle();
914
+ const hasOtherTransactions = [...this._activePromptTransactions.keys()].some((transactionId) => !excludeExtensionCommands || !this._extensionCommandTransactions.has(transactionId));
915
+ if (this._activePromptRuns.size === 0 && !hasOtherTransactions && this._activeSessionOperations.size === 0) {
916
+ return;
917
+ }
918
+ }
919
+ }
920
+ async _handlePostAgentRun(abortGeneration = this._abortGeneration) {
921
+ // Disposal stops all continuations. Abort stops automatic retry/compaction
922
+ // resurrection, but intentionally preserves messages queued before abort.
923
+ if (this._disposed) {
924
+ return false;
925
+ }
926
+ if (abortGeneration !== this._abortGeneration) {
927
+ this._lastAssistantMessage = undefined;
928
+ this._settleRetry(false, "Retry cancelled");
929
+ return this.agent.hasQueuedMessages();
930
+ }
931
+ const msg = this._lastAssistantMessage;
932
+ this._lastAssistantMessage = undefined;
933
+ if (!msg) {
934
+ return false;
935
+ }
936
+ if (this._proactiveCompactionStopped) {
937
+ this._proactiveCompactionStopped = false;
938
+ // The run was interrupted mid-task by _shouldStopForProactiveCompaction,
939
+ // so always resume it, even when compaction bails or fails, unless the
940
+ // session was disposed while compaction was in flight.
941
+ await this._runAutoCompaction("threshold", false, true, true);
942
+ return !this._disposed && (abortGeneration === this._abortGeneration || this.agent.hasQueuedMessages());
943
+ }
944
+ if (this._isRetryableError(msg) && (await this._prepareRetry(msg, abortGeneration))) {
945
+ return !this._disposed && abortGeneration === this._abortGeneration;
946
+ }
947
+ if (this._disposed) {
948
+ return false;
949
+ }
950
+ if (abortGeneration !== this._abortGeneration) {
951
+ return this.agent.hasQueuedMessages();
952
+ }
953
+ if (msg.stopReason === "error") {
954
+ this._settleRetry(false, msg.errorMessage);
955
+ }
956
+ if (await this._checkCompaction(msg)) {
957
+ return !this._disposed && (abortGeneration === this._abortGeneration || this.agent.hasQueuedMessages());
958
+ }
959
+ // The agent loop drains both queues before emitting agent_end. Any messages
960
+ // here were queued by agent_end extension handlers and need a continuation,
961
+ // including messages that were already queued when the run was aborted.
962
+ return !this._disposed && this.agent.hasQueuedMessages();
963
+ }
964
+ /**
965
+ * Send a prompt to the agent.
966
+ * - Handles extension commands (registered via volt.registerCommand) immediately, even during streaming
967
+ * - Expands file-based prompt templates by default
968
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
969
+ * - Validates model and API key before sending (when not streaming)
970
+ * @throws Error if streaming and no streamingBehavior specified
971
+ * @throws Error if no model selected or no API key available (when not streaming)
972
+ */
973
+ prompt(text, options) {
974
+ const isRunning = this.isStreaming;
975
+ const shouldQueue = isRunning || this._activePromptTransactions.size > 0 || this._abortPromise !== undefined;
976
+ const allowQueue = isRunning && this._abortPromise === undefined;
977
+ const abortGeneration = this._abortGeneration;
978
+ return this._trackPromptTransaction((transactionId) => this._prompt(text, options, shouldQueue, allowQueue, abortGeneration, transactionId));
979
+ }
980
+ async _prompt(text, options, shouldQueue, allowQueue, abortGeneration, transactionId) {
981
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
982
+ const preflightResult = options?.preflightResult;
983
+ let messages;
984
+ try {
985
+ if (this._disposed || abortGeneration !== this._abortGeneration) {
986
+ throw new Error("Prompt aborted before preflight started");
987
+ }
988
+ // Handle extension commands first (execute immediately, even during streaming)
989
+ // Extension commands manage their own LLM interaction via volt.sendMessage()
990
+ if (expandPromptTemplates && text.startsWith("/")) {
991
+ const handled = await this._tryExecuteExtensionCommand(text, transactionId);
992
+ if (handled) {
993
+ // Extension command executed, no prompt to send
994
+ preflightResult?.(true);
995
+ return;
996
+ }
997
+ }
998
+ // Emit input event for extension interception (before skill/template expansion)
999
+ let currentText = text;
1000
+ let currentImages = options?.images;
1001
+ if (this._extensionRunner.hasHandlers("input")) {
1002
+ const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive", shouldQueue ? options?.streamingBehavior : undefined);
1003
+ if (this._disposed || abortGeneration !== this._abortGeneration) {
1004
+ throw new Error("Prompt aborted during input preflight");
1005
+ }
1006
+ if (inputResult.action === "handled") {
1007
+ preflightResult?.(true);
1008
+ return;
1009
+ }
1010
+ if (inputResult.action === "transform") {
1011
+ currentText = inputResult.text;
1012
+ currentImages = inputResult.images ?? currentImages;
1013
+ }
1014
+ }
1015
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
1016
+ let expandedText = currentText;
1017
+ if (expandPromptTemplates) {
1018
+ expandedText = this._expandSkillCommand(expandedText);
1019
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1020
+ }
1021
+ // Queue only behind an active agent run. During preflight or abort,
1022
+ // reject promptly so an accepted message cannot be stranded.
1023
+ if (shouldQueue) {
1024
+ if (allowQueue && !this.isStreaming) {
1025
+ throw new Error("Agent finished processing while queued prompt preflight was running. Resubmit the prompt.");
1026
+ }
1027
+ if (!allowQueue || !options?.streamingBehavior) {
1028
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
1029
+ }
1030
+ if (options.streamingBehavior === "followUp") {
1031
+ await this._queueFollowUp(expandedText, currentImages);
1032
+ }
1033
+ else {
1034
+ await this._queueSteer(expandedText, currentImages);
1035
+ }
1036
+ preflightResult?.(true);
1037
+ return;
1038
+ }
1039
+ // Flush any pending bash messages before the new prompt
1040
+ this._flushPendingBashMessages();
1041
+ // Validate model
1042
+ if (!this.model) {
1043
+ throw new Error(formatNoModelSelectedMessage());
1044
+ }
1045
+ if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
1046
+ const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
1047
+ if (isOAuth) {
1048
+ throw new Error(`Authentication failed for "${this.model.provider}". ` +
1049
+ `Credentials may have expired or network is unavailable. ` +
1050
+ `Run '/login ${this.model.provider}' to re-authenticate.`);
1051
+ }
1052
+ throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
1053
+ }
1054
+ // Check if we need to compact before sending (catches aborted responses)
1055
+ const lastAssistant = this._findLastAssistantMessage();
1056
+ if (lastAssistant && (await this._checkCompaction(lastAssistant, false))) {
1057
+ // dispose() or abort() can land during the _checkCompaction await.
1058
+ // agent.continue() mints a fresh controller, so it must not run for a
1059
+ // disposed generation or an aborted prompt transaction.
1060
+ if (this._disposed || abortGeneration !== this._abortGeneration) {
1061
+ throw new Error("Prompt aborted before recovery could continue");
1062
+ }
1063
+ try {
1064
+ await this._continueAgent();
1065
+ while (await this._handlePostAgentRun(abortGeneration)) {
1066
+ await this._continueAgent();
1067
+ }
1068
+ }
1069
+ finally {
1070
+ this._flushPendingBashMessages();
1071
+ }
1072
+ }
1073
+ if (this._disposed || abortGeneration !== this._abortGeneration) {
1074
+ throw new Error("Prompt aborted before the agent run started");
1075
+ }
1076
+ // Build messages array (custom message if any, then user message)
1077
+ messages = [];
1078
+ // Add user message
1079
+ const userContent = [{ type: "text", text: expandedText }];
1080
+ if (currentImages) {
1081
+ userContent.push(...currentImages);
1082
+ }
1083
+ messages.push({
1084
+ role: "user",
1085
+ content: userContent,
1086
+ timestamp: Date.now(),
1087
+ });
1088
+ // Snapshot pending "nextTurn" context. It is consumed only after preflight
1089
+ // is accepted so aborting an extension hook cannot lose queued context.
1090
+ const pendingNextTurnMessages = [...this._pendingNextTurnMessages];
1091
+ messages.push(...pendingNextTurnMessages);
1092
+ // Emit before_agent_start extension event
1093
+ const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
1094
+ if (this._disposed || abortGeneration !== this._abortGeneration) {
1095
+ throw new Error("Prompt aborted before the agent run started");
1096
+ }
1097
+ // Add all custom messages from extensions
1098
+ if (result?.messages) {
1099
+ for (const msg of result.messages) {
1100
+ messages.push({
1101
+ role: "custom",
1102
+ customType: msg.customType,
1103
+ content: msg.content,
1104
+ display: msg.display,
1105
+ details: msg.details,
1106
+ timestamp: Date.now(),
1107
+ });
1108
+ }
1109
+ }
1110
+ // Apply extension-modified system prompt, or reset to base
1111
+ if (result?.systemPrompt) {
1112
+ this.agent.state.systemPrompt = result.systemPrompt;
1113
+ }
1114
+ else {
1115
+ // Ensure we're using the base prompt (in case previous turn had modifications)
1116
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
1117
+ }
1118
+ this._pendingNextTurnMessages.splice(0, pendingNextTurnMessages.length);
1119
+ // Name the session only after all abortable preflight work is accepted.
1120
+ this._maybeGenerateSessionName(expandedText);
1121
+ }
1122
+ catch (error) {
1123
+ preflightResult?.(false);
1124
+ throw error;
1125
+ }
1126
+ if (!messages) {
1127
+ return;
1128
+ }
1129
+ if (this._disposed || abortGeneration !== this._abortGeneration) {
1130
+ preflightResult?.(false);
1131
+ throw new Error("Prompt aborted before the agent run started");
1132
+ }
1133
+ preflightResult?.(true);
1134
+ await this._runAgentPrompt(messages, abortGeneration);
1135
+ }
1136
+ /**
1137
+ * Try to execute an extension command. Returns true if command was found and executed.
1138
+ */
1139
+ async _tryExecuteExtensionCommand(text, transactionId) {
1140
+ // Parse command name and args
1141
+ const spaceIndex = text.indexOf(" ");
1142
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1143
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
1144
+ const command = this._extensionRunner.getCommand(commandName);
1145
+ if (!command)
1146
+ return false;
1147
+ this._extensionCommandTransactions.add(transactionId);
1148
+ // Command transactions must not wait on themselves or each other.
1149
+ // waitForIdle still waits for active runs and non-command prompt work.
1150
+ const ctx = this._extensionRunner.createCommandContext(() => this._waitForIdle(true));
1151
+ try {
1152
+ this._activeExtensionCommandHandlers++;
1153
+ await command.handler(args, ctx);
1154
+ return true;
1155
+ }
1156
+ catch (err) {
1157
+ // Emit error via extension runner
1158
+ this._extensionRunner.emitError({
1159
+ extensionPath: `command:${commandName}`,
1160
+ event: "command",
1161
+ error: err instanceof Error ? err.message : String(err),
1162
+ });
1163
+ return true;
1164
+ }
1165
+ finally {
1166
+ this._activeExtensionCommandHandlers--;
1167
+ }
1168
+ }
1169
+ /**
1170
+ * Expand skill commands (/skill:name args) to their full content.
1171
+ * Returns the expanded text, or the original text if not a skill command or skill not found.
1172
+ * Emits errors via extension runner if file read fails.
1173
+ */
1174
+ _expandSkillCommand(text) {
1175
+ if (!text.startsWith("/skill:"))
1176
+ return text;
1177
+ const spaceIndex = text.indexOf(" ");
1178
+ const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
1179
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
1180
+ const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
1181
+ if (!skill)
1182
+ return text; // Unknown skill, pass through
1183
+ try {
1184
+ const content = readFileSync(skill.filePath, "utf-8");
1185
+ const body = stripFrontmatter(content).trim();
1186
+ const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
1187
+ return args ? `${skillBlock}\n\n${args}` : skillBlock;
1188
+ }
1189
+ catch (err) {
1190
+ // Emit error like extension commands do
1191
+ this._extensionRunner.emitError({
1192
+ extensionPath: skill.filePath,
1193
+ event: "skill_expansion",
1194
+ error: err instanceof Error ? err.message : String(err),
1195
+ });
1196
+ return text; // Return original on error
1197
+ }
1198
+ }
1199
+ /**
1200
+ * Queue a steering message while the agent is running.
1201
+ * Delivered after the current assistant turn finishes executing its tool calls,
1202
+ * before the next LLM call.
1203
+ * Expands skill commands and prompt templates. Errors on extension commands.
1204
+ * @param images Optional image attachments to include with the message
1205
+ * @throws Error if text is an extension command
1206
+ */
1207
+ async steer(text, images) {
1208
+ // Check for extension commands (cannot be queued)
1209
+ if (text.startsWith("/")) {
1210
+ this._throwIfExtensionCommand(text);
1211
+ }
1212
+ // Expand skill commands and prompt templates
1213
+ let expandedText = this._expandSkillCommand(text);
1214
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1215
+ await this._queueSteer(expandedText, images);
1216
+ }
1217
+ /**
1218
+ * Queue a follow-up message to be processed after the agent finishes.
1219
+ * Delivered only when agent has no more tool calls or steering messages.
1220
+ * Expands skill commands and prompt templates. Errors on extension commands.
1221
+ * @param images Optional image attachments to include with the message
1222
+ * @throws Error if text is an extension command
1223
+ */
1224
+ async followUp(text, images) {
1225
+ // Check for extension commands (cannot be queued)
1226
+ if (text.startsWith("/")) {
1227
+ this._throwIfExtensionCommand(text);
1228
+ }
1229
+ // Expand skill commands and prompt templates
1230
+ let expandedText = this._expandSkillCommand(text);
1231
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
1232
+ await this._queueFollowUp(expandedText, images);
1233
+ }
1234
+ /**
1235
+ * Internal: Queue a steering message (already expanded, no extension command check).
1236
+ */
1237
+ async _queueSteer(text, images) {
1238
+ this._steeringMessages.push(text);
1239
+ this._emitQueueUpdate();
1240
+ const content = [{ type: "text", text }];
1241
+ if (images) {
1242
+ content.push(...images);
1243
+ }
1244
+ this.agent.steer({
1245
+ role: "user",
1246
+ content,
1247
+ timestamp: Date.now(),
1248
+ });
1249
+ }
1250
+ /**
1251
+ * Internal: Queue a follow-up message (already expanded, no extension command check).
1252
+ */
1253
+ async _queueFollowUp(text, images) {
1254
+ this._followUpMessages.push(text);
1255
+ this._emitQueueUpdate();
1256
+ const content = [{ type: "text", text }];
1257
+ if (images) {
1258
+ content.push(...images);
1259
+ }
1260
+ this.agent.followUp({
1261
+ role: "user",
1262
+ content,
1263
+ timestamp: Date.now(),
1264
+ });
1265
+ }
1266
+ /**
1267
+ * Throw an error if the text is an extension command.
1268
+ */
1269
+ _throwIfExtensionCommand(text) {
1270
+ const spaceIndex = text.indexOf(" ");
1271
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
1272
+ const command = this._extensionRunner.getCommand(commandName);
1273
+ if (command) {
1274
+ throw new Error(`Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`);
1275
+ }
1276
+ }
1277
+ /**
1278
+ * Send a custom message to the session. Creates a CustomMessageEntry.
1279
+ *
1280
+ * Handles three cases:
1281
+ * - Streaming: queues message, processed when loop pulls from queue
1282
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
1283
+ * - Not streaming + no trigger: appends to state/session, no turn
1284
+ *
1285
+ * @param message Custom message with customType, content, display, details
1286
+ * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
1287
+ * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
1288
+ */
1289
+ async sendCustomMessage(message, options) {
1290
+ await this._sendCustomMessage(message, options, false);
1291
+ }
1292
+ async _sendCustomMessage(message, options, allowDuringPromptTransaction) {
1293
+ const appMessage = {
1294
+ role: "custom",
1295
+ customType: message.customType,
1296
+ content: message.content,
1297
+ display: message.display,
1298
+ details: message.details,
1299
+ timestamp: Date.now(),
1300
+ };
1301
+ if (options?.deliverAs === "nextTurn") {
1302
+ this._pendingNextTurnMessages.push(appMessage);
1303
+ }
1304
+ else if (this.isStreaming) {
1305
+ if (options?.deliverAs === "followUp") {
1306
+ this.agent.followUp(appMessage);
1307
+ }
1308
+ else {
1309
+ this.agent.steer(appMessage);
1310
+ }
1311
+ }
1312
+ else if (options?.triggerTurn) {
1313
+ if (this._activePromptTransactions.size > 0 && !allowDuringPromptTransaction) {
1314
+ throw new Error("Agent is already processing a prompt transaction");
1315
+ }
1316
+ if (allowDuringPromptTransaction) {
1317
+ await this._runAgentPrompt(appMessage);
1318
+ }
1319
+ else {
1320
+ const abortGeneration = this._abortGeneration;
1321
+ await this._trackPromptTransaction(() => this._runAgentPrompt(appMessage, abortGeneration));
1322
+ }
1323
+ }
1324
+ else {
1325
+ this.agent.state.messages.push(appMessage);
1326
+ this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
1327
+ this._emit({ type: "message_start", message: appMessage });
1328
+ this._emit({ type: "message_end", message: appMessage });
1329
+ }
1330
+ }
1331
+ /**
1332
+ * Send a user message to the agent. Always triggers a turn.
1333
+ * When the agent is streaming, use deliverAs to specify how to queue the message.
1334
+ *
1335
+ * @param content User message content (string or content array)
1336
+ * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
1337
+ */
1338
+ async sendUserMessage(content, options) {
1339
+ // Normalize content to text string + optional images
1340
+ let text;
1341
+ let images;
1342
+ if (typeof content === "string") {
1343
+ text = content;
1344
+ }
1345
+ else {
1346
+ const textParts = [];
1347
+ images = [];
1348
+ for (const part of content) {
1349
+ if (part.type === "text") {
1350
+ textParts.push(part.text);
1351
+ }
1352
+ else {
1353
+ images.push(part);
1354
+ }
1355
+ }
1356
+ text = textParts.join("\n");
1357
+ if (images.length === 0)
1358
+ images = undefined;
1359
+ }
1360
+ // Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
1361
+ await this.prompt(text, {
1362
+ expandPromptTemplates: false,
1363
+ streamingBehavior: options?.deliverAs,
1364
+ images,
1365
+ source: "extension",
1366
+ });
1367
+ }
1368
+ /**
1369
+ * Clear all queued messages and return them.
1370
+ * Useful for restoring to editor when user aborts.
1371
+ * @returns Object with steering and followUp arrays
1372
+ */
1373
+ clearQueue() {
1374
+ const steering = [...this._steeringMessages];
1375
+ const followUp = [...this._followUpMessages];
1376
+ this._steeringMessages = [];
1377
+ this._followUpMessages = [];
1378
+ this.agent.clearAllQueues();
1379
+ this._emitQueueUpdate();
1380
+ return { steering, followUp };
1381
+ }
1382
+ /** Number of pending messages (includes both steering and follow-up) */
1383
+ get pendingMessageCount() {
1384
+ return this._steeringMessages.length + this._followUpMessages.length;
1385
+ }
1386
+ /** Get pending steering messages (read-only) */
1387
+ getSteeringMessages() {
1388
+ return this._steeringMessages;
1389
+ }
1390
+ /** Get pending follow-up messages (read-only) */
1391
+ getFollowUpMessages() {
1392
+ return this._followUpMessages;
1393
+ }
1394
+ get resourceLoader() {
1395
+ return this._resourceLoader;
1396
+ }
1397
+ /**
1398
+ * Abort current operation and wait for agent to become idle.
1399
+ */
1400
+ abort() {
1401
+ if (this._abortPromise) {
1402
+ return this._abortPromise;
1403
+ }
1404
+ this._abortGeneration += 1;
1405
+ this.abortRetry();
1406
+ this.abortCompaction();
1407
+ this.agent.abort();
1408
+ const idlePromise = this.waitForIdle();
1409
+ const abortPromise = idlePromise.finally(() => {
1410
+ if (this._abortPromise === abortPromise) {
1411
+ this._abortPromise = undefined;
1412
+ }
1413
+ });
1414
+ this._abortPromise = abortPromise;
1415
+ return abortPromise;
1416
+ }
1417
+ // =========================================================================
1418
+ // Model Management
1419
+ // =========================================================================
1420
+ async _emitModelSelect(nextModel, previousModel, source) {
1421
+ if (modelsAreEqual(previousModel, nextModel))
1422
+ return;
1423
+ await this._extensionRunner.emit({
1424
+ type: "model_select",
1425
+ model: nextModel,
1426
+ previousModel,
1427
+ source,
1428
+ });
1429
+ }
1430
+ /**
1431
+ * Set model directly.
1432
+ * Validates that auth is configured, saves to session, and persists as the default unless disabled.
1433
+ * @throws Error if no auth is configured for the model
1434
+ */
1435
+ async setModel(model, options) {
1436
+ if (!this._modelRegistry.hasConfiguredAuth(model)) {
1437
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
1438
+ }
1439
+ const previousModel = this.model;
1440
+ const persistDefault = options?.persistDefault !== false;
1441
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1442
+ this.agent.state.model = model;
1443
+ this.sessionManager.appendModelChange(model.provider, model.id);
1444
+ if (persistDefault) {
1445
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1446
+ }
1447
+ // Re-clamp thinking level for new model's capabilities
1448
+ this.setThinkingLevel(thinkingLevel, { persistDefault });
1449
+ await this._emitModelSelect(model, previousModel, "set");
1450
+ }
1451
+ /**
1452
+ * Cycle to next/previous model.
1453
+ * Uses scoped models (from --models flag) if available, otherwise all available models.
1454
+ * @param direction - "forward" (default) or "backward"
1455
+ * @returns The new model info, or undefined if only one model available
1456
+ */
1457
+ async cycleModel(direction = "forward") {
1458
+ if (this._scopedModels.length > 0) {
1459
+ return this._cycleScopedModel(direction);
1460
+ }
1461
+ return this._cycleAvailableModel(direction);
1462
+ }
1463
+ async _cycleScopedModel(direction) {
1464
+ const scopedModels = this._scopedModels.filter((scoped) => this._modelRegistry.hasConfiguredAuth(scoped.model));
1465
+ if (scopedModels.length <= 1)
1466
+ return undefined;
1467
+ const currentModel = this.model;
1468
+ let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
1469
+ if (currentIndex === -1)
1470
+ currentIndex = 0;
1471
+ const len = scopedModels.length;
1472
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1473
+ const next = scopedModels[nextIndex];
1474
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
1475
+ // Apply model
1476
+ this.agent.state.model = next.model;
1477
+ this.sessionManager.appendModelChange(next.model.provider, next.model.id);
1478
+ this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1479
+ // Apply thinking level.
1480
+ // - Explicit scoped model thinking level overrides current session level
1481
+ // - Undefined scoped model thinking level inherits the current session preference
1482
+ // setThinkingLevel clamps to model capabilities.
1483
+ this.setThinkingLevel(thinkingLevel);
1484
+ await this._emitModelSelect(next.model, currentModel, "cycle");
1485
+ return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1486
+ }
1487
+ async _cycleAvailableModel(direction) {
1488
+ const availableModels = await this._modelRegistry.getAvailable();
1489
+ if (availableModels.length <= 1)
1490
+ return undefined;
1491
+ const currentModel = this.model;
1492
+ let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
1493
+ if (currentIndex === -1)
1494
+ currentIndex = 0;
1495
+ const len = availableModels.length;
1496
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1497
+ const nextModel = availableModels[nextIndex];
1498
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1499
+ this.agent.state.model = nextModel;
1500
+ this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
1501
+ this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1502
+ // Re-clamp thinking level for new model's capabilities
1503
+ this.setThinkingLevel(thinkingLevel);
1504
+ await this._emitModelSelect(nextModel, currentModel, "cycle");
1505
+ return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
1506
+ }
1507
+ // =========================================================================
1508
+ // Thinking Level Management
1509
+ // =========================================================================
1510
+ /**
1511
+ * Set thinking level.
1512
+ * Clamps to model capabilities based on available thinking levels.
1513
+ * Saves to session and settings only if the level actually changes. Settings persistence can be disabled.
1514
+ */
1515
+ setThinkingLevel(level, options) {
1516
+ this._clearFastModeUnlessPreserved(options);
1517
+ const availableLevels = this.getAvailableThinkingLevels();
1518
+ const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
1519
+ // Only persist if actually changing
1520
+ const previousLevel = this.agent.state.thinkingLevel;
1521
+ const isChanging = effectiveLevel !== previousLevel;
1522
+ const persistDefault = options?.persistDefault !== false;
1523
+ this.agent.state.thinkingLevel = effectiveLevel;
1524
+ if (isChanging) {
1525
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1526
+ if (persistDefault && (this.supportsThinking() || effectiveLevel !== "off")) {
1527
+ this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1528
+ }
1529
+ this._emit({ type: "thinking_level_changed", level: effectiveLevel });
1530
+ void this._extensionRunner.emit({
1531
+ type: "thinking_level_select",
1532
+ level: effectiveLevel,
1533
+ previousLevel,
1534
+ });
1535
+ }
1536
+ }
1537
+ /**
1538
+ * Cycle to next thinking level.
1539
+ * @returns New level, or undefined if model doesn't support thinking
1540
+ */
1541
+ cycleThinkingLevel() {
1542
+ if (!this.supportsThinking())
1543
+ return undefined;
1544
+ const levels = this.getAvailableThinkingLevels();
1545
+ const currentIndex = levels.indexOf(this.thinkingLevel);
1546
+ const nextIndex = (currentIndex + 1) % levels.length;
1547
+ const nextLevel = levels[nextIndex];
1548
+ this.setThinkingLevel(nextLevel);
1549
+ return nextLevel;
1550
+ }
1551
+ /**
1552
+ * Get available thinking levels for current model.
1553
+ * The provider will clamp to what the specific model supports internally.
1554
+ */
1555
+ getAvailableThinkingLevels() {
1556
+ if (!this.model)
1557
+ return THINKING_LEVELS;
1558
+ return getSupportedThinkingLevels(this.model);
1559
+ }
1560
+ /**
1561
+ * Check if current model supports thinking/reasoning.
1562
+ */
1563
+ supportsThinking() {
1564
+ return !!this.model?.reasoning;
1565
+ }
1566
+ _getThinkingLevelForModelSwitch(explicitLevel) {
1567
+ if (explicitLevel !== undefined) {
1568
+ return explicitLevel;
1569
+ }
1570
+ if (!this.supportsThinking()) {
1571
+ return this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
1572
+ }
1573
+ return this.thinkingLevel;
1574
+ }
1575
+ _clampThinkingLevel(level, _availableLevels) {
1576
+ return this.model ? clampThinkingLevel(this.model, level) : "off";
1577
+ }
1578
+ _clearFastModeUnlessPreserved(options) {
1579
+ if (options?.preserveFastMode !== true) {
1580
+ this._fastModeRestoreThinkingLevel = undefined;
1581
+ }
1582
+ }
1583
+ // =========================================================================
1584
+ // Queue Mode Management
1585
+ // =========================================================================
1586
+ syncQueueModesFromSettings() {
1587
+ this.agent.steeringMode = this.settingsManager.getSteeringMode();
1588
+ this.agent.followUpMode = this.settingsManager.getFollowUpMode();
1589
+ }
1590
+ syncAgentRuntimeSettingsFromSettings() {
1591
+ this.syncQueueModesFromSettings();
1592
+ this.agent.transport = this.settingsManager.getTransport();
1593
+ this.agent.thinkingBudgets = this.settingsManager.getThinkingBudgets();
1594
+ this.agent.maxRetryDelayMs = this.settingsManager.getProviderRetrySettings().maxRetryDelayMs;
1595
+ }
1596
+ /**
1597
+ * Set steering message mode.
1598
+ * Saves to settings.
1599
+ */
1600
+ setSteeringMode(mode) {
1601
+ this.agent.steeringMode = mode;
1602
+ this.settingsManager.setSteeringMode(mode);
1603
+ }
1604
+ /**
1605
+ * Set follow-up message mode.
1606
+ * Saves to settings.
1607
+ */
1608
+ setFollowUpMode(mode) {
1609
+ this.agent.followUpMode = mode;
1610
+ this.settingsManager.setFollowUpMode(mode);
1611
+ }
1612
+ // =========================================================================
1613
+ // Compaction
1614
+ // =========================================================================
1615
+ /**
1616
+ * Manually compact the session context.
1617
+ * Aborts current agent operation first.
1618
+ * @param customInstructions Optional instructions for the compaction summary
1619
+ */
1620
+ async compact(customInstructions) {
1621
+ this._disconnectFromAgent();
1622
+ await this.abort();
1623
+ return this._trackSessionOperation(() => this._compact(customInstructions));
1624
+ }
1625
+ async _compact(customInstructions) {
1626
+ this._compactionAbortController = new AbortController();
1627
+ this._activeCompaction = { reason: "manual", startedAt: Date.now() };
1628
+ this._emit({ type: "compaction_start", reason: "manual" });
1629
+ try {
1630
+ if (!this.model) {
1631
+ throw new Error(formatNoModelSelectedMessage());
1632
+ }
1633
+ const { apiKey, headers, env } = await this._getCompactionRequestAuth(this.model);
1634
+ const pathEntries = this.sessionManager.getBranch();
1635
+ const settings = this.settingsManager.getCompactionSettings();
1636
+ const preparation = prepareCompaction(pathEntries, settings);
1637
+ if (!preparation) {
1638
+ // Check why we can't compact
1639
+ const lastEntry = pathEntries[pathEntries.length - 1];
1640
+ if (lastEntry?.type === "compaction") {
1641
+ throw new Error("Already compacted");
1642
+ }
1643
+ throw new Error("Nothing to compact (session too small)");
1644
+ }
1645
+ let extensionCompaction;
1646
+ let fromExtension = false;
1647
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1648
+ const result = (await this._extensionRunner.emit({
1649
+ type: "session_before_compact",
1650
+ preparation,
1651
+ branchEntries: pathEntries,
1652
+ customInstructions,
1653
+ signal: this._compactionAbortController.signal,
1654
+ }));
1655
+ if (result?.cancel) {
1656
+ throw new Error("Compaction cancelled");
1657
+ }
1658
+ if (result?.compaction) {
1659
+ extensionCompaction = result.compaction;
1660
+ fromExtension = true;
1661
+ }
1662
+ }
1663
+ let summary;
1664
+ let firstKeptEntryId;
1665
+ let tokensBefore;
1666
+ let details;
1667
+ if (extensionCompaction) {
1668
+ // Extension provided compaction content
1669
+ summary = extensionCompaction.summary;
1670
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1671
+ tokensBefore = extensionCompaction.tokensBefore;
1672
+ details = extensionCompaction.details;
1673
+ }
1674
+ else {
1675
+ // Generate compaction result
1676
+ const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal, this.thinkingLevel, this.agent.streamFn, env);
1677
+ summary = result.summary;
1678
+ firstKeptEntryId = result.firstKeptEntryId;
1679
+ tokensBefore = result.tokensBefore;
1680
+ details = result.details;
1681
+ }
1682
+ if (this._compactionAbortController.signal.aborted) {
1683
+ throw new Error("Compaction cancelled");
1684
+ }
1685
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1686
+ this._proactiveCompactionAttempted = false;
1687
+ const newEntries = this.sessionManager.getEntries();
1688
+ const sessionContext = this.sessionManager.buildSessionContext();
1689
+ this.agent.state.messages = sessionContext.messages;
1690
+ // Get the saved compaction entry for the extension event
1691
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1692
+ if (this._extensionRunner && savedCompactionEntry) {
1693
+ await this._extensionRunner.emit({
1694
+ type: "session_compact",
1695
+ compactionEntry: savedCompactionEntry,
1696
+ fromExtension,
1697
+ });
1698
+ }
1699
+ const compactionResult = {
1700
+ summary,
1701
+ firstKeptEntryId,
1702
+ tokensBefore,
1703
+ details,
1704
+ };
1705
+ this._emit({
1706
+ type: "compaction_end",
1707
+ reason: "manual",
1708
+ result: compactionResult,
1709
+ aborted: false,
1710
+ willRetry: false,
1711
+ });
1712
+ return compactionResult;
1713
+ }
1714
+ catch (error) {
1715
+ const message = error instanceof Error ? error.message : String(error);
1716
+ const aborted = message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
1717
+ this._emit({
1718
+ type: "compaction_end",
1719
+ reason: "manual",
1720
+ result: undefined,
1721
+ aborted,
1722
+ willRetry: false,
1723
+ errorMessage: aborted ? undefined : `Compaction failed: ${message}`,
1724
+ });
1725
+ throw error;
1726
+ }
1727
+ finally {
1728
+ this._activeCompaction = undefined;
1729
+ this._compactionAbortController = undefined;
1730
+ this._reconnectToAgent();
1731
+ }
1732
+ }
1733
+ /**
1734
+ * Cancel in-progress compaction (manual or auto).
1735
+ */
1736
+ abortCompaction() {
1737
+ this._compactionAbortController?.abort();
1738
+ this._autoCompactionAbortController?.abort();
1739
+ }
1740
+ /**
1741
+ * Cancel in-progress branch summarization.
1742
+ */
1743
+ abortBranchSummary() {
1744
+ this._branchSummaryAbortController?.abort();
1745
+ }
1746
+ /**
1747
+ * Agent-loop hook: stop the run after the current turn when live context
1748
+ * usage crosses the compaction threshold, so threshold compaction runs
1749
+ * mid-task instead of only after the full agent/tool loop finishes.
1750
+ * _handlePostAgentRun always resumes an interrupted run.
1751
+ *
1752
+ * Contract: must not throw (see AgentLoopConfig.shouldStopAfterTurn).
1753
+ */
1754
+ _shouldStopForProactiveCompaction(context) {
1755
+ try {
1756
+ if (this._disposed)
1757
+ return false;
1758
+ const hasQueuedMessages = this.agent.hasQueuedMessages();
1759
+ if (context.toolBatchTerminated && hasQueuedMessages) {
1760
+ this._drainFollowUpsOnNextContinuation = true;
1761
+ }
1762
+ if (this._proactiveCompactionAttempted)
1763
+ return false;
1764
+ // Only interrupt turns that would otherwise continue with another LLM
1765
+ // call. Queued steering/follow-up messages also force a continuation,
1766
+ // including after a plain response or a terminating tool batch.
1767
+ const willContinueForTools = context.toolResults.length > 0 && !context.toolBatchTerminated;
1768
+ if (!willContinueForTools && !hasQueuedMessages)
1769
+ return false;
1770
+ const message = context.message;
1771
+ if (message.stopReason === "aborted" || message.stopReason === "error")
1772
+ return false;
1773
+ const settings = this.settingsManager.getCompactionSettings();
1774
+ if (!settings.enabled)
1775
+ return false;
1776
+ const model = this.model;
1777
+ if (!model || message.provider !== model.provider || message.model !== model.id)
1778
+ return false;
1779
+ // Provider usage predates this turn's tool execution. Estimate from the
1780
+ // live context so newly appended tool results are included before the
1781
+ // loop starts another provider request.
1782
+ const contextTokens = estimateContextTokens(context.context.messages).tokens;
1783
+ if (!shouldCompact(contextTokens, model.contextWindow ?? 0, settings))
1784
+ return false;
1785
+ this._proactiveCompactionAttempted = true;
1786
+ this._proactiveCompactionStopped = true;
1787
+ return true;
1788
+ }
1789
+ catch {
1790
+ return false;
1791
+ }
1792
+ }
1793
+ /**
1794
+ * Check if compaction is needed and run it.
1795
+ * Called after agent_end and before prompt submission.
1796
+ *
1797
+ * Two cases:
1798
+ * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
1799
+ * 2. Threshold: Context over threshold, compact; continue only when a length stop produced no visible output
1800
+ *
1801
+ * @param assistantMessage The assistant message to check
1802
+ * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
1803
+ */
1804
+ async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
1805
+ const settings = this.settingsManager.getCompactionSettings();
1806
+ if (!settings.enabled)
1807
+ return false;
1808
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1809
+ if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
1810
+ return false;
1811
+ const contextWindow = this.model?.contextWindow ?? 0;
1812
+ // Skip overflow check if the message came from a different model.
1813
+ // This handles the case where user switched from a smaller-context model (e.g. opus)
1814
+ // to a larger-context model (e.g. codex) - the overflow error from the old model
1815
+ // shouldn't trigger compaction for the new model.
1816
+ const sameModel = this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
1817
+ // Skip compaction checks if this assistant message is older than the latest
1818
+ // compaction boundary. This prevents a stale pre-compaction usage/error
1819
+ // from retriggering compaction on the first prompt after compaction.
1820
+ const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
1821
+ const assistantIsFromBeforeCompaction = compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
1822
+ if (assistantIsFromBeforeCompaction) {
1823
+ return false;
1824
+ }
1825
+ // Case 1: Overflow - LLM returned context overflow error
1826
+ if (sameModel && isContextOverflow(assistantMessage, contextWindow)) {
1827
+ if (this._overflowRecoveryAttempted) {
1828
+ this._emit({
1829
+ type: "compaction_end",
1830
+ reason: "overflow",
1831
+ result: undefined,
1832
+ aborted: false,
1833
+ willRetry: false,
1834
+ errorMessage: "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
1835
+ });
1836
+ return false;
1837
+ }
1838
+ this._overflowRecoveryAttempted = true;
1839
+ // Remove the error message from agent state (it IS saved to session for history,
1840
+ // but we don't want it in context for the retry)
1841
+ const messages = this.agent.state.messages;
1842
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1843
+ this.agent.state.messages = messages.slice(0, -1);
1844
+ }
1845
+ return await this._runAutoCompaction("overflow", true);
1846
+ }
1847
+ // Case 2: Threshold - context is getting large. Estimate from the live
1848
+ // context so tool results and other messages appended after provider usage
1849
+ // are included. For error messages, require a prior successful usage source.
1850
+ const messages = this.agent.state.messages;
1851
+ const estimate = estimateContextTokens(messages);
1852
+ let contextTokens;
1853
+ if (assistantMessage.stopReason === "error") {
1854
+ if (estimate.lastUsageIndex === null)
1855
+ return false; // No usage data at all
1856
+ // Verify the usage source is post-compaction. Kept pre-compaction messages
1857
+ // have stale usage reflecting the old (larger) context and would falsely
1858
+ // trigger compaction right after one just finished.
1859
+ const usageMsg = messages[estimate.lastUsageIndex];
1860
+ if (compactionEntry &&
1861
+ usageMsg.role === "assistant" &&
1862
+ usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
1863
+ return false;
1864
+ }
1865
+ contextTokens = estimate.tokens;
1866
+ }
1867
+ else {
1868
+ // A lone aborted response may not be considered a trustworthy estimate
1869
+ // source, but its provider usage is still better than a character-only
1870
+ // fallback for the pre-prompt recovery check.
1871
+ contextTokens =
1872
+ estimate.lastUsageIndex === null ? calculateContextTokens(assistantMessage.usage) : estimate.tokens;
1873
+ }
1874
+ if (shouldCompact(contextTokens, contextWindow, settings)) {
1875
+ const continueAfterCompaction = assistantMessage.stopReason === "length" &&
1876
+ !assistantMessage.content.some((content) => (content.type === "text" && content.text.trim().length > 0) || content.type === "toolCall");
1877
+ if (continueAfterCompaction) {
1878
+ return await this._runAutoCompaction("threshold", false, true);
1879
+ }
1880
+ return await this._runAutoCompaction("threshold", false);
1881
+ }
1882
+ return false;
1883
+ }
1884
+ /**
1885
+ * Internal: Run auto-compaction with events.
1886
+ */
1887
+ async _runAutoCompaction(reason, willRetry, continueAfterCompaction = false, continueWithoutCompaction = false) {
1888
+ const settings = this.settingsManager.getCompactionSettings();
1889
+ const abortGeneration = this._abortGeneration;
1890
+ const canContinue = () => !this._disposed && abortGeneration === this._abortGeneration;
1891
+ this._autoCompactionAbortController = new AbortController();
1892
+ this._activeCompaction = { reason, startedAt: Date.now() };
1893
+ this._emit({ type: "compaction_start", reason });
1894
+ try {
1895
+ if (!this.model) {
1896
+ this._emit({
1897
+ type: "compaction_end",
1898
+ reason,
1899
+ result: undefined,
1900
+ aborted: false,
1901
+ willRetry: canContinue() && continueWithoutCompaction,
1902
+ });
1903
+ return false;
1904
+ }
1905
+ let apiKey;
1906
+ let headers;
1907
+ let env;
1908
+ if (this.agent.streamFn === streamSimple) {
1909
+ const authResult = await this._modelRegistry.getApiKeyAndHeaders(this.model);
1910
+ if (!authResult.ok || !authResult.apiKey) {
1911
+ this._emit({
1912
+ type: "compaction_end",
1913
+ reason,
1914
+ result: undefined,
1915
+ aborted: false,
1916
+ willRetry: canContinue() && continueWithoutCompaction,
1917
+ });
1918
+ return false;
1919
+ }
1920
+ apiKey = authResult.apiKey;
1921
+ headers = authResult.headers;
1922
+ env = authResult.env;
1923
+ }
1924
+ else {
1925
+ ({ apiKey, headers, env } = await this._getCompactionRequestAuth(this.model));
1926
+ }
1927
+ const pathEntries = this.sessionManager.getBranch();
1928
+ const preparation = prepareCompaction(pathEntries, settings);
1929
+ if (!preparation) {
1930
+ this._emit({
1931
+ type: "compaction_end",
1932
+ reason,
1933
+ result: undefined,
1934
+ aborted: false,
1935
+ willRetry: canContinue() && continueWithoutCompaction,
1936
+ });
1937
+ return false;
1938
+ }
1939
+ let extensionCompaction;
1940
+ let fromExtension = false;
1941
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1942
+ const extensionResult = (await this._extensionRunner.emit({
1943
+ type: "session_before_compact",
1944
+ preparation,
1945
+ branchEntries: pathEntries,
1946
+ customInstructions: undefined,
1947
+ signal: this._autoCompactionAbortController.signal,
1948
+ }));
1949
+ if (extensionResult?.cancel) {
1950
+ this._emit({
1951
+ type: "compaction_end",
1952
+ reason,
1953
+ result: undefined,
1954
+ aborted: true,
1955
+ willRetry: canContinue() && continueWithoutCompaction,
1956
+ });
1957
+ return false;
1958
+ }
1959
+ if (extensionResult?.compaction) {
1960
+ extensionCompaction = extensionResult.compaction;
1961
+ fromExtension = true;
1962
+ }
1963
+ }
1964
+ let summary;
1965
+ let firstKeptEntryId;
1966
+ let tokensBefore;
1967
+ let details;
1968
+ if (extensionCompaction) {
1969
+ // Extension provided compaction content
1970
+ summary = extensionCompaction.summary;
1971
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1972
+ tokensBefore = extensionCompaction.tokensBefore;
1973
+ details = extensionCompaction.details;
1974
+ }
1975
+ else {
1976
+ // Generate compaction result
1977
+ const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal, this.thinkingLevel, this.agent.streamFn, env);
1978
+ summary = compactResult.summary;
1979
+ firstKeptEntryId = compactResult.firstKeptEntryId;
1980
+ tokensBefore = compactResult.tokensBefore;
1981
+ details = compactResult.details;
1982
+ }
1983
+ if (this._autoCompactionAbortController.signal.aborted) {
1984
+ this._emit({
1985
+ type: "compaction_end",
1986
+ reason,
1987
+ result: undefined,
1988
+ aborted: true,
1989
+ willRetry: canContinue() && continueWithoutCompaction,
1990
+ });
1991
+ return false;
1992
+ }
1993
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1994
+ this._proactiveCompactionAttempted = false;
1995
+ const newEntries = this.sessionManager.getEntries();
1996
+ const sessionContext = this.sessionManager.buildSessionContext();
1997
+ this.agent.state.messages = sessionContext.messages;
1998
+ // Get the saved compaction entry for the extension event
1999
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
2000
+ if (this._extensionRunner && savedCompactionEntry) {
2001
+ await this._extensionRunner.emit({
2002
+ type: "session_compact",
2003
+ compactionEntry: savedCompactionEntry,
2004
+ fromExtension,
2005
+ });
2006
+ }
2007
+ const result = {
2008
+ summary,
2009
+ firstKeptEntryId,
2010
+ tokensBefore,
2011
+ details,
2012
+ };
2013
+ this._emit({
2014
+ type: "compaction_end",
2015
+ reason,
2016
+ result,
2017
+ aborted: false,
2018
+ willRetry: canContinue() && (willRetry || continueAfterCompaction),
2019
+ });
2020
+ if (willRetry) {
2021
+ const messages = this.agent.state.messages;
2022
+ const lastMsg = messages[messages.length - 1];
2023
+ if (lastMsg?.role === "assistant" && lastMsg.stopReason === "error") {
2024
+ this.agent.state.messages = messages.slice(0, -1);
2025
+ }
2026
+ return true;
2027
+ }
2028
+ if (continueAfterCompaction) {
2029
+ return true;
2030
+ }
2031
+ // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
2032
+ // Continue once so queued messages are delivered.
2033
+ return this.agent.hasQueuedMessages();
2034
+ }
2035
+ catch (error) {
2036
+ const aborted = this._autoCompactionAbortController.signal.aborted ||
2037
+ (error instanceof Error && error.name === "AbortError");
2038
+ const errorMessage = error instanceof Error ? error.message : "compaction failed";
2039
+ this._emit({
2040
+ type: "compaction_end",
2041
+ reason,
2042
+ result: undefined,
2043
+ aborted,
2044
+ willRetry: canContinue() && continueWithoutCompaction,
2045
+ ...(aborted
2046
+ ? {}
2047
+ : {
2048
+ errorMessage: reason === "overflow"
2049
+ ? `Context overflow recovery failed: ${errorMessage}`
2050
+ : `Auto-compaction failed: ${errorMessage}`,
2051
+ }),
2052
+ });
2053
+ return false;
2054
+ }
2055
+ finally {
2056
+ this._activeCompaction = undefined;
2057
+ this._autoCompactionAbortController = undefined;
2058
+ }
2059
+ }
2060
+ /**
2061
+ * Toggle auto-compaction setting.
2062
+ */
2063
+ setAutoCompactionEnabled(enabled) {
2064
+ this.settingsManager.setCompactionEnabled(enabled);
2065
+ }
2066
+ /** Whether auto-compaction is enabled */
2067
+ get autoCompactionEnabled() {
2068
+ return this.settingsManager.getCompactionEnabled();
2069
+ }
2070
+ async bindExtensions(bindings) {
2071
+ if (bindings.uiContext !== undefined) {
2072
+ this._extensionUIContext = bindings.uiContext;
2073
+ }
2074
+ if (bindings.mode !== undefined) {
2075
+ this._extensionMode = bindings.mode;
2076
+ }
2077
+ if (bindings.commandContextActions !== undefined) {
2078
+ this._extensionCommandContextActions = bindings.commandContextActions;
2079
+ }
2080
+ if (bindings.abortHandler !== undefined) {
2081
+ this._extensionAbortHandler = bindings.abortHandler;
2082
+ }
2083
+ if (bindings.shutdownHandler !== undefined) {
2084
+ this._extensionShutdownHandler = bindings.shutdownHandler;
2085
+ }
2086
+ if (bindings.onError !== undefined) {
2087
+ this._extensionErrorListener = bindings.onError;
2088
+ }
2089
+ this._applyExtensionBindings(this._extensionRunner);
2090
+ await this._extensionRunner.emit(this._sessionStartEvent);
2091
+ await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
2092
+ }
2093
+ async extendResourcesFromExtensions(reason) {
2094
+ if (!this._extensionRunner.hasHandlers("resources_discover")) {
2095
+ return;
2096
+ }
2097
+ const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
2098
+ if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
2099
+ return;
2100
+ }
2101
+ const extensionPaths = {
2102
+ skillPaths: this.buildExtensionResourcePaths(skillPaths),
2103
+ promptPaths: this.buildExtensionResourcePaths(promptPaths),
2104
+ themePaths: this.buildExtensionResourcePaths(themePaths),
2105
+ };
2106
+ this._resourceLoader.extendResources(extensionPaths);
2107
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
2108
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
2109
+ }
2110
+ buildExtensionResourcePaths(entries) {
2111
+ return entries.map((entry) => {
2112
+ const source = this.getExtensionSourceLabel(entry.extensionPath);
2113
+ const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
2114
+ return {
2115
+ path: entry.path,
2116
+ metadata: {
2117
+ source,
2118
+ scope: "temporary",
2119
+ origin: "top-level",
2120
+ baseDir,
2121
+ },
2122
+ };
2123
+ });
2124
+ }
2125
+ getExtensionSourceLabel(extensionPath) {
2126
+ if (extensionPath.startsWith("<")) {
2127
+ return `extension:${extensionPath.replace(/[<>]/g, "")}`;
2128
+ }
2129
+ const base = basename(extensionPath);
2130
+ const name = base.replace(/\.(ts|js)$/, "");
2131
+ return `extension:${name}`;
2132
+ }
2133
+ _applyExtensionBindings(runner) {
2134
+ runner.setUIContext(this._extensionUIContext, this._extensionMode);
2135
+ runner.bindCommandContext(this._extensionCommandContextActions);
2136
+ this._extensionErrorUnsubscriber?.();
2137
+ this._extensionErrorUnsubscriber = this._extensionErrorListener
2138
+ ? runner.onError(this._extensionErrorListener)
2139
+ : undefined;
2140
+ }
2141
+ _refreshCurrentModelFromRegistry() {
2142
+ const currentModel = this.model;
2143
+ if (!currentModel) {
2144
+ return;
2145
+ }
2146
+ const refreshedModel = this._modelRegistry.find(currentModel.provider, currentModel.id);
2147
+ if (refreshedModel) {
2148
+ if (refreshedModel !== currentModel) {
2149
+ this.agent.state.model = refreshedModel;
2150
+ }
2151
+ return;
2152
+ }
2153
+ const scopedFallback = this._scopedModels
2154
+ .map((scoped) => this._modelRegistry.find(scoped.model.provider, scoped.model.id))
2155
+ .find((model) => model !== undefined && this._modelRegistry.hasConfiguredAuth(model));
2156
+ const fallbackModel = scopedFallback ?? this._modelRegistry.getAvailable()[0];
2157
+ if (!fallbackModel) {
2158
+ this.agent.state.model = undefined;
2159
+ return;
2160
+ }
2161
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
2162
+ this.agent.state.model = fallbackModel;
2163
+ this.sessionManager.appendModelChange(fallbackModel.provider, fallbackModel.id);
2164
+ this.setThinkingLevel(thinkingLevel, { persistDefault: false });
2165
+ }
2166
+ _bindExtensionCore(runner) {
2167
+ const getCommands = () => {
2168
+ const extensionCommands = runner.getRegisteredCommands().map((command) => ({
2169
+ name: command.invocationName,
2170
+ description: command.description,
2171
+ source: "extension",
2172
+ sourceInfo: command.sourceInfo,
2173
+ }));
2174
+ const templates = this.promptTemplates.map((template) => ({
2175
+ name: template.name,
2176
+ description: template.description,
2177
+ source: "prompt",
2178
+ sourceInfo: template.sourceInfo,
2179
+ }));
2180
+ const skills = this._resourceLoader.getSkills().skills.map((skill) => ({
2181
+ name: `skill:${skill.name}`,
2182
+ description: skill.description,
2183
+ source: "skill",
2184
+ sourceInfo: skill.sourceInfo,
2185
+ }));
2186
+ return [...extensionCommands, ...templates, ...skills];
2187
+ };
2188
+ runner.bindCore({
2189
+ sendMessage: (message, options) => {
2190
+ this._sendCustomMessage(message, options, this._activeExtensionCommandHandlers > 0).catch((err) => {
2191
+ runner.emitError({
2192
+ extensionPath: "<runtime>",
2193
+ event: "send_message",
2194
+ error: err instanceof Error ? err.message : String(err),
2195
+ });
2196
+ });
2197
+ },
2198
+ sendUserMessage: (content, options) => {
2199
+ this.sendUserMessage(content, options).catch((err) => {
2200
+ runner.emitError({
2201
+ extensionPath: "<runtime>",
2202
+ event: "send_user_message",
2203
+ error: err instanceof Error ? err.message : String(err),
2204
+ });
2205
+ });
2206
+ },
2207
+ appendEntry: (customType, data) => {
2208
+ this.sessionManager.appendCustomEntry(customType, data);
2209
+ },
2210
+ setSessionName: (name) => {
2211
+ this.setSessionName(name);
2212
+ },
2213
+ getSessionName: () => {
2214
+ return this.sessionManager.getSessionName();
2215
+ },
2216
+ setLabel: (entryId, label) => {
2217
+ this.sessionManager.appendLabelChange(entryId, label);
2218
+ },
2219
+ getActiveTools: () => this.getActiveToolNames(),
2220
+ getAllTools: () => this.getAllTools(),
2221
+ setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
2222
+ refreshTools: () => this._refreshToolRegistry(),
2223
+ getCommands,
2224
+ setModel: async (model) => {
2225
+ if (!this.modelRegistry.hasConfiguredAuth(model))
2226
+ return false;
2227
+ await this.setModel(model);
2228
+ return true;
2229
+ },
2230
+ getThinkingLevel: () => this.thinkingLevel,
2231
+ setThinkingLevel: (level) => this.setThinkingLevel(level),
2232
+ }, {
2233
+ getModel: () => this.model,
2234
+ isIdle: () => !this.isBusy,
2235
+ isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
2236
+ getSignal: () => this.agent.signal,
2237
+ abort: () => {
2238
+ if (this._extensionAbortHandler) {
2239
+ this._extensionAbortHandler();
2240
+ return;
2241
+ }
2242
+ void this.abort();
2243
+ },
2244
+ hasPendingMessages: () => this.pendingMessageCount > 0,
2245
+ shutdown: () => {
2246
+ this._extensionShutdownHandler?.();
2247
+ },
2248
+ getContextUsage: () => this.getContextUsage(),
2249
+ compact: (options) => {
2250
+ void (async () => {
2251
+ try {
2252
+ const result = await this.compact(options?.customInstructions);
2253
+ options?.onComplete?.(result);
2254
+ }
2255
+ catch (error) {
2256
+ const err = error instanceof Error ? error : new Error(String(error));
2257
+ options?.onError?.(err);
2258
+ }
2259
+ })();
2260
+ },
2261
+ getSystemPrompt: () => this.systemPrompt,
2262
+ getSystemPromptOptions: () => this._baseSystemPromptOptions,
2263
+ }, {
2264
+ registerProvider: (name, config) => {
2265
+ this._modelRegistry.registerProvider(name, config);
2266
+ this._refreshCurrentModelFromRegistry();
2267
+ },
2268
+ unregisterProvider: (name) => {
2269
+ this._modelRegistry.unregisterProvider(name);
2270
+ this._refreshCurrentModelFromRegistry();
2271
+ },
2272
+ });
2273
+ }
2274
+ _refreshToolRegistry(options) {
2275
+ const previousRegistryNames = new Set(this._toolRegistry.keys());
2276
+ const previousActiveToolNames = this.getActiveToolNames();
2277
+ const allowedToolNames = this._allowedToolNames;
2278
+ const allowUnlistedExtensionTools = this._allowUnlistedExtensionTools;
2279
+ const excludedToolNames = this._excludedToolNames;
2280
+ const isExcludedTool = (name) => excludedToolNames?.has(name) === true;
2281
+ const isAllowedListedTool = (name) => (!allowedToolNames || allowedToolNames.has(name)) && !isExcludedTool(name);
2282
+ const isAllowedExtensionTool = (name) => !isExcludedTool(name) && (!allowedToolNames || allowUnlistedExtensionTools || allowedToolNames.has(name));
2283
+ const registeredTools = this._extensionRunner.getAllRegisteredTools();
2284
+ const allCustomTools = [
2285
+ ...registeredTools,
2286
+ ...this._customTools.map((definition) => ({
2287
+ definition,
2288
+ sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
2289
+ })),
2290
+ ].filter((tool) => isAllowedExtensionTool(tool.definition.name));
2291
+ const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
2292
+ .filter(([name]) => isAllowedListedTool(name))
2293
+ .map(([name, definition]) => [
2294
+ name,
2295
+ {
2296
+ definition,
2297
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
2298
+ },
2299
+ ]));
2300
+ for (const tool of allCustomTools) {
2301
+ definitionRegistry.set(tool.definition.name, {
2302
+ definition: tool.definition,
2303
+ sourceInfo: tool.sourceInfo,
2304
+ });
2305
+ }
2306
+ this._toolDefinitions = definitionRegistry;
2307
+ this._toolPromptSnippets = new Map(Array.from(definitionRegistry.values())
2308
+ .map(({ definition }) => {
2309
+ const snippet = this._normalizePromptSnippet(definition.promptSnippet);
2310
+ return snippet ? [definition.name, snippet] : undefined;
2311
+ })
2312
+ .filter((entry) => entry !== undefined));
2313
+ this._toolPromptGuidelines = new Map(Array.from(definitionRegistry.values())
2314
+ .map(({ definition }) => {
2315
+ const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
2316
+ return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
2317
+ })
2318
+ .filter((entry) => entry !== undefined));
2319
+ const runner = this._extensionRunner;
2320
+ const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
2321
+ const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
2322
+ .filter((definition) => isAllowedListedTool(definition.name))
2323
+ .map((definition) => ({
2324
+ definition,
2325
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
2326
+ })), runner);
2327
+ const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
2328
+ for (const tool of wrappedExtensionTools) {
2329
+ toolRegistry.set(tool.name, tool);
2330
+ }
2331
+ this._toolRegistry = toolRegistry;
2332
+ const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => this._toolRegistry.has(name));
2333
+ if (allowedToolNames) {
2334
+ for (const toolName of this._toolRegistry.keys()) {
2335
+ if (allowedToolNames.has(toolName)) {
2336
+ nextActiveToolNames.push(toolName);
2337
+ }
2338
+ }
2339
+ if (allowUnlistedExtensionTools) {
2340
+ for (const tool of wrappedExtensionTools) {
2341
+ nextActiveToolNames.push(tool.name);
2342
+ }
2343
+ }
2344
+ }
2345
+ else if (options?.includeAllExtensionTools) {
2346
+ for (const tool of wrappedExtensionTools) {
2347
+ nextActiveToolNames.push(tool.name);
2348
+ }
2349
+ }
2350
+ else if (!options?.activeToolNames) {
2351
+ for (const toolName of this._toolRegistry.keys()) {
2352
+ if (!previousRegistryNames.has(toolName)) {
2353
+ nextActiveToolNames.push(toolName);
2354
+ }
2355
+ }
2356
+ }
2357
+ this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
2358
+ }
2359
+ _buildRuntime(options) {
2360
+ const autoResizeImages = this.settingsManager.getImageAutoResize();
2361
+ const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
2362
+ const shellPath = this.settingsManager.getShellPath();
2363
+ this._lspManager?.dispose();
2364
+ this._lspManager = undefined;
2365
+ const lspConfig = resolveLspConfig(this.settingsManager.getLspSettings());
2366
+ if (lspConfig.enabled) {
2367
+ this._lspManager = new LspManager({
2368
+ cwd: this._cwd,
2369
+ config: lspConfig,
2370
+ hostInteraction: this._hostInteraction,
2371
+ });
2372
+ }
2373
+ const directMcpToolDefinitions = this._mcpManager ? createMcpDirectToolDefinitions(this._mcpManager) : [];
2374
+ const subagentToolManager = this._subagentToolManager &&
2375
+ (this._subagentToolManager.listAvailableDefinitions === undefined ||
2376
+ this._subagentToolManager.listAvailableDefinitions().length > 0)
2377
+ ? this._subagentToolManager
2378
+ : undefined;
2379
+ const baseToolDefinitions = this._baseToolsOverride
2380
+ ? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
2381
+ name,
2382
+ createToolDefinitionFromAgentTool(tool),
2383
+ ]))
2384
+ : createAllToolDefinitions(this._cwd, {
2385
+ read: { autoResizeImages },
2386
+ bash: { commandPrefix: shellCommandPrefix, shellPath },
2387
+ edit: { diagnosticsProvider: this._lspManager },
2388
+ write: { diagnosticsProvider: this._lspManager },
2389
+ webSearch: {
2390
+ operations: createDefaultWebSearchOperations({
2391
+ fallbackBraveApiKey: () => this._modelRegistry.authStorage.getApiKey(BRAVE_SEARCH_AUTH_PROVIDER, {
2392
+ includeFallback: false,
2393
+ }),
2394
+ modelContext: async () => {
2395
+ const model = this.model;
2396
+ if (!model) {
2397
+ return undefined;
2398
+ }
2399
+ if (model.provider !== "openai" && model.provider !== "openai-codex") {
2400
+ return { model };
2401
+ }
2402
+ const auth = await this._modelRegistry.getApiKeyAndHeaders(model);
2403
+ if (!auth.ok) {
2404
+ throw new Error(auth.error);
2405
+ }
2406
+ return {
2407
+ model,
2408
+ apiKey: auth.apiKey,
2409
+ headers: auth.headers,
2410
+ sessionId: this.sessionManager.getSessionId(),
2411
+ };
2412
+ },
2413
+ }),
2414
+ },
2415
+ lsp: { provider: this._lspManager },
2416
+ ...(subagentToolManager
2417
+ ? {
2418
+ subagent: {
2419
+ manager: subagentToolManager,
2420
+ getAllowedTools: () => this.getActiveToolNames(),
2421
+ },
2422
+ }
2423
+ : {}),
2424
+ ...(this._mcpManager ? { mcp: { manager: this._mcpManager } } : {}),
2425
+ });
2426
+ this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
2427
+ for (const definition of directMcpToolDefinitions) {
2428
+ this._baseToolDefinitions.set(definition.name, definition);
2429
+ }
2430
+ const extensionsResult = this._resourceLoader.getExtensions();
2431
+ if (options.flagValues) {
2432
+ for (const [name, value] of options.flagValues) {
2433
+ extensionsResult.runtime.flagValues.set(name, value);
2434
+ }
2435
+ }
2436
+ // May be undefined during construction (first _buildRuntime call).
2437
+ const previousRunner = this._extensionRunner;
2438
+ this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry);
2439
+ if (this._extensionRunnerRef) {
2440
+ this._extensionRunnerRef.current = this._extensionRunner;
2441
+ }
2442
+ // Honor the documented contract: a ctx/volt captured before reload must
2443
+ // not be used after reload. No-ops when the new runner shares the old
2444
+ // runtime (project-trust rebuild), so live generations are unaffected.
2445
+ previousRunner?.invalidateStaleGeneration(extensionsResult.runtime);
2446
+ this._bindExtensionCore(this._extensionRunner);
2447
+ this._applyExtensionBindings(this._extensionRunner);
2448
+ const defaultActiveToolNames = this._baseToolsOverride
2449
+ ? Object.keys(this._baseToolsOverride)
2450
+ : [
2451
+ ...DEFAULT_ACTIVE_TOOL_NAMES,
2452
+ ...(subagentToolManager ? ["subagent"] : []),
2453
+ ...(this._mcpManager ? ["mcp"] : []),
2454
+ ...directMcpToolDefinitions.map((definition) => definition.name),
2455
+ ...(this._lspManager ? ["lsp"] : []),
2456
+ ];
2457
+ const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
2458
+ this._refreshToolRegistry({
2459
+ activeToolNames: baseActiveToolNames,
2460
+ includeAllExtensionTools: options.includeAllExtensionTools,
2461
+ });
2462
+ }
2463
+ async reload() {
2464
+ const previousFlagValues = this._extensionRunner.getFlagValues();
2465
+ await emitSessionShutdownEvent(this._extensionRunner, { type: "session_shutdown", reason: "reload" });
2466
+ await this.settingsManager.reload();
2467
+ this.syncAgentRuntimeSettingsFromSettings();
2468
+ this._modelRegistry.clearRegisteredProviders();
2469
+ await this._resourceLoader.reload();
2470
+ await this._reloadMcpManager();
2471
+ const activeToolNames = this.getActiveToolNames();
2472
+ if (this._mcpManager?.isEnabled() && !this._allowedToolNames && !this._excludedToolNames?.has("mcp")) {
2473
+ if (!activeToolNames.includes("mcp")) {
2474
+ activeToolNames.push("mcp");
2475
+ }
2476
+ for (const candidate of this._mcpManager.getDirectToolCandidates()) {
2477
+ if (!this._excludedToolNames?.has(candidate.directToolName) &&
2478
+ !activeToolNames.includes(candidate.directToolName)) {
2479
+ activeToolNames.push(candidate.directToolName);
2480
+ }
2481
+ }
2482
+ }
2483
+ this._buildRuntime({
2484
+ activeToolNames,
2485
+ flagValues: previousFlagValues,
2486
+ includeAllExtensionTools: true,
2487
+ });
2488
+ this._refreshCurrentModelFromRegistry();
2489
+ const hasBindings = this._extensionUIContext ||
2490
+ this._extensionCommandContextActions ||
2491
+ this._extensionShutdownHandler ||
2492
+ this._extensionErrorListener;
2493
+ if (hasBindings) {
2494
+ await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
2495
+ await this.extendResourcesFromExtensions("reload");
2496
+ }
2497
+ }
2498
+ async _reloadMcpManager() {
2499
+ if (!this._mcpManagerFactory) {
2500
+ return;
2501
+ }
2502
+ const previousManager = this._mcpManager;
2503
+ const nextManager = await this._mcpManagerFactory();
2504
+ if (previousManager && previousManager !== nextManager) {
2505
+ await previousManager.dispose();
2506
+ }
2507
+ this._mcpManager = nextManager;
2508
+ this._attachMcpManagerEvents();
2509
+ if (previousManager !== nextManager) {
2510
+ this._emit({ type: "mcp_servers_changed", servers: nextManager?.listServers() ?? [] });
2511
+ }
2512
+ }
2513
+ /** Forward MCP manager lifecycle events into the session event stream. */
2514
+ _attachMcpManagerEvents() {
2515
+ this._unsubscribeMcpManager?.();
2516
+ this._unsubscribeMcpManager = this._mcpManager?.subscribe((event) => {
2517
+ this._emit(event);
2518
+ });
2519
+ }
2520
+ // =========================================================================
2521
+ // Auto-Retry
2522
+ // =========================================================================
2523
+ _isNonRetryableProviderLimitError(errorMessage) {
2524
+ return /GoUsageLimitError|FreeUsageLimitError|Monthly usage limit reached|available balance|insufficient_quota|out of budget|quota exceeded|billing/i.test(errorMessage);
2525
+ }
2526
+ /**
2527
+ * Check if an error is retryable (overloaded, rate limit, server errors).
2528
+ * Context overflow errors are NOT retryable (handled by compaction instead).
2529
+ */
2530
+ _isRetryableError(message) {
2531
+ if (message.stopReason !== "error" || !message.errorMessage)
2532
+ return false;
2533
+ // Context overflow is handled by compaction, not retry
2534
+ const contextWindow = this.model?.contextWindow ?? 0;
2535
+ if (isContextOverflow(message, contextWindow))
2536
+ return false;
2537
+ const err = message.errorMessage;
2538
+ if (this._isNonRetryableProviderLimitError(err))
2539
+ return false;
2540
+ // Match: overloaded_error, provider returned error, rate limit, 429, 500, 502, 503, 504, service unavailable, network/connection errors (including connection lost), WebSocket transport closes/errors, fetch failed, premature stream endings, HTTP/2 closed before response, terminated, retry delay exceeded
2541
+ return /overloaded|provider.?returned.?error|rate.?limit|too many requests|429|500|502|503|504|service.?unavailable|server.?error|internal.?error|network.?error|connection.?error|connection.?refused|connection.?lost|websocket.?closed|websocket.?error|other side closed|fetch failed|upstream.?connect|reset before headers|socket hang up|ended without|stream ended before message_stop|http2 request did not get a response|timed? out|timeout|terminated|retry delay/i.test(err);
2542
+ }
2543
+ /**
2544
+ * Prepare a retryable error for continuation with exponential backoff.
2545
+ * @returns true if the caller should continue the agent, false otherwise
2546
+ */
2547
+ async _prepareRetry(message, abortGeneration) {
2548
+ const settings = this.settingsManager.getRetrySettings();
2549
+ if (!settings.enabled || this._disposed || abortGeneration !== this._abortGeneration) {
2550
+ return false;
2551
+ }
2552
+ this._retryAttempt++;
2553
+ if (this._retryAttempt > settings.maxRetries) {
2554
+ // Preserve the completed attempt count so post-run handling can emit the final failure.
2555
+ this._retryAttempt--;
2556
+ return false;
2557
+ }
2558
+ const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
2559
+ this._emit({
2560
+ type: "auto_retry_start",
2561
+ attempt: this._retryAttempt,
2562
+ maxAttempts: settings.maxRetries,
2563
+ delayMs,
2564
+ errorMessage: message.errorMessage || "Unknown error",
2565
+ });
2566
+ if (this._disposed || abortGeneration !== this._abortGeneration) {
2567
+ this._settleRetry(false, "Retry cancelled");
2568
+ return false;
2569
+ }
2570
+ // Remove error message from agent state (keep in session for history)
2571
+ const messages = this.agent.state.messages;
2572
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
2573
+ this.agent.state.messages = messages.slice(0, -1);
2574
+ }
2575
+ // Wait with exponential backoff (abortable)
2576
+ this._retryAbortController = new AbortController();
2577
+ try {
2578
+ await sleep(delayMs, this._retryAbortController.signal);
2579
+ }
2580
+ catch {
2581
+ // Aborted during sleep - emit end event so UI can clean up
2582
+ this._settleRetry(false, "Retry cancelled");
2583
+ return false;
2584
+ }
2585
+ finally {
2586
+ this._retryAbortController = undefined;
2587
+ }
2588
+ return !this._disposed && abortGeneration === this._abortGeneration;
2589
+ }
2590
+ /**
2591
+ * Cancel in-progress retry.
2592
+ */
2593
+ abortRetry() {
2594
+ this._retryAbortController?.abort();
2595
+ }
2596
+ /** Whether auto-retry is currently in progress */
2597
+ get isRetrying() {
2598
+ return this._retryAbortController !== undefined;
2599
+ }
2600
+ /** Whether auto-retry is enabled */
2601
+ get autoRetryEnabled() {
2602
+ return this.settingsManager.getRetryEnabled();
2603
+ }
2604
+ /**
2605
+ * Toggle auto-retry setting.
2606
+ */
2607
+ setAutoRetryEnabled(enabled) {
2608
+ this.settingsManager.setRetryEnabled(enabled);
2609
+ }
2610
+ // =========================================================================
2611
+ // Bash Execution
2612
+ // =========================================================================
2613
+ /**
2614
+ * Execute a bash command.
2615
+ * Adds result to agent context and session.
2616
+ * @param command The bash command to execute
2617
+ * @param onChunk Optional streaming callback for output
2618
+ * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
2619
+ * @param options.operations Custom BashOperations for remote execution
2620
+ */
2621
+ async executeBash(command, onChunk, options) {
2622
+ this._bashAbortController = new AbortController();
2623
+ // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
2624
+ const prefix = this.settingsManager.getShellCommandPrefix();
2625
+ const shellPath = this.settingsManager.getShellPath();
2626
+ const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
2627
+ try {
2628
+ const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
2629
+ onChunk,
2630
+ signal: this._bashAbortController.signal,
2631
+ });
2632
+ this.recordBashResult(command, result, options);
2633
+ return result;
2634
+ }
2635
+ finally {
2636
+ this._bashAbortController = undefined;
2637
+ }
2638
+ }
2639
+ /**
2640
+ * Record a bash execution result in session history.
2641
+ * Used by executeBash and by extensions that handle bash execution themselves.
2642
+ */
2643
+ recordBashResult(command, result, options) {
2644
+ const bashMessage = {
2645
+ role: "bashExecution",
2646
+ command,
2647
+ output: result.output,
2648
+ exitCode: result.exitCode,
2649
+ cancelled: result.cancelled,
2650
+ truncated: result.truncated,
2651
+ fullOutputPath: result.fullOutputPath,
2652
+ timestamp: Date.now(),
2653
+ excludeFromContext: options?.excludeFromContext,
2654
+ };
2655
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
2656
+ if (this.isStreaming) {
2657
+ // Queue for later - will be flushed on agent_end
2658
+ this._pendingBashMessages.push(bashMessage);
2659
+ }
2660
+ else {
2661
+ // Add to agent state immediately
2662
+ this.agent.state.messages.push(bashMessage);
2663
+ // Save to session
2664
+ this.sessionManager.appendMessage(bashMessage);
2665
+ }
2666
+ }
2667
+ /**
2668
+ * Cancel running bash command.
2669
+ */
2670
+ abortBash() {
2671
+ this._bashAbortController?.abort();
2672
+ }
2673
+ /** Whether a bash command is currently running */
2674
+ get isBashRunning() {
2675
+ return this._bashAbortController !== undefined;
2676
+ }
2677
+ /** Whether there are pending bash messages waiting to be flushed */
2678
+ get hasPendingBashMessages() {
2679
+ return this._pendingBashMessages.length > 0;
2680
+ }
2681
+ /**
2682
+ * Flush pending bash messages to agent state and session.
2683
+ * Called after agent turn completes to maintain proper message ordering.
2684
+ */
2685
+ _flushPendingBashMessages() {
2686
+ if (this._pendingBashMessages.length === 0)
2687
+ return;
2688
+ for (const bashMessage of this._pendingBashMessages) {
2689
+ // Add to agent state
2690
+ this.agent.state.messages.push(bashMessage);
2691
+ // Save to session
2692
+ this.sessionManager.appendMessage(bashMessage);
2693
+ }
2694
+ this._pendingBashMessages = [];
2695
+ }
2696
+ // =========================================================================
2697
+ // Session Management
2698
+ // =========================================================================
2699
+ /**
2700
+ * Set a display name for the current session.
2701
+ */
2702
+ setSessionName(name) {
2703
+ this.sessionManager.appendSessionInfo(name);
2704
+ this._emit({ type: "session_info_changed", name: this.sessionManager.getSessionName() });
2705
+ }
2706
+ _sessionNameGenerationInFlight = false;
2707
+ /**
2708
+ * Best-effort, fire-and-forget: name an unnamed session from the user's
2709
+ * prompt with a single tiny completion, so session lists show "Fix login
2710
+ * crash" instead of a session-id prefix. Runs concurrently with the turn;
2711
+ * an explicit name set in the meantime wins (checked again before commit).
2712
+ * Never throws and never blocks or fails the prompt itself.
2713
+ */
2714
+ _maybeGenerateSessionName(userText) {
2715
+ if (this._sessionNameGenerationInFlight || this.sessionManager.getSessionName()) {
2716
+ return;
2717
+ }
2718
+ const model = this.model;
2719
+ const request = userText.trim();
2720
+ if (!model || !request) {
2721
+ return;
2722
+ }
2723
+ this._sessionNameGenerationInFlight = true;
2724
+ void (async () => {
2725
+ try {
2726
+ const { apiKey, headers, env } = await this._getCompactionRequestAuth(model);
2727
+ const promptText = `Write a short title (3-6 words, plain text, no quotes, no trailing punctuation) ` +
2728
+ `for a coding session that starts with this request:\n\n<request>\n${request.slice(0, 2000)}\n</request>\n\n` +
2729
+ `Reply with only the title.`;
2730
+ const options = { maxTokens: 64, apiKey, headers, env };
2731
+ const response = await completeSimple(model, {
2732
+ systemPrompt: "You title coding assistant sessions.",
2733
+ messages: [{ role: "user", content: [{ type: "text", text: promptText }], timestamp: Date.now() }],
2734
+ }, options);
2735
+ if (response.stopReason === "error") {
2736
+ return;
2737
+ }
2738
+ const name = AgentSession._sanitizeGeneratedSessionName(response.content
2739
+ .filter((c) => c.type === "text")
2740
+ .map((c) => c.text)
2741
+ .join(" "));
2742
+ if (name && !this._disposed && !this.sessionManager.getSessionName()) {
2743
+ this.setSessionName(name);
2744
+ }
2745
+ }
2746
+ catch {
2747
+ // Naming is cosmetic; the session keeps its id-derived fallback.
2748
+ }
2749
+ finally {
2750
+ this._sessionNameGenerationInFlight = false;
2751
+ }
2752
+ })();
2753
+ }
2754
+ static _sanitizeGeneratedSessionName(raw) {
2755
+ const firstLine = raw.split("\n").find((line) => line.trim().length > 0) ?? "";
2756
+ const name = firstLine
2757
+ .trim()
2758
+ .replace(/^["'`#*\s]+|["'`*\s.]+$/g, "")
2759
+ .replace(/\s+/g, " ");
2760
+ if (!name) {
2761
+ return undefined;
2762
+ }
2763
+ return name.length > 60 ? `${name.slice(0, 57)}…` : name;
2764
+ }
2765
+ // =========================================================================
2766
+ // Tree Navigation
2767
+ // =========================================================================
2768
+ /**
2769
+ * Navigate to a different node in the session tree.
2770
+ * Unlike fork() which creates a new session file, this stays in the same file.
2771
+ *
2772
+ * @param targetId The entry ID to navigate to
2773
+ * @param options.summarize Whether user wants to summarize abandoned branch
2774
+ * @param options.customInstructions Custom instructions for summarizer
2775
+ * @param options.replaceInstructions If true, customInstructions replaces the default prompt
2776
+ * @param options.label Label to attach to the branch summary entry
2777
+ * @returns Result with editorText (if user message) and cancelled status
2778
+ */
2779
+ navigateTree(targetId, options = {}) {
2780
+ return this._trackSessionOperation(() => this._navigateTree(targetId, options));
2781
+ }
2782
+ async _navigateTree(targetId, options) {
2783
+ const oldLeafId = this.sessionManager.getLeafId();
2784
+ // No-op if already at target
2785
+ if (targetId === oldLeafId) {
2786
+ return { cancelled: false };
2787
+ }
2788
+ // Model required for summarization
2789
+ if (options.summarize && !this.model) {
2790
+ throw new Error("No model available for summarization");
2791
+ }
2792
+ const targetEntry = this.sessionManager.getEntry(targetId);
2793
+ if (!targetEntry) {
2794
+ throw new Error(`Entry ${targetId} not found`);
2795
+ }
2796
+ // Collect entries to summarize (from old leaf to common ancestor)
2797
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
2798
+ // Prepare event data - mutable so extensions can override
2799
+ let customInstructions = options.customInstructions;
2800
+ let replaceInstructions = options.replaceInstructions;
2801
+ let label = options.label;
2802
+ const preparation = {
2803
+ targetId,
2804
+ oldLeafId,
2805
+ commonAncestorId,
2806
+ entriesToSummarize,
2807
+ userWantsSummary: options.summarize ?? false,
2808
+ customInstructions,
2809
+ replaceInstructions,
2810
+ label,
2811
+ };
2812
+ // Set up abort controller for summarization
2813
+ this._branchSummaryAbortController = new AbortController();
2814
+ try {
2815
+ let extensionSummary;
2816
+ let fromExtension = false;
2817
+ // Emit session_before_tree event
2818
+ if (this._extensionRunner.hasHandlers("session_before_tree")) {
2819
+ const result = (await this._extensionRunner.emit({
2820
+ type: "session_before_tree",
2821
+ preparation,
2822
+ signal: this._branchSummaryAbortController.signal,
2823
+ }));
2824
+ if (result?.cancel) {
2825
+ return { cancelled: true };
2826
+ }
2827
+ if (result?.summary && options.summarize) {
2828
+ extensionSummary = result.summary;
2829
+ fromExtension = true;
2830
+ }
2831
+ // Allow extensions to override instructions and label
2832
+ if (result?.customInstructions !== undefined) {
2833
+ customInstructions = result.customInstructions;
2834
+ }
2835
+ if (result?.replaceInstructions !== undefined) {
2836
+ replaceInstructions = result.replaceInstructions;
2837
+ }
2838
+ if (result?.label !== undefined) {
2839
+ label = result.label;
2840
+ }
2841
+ }
2842
+ // Run default summarizer if needed
2843
+ let summaryText;
2844
+ let summaryDetails;
2845
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2846
+ const model = this.model;
2847
+ const { apiKey, headers, env } = await this._getRequiredRequestAuth(model);
2848
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2849
+ const result = await generateBranchSummary(entriesToSummarize, {
2850
+ model,
2851
+ apiKey,
2852
+ headers,
2853
+ env,
2854
+ signal: this._branchSummaryAbortController.signal,
2855
+ customInstructions,
2856
+ replaceInstructions,
2857
+ reserveTokens: branchSummarySettings.reserveTokens,
2858
+ streamFn: this.agent.streamFn,
2859
+ });
2860
+ if (result.aborted) {
2861
+ return { cancelled: true, aborted: true };
2862
+ }
2863
+ if (result.error) {
2864
+ throw new Error(result.error);
2865
+ }
2866
+ summaryText = result.summary;
2867
+ summaryDetails = {
2868
+ readFiles: result.readFiles || [],
2869
+ modifiedFiles: result.modifiedFiles || [],
2870
+ };
2871
+ }
2872
+ else if (extensionSummary) {
2873
+ summaryText = extensionSummary.summary;
2874
+ summaryDetails = extensionSummary.details;
2875
+ }
2876
+ // Determine the new leaf position based on target type
2877
+ let newLeafId;
2878
+ let editorText;
2879
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
2880
+ // User message: leaf = parent (null if root), text goes to editor
2881
+ newLeafId = targetEntry.parentId;
2882
+ editorText = this._extractUserMessageText(targetEntry.message.content);
2883
+ }
2884
+ else if (targetEntry.type === "custom_message") {
2885
+ // Custom message: leaf = parent (null if root), text goes to editor
2886
+ newLeafId = targetEntry.parentId;
2887
+ editorText =
2888
+ typeof targetEntry.content === "string"
2889
+ ? targetEntry.content
2890
+ : targetEntry.content
2891
+ .filter((c) => c.type === "text")
2892
+ .map((c) => c.text)
2893
+ .join("");
2894
+ }
2895
+ else {
2896
+ // Non-user message: leaf = selected node
2897
+ newLeafId = targetId;
2898
+ }
2899
+ // Switch leaf (with or without summary)
2900
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
2901
+ let summaryEntry;
2902
+ if (summaryText) {
2903
+ // Create summary at target position (can be null for root)
2904
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
2905
+ summaryEntry = this.sessionManager.getEntry(summaryId);
2906
+ // Attach label to the summary entry
2907
+ if (label) {
2908
+ this.sessionManager.appendLabelChange(summaryId, label);
2909
+ }
2910
+ }
2911
+ else if (newLeafId === null) {
2912
+ // No summary, navigating to root - reset leaf
2913
+ this.sessionManager.resetLeaf();
2914
+ }
2915
+ else {
2916
+ // No summary, navigating to non-root
2917
+ this.sessionManager.branch(newLeafId);
2918
+ }
2919
+ // Attach label to target entry when not summarizing (no summary entry to label)
2920
+ if (label && !summaryText) {
2921
+ this.sessionManager.appendLabelChange(targetId, label);
2922
+ }
2923
+ // Update agent state
2924
+ const sessionContext = this.sessionManager.buildSessionContext();
2925
+ this.agent.state.messages = sessionContext.messages;
2926
+ // Emit session_tree event
2927
+ await this._extensionRunner.emit({
2928
+ type: "session_tree",
2929
+ newLeafId: this.sessionManager.getLeafId(),
2930
+ oldLeafId,
2931
+ summaryEntry,
2932
+ fromExtension: summaryText ? fromExtension : undefined,
2933
+ });
2934
+ // Emit to custom tools
2935
+ return { editorText, cancelled: false, summaryEntry };
2936
+ }
2937
+ finally {
2938
+ this._branchSummaryAbortController = undefined;
2939
+ }
2940
+ }
2941
+ /**
2942
+ * Get all user messages from session for fork selector.
2943
+ */
2944
+ getUserMessagesForForking() {
2945
+ const entries = this.sessionManager.getEntries();
2946
+ const result = [];
2947
+ for (const entry of entries) {
2948
+ if (entry.type !== "message")
2949
+ continue;
2950
+ if (entry.message.role !== "user")
2951
+ continue;
2952
+ const text = this._extractUserMessageText(entry.message.content);
2953
+ if (text) {
2954
+ result.push({ entryId: entry.id, text });
2955
+ }
2956
+ }
2957
+ return result;
2958
+ }
2959
+ _extractUserMessageText(content) {
2960
+ if (typeof content === "string")
2961
+ return content;
2962
+ if (Array.isArray(content)) {
2963
+ return content
2964
+ .filter((c) => c.type === "text")
2965
+ .map((c) => c.text)
2966
+ .join("");
2967
+ }
2968
+ return "";
2969
+ }
2970
+ /**
2971
+ * Get session statistics.
2972
+ */
2973
+ getSessionStats() {
2974
+ const state = this.state;
2975
+ const userMessages = state.messages.filter((m) => m.role === "user").length;
2976
+ const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
2977
+ const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
2978
+ let toolCalls = 0;
2979
+ let totalInput = 0;
2980
+ let totalOutput = 0;
2981
+ let totalCacheRead = 0;
2982
+ let totalCacheWrite = 0;
2983
+ let totalCost = 0;
2984
+ for (const message of state.messages) {
2985
+ if (message.role === "assistant") {
2986
+ const assistantMsg = message;
2987
+ toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
2988
+ totalInput += assistantMsg.usage.input;
2989
+ totalOutput += assistantMsg.usage.output;
2990
+ totalCacheRead += assistantMsg.usage.cacheRead;
2991
+ totalCacheWrite += assistantMsg.usage.cacheWrite;
2992
+ totalCost += assistantMsg.usage.cost.total;
2993
+ }
2994
+ }
2995
+ return {
2996
+ sessionFile: this.sessionFile,
2997
+ sessionId: this.sessionId,
2998
+ userMessages,
2999
+ assistantMessages,
3000
+ toolCalls,
3001
+ toolResults,
3002
+ totalMessages: state.messages.length,
3003
+ tokens: {
3004
+ input: totalInput,
3005
+ output: totalOutput,
3006
+ cacheRead: totalCacheRead,
3007
+ cacheWrite: totalCacheWrite,
3008
+ total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
3009
+ },
3010
+ cost: totalCost,
3011
+ contextUsage: this.getContextUsage(),
3012
+ };
3013
+ }
3014
+ getContextUsage() {
3015
+ const model = this.model;
3016
+ if (!model)
3017
+ return undefined;
3018
+ const contextWindow = model.contextWindow ?? 0;
3019
+ if (contextWindow <= 0)
3020
+ return undefined;
3021
+ // After compaction, the last assistant usage reflects pre-compaction context size.
3022
+ // We can only trust usage from an assistant that responded after the latest compaction.
3023
+ // If no such assistant exists, context token count is unknown until the next LLM response.
3024
+ const branchEntries = this.sessionManager.getBranch();
3025
+ const latestCompaction = getLatestCompactionEntry(branchEntries);
3026
+ if (latestCompaction) {
3027
+ // Check if there's a valid assistant usage after the compaction boundary
3028
+ const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
3029
+ let hasPostCompactionUsage = false;
3030
+ for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
3031
+ const entry = branchEntries[i];
3032
+ if (entry.type === "message" && entry.message.role === "assistant") {
3033
+ const assistant = entry.message;
3034
+ if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
3035
+ const contextTokens = calculateContextTokens(assistant.usage);
3036
+ if (contextTokens > 0) {
3037
+ hasPostCompactionUsage = true;
3038
+ }
3039
+ break;
3040
+ }
3041
+ }
3042
+ }
3043
+ if (!hasPostCompactionUsage) {
3044
+ return { tokens: null, contextWindow, percent: null };
3045
+ }
3046
+ }
3047
+ const estimate = estimateContextTokens(this.messages);
3048
+ const percent = (estimate.tokens / contextWindow) * 100;
3049
+ return {
3050
+ tokens: estimate.tokens,
3051
+ contextWindow,
3052
+ percent,
3053
+ };
3054
+ }
3055
+ /**
3056
+ * Export session to HTML.
3057
+ * @param outputPath Optional output path (defaults to session directory)
3058
+ * @returns Path to exported file
3059
+ */
3060
+ async exportToHtml(outputPath) {
3061
+ const configuredThemeName = this.settingsManager.getTheme();
3062
+ const themeName = configuredThemeName && getThemeByName(configuredThemeName) ? configuredThemeName : undefined;
3063
+ // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
3064
+ const toolRenderer = createToolHtmlRenderer({
3065
+ getToolDefinition: (name) => this.getToolDefinition(name),
3066
+ theme,
3067
+ cwd: this.sessionManager.getCwd(),
3068
+ });
3069
+ return await exportSessionToHtml(this.sessionManager, this.state, {
3070
+ outputPath,
3071
+ themeName,
3072
+ toolRenderer,
3073
+ });
3074
+ }
3075
+ /**
3076
+ * Export the current session branch to a JSONL file.
3077
+ * Writes the session header followed by all entries on the current branch path.
3078
+ * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
3079
+ * @returns The resolved output file path.
3080
+ */
3081
+ exportToJsonl(outputPath) {
3082
+ const filePath = resolvePath(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`, process.cwd());
3083
+ const header = {
3084
+ type: "session",
3085
+ version: CURRENT_SESSION_VERSION,
3086
+ id: this.sessionManager.getSessionId(),
3087
+ timestamp: new Date().toISOString(),
3088
+ cwd: this.sessionManager.getCwd(),
3089
+ };
3090
+ const branchEntries = this.sessionManager.getBranch();
3091
+ const lines = [JSON.stringify(header)];
3092
+ // Re-chain parentIds to form a linear sequence
3093
+ let prevId = null;
3094
+ for (const entry of branchEntries) {
3095
+ const linear = { ...entry, parentId: prevId };
3096
+ lines.push(JSON.stringify(linear));
3097
+ prevId = entry.id;
3098
+ }
3099
+ writeDurableAtomicFileSync(filePath, `${lines.join("\n")}\n`, {
3100
+ directoryMode: PRIVATE_DIRECTORY_MODE,
3101
+ fileMode: PRIVATE_FILE_MODE,
3102
+ });
3103
+ return filePath;
3104
+ }
3105
+ // =========================================================================
3106
+ // Utilities
3107
+ // =========================================================================
3108
+ /**
3109
+ * Get text content of last assistant message.
3110
+ * Useful for /copy command.
3111
+ * @returns Text content, or undefined if no assistant message exists
3112
+ */
3113
+ getLastAssistantText() {
3114
+ const lastAssistant = this.messages
3115
+ .slice()
3116
+ .reverse()
3117
+ .find((m) => {
3118
+ if (m.role !== "assistant")
3119
+ return false;
3120
+ const msg = m;
3121
+ // Skip aborted messages with no content
3122
+ if (msg.stopReason === "aborted" && msg.content.length === 0)
3123
+ return false;
3124
+ return true;
3125
+ });
3126
+ if (!lastAssistant)
3127
+ return undefined;
3128
+ let text = "";
3129
+ for (const content of lastAssistant.content) {
3130
+ if (content.type === "text") {
3131
+ text += content.text;
3132
+ }
3133
+ }
3134
+ return text.trim() || undefined;
3135
+ }
3136
+ // =========================================================================
3137
+ // Extension System
3138
+ // =========================================================================
3139
+ createReplacedSessionContext() {
3140
+ const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
3141
+ context.sendMessage = (message, options) => this._sendCustomMessage(message, options, true);
3142
+ context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
3143
+ return context;
3144
+ }
3145
+ /**
3146
+ * Check if extensions have handlers for a specific event type.
3147
+ */
3148
+ hasExtensionHandlers(eventType) {
3149
+ return this._extensionRunner.hasHandlers(eventType);
3150
+ }
3151
+ /**
3152
+ * Get the extension runner (for setting UI context and error handlers).
3153
+ */
3154
+ get extensionRunner() {
3155
+ return this._extensionRunner;
3156
+ }
3157
+ }
3158
+ //# sourceMappingURL=agent-session.js.map