@voxcode-dev/voxcode 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 (738) hide show
  1. package/CHANGELOG.md +4339 -0
  2. package/README.md +71 -0
  3. package/dist/bun/cli.d.ts +3 -0
  4. package/dist/bun/cli.d.ts.map +1 -0
  5. package/dist/bun/cli.js +9 -0
  6. package/dist/bun/cli.js.map +1 -0
  7. package/dist/bun/register-bedrock.d.ts +2 -0
  8. package/dist/bun/register-bedrock.d.ts.map +1 -0
  9. package/dist/bun/register-bedrock.js +4 -0
  10. package/dist/bun/register-bedrock.js.map +1 -0
  11. package/dist/bun/restore-sandbox-env.d.ts +13 -0
  12. package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
  13. package/dist/bun/restore-sandbox-env.js +32 -0
  14. package/dist/bun/restore-sandbox-env.js.map +1 -0
  15. package/dist/cli/args.d.ts +53 -0
  16. package/dist/cli/args.d.ts.map +1 -0
  17. package/dist/cli/args.js +341 -0
  18. package/dist/cli/args.js.map +1 -0
  19. package/dist/cli/config-selector.d.ts +14 -0
  20. package/dist/cli/config-selector.d.ts.map +1 -0
  21. package/dist/cli/config-selector.js +31 -0
  22. package/dist/cli/config-selector.js.map +1 -0
  23. package/dist/cli/file-processor.d.ts +15 -0
  24. package/dist/cli/file-processor.d.ts.map +1 -0
  25. package/dist/cli/file-processor.js +82 -0
  26. package/dist/cli/file-processor.js.map +1 -0
  27. package/dist/cli/initial-message.d.ts +18 -0
  28. package/dist/cli/initial-message.d.ts.map +1 -0
  29. package/dist/cli/initial-message.js +22 -0
  30. package/dist/cli/initial-message.js.map +1 -0
  31. package/dist/cli/list-models.d.ts +9 -0
  32. package/dist/cli/list-models.d.ts.map +1 -0
  33. package/dist/cli/list-models.js +98 -0
  34. package/dist/cli/list-models.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.d.ts +3 -0
  40. package/dist/cli.d.ts.map +1 -0
  41. package/dist/cli.js +18 -0
  42. package/dist/cli.js.map +1 -0
  43. package/dist/config.d.ts +92 -0
  44. package/dist/config.d.ts.map +1 -0
  45. package/dist/config.js +415 -0
  46. package/dist/config.js.map +1 -0
  47. package/dist/core/agent-session-runtime.d.ts +117 -0
  48. package/dist/core/agent-session-runtime.d.ts.map +1 -0
  49. package/dist/core/agent-session-runtime.js +300 -0
  50. package/dist/core/agent-session-runtime.js.map +1 -0
  51. package/dist/core/agent-session-services.d.ts +86 -0
  52. package/dist/core/agent-session-services.d.ts.map +1 -0
  53. package/dist/core/agent-session-services.js +118 -0
  54. package/dist/core/agent-session-services.js.map +1 -0
  55. package/dist/core/agent-session.d.ts +598 -0
  56. package/dist/core/agent-session.d.ts.map +1 -0
  57. package/dist/core/agent-session.js +2498 -0
  58. package/dist/core/agent-session.js.map +1 -0
  59. package/dist/core/auth-guidance.d.ts +5 -0
  60. package/dist/core/auth-guidance.d.ts.map +1 -0
  61. package/dist/core/auth-guidance.js +21 -0
  62. package/dist/core/auth-guidance.js.map +1 -0
  63. package/dist/core/auth-storage.d.ts +141 -0
  64. package/dist/core/auth-storage.d.ts.map +1 -0
  65. package/dist/core/auth-storage.js +442 -0
  66. package/dist/core/auth-storage.js.map +1 -0
  67. package/dist/core/bash-executor.d.ts +32 -0
  68. package/dist/core/bash-executor.d.ts.map +1 -0
  69. package/dist/core/bash-executor.js +111 -0
  70. package/dist/core/bash-executor.js.map +1 -0
  71. package/dist/core/compaction/branch-summarization.d.ts +88 -0
  72. package/dist/core/compaction/branch-summarization.d.ts.map +1 -0
  73. package/dist/core/compaction/branch-summarization.js +243 -0
  74. package/dist/core/compaction/branch-summarization.js.map +1 -0
  75. package/dist/core/compaction/compaction.d.ts +121 -0
  76. package/dist/core/compaction/compaction.d.ts.map +1 -0
  77. package/dist/core/compaction/compaction.js +625 -0
  78. package/dist/core/compaction/compaction.js.map +1 -0
  79. package/dist/core/compaction/index.d.ts +7 -0
  80. package/dist/core/compaction/index.d.ts.map +1 -0
  81. package/dist/core/compaction/index.js +7 -0
  82. package/dist/core/compaction/index.js.map +1 -0
  83. package/dist/core/compaction/utils.d.ts +38 -0
  84. package/dist/core/compaction/utils.d.ts.map +1 -0
  85. package/dist/core/compaction/utils.js +153 -0
  86. package/dist/core/compaction/utils.js.map +1 -0
  87. package/dist/core/defaults.d.ts +3 -0
  88. package/dist/core/defaults.d.ts.map +1 -0
  89. package/dist/core/defaults.js +2 -0
  90. package/dist/core/defaults.js.map +1 -0
  91. package/dist/core/diagnostics.d.ts +15 -0
  92. package/dist/core/diagnostics.d.ts.map +1 -0
  93. package/dist/core/diagnostics.js +2 -0
  94. package/dist/core/diagnostics.js.map +1 -0
  95. package/dist/core/event-bus.d.ts +9 -0
  96. package/dist/core/event-bus.d.ts.map +1 -0
  97. package/dist/core/event-bus.js +25 -0
  98. package/dist/core/event-bus.js.map +1 -0
  99. package/dist/core/exec.d.ts +29 -0
  100. package/dist/core/exec.d.ts.map +1 -0
  101. package/dist/core/exec.js +75 -0
  102. package/dist/core/exec.js.map +1 -0
  103. package/dist/core/export-html/ansi-to-html.d.ts +22 -0
  104. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -0
  105. package/dist/core/export-html/ansi-to-html.js +249 -0
  106. package/dist/core/export-html/ansi-to-html.js.map +1 -0
  107. package/dist/core/export-html/index.d.ts +37 -0
  108. package/dist/core/export-html/index.d.ts.map +1 -0
  109. package/dist/core/export-html/index.js +226 -0
  110. package/dist/core/export-html/index.js.map +1 -0
  111. package/dist/core/export-html/template.css +1066 -0
  112. package/dist/core/export-html/template.html +55 -0
  113. package/dist/core/export-html/template.js +1851 -0
  114. package/dist/core/export-html/tool-renderer.d.ts +34 -0
  115. package/dist/core/export-html/tool-renderer.d.ts.map +1 -0
  116. package/dist/core/export-html/tool-renderer.js +108 -0
  117. package/dist/core/export-html/tool-renderer.js.map +1 -0
  118. package/dist/core/export-html/vendor/highlight.min.js +1213 -0
  119. package/dist/core/export-html/vendor/marked.min.js +6 -0
  120. package/dist/core/extensions/index.d.ts +12 -0
  121. package/dist/core/extensions/index.d.ts.map +1 -0
  122. package/dist/core/extensions/index.js +9 -0
  123. package/dist/core/extensions/index.js.map +1 -0
  124. package/dist/core/extensions/loader.d.ts +24 -0
  125. package/dist/core/extensions/loader.d.ts.map +1 -0
  126. package/dist/core/extensions/loader.js +473 -0
  127. package/dist/core/extensions/loader.js.map +1 -0
  128. package/dist/core/extensions/runner.d.ts +159 -0
  129. package/dist/core/extensions/runner.d.ts.map +1 -0
  130. package/dist/core/extensions/runner.js +824 -0
  131. package/dist/core/extensions/runner.js.map +1 -0
  132. package/dist/core/extensions/types.d.ts +1173 -0
  133. package/dist/core/extensions/types.d.ts.map +1 -0
  134. package/dist/core/extensions/types.js +45 -0
  135. package/dist/core/extensions/types.js.map +1 -0
  136. package/dist/core/extensions/wrapper.d.ts +20 -0
  137. package/dist/core/extensions/wrapper.d.ts.map +1 -0
  138. package/dist/core/extensions/wrapper.js +22 -0
  139. package/dist/core/extensions/wrapper.js.map +1 -0
  140. package/dist/core/footer-data-provider.d.ts +52 -0
  141. package/dist/core/footer-data-provider.d.ts.map +1 -0
  142. package/dist/core/footer-data-provider.js +310 -0
  143. package/dist/core/footer-data-provider.js.map +1 -0
  144. package/dist/core/http-dispatcher.d.ts +21 -0
  145. package/dist/core/http-dispatcher.d.ts.map +1 -0
  146. package/dist/core/http-dispatcher.js +48 -0
  147. package/dist/core/http-dispatcher.js.map +1 -0
  148. package/dist/core/index.d.ts +12 -0
  149. package/dist/core/index.d.ts.map +1 -0
  150. package/dist/core/index.js +12 -0
  151. package/dist/core/index.js.map +1 -0
  152. package/dist/core/keybindings.d.ts +353 -0
  153. package/dist/core/keybindings.d.ts.map +1 -0
  154. package/dist/core/keybindings.js +295 -0
  155. package/dist/core/keybindings.js.map +1 -0
  156. package/dist/core/messages.d.ts +77 -0
  157. package/dist/core/messages.d.ts.map +1 -0
  158. package/dist/core/messages.js +123 -0
  159. package/dist/core/messages.js.map +1 -0
  160. package/dist/core/model-registry.d.ts +150 -0
  161. package/dist/core/model-registry.d.ts.map +1 -0
  162. package/dist/core/model-registry.js +732 -0
  163. package/dist/core/model-registry.js.map +1 -0
  164. package/dist/core/model-resolver.d.ts +110 -0
  165. package/dist/core/model-resolver.d.ts.map +1 -0
  166. package/dist/core/model-resolver.js +495 -0
  167. package/dist/core/model-resolver.js.map +1 -0
  168. package/dist/core/output-guard.d.ts +6 -0
  169. package/dist/core/output-guard.d.ts.map +1 -0
  170. package/dist/core/output-guard.js +59 -0
  171. package/dist/core/output-guard.js.map +1 -0
  172. package/dist/core/package-manager.d.ts +204 -0
  173. package/dist/core/package-manager.d.ts.map +1 -0
  174. package/dist/core/package-manager.js +2040 -0
  175. package/dist/core/package-manager.js.map +1 -0
  176. package/dist/core/prompt-templates.d.ts +52 -0
  177. package/dist/core/prompt-templates.d.ts.map +1 -0
  178. package/dist/core/prompt-templates.js +238 -0
  179. package/dist/core/prompt-templates.js.map +1 -0
  180. package/dist/core/provider-display-names.d.ts +2 -0
  181. package/dist/core/provider-display-names.d.ts.map +1 -0
  182. package/dist/core/provider-display-names.js +33 -0
  183. package/dist/core/provider-display-names.js.map +1 -0
  184. package/dist/core/resolve-config-value.d.ts +23 -0
  185. package/dist/core/resolve-config-value.d.ts.map +1 -0
  186. package/dist/core/resolve-config-value.js +126 -0
  187. package/dist/core/resolve-config-value.js.map +1 -0
  188. package/dist/core/resource-loader.d.ts +194 -0
  189. package/dist/core/resource-loader.d.ts.map +1 -0
  190. package/dist/core/resource-loader.js +734 -0
  191. package/dist/core/resource-loader.js.map +1 -0
  192. package/dist/core/sdk.d.ts +107 -0
  193. package/dist/core/sdk.d.ts.map +1 -0
  194. package/dist/core/sdk.js +287 -0
  195. package/dist/core/sdk.js.map +1 -0
  196. package/dist/core/session-cwd.d.ts +19 -0
  197. package/dist/core/session-cwd.d.ts.map +1 -0
  198. package/dist/core/session-cwd.js +38 -0
  199. package/dist/core/session-cwd.js.map +1 -0
  200. package/dist/core/session-manager.d.ts +333 -0
  201. package/dist/core/session-manager.d.ts.map +1 -0
  202. package/dist/core/session-manager.js +1147 -0
  203. package/dist/core/session-manager.js.map +1 -0
  204. package/dist/core/settings-manager.d.ts +264 -0
  205. package/dist/core/settings-manager.d.ts.map +1 -0
  206. package/dist/core/settings-manager.js +795 -0
  207. package/dist/core/settings-manager.js.map +1 -0
  208. package/dist/core/skills.d.ts +60 -0
  209. package/dist/core/skills.d.ts.map +1 -0
  210. package/dist/core/skills.js +387 -0
  211. package/dist/core/skills.js.map +1 -0
  212. package/dist/core/slash-commands.d.ts +14 -0
  213. package/dist/core/slash-commands.d.ts.map +1 -0
  214. package/dist/core/slash-commands.js +25 -0
  215. package/dist/core/slash-commands.js.map +1 -0
  216. package/dist/core/source-info.d.ts +18 -0
  217. package/dist/core/source-info.d.ts.map +1 -0
  218. package/dist/core/source-info.js +19 -0
  219. package/dist/core/source-info.js.map +1 -0
  220. package/dist/core/system-prompt.d.ts +28 -0
  221. package/dist/core/system-prompt.d.ts.map +1 -0
  222. package/dist/core/system-prompt.js +123 -0
  223. package/dist/core/system-prompt.js.map +1 -0
  224. package/dist/core/telemetry.d.ts +3 -0
  225. package/dist/core/telemetry.d.ts.map +1 -0
  226. package/dist/core/telemetry.js +9 -0
  227. package/dist/core/telemetry.js.map +1 -0
  228. package/dist/core/timings.d.ts +8 -0
  229. package/dist/core/timings.d.ts.map +1 -0
  230. package/dist/core/timings.js +31 -0
  231. package/dist/core/timings.js.map +1 -0
  232. package/dist/core/tools/bash.d.ts +68 -0
  233. package/dist/core/tools/bash.d.ts.map +1 -0
  234. package/dist/core/tools/bash.js +337 -0
  235. package/dist/core/tools/bash.js.map +1 -0
  236. package/dist/core/tools/edit-diff.d.ts +87 -0
  237. package/dist/core/tools/edit-diff.d.ts.map +1 -0
  238. package/dist/core/tools/edit-diff.js +345 -0
  239. package/dist/core/tools/edit-diff.js.map +1 -0
  240. package/dist/core/tools/edit.d.ts +51 -0
  241. package/dist/core/tools/edit.d.ts.map +1 -0
  242. package/dist/core/tools/edit.js +287 -0
  243. package/dist/core/tools/edit.js.map +1 -0
  244. package/dist/core/tools/file-mutation-queue.d.ts +6 -0
  245. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -0
  246. package/dist/core/tools/file-mutation-queue.js +52 -0
  247. package/dist/core/tools/file-mutation-queue.js.map +1 -0
  248. package/dist/core/tools/find.d.ts +35 -0
  249. package/dist/core/tools/find.d.ts.map +1 -0
  250. package/dist/core/tools/find.js +297 -0
  251. package/dist/core/tools/find.js.map +1 -0
  252. package/dist/core/tools/grep.d.ts +37 -0
  253. package/dist/core/tools/grep.d.ts.map +1 -0
  254. package/dist/core/tools/grep.js +304 -0
  255. package/dist/core/tools/grep.js.map +1 -0
  256. package/dist/core/tools/index.d.ts +40 -0
  257. package/dist/core/tools/index.d.ts.map +1 -0
  258. package/dist/core/tools/index.js +112 -0
  259. package/dist/core/tools/index.js.map +1 -0
  260. package/dist/core/tools/ls.d.ts +37 -0
  261. package/dist/core/tools/ls.d.ts.map +1 -0
  262. package/dist/core/tools/ls.js +169 -0
  263. package/dist/core/tools/ls.js.map +1 -0
  264. package/dist/core/tools/output-accumulator.d.ts +52 -0
  265. package/dist/core/tools/output-accumulator.d.ts.map +1 -0
  266. package/dist/core/tools/output-accumulator.js +184 -0
  267. package/dist/core/tools/output-accumulator.js.map +1 -0
  268. package/dist/core/tools/path-utils.d.ts +10 -0
  269. package/dist/core/tools/path-utils.d.ts.map +1 -0
  270. package/dist/core/tools/path-utils.js +99 -0
  271. package/dist/core/tools/path-utils.js.map +1 -0
  272. package/dist/core/tools/read.d.ts +35 -0
  273. package/dist/core/tools/read.d.ts.map +1 -0
  274. package/dist/core/tools/read.js +290 -0
  275. package/dist/core/tools/read.js.map +1 -0
  276. package/dist/core/tools/render-utils.d.ts +21 -0
  277. package/dist/core/tools/render-utils.d.ts.map +1 -0
  278. package/dist/core/tools/render-utils.js +49 -0
  279. package/dist/core/tools/render-utils.js.map +1 -0
  280. package/dist/core/tools/tool-definition-wrapper.d.ts +14 -0
  281. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -0
  282. package/dist/core/tools/tool-definition-wrapper.js +34 -0
  283. package/dist/core/tools/tool-definition-wrapper.js.map +1 -0
  284. package/dist/core/tools/truncate.d.ts +70 -0
  285. package/dist/core/tools/truncate.d.ts.map +1 -0
  286. package/dist/core/tools/truncate.js +215 -0
  287. package/dist/core/tools/truncate.js.map +1 -0
  288. package/dist/core/tools/write.d.ts +26 -0
  289. package/dist/core/tools/write.d.ts.map +1 -0
  290. package/dist/core/tools/write.js +198 -0
  291. package/dist/core/tools/write.js.map +1 -0
  292. package/dist/index.d.ts +29 -0
  293. package/dist/index.d.ts.map +1 -0
  294. package/dist/index.js +42 -0
  295. package/dist/index.js.map +1 -0
  296. package/dist/main.d.ts +12 -0
  297. package/dist/main.d.ts.map +1 -0
  298. package/dist/main.js +578 -0
  299. package/dist/main.js.map +1 -0
  300. package/dist/migrations.d.ts +33 -0
  301. package/dist/migrations.d.ts.map +1 -0
  302. package/dist/migrations.js +281 -0
  303. package/dist/migrations.js.map +1 -0
  304. package/dist/modes/index.d.ts +9 -0
  305. package/dist/modes/index.d.ts.map +1 -0
  306. package/dist/modes/index.js +8 -0
  307. package/dist/modes/index.js.map +1 -0
  308. package/dist/modes/interactive/assets/clankolas.png +0 -0
  309. package/dist/modes/interactive/components/armin.d.ts +34 -0
  310. package/dist/modes/interactive/components/armin.d.ts.map +1 -0
  311. package/dist/modes/interactive/components/armin.js +333 -0
  312. package/dist/modes/interactive/components/armin.js.map +1 -0
  313. package/dist/modes/interactive/components/assistant-message.d.ts +20 -0
  314. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -0
  315. package/dist/modes/interactive/components/assistant-message.js +121 -0
  316. package/dist/modes/interactive/components/assistant-message.js.map +1 -0
  317. package/dist/modes/interactive/components/bash-execution.d.ts +34 -0
  318. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -0
  319. package/dist/modes/interactive/components/bash-execution.js +175 -0
  320. package/dist/modes/interactive/components/bash-execution.js.map +1 -0
  321. package/dist/modes/interactive/components/bordered-loader.d.ts +16 -0
  322. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -0
  323. package/dist/modes/interactive/components/bordered-loader.js +54 -0
  324. package/dist/modes/interactive/components/bordered-loader.js.map +1 -0
  325. package/dist/modes/interactive/components/branch-summary-message.d.ts +16 -0
  326. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -0
  327. package/dist/modes/interactive/components/branch-summary-message.js +44 -0
  328. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -0
  329. package/dist/modes/interactive/components/compaction-summary-message.d.ts +16 -0
  330. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -0
  331. package/dist/modes/interactive/components/compaction-summary-message.js +45 -0
  332. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -0
  333. package/dist/modes/interactive/components/config-selector.d.ts +71 -0
  334. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -0
  335. package/dist/modes/interactive/components/config-selector.js +506 -0
  336. package/dist/modes/interactive/components/config-selector.js.map +1 -0
  337. package/dist/modes/interactive/components/countdown-timer.d.ts +14 -0
  338. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -0
  339. package/dist/modes/interactive/components/countdown-timer.js +33 -0
  340. package/dist/modes/interactive/components/countdown-timer.js.map +1 -0
  341. package/dist/modes/interactive/components/custom-editor.d.ts +21 -0
  342. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -0
  343. package/dist/modes/interactive/components/custom-editor.js +70 -0
  344. package/dist/modes/interactive/components/custom-editor.js.map +1 -0
  345. package/dist/modes/interactive/components/custom-message.d.ts +20 -0
  346. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -0
  347. package/dist/modes/interactive/components/custom-message.js +79 -0
  348. package/dist/modes/interactive/components/custom-message.js.map +1 -0
  349. package/dist/modes/interactive/components/daxnuts.d.ts +23 -0
  350. package/dist/modes/interactive/components/daxnuts.d.ts.map +1 -0
  351. package/dist/modes/interactive/components/daxnuts.js +140 -0
  352. package/dist/modes/interactive/components/daxnuts.js.map +1 -0
  353. package/dist/modes/interactive/components/diff.d.ts +12 -0
  354. package/dist/modes/interactive/components/diff.d.ts.map +1 -0
  355. package/dist/modes/interactive/components/diff.js +133 -0
  356. package/dist/modes/interactive/components/diff.js.map +1 -0
  357. package/dist/modes/interactive/components/dynamic-border.d.ts +15 -0
  358. package/dist/modes/interactive/components/dynamic-border.d.ts.map +1 -0
  359. package/dist/modes/interactive/components/dynamic-border.js +21 -0
  360. package/dist/modes/interactive/components/dynamic-border.js.map +1 -0
  361. package/dist/modes/interactive/components/earendil-announcement.d.ts +5 -0
  362. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -0
  363. package/dist/modes/interactive/components/earendil-announcement.js +40 -0
  364. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -0
  365. package/dist/modes/interactive/components/extension-editor.d.ts +20 -0
  366. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -0
  367. package/dist/modes/interactive/components/extension-editor.js +119 -0
  368. package/dist/modes/interactive/components/extension-editor.js.map +1 -0
  369. package/dist/modes/interactive/components/extension-input.d.ts +23 -0
  370. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -0
  371. package/dist/modes/interactive/components/extension-input.js +61 -0
  372. package/dist/modes/interactive/components/extension-input.js.map +1 -0
  373. package/dist/modes/interactive/components/extension-selector.d.ts +26 -0
  374. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -0
  375. package/dist/modes/interactive/components/extension-selector.js +83 -0
  376. package/dist/modes/interactive/components/extension-selector.js.map +1 -0
  377. package/dist/modes/interactive/components/footer.d.ts +28 -0
  378. package/dist/modes/interactive/components/footer.d.ts.map +1 -0
  379. package/dist/modes/interactive/components/footer.js +210 -0
  380. package/dist/modes/interactive/components/footer.js.map +1 -0
  381. package/dist/modes/interactive/components/index.d.ts +32 -0
  382. package/dist/modes/interactive/components/index.d.ts.map +1 -0
  383. package/dist/modes/interactive/components/index.js +33 -0
  384. package/dist/modes/interactive/components/index.js.map +1 -0
  385. package/dist/modes/interactive/components/keybinding-hints.d.ts +13 -0
  386. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -0
  387. package/dist/modes/interactive/components/keybinding-hints.js +36 -0
  388. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -0
  389. package/dist/modes/interactive/components/login-dialog.d.ts +54 -0
  390. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -0
  391. package/dist/modes/interactive/components/login-dialog.js +185 -0
  392. package/dist/modes/interactive/components/login-dialog.js.map +1 -0
  393. package/dist/modes/interactive/components/model-selector.d.ts +47 -0
  394. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -0
  395. package/dist/modes/interactive/components/model-selector.js +278 -0
  396. package/dist/modes/interactive/components/model-selector.js.map +1 -0
  397. package/dist/modes/interactive/components/oauth-selector.d.ts +31 -0
  398. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -0
  399. package/dist/modes/interactive/components/oauth-selector.js +165 -0
  400. package/dist/modes/interactive/components/oauth-selector.js.map +1 -0
  401. package/dist/modes/interactive/components/scoped-models-selector.d.ts +42 -0
  402. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -0
  403. package/dist/modes/interactive/components/scoped-models-selector.js +290 -0
  404. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -0
  405. package/dist/modes/interactive/components/session-selector-search.d.ts +23 -0
  406. package/dist/modes/interactive/components/session-selector-search.d.ts.map +1 -0
  407. package/dist/modes/interactive/components/session-selector-search.js +155 -0
  408. package/dist/modes/interactive/components/session-selector-search.js.map +1 -0
  409. package/dist/modes/interactive/components/session-selector.d.ts +96 -0
  410. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -0
  411. package/dist/modes/interactive/components/session-selector.js +861 -0
  412. package/dist/modes/interactive/components/session-selector.js.map +1 -0
  413. package/dist/modes/interactive/components/settings-selector.d.ts +69 -0
  414. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -0
  415. package/dist/modes/interactive/components/settings-selector.js +390 -0
  416. package/dist/modes/interactive/components/settings-selector.js.map +1 -0
  417. package/dist/modes/interactive/components/show-images-selector.d.ts +10 -0
  418. package/dist/modes/interactive/components/show-images-selector.d.ts.map +1 -0
  419. package/dist/modes/interactive/components/show-images-selector.js +39 -0
  420. package/dist/modes/interactive/components/show-images-selector.js.map +1 -0
  421. package/dist/modes/interactive/components/skill-invocation-message.d.ts +17 -0
  422. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -0
  423. package/dist/modes/interactive/components/skill-invocation-message.js +47 -0
  424. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -0
  425. package/dist/modes/interactive/components/theme-selector.d.ts +11 -0
  426. package/dist/modes/interactive/components/theme-selector.d.ts.map +1 -0
  427. package/dist/modes/interactive/components/theme-selector.js +50 -0
  428. package/dist/modes/interactive/components/theme-selector.js.map +1 -0
  429. package/dist/modes/interactive/components/thinking-selector.d.ts +11 -0
  430. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -0
  431. package/dist/modes/interactive/components/thinking-selector.js +51 -0
  432. package/dist/modes/interactive/components/thinking-selector.js.map +1 -0
  433. package/dist/modes/interactive/components/tool-execution.d.ts +63 -0
  434. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -0
  435. package/dist/modes/interactive/components/tool-execution.js +295 -0
  436. package/dist/modes/interactive/components/tool-execution.js.map +1 -0
  437. package/dist/modes/interactive/components/tree-selector.d.ts +89 -0
  438. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -0
  439. package/dist/modes/interactive/components/tree-selector.js +1093 -0
  440. package/dist/modes/interactive/components/tree-selector.js.map +1 -0
  441. package/dist/modes/interactive/components/user-message-selector.d.ts +30 -0
  442. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -0
  443. package/dist/modes/interactive/components/user-message-selector.js +114 -0
  444. package/dist/modes/interactive/components/user-message-selector.js.map +1 -0
  445. package/dist/modes/interactive/components/user-message.d.ts +10 -0
  446. package/dist/modes/interactive/components/user-message.d.ts.map +1 -0
  447. package/dist/modes/interactive/components/user-message.js +29 -0
  448. package/dist/modes/interactive/components/user-message.js.map +1 -0
  449. package/dist/modes/interactive/components/visual-truncate.d.ts +24 -0
  450. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -0
  451. package/dist/modes/interactive/components/visual-truncate.js +33 -0
  452. package/dist/modes/interactive/components/visual-truncate.js.map +1 -0
  453. package/dist/modes/interactive/interactive-mode.d.ts +370 -0
  454. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -0
  455. package/dist/modes/interactive/interactive-mode.js +4655 -0
  456. package/dist/modes/interactive/interactive-mode.js.map +1 -0
  457. package/dist/modes/interactive/theme/dark.json +86 -0
  458. package/dist/modes/interactive/theme/light.json +85 -0
  459. package/dist/modes/interactive/theme/theme-schema.json +335 -0
  460. package/dist/modes/interactive/theme/theme.d.ts +100 -0
  461. package/dist/modes/interactive/theme/theme.d.ts.map +1 -0
  462. package/dist/modes/interactive/theme/theme.js +1024 -0
  463. package/dist/modes/interactive/theme/theme.js.map +1 -0
  464. package/dist/modes/print-mode.d.ts +28 -0
  465. package/dist/modes/print-mode.d.ts.map +1 -0
  466. package/dist/modes/print-mode.js +131 -0
  467. package/dist/modes/print-mode.js.map +1 -0
  468. package/dist/modes/rpc/jsonl.d.ts +17 -0
  469. package/dist/modes/rpc/jsonl.d.ts.map +1 -0
  470. package/dist/modes/rpc/jsonl.js +49 -0
  471. package/dist/modes/rpc/jsonl.js.map +1 -0
  472. package/dist/modes/rpc/rpc-client.d.ts +224 -0
  473. package/dist/modes/rpc/rpc-client.d.ts.map +1 -0
  474. package/dist/modes/rpc/rpc-client.js +410 -0
  475. package/dist/modes/rpc/rpc-client.js.map +1 -0
  476. package/dist/modes/rpc/rpc-mode.d.ts +20 -0
  477. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -0
  478. package/dist/modes/rpc/rpc-mode.js +601 -0
  479. package/dist/modes/rpc/rpc-mode.js.map +1 -0
  480. package/dist/modes/rpc/rpc-types.d.ts +419 -0
  481. package/dist/modes/rpc/rpc-types.d.ts.map +1 -0
  482. package/dist/modes/rpc/rpc-types.js +8 -0
  483. package/dist/modes/rpc/rpc-types.js.map +1 -0
  484. package/dist/package-manager-cli.d.ts +4 -0
  485. package/dist/package-manager-cli.d.ts.map +1 -0
  486. package/dist/package-manager-cli.js +515 -0
  487. package/dist/package-manager-cli.js.map +1 -0
  488. package/dist/utils/ansi.d.ts +2 -0
  489. package/dist/utils/ansi.d.ts.map +1 -0
  490. package/dist/utils/ansi.js +52 -0
  491. package/dist/utils/ansi.js.map +1 -0
  492. package/dist/utils/changelog.d.ts +21 -0
  493. package/dist/utils/changelog.d.ts.map +1 -0
  494. package/dist/utils/changelog.js +87 -0
  495. package/dist/utils/changelog.js.map +1 -0
  496. package/dist/utils/child-process.d.ts +15 -0
  497. package/dist/utils/child-process.d.ts.map +1 -0
  498. package/dist/utils/child-process.js +88 -0
  499. package/dist/utils/child-process.js.map +1 -0
  500. package/dist/utils/clipboard-image.d.ts +11 -0
  501. package/dist/utils/clipboard-image.d.ts.map +1 -0
  502. package/dist/utils/clipboard-image.js +245 -0
  503. package/dist/utils/clipboard-image.js.map +1 -0
  504. package/dist/utils/clipboard-native.d.ts +10 -0
  505. package/dist/utils/clipboard-native.d.ts.map +1 -0
  506. package/dist/utils/clipboard-native.js +20 -0
  507. package/dist/utils/clipboard-native.js.map +1 -0
  508. package/dist/utils/clipboard.d.ts +2 -0
  509. package/dist/utils/clipboard.d.ts.map +1 -0
  510. package/dist/utils/clipboard.js +117 -0
  511. package/dist/utils/clipboard.js.map +1 -0
  512. package/dist/utils/exif-orientation.d.ts +5 -0
  513. package/dist/utils/exif-orientation.d.ts.map +1 -0
  514. package/dist/utils/exif-orientation.js +158 -0
  515. package/dist/utils/exif-orientation.js.map +1 -0
  516. package/dist/utils/frontmatter.d.ts +8 -0
  517. package/dist/utils/frontmatter.d.ts.map +1 -0
  518. package/dist/utils/frontmatter.js +26 -0
  519. package/dist/utils/frontmatter.js.map +1 -0
  520. package/dist/utils/fs-watch.d.ts +5 -0
  521. package/dist/utils/fs-watch.d.ts.map +1 -0
  522. package/dist/utils/fs-watch.js +25 -0
  523. package/dist/utils/fs-watch.js.map +1 -0
  524. package/dist/utils/git.d.ts +26 -0
  525. package/dist/utils/git.d.ts.map +1 -0
  526. package/dist/utils/git.js +163 -0
  527. package/dist/utils/git.js.map +1 -0
  528. package/dist/utils/html.d.ts +7 -0
  529. package/dist/utils/html.d.ts.map +1 -0
  530. package/dist/utils/html.js +40 -0
  531. package/dist/utils/html.js.map +1 -0
  532. package/dist/utils/image-convert.d.ts +9 -0
  533. package/dist/utils/image-convert.d.ts.map +1 -0
  534. package/dist/utils/image-convert.js +39 -0
  535. package/dist/utils/image-convert.js.map +1 -0
  536. package/dist/utils/image-resize-core.d.ts +30 -0
  537. package/dist/utils/image-resize-core.d.ts.map +1 -0
  538. package/dist/utils/image-resize-core.js +124 -0
  539. package/dist/utils/image-resize-core.js.map +1 -0
  540. package/dist/utils/image-resize-worker.d.ts +2 -0
  541. package/dist/utils/image-resize-worker.d.ts.map +1 -0
  542. package/dist/utils/image-resize-worker.js +31 -0
  543. package/dist/utils/image-resize-worker.js.map +1 -0
  544. package/dist/utils/image-resize.d.ts +16 -0
  545. package/dist/utils/image-resize.d.ts.map +1 -0
  546. package/dist/utils/image-resize.js +97 -0
  547. package/dist/utils/image-resize.js.map +1 -0
  548. package/dist/utils/mime.d.ts +3 -0
  549. package/dist/utils/mime.d.ts.map +1 -0
  550. package/dist/utils/mime.js +69 -0
  551. package/dist/utils/mime.js.map +1 -0
  552. package/dist/utils/paths.d.ts +31 -0
  553. package/dist/utils/paths.d.ts.map +1 -0
  554. package/dist/utils/paths.js +92 -0
  555. package/dist/utils/paths.js.map +1 -0
  556. package/dist/utils/photon.d.ts +21 -0
  557. package/dist/utils/photon.d.ts.map +1 -0
  558. package/dist/utils/photon.js +121 -0
  559. package/dist/utils/photon.js.map +1 -0
  560. package/dist/utils/pi-user-agent.d.ts +2 -0
  561. package/dist/utils/pi-user-agent.d.ts.map +1 -0
  562. package/dist/utils/pi-user-agent.js +5 -0
  563. package/dist/utils/pi-user-agent.js.map +1 -0
  564. package/dist/utils/shell.d.ts +30 -0
  565. package/dist/utils/shell.d.ts.map +1 -0
  566. package/dist/utils/shell.js +195 -0
  567. package/dist/utils/shell.js.map +1 -0
  568. package/dist/utils/sleep.d.ts +5 -0
  569. package/dist/utils/sleep.d.ts.map +1 -0
  570. package/dist/utils/sleep.js +17 -0
  571. package/dist/utils/sleep.js.map +1 -0
  572. package/dist/utils/syntax-highlight.d.ts +12 -0
  573. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  574. package/dist/utils/syntax-highlight.js +118 -0
  575. package/dist/utils/syntax-highlight.js.map +1 -0
  576. package/dist/utils/tools-manager.d.ts +3 -0
  577. package/dist/utils/tools-manager.d.ts.map +1 -0
  578. package/dist/utils/tools-manager.js +328 -0
  579. package/dist/utils/tools-manager.js.map +1 -0
  580. package/dist/utils/version-check.d.ts +15 -0
  581. package/dist/utils/version-check.d.ts.map +1 -0
  582. package/dist/utils/version-check.js +82 -0
  583. package/dist/utils/version-check.js.map +1 -0
  584. package/dist/utils/windows-self-update.d.ts +3 -0
  585. package/dist/utils/windows-self-update.d.ts.map +1 -0
  586. package/dist/utils/windows-self-update.js +77 -0
  587. package/dist/utils/windows-self-update.js.map +1 -0
  588. package/docs/compaction.md +15 -0
  589. package/docs/custom-provider.md +13 -0
  590. package/docs/development.md +28 -0
  591. package/docs/docs.json +45 -0
  592. package/docs/extensions.md +18 -0
  593. package/docs/images/interactive-mode.png +0 -0
  594. package/docs/images/tree-view.png +0 -0
  595. package/docs/index.md +34 -0
  596. package/docs/json.md +15 -0
  597. package/docs/keybindings.md +12 -0
  598. package/docs/models.md +19 -0
  599. package/docs/packages.md +8 -0
  600. package/docs/prompt-templates.md +16 -0
  601. package/docs/providers.md +21 -0
  602. package/docs/quickstart.md +29 -0
  603. package/docs/rpc.md +15 -0
  604. package/docs/sdk.md +12 -0
  605. package/docs/session-format.md +12 -0
  606. package/docs/sessions.md +17 -0
  607. package/docs/settings.md +15 -0
  608. package/docs/shell-aliases.md +10 -0
  609. package/docs/skills.md +18 -0
  610. package/docs/terminal-setup.md +15 -0
  611. package/docs/termux.md +9 -0
  612. package/docs/themes.md +13 -0
  613. package/docs/tmux.md +9 -0
  614. package/docs/tui.md +12 -0
  615. package/docs/usage.md +19 -0
  616. package/docs/windows.md +11 -0
  617. package/examples/README.md +25 -0
  618. package/examples/extensions/README.md +208 -0
  619. package/examples/extensions/auto-commit-on-exit.ts +49 -0
  620. package/examples/extensions/bash-spawn-hook.ts +30 -0
  621. package/examples/extensions/bookmark.ts +50 -0
  622. package/examples/extensions/border-status-editor.ts +145 -0
  623. package/examples/extensions/built-in-tool-renderer.ts +249 -0
  624. package/examples/extensions/claude-rules.ts +86 -0
  625. package/examples/extensions/commands.ts +72 -0
  626. package/examples/extensions/confirm-destructive.ts +59 -0
  627. package/examples/extensions/custom-compaction.ts +127 -0
  628. package/examples/extensions/custom-footer.ts +64 -0
  629. package/examples/extensions/custom-header.ts +73 -0
  630. package/examples/extensions/custom-provider-anthropic/index.ts +604 -0
  631. package/examples/extensions/custom-provider-anthropic/package-lock.json +24 -0
  632. package/examples/extensions/custom-provider-anthropic/package.json +19 -0
  633. package/examples/extensions/custom-provider-gitlab-duo/index.ts +349 -0
  634. package/examples/extensions/custom-provider-gitlab-duo/package.json +16 -0
  635. package/examples/extensions/custom-provider-gitlab-duo/test.ts +82 -0
  636. package/examples/extensions/dirty-repo-guard.ts +56 -0
  637. package/examples/extensions/doom-overlay/README.md +46 -0
  638. package/examples/extensions/doom-overlay/doom/build/doom.js +21 -0
  639. package/examples/extensions/doom-overlay/doom/build/doom.wasm +0 -0
  640. package/examples/extensions/doom-overlay/doom/build.sh +152 -0
  641. package/examples/extensions/doom-overlay/doom/doomgeneric_pi.c +72 -0
  642. package/examples/extensions/doom-overlay/doom-component.ts +132 -0
  643. package/examples/extensions/doom-overlay/doom-engine.ts +173 -0
  644. package/examples/extensions/doom-overlay/doom-keys.ts +104 -0
  645. package/examples/extensions/doom-overlay/index.ts +74 -0
  646. package/examples/extensions/doom-overlay/wad-finder.ts +51 -0
  647. package/examples/extensions/dynamic-resources/SKILL.md +8 -0
  648. package/examples/extensions/dynamic-resources/dynamic.json +79 -0
  649. package/examples/extensions/dynamic-resources/dynamic.md +5 -0
  650. package/examples/extensions/dynamic-resources/index.ts +15 -0
  651. package/examples/extensions/dynamic-tools.ts +74 -0
  652. package/examples/extensions/event-bus.ts +43 -0
  653. package/examples/extensions/file-trigger.ts +41 -0
  654. package/examples/extensions/git-checkpoint.ts +53 -0
  655. package/examples/extensions/github-issue-autocomplete.ts +185 -0
  656. package/examples/extensions/handoff.ts +191 -0
  657. package/examples/extensions/hello.ts +26 -0
  658. package/examples/extensions/hidden-thinking-label.ts +53 -0
  659. package/examples/extensions/inline-bash.ts +94 -0
  660. package/examples/extensions/input-transform.ts +43 -0
  661. package/examples/extensions/interactive-shell.ts +196 -0
  662. package/examples/extensions/mac-system-theme.ts +47 -0
  663. package/examples/extensions/message-renderer.ts +59 -0
  664. package/examples/extensions/minimal-mode.ts +426 -0
  665. package/examples/extensions/modal-editor.ts +85 -0
  666. package/examples/extensions/model-status.ts +31 -0
  667. package/examples/extensions/notify.ts +55 -0
  668. package/examples/extensions/overlay-qa-tests.ts +1379 -0
  669. package/examples/extensions/overlay-test.ts +153 -0
  670. package/examples/extensions/permission-gate.ts +34 -0
  671. package/examples/extensions/pirate.ts +47 -0
  672. package/examples/extensions/plan-mode/README.md +65 -0
  673. package/examples/extensions/plan-mode/index.ts +340 -0
  674. package/examples/extensions/plan-mode/utils.ts +168 -0
  675. package/examples/extensions/preset.ts +430 -0
  676. package/examples/extensions/prompt-customizer.ts +97 -0
  677. package/examples/extensions/protected-paths.ts +30 -0
  678. package/examples/extensions/provider-payload.ts +18 -0
  679. package/examples/extensions/qna.ts +122 -0
  680. package/examples/extensions/question.ts +264 -0
  681. package/examples/extensions/questionnaire.ts +427 -0
  682. package/examples/extensions/rainbow-editor.ts +88 -0
  683. package/examples/extensions/reload-runtime.ts +37 -0
  684. package/examples/extensions/rpc-demo.ts +118 -0
  685. package/examples/extensions/sandbox/index.ts +321 -0
  686. package/examples/extensions/sandbox/package-lock.json +92 -0
  687. package/examples/extensions/sandbox/package.json +19 -0
  688. package/examples/extensions/send-user-message.ts +97 -0
  689. package/examples/extensions/session-name.ts +27 -0
  690. package/examples/extensions/shutdown-command.ts +63 -0
  691. package/examples/extensions/snake.ts +343 -0
  692. package/examples/extensions/space-invaders.ts +560 -0
  693. package/examples/extensions/ssh.ts +220 -0
  694. package/examples/extensions/status-line.ts +32 -0
  695. package/examples/extensions/structured-output.ts +65 -0
  696. package/examples/extensions/subagent/README.md +175 -0
  697. package/examples/extensions/subagent/agents/planner.md +37 -0
  698. package/examples/extensions/subagent/agents/reviewer.md +35 -0
  699. package/examples/extensions/subagent/agents/scout.md +50 -0
  700. package/examples/extensions/subagent/agents/worker.md +24 -0
  701. package/examples/extensions/subagent/agents.ts +126 -0
  702. package/examples/extensions/subagent/index.ts +1009 -0
  703. package/examples/extensions/subagent/prompts/implement-and-review.md +10 -0
  704. package/examples/extensions/subagent/prompts/implement.md +10 -0
  705. package/examples/extensions/subagent/prompts/scout-and-plan.md +9 -0
  706. package/examples/extensions/summarize.ts +206 -0
  707. package/examples/extensions/system-prompt-header.ts +17 -0
  708. package/examples/extensions/tic-tac-toe.ts +1008 -0
  709. package/examples/extensions/timed-confirm.ts +70 -0
  710. package/examples/extensions/titlebar-spinner.ts +58 -0
  711. package/examples/extensions/todo.ts +297 -0
  712. package/examples/extensions/tool-override.ts +144 -0
  713. package/examples/extensions/tools.ts +141 -0
  714. package/examples/extensions/trigger-compact.ts +50 -0
  715. package/examples/extensions/truncated-tool.ts +195 -0
  716. package/examples/extensions/widget-placement.ts +9 -0
  717. package/examples/extensions/with-deps/index.ts +32 -0
  718. package/examples/extensions/with-deps/package-lock.json +31 -0
  719. package/examples/extensions/with-deps/package.json +22 -0
  720. package/examples/extensions/working-indicator.ts +123 -0
  721. package/examples/extensions/working-message-test.ts +25 -0
  722. package/examples/rpc-extension-ui.ts +632 -0
  723. package/examples/sdk/01-minimal.ts +26 -0
  724. package/examples/sdk/02-custom-model.ts +53 -0
  725. package/examples/sdk/03-custom-prompt.ts +70 -0
  726. package/examples/sdk/04-skills.ts +55 -0
  727. package/examples/sdk/05-tools.ts +48 -0
  728. package/examples/sdk/06-extensions.ts +94 -0
  729. package/examples/sdk/07-context-files.ts +42 -0
  730. package/examples/sdk/08-prompt-templates.ts +51 -0
  731. package/examples/sdk/09-api-keys-and-oauth.ts +52 -0
  732. package/examples/sdk/10-settings.ts +53 -0
  733. package/examples/sdk/11-sessions.ts +52 -0
  734. package/examples/sdk/12-full-control.ts +77 -0
  735. package/examples/sdk/13-session-runtime.ts +67 -0
  736. package/examples/sdk/README.md +144 -0
  737. package/npm-shrinkwrap.json +1790 -0
  738. package/package.json +98 -0
