@hyperspaceng/neural-coding-agent 0.61.2 → 0.61.4

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