@phi-code-admin/phi-code 0.56.3

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