@@ -0,0 +1,2498 @@
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 { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
+ import { basename, dirname } from "node:path";
17
+ import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, modelsAreEqual, resetApiProviders, streamSimple, } from "@voxcode/voxcode-ai";
18
+ import { theme } from "../modes/interactive/theme/theme.js";
19
+ import { stripFrontmatter } from "../utils/frontmatter.js";
20
+ import { resolvePath } from "../utils/paths.js";
21
+ import { sleep } from "../utils/sleep.js";
22
+ import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
23
+ import { executeBashWithOperations } from "./bash-executor.js";
24
+ import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
25
+ import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
26
+ import { exportSessionToHtml } from "./export-html/index.js";
27
+ import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
28
+ import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
29
+ import { emitSessionShutdownEvent } from "./extensions/runner.js";
30
+ import { expandPromptTemplate } from "./prompt-templates.js";
31
+ import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
32
+ import { createSyntheticSourceInfo } from "./source-info.js";
33
+ import { buildSystemPrompt } from "./system-prompt.js";
34
+ import { createLocalBashOperations } from "./tools/bash.js";
35
+ import { createAllToolDefinitions } from "./tools/index.js";
36
+ import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
37
+ /**
38
+ * Parse a skill block from message text.
39
+ * Returns null if the text doesn't contain a skill block.
40
+ */
41
+ export function parseSkillBlock(text) {
42
+ const match = text.match(/^<skill name="([^"]+)" location="([^"]+)">\n([\s\S]*?)\n<\/skill>(?:\n\n([\s\S]+))?$/);
43
+ if (!match)
44
+ return null;
45
+ return {
46
+ name: match[1],
47
+ location: match[2],
48
+ content: match[3],
49
+ userMessage: match[4]?.trim() || undefined,
50
+ };
51
+ }
52
+ // ============================================================================
53
+ // Constants
54
+ // ============================================================================
55
+ /** Standard thinking levels */
56
+ const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high"];
57
+ // ============================================================================
58
+ // AgentSession Class
59
+ // ============================================================================
60
+ export class AgentSession {
61
+ agent;
62
+ sessionManager;
63
+ settingsManager;
64
+ _scopedModels;
65
+ // Event subscription state
66
+ _unsubscribeAgent;
67
+ _eventListeners = [];
68
+ /** Tracks pending steering messages for UI display. Removed when delivered. */
69
+ _steeringMessages = [];
70
+ /** Tracks pending follow-up messages for UI display. Removed when delivered. */
71
+ _followUpMessages = [];
72
+ /** Messages queued to be included with the next user prompt as context ("asides"). */
73
+ _pendingNextTurnMessages = [];
74
+ // Compaction state
75
+ _compactionAbortController = undefined;
76
+ _autoCompactionAbortController = undefined;
77
+ _overflowRecoveryAttempted = false;
78
+ // Branch summarization state
79
+ _branchSummaryAbortController = undefined;
80
+ // Retry state
81
+ _retryAbortController = undefined;
82
+ _retryAttempt = 0;
83
+ // Bash execution state
84
+ _bashAbortController = undefined;
85
+ _pendingBashMessages = [];
86
+ // Extension system
87
+ _extensionRunner;
88
+ _turnIndex = 0;
89
+ _resourceLoader;
90
+ _customTools;
91
+ _baseToolDefinitions = new Map();
92
+ _cwd;
93
+ _extensionRunnerRef;
94
+ _initialActiveToolNames;
95
+ _allowedToolNames;
96
+ _baseToolsOverride;
97
+ _sessionStartEvent;
98
+ _extensionUIContext;
99
+ _extensionCommandContextActions;
100
+ _extensionAbortHandler;
101
+ _extensionShutdownHandler;
102
+ _extensionErrorListener;
103
+ _extensionErrorUnsubscriber;
104
+ // Model registry for API key resolution
105
+ _modelRegistry;
106
+ // Tool registry for extension getTools/setTools
107
+ _toolRegistry = new Map();
108
+ _toolDefinitions = new Map();
109
+ _toolPromptSnippets = new Map();
110
+ _toolPromptGuidelines = new Map();
111
+ // Base system prompt (without extension appends) - used to apply fresh appends each turn
112
+ _baseSystemPrompt = "";
113
+ _baseSystemPromptOptions;
114
+ constructor(config) {
115
+ this.agent = config.agent;
116
+ this.sessionManager = config.sessionManager;
117
+ this.settingsManager = config.settingsManager;
118
+ this._scopedModels = config.scopedModels ?? [];
119
+ this._resourceLoader = config.resourceLoader;
120
+ this._customTools = config.customTools ?? [];
121
+ this._cwd = config.cwd;
122
+ this._modelRegistry = config.modelRegistry;
123
+ this._extensionRunnerRef = config.extensionRunnerRef;
124
+ this._initialActiveToolNames = config.initialActiveToolNames;
125
+ this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
126
+ this._baseToolsOverride = config.baseToolsOverride;
127
+ this._sessionStartEvent = config.sessionStartEvent ?? { type: "session_start", reason: "startup" };
128
+ // Always subscribe to agent events for internal handling
129
+ // (session persistence, extensions, auto-compaction, retry logic)
130
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
131
+ this._installAgentToolHooks();
132
+ this._buildRuntime({
133
+ activeToolNames: this._initialActiveToolNames,
134
+ includeAllExtensionTools: true,
135
+ });
136
+ }
137
+ /** Model registry for API key resolution and model discovery */
138
+ get modelRegistry() {
139
+ return this._modelRegistry;
140
+ }
141
+ async _getRequiredRequestAuth(model) {
142
+ const result = await this._modelRegistry.getApiKeyAndHeaders(model);
143
+ if (!result.ok) {
144
+ if (result.error.startsWith("No API key found")) {
145
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
146
+ }
147
+ throw new Error(result.error);
148
+ }
149
+ if (result.apiKey) {
150
+ return { apiKey: result.apiKey, headers: result.headers };
151
+ }
152
+ const isOAuth = this._modelRegistry.isUsingOAuth(model);
153
+ if (isOAuth) {
154
+ throw new Error(`Authentication failed for "${model.provider}". ` +
155
+ `Credentials may have expired or network is unavailable. ` +
156
+ `Run '/login ${model.provider}' to re-authenticate.`);
157
+ }
158
+ throw new Error(formatNoApiKeyFoundMessage(model.provider));
159
+ }
160
+ async _getCompactionRequestAuth(model) {
161
+ if (this.agent.streamFn === streamSimple) {
162
+ return this._getRequiredRequestAuth(model);
163
+ }
164
+ const result = await this._modelRegistry.getApiKeyAndHeaders(model);
165
+ return result.ok ? { apiKey: result.apiKey, headers: result.headers } : {};
166
+ }
167
+ /**
168
+ * Install tool hooks once on the Agent instance.
169
+ *
170
+ * The callbacks read `this._extensionRunner` at execution time, so extension reload swaps in the
171
+ * new runner without reinstalling hooks. Extension-specific tool wrappers are still used to adapt
172
+ * registered tool execution to the extension context. Tool call and tool result interception now
173
+ * happens here instead of in wrappers.
174
+ */
175
+ _installAgentToolHooks() {
176
+ this.agent.beforeToolCall = async ({ toolCall, args }) => {
177
+ const runner = this._extensionRunner;
178
+ if (!runner.hasHandlers("tool_call")) {
179
+ return undefined;
180
+ }
181
+ try {
182
+ return await runner.emitToolCall({
183
+ type: "tool_call",
184
+ toolName: toolCall.name,
185
+ toolCallId: toolCall.id,
186
+ input: args,
187
+ });
188
+ }
189
+ catch (err) {
190
+ if (err instanceof Error) {
191
+ throw err;
192
+ }
193
+ throw new Error(`Extension failed, blocking execution: ${String(err)}`);
194
+ }
195
+ };
196
+ this.agent.afterToolCall = async ({ toolCall, args, result, isError }) => {
197
+ const runner = this._extensionRunner;
198
+ if (!runner.hasHandlers("tool_result")) {
199
+ return undefined;
200
+ }
201
+ const hookResult = await runner.emitToolResult({
202
+ type: "tool_result",
203
+ toolName: toolCall.name,
204
+ toolCallId: toolCall.id,
205
+ input: args,
206
+ content: result.content,
207
+ details: result.details,
208
+ isError,
209
+ });
210
+ if (!hookResult) {
211
+ return undefined;
212
+ }
213
+ return {
214
+ content: hookResult.content,
215
+ details: hookResult.details,
216
+ isError: hookResult.isError ?? isError,
217
+ };
218
+ };
219
+ }
220
+ // =========================================================================
221
+ // Event Subscription
222
+ // =========================================================================
223
+ /** Emit an event to all listeners */
224
+ _emit(event) {
225
+ for (const l of this._eventListeners) {
226
+ l(event);
227
+ }
228
+ }
229
+ _emitQueueUpdate() {
230
+ this._emit({
231
+ type: "queue_update",
232
+ steering: [...this._steeringMessages],
233
+ followUp: [...this._followUpMessages],
234
+ });
235
+ }
236
+ // Track last assistant message for auto-compaction check
237
+ _lastAssistantMessage = undefined;
238
+ /** Internal handler for agent events - shared by subscribe and reconnect */
239
+ _handleAgentEvent = async (event) => {
240
+ // When a user message starts, check if it's from either queue and remove it BEFORE emitting
241
+ // This ensures the UI sees the updated queue state
242
+ if (event.type === "message_start" && event.message.role === "user") {
243
+ this._overflowRecoveryAttempted = false;
244
+ const messageText = this._getUserMessageText(event.message);
245
+ if (messageText) {
246
+ // Check steering queue first
247
+ const steeringIndex = this._steeringMessages.indexOf(messageText);
248
+ if (steeringIndex !== -1) {
249
+ this._steeringMessages.splice(steeringIndex, 1);
250
+ this._emitQueueUpdate();
251
+ }
252
+ else {
253
+ // Check follow-up queue
254
+ const followUpIndex = this._followUpMessages.indexOf(messageText);
255
+ if (followUpIndex !== -1) {
256
+ this._followUpMessages.splice(followUpIndex, 1);
257
+ this._emitQueueUpdate();
258
+ }
259
+ }
260
+ }
261
+ }
262
+ // Emit to extensions first
263
+ await this._emitExtensionEvent(event);
264
+ // Notify all listeners
265
+ this._emit(event.type === "agent_end" ? { ...event, willRetry: this._willRetryAfterAgentEnd(event) } : event);
266
+ // Handle session persistence
267
+ if (event.type === "message_end") {
268
+ // Check if this is a custom message from extensions
269
+ if (event.message.role === "custom") {
270
+ // Persist as CustomMessageEntry
271
+ this.sessionManager.appendCustomMessageEntry(event.message.customType, event.message.content, event.message.display, event.message.details);
272
+ }
273
+ else if (event.message.role === "user" ||
274
+ event.message.role === "assistant" ||
275
+ event.message.role === "toolResult") {
276
+ // Regular LLM message - persist as SessionMessageEntry
277
+ this.sessionManager.appendMessage(event.message);
278
+ }
279
+ // Other message types (bashExecution, compactionSummary, branchSummary) are persisted elsewhere
280
+ // Track assistant message for auto-compaction (checked on agent_end)
281
+ if (event.message.role === "assistant") {
282
+ this._lastAssistantMessage = event.message;
283
+ const assistantMsg = event.message;
284
+ if (assistantMsg.stopReason !== "error") {
285
+ this._overflowRecoveryAttempted = false;
286
+ }
287
+ // Reset retry counter immediately on successful assistant response
288
+ // This prevents accumulation across multiple LLM calls within a turn
289
+ if (assistantMsg.stopReason !== "error" && this._retryAttempt > 0) {
290
+ this._emit({
291
+ type: "auto_retry_end",
292
+ success: true,
293
+ attempt: this._retryAttempt,
294
+ });
295
+ this._retryAttempt = 0;
296
+ }
297
+ }
298
+ }
299
+ };
300
+ _willRetryAfterAgentEnd(event) {
301
+ const settings = this.settingsManager.getRetrySettings();
302
+ if (!settings.enabled || this._retryAttempt >= settings.maxRetries) {
303
+ return false;
304
+ }
305
+ for (let i = event.messages.length - 1; i >= 0; i--) {
306
+ const message = event.messages[i];
307
+ if (message.role === "assistant") {
308
+ return this._isRetryableError(message);
309
+ }
310
+ }
311
+ return false;
312
+ }
313
+ /** Extract text content from a message */
314
+ _getUserMessageText(message) {
315
+ if (message.role !== "user")
316
+ return "";
317
+ const content = message.content;
318
+ if (typeof content === "string")
319
+ return content;
320
+ const textBlocks = content.filter((c) => c.type === "text");
321
+ return textBlocks.map((c) => c.text).join("");
322
+ }
323
+ /** Find the last assistant message in agent state (including aborted ones) */
324
+ _findLastAssistantMessage() {
325
+ const messages = this.agent.state.messages;
326
+ for (let i = messages.length - 1; i >= 0; i--) {
327
+ const msg = messages[i];
328
+ if (msg.role === "assistant") {
329
+ return msg;
330
+ }
331
+ }
332
+ return undefined;
333
+ }
334
+ _replaceMessageInPlace(target, replacement) {
335
+ // Agent-core stores the finalized message object in its state before emitting message_end.
336
+ // SessionManager persistence happens later in _handleAgentEvent() with event.message.
337
+ // Mutating this object in place keeps agent state, later turn/agent events, listeners,
338
+ // and the eventual SessionManager.appendMessage(event.message) persistence in sync.
339
+ if (target === replacement) {
340
+ return;
341
+ }
342
+ const targetRecord = target;
343
+ for (const key of Object.keys(targetRecord)) {
344
+ delete targetRecord[key];
345
+ }
346
+ Object.assign(targetRecord, replacement);
347
+ }
348
+ /** Emit extension events based on agent events */
349
+ async _emitExtensionEvent(event) {
350
+ if (event.type === "agent_start") {
351
+ this._turnIndex = 0;
352
+ await this._extensionRunner.emit({ type: "agent_start" });
353
+ }
354
+ else if (event.type === "agent_end") {
355
+ await this._extensionRunner.emit({ type: "agent_end", messages: event.messages });
356
+ }
357
+ else if (event.type === "turn_start") {
358
+ const extensionEvent = {
359
+ type: "turn_start",
360
+ turnIndex: this._turnIndex,
361
+ timestamp: Date.now(),
362
+ };
363
+ await this._extensionRunner.emit(extensionEvent);
364
+ }
365
+ else if (event.type === "turn_end") {
366
+ const extensionEvent = {
367
+ type: "turn_end",
368
+ turnIndex: this._turnIndex,
369
+ message: event.message,
370
+ toolResults: event.toolResults,
371
+ };
372
+ await this._extensionRunner.emit(extensionEvent);
373
+ this._turnIndex++;
374
+ }
375
+ else if (event.type === "message_start") {
376
+ const extensionEvent = {
377
+ type: "message_start",
378
+ message: event.message,
379
+ };
380
+ await this._extensionRunner.emit(extensionEvent);
381
+ }
382
+ else if (event.type === "message_update") {
383
+ const extensionEvent = {
384
+ type: "message_update",
385
+ message: event.message,
386
+ assistantMessageEvent: event.assistantMessageEvent,
387
+ };
388
+ await this._extensionRunner.emit(extensionEvent);
389
+ }
390
+ else if (event.type === "message_end") {
391
+ const extensionEvent = {
392
+ type: "message_end",
393
+ message: event.message,
394
+ };
395
+ const replacement = await this._extensionRunner.emitMessageEnd(extensionEvent);
396
+ if (replacement) {
397
+ this._replaceMessageInPlace(event.message, replacement);
398
+ }
399
+ }
400
+ else if (event.type === "tool_execution_start") {
401
+ const extensionEvent = {
402
+ type: "tool_execution_start",
403
+ toolCallId: event.toolCallId,
404
+ toolName: event.toolName,
405
+ args: event.args,
406
+ };
407
+ await this._extensionRunner.emit(extensionEvent);
408
+ }
409
+ else if (event.type === "tool_execution_update") {
410
+ const extensionEvent = {
411
+ type: "tool_execution_update",
412
+ toolCallId: event.toolCallId,
413
+ toolName: event.toolName,
414
+ args: event.args,
415
+ partialResult: event.partialResult,
416
+ };
417
+ await this._extensionRunner.emit(extensionEvent);
418
+ }
419
+ else if (event.type === "tool_execution_end") {
420
+ const extensionEvent = {
421
+ type: "tool_execution_end",
422
+ toolCallId: event.toolCallId,
423
+ toolName: event.toolName,
424
+ result: event.result,
425
+ isError: event.isError,
426
+ };
427
+ await this._extensionRunner.emit(extensionEvent);
428
+ }
429
+ }
430
+ /**
431
+ * Subscribe to agent events.
432
+ * Session persistence is handled internally (saves messages on message_end).
433
+ * Multiple listeners can be added. Returns unsubscribe function for this listener.
434
+ */
435
+ subscribe(listener) {
436
+ this._eventListeners.push(listener);
437
+ // Return unsubscribe function for this specific listener
438
+ return () => {
439
+ const index = this._eventListeners.indexOf(listener);
440
+ if (index !== -1) {
441
+ this._eventListeners.splice(index, 1);
442
+ }
443
+ };
444
+ }
445
+ /**
446
+ * Temporarily disconnect from agent events.
447
+ * User listeners are preserved and will receive events again after resubscribe().
448
+ * Used internally during operations that need to pause event processing.
449
+ */
450
+ _disconnectFromAgent() {
451
+ if (this._unsubscribeAgent) {
452
+ this._unsubscribeAgent();
453
+ this._unsubscribeAgent = undefined;
454
+ }
455
+ }
456
+ /**
457
+ * Reconnect to agent events after _disconnectFromAgent().
458
+ * Preserves all existing listeners.
459
+ */
460
+ _reconnectToAgent() {
461
+ if (this._unsubscribeAgent)
462
+ return; // Already connected
463
+ this._unsubscribeAgent = this.agent.subscribe(this._handleAgentEvent);
464
+ }
465
+ /**
466
+ * Remove all listeners and disconnect from agent.
467
+ * Call this when completely done with the session.
468
+ */
469
+ dispose() {
470
+ this._extensionRunner.invalidate("This extension ctx is stale after session replacement or reload. Do not use a captured pi 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().");
471
+ this._disconnectFromAgent();
472
+ this._eventListeners = [];
473
+ cleanupSessionResources(this.sessionId);
474
+ }
475
+ // =========================================================================
476
+ // Read-only State Access
477
+ // =========================================================================
478
+ /** Full agent state */
479
+ get state() {
480
+ return this.agent.state;
481
+ }
482
+ /** Current model (may be undefined if not yet selected) */
483
+ get model() {
484
+ return this.agent.state.model;
485
+ }
486
+ /** Current thinking level */
487
+ get thinkingLevel() {
488
+ return this.agent.state.thinkingLevel;
489
+ }
490
+ /** Whether agent is currently streaming a response */
491
+ get isStreaming() {
492
+ return this.agent.state.isStreaming;
493
+ }
494
+ /** Current effective system prompt (includes any per-turn extension modifications) */
495
+ get systemPrompt() {
496
+ return this.agent.state.systemPrompt;
497
+ }
498
+ /** Current retry attempt (0 if not retrying) */
499
+ get retryAttempt() {
500
+ return this._retryAttempt;
501
+ }
502
+ /**
503
+ * Get the names of currently active tools.
504
+ * Returns the names of tools currently set on the agent.
505
+ */
506
+ getActiveToolNames() {
507
+ return this.agent.state.tools.map((t) => t.name);
508
+ }
509
+ /**
510
+ * Get all configured tools with name, description, parameter schema, and source metadata.
511
+ */
512
+ getAllTools() {
513
+ return Array.from(this._toolDefinitions.values()).map(({ definition, sourceInfo }) => ({
514
+ name: definition.name,
515
+ description: definition.description,
516
+ parameters: definition.parameters,
517
+ sourceInfo,
518
+ }));
519
+ }
520
+ getToolDefinition(name) {
521
+ return this._toolDefinitions.get(name)?.definition;
522
+ }
523
+ /**
524
+ * Set active tools by name.
525
+ * Only tools in the registry can be enabled. Unknown tool names are ignored.
526
+ * Also rebuilds the system prompt to reflect the new tool set.
527
+ * Changes take effect on the next agent turn.
528
+ */
529
+ setActiveToolsByName(toolNames) {
530
+ const tools = [];
531
+ const validToolNames = [];
532
+ for (const name of toolNames) {
533
+ const tool = this._toolRegistry.get(name);
534
+ if (tool) {
535
+ tools.push(tool);
536
+ validToolNames.push(name);
537
+ }
538
+ }
539
+ this.agent.state.tools = tools;
540
+ // Rebuild base system prompt with new tool set
541
+ this._baseSystemPrompt = this._rebuildSystemPrompt(validToolNames);
542
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
543
+ }
544
+ /** Whether compaction or branch summarization is currently running */
545
+ get isCompacting() {
546
+ return (this._autoCompactionAbortController !== undefined ||
547
+ this._compactionAbortController !== undefined ||
548
+ this._branchSummaryAbortController !== undefined);
549
+ }
550
+ /** All messages including custom types like BashExecutionMessage */
551
+ get messages() {
552
+ return this.agent.state.messages;
553
+ }
554
+ /** Current steering mode */
555
+ get steeringMode() {
556
+ return this.agent.steeringMode;
557
+ }
558
+ /** Current follow-up mode */
559
+ get followUpMode() {
560
+ return this.agent.followUpMode;
561
+ }
562
+ /** Current session file path, or undefined if sessions are disabled */
563
+ get sessionFile() {
564
+ return this.sessionManager.getSessionFile();
565
+ }
566
+ /** Current session ID */
567
+ get sessionId() {
568
+ return this.sessionManager.getSessionId();
569
+ }
570
+ /** Current session display name, if set */
571
+ get sessionName() {
572
+ return this.sessionManager.getSessionName();
573
+ }
574
+ /** Scoped models for cycling (from --models flag) */
575
+ get scopedModels() {
576
+ return this._scopedModels;
577
+ }
578
+ /** Update scoped models for cycling */
579
+ setScopedModels(scopedModels) {
580
+ this._scopedModels = scopedModels;
581
+ }
582
+ /** File-based prompt templates */
583
+ get promptTemplates() {
584
+ return this._resourceLoader.getPrompts().prompts;
585
+ }
586
+ _normalizePromptSnippet(text) {
587
+ if (!text)
588
+ return undefined;
589
+ const oneLine = text
590
+ .replace(/[\r\n]+/g, " ")
591
+ .replace(/\s+/g, " ")
592
+ .trim();
593
+ return oneLine.length > 0 ? oneLine : undefined;
594
+ }
595
+ _normalizePromptGuidelines(guidelines) {
596
+ if (!guidelines || guidelines.length === 0) {
597
+ return [];
598
+ }
599
+ const unique = new Set();
600
+ for (const guideline of guidelines) {
601
+ const normalized = guideline.trim();
602
+ if (normalized.length > 0) {
603
+ unique.add(normalized);
604
+ }
605
+ }
606
+ return Array.from(unique);
607
+ }
608
+ _rebuildSystemPrompt(toolNames) {
609
+ const validToolNames = toolNames.filter((name) => this._toolRegistry.has(name));
610
+ const toolSnippets = {};
611
+ const promptGuidelines = [];
612
+ for (const name of validToolNames) {
613
+ const snippet = this._toolPromptSnippets.get(name);
614
+ if (snippet) {
615
+ toolSnippets[name] = snippet;
616
+ }
617
+ const toolGuidelines = this._toolPromptGuidelines.get(name);
618
+ if (toolGuidelines) {
619
+ promptGuidelines.push(...toolGuidelines);
620
+ }
621
+ }
622
+ const loaderSystemPrompt = this._resourceLoader.getSystemPrompt();
623
+ const loaderAppendSystemPrompt = this._resourceLoader.getAppendSystemPrompt();
624
+ const appendSystemPrompt = loaderAppendSystemPrompt.length > 0 ? loaderAppendSystemPrompt.join("\n\n") : undefined;
625
+ const loadedSkills = this._resourceLoader.getSkills().skills;
626
+ const loadedContextFiles = this._resourceLoader.getAgentsFiles().agentsFiles;
627
+ this._baseSystemPromptOptions = {
628
+ cwd: this._cwd,
629
+ skills: loadedSkills,
630
+ contextFiles: loadedContextFiles,
631
+ customPrompt: loaderSystemPrompt,
632
+ appendSystemPrompt,
633
+ selectedTools: validToolNames,
634
+ toolSnippets,
635
+ promptGuidelines,
636
+ };
637
+ return buildSystemPrompt(this._baseSystemPromptOptions);
638
+ }
639
+ // =========================================================================
640
+ // Prompting
641
+ // =========================================================================
642
+ async _runAgentPrompt(messages) {
643
+ try {
644
+ await this.agent.prompt(messages);
645
+ while (await this._handlePostAgentRun()) {
646
+ await this.agent.continue();
647
+ }
648
+ }
649
+ finally {
650
+ this._flushPendingBashMessages();
651
+ }
652
+ }
653
+ async _handlePostAgentRun() {
654
+ const msg = this._lastAssistantMessage;
655
+ this._lastAssistantMessage = undefined;
656
+ if (!msg) {
657
+ return false;
658
+ }
659
+ if (this._isRetryableError(msg) && (await this._prepareRetry(msg))) {
660
+ return true;
661
+ }
662
+ if (msg.stopReason === "error" && this._retryAttempt > 0) {
663
+ this._emit({
664
+ type: "auto_retry_end",
665
+ success: false,
666
+ attempt: this._retryAttempt,
667
+ finalError: msg.errorMessage,
668
+ });
669
+ this._retryAttempt = 0;
670
+ }
671
+ return await this._checkCompaction(msg);
672
+ }
673
+ /**
674
+ * Send a prompt to the agent.
675
+ * - Handles extension commands (registered via pi.registerCommand) immediately, even during streaming
676
+ * - Expands file-based prompt templates by default
677
+ * - During streaming, queues via steer() or followUp() based on streamingBehavior option
678
+ * - Validates model and API key before sending (when not streaming)
679
+ * @throws Error if streaming and no streamingBehavior specified
680
+ * @throws Error if no model selected or no API key available (when not streaming)
681
+ */
682
+ async prompt(text, options) {
683
+ const expandPromptTemplates = options?.expandPromptTemplates ?? true;
684
+ const preflightResult = options?.preflightResult;
685
+ let messages;
686
+ try {
687
+ // Handle extension commands first (execute immediately, even during streaming)
688
+ // Extension commands manage their own LLM interaction via pi.sendMessage()
689
+ if (expandPromptTemplates && text.startsWith("/")) {
690
+ const handled = await this._tryExecuteExtensionCommand(text);
691
+ if (handled) {
692
+ // Extension command executed, no prompt to send
693
+ preflightResult?.(true);
694
+ return;
695
+ }
696
+ }
697
+ // Emit input event for extension interception (before skill/template expansion)
698
+ let currentText = text;
699
+ let currentImages = options?.images;
700
+ if (this._extensionRunner.hasHandlers("input")) {
701
+ const inputResult = await this._extensionRunner.emitInput(currentText, currentImages, options?.source ?? "interactive");
702
+ if (inputResult.action === "handled") {
703
+ preflightResult?.(true);
704
+ return;
705
+ }
706
+ if (inputResult.action === "transform") {
707
+ currentText = inputResult.text;
708
+ currentImages = inputResult.images ?? currentImages;
709
+ }
710
+ }
711
+ // Expand skill commands (/skill:name args) and prompt templates (/template args)
712
+ let expandedText = currentText;
713
+ if (expandPromptTemplates) {
714
+ expandedText = this._expandSkillCommand(expandedText);
715
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
716
+ }
717
+ // If streaming, queue via steer() or followUp() based on option
718
+ if (this.isStreaming) {
719
+ if (!options?.streamingBehavior) {
720
+ throw new Error("Agent is already processing. Specify streamingBehavior ('steer' or 'followUp') to queue the message.");
721
+ }
722
+ if (options.streamingBehavior === "followUp") {
723
+ await this._queueFollowUp(expandedText, currentImages);
724
+ }
725
+ else {
726
+ await this._queueSteer(expandedText, currentImages);
727
+ }
728
+ preflightResult?.(true);
729
+ return;
730
+ }
731
+ // Flush any pending bash messages before the new prompt
732
+ this._flushPendingBashMessages();
733
+ // Validate model
734
+ if (!this.model) {
735
+ throw new Error(formatNoModelSelectedMessage());
736
+ }
737
+ if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
738
+ const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
739
+ if (isOAuth) {
740
+ throw new Error(`Authentication failed for "${this.model.provider}". ` +
741
+ `Credentials may have expired or network is unavailable. ` +
742
+ `Run '/login ${this.model.provider}' to re-authenticate.`);
743
+ }
744
+ throw new Error(formatNoApiKeyFoundMessage(this.model.provider));
745
+ }
746
+ // Check if we need to compact before sending (catches aborted responses)
747
+ const lastAssistant = this._findLastAssistantMessage();
748
+ if (lastAssistant && (await this._checkCompaction(lastAssistant, false))) {
749
+ try {
750
+ await this.agent.continue();
751
+ while (await this._handlePostAgentRun()) {
752
+ await this.agent.continue();
753
+ }
754
+ }
755
+ finally {
756
+ this._flushPendingBashMessages();
757
+ }
758
+ }
759
+ // Build messages array (custom message if any, then user message)
760
+ messages = [];
761
+ // Add user message
762
+ const userContent = [{ type: "text", text: expandedText }];
763
+ if (currentImages) {
764
+ userContent.push(...currentImages);
765
+ }
766
+ messages.push({
767
+ role: "user",
768
+ content: userContent,
769
+ timestamp: Date.now(),
770
+ });
771
+ // Inject any pending "nextTurn" messages as context alongside the user message
772
+ for (const msg of this._pendingNextTurnMessages) {
773
+ messages.push(msg);
774
+ }
775
+ this._pendingNextTurnMessages = [];
776
+ // Emit before_agent_start extension event
777
+ const result = await this._extensionRunner.emitBeforeAgentStart(expandedText, currentImages, this._baseSystemPrompt, this._baseSystemPromptOptions);
778
+ // Add all custom messages from extensions
779
+ if (result?.messages) {
780
+ for (const msg of result.messages) {
781
+ messages.push({
782
+ role: "custom",
783
+ customType: msg.customType,
784
+ content: msg.content,
785
+ display: msg.display,
786
+ details: msg.details,
787
+ timestamp: Date.now(),
788
+ });
789
+ }
790
+ }
791
+ // Apply extension-modified system prompt, or reset to base
792
+ if (result?.systemPrompt) {
793
+ this.agent.state.systemPrompt = result.systemPrompt;
794
+ }
795
+ else {
796
+ // Ensure we're using the base prompt (in case previous turn had modifications)
797
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
798
+ }
799
+ }
800
+ catch (error) {
801
+ preflightResult?.(false);
802
+ throw error;
803
+ }
804
+ if (!messages) {
805
+ return;
806
+ }
807
+ preflightResult?.(true);
808
+ await this._runAgentPrompt(messages);
809
+ }
810
+ /**
811
+ * Try to execute an extension command. Returns true if command was found and executed.
812
+ */
813
+ async _tryExecuteExtensionCommand(text) {
814
+ // Parse command name and args
815
+ const spaceIndex = text.indexOf(" ");
816
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
817
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1);
818
+ const command = this._extensionRunner.getCommand(commandName);
819
+ if (!command)
820
+ return false;
821
+ // Get command context from extension runner (includes session control methods)
822
+ const ctx = this._extensionRunner.createCommandContext();
823
+ try {
824
+ await command.handler(args, ctx);
825
+ return true;
826
+ }
827
+ catch (err) {
828
+ // Emit error via extension runner
829
+ this._extensionRunner.emitError({
830
+ extensionPath: `command:${commandName}`,
831
+ event: "command",
832
+ error: err instanceof Error ? err.message : String(err),
833
+ });
834
+ return true;
835
+ }
836
+ }
837
+ /**
838
+ * Expand skill commands (/skill:name args) to their full content.
839
+ * Returns the expanded text, or the original text if not a skill command or skill not found.
840
+ * Emits errors via extension runner if file read fails.
841
+ */
842
+ _expandSkillCommand(text) {
843
+ if (!text.startsWith("/skill:"))
844
+ return text;
845
+ const spaceIndex = text.indexOf(" ");
846
+ const skillName = spaceIndex === -1 ? text.slice(7) : text.slice(7, spaceIndex);
847
+ const args = spaceIndex === -1 ? "" : text.slice(spaceIndex + 1).trim();
848
+ const skill = this.resourceLoader.getSkills().skills.find((s) => s.name === skillName);
849
+ if (!skill)
850
+ return text; // Unknown skill, pass through
851
+ try {
852
+ const content = readFileSync(skill.filePath, "utf-8");
853
+ const body = stripFrontmatter(content).trim();
854
+ const skillBlock = `<skill name="${skill.name}" location="${skill.filePath}">\nReferences are relative to ${skill.baseDir}.\n\n${body}\n</skill>`;
855
+ return args ? `${skillBlock}\n\n${args}` : skillBlock;
856
+ }
857
+ catch (err) {
858
+ // Emit error like extension commands do
859
+ this._extensionRunner.emitError({
860
+ extensionPath: skill.filePath,
861
+ event: "skill_expansion",
862
+ error: err instanceof Error ? err.message : String(err),
863
+ });
864
+ return text; // Return original on error
865
+ }
866
+ }
867
+ /**
868
+ * Queue a steering message while the agent is running.
869
+ * Delivered after the current assistant turn finishes executing its tool calls,
870
+ * before the next LLM call.
871
+ * Expands skill commands and prompt templates. Errors on extension commands.
872
+ * @param images Optional image attachments to include with the message
873
+ * @throws Error if text is an extension command
874
+ */
875
+ async steer(text, images) {
876
+ // Check for extension commands (cannot be queued)
877
+ if (text.startsWith("/")) {
878
+ this._throwIfExtensionCommand(text);
879
+ }
880
+ // Expand skill commands and prompt templates
881
+ let expandedText = this._expandSkillCommand(text);
882
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
883
+ await this._queueSteer(expandedText, images);
884
+ }
885
+ /**
886
+ * Queue a follow-up message to be processed after the agent finishes.
887
+ * Delivered only when agent has no more tool calls or steering messages.
888
+ * Expands skill commands and prompt templates. Errors on extension commands.
889
+ * @param images Optional image attachments to include with the message
890
+ * @throws Error if text is an extension command
891
+ */
892
+ async followUp(text, images) {
893
+ // Check for extension commands (cannot be queued)
894
+ if (text.startsWith("/")) {
895
+ this._throwIfExtensionCommand(text);
896
+ }
897
+ // Expand skill commands and prompt templates
898
+ let expandedText = this._expandSkillCommand(text);
899
+ expandedText = expandPromptTemplate(expandedText, [...this.promptTemplates]);
900
+ await this._queueFollowUp(expandedText, images);
901
+ }
902
+ /**
903
+ * Internal: Queue a steering message (already expanded, no extension command check).
904
+ */
905
+ async _queueSteer(text, images) {
906
+ this._steeringMessages.push(text);
907
+ this._emitQueueUpdate();
908
+ const content = [{ type: "text", text }];
909
+ if (images) {
910
+ content.push(...images);
911
+ }
912
+ this.agent.steer({
913
+ role: "user",
914
+ content,
915
+ timestamp: Date.now(),
916
+ });
917
+ }
918
+ /**
919
+ * Internal: Queue a follow-up message (already expanded, no extension command check).
920
+ */
921
+ async _queueFollowUp(text, images) {
922
+ this._followUpMessages.push(text);
923
+ this._emitQueueUpdate();
924
+ const content = [{ type: "text", text }];
925
+ if (images) {
926
+ content.push(...images);
927
+ }
928
+ this.agent.followUp({
929
+ role: "user",
930
+ content,
931
+ timestamp: Date.now(),
932
+ });
933
+ }
934
+ /**
935
+ * Throw an error if the text is an extension command.
936
+ */
937
+ _throwIfExtensionCommand(text) {
938
+ const spaceIndex = text.indexOf(" ");
939
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
940
+ const command = this._extensionRunner.getCommand(commandName);
941
+ if (command) {
942
+ throw new Error(`Extension command "/${commandName}" cannot be queued. Use prompt() or execute the command when not streaming.`);
943
+ }
944
+ }
945
+ /**
946
+ * Send a custom message to the session. Creates a CustomMessageEntry.
947
+ *
948
+ * Handles three cases:
949
+ * - Streaming: queues message, processed when loop pulls from queue
950
+ * - Not streaming + triggerTurn: appends to state/session, starts new turn
951
+ * - Not streaming + no trigger: appends to state/session, no turn
952
+ *
953
+ * @param message Custom message with customType, content, display, details
954
+ * @param options.triggerTurn If true and not streaming, triggers a new LLM turn
955
+ * @param options.deliverAs Delivery mode: "steer", "followUp", or "nextTurn"
956
+ */
957
+ async sendCustomMessage(message, options) {
958
+ const appMessage = {
959
+ role: "custom",
960
+ customType: message.customType,
961
+ content: message.content,
962
+ display: message.display,
963
+ details: message.details,
964
+ timestamp: Date.now(),
965
+ };
966
+ if (options?.deliverAs === "nextTurn") {
967
+ this._pendingNextTurnMessages.push(appMessage);
968
+ }
969
+ else if (this.isStreaming) {
970
+ if (options?.deliverAs === "followUp") {
971
+ this.agent.followUp(appMessage);
972
+ }
973
+ else {
974
+ this.agent.steer(appMessage);
975
+ }
976
+ }
977
+ else if (options?.triggerTurn) {
978
+ await this._runAgentPrompt(appMessage);
979
+ }
980
+ else {
981
+ this.agent.state.messages.push(appMessage);
982
+ this.sessionManager.appendCustomMessageEntry(message.customType, message.content, message.display, message.details);
983
+ this._emit({ type: "message_start", message: appMessage });
984
+ this._emit({ type: "message_end", message: appMessage });
985
+ }
986
+ }
987
+ /**
988
+ * Send a user message to the agent. Always triggers a turn.
989
+ * When the agent is streaming, use deliverAs to specify how to queue the message.
990
+ *
991
+ * @param content User message content (string or content array)
992
+ * @param options.deliverAs Delivery mode when streaming: "steer" or "followUp"
993
+ */
994
+ async sendUserMessage(content, options) {
995
+ // Normalize content to text string + optional images
996
+ let text;
997
+ let images;
998
+ if (typeof content === "string") {
999
+ text = content;
1000
+ }
1001
+ else {
1002
+ const textParts = [];
1003
+ images = [];
1004
+ for (const part of content) {
1005
+ if (part.type === "text") {
1006
+ textParts.push(part.text);
1007
+ }
1008
+ else {
1009
+ images.push(part);
1010
+ }
1011
+ }
1012
+ text = textParts.join("\n");
1013
+ if (images.length === 0)
1014
+ images = undefined;
1015
+ }
1016
+ // Use prompt() with expandPromptTemplates: false to skip command handling and template expansion
1017
+ await this.prompt(text, {
1018
+ expandPromptTemplates: false,
1019
+ streamingBehavior: options?.deliverAs,
1020
+ images,
1021
+ source: "extension",
1022
+ });
1023
+ }
1024
+ /**
1025
+ * Clear all queued messages and return them.
1026
+ * Useful for restoring to editor when user aborts.
1027
+ * @returns Object with steering and followUp arrays
1028
+ */
1029
+ clearQueue() {
1030
+ const steering = [...this._steeringMessages];
1031
+ const followUp = [...this._followUpMessages];
1032
+ this._steeringMessages = [];
1033
+ this._followUpMessages = [];
1034
+ this.agent.clearAllQueues();
1035
+ this._emitQueueUpdate();
1036
+ return { steering, followUp };
1037
+ }
1038
+ /** Number of pending messages (includes both steering and follow-up) */
1039
+ get pendingMessageCount() {
1040
+ return this._steeringMessages.length + this._followUpMessages.length;
1041
+ }
1042
+ /** Get pending steering messages (read-only) */
1043
+ getSteeringMessages() {
1044
+ return this._steeringMessages;
1045
+ }
1046
+ /** Get pending follow-up messages (read-only) */
1047
+ getFollowUpMessages() {
1048
+ return this._followUpMessages;
1049
+ }
1050
+ get resourceLoader() {
1051
+ return this._resourceLoader;
1052
+ }
1053
+ /**
1054
+ * Abort current operation and wait for agent to become idle.
1055
+ */
1056
+ async abort() {
1057
+ this.abortRetry();
1058
+ this.agent.abort();
1059
+ await this.agent.waitForIdle();
1060
+ }
1061
+ // =========================================================================
1062
+ // Model Management
1063
+ // =========================================================================
1064
+ async _emitModelSelect(nextModel, previousModel, source) {
1065
+ if (modelsAreEqual(previousModel, nextModel))
1066
+ return;
1067
+ await this._extensionRunner.emit({
1068
+ type: "model_select",
1069
+ model: nextModel,
1070
+ previousModel,
1071
+ source,
1072
+ });
1073
+ }
1074
+ /**
1075
+ * Set model directly.
1076
+ * Validates that auth is configured, saves to session and settings.
1077
+ * @throws Error if no auth is configured for the model
1078
+ */
1079
+ async setModel(model) {
1080
+ if (!this._modelRegistry.hasConfiguredAuth(model)) {
1081
+ throw new Error(`No API key for ${model.provider}/${model.id}`);
1082
+ }
1083
+ const previousModel = this.model;
1084
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1085
+ this.agent.state.model = model;
1086
+ this.sessionManager.appendModelChange(model.provider, model.id);
1087
+ this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1088
+ // Re-clamp thinking level for new model's capabilities
1089
+ this.setThinkingLevel(thinkingLevel);
1090
+ await this._emitModelSelect(model, previousModel, "set");
1091
+ }
1092
+ /**
1093
+ * Cycle to next/previous model.
1094
+ * Uses scoped models (from --models flag) if available, otherwise all available models.
1095
+ * @param direction - "forward" (default) or "backward"
1096
+ * @returns The new model info, or undefined if only one model available
1097
+ */
1098
+ async cycleModel(direction = "forward") {
1099
+ if (this._scopedModels.length > 0) {
1100
+ return this._cycleScopedModel(direction);
1101
+ }
1102
+ return this._cycleAvailableModel(direction);
1103
+ }
1104
+ async _cycleScopedModel(direction) {
1105
+ const scopedModels = this._scopedModels.filter((scoped) => this._modelRegistry.hasConfiguredAuth(scoped.model));
1106
+ if (scopedModels.length <= 1)
1107
+ return undefined;
1108
+ const currentModel = this.model;
1109
+ let currentIndex = scopedModels.findIndex((sm) => modelsAreEqual(sm.model, currentModel));
1110
+ if (currentIndex === -1)
1111
+ currentIndex = 0;
1112
+ const len = scopedModels.length;
1113
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1114
+ const next = scopedModels[nextIndex];
1115
+ const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
1116
+ // Apply model
1117
+ this.agent.state.model = next.model;
1118
+ this.sessionManager.appendModelChange(next.model.provider, next.model.id);
1119
+ this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1120
+ // Apply thinking level.
1121
+ // - Explicit scoped model thinking level overrides current session level
1122
+ // - Undefined scoped model thinking level inherits the current session preference
1123
+ // setThinkingLevel clamps to model capabilities.
1124
+ this.setThinkingLevel(thinkingLevel);
1125
+ await this._emitModelSelect(next.model, currentModel, "cycle");
1126
+ return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1127
+ }
1128
+ async _cycleAvailableModel(direction) {
1129
+ const availableModels = await this._modelRegistry.getAvailable();
1130
+ if (availableModels.length <= 1)
1131
+ return undefined;
1132
+ const currentModel = this.model;
1133
+ let currentIndex = availableModels.findIndex((m) => modelsAreEqual(m, currentModel));
1134
+ if (currentIndex === -1)
1135
+ currentIndex = 0;
1136
+ const len = availableModels.length;
1137
+ const nextIndex = direction === "forward" ? (currentIndex + 1) % len : (currentIndex - 1 + len) % len;
1138
+ const nextModel = availableModels[nextIndex];
1139
+ const thinkingLevel = this._getThinkingLevelForModelSwitch();
1140
+ this.agent.state.model = nextModel;
1141
+ this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
1142
+ this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1143
+ // Re-clamp thinking level for new model's capabilities
1144
+ this.setThinkingLevel(thinkingLevel);
1145
+ await this._emitModelSelect(nextModel, currentModel, "cycle");
1146
+ return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
1147
+ }
1148
+ // =========================================================================
1149
+ // Thinking Level Management
1150
+ // =========================================================================
1151
+ /**
1152
+ * Set thinking level.
1153
+ * Clamps to model capabilities based on available thinking levels.
1154
+ * Saves to session and settings only if the level actually changes.
1155
+ */
1156
+ setThinkingLevel(level) {
1157
+ const availableLevels = this.getAvailableThinkingLevels();
1158
+ const effectiveLevel = availableLevels.includes(level) ? level : this._clampThinkingLevel(level, availableLevels);
1159
+ // Only persist if actually changing
1160
+ const previousLevel = this.agent.state.thinkingLevel;
1161
+ const isChanging = effectiveLevel !== previousLevel;
1162
+ this.agent.state.thinkingLevel = effectiveLevel;
1163
+ if (isChanging) {
1164
+ this.sessionManager.appendThinkingLevelChange(effectiveLevel);
1165
+ if (this.supportsThinking() || effectiveLevel !== "off") {
1166
+ this.settingsManager.setDefaultThinkingLevel(effectiveLevel);
1167
+ }
1168
+ this._emit({ type: "thinking_level_changed", level: effectiveLevel });
1169
+ void this._extensionRunner.emit({
1170
+ type: "thinking_level_select",
1171
+ level: effectiveLevel,
1172
+ previousLevel,
1173
+ });
1174
+ }
1175
+ }
1176
+ /**
1177
+ * Cycle to next thinking level.
1178
+ * @returns New level, or undefined if model doesn't support thinking
1179
+ */
1180
+ cycleThinkingLevel() {
1181
+ if (!this.supportsThinking())
1182
+ return undefined;
1183
+ const levels = this.getAvailableThinkingLevels();
1184
+ const currentIndex = levels.indexOf(this.thinkingLevel);
1185
+ const nextIndex = (currentIndex + 1) % levels.length;
1186
+ const nextLevel = levels[nextIndex];
1187
+ this.setThinkingLevel(nextLevel);
1188
+ return nextLevel;
1189
+ }
1190
+ /**
1191
+ * Get available thinking levels for current model.
1192
+ * The provider will clamp to what the specific model supports internally.
1193
+ */
1194
+ getAvailableThinkingLevels() {
1195
+ if (!this.model)
1196
+ return THINKING_LEVELS;
1197
+ return getSupportedThinkingLevels(this.model);
1198
+ }
1199
+ /**
1200
+ * Check if current model supports thinking/reasoning.
1201
+ */
1202
+ supportsThinking() {
1203
+ return !!this.model?.reasoning;
1204
+ }
1205
+ _getThinkingLevelForModelSwitch(explicitLevel) {
1206
+ if (explicitLevel !== undefined) {
1207
+ return explicitLevel;
1208
+ }
1209
+ if (!this.supportsThinking()) {
1210
+ return this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
1211
+ }
1212
+ return this.thinkingLevel;
1213
+ }
1214
+ _clampThinkingLevel(level, _availableLevels) {
1215
+ return this.model ? clampThinkingLevel(this.model, level) : "off";
1216
+ }
1217
+ // =========================================================================
1218
+ // Queue Mode Management
1219
+ // =========================================================================
1220
+ /**
1221
+ * Set steering message mode.
1222
+ * Saves to settings.
1223
+ */
1224
+ setSteeringMode(mode) {
1225
+ this.agent.steeringMode = mode;
1226
+ this.settingsManager.setSteeringMode(mode);
1227
+ }
1228
+ /**
1229
+ * Set follow-up message mode.
1230
+ * Saves to settings.
1231
+ */
1232
+ setFollowUpMode(mode) {
1233
+ this.agent.followUpMode = mode;
1234
+ this.settingsManager.setFollowUpMode(mode);
1235
+ }
1236
+ // =========================================================================
1237
+ // Compaction
1238
+ // =========================================================================
1239
+ /**
1240
+ * Manually compact the session context.
1241
+ * Aborts current agent operation first.
1242
+ * @param customInstructions Optional instructions for the compaction summary
1243
+ */
1244
+ async compact(customInstructions) {
1245
+ this._disconnectFromAgent();
1246
+ await this.abort();
1247
+ this._compactionAbortController = new AbortController();
1248
+ this._emit({ type: "compaction_start", reason: "manual" });
1249
+ try {
1250
+ if (!this.model) {
1251
+ throw new Error(formatNoModelSelectedMessage());
1252
+ }
1253
+ const { apiKey, headers } = await this._getCompactionRequestAuth(this.model);
1254
+ const pathEntries = this.sessionManager.getBranch();
1255
+ const settings = this.settingsManager.getCompactionSettings();
1256
+ const preparation = prepareCompaction(pathEntries, settings);
1257
+ if (!preparation) {
1258
+ // Check why we can't compact
1259
+ const lastEntry = pathEntries[pathEntries.length - 1];
1260
+ if (lastEntry?.type === "compaction") {
1261
+ throw new Error("Already compacted");
1262
+ }
1263
+ throw new Error("Nothing to compact (session too small)");
1264
+ }
1265
+ let extensionCompaction;
1266
+ let fromExtension = false;
1267
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1268
+ const result = (await this._extensionRunner.emit({
1269
+ type: "session_before_compact",
1270
+ preparation,
1271
+ branchEntries: pathEntries,
1272
+ customInstructions,
1273
+ signal: this._compactionAbortController.signal,
1274
+ }));
1275
+ if (result?.cancel) {
1276
+ throw new Error("Compaction cancelled");
1277
+ }
1278
+ if (result?.compaction) {
1279
+ extensionCompaction = result.compaction;
1280
+ fromExtension = true;
1281
+ }
1282
+ }
1283
+ let summary;
1284
+ let firstKeptEntryId;
1285
+ let tokensBefore;
1286
+ let details;
1287
+ if (extensionCompaction) {
1288
+ // Extension provided compaction content
1289
+ summary = extensionCompaction.summary;
1290
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1291
+ tokensBefore = extensionCompaction.tokensBefore;
1292
+ details = extensionCompaction.details;
1293
+ }
1294
+ else {
1295
+ // Generate compaction result
1296
+ const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal, this.thinkingLevel, this.agent.streamFn);
1297
+ summary = result.summary;
1298
+ firstKeptEntryId = result.firstKeptEntryId;
1299
+ tokensBefore = result.tokensBefore;
1300
+ details = result.details;
1301
+ }
1302
+ if (this._compactionAbortController.signal.aborted) {
1303
+ throw new Error("Compaction cancelled");
1304
+ }
1305
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1306
+ const newEntries = this.sessionManager.getEntries();
1307
+ const sessionContext = this.sessionManager.buildSessionContext();
1308
+ this.agent.state.messages = sessionContext.messages;
1309
+ // Get the saved compaction entry for the extension event
1310
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1311
+ if (this._extensionRunner && savedCompactionEntry) {
1312
+ await this._extensionRunner.emit({
1313
+ type: "session_compact",
1314
+ compactionEntry: savedCompactionEntry,
1315
+ fromExtension,
1316
+ });
1317
+ }
1318
+ const compactionResult = {
1319
+ summary,
1320
+ firstKeptEntryId,
1321
+ tokensBefore,
1322
+ details,
1323
+ };
1324
+ this._emit({
1325
+ type: "compaction_end",
1326
+ reason: "manual",
1327
+ result: compactionResult,
1328
+ aborted: false,
1329
+ willRetry: false,
1330
+ });
1331
+ return compactionResult;
1332
+ }
1333
+ catch (error) {
1334
+ const message = error instanceof Error ? error.message : String(error);
1335
+ const aborted = message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError");
1336
+ this._emit({
1337
+ type: "compaction_end",
1338
+ reason: "manual",
1339
+ result: undefined,
1340
+ aborted,
1341
+ willRetry: false,
1342
+ errorMessage: aborted ? undefined : `Compaction failed: ${message}`,
1343
+ });
1344
+ throw error;
1345
+ }
1346
+ finally {
1347
+ this._compactionAbortController = undefined;
1348
+ this._reconnectToAgent();
1349
+ }
1350
+ }
1351
+ /**
1352
+ * Cancel in-progress compaction (manual or auto).
1353
+ */
1354
+ abortCompaction() {
1355
+ this._compactionAbortController?.abort();
1356
+ this._autoCompactionAbortController?.abort();
1357
+ }
1358
+ /**
1359
+ * Cancel in-progress branch summarization.
1360
+ */
1361
+ abortBranchSummary() {
1362
+ this._branchSummaryAbortController?.abort();
1363
+ }
1364
+ /**
1365
+ * Check if compaction is needed and run it.
1366
+ * Called after agent_end and before prompt submission.
1367
+ *
1368
+ * Two cases:
1369
+ * 1. Overflow: LLM returned context overflow error, remove error message from agent state, compact, auto-retry
1370
+ * 2. Threshold: Context over threshold, compact, NO auto-retry (user continues manually)
1371
+ *
1372
+ * @param assistantMessage The assistant message to check
1373
+ * @param skipAbortedCheck If false, include aborted messages (for pre-prompt check). Default: true
1374
+ */
1375
+ async _checkCompaction(assistantMessage, skipAbortedCheck = true) {
1376
+ const settings = this.settingsManager.getCompactionSettings();
1377
+ if (!settings.enabled)
1378
+ return false;
1379
+ // Skip if message was aborted (user cancelled) - unless skipAbortedCheck is false
1380
+ if (skipAbortedCheck && assistantMessage.stopReason === "aborted")
1381
+ return false;
1382
+ const contextWindow = this.model?.contextWindow ?? 0;
1383
+ // Skip overflow check if the message came from a different model.
1384
+ // This handles the case where user switched from a smaller-context model (e.g. opus)
1385
+ // to a larger-context model (e.g. codex) - the overflow error from the old model
1386
+ // shouldn't trigger compaction for the new model.
1387
+ const sameModel = this.model && assistantMessage.provider === this.model.provider && assistantMessage.model === this.model.id;
1388
+ // Skip compaction checks if this assistant message is older than the latest
1389
+ // compaction boundary. This prevents a stale pre-compaction usage/error
1390
+ // from retriggering compaction on the first prompt after compaction.
1391
+ const compactionEntry = getLatestCompactionEntry(this.sessionManager.getBranch());
1392
+ const assistantIsFromBeforeCompaction = compactionEntry !== null && assistantMessage.timestamp <= new Date(compactionEntry.timestamp).getTime();
1393
+ if (assistantIsFromBeforeCompaction) {
1394
+ return false;
1395
+ }
1396
+ // Case 1: Overflow - LLM returned context overflow error
1397
+ if (sameModel && isContextOverflow(assistantMessage, contextWindow)) {
1398
+ if (this._overflowRecoveryAttempted) {
1399
+ this._emit({
1400
+ type: "compaction_end",
1401
+ reason: "overflow",
1402
+ result: undefined,
1403
+ aborted: false,
1404
+ willRetry: false,
1405
+ errorMessage: "Context overflow recovery failed after one compact-and-retry attempt. Try reducing context or switching to a larger-context model.",
1406
+ });
1407
+ return false;
1408
+ }
1409
+ this._overflowRecoveryAttempted = true;
1410
+ // Remove the error message from agent state (it IS saved to session for history,
1411
+ // but we don't want it in context for the retry)
1412
+ const messages = this.agent.state.messages;
1413
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1414
+ this.agent.state.messages = messages.slice(0, -1);
1415
+ }
1416
+ return await this._runAutoCompaction("overflow", true);
1417
+ }
1418
+ // Case 2: Threshold - context is getting large
1419
+ // For error messages (no usage data), estimate from last successful response.
1420
+ // This ensures sessions that hit persistent API errors (e.g. 529) can still compact.
1421
+ let contextTokens;
1422
+ if (assistantMessage.stopReason === "error") {
1423
+ const messages = this.agent.state.messages;
1424
+ const estimate = estimateContextTokens(messages);
1425
+ if (estimate.lastUsageIndex === null)
1426
+ return false; // No usage data at all
1427
+ // Verify the usage source is post-compaction. Kept pre-compaction messages
1428
+ // have stale usage reflecting the old (larger) context and would falsely
1429
+ // trigger compaction right after one just finished.
1430
+ const usageMsg = messages[estimate.lastUsageIndex];
1431
+ if (compactionEntry &&
1432
+ usageMsg.role === "assistant" &&
1433
+ usageMsg.timestamp <= new Date(compactionEntry.timestamp).getTime()) {
1434
+ return false;
1435
+ }
1436
+ contextTokens = estimate.tokens;
1437
+ }
1438
+ else {
1439
+ contextTokens = calculateContextTokens(assistantMessage.usage);
1440
+ }
1441
+ if (shouldCompact(contextTokens, contextWindow, settings)) {
1442
+ return await this._runAutoCompaction("threshold", false);
1443
+ }
1444
+ return false;
1445
+ }
1446
+ /**
1447
+ * Internal: Run auto-compaction with events.
1448
+ */
1449
+ async _runAutoCompaction(reason, willRetry) {
1450
+ const settings = this.settingsManager.getCompactionSettings();
1451
+ this._emit({ type: "compaction_start", reason });
1452
+ this._autoCompactionAbortController = new AbortController();
1453
+ try {
1454
+ if (!this.model) {
1455
+ this._emit({
1456
+ type: "compaction_end",
1457
+ reason,
1458
+ result: undefined,
1459
+ aborted: false,
1460
+ willRetry: false,
1461
+ });
1462
+ return false;
1463
+ }
1464
+ let apiKey;
1465
+ let headers;
1466
+ if (this.agent.streamFn === streamSimple) {
1467
+ const authResult = await this._modelRegistry.getApiKeyAndHeaders(this.model);
1468
+ if (!authResult.ok || !authResult.apiKey) {
1469
+ this._emit({
1470
+ type: "compaction_end",
1471
+ reason,
1472
+ result: undefined,
1473
+ aborted: false,
1474
+ willRetry: false,
1475
+ });
1476
+ return false;
1477
+ }
1478
+ apiKey = authResult.apiKey;
1479
+ headers = authResult.headers;
1480
+ }
1481
+ else {
1482
+ ({ apiKey, headers } = await this._getCompactionRequestAuth(this.model));
1483
+ }
1484
+ const pathEntries = this.sessionManager.getBranch();
1485
+ const preparation = prepareCompaction(pathEntries, settings);
1486
+ if (!preparation) {
1487
+ this._emit({
1488
+ type: "compaction_end",
1489
+ reason,
1490
+ result: undefined,
1491
+ aborted: false,
1492
+ willRetry: false,
1493
+ });
1494
+ return false;
1495
+ }
1496
+ let extensionCompaction;
1497
+ let fromExtension = false;
1498
+ if (this._extensionRunner.hasHandlers("session_before_compact")) {
1499
+ const extensionResult = (await this._extensionRunner.emit({
1500
+ type: "session_before_compact",
1501
+ preparation,
1502
+ branchEntries: pathEntries,
1503
+ customInstructions: undefined,
1504
+ signal: this._autoCompactionAbortController.signal,
1505
+ }));
1506
+ if (extensionResult?.cancel) {
1507
+ this._emit({
1508
+ type: "compaction_end",
1509
+ reason,
1510
+ result: undefined,
1511
+ aborted: true,
1512
+ willRetry: false,
1513
+ });
1514
+ return false;
1515
+ }
1516
+ if (extensionResult?.compaction) {
1517
+ extensionCompaction = extensionResult.compaction;
1518
+ fromExtension = true;
1519
+ }
1520
+ }
1521
+ let summary;
1522
+ let firstKeptEntryId;
1523
+ let tokensBefore;
1524
+ let details;
1525
+ if (extensionCompaction) {
1526
+ // Extension provided compaction content
1527
+ summary = extensionCompaction.summary;
1528
+ firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1529
+ tokensBefore = extensionCompaction.tokensBefore;
1530
+ details = extensionCompaction.details;
1531
+ }
1532
+ else {
1533
+ // Generate compaction result
1534
+ const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal, this.thinkingLevel, this.agent.streamFn);
1535
+ summary = compactResult.summary;
1536
+ firstKeptEntryId = compactResult.firstKeptEntryId;
1537
+ tokensBefore = compactResult.tokensBefore;
1538
+ details = compactResult.details;
1539
+ }
1540
+ if (this._autoCompactionAbortController.signal.aborted) {
1541
+ this._emit({
1542
+ type: "compaction_end",
1543
+ reason,
1544
+ result: undefined,
1545
+ aborted: true,
1546
+ willRetry: false,
1547
+ });
1548
+ return false;
1549
+ }
1550
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1551
+ const newEntries = this.sessionManager.getEntries();
1552
+ const sessionContext = this.sessionManager.buildSessionContext();
1553
+ this.agent.state.messages = sessionContext.messages;
1554
+ // Get the saved compaction entry for the extension event
1555
+ const savedCompactionEntry = newEntries.find((e) => e.type === "compaction" && e.summary === summary);
1556
+ if (this._extensionRunner && savedCompactionEntry) {
1557
+ await this._extensionRunner.emit({
1558
+ type: "session_compact",
1559
+ compactionEntry: savedCompactionEntry,
1560
+ fromExtension,
1561
+ });
1562
+ }
1563
+ const result = {
1564
+ summary,
1565
+ firstKeptEntryId,
1566
+ tokensBefore,
1567
+ details,
1568
+ };
1569
+ this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
1570
+ if (willRetry) {
1571
+ const messages = this.agent.state.messages;
1572
+ const lastMsg = messages[messages.length - 1];
1573
+ if (lastMsg?.role === "assistant" && lastMsg.stopReason === "error") {
1574
+ this.agent.state.messages = messages.slice(0, -1);
1575
+ }
1576
+ return true;
1577
+ }
1578
+ // Auto-compaction can complete while follow-up/steering/custom messages are waiting.
1579
+ // Continue once so queued messages are delivered.
1580
+ return this.agent.hasQueuedMessages();
1581
+ }
1582
+ catch (error) {
1583
+ const errorMessage = error instanceof Error ? error.message : "compaction failed";
1584
+ this._emit({
1585
+ type: "compaction_end",
1586
+ reason,
1587
+ result: undefined,
1588
+ aborted: false,
1589
+ willRetry: false,
1590
+ errorMessage: reason === "overflow"
1591
+ ? `Context overflow recovery failed: ${errorMessage}`
1592
+ : `Auto-compaction failed: ${errorMessage}`,
1593
+ });
1594
+ return false;
1595
+ }
1596
+ finally {
1597
+ this._autoCompactionAbortController = undefined;
1598
+ }
1599
+ }
1600
+ /**
1601
+ * Toggle auto-compaction setting.
1602
+ */
1603
+ setAutoCompactionEnabled(enabled) {
1604
+ this.settingsManager.setCompactionEnabled(enabled);
1605
+ }
1606
+ /** Whether auto-compaction is enabled */
1607
+ get autoCompactionEnabled() {
1608
+ return this.settingsManager.getCompactionEnabled();
1609
+ }
1610
+ async bindExtensions(bindings) {
1611
+ if (bindings.uiContext !== undefined) {
1612
+ this._extensionUIContext = bindings.uiContext;
1613
+ }
1614
+ if (bindings.commandContextActions !== undefined) {
1615
+ this._extensionCommandContextActions = bindings.commandContextActions;
1616
+ }
1617
+ if (bindings.abortHandler !== undefined) {
1618
+ this._extensionAbortHandler = bindings.abortHandler;
1619
+ }
1620
+ if (bindings.shutdownHandler !== undefined) {
1621
+ this._extensionShutdownHandler = bindings.shutdownHandler;
1622
+ }
1623
+ if (bindings.onError !== undefined) {
1624
+ this._extensionErrorListener = bindings.onError;
1625
+ }
1626
+ this._applyExtensionBindings(this._extensionRunner);
1627
+ await this._extensionRunner.emit(this._sessionStartEvent);
1628
+ await this.extendResourcesFromExtensions(this._sessionStartEvent.reason === "reload" ? "reload" : "startup");
1629
+ }
1630
+ async extendResourcesFromExtensions(reason) {
1631
+ if (!this._extensionRunner.hasHandlers("resources_discover")) {
1632
+ return;
1633
+ }
1634
+ const { skillPaths, promptPaths, themePaths } = await this._extensionRunner.emitResourcesDiscover(this._cwd, reason);
1635
+ if (skillPaths.length === 0 && promptPaths.length === 0 && themePaths.length === 0) {
1636
+ return;
1637
+ }
1638
+ const extensionPaths = {
1639
+ skillPaths: this.buildExtensionResourcePaths(skillPaths),
1640
+ promptPaths: this.buildExtensionResourcePaths(promptPaths),
1641
+ themePaths: this.buildExtensionResourcePaths(themePaths),
1642
+ };
1643
+ this._resourceLoader.extendResources(extensionPaths);
1644
+ this._baseSystemPrompt = this._rebuildSystemPrompt(this.getActiveToolNames());
1645
+ this.agent.state.systemPrompt = this._baseSystemPrompt;
1646
+ }
1647
+ buildExtensionResourcePaths(entries) {
1648
+ return entries.map((entry) => {
1649
+ const source = this.getExtensionSourceLabel(entry.extensionPath);
1650
+ const baseDir = entry.extensionPath.startsWith("<") ? undefined : dirname(entry.extensionPath);
1651
+ return {
1652
+ path: entry.path,
1653
+ metadata: {
1654
+ source,
1655
+ scope: "temporary",
1656
+ origin: "top-level",
1657
+ baseDir,
1658
+ },
1659
+ };
1660
+ });
1661
+ }
1662
+ getExtensionSourceLabel(extensionPath) {
1663
+ if (extensionPath.startsWith("<")) {
1664
+ return `extension:${extensionPath.replace(/[<>]/g, "")}`;
1665
+ }
1666
+ const base = basename(extensionPath);
1667
+ const name = base.replace(/\.(ts|js)$/, "");
1668
+ return `extension:${name}`;
1669
+ }
1670
+ _applyExtensionBindings(runner) {
1671
+ runner.setUIContext(this._extensionUIContext);
1672
+ runner.bindCommandContext(this._extensionCommandContextActions);
1673
+ this._extensionErrorUnsubscriber?.();
1674
+ this._extensionErrorUnsubscriber = this._extensionErrorListener
1675
+ ? runner.onError(this._extensionErrorListener)
1676
+ : undefined;
1677
+ }
1678
+ _refreshCurrentModelFromRegistry() {
1679
+ const currentModel = this.model;
1680
+ if (!currentModel) {
1681
+ return;
1682
+ }
1683
+ const refreshedModel = this._modelRegistry.find(currentModel.provider, currentModel.id);
1684
+ if (!refreshedModel || refreshedModel === currentModel) {
1685
+ return;
1686
+ }
1687
+ this.agent.state.model = refreshedModel;
1688
+ }
1689
+ _bindExtensionCore(runner) {
1690
+ const getCommands = () => {
1691
+ const extensionCommands = runner.getRegisteredCommands().map((command) => ({
1692
+ name: command.invocationName,
1693
+ description: command.description,
1694
+ source: "extension",
1695
+ sourceInfo: command.sourceInfo,
1696
+ }));
1697
+ const templates = this.promptTemplates.map((template) => ({
1698
+ name: template.name,
1699
+ description: template.description,
1700
+ source: "prompt",
1701
+ sourceInfo: template.sourceInfo,
1702
+ }));
1703
+ const skills = this._resourceLoader.getSkills().skills.map((skill) => ({
1704
+ name: `skill:${skill.name}`,
1705
+ description: skill.description,
1706
+ source: "skill",
1707
+ sourceInfo: skill.sourceInfo,
1708
+ }));
1709
+ return [...extensionCommands, ...templates, ...skills];
1710
+ };
1711
+ runner.bindCore({
1712
+ sendMessage: (message, options) => {
1713
+ this.sendCustomMessage(message, options).catch((err) => {
1714
+ runner.emitError({
1715
+ extensionPath: "<runtime>",
1716
+ event: "send_message",
1717
+ error: err instanceof Error ? err.message : String(err),
1718
+ });
1719
+ });
1720
+ },
1721
+ sendUserMessage: (content, options) => {
1722
+ this.sendUserMessage(content, options).catch((err) => {
1723
+ runner.emitError({
1724
+ extensionPath: "<runtime>",
1725
+ event: "send_user_message",
1726
+ error: err instanceof Error ? err.message : String(err),
1727
+ });
1728
+ });
1729
+ },
1730
+ appendEntry: (customType, data) => {
1731
+ this.sessionManager.appendCustomEntry(customType, data);
1732
+ },
1733
+ setSessionName: (name) => {
1734
+ this.setSessionName(name);
1735
+ },
1736
+ getSessionName: () => {
1737
+ return this.sessionManager.getSessionName();
1738
+ },
1739
+ setLabel: (entryId, label) => {
1740
+ this.sessionManager.appendLabelChange(entryId, label);
1741
+ },
1742
+ getActiveTools: () => this.getActiveToolNames(),
1743
+ getAllTools: () => this.getAllTools(),
1744
+ setActiveTools: (toolNames) => this.setActiveToolsByName(toolNames),
1745
+ refreshTools: () => this._refreshToolRegistry(),
1746
+ getCommands,
1747
+ setModel: async (model) => {
1748
+ if (!this.modelRegistry.hasConfiguredAuth(model))
1749
+ return false;
1750
+ await this.setModel(model);
1751
+ return true;
1752
+ },
1753
+ getThinkingLevel: () => this.thinkingLevel,
1754
+ setThinkingLevel: (level) => this.setThinkingLevel(level),
1755
+ }, {
1756
+ getModel: () => this.model,
1757
+ isIdle: () => !this.isStreaming,
1758
+ getSignal: () => this.agent.signal,
1759
+ abort: () => {
1760
+ if (this._extensionAbortHandler) {
1761
+ this._extensionAbortHandler();
1762
+ return;
1763
+ }
1764
+ void this.abort();
1765
+ },
1766
+ hasPendingMessages: () => this.pendingMessageCount > 0,
1767
+ shutdown: () => {
1768
+ this._extensionShutdownHandler?.();
1769
+ },
1770
+ getContextUsage: () => this.getContextUsage(),
1771
+ compact: (options) => {
1772
+ void (async () => {
1773
+ try {
1774
+ const result = await this.compact(options?.customInstructions);
1775
+ options?.onComplete?.(result);
1776
+ }
1777
+ catch (error) {
1778
+ const err = error instanceof Error ? error : new Error(String(error));
1779
+ options?.onError?.(err);
1780
+ }
1781
+ })();
1782
+ },
1783
+ getSystemPrompt: () => this.systemPrompt,
1784
+ }, {
1785
+ registerProvider: (name, config) => {
1786
+ this._modelRegistry.registerProvider(name, config);
1787
+ this._refreshCurrentModelFromRegistry();
1788
+ },
1789
+ unregisterProvider: (name) => {
1790
+ this._modelRegistry.unregisterProvider(name);
1791
+ this._refreshCurrentModelFromRegistry();
1792
+ },
1793
+ });
1794
+ }
1795
+ _refreshToolRegistry(options) {
1796
+ const previousRegistryNames = new Set(this._toolRegistry.keys());
1797
+ const previousActiveToolNames = this.getActiveToolNames();
1798
+ const allowedToolNames = this._allowedToolNames;
1799
+ const isAllowedTool = (name) => !allowedToolNames || allowedToolNames.has(name);
1800
+ const registeredTools = this._extensionRunner.getAllRegisteredTools();
1801
+ const allCustomTools = [
1802
+ ...registeredTools,
1803
+ ...this._customTools.map((definition) => ({
1804
+ definition,
1805
+ sourceInfo: createSyntheticSourceInfo(`<sdk:${definition.name}>`, { source: "sdk" }),
1806
+ })),
1807
+ ].filter((tool) => isAllowedTool(tool.definition.name));
1808
+ const definitionRegistry = new Map(Array.from(this._baseToolDefinitions.entries())
1809
+ .filter(([name]) => isAllowedTool(name))
1810
+ .map(([name, definition]) => [
1811
+ name,
1812
+ {
1813
+ definition,
1814
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${name}>`, { source: "builtin" }),
1815
+ },
1816
+ ]));
1817
+ for (const tool of allCustomTools) {
1818
+ definitionRegistry.set(tool.definition.name, {
1819
+ definition: tool.definition,
1820
+ sourceInfo: tool.sourceInfo,
1821
+ });
1822
+ }
1823
+ this._toolDefinitions = definitionRegistry;
1824
+ this._toolPromptSnippets = new Map(Array.from(definitionRegistry.values())
1825
+ .map(({ definition }) => {
1826
+ const snippet = this._normalizePromptSnippet(definition.promptSnippet);
1827
+ return snippet ? [definition.name, snippet] : undefined;
1828
+ })
1829
+ .filter((entry) => entry !== undefined));
1830
+ this._toolPromptGuidelines = new Map(Array.from(definitionRegistry.values())
1831
+ .map(({ definition }) => {
1832
+ const guidelines = this._normalizePromptGuidelines(definition.promptGuidelines);
1833
+ return guidelines.length > 0 ? [definition.name, guidelines] : undefined;
1834
+ })
1835
+ .filter((entry) => entry !== undefined));
1836
+ const runner = this._extensionRunner;
1837
+ const wrappedExtensionTools = wrapRegisteredTools(allCustomTools, runner);
1838
+ const wrappedBuiltInTools = wrapRegisteredTools(Array.from(this._baseToolDefinitions.values())
1839
+ .filter((definition) => isAllowedTool(definition.name))
1840
+ .map((definition) => ({
1841
+ definition,
1842
+ sourceInfo: createSyntheticSourceInfo(`<builtin:${definition.name}>`, { source: "builtin" }),
1843
+ })), runner);
1844
+ const toolRegistry = new Map(wrappedBuiltInTools.map((tool) => [tool.name, tool]));
1845
+ for (const tool of wrappedExtensionTools) {
1846
+ toolRegistry.set(tool.name, tool);
1847
+ }
1848
+ this._toolRegistry = toolRegistry;
1849
+ const nextActiveToolNames = (options?.activeToolNames ? [...options.activeToolNames] : [...previousActiveToolNames]).filter((name) => isAllowedTool(name));
1850
+ if (allowedToolNames) {
1851
+ for (const toolName of this._toolRegistry.keys()) {
1852
+ if (allowedToolNames.has(toolName)) {
1853
+ nextActiveToolNames.push(toolName);
1854
+ }
1855
+ }
1856
+ }
1857
+ else if (options?.includeAllExtensionTools) {
1858
+ for (const tool of wrappedExtensionTools) {
1859
+ nextActiveToolNames.push(tool.name);
1860
+ }
1861
+ }
1862
+ else if (!options?.activeToolNames) {
1863
+ for (const toolName of this._toolRegistry.keys()) {
1864
+ if (!previousRegistryNames.has(toolName)) {
1865
+ nextActiveToolNames.push(toolName);
1866
+ }
1867
+ }
1868
+ }
1869
+ this.setActiveToolsByName([...new Set(nextActiveToolNames)]);
1870
+ }
1871
+ _buildRuntime(options) {
1872
+ const autoResizeImages = this.settingsManager.getImageAutoResize();
1873
+ const shellCommandPrefix = this.settingsManager.getShellCommandPrefix();
1874
+ const shellPath = this.settingsManager.getShellPath();
1875
+ const baseToolDefinitions = this._baseToolsOverride
1876
+ ? Object.fromEntries(Object.entries(this._baseToolsOverride).map(([name, tool]) => [
1877
+ name,
1878
+ createToolDefinitionFromAgentTool(tool),
1879
+ ]))
1880
+ : createAllToolDefinitions(this._cwd, {
1881
+ read: { autoResizeImages },
1882
+ bash: { commandPrefix: shellCommandPrefix, shellPath },
1883
+ });
1884
+ this._baseToolDefinitions = new Map(Object.entries(baseToolDefinitions).map(([name, tool]) => [name, tool]));
1885
+ const extensionsResult = this._resourceLoader.getExtensions();
1886
+ if (options.flagValues) {
1887
+ for (const [name, value] of options.flagValues) {
1888
+ extensionsResult.runtime.flagValues.set(name, value);
1889
+ }
1890
+ }
1891
+ this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry);
1892
+ if (this._extensionRunnerRef) {
1893
+ this._extensionRunnerRef.current = this._extensionRunner;
1894
+ }
1895
+ this._bindExtensionCore(this._extensionRunner);
1896
+ this._applyExtensionBindings(this._extensionRunner);
1897
+ const defaultActiveToolNames = this._baseToolsOverride
1898
+ ? Object.keys(this._baseToolsOverride)
1899
+ : ["read", "bash", "edit", "write"];
1900
+ const baseActiveToolNames = options.activeToolNames ?? defaultActiveToolNames;
1901
+ this._refreshToolRegistry({
1902
+ activeToolNames: baseActiveToolNames,
1903
+ includeAllExtensionTools: options.includeAllExtensionTools,
1904
+ });
1905
+ }
1906
+ async reload() {
1907
+ const previousFlagValues = this._extensionRunner.getFlagValues();
1908
+ await emitSessionShutdownEvent(this._extensionRunner, { type: "session_shutdown", reason: "reload" });
1909
+ await this.settingsManager.reload();
1910
+ resetApiProviders();
1911
+ await this._resourceLoader.reload();
1912
+ this._buildRuntime({
1913
+ activeToolNames: this.getActiveToolNames(),
1914
+ flagValues: previousFlagValues,
1915
+ includeAllExtensionTools: true,
1916
+ });
1917
+ const hasBindings = this._extensionUIContext ||
1918
+ this._extensionCommandContextActions ||
1919
+ this._extensionShutdownHandler ||
1920
+ this._extensionErrorListener;
1921
+ if (hasBindings) {
1922
+ await this._extensionRunner.emit({ type: "session_start", reason: "reload" });
1923
+ await this.extendResourcesFromExtensions("reload");
1924
+ }
1925
+ }
1926
+ // =========================================================================
1927
+ // Auto-Retry
1928
+ // =========================================================================
1929
+ /**
1930
+ * Check if an error is retryable (overloaded, rate limit, server errors).
1931
+ * Context overflow errors are NOT retryable (handled by compaction instead).
1932
+ */
1933
+ _isRetryableError(message) {
1934
+ if (message.stopReason !== "error" || !message.errorMessage)
1935
+ return false;
1936
+ // Context overflow is handled by compaction, not retry
1937
+ const contextWindow = this.model?.contextWindow ?? 0;
1938
+ if (isContextOverflow(message, contextWindow))
1939
+ return false;
1940
+ const err = message.errorMessage;
1941
+ // 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
1942
+ 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);
1943
+ }
1944
+ /**
1945
+ * Prepare a retryable error for continuation with exponential backoff.
1946
+ * @returns true if the caller should continue the agent, false otherwise
1947
+ */
1948
+ async _prepareRetry(message) {
1949
+ const settings = this.settingsManager.getRetrySettings();
1950
+ if (!settings.enabled) {
1951
+ return false;
1952
+ }
1953
+ this._retryAttempt++;
1954
+ if (this._retryAttempt > settings.maxRetries) {
1955
+ // Preserve the completed attempt count so post-run handling can emit the final failure.
1956
+ this._retryAttempt--;
1957
+ return false;
1958
+ }
1959
+ const delayMs = settings.baseDelayMs * 2 ** (this._retryAttempt - 1);
1960
+ this._emit({
1961
+ type: "auto_retry_start",
1962
+ attempt: this._retryAttempt,
1963
+ maxAttempts: settings.maxRetries,
1964
+ delayMs,
1965
+ errorMessage: message.errorMessage || "Unknown error",
1966
+ });
1967
+ // Remove error message from agent state (keep in session for history)
1968
+ const messages = this.agent.state.messages;
1969
+ if (messages.length > 0 && messages[messages.length - 1].role === "assistant") {
1970
+ this.agent.state.messages = messages.slice(0, -1);
1971
+ }
1972
+ // Wait with exponential backoff (abortable)
1973
+ this._retryAbortController = new AbortController();
1974
+ try {
1975
+ await sleep(delayMs, this._retryAbortController.signal);
1976
+ }
1977
+ catch {
1978
+ // Aborted during sleep - emit end event so UI can clean up
1979
+ const attempt = this._retryAttempt;
1980
+ this._retryAttempt = 0;
1981
+ this._emit({
1982
+ type: "auto_retry_end",
1983
+ success: false,
1984
+ attempt,
1985
+ finalError: "Retry cancelled",
1986
+ });
1987
+ return false;
1988
+ }
1989
+ finally {
1990
+ this._retryAbortController = undefined;
1991
+ }
1992
+ return true;
1993
+ }
1994
+ /**
1995
+ * Cancel in-progress retry.
1996
+ */
1997
+ abortRetry() {
1998
+ this._retryAbortController?.abort();
1999
+ }
2000
+ /** Whether auto-retry is currently in progress */
2001
+ get isRetrying() {
2002
+ return this._retryAbortController !== undefined;
2003
+ }
2004
+ /** Whether auto-retry is enabled */
2005
+ get autoRetryEnabled() {
2006
+ return this.settingsManager.getRetryEnabled();
2007
+ }
2008
+ /**
2009
+ * Toggle auto-retry setting.
2010
+ */
2011
+ setAutoRetryEnabled(enabled) {
2012
+ this.settingsManager.setRetryEnabled(enabled);
2013
+ }
2014
+ // =========================================================================
2015
+ // Bash Execution
2016
+ // =========================================================================
2017
+ /**
2018
+ * Execute a bash command.
2019
+ * Adds result to agent context and session.
2020
+ * @param command The bash command to execute
2021
+ * @param onChunk Optional streaming callback for output
2022
+ * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
2023
+ * @param options.operations Custom BashOperations for remote execution
2024
+ */
2025
+ async executeBash(command, onChunk, options) {
2026
+ this._bashAbortController = new AbortController();
2027
+ // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
2028
+ const prefix = this.settingsManager.getShellCommandPrefix();
2029
+ const shellPath = this.settingsManager.getShellPath();
2030
+ const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
2031
+ try {
2032
+ const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
2033
+ onChunk,
2034
+ signal: this._bashAbortController.signal,
2035
+ });
2036
+ this.recordBashResult(command, result, options);
2037
+ return result;
2038
+ }
2039
+ finally {
2040
+ this._bashAbortController = undefined;
2041
+ }
2042
+ }
2043
+ /**
2044
+ * Record a bash execution result in session history.
2045
+ * Used by executeBash and by extensions that handle bash execution themselves.
2046
+ */
2047
+ recordBashResult(command, result, options) {
2048
+ const bashMessage = {
2049
+ role: "bashExecution",
2050
+ command,
2051
+ output: result.output,
2052
+ exitCode: result.exitCode,
2053
+ cancelled: result.cancelled,
2054
+ truncated: result.truncated,
2055
+ fullOutputPath: result.fullOutputPath,
2056
+ timestamp: Date.now(),
2057
+ excludeFromContext: options?.excludeFromContext,
2058
+ };
2059
+ // If agent is streaming, defer adding to avoid breaking tool_use/tool_result ordering
2060
+ if (this.isStreaming) {
2061
+ // Queue for later - will be flushed on agent_end
2062
+ this._pendingBashMessages.push(bashMessage);
2063
+ }
2064
+ else {
2065
+ // Add to agent state immediately
2066
+ this.agent.state.messages.push(bashMessage);
2067
+ // Save to session
2068
+ this.sessionManager.appendMessage(bashMessage);
2069
+ }
2070
+ }
2071
+ /**
2072
+ * Cancel running bash command.
2073
+ */
2074
+ abortBash() {
2075
+ this._bashAbortController?.abort();
2076
+ }
2077
+ /** Whether a bash command is currently running */
2078
+ get isBashRunning() {
2079
+ return this._bashAbortController !== undefined;
2080
+ }
2081
+ /** Whether there are pending bash messages waiting to be flushed */
2082
+ get hasPendingBashMessages() {
2083
+ return this._pendingBashMessages.length > 0;
2084
+ }
2085
+ /**
2086
+ * Flush pending bash messages to agent state and session.
2087
+ * Called after agent turn completes to maintain proper message ordering.
2088
+ */
2089
+ _flushPendingBashMessages() {
2090
+ if (this._pendingBashMessages.length === 0)
2091
+ return;
2092
+ for (const bashMessage of this._pendingBashMessages) {
2093
+ // Add to agent state
2094
+ this.agent.state.messages.push(bashMessage);
2095
+ // Save to session
2096
+ this.sessionManager.appendMessage(bashMessage);
2097
+ }
2098
+ this._pendingBashMessages = [];
2099
+ }
2100
+ // =========================================================================
2101
+ // Session Management
2102
+ // =========================================================================
2103
+ /**
2104
+ * Set a display name for the current session.
2105
+ */
2106
+ setSessionName(name) {
2107
+ this.sessionManager.appendSessionInfo(name);
2108
+ this._emit({ type: "session_info_changed", name: this.sessionManager.getSessionName() });
2109
+ }
2110
+ // =========================================================================
2111
+ // Tree Navigation
2112
+ // =========================================================================
2113
+ /**
2114
+ * Navigate to a different node in the session tree.
2115
+ * Unlike fork() which creates a new session file, this stays in the same file.
2116
+ *
2117
+ * @param targetId The entry ID to navigate to
2118
+ * @param options.summarize Whether user wants to summarize abandoned branch
2119
+ * @param options.customInstructions Custom instructions for summarizer
2120
+ * @param options.replaceInstructions If true, customInstructions replaces the default prompt
2121
+ * @param options.label Label to attach to the branch summary entry
2122
+ * @returns Result with editorText (if user message) and cancelled status
2123
+ */
2124
+ async navigateTree(targetId, options = {}) {
2125
+ const oldLeafId = this.sessionManager.getLeafId();
2126
+ // No-op if already at target
2127
+ if (targetId === oldLeafId) {
2128
+ return { cancelled: false };
2129
+ }
2130
+ // Model required for summarization
2131
+ if (options.summarize && !this.model) {
2132
+ throw new Error("No model available for summarization");
2133
+ }
2134
+ const targetEntry = this.sessionManager.getEntry(targetId);
2135
+ if (!targetEntry) {
2136
+ throw new Error(`Entry ${targetId} not found`);
2137
+ }
2138
+ // Collect entries to summarize (from old leaf to common ancestor)
2139
+ const { entries: entriesToSummarize, commonAncestorId } = collectEntriesForBranchSummary(this.sessionManager, oldLeafId, targetId);
2140
+ // Prepare event data - mutable so extensions can override
2141
+ let customInstructions = options.customInstructions;
2142
+ let replaceInstructions = options.replaceInstructions;
2143
+ let label = options.label;
2144
+ const preparation = {
2145
+ targetId,
2146
+ oldLeafId,
2147
+ commonAncestorId,
2148
+ entriesToSummarize,
2149
+ userWantsSummary: options.summarize ?? false,
2150
+ customInstructions,
2151
+ replaceInstructions,
2152
+ label,
2153
+ };
2154
+ // Set up abort controller for summarization
2155
+ this._branchSummaryAbortController = new AbortController();
2156
+ try {
2157
+ let extensionSummary;
2158
+ let fromExtension = false;
2159
+ // Emit session_before_tree event
2160
+ if (this._extensionRunner.hasHandlers("session_before_tree")) {
2161
+ const result = (await this._extensionRunner.emit({
2162
+ type: "session_before_tree",
2163
+ preparation,
2164
+ signal: this._branchSummaryAbortController.signal,
2165
+ }));
2166
+ if (result?.cancel) {
2167
+ return { cancelled: true };
2168
+ }
2169
+ if (result?.summary && options.summarize) {
2170
+ extensionSummary = result.summary;
2171
+ fromExtension = true;
2172
+ }
2173
+ // Allow extensions to override instructions and label
2174
+ if (result?.customInstructions !== undefined) {
2175
+ customInstructions = result.customInstructions;
2176
+ }
2177
+ if (result?.replaceInstructions !== undefined) {
2178
+ replaceInstructions = result.replaceInstructions;
2179
+ }
2180
+ if (result?.label !== undefined) {
2181
+ label = result.label;
2182
+ }
2183
+ }
2184
+ // Run default summarizer if needed
2185
+ let summaryText;
2186
+ let summaryDetails;
2187
+ if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2188
+ const model = this.model;
2189
+ const { apiKey, headers } = await this._getRequiredRequestAuth(model);
2190
+ const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2191
+ const result = await generateBranchSummary(entriesToSummarize, {
2192
+ model,
2193
+ apiKey,
2194
+ headers,
2195
+ signal: this._branchSummaryAbortController.signal,
2196
+ customInstructions,
2197
+ replaceInstructions,
2198
+ reserveTokens: branchSummarySettings.reserveTokens,
2199
+ });
2200
+ if (result.aborted) {
2201
+ return { cancelled: true, aborted: true };
2202
+ }
2203
+ if (result.error) {
2204
+ throw new Error(result.error);
2205
+ }
2206
+ summaryText = result.summary;
2207
+ summaryDetails = {
2208
+ readFiles: result.readFiles || [],
2209
+ modifiedFiles: result.modifiedFiles || [],
2210
+ };
2211
+ }
2212
+ else if (extensionSummary) {
2213
+ summaryText = extensionSummary.summary;
2214
+ summaryDetails = extensionSummary.details;
2215
+ }
2216
+ // Determine the new leaf position based on target type
2217
+ let newLeafId;
2218
+ let editorText;
2219
+ if (targetEntry.type === "message" && targetEntry.message.role === "user") {
2220
+ // User message: leaf = parent (null if root), text goes to editor
2221
+ newLeafId = targetEntry.parentId;
2222
+ editorText = this._extractUserMessageText(targetEntry.message.content);
2223
+ }
2224
+ else if (targetEntry.type === "custom_message") {
2225
+ // Custom message: leaf = parent (null if root), text goes to editor
2226
+ newLeafId = targetEntry.parentId;
2227
+ editorText =
2228
+ typeof targetEntry.content === "string"
2229
+ ? targetEntry.content
2230
+ : targetEntry.content
2231
+ .filter((c) => c.type === "text")
2232
+ .map((c) => c.text)
2233
+ .join("");
2234
+ }
2235
+ else {
2236
+ // Non-user message: leaf = selected node
2237
+ newLeafId = targetId;
2238
+ }
2239
+ // Switch leaf (with or without summary)
2240
+ // Summary is attached at the navigation target position (newLeafId), not the old branch
2241
+ let summaryEntry;
2242
+ if (summaryText) {
2243
+ // Create summary at target position (can be null for root)
2244
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
2245
+ summaryEntry = this.sessionManager.getEntry(summaryId);
2246
+ // Attach label to the summary entry
2247
+ if (label) {
2248
+ this.sessionManager.appendLabelChange(summaryId, label);
2249
+ }
2250
+ }
2251
+ else if (newLeafId === null) {
2252
+ // No summary, navigating to root - reset leaf
2253
+ this.sessionManager.resetLeaf();
2254
+ }
2255
+ else {
2256
+ // No summary, navigating to non-root
2257
+ this.sessionManager.branch(newLeafId);
2258
+ }
2259
+ // Attach label to target entry when not summarizing (no summary entry to label)
2260
+ if (label && !summaryText) {
2261
+ this.sessionManager.appendLabelChange(targetId, label);
2262
+ }
2263
+ // Update agent state
2264
+ const sessionContext = this.sessionManager.buildSessionContext();
2265
+ this.agent.state.messages = sessionContext.messages;
2266
+ // Emit session_tree event
2267
+ await this._extensionRunner.emit({
2268
+ type: "session_tree",
2269
+ newLeafId: this.sessionManager.getLeafId(),
2270
+ oldLeafId,
2271
+ summaryEntry,
2272
+ fromExtension: summaryText ? fromExtension : undefined,
2273
+ });
2274
+ // Emit to custom tools
2275
+ return { editorText, cancelled: false, summaryEntry };
2276
+ }
2277
+ finally {
2278
+ this._branchSummaryAbortController = undefined;
2279
+ }
2280
+ }
2281
+ /**
2282
+ * Get all user messages from session for fork selector.
2283
+ */
2284
+ getUserMessagesForForking() {
2285
+ const entries = this.sessionManager.getEntries();
2286
+ const result = [];
2287
+ for (const entry of entries) {
2288
+ if (entry.type !== "message")
2289
+ continue;
2290
+ if (entry.message.role !== "user")
2291
+ continue;
2292
+ const text = this._extractUserMessageText(entry.message.content);
2293
+ if (text) {
2294
+ result.push({ entryId: entry.id, text });
2295
+ }
2296
+ }
2297
+ return result;
2298
+ }
2299
+ _extractUserMessageText(content) {
2300
+ if (typeof content === "string")
2301
+ return content;
2302
+ if (Array.isArray(content)) {
2303
+ return content
2304
+ .filter((c) => c.type === "text")
2305
+ .map((c) => c.text)
2306
+ .join("");
2307
+ }
2308
+ return "";
2309
+ }
2310
+ /**
2311
+ * Get session statistics.
2312
+ */
2313
+ getSessionStats() {
2314
+ const state = this.state;
2315
+ const userMessages = state.messages.filter((m) => m.role === "user").length;
2316
+ const assistantMessages = state.messages.filter((m) => m.role === "assistant").length;
2317
+ const toolResults = state.messages.filter((m) => m.role === "toolResult").length;
2318
+ let toolCalls = 0;
2319
+ let totalInput = 0;
2320
+ let totalOutput = 0;
2321
+ let totalCacheRead = 0;
2322
+ let totalCacheWrite = 0;
2323
+ let totalCost = 0;
2324
+ for (const message of state.messages) {
2325
+ if (message.role === "assistant") {
2326
+ const assistantMsg = message;
2327
+ toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
2328
+ totalInput += assistantMsg.usage.input;
2329
+ totalOutput += assistantMsg.usage.output;
2330
+ totalCacheRead += assistantMsg.usage.cacheRead;
2331
+ totalCacheWrite += assistantMsg.usage.cacheWrite;
2332
+ totalCost += assistantMsg.usage.cost.total;
2333
+ }
2334
+ }
2335
+ return {
2336
+ sessionFile: this.sessionFile,
2337
+ sessionId: this.sessionId,
2338
+ userMessages,
2339
+ assistantMessages,
2340
+ toolCalls,
2341
+ toolResults,
2342
+ totalMessages: state.messages.length,
2343
+ tokens: {
2344
+ input: totalInput,
2345
+ output: totalOutput,
2346
+ cacheRead: totalCacheRead,
2347
+ cacheWrite: totalCacheWrite,
2348
+ total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
2349
+ },
2350
+ cost: totalCost,
2351
+ contextUsage: this.getContextUsage(),
2352
+ };
2353
+ }
2354
+ getContextUsage() {
2355
+ const model = this.model;
2356
+ if (!model)
2357
+ return undefined;
2358
+ const contextWindow = model.contextWindow ?? 0;
2359
+ if (contextWindow <= 0)
2360
+ return undefined;
2361
+ // After compaction, the last assistant usage reflects pre-compaction context size.
2362
+ // We can only trust usage from an assistant that responded after the latest compaction.
2363
+ // If no such assistant exists, context token count is unknown until the next LLM response.
2364
+ const branchEntries = this.sessionManager.getBranch();
2365
+ const latestCompaction = getLatestCompactionEntry(branchEntries);
2366
+ if (latestCompaction) {
2367
+ // Check if there's a valid assistant usage after the compaction boundary
2368
+ const compactionIndex = branchEntries.lastIndexOf(latestCompaction);
2369
+ let hasPostCompactionUsage = false;
2370
+ for (let i = branchEntries.length - 1; i > compactionIndex; i--) {
2371
+ const entry = branchEntries[i];
2372
+ if (entry.type === "message" && entry.message.role === "assistant") {
2373
+ const assistant = entry.message;
2374
+ if (assistant.stopReason !== "aborted" && assistant.stopReason !== "error") {
2375
+ const contextTokens = calculateContextTokens(assistant.usage);
2376
+ if (contextTokens > 0) {
2377
+ hasPostCompactionUsage = true;
2378
+ }
2379
+ break;
2380
+ }
2381
+ }
2382
+ }
2383
+ if (!hasPostCompactionUsage) {
2384
+ return { tokens: null, contextWindow, percent: null };
2385
+ }
2386
+ }
2387
+ const estimate = estimateContextTokens(this.messages);
2388
+ const percent = (estimate.tokens / contextWindow) * 100;
2389
+ return {
2390
+ tokens: estimate.tokens,
2391
+ contextWindow,
2392
+ percent,
2393
+ };
2394
+ }
2395
+ /**
2396
+ * Export session to HTML.
2397
+ * @param outputPath Optional output path (defaults to session directory)
2398
+ * @returns Path to exported file
2399
+ */
2400
+ async exportToHtml(outputPath) {
2401
+ const themeName = this.settingsManager.getTheme();
2402
+ // Create tool renderer if we have an extension runner (for custom tool HTML rendering)
2403
+ const toolRenderer = createToolHtmlRenderer({
2404
+ getToolDefinition: (name) => this.getToolDefinition(name),
2405
+ theme,
2406
+ cwd: this.sessionManager.getCwd(),
2407
+ });
2408
+ return await exportSessionToHtml(this.sessionManager, this.state, {
2409
+ outputPath,
2410
+ themeName,
2411
+ toolRenderer,
2412
+ });
2413
+ }
2414
+ /**
2415
+ * Export the current session branch to a JSONL file.
2416
+ * Writes the session header followed by all entries on the current branch path.
2417
+ * @param outputPath Target file path. If omitted, generates a timestamped file in cwd.
2418
+ * @returns The resolved output file path.
2419
+ */
2420
+ exportToJsonl(outputPath) {
2421
+ const filePath = resolvePath(outputPath ?? `session-${new Date().toISOString().replace(/[:.]/g, "-")}.jsonl`, process.cwd());
2422
+ const dir = dirname(filePath);
2423
+ if (!existsSync(dir)) {
2424
+ mkdirSync(dir, { recursive: true });
2425
+ }
2426
+ const header = {
2427
+ type: "session",
2428
+ version: CURRENT_SESSION_VERSION,
2429
+ id: this.sessionManager.getSessionId(),
2430
+ timestamp: new Date().toISOString(),
2431
+ cwd: this.sessionManager.getCwd(),
2432
+ };
2433
+ const branchEntries = this.sessionManager.getBranch();
2434
+ const lines = [JSON.stringify(header)];
2435
+ // Re-chain parentIds to form a linear sequence
2436
+ let prevId = null;
2437
+ for (const entry of branchEntries) {
2438
+ const linear = { ...entry, parentId: prevId };
2439
+ lines.push(JSON.stringify(linear));
2440
+ prevId = entry.id;
2441
+ }
2442
+ writeFileSync(filePath, `${lines.join("\n")}\n`);
2443
+ return filePath;
2444
+ }
2445
+ // =========================================================================
2446
+ // Utilities
2447
+ // =========================================================================
2448
+ /**
2449
+ * Get text content of last assistant message.
2450
+ * Useful for /copy command.
2451
+ * @returns Text content, or undefined if no assistant message exists
2452
+ */
2453
+ getLastAssistantText() {
2454
+ const lastAssistant = this.messages
2455
+ .slice()
2456
+ .reverse()
2457
+ .find((m) => {
2458
+ if (m.role !== "assistant")
2459
+ return false;
2460
+ const msg = m;
2461
+ // Skip aborted messages with no content
2462
+ if (msg.stopReason === "aborted" && msg.content.length === 0)
2463
+ return false;
2464
+ return true;
2465
+ });
2466
+ if (!lastAssistant)
2467
+ return undefined;
2468
+ let text = "";
2469
+ for (const content of lastAssistant.content) {
2470
+ if (content.type === "text") {
2471
+ text += content.text;
2472
+ }
2473
+ }
2474
+ return text.trim() || undefined;
2475
+ }
2476
+ // =========================================================================
2477
+ // Extension System
2478
+ // =========================================================================
2479
+ createReplacedSessionContext() {
2480
+ const context = Object.defineProperties({}, Object.getOwnPropertyDescriptors(this._extensionRunner.createCommandContext()));
2481
+ context.sendMessage = (message, options) => this.sendCustomMessage(message, options);
2482
+ context.sendUserMessage = (content, options) => this.sendUserMessage(content, options);
2483
+ return context;
2484
+ }
2485
+ /**
2486
+ * Check if extensions have handlers for a specific event type.
2487
+ */
2488
+ hasExtensionHandlers(eventType) {
2489
+ return this._extensionRunner.hasHandlers(eventType);
2490
+ }
2491
+ /**
2492
+ * Get the extension runner (for setting UI context and error handlers).
2493
+ */
2494
+ get extensionRunner() {
2495
+ return this._extensionRunner;
2496
+ }
2497
+ }
2498
+ //# sourceMappingURL=agent-session.js.map