@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,3710 @@
1
+ /**
2
+ * Interactive mode for the coding agent.
3
+ * Handles TUI rendering and user interaction, delegating business logic to AgentSession.
4
+ */
5
+ import * as crypto from "node:crypto";
6
+ import * as fs from "node:fs";
7
+ import * as os from "node:os";
8
+ import * as path from "node:path";
9
+ import { CombinedAutocompleteProvider, Container, fuzzyFilter, Loader, Markdown, matchesKey, ProcessTerminal, Spacer, Text, TruncatedText, TUI, visibleWidth, } from "phi-code-tui";
10
+ import { spawn, spawnSync } from "child_process";
11
+ import { APP_NAME, getAuthPath, getDebugLogPath, getShareViewerUrl, getUpdateInstruction, VERSION, } from "../../config.js";
12
+ import { parseSkillBlock } from "../../core/agent-session.js";
13
+ import { FooterDataProvider } from "../../core/footer-data-provider.js";
14
+ import { KeybindingsManager } from "../../core/keybindings.js";
15
+ import { createCompactionSummaryMessage } from "../../core/messages.js";
16
+ import { resolveModelScope } from "../../core/model-resolver.js";
17
+ import { SessionManager } from "../../core/session-manager.js";
18
+ import { BUILTIN_SLASH_COMMANDS } from "../../core/slash-commands.js";
19
+ import { getChangelogPath, getNewEntries, parseChangelog } from "../../utils/changelog.js";
20
+ import { copyToClipboard } from "../../utils/clipboard.js";
21
+ import { extensionForImageMimeType, readClipboardImage } from "../../utils/clipboard-image.js";
22
+ import { ensureTool } from "../../utils/tools-manager.js";
23
+ import { ArminComponent } from "./components/armin.js";
24
+ import { AssistantMessageComponent } from "./components/assistant-message.js";
25
+ import { BashExecutionComponent } from "./components/bash-execution.js";
26
+ import { BorderedLoader } from "./components/bordered-loader.js";
27
+ import { BranchSummaryMessageComponent } from "./components/branch-summary-message.js";
28
+ import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";
29
+ import { CustomEditor } from "./components/custom-editor.js";
30
+ import { CustomMessageComponent } from "./components/custom-message.js";
31
+ import { DaxnutsComponent } from "./components/daxnuts.js";
32
+ import { DynamicBorder } from "./components/dynamic-border.js";
33
+ import { ExtensionEditorComponent } from "./components/extension-editor.js";
34
+ import { ExtensionInputComponent } from "./components/extension-input.js";
35
+ import { ExtensionSelectorComponent } from "./components/extension-selector.js";
36
+ import { FooterComponent } from "./components/footer.js";
37
+ import { appKey, appKeyHint, editorKey, keyHint, rawKeyHint } from "./components/keybinding-hints.js";
38
+ import { LoginDialogComponent } from "./components/login-dialog.js";
39
+ import { ModelSelectorComponent } from "./components/model-selector.js";
40
+ import { OAuthSelectorComponent } from "./components/oauth-selector.js";
41
+ import { ScopedModelsSelectorComponent } from "./components/scoped-models-selector.js";
42
+ import { SessionSelectorComponent } from "./components/session-selector.js";
43
+ import { SettingsSelectorComponent } from "./components/settings-selector.js";
44
+ import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
45
+ import { ToolExecutionComponent } from "./components/tool-execution.js";
46
+ import { TreeSelectorComponent } from "./components/tree-selector.js";
47
+ import { UserMessageComponent } from "./components/user-message.js";
48
+ import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
49
+ import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getThemeByName, initTheme, onThemeChange, setRegisteredThemes, setTheme, setThemeInstance, Theme, theme, } from "./theme/theme.js";
50
+ function isExpandable(obj) {
51
+ return typeof obj === "object" && obj !== null && "setExpanded" in obj && typeof obj.setExpanded === "function";
52
+ }
53
+ export class InteractiveMode {
54
+ // Convenience accessors
55
+ get agent() {
56
+ return this.session.agent;
57
+ }
58
+ get sessionManager() {
59
+ return this.session.sessionManager;
60
+ }
61
+ get settingsManager() {
62
+ return this.session.settingsManager;
63
+ }
64
+ constructor(session, options = {}) {
65
+ this.options = options;
66
+ this.isInitialized = false;
67
+ this.loadingAnimation = undefined;
68
+ this.pendingWorkingMessage = undefined;
69
+ this.defaultWorkingMessage = "Working...";
70
+ this.lastSigintTime = 0;
71
+ this.lastEscapeTime = 0;
72
+ this.changelogMarkdown = undefined;
73
+ // Status line tracking (for mutating immediately-sequential status updates)
74
+ this.lastStatusSpacer = undefined;
75
+ this.lastStatusText = undefined;
76
+ // Streaming message tracking
77
+ this.streamingComponent = undefined;
78
+ this.streamingMessage = undefined;
79
+ // Tool execution tracking: toolCallId -> component
80
+ this.pendingTools = new Map();
81
+ // Tool output expansion state
82
+ this.toolOutputExpanded = false;
83
+ // Thinking block visibility state
84
+ this.hideThinkingBlock = false;
85
+ // Skill commands: command name -> skill file path
86
+ this.skillCommands = new Map();
87
+ // Track if editor is in bash mode (text starts with !)
88
+ this.isBashMode = false;
89
+ // Track current bash execution component
90
+ this.bashComponent = undefined;
91
+ // Track pending bash components (shown in pending area, moved to chat on submit)
92
+ this.pendingBashComponents = [];
93
+ // Auto-compaction state
94
+ this.autoCompactionLoader = undefined;
95
+ // Auto-retry state
96
+ this.retryLoader = undefined;
97
+ // Messages queued while compaction is running
98
+ this.compactionQueuedMessages = [];
99
+ // Shutdown state
100
+ this.shutdownRequested = false;
101
+ // Extension UI state
102
+ this.extensionSelector = undefined;
103
+ this.extensionInput = undefined;
104
+ this.extensionEditor = undefined;
105
+ this.extensionTerminalInputUnsubscribers = new Set();
106
+ // Extension widgets (components rendered above/below the editor)
107
+ this.extensionWidgetsAbove = new Map();
108
+ this.extensionWidgetsBelow = new Map();
109
+ // Custom footer from extension (undefined = use built-in footer)
110
+ this.customFooter = undefined;
111
+ // Built-in header (logo + keybinding hints + changelog)
112
+ this.builtInHeader = undefined;
113
+ // Custom header from extension (undefined = use built-in header)
114
+ this.customHeader = undefined;
115
+ /**
116
+ * Gracefully shutdown the agent.
117
+ * Emits shutdown event to extensions, then exits.
118
+ */
119
+ this.isShuttingDown = false;
120
+ this.session = session;
121
+ this.version = VERSION;
122
+ this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor());
123
+ this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
124
+ this.headerContainer = new Container();
125
+ this.chatContainer = new Container();
126
+ this.pendingMessagesContainer = new Container();
127
+ this.statusContainer = new Container();
128
+ this.widgetContainerAbove = new Container();
129
+ this.widgetContainerBelow = new Container();
130
+ this.keybindings = KeybindingsManager.create();
131
+ const editorPaddingX = this.settingsManager.getEditorPaddingX();
132
+ const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();
133
+ this.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {
134
+ paddingX: editorPaddingX,
135
+ autocompleteMaxVisible,
136
+ });
137
+ this.editor = this.defaultEditor;
138
+ this.editorContainer = new Container();
139
+ this.editorContainer.addChild(this.editor);
140
+ this.footerDataProvider = new FooterDataProvider();
141
+ this.footer = new FooterComponent(session, this.footerDataProvider);
142
+ this.footer.setAutoCompactEnabled(session.autoCompactionEnabled);
143
+ // Load hide thinking block setting
144
+ this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
145
+ // Register themes from resource loader and initialize
146
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
147
+ initTheme(this.settingsManager.getTheme(), true);
148
+ }
149
+ setupAutocomplete(fdPath) {
150
+ // Define commands for autocomplete
151
+ const slashCommands = BUILTIN_SLASH_COMMANDS.map((command) => ({
152
+ name: command.name,
153
+ description: command.description,
154
+ }));
155
+ const modelCommand = slashCommands.find((command) => command.name === "model");
156
+ if (modelCommand) {
157
+ modelCommand.getArgumentCompletions = (prefix) => {
158
+ // Get available models (scoped or from registry)
159
+ const models = this.session.scopedModels.length > 0
160
+ ? this.session.scopedModels.map((s) => s.model)
161
+ : this.session.modelRegistry.getAvailable();
162
+ if (models.length === 0)
163
+ return null;
164
+ // Create items with provider/id format
165
+ const items = models.map((m) => ({
166
+ id: m.id,
167
+ provider: m.provider,
168
+ label: `${m.provider}/${m.id}`,
169
+ }));
170
+ // Fuzzy filter by model ID + provider (allows "opus anthropic" to match)
171
+ const filtered = fuzzyFilter(items, prefix, (item) => `${item.id} ${item.provider}`);
172
+ if (filtered.length === 0)
173
+ return null;
174
+ return filtered.map((item) => ({
175
+ value: item.label,
176
+ label: item.id,
177
+ description: item.provider,
178
+ }));
179
+ };
180
+ }
181
+ // Convert prompt templates to SlashCommand format for autocomplete
182
+ const templateCommands = this.session.promptTemplates.map((cmd) => ({
183
+ name: cmd.name,
184
+ description: cmd.description,
185
+ }));
186
+ // Convert extension commands to SlashCommand format
187
+ const builtinCommandNames = new Set(slashCommands.map((c) => c.name));
188
+ const extensionCommands = (this.session.extensionRunner?.getRegisteredCommands(builtinCommandNames) ?? []).map((cmd) => ({
189
+ name: cmd.name,
190
+ description: cmd.description ?? "(extension command)",
191
+ getArgumentCompletions: cmd.getArgumentCompletions,
192
+ }));
193
+ // Build skill commands from session.skills (if enabled)
194
+ this.skillCommands.clear();
195
+ const skillCommandList = [];
196
+ if (this.settingsManager.getEnableSkillCommands()) {
197
+ for (const skill of this.session.resourceLoader.getSkills().skills) {
198
+ const commandName = `skill:${skill.name}`;
199
+ this.skillCommands.set(commandName, skill.filePath);
200
+ skillCommandList.push({ name: commandName, description: skill.description });
201
+ }
202
+ }
203
+ // Setup autocomplete
204
+ this.autocompleteProvider = new CombinedAutocompleteProvider([...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList], process.cwd(), fdPath);
205
+ this.defaultEditor.setAutocompleteProvider(this.autocompleteProvider);
206
+ if (this.editor !== this.defaultEditor) {
207
+ this.editor.setAutocompleteProvider?.(this.autocompleteProvider);
208
+ }
209
+ }
210
+ async init() {
211
+ if (this.isInitialized)
212
+ return;
213
+ // Load changelog (only show new entries, skip for resumed sessions)
214
+ this.changelogMarkdown = this.getChangelogForDisplay();
215
+ // Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)
216
+ // Both are needed: fd for autocomplete, rg for grep tool and bash commands
217
+ const [fdPath] = await Promise.all([ensureTool("fd"), ensureTool("rg")]);
218
+ this.fdPath = fdPath;
219
+ // Add header container as first child
220
+ this.ui.addChild(this.headerContainer);
221
+ // Add header with keybindings from config (unless silenced)
222
+ if (this.options.verbose || !this.settingsManager.getQuietStartup()) {
223
+ const logo = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${this.version}`);
224
+ // Build startup instructions using keybinding hint helpers
225
+ const kb = this.keybindings;
226
+ const hint = (action, desc) => appKeyHint(kb, action, desc);
227
+ const instructions = [
228
+ hint("interrupt", "to interrupt"),
229
+ hint("clear", "to clear"),
230
+ rawKeyHint(`${appKey(kb, "clear")} twice`, "to exit"),
231
+ hint("exit", "to exit (empty)"),
232
+ hint("suspend", "to suspend"),
233
+ keyHint("deleteToLineEnd", "to delete to end"),
234
+ hint("cycleThinkingLevel", "to cycle thinking level"),
235
+ rawKeyHint(`${appKey(kb, "cycleModelForward")}/${appKey(kb, "cycleModelBackward")}`, "to cycle models"),
236
+ hint("selectModel", "to select model"),
237
+ hint("expandTools", "to expand tools"),
238
+ hint("toggleThinking", "to expand thinking"),
239
+ hint("externalEditor", "for external editor"),
240
+ rawKeyHint("/", "for commands"),
241
+ rawKeyHint("!", "to run bash"),
242
+ rawKeyHint("!!", "to run bash (no context)"),
243
+ hint("followUp", "to queue follow-up"),
244
+ hint("dequeue", "to edit all queued messages"),
245
+ hint("pasteImage", "to paste image"),
246
+ rawKeyHint("drop files", "to attach"),
247
+ ].join("\n");
248
+ this.builtInHeader = new Text(`${logo}\n${instructions}`, 1, 0);
249
+ // Setup UI layout
250
+ this.headerContainer.addChild(new Spacer(1));
251
+ this.headerContainer.addChild(this.builtInHeader);
252
+ this.headerContainer.addChild(new Spacer(1));
253
+ // Add changelog if provided
254
+ if (this.changelogMarkdown) {
255
+ this.headerContainer.addChild(new DynamicBorder());
256
+ if (this.settingsManager.getCollapseChangelog()) {
257
+ const versionMatch = this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/);
258
+ const latestVersion = versionMatch ? versionMatch[1] : this.version;
259
+ const condensedText = `Updated to v${latestVersion}. Use ${theme.bold("/changelog")} to view full changelog.`;
260
+ this.headerContainer.addChild(new Text(condensedText, 1, 0));
261
+ }
262
+ else {
263
+ this.headerContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
264
+ this.headerContainer.addChild(new Spacer(1));
265
+ this.headerContainer.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()));
266
+ this.headerContainer.addChild(new Spacer(1));
267
+ }
268
+ this.headerContainer.addChild(new DynamicBorder());
269
+ }
270
+ }
271
+ else {
272
+ // Minimal header when silenced
273
+ this.builtInHeader = new Text("", 0, 0);
274
+ this.headerContainer.addChild(this.builtInHeader);
275
+ if (this.changelogMarkdown) {
276
+ // Still show changelog notification even in silent mode
277
+ this.headerContainer.addChild(new Spacer(1));
278
+ const versionMatch = this.changelogMarkdown.match(/##\s+\[?(\d+\.\d+\.\d+)\]?/);
279
+ const latestVersion = versionMatch ? versionMatch[1] : this.version;
280
+ const condensedText = `Updated to v${latestVersion}. Use ${theme.bold("/changelog")} to view full changelog.`;
281
+ this.headerContainer.addChild(new Text(condensedText, 1, 0));
282
+ }
283
+ }
284
+ this.ui.addChild(this.chatContainer);
285
+ this.ui.addChild(this.pendingMessagesContainer);
286
+ this.ui.addChild(this.statusContainer);
287
+ this.renderWidgets(); // Initialize with default spacer
288
+ this.ui.addChild(this.widgetContainerAbove);
289
+ this.ui.addChild(this.editorContainer);
290
+ this.ui.addChild(this.widgetContainerBelow);
291
+ this.ui.addChild(this.footer);
292
+ this.ui.setFocus(this.editor);
293
+ this.setupKeyHandlers();
294
+ this.setupEditorSubmitHandler();
295
+ // Initialize extensions first so resources are shown before messages
296
+ await this.initExtensions();
297
+ // Render initial messages AFTER showing loaded resources
298
+ this.renderInitialMessages();
299
+ // Start the UI
300
+ this.ui.start();
301
+ this.isInitialized = true;
302
+ // Set terminal title
303
+ this.updateTerminalTitle();
304
+ // Subscribe to agent events
305
+ this.subscribeToAgent();
306
+ // Set up theme file watcher
307
+ onThemeChange(() => {
308
+ this.ui.invalidate();
309
+ this.updateEditorBorderColor();
310
+ this.ui.requestRender();
311
+ });
312
+ // Set up git branch watcher (uses provider instead of footer)
313
+ this.footerDataProvider.onBranchChange(() => {
314
+ this.ui.requestRender();
315
+ });
316
+ // Initialize available provider count for footer display
317
+ await this.updateAvailableProviderCount();
318
+ }
319
+ /**
320
+ * Update terminal title with session name and cwd.
321
+ */
322
+ updateTerminalTitle() {
323
+ const cwdBasename = path.basename(process.cwd());
324
+ const sessionName = this.sessionManager.getSessionName();
325
+ if (sessionName) {
326
+ this.ui.terminal.setTitle(`π - ${sessionName} - ${cwdBasename}`);
327
+ }
328
+ else {
329
+ this.ui.terminal.setTitle(`π - ${cwdBasename}`);
330
+ }
331
+ }
332
+ /**
333
+ * Run the interactive mode. This is the main entry point.
334
+ * Initializes the UI, shows warnings, processes initial messages, and starts the interactive loop.
335
+ */
336
+ async run() {
337
+ await this.init();
338
+ // Start version check asynchronously
339
+ this.checkForNewVersion().then((newVersion) => {
340
+ if (newVersion) {
341
+ this.showNewVersionNotification(newVersion);
342
+ }
343
+ });
344
+ // Show startup warnings
345
+ const { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages } = this.options;
346
+ if (migratedProviders && migratedProviders.length > 0) {
347
+ this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`);
348
+ }
349
+ const modelsJsonError = this.session.modelRegistry.getError();
350
+ if (modelsJsonError) {
351
+ this.showError(`models.json error: ${modelsJsonError}`);
352
+ }
353
+ if (modelFallbackMessage) {
354
+ this.showWarning(modelFallbackMessage);
355
+ }
356
+ // Process initial messages
357
+ if (initialMessage) {
358
+ try {
359
+ await this.session.prompt(initialMessage, { images: initialImages });
360
+ }
361
+ catch (error) {
362
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
363
+ this.showError(errorMessage);
364
+ }
365
+ }
366
+ if (initialMessages) {
367
+ for (const message of initialMessages) {
368
+ try {
369
+ await this.session.prompt(message);
370
+ }
371
+ catch (error) {
372
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
373
+ this.showError(errorMessage);
374
+ }
375
+ }
376
+ }
377
+ // Main interactive loop
378
+ while (true) {
379
+ const userInput = await this.getUserInput();
380
+ try {
381
+ await this.session.prompt(userInput);
382
+ }
383
+ catch (error) {
384
+ const errorMessage = error instanceof Error ? error.message : "Unknown error occurred";
385
+ this.showError(errorMessage);
386
+ }
387
+ }
388
+ }
389
+ /**
390
+ * Check npm registry for a newer version.
391
+ */
392
+ async checkForNewVersion() {
393
+ if (process.env.PI_SKIP_VERSION_CHECK || process.env.PI_OFFLINE)
394
+ return undefined;
395
+ try {
396
+ const response = await fetch("https://registry.npmjs.org/phi-code/latest", {
397
+ signal: AbortSignal.timeout(10000),
398
+ });
399
+ if (!response.ok)
400
+ return undefined;
401
+ const data = (await response.json());
402
+ const latestVersion = data.version;
403
+ if (latestVersion && latestVersion !== this.version) {
404
+ return latestVersion;
405
+ }
406
+ return undefined;
407
+ }
408
+ catch {
409
+ return undefined;
410
+ }
411
+ }
412
+ /**
413
+ * Get changelog entries to display on startup.
414
+ * Only shows new entries since last seen version, skips for resumed sessions.
415
+ */
416
+ getChangelogForDisplay() {
417
+ // Skip changelog for resumed/continued sessions (already have messages)
418
+ if (this.session.state.messages.length > 0) {
419
+ return undefined;
420
+ }
421
+ const lastVersion = this.settingsManager.getLastChangelogVersion();
422
+ const changelogPath = getChangelogPath();
423
+ const entries = parseChangelog(changelogPath);
424
+ if (!lastVersion) {
425
+ // Fresh install - just record the version, don't show changelog
426
+ this.settingsManager.setLastChangelogVersion(VERSION);
427
+ return undefined;
428
+ }
429
+ else {
430
+ const newEntries = getNewEntries(entries, lastVersion);
431
+ if (newEntries.length > 0) {
432
+ this.settingsManager.setLastChangelogVersion(VERSION);
433
+ return newEntries.map((e) => e.content).join("\n\n");
434
+ }
435
+ }
436
+ return undefined;
437
+ }
438
+ getMarkdownThemeWithSettings() {
439
+ return {
440
+ ...getMarkdownTheme(),
441
+ codeBlockIndent: this.settingsManager.getCodeBlockIndent(),
442
+ };
443
+ }
444
+ // =========================================================================
445
+ // Extension System
446
+ // =========================================================================
447
+ formatDisplayPath(p) {
448
+ const home = os.homedir();
449
+ let result = p;
450
+ // Replace home directory with ~
451
+ if (result.startsWith(home)) {
452
+ result = `~${result.slice(home.length)}`;
453
+ }
454
+ return result;
455
+ }
456
+ /**
457
+ * Get a short path relative to the package root for display.
458
+ */
459
+ getShortPath(fullPath, source) {
460
+ // For npm packages, show path relative to node_modules/pkg/
461
+ const npmMatch = fullPath.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);
462
+ if (npmMatch && source.startsWith("npm:")) {
463
+ return npmMatch[2];
464
+ }
465
+ // For git packages, show path relative to repo root
466
+ const gitMatch = fullPath.match(/git\/[^/]+\/[^/]+\/(.*)/);
467
+ if (gitMatch && source.startsWith("git:")) {
468
+ return gitMatch[1];
469
+ }
470
+ // For local/auto, just use formatDisplayPath
471
+ return this.formatDisplayPath(fullPath);
472
+ }
473
+ getDisplaySourceInfo(source, scope) {
474
+ if (source === "local") {
475
+ if (scope === "user") {
476
+ return { label: "user", color: "muted" };
477
+ }
478
+ if (scope === "project") {
479
+ return { label: "project", color: "muted" };
480
+ }
481
+ if (scope === "temporary") {
482
+ return { label: "path", scopeLabel: "temp", color: "muted" };
483
+ }
484
+ return { label: "path", color: "muted" };
485
+ }
486
+ if (source === "cli") {
487
+ return { label: "path", scopeLabel: scope === "temporary" ? "temp" : undefined, color: "muted" };
488
+ }
489
+ const scopeLabel = scope === "user" ? "user" : scope === "project" ? "project" : scope === "temporary" ? "temp" : undefined;
490
+ return { label: source, scopeLabel, color: "accent" };
491
+ }
492
+ getScopeGroup(source, scope) {
493
+ if (source === "cli" || scope === "temporary")
494
+ return "path";
495
+ if (scope === "user")
496
+ return "user";
497
+ if (scope === "project")
498
+ return "project";
499
+ return "path";
500
+ }
501
+ isPackageSource(source) {
502
+ return source.startsWith("npm:") || source.startsWith("git:");
503
+ }
504
+ buildScopeGroups(paths, metadata) {
505
+ const groups = {
506
+ user: { scope: "user", paths: [], packages: new Map() },
507
+ project: { scope: "project", paths: [], packages: new Map() },
508
+ path: { scope: "path", paths: [], packages: new Map() },
509
+ };
510
+ for (const p of paths) {
511
+ const meta = this.findMetadata(p, metadata);
512
+ const source = meta?.source ?? "local";
513
+ const scope = meta?.scope ?? "project";
514
+ const groupKey = this.getScopeGroup(source, scope);
515
+ const group = groups[groupKey];
516
+ if (this.isPackageSource(source)) {
517
+ const list = group.packages.get(source) ?? [];
518
+ list.push(p);
519
+ group.packages.set(source, list);
520
+ }
521
+ else {
522
+ group.paths.push(p);
523
+ }
524
+ }
525
+ return [groups.project, groups.user, groups.path].filter((group) => group.paths.length > 0 || group.packages.size > 0);
526
+ }
527
+ formatScopeGroups(groups, options) {
528
+ const lines = [];
529
+ for (const group of groups) {
530
+ lines.push(` ${theme.fg("accent", group.scope)}`);
531
+ const sortedPaths = [...group.paths].sort((a, b) => a.localeCompare(b));
532
+ for (const p of sortedPaths) {
533
+ lines.push(theme.fg("dim", ` ${options.formatPath(p)}`));
534
+ }
535
+ const sortedPackages = Array.from(group.packages.entries()).sort(([a], [b]) => a.localeCompare(b));
536
+ for (const [source, paths] of sortedPackages) {
537
+ lines.push(` ${theme.fg("mdLink", source)}`);
538
+ const sortedPackagePaths = [...paths].sort((a, b) => a.localeCompare(b));
539
+ for (const p of sortedPackagePaths) {
540
+ lines.push(theme.fg("dim", ` ${options.formatPackagePath(p, source)}`));
541
+ }
542
+ }
543
+ }
544
+ return lines.join("\n");
545
+ }
546
+ /**
547
+ * Find metadata for a path, checking parent directories if exact match fails.
548
+ * Package manager stores metadata for directories, but we display file paths.
549
+ */
550
+ findMetadata(p, metadata) {
551
+ // Try exact match first
552
+ const exact = metadata.get(p);
553
+ if (exact)
554
+ return exact;
555
+ // Try parent directories (package manager stores directory paths)
556
+ let current = p;
557
+ while (current.includes("/")) {
558
+ current = current.substring(0, current.lastIndexOf("/"));
559
+ const parent = metadata.get(current);
560
+ if (parent)
561
+ return parent;
562
+ }
563
+ return undefined;
564
+ }
565
+ /**
566
+ * Format a path with its source/scope info from metadata.
567
+ */
568
+ formatPathWithSource(p, metadata) {
569
+ const meta = this.findMetadata(p, metadata);
570
+ if (meta) {
571
+ const shortPath = this.getShortPath(p, meta.source);
572
+ const { label, scopeLabel } = this.getDisplaySourceInfo(meta.source, meta.scope);
573
+ const labelText = scopeLabel ? `${label} (${scopeLabel})` : label;
574
+ return `${labelText} ${shortPath}`;
575
+ }
576
+ return this.formatDisplayPath(p);
577
+ }
578
+ /**
579
+ * Format resource diagnostics with nice collision display using metadata.
580
+ */
581
+ formatDiagnostics(diagnostics, metadata) {
582
+ const lines = [];
583
+ // Group collision diagnostics by name
584
+ const collisions = new Map();
585
+ const otherDiagnostics = [];
586
+ for (const d of diagnostics) {
587
+ if (d.type === "collision" && d.collision) {
588
+ const list = collisions.get(d.collision.name) ?? [];
589
+ list.push(d);
590
+ collisions.set(d.collision.name, list);
591
+ }
592
+ else {
593
+ otherDiagnostics.push(d);
594
+ }
595
+ }
596
+ // Format collision diagnostics grouped by name
597
+ for (const [name, collisionList] of collisions) {
598
+ const first = collisionList[0]?.collision;
599
+ if (!first)
600
+ continue;
601
+ lines.push(theme.fg("warning", ` "${name}" collision:`));
602
+ // Show winner
603
+ lines.push(theme.fg("dim", ` ${theme.fg("success", "✓")} ${this.formatPathWithSource(first.winnerPath, metadata)}`));
604
+ // Show all losers
605
+ for (const d of collisionList) {
606
+ if (d.collision) {
607
+ lines.push(theme.fg("dim", ` ${theme.fg("warning", "✗")} ${this.formatPathWithSource(d.collision.loserPath, metadata)} (skipped)`));
608
+ }
609
+ }
610
+ }
611
+ // Format other diagnostics (skill name collisions, parse errors, etc.)
612
+ for (const d of otherDiagnostics) {
613
+ if (d.path) {
614
+ // Use metadata-aware formatting for paths
615
+ const sourceInfo = this.formatPathWithSource(d.path, metadata);
616
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${sourceInfo}`));
617
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`));
618
+ }
619
+ else {
620
+ lines.push(theme.fg(d.type === "error" ? "error" : "warning", ` ${d.message}`));
621
+ }
622
+ }
623
+ return lines.join("\n");
624
+ }
625
+ showLoadedResources(options) {
626
+ const showListing = options?.force || this.options.verbose || !this.settingsManager.getQuietStartup();
627
+ const showDiagnostics = showListing || options?.showDiagnosticsWhenQuiet === true;
628
+ if (!showListing && !showDiagnostics) {
629
+ return;
630
+ }
631
+ const metadata = this.session.resourceLoader.getPathMetadata();
632
+ const sectionHeader = (name, color = "mdHeading") => theme.fg(color, `[${name}]`);
633
+ const skillsResult = this.session.resourceLoader.getSkills();
634
+ const promptsResult = this.session.resourceLoader.getPrompts();
635
+ const themesResult = this.session.resourceLoader.getThemes();
636
+ if (showListing) {
637
+ const contextFiles = this.session.resourceLoader.getAgentsFiles().agentsFiles;
638
+ if (contextFiles.length > 0) {
639
+ this.chatContainer.addChild(new Spacer(1));
640
+ const contextList = contextFiles
641
+ .map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`))
642
+ .join("\n");
643
+ this.chatContainer.addChild(new Text(`${sectionHeader("Context")}\n${contextList}`, 0, 0));
644
+ this.chatContainer.addChild(new Spacer(1));
645
+ }
646
+ const skills = skillsResult.skills;
647
+ if (skills.length > 0) {
648
+ const skillPaths = skills.map((s) => s.filePath);
649
+ const groups = this.buildScopeGroups(skillPaths, metadata);
650
+ const skillList = this.formatScopeGroups(groups, {
651
+ formatPath: (p) => this.formatDisplayPath(p),
652
+ formatPackagePath: (p, source) => this.getShortPath(p, source),
653
+ });
654
+ this.chatContainer.addChild(new Text(`${sectionHeader("Skills")}\n${skillList}`, 0, 0));
655
+ this.chatContainer.addChild(new Spacer(1));
656
+ }
657
+ const templates = this.session.promptTemplates;
658
+ if (templates.length > 0) {
659
+ const templatePaths = templates.map((t) => t.filePath);
660
+ const groups = this.buildScopeGroups(templatePaths, metadata);
661
+ const templateByPath = new Map(templates.map((t) => [t.filePath, t]));
662
+ const templateList = this.formatScopeGroups(groups, {
663
+ formatPath: (p) => {
664
+ const template = templateByPath.get(p);
665
+ return template ? `/${template.name}` : this.formatDisplayPath(p);
666
+ },
667
+ formatPackagePath: (p) => {
668
+ const template = templateByPath.get(p);
669
+ return template ? `/${template.name}` : this.formatDisplayPath(p);
670
+ },
671
+ });
672
+ this.chatContainer.addChild(new Text(`${sectionHeader("Prompts")}\n${templateList}`, 0, 0));
673
+ this.chatContainer.addChild(new Spacer(1));
674
+ }
675
+ const extensionPaths = options?.extensionPaths ?? [];
676
+ if (extensionPaths.length > 0) {
677
+ const groups = this.buildScopeGroups(extensionPaths, metadata);
678
+ const extList = this.formatScopeGroups(groups, {
679
+ formatPath: (p) => this.formatDisplayPath(p),
680
+ formatPackagePath: (p, source) => this.getShortPath(p, source),
681
+ });
682
+ this.chatContainer.addChild(new Text(`${sectionHeader("Extensions", "mdHeading")}\n${extList}`, 0, 0));
683
+ this.chatContainer.addChild(new Spacer(1));
684
+ }
685
+ // Show loaded themes (excluding built-in)
686
+ const loadedThemes = themesResult.themes;
687
+ const customThemes = loadedThemes.filter((t) => t.sourcePath);
688
+ if (customThemes.length > 0) {
689
+ const themePaths = customThemes.map((t) => t.sourcePath);
690
+ const groups = this.buildScopeGroups(themePaths, metadata);
691
+ const themeList = this.formatScopeGroups(groups, {
692
+ formatPath: (p) => this.formatDisplayPath(p),
693
+ formatPackagePath: (p, source) => this.getShortPath(p, source),
694
+ });
695
+ this.chatContainer.addChild(new Text(`${sectionHeader("Themes")}\n${themeList}`, 0, 0));
696
+ this.chatContainer.addChild(new Spacer(1));
697
+ }
698
+ }
699
+ if (showDiagnostics) {
700
+ const skillDiagnostics = skillsResult.diagnostics;
701
+ if (skillDiagnostics.length > 0) {
702
+ const warningLines = this.formatDiagnostics(skillDiagnostics, metadata);
703
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Skill conflicts]")}\n${warningLines}`, 0, 0));
704
+ this.chatContainer.addChild(new Spacer(1));
705
+ }
706
+ const promptDiagnostics = promptsResult.diagnostics;
707
+ if (promptDiagnostics.length > 0) {
708
+ const warningLines = this.formatDiagnostics(promptDiagnostics, metadata);
709
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Prompt conflicts]")}\n${warningLines}`, 0, 0));
710
+ this.chatContainer.addChild(new Spacer(1));
711
+ }
712
+ const extensionDiagnostics = [];
713
+ const extensionErrors = this.session.resourceLoader.getExtensions().errors;
714
+ if (extensionErrors.length > 0) {
715
+ for (const error of extensionErrors) {
716
+ extensionDiagnostics.push({ type: "error", message: error.error, path: error.path });
717
+ }
718
+ }
719
+ const commandDiagnostics = this.session.extensionRunner?.getCommandDiagnostics() ?? [];
720
+ extensionDiagnostics.push(...commandDiagnostics);
721
+ const shortcutDiagnostics = this.session.extensionRunner?.getShortcutDiagnostics() ?? [];
722
+ extensionDiagnostics.push(...shortcutDiagnostics);
723
+ if (extensionDiagnostics.length > 0) {
724
+ const warningLines = this.formatDiagnostics(extensionDiagnostics, metadata);
725
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Extension issues]")}\n${warningLines}`, 0, 0));
726
+ this.chatContainer.addChild(new Spacer(1));
727
+ }
728
+ const themeDiagnostics = themesResult.diagnostics;
729
+ if (themeDiagnostics.length > 0) {
730
+ const warningLines = this.formatDiagnostics(themeDiagnostics, metadata);
731
+ this.chatContainer.addChild(new Text(`${theme.fg("warning", "[Theme conflicts]")}\n${warningLines}`, 0, 0));
732
+ this.chatContainer.addChild(new Spacer(1));
733
+ }
734
+ }
735
+ }
736
+ /**
737
+ * Initialize the extension system with TUI-based UI context.
738
+ */
739
+ async initExtensions() {
740
+ const uiContext = this.createExtensionUIContext();
741
+ await this.session.bindExtensions({
742
+ uiContext,
743
+ commandContextActions: {
744
+ waitForIdle: () => this.session.agent.waitForIdle(),
745
+ newSession: async (options) => {
746
+ if (this.loadingAnimation) {
747
+ this.loadingAnimation.stop();
748
+ this.loadingAnimation = undefined;
749
+ }
750
+ this.statusContainer.clear();
751
+ // Delegate to AgentSession (handles setup + agent state sync)
752
+ const success = await this.session.newSession(options);
753
+ if (!success) {
754
+ return { cancelled: true };
755
+ }
756
+ // Clear UI state
757
+ this.chatContainer.clear();
758
+ this.pendingMessagesContainer.clear();
759
+ this.compactionQueuedMessages = [];
760
+ this.streamingComponent = undefined;
761
+ this.streamingMessage = undefined;
762
+ this.pendingTools.clear();
763
+ // Render any messages added via setup, or show empty session
764
+ this.renderInitialMessages();
765
+ this.ui.requestRender();
766
+ return { cancelled: false };
767
+ },
768
+ fork: async (entryId) => {
769
+ const result = await this.session.fork(entryId);
770
+ if (result.cancelled) {
771
+ return { cancelled: true };
772
+ }
773
+ this.chatContainer.clear();
774
+ this.renderInitialMessages();
775
+ this.editor.setText(result.selectedText);
776
+ this.showStatus("Forked to new session");
777
+ return { cancelled: false };
778
+ },
779
+ navigateTree: async (targetId, options) => {
780
+ const result = await this.session.navigateTree(targetId, {
781
+ summarize: options?.summarize,
782
+ customInstructions: options?.customInstructions,
783
+ replaceInstructions: options?.replaceInstructions,
784
+ label: options?.label,
785
+ });
786
+ if (result.cancelled) {
787
+ return { cancelled: true };
788
+ }
789
+ this.chatContainer.clear();
790
+ this.renderInitialMessages();
791
+ if (result.editorText && !this.editor.getText().trim()) {
792
+ this.editor.setText(result.editorText);
793
+ }
794
+ this.showStatus("Navigated to selected point");
795
+ return { cancelled: false };
796
+ },
797
+ switchSession: async (sessionPath) => {
798
+ await this.handleResumeSession(sessionPath);
799
+ return { cancelled: false };
800
+ },
801
+ reload: async () => {
802
+ await this.handleReloadCommand();
803
+ },
804
+ },
805
+ shutdownHandler: () => {
806
+ this.shutdownRequested = true;
807
+ if (!this.session.isStreaming) {
808
+ void this.shutdown();
809
+ }
810
+ },
811
+ onError: (error) => {
812
+ this.showExtensionError(error.extensionPath, error.error, error.stack);
813
+ },
814
+ });
815
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
816
+ this.setupAutocomplete(this.fdPath);
817
+ const extensionRunner = this.session.extensionRunner;
818
+ if (!extensionRunner) {
819
+ this.showLoadedResources({ extensionPaths: [], force: false });
820
+ return;
821
+ }
822
+ this.setupExtensionShortcuts(extensionRunner);
823
+ this.showLoadedResources({ extensionPaths: extensionRunner.getExtensionPaths(), force: false });
824
+ }
825
+ /**
826
+ * Get a registered tool definition by name (for custom rendering).
827
+ */
828
+ getRegisteredToolDefinition(toolName) {
829
+ const tools = this.session.extensionRunner?.getAllRegisteredTools() ?? [];
830
+ const registeredTool = tools.find((t) => t.definition.name === toolName);
831
+ return registeredTool?.definition;
832
+ }
833
+ /**
834
+ * Set up keyboard shortcuts registered by extensions.
835
+ */
836
+ setupExtensionShortcuts(extensionRunner) {
837
+ const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
838
+ if (shortcuts.size === 0)
839
+ return;
840
+ // Create a context for shortcut handlers
841
+ const createContext = () => ({
842
+ ui: this.createExtensionUIContext(),
843
+ hasUI: true,
844
+ cwd: process.cwd(),
845
+ sessionManager: this.sessionManager,
846
+ modelRegistry: this.session.modelRegistry,
847
+ model: this.session.model,
848
+ isIdle: () => !this.session.isStreaming,
849
+ abort: () => this.session.abort(),
850
+ hasPendingMessages: () => this.session.pendingMessageCount > 0,
851
+ shutdown: () => {
852
+ this.shutdownRequested = true;
853
+ },
854
+ getContextUsage: () => this.session.getContextUsage(),
855
+ compact: (options) => {
856
+ void (async () => {
857
+ try {
858
+ const result = await this.executeCompaction(options?.customInstructions, false);
859
+ if (result) {
860
+ options?.onComplete?.(result);
861
+ }
862
+ }
863
+ catch (error) {
864
+ const err = error instanceof Error ? error : new Error(String(error));
865
+ options?.onError?.(err);
866
+ }
867
+ })();
868
+ },
869
+ getSystemPrompt: () => this.session.systemPrompt,
870
+ });
871
+ // Set up the extension shortcut handler on the default editor
872
+ this.defaultEditor.onExtensionShortcut = (data) => {
873
+ for (const [shortcutStr, shortcut] of shortcuts) {
874
+ // Cast to KeyId - extension shortcuts use the same format
875
+ if (matchesKey(data, shortcutStr)) {
876
+ // Run handler async, don't block input
877
+ Promise.resolve(shortcut.handler(createContext())).catch((err) => {
878
+ this.showError(`Shortcut handler error: ${err instanceof Error ? err.message : String(err)}`);
879
+ });
880
+ return true;
881
+ }
882
+ }
883
+ return false;
884
+ };
885
+ }
886
+ /**
887
+ * Set extension status text in the footer.
888
+ */
889
+ setExtensionStatus(key, text) {
890
+ this.footerDataProvider.setExtensionStatus(key, text);
891
+ this.ui.requestRender();
892
+ }
893
+ /**
894
+ * Set an extension widget (string array or custom component).
895
+ */
896
+ setExtensionWidget(key, content, options) {
897
+ const placement = options?.placement ?? "aboveEditor";
898
+ const removeExisting = (map) => {
899
+ const existing = map.get(key);
900
+ if (existing?.dispose)
901
+ existing.dispose();
902
+ map.delete(key);
903
+ };
904
+ removeExisting(this.extensionWidgetsAbove);
905
+ removeExisting(this.extensionWidgetsBelow);
906
+ if (content === undefined) {
907
+ this.renderWidgets();
908
+ return;
909
+ }
910
+ let component;
911
+ if (Array.isArray(content)) {
912
+ // Wrap string array in a Container with Text components
913
+ const container = new Container();
914
+ for (const line of content.slice(0, InteractiveMode.MAX_WIDGET_LINES)) {
915
+ container.addChild(new Text(line, 1, 0));
916
+ }
917
+ if (content.length > InteractiveMode.MAX_WIDGET_LINES) {
918
+ container.addChild(new Text(theme.fg("muted", "... (widget truncated)"), 1, 0));
919
+ }
920
+ component = container;
921
+ }
922
+ else {
923
+ // Factory function - create component
924
+ component = content(this.ui, theme);
925
+ }
926
+ const targetMap = placement === "belowEditor" ? this.extensionWidgetsBelow : this.extensionWidgetsAbove;
927
+ targetMap.set(key, component);
928
+ this.renderWidgets();
929
+ }
930
+ clearExtensionWidgets() {
931
+ for (const widget of this.extensionWidgetsAbove.values()) {
932
+ widget.dispose?.();
933
+ }
934
+ for (const widget of this.extensionWidgetsBelow.values()) {
935
+ widget.dispose?.();
936
+ }
937
+ this.extensionWidgetsAbove.clear();
938
+ this.extensionWidgetsBelow.clear();
939
+ this.renderWidgets();
940
+ }
941
+ resetExtensionUI() {
942
+ if (this.extensionSelector) {
943
+ this.hideExtensionSelector();
944
+ }
945
+ if (this.extensionInput) {
946
+ this.hideExtensionInput();
947
+ }
948
+ if (this.extensionEditor) {
949
+ this.hideExtensionEditor();
950
+ }
951
+ this.ui.hideOverlay();
952
+ this.clearExtensionTerminalInputListeners();
953
+ this.setExtensionFooter(undefined);
954
+ this.setExtensionHeader(undefined);
955
+ this.clearExtensionWidgets();
956
+ this.footerDataProvider.clearExtensionStatuses();
957
+ this.footer.invalidate();
958
+ this.setCustomEditorComponent(undefined);
959
+ this.defaultEditor.onExtensionShortcut = undefined;
960
+ this.updateTerminalTitle();
961
+ if (this.loadingAnimation) {
962
+ this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${appKey(this.keybindings, "interrupt")} to interrupt)`);
963
+ }
964
+ }
965
+ // Maximum total widget lines to prevent viewport overflow
966
+ static { this.MAX_WIDGET_LINES = 10; }
967
+ /**
968
+ * Render all extension widgets to the widget container.
969
+ */
970
+ renderWidgets() {
971
+ if (!this.widgetContainerAbove || !this.widgetContainerBelow)
972
+ return;
973
+ this.renderWidgetContainer(this.widgetContainerAbove, this.extensionWidgetsAbove, true, true);
974
+ this.renderWidgetContainer(this.widgetContainerBelow, this.extensionWidgetsBelow, false, false);
975
+ this.ui.requestRender();
976
+ }
977
+ renderWidgetContainer(container, widgets, spacerWhenEmpty, leadingSpacer) {
978
+ container.clear();
979
+ if (widgets.size === 0) {
980
+ if (spacerWhenEmpty) {
981
+ container.addChild(new Spacer(1));
982
+ }
983
+ return;
984
+ }
985
+ if (leadingSpacer) {
986
+ container.addChild(new Spacer(1));
987
+ }
988
+ for (const component of widgets.values()) {
989
+ container.addChild(component);
990
+ }
991
+ }
992
+ /**
993
+ * Set a custom footer component, or restore the built-in footer.
994
+ */
995
+ setExtensionFooter(factory) {
996
+ // Dispose existing custom footer
997
+ if (this.customFooter?.dispose) {
998
+ this.customFooter.dispose();
999
+ }
1000
+ // Remove current footer from UI
1001
+ if (this.customFooter) {
1002
+ this.ui.removeChild(this.customFooter);
1003
+ }
1004
+ else {
1005
+ this.ui.removeChild(this.footer);
1006
+ }
1007
+ if (factory) {
1008
+ // Create and add custom footer, passing the data provider
1009
+ this.customFooter = factory(this.ui, theme, this.footerDataProvider);
1010
+ this.ui.addChild(this.customFooter);
1011
+ }
1012
+ else {
1013
+ // Restore built-in footer
1014
+ this.customFooter = undefined;
1015
+ this.ui.addChild(this.footer);
1016
+ }
1017
+ this.ui.requestRender();
1018
+ }
1019
+ /**
1020
+ * Set a custom header component, or restore the built-in header.
1021
+ */
1022
+ setExtensionHeader(factory) {
1023
+ // Header may not be initialized yet if called during early initialization
1024
+ if (!this.builtInHeader) {
1025
+ return;
1026
+ }
1027
+ // Dispose existing custom header
1028
+ if (this.customHeader?.dispose) {
1029
+ this.customHeader.dispose();
1030
+ }
1031
+ // Find the index of the current header in the header container
1032
+ const currentHeader = this.customHeader || this.builtInHeader;
1033
+ const index = this.headerContainer.children.indexOf(currentHeader);
1034
+ if (factory) {
1035
+ // Create and add custom header
1036
+ this.customHeader = factory(this.ui, theme);
1037
+ if (index !== -1) {
1038
+ this.headerContainer.children[index] = this.customHeader;
1039
+ }
1040
+ else {
1041
+ // If not found (e.g. builtInHeader was never added), add at the top
1042
+ this.headerContainer.children.unshift(this.customHeader);
1043
+ }
1044
+ }
1045
+ else {
1046
+ // Restore built-in header
1047
+ this.customHeader = undefined;
1048
+ if (index !== -1) {
1049
+ this.headerContainer.children[index] = this.builtInHeader;
1050
+ }
1051
+ }
1052
+ this.ui.requestRender();
1053
+ }
1054
+ addExtensionTerminalInputListener(handler) {
1055
+ const unsubscribe = this.ui.addInputListener(handler);
1056
+ this.extensionTerminalInputUnsubscribers.add(unsubscribe);
1057
+ return () => {
1058
+ unsubscribe();
1059
+ this.extensionTerminalInputUnsubscribers.delete(unsubscribe);
1060
+ };
1061
+ }
1062
+ clearExtensionTerminalInputListeners() {
1063
+ for (const unsubscribe of this.extensionTerminalInputUnsubscribers) {
1064
+ unsubscribe();
1065
+ }
1066
+ this.extensionTerminalInputUnsubscribers.clear();
1067
+ }
1068
+ /**
1069
+ * Create the ExtensionUIContext for extensions.
1070
+ */
1071
+ createExtensionUIContext() {
1072
+ return {
1073
+ select: (title, options, opts) => this.showExtensionSelector(title, options, opts),
1074
+ confirm: (title, message, opts) => this.showExtensionConfirm(title, message, opts),
1075
+ input: (title, placeholder, opts) => this.showExtensionInput(title, placeholder, opts),
1076
+ notify: (message, type) => this.showExtensionNotify(message, type),
1077
+ onTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler),
1078
+ setStatus: (key, text) => this.setExtensionStatus(key, text),
1079
+ setWorkingMessage: (message) => {
1080
+ if (this.loadingAnimation) {
1081
+ if (message) {
1082
+ this.loadingAnimation.setMessage(message);
1083
+ }
1084
+ else {
1085
+ this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${appKey(this.keybindings, "interrupt")} to interrupt)`);
1086
+ }
1087
+ }
1088
+ else {
1089
+ // Queue message for when loadingAnimation is created (handles agent_start race)
1090
+ this.pendingWorkingMessage = message;
1091
+ }
1092
+ },
1093
+ setWidget: (key, content, options) => this.setExtensionWidget(key, content, options),
1094
+ setFooter: (factory) => this.setExtensionFooter(factory),
1095
+ setHeader: (factory) => this.setExtensionHeader(factory),
1096
+ setTitle: (title) => this.ui.terminal.setTitle(title),
1097
+ custom: (factory, options) => this.showExtensionCustom(factory, options),
1098
+ pasteToEditor: (text) => this.editor.handleInput(`\x1b[200~${text}\x1b[201~`),
1099
+ setEditorText: (text) => this.editor.setText(text),
1100
+ getEditorText: () => this.editor.getText(),
1101
+ editor: (title, prefill) => this.showExtensionEditor(title, prefill),
1102
+ setEditorComponent: (factory) => this.setCustomEditorComponent(factory),
1103
+ get theme() {
1104
+ return theme;
1105
+ },
1106
+ getAllThemes: () => getAvailableThemesWithPaths(),
1107
+ getTheme: (name) => getThemeByName(name),
1108
+ setTheme: (themeOrName) => {
1109
+ if (themeOrName instanceof Theme) {
1110
+ setThemeInstance(themeOrName);
1111
+ this.ui.requestRender();
1112
+ return { success: true };
1113
+ }
1114
+ const result = setTheme(themeOrName, true);
1115
+ if (result.success) {
1116
+ if (this.settingsManager.getTheme() !== themeOrName) {
1117
+ this.settingsManager.setTheme(themeOrName);
1118
+ }
1119
+ this.ui.requestRender();
1120
+ }
1121
+ return result;
1122
+ },
1123
+ getToolsExpanded: () => this.toolOutputExpanded,
1124
+ setToolsExpanded: (expanded) => this.setToolsExpanded(expanded),
1125
+ };
1126
+ }
1127
+ /**
1128
+ * Show a selector for extensions.
1129
+ */
1130
+ showExtensionSelector(title, options, opts) {
1131
+ return new Promise((resolve) => {
1132
+ if (opts?.signal?.aborted) {
1133
+ resolve(undefined);
1134
+ return;
1135
+ }
1136
+ const onAbort = () => {
1137
+ this.hideExtensionSelector();
1138
+ resolve(undefined);
1139
+ };
1140
+ opts?.signal?.addEventListener("abort", onAbort, { once: true });
1141
+ this.extensionSelector = new ExtensionSelectorComponent(title, options, (option) => {
1142
+ opts?.signal?.removeEventListener("abort", onAbort);
1143
+ this.hideExtensionSelector();
1144
+ resolve(option);
1145
+ }, () => {
1146
+ opts?.signal?.removeEventListener("abort", onAbort);
1147
+ this.hideExtensionSelector();
1148
+ resolve(undefined);
1149
+ }, { tui: this.ui, timeout: opts?.timeout });
1150
+ this.editorContainer.clear();
1151
+ this.editorContainer.addChild(this.extensionSelector);
1152
+ this.ui.setFocus(this.extensionSelector);
1153
+ this.ui.requestRender();
1154
+ });
1155
+ }
1156
+ /**
1157
+ * Hide the extension selector.
1158
+ */
1159
+ hideExtensionSelector() {
1160
+ this.extensionSelector?.dispose();
1161
+ this.editorContainer.clear();
1162
+ this.editorContainer.addChild(this.editor);
1163
+ this.extensionSelector = undefined;
1164
+ this.ui.setFocus(this.editor);
1165
+ this.ui.requestRender();
1166
+ }
1167
+ /**
1168
+ * Show a confirmation dialog for extensions.
1169
+ */
1170
+ async showExtensionConfirm(title, message, opts) {
1171
+ const result = await this.showExtensionSelector(`${title}\n${message}`, ["Yes", "No"], opts);
1172
+ return result === "Yes";
1173
+ }
1174
+ /**
1175
+ * Show a text input for extensions.
1176
+ */
1177
+ showExtensionInput(title, placeholder, opts) {
1178
+ return new Promise((resolve) => {
1179
+ if (opts?.signal?.aborted) {
1180
+ resolve(undefined);
1181
+ return;
1182
+ }
1183
+ const onAbort = () => {
1184
+ this.hideExtensionInput();
1185
+ resolve(undefined);
1186
+ };
1187
+ opts?.signal?.addEventListener("abort", onAbort, { once: true });
1188
+ this.extensionInput = new ExtensionInputComponent(title, placeholder, (value) => {
1189
+ opts?.signal?.removeEventListener("abort", onAbort);
1190
+ this.hideExtensionInput();
1191
+ resolve(value);
1192
+ }, () => {
1193
+ opts?.signal?.removeEventListener("abort", onAbort);
1194
+ this.hideExtensionInput();
1195
+ resolve(undefined);
1196
+ }, { tui: this.ui, timeout: opts?.timeout });
1197
+ this.editorContainer.clear();
1198
+ this.editorContainer.addChild(this.extensionInput);
1199
+ this.ui.setFocus(this.extensionInput);
1200
+ this.ui.requestRender();
1201
+ });
1202
+ }
1203
+ /**
1204
+ * Hide the extension input.
1205
+ */
1206
+ hideExtensionInput() {
1207
+ this.extensionInput?.dispose();
1208
+ this.editorContainer.clear();
1209
+ this.editorContainer.addChild(this.editor);
1210
+ this.extensionInput = undefined;
1211
+ this.ui.setFocus(this.editor);
1212
+ this.ui.requestRender();
1213
+ }
1214
+ /**
1215
+ * Show a multi-line editor for extensions (with Ctrl+G support).
1216
+ */
1217
+ showExtensionEditor(title, prefill) {
1218
+ return new Promise((resolve) => {
1219
+ this.extensionEditor = new ExtensionEditorComponent(this.ui, this.keybindings, title, prefill, (value) => {
1220
+ this.hideExtensionEditor();
1221
+ resolve(value);
1222
+ }, () => {
1223
+ this.hideExtensionEditor();
1224
+ resolve(undefined);
1225
+ });
1226
+ this.editorContainer.clear();
1227
+ this.editorContainer.addChild(this.extensionEditor);
1228
+ this.ui.setFocus(this.extensionEditor);
1229
+ this.ui.requestRender();
1230
+ });
1231
+ }
1232
+ /**
1233
+ * Hide the extension editor.
1234
+ */
1235
+ hideExtensionEditor() {
1236
+ this.editorContainer.clear();
1237
+ this.editorContainer.addChild(this.editor);
1238
+ this.extensionEditor = undefined;
1239
+ this.ui.setFocus(this.editor);
1240
+ this.ui.requestRender();
1241
+ }
1242
+ /**
1243
+ * Set a custom editor component from an extension.
1244
+ * Pass undefined to restore the default editor.
1245
+ */
1246
+ setCustomEditorComponent(factory) {
1247
+ // Save text from current editor before switching
1248
+ const currentText = this.editor.getText();
1249
+ this.editorContainer.clear();
1250
+ if (factory) {
1251
+ // Create the custom editor with tui, theme, and keybindings
1252
+ const newEditor = factory(this.ui, getEditorTheme(), this.keybindings);
1253
+ // Wire up callbacks from the default editor
1254
+ newEditor.onSubmit = this.defaultEditor.onSubmit;
1255
+ newEditor.onChange = this.defaultEditor.onChange;
1256
+ // Copy text from previous editor
1257
+ newEditor.setText(currentText);
1258
+ // Copy appearance settings if supported
1259
+ if (newEditor.borderColor !== undefined) {
1260
+ newEditor.borderColor = this.defaultEditor.borderColor;
1261
+ }
1262
+ if (newEditor.setPaddingX !== undefined) {
1263
+ newEditor.setPaddingX(this.defaultEditor.getPaddingX());
1264
+ }
1265
+ // Set autocomplete if supported
1266
+ if (newEditor.setAutocompleteProvider && this.autocompleteProvider) {
1267
+ newEditor.setAutocompleteProvider(this.autocompleteProvider);
1268
+ }
1269
+ // If extending CustomEditor, copy app-level handlers
1270
+ // Use duck typing since instanceof fails across jiti module boundaries
1271
+ const customEditor = newEditor;
1272
+ if ("actionHandlers" in customEditor && customEditor.actionHandlers instanceof Map) {
1273
+ if (!customEditor.onEscape) {
1274
+ customEditor.onEscape = () => this.defaultEditor.onEscape?.();
1275
+ }
1276
+ if (!customEditor.onCtrlD) {
1277
+ customEditor.onCtrlD = () => this.defaultEditor.onCtrlD?.();
1278
+ }
1279
+ if (!customEditor.onPasteImage) {
1280
+ customEditor.onPasteImage = () => this.defaultEditor.onPasteImage?.();
1281
+ }
1282
+ if (!customEditor.onExtensionShortcut) {
1283
+ customEditor.onExtensionShortcut = (data) => this.defaultEditor.onExtensionShortcut?.(data);
1284
+ }
1285
+ // Copy action handlers (clear, suspend, model switching, etc.)
1286
+ for (const [action, handler] of this.defaultEditor.actionHandlers) {
1287
+ customEditor.actionHandlers.set(action, handler);
1288
+ }
1289
+ }
1290
+ this.editor = newEditor;
1291
+ }
1292
+ else {
1293
+ // Restore default editor with text from custom editor
1294
+ this.defaultEditor.setText(currentText);
1295
+ this.editor = this.defaultEditor;
1296
+ }
1297
+ this.editorContainer.addChild(this.editor);
1298
+ this.ui.setFocus(this.editor);
1299
+ this.ui.requestRender();
1300
+ }
1301
+ /**
1302
+ * Show a notification for extensions.
1303
+ */
1304
+ showExtensionNotify(message, type) {
1305
+ if (type === "error") {
1306
+ this.showError(message);
1307
+ }
1308
+ else if (type === "warning") {
1309
+ this.showWarning(message);
1310
+ }
1311
+ else {
1312
+ this.showStatus(message);
1313
+ }
1314
+ }
1315
+ /** Show a custom component with keyboard focus. Overlay mode renders on top of existing content. */
1316
+ async showExtensionCustom(factory, options) {
1317
+ const savedText = this.editor.getText();
1318
+ const isOverlay = options?.overlay ?? false;
1319
+ const restoreEditor = () => {
1320
+ this.editorContainer.clear();
1321
+ this.editorContainer.addChild(this.editor);
1322
+ this.editor.setText(savedText);
1323
+ this.ui.setFocus(this.editor);
1324
+ this.ui.requestRender();
1325
+ };
1326
+ return new Promise((resolve, reject) => {
1327
+ let component;
1328
+ let closed = false;
1329
+ const close = (result) => {
1330
+ if (closed)
1331
+ return;
1332
+ closed = true;
1333
+ if (isOverlay)
1334
+ this.ui.hideOverlay();
1335
+ else
1336
+ restoreEditor();
1337
+ // Note: both branches above already call requestRender
1338
+ resolve(result);
1339
+ try {
1340
+ component?.dispose?.();
1341
+ }
1342
+ catch {
1343
+ /* ignore dispose errors */
1344
+ }
1345
+ };
1346
+ Promise.resolve(factory(this.ui, theme, this.keybindings, close))
1347
+ .then((c) => {
1348
+ if (closed)
1349
+ return;
1350
+ component = c;
1351
+ if (isOverlay) {
1352
+ // Resolve overlay options - can be static or dynamic function
1353
+ const resolveOptions = () => {
1354
+ if (options?.overlayOptions) {
1355
+ const opts = typeof options.overlayOptions === "function"
1356
+ ? options.overlayOptions()
1357
+ : options.overlayOptions;
1358
+ return opts;
1359
+ }
1360
+ // Fallback: use component's width property if available
1361
+ const w = component.width;
1362
+ return w ? { width: w } : undefined;
1363
+ };
1364
+ const handle = this.ui.showOverlay(component, resolveOptions());
1365
+ // Expose handle to caller for visibility control
1366
+ options?.onHandle?.(handle);
1367
+ }
1368
+ else {
1369
+ this.editorContainer.clear();
1370
+ this.editorContainer.addChild(component);
1371
+ this.ui.setFocus(component);
1372
+ this.ui.requestRender();
1373
+ }
1374
+ })
1375
+ .catch((err) => {
1376
+ if (closed)
1377
+ return;
1378
+ if (!isOverlay)
1379
+ restoreEditor();
1380
+ reject(err);
1381
+ });
1382
+ });
1383
+ }
1384
+ /**
1385
+ * Show an extension error in the UI.
1386
+ */
1387
+ showExtensionError(extensionPath, error, stack) {
1388
+ const errorMsg = `Extension "${extensionPath}" error: ${error}`;
1389
+ const errorText = new Text(theme.fg("error", errorMsg), 1, 0);
1390
+ this.chatContainer.addChild(errorText);
1391
+ if (stack) {
1392
+ // Show stack trace in dim color, indented
1393
+ const stackLines = stack
1394
+ .split("\n")
1395
+ .slice(1) // Skip first line (duplicates error message)
1396
+ .map((line) => theme.fg("dim", ` ${line.trim()}`))
1397
+ .join("\n");
1398
+ if (stackLines) {
1399
+ this.chatContainer.addChild(new Text(stackLines, 1, 0));
1400
+ }
1401
+ }
1402
+ this.ui.requestRender();
1403
+ }
1404
+ // =========================================================================
1405
+ // Key Handlers
1406
+ // =========================================================================
1407
+ setupKeyHandlers() {
1408
+ // Set up handlers on defaultEditor - they use this.editor for text access
1409
+ // so they work correctly regardless of which editor is active
1410
+ this.defaultEditor.onEscape = () => {
1411
+ if (this.loadingAnimation) {
1412
+ this.restoreQueuedMessagesToEditor({ abort: true });
1413
+ }
1414
+ else if (this.session.isBashRunning) {
1415
+ this.session.abortBash();
1416
+ }
1417
+ else if (this.isBashMode) {
1418
+ this.editor.setText("");
1419
+ this.isBashMode = false;
1420
+ this.updateEditorBorderColor();
1421
+ }
1422
+ else if (!this.editor.getText().trim()) {
1423
+ // Double-escape with empty editor triggers /tree, /fork, or nothing based on setting
1424
+ const action = this.settingsManager.getDoubleEscapeAction();
1425
+ if (action !== "none") {
1426
+ const now = Date.now();
1427
+ if (now - this.lastEscapeTime < 500) {
1428
+ if (action === "tree") {
1429
+ this.showTreeSelector();
1430
+ }
1431
+ else {
1432
+ this.showUserMessageSelector();
1433
+ }
1434
+ this.lastEscapeTime = 0;
1435
+ }
1436
+ else {
1437
+ this.lastEscapeTime = now;
1438
+ }
1439
+ }
1440
+ }
1441
+ };
1442
+ // Register app action handlers
1443
+ this.defaultEditor.onAction("clear", () => this.handleCtrlC());
1444
+ this.defaultEditor.onCtrlD = () => this.handleCtrlD();
1445
+ this.defaultEditor.onAction("suspend", () => this.handleCtrlZ());
1446
+ this.defaultEditor.onAction("cycleThinkingLevel", () => this.cycleThinkingLevel());
1447
+ this.defaultEditor.onAction("cycleModelForward", () => this.cycleModel("forward"));
1448
+ this.defaultEditor.onAction("cycleModelBackward", () => this.cycleModel("backward"));
1449
+ // Global debug handler on TUI (works regardless of focus)
1450
+ this.ui.onDebug = () => this.handleDebugCommand();
1451
+ this.defaultEditor.onAction("selectModel", () => this.showModelSelector());
1452
+ this.defaultEditor.onAction("expandTools", () => this.toggleToolOutputExpansion());
1453
+ this.defaultEditor.onAction("toggleThinking", () => this.toggleThinkingBlockVisibility());
1454
+ this.defaultEditor.onAction("externalEditor", () => this.openExternalEditor());
1455
+ this.defaultEditor.onAction("followUp", () => this.handleFollowUp());
1456
+ this.defaultEditor.onAction("dequeue", () => this.handleDequeue());
1457
+ this.defaultEditor.onAction("newSession", () => this.handleClearCommand());
1458
+ this.defaultEditor.onAction("tree", () => this.showTreeSelector());
1459
+ this.defaultEditor.onAction("fork", () => this.showUserMessageSelector());
1460
+ this.defaultEditor.onAction("resume", () => this.showSessionSelector());
1461
+ this.defaultEditor.onChange = (text) => {
1462
+ const wasBashMode = this.isBashMode;
1463
+ this.isBashMode = text.trimStart().startsWith("!");
1464
+ if (wasBashMode !== this.isBashMode) {
1465
+ this.updateEditorBorderColor();
1466
+ }
1467
+ };
1468
+ // Handle clipboard image paste (triggered on Ctrl+V)
1469
+ this.defaultEditor.onPasteImage = () => {
1470
+ this.handleClipboardImagePaste();
1471
+ };
1472
+ }
1473
+ async handleClipboardImagePaste() {
1474
+ try {
1475
+ const image = await readClipboardImage();
1476
+ if (!image) {
1477
+ return;
1478
+ }
1479
+ // Write to temp file
1480
+ const tmpDir = os.tmpdir();
1481
+ const ext = extensionForImageMimeType(image.mimeType) ?? "png";
1482
+ const fileName = `pi-clipboard-${crypto.randomUUID()}.${ext}`;
1483
+ const filePath = path.join(tmpDir, fileName);
1484
+ fs.writeFileSync(filePath, Buffer.from(image.bytes));
1485
+ // Insert file path directly
1486
+ this.editor.insertTextAtCursor?.(filePath);
1487
+ this.ui.requestRender();
1488
+ }
1489
+ catch {
1490
+ // Silently ignore clipboard errors (may not have permission, etc.)
1491
+ }
1492
+ }
1493
+ setupEditorSubmitHandler() {
1494
+ this.defaultEditor.onSubmit = async (text) => {
1495
+ text = text.trim();
1496
+ if (!text)
1497
+ return;
1498
+ // Handle commands
1499
+ if (text === "/settings") {
1500
+ this.showSettingsSelector();
1501
+ this.editor.setText("");
1502
+ return;
1503
+ }
1504
+ if (text === "/scoped-models") {
1505
+ this.editor.setText("");
1506
+ await this.showModelsSelector();
1507
+ return;
1508
+ }
1509
+ if (text === "/model" || text.startsWith("/model ")) {
1510
+ const searchTerm = text.startsWith("/model ") ? text.slice(7).trim() : undefined;
1511
+ this.editor.setText("");
1512
+ await this.handleModelCommand(searchTerm);
1513
+ return;
1514
+ }
1515
+ if (text.startsWith("/export")) {
1516
+ await this.handleExportCommand(text);
1517
+ this.editor.setText("");
1518
+ return;
1519
+ }
1520
+ if (text === "/share") {
1521
+ await this.handleShareCommand();
1522
+ this.editor.setText("");
1523
+ return;
1524
+ }
1525
+ if (text === "/copy") {
1526
+ this.handleCopyCommand();
1527
+ this.editor.setText("");
1528
+ return;
1529
+ }
1530
+ if (text === "/name" || text.startsWith("/name ")) {
1531
+ this.handleNameCommand(text);
1532
+ this.editor.setText("");
1533
+ return;
1534
+ }
1535
+ if (text === "/session") {
1536
+ this.handleSessionCommand();
1537
+ this.editor.setText("");
1538
+ return;
1539
+ }
1540
+ if (text === "/changelog") {
1541
+ this.handleChangelogCommand();
1542
+ this.editor.setText("");
1543
+ return;
1544
+ }
1545
+ if (text === "/hotkeys") {
1546
+ this.handleHotkeysCommand();
1547
+ this.editor.setText("");
1548
+ return;
1549
+ }
1550
+ if (text === "/fork") {
1551
+ this.showUserMessageSelector();
1552
+ this.editor.setText("");
1553
+ return;
1554
+ }
1555
+ if (text === "/tree") {
1556
+ this.showTreeSelector();
1557
+ this.editor.setText("");
1558
+ return;
1559
+ }
1560
+ if (text === "/login") {
1561
+ this.showOAuthSelector("login");
1562
+ this.editor.setText("");
1563
+ return;
1564
+ }
1565
+ if (text === "/logout") {
1566
+ this.showOAuthSelector("logout");
1567
+ this.editor.setText("");
1568
+ return;
1569
+ }
1570
+ if (text === "/new") {
1571
+ this.editor.setText("");
1572
+ await this.handleClearCommand();
1573
+ return;
1574
+ }
1575
+ if (text === "/compact" || text.startsWith("/compact ")) {
1576
+ const customInstructions = text.startsWith("/compact ") ? text.slice(9).trim() : undefined;
1577
+ this.editor.setText("");
1578
+ await this.handleCompactCommand(customInstructions);
1579
+ return;
1580
+ }
1581
+ if (text === "/reload") {
1582
+ this.editor.setText("");
1583
+ await this.handleReloadCommand();
1584
+ return;
1585
+ }
1586
+ if (text === "/debug") {
1587
+ this.handleDebugCommand();
1588
+ this.editor.setText("");
1589
+ return;
1590
+ }
1591
+ if (text === "/arminsayshi") {
1592
+ this.handleArminSaysHi();
1593
+ this.editor.setText("");
1594
+ return;
1595
+ }
1596
+ if (text === "/resume") {
1597
+ this.showSessionSelector();
1598
+ this.editor.setText("");
1599
+ return;
1600
+ }
1601
+ if (text === "/quit") {
1602
+ this.editor.setText("");
1603
+ await this.shutdown();
1604
+ return;
1605
+ }
1606
+ // Handle bash command (! for normal, !! for excluded from context)
1607
+ if (text.startsWith("!")) {
1608
+ const isExcluded = text.startsWith("!!");
1609
+ const command = isExcluded ? text.slice(2).trim() : text.slice(1).trim();
1610
+ if (command) {
1611
+ if (this.session.isBashRunning) {
1612
+ this.showWarning("A bash command is already running. Press Esc to cancel it first.");
1613
+ this.editor.setText(text);
1614
+ return;
1615
+ }
1616
+ this.editor.addToHistory?.(text);
1617
+ await this.handleBashCommand(command, isExcluded);
1618
+ this.isBashMode = false;
1619
+ this.updateEditorBorderColor();
1620
+ return;
1621
+ }
1622
+ }
1623
+ // Queue input during compaction (extension commands execute immediately)
1624
+ if (this.session.isCompacting) {
1625
+ if (this.isExtensionCommand(text)) {
1626
+ this.editor.addToHistory?.(text);
1627
+ this.editor.setText("");
1628
+ await this.session.prompt(text);
1629
+ }
1630
+ else {
1631
+ this.queueCompactionMessage(text, "steer");
1632
+ }
1633
+ return;
1634
+ }
1635
+ // If streaming, use prompt() with steer behavior
1636
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
1637
+ if (this.session.isStreaming) {
1638
+ this.editor.addToHistory?.(text);
1639
+ this.editor.setText("");
1640
+ await this.session.prompt(text, { streamingBehavior: "steer" });
1641
+ this.updatePendingMessagesDisplay();
1642
+ this.ui.requestRender();
1643
+ return;
1644
+ }
1645
+ // Normal message submission
1646
+ // First, move any pending bash components to chat
1647
+ this.flushPendingBashComponents();
1648
+ if (this.onInputCallback) {
1649
+ this.onInputCallback(text);
1650
+ }
1651
+ this.editor.addToHistory?.(text);
1652
+ };
1653
+ }
1654
+ subscribeToAgent() {
1655
+ this.unsubscribe = this.session.subscribe(async (event) => {
1656
+ await this.handleEvent(event);
1657
+ });
1658
+ }
1659
+ async handleEvent(event) {
1660
+ if (!this.isInitialized) {
1661
+ await this.init();
1662
+ }
1663
+ this.footer.invalidate();
1664
+ switch (event.type) {
1665
+ case "agent_start":
1666
+ // Restore main escape handler if retry handler is still active
1667
+ // (retry success event fires later, but we need main handler now)
1668
+ if (this.retryEscapeHandler) {
1669
+ this.defaultEditor.onEscape = this.retryEscapeHandler;
1670
+ this.retryEscapeHandler = undefined;
1671
+ }
1672
+ if (this.retryLoader) {
1673
+ this.retryLoader.stop();
1674
+ this.retryLoader = undefined;
1675
+ }
1676
+ if (this.loadingAnimation) {
1677
+ this.loadingAnimation.stop();
1678
+ }
1679
+ this.statusContainer.clear();
1680
+ this.loadingAnimation = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), this.defaultWorkingMessage);
1681
+ this.statusContainer.addChild(this.loadingAnimation);
1682
+ // Apply any pending working message queued before loader existed
1683
+ if (this.pendingWorkingMessage !== undefined) {
1684
+ if (this.pendingWorkingMessage) {
1685
+ this.loadingAnimation.setMessage(this.pendingWorkingMessage);
1686
+ }
1687
+ this.pendingWorkingMessage = undefined;
1688
+ }
1689
+ this.ui.requestRender();
1690
+ break;
1691
+ case "message_start":
1692
+ if (event.message.role === "custom") {
1693
+ this.addMessageToChat(event.message);
1694
+ this.ui.requestRender();
1695
+ }
1696
+ else if (event.message.role === "user") {
1697
+ this.addMessageToChat(event.message);
1698
+ this.updatePendingMessagesDisplay();
1699
+ this.ui.requestRender();
1700
+ }
1701
+ else if (event.message.role === "assistant") {
1702
+ this.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock, this.getMarkdownThemeWithSettings());
1703
+ this.streamingMessage = event.message;
1704
+ this.chatContainer.addChild(this.streamingComponent);
1705
+ this.streamingComponent.updateContent(this.streamingMessage);
1706
+ this.ui.requestRender();
1707
+ }
1708
+ break;
1709
+ case "message_update":
1710
+ if (this.streamingComponent && event.message.role === "assistant") {
1711
+ this.streamingMessage = event.message;
1712
+ this.streamingComponent.updateContent(this.streamingMessage);
1713
+ for (const content of this.streamingMessage.content) {
1714
+ if (content.type === "toolCall") {
1715
+ if (!this.pendingTools.has(content.id)) {
1716
+ const component = new ToolExecutionComponent(content.name, content.arguments, {
1717
+ showImages: this.settingsManager.getShowImages(),
1718
+ }, this.getRegisteredToolDefinition(content.name), this.ui);
1719
+ component.setExpanded(this.toolOutputExpanded);
1720
+ this.chatContainer.addChild(component);
1721
+ this.pendingTools.set(content.id, component);
1722
+ }
1723
+ else {
1724
+ const component = this.pendingTools.get(content.id);
1725
+ if (component) {
1726
+ component.updateArgs(content.arguments);
1727
+ }
1728
+ }
1729
+ }
1730
+ }
1731
+ this.ui.requestRender();
1732
+ }
1733
+ break;
1734
+ case "message_end":
1735
+ if (event.message.role === "user")
1736
+ break;
1737
+ if (this.streamingComponent && event.message.role === "assistant") {
1738
+ this.streamingMessage = event.message;
1739
+ let errorMessage;
1740
+ if (this.streamingMessage.stopReason === "aborted") {
1741
+ const retryAttempt = this.session.retryAttempt;
1742
+ errorMessage =
1743
+ retryAttempt > 0
1744
+ ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}`
1745
+ : "Operation aborted";
1746
+ this.streamingMessage.errorMessage = errorMessage;
1747
+ }
1748
+ this.streamingComponent.updateContent(this.streamingMessage);
1749
+ if (this.streamingMessage.stopReason === "aborted" || this.streamingMessage.stopReason === "error") {
1750
+ if (!errorMessage) {
1751
+ errorMessage = this.streamingMessage.errorMessage || "Error";
1752
+ }
1753
+ for (const [, component] of this.pendingTools.entries()) {
1754
+ component.updateResult({
1755
+ content: [{ type: "text", text: errorMessage }],
1756
+ isError: true,
1757
+ });
1758
+ }
1759
+ this.pendingTools.clear();
1760
+ }
1761
+ else {
1762
+ // Args are now complete - trigger diff computation for edit tools
1763
+ for (const [, component] of this.pendingTools.entries()) {
1764
+ component.setArgsComplete();
1765
+ }
1766
+ }
1767
+ this.streamingComponent = undefined;
1768
+ this.streamingMessage = undefined;
1769
+ this.footer.invalidate();
1770
+ }
1771
+ this.ui.requestRender();
1772
+ break;
1773
+ case "tool_execution_start": {
1774
+ if (!this.pendingTools.has(event.toolCallId)) {
1775
+ const component = new ToolExecutionComponent(event.toolName, event.args, {
1776
+ showImages: this.settingsManager.getShowImages(),
1777
+ }, this.getRegisteredToolDefinition(event.toolName), this.ui);
1778
+ component.setExpanded(this.toolOutputExpanded);
1779
+ this.chatContainer.addChild(component);
1780
+ this.pendingTools.set(event.toolCallId, component);
1781
+ this.ui.requestRender();
1782
+ }
1783
+ break;
1784
+ }
1785
+ case "tool_execution_update": {
1786
+ const component = this.pendingTools.get(event.toolCallId);
1787
+ if (component) {
1788
+ component.updateResult({ ...event.partialResult, isError: false }, true);
1789
+ this.ui.requestRender();
1790
+ }
1791
+ break;
1792
+ }
1793
+ case "tool_execution_end": {
1794
+ const component = this.pendingTools.get(event.toolCallId);
1795
+ if (component) {
1796
+ component.updateResult({ ...event.result, isError: event.isError });
1797
+ this.pendingTools.delete(event.toolCallId);
1798
+ this.ui.requestRender();
1799
+ }
1800
+ break;
1801
+ }
1802
+ case "agent_end":
1803
+ if (this.loadingAnimation) {
1804
+ this.loadingAnimation.stop();
1805
+ this.loadingAnimation = undefined;
1806
+ this.statusContainer.clear();
1807
+ }
1808
+ if (this.streamingComponent) {
1809
+ this.chatContainer.removeChild(this.streamingComponent);
1810
+ this.streamingComponent = undefined;
1811
+ this.streamingMessage = undefined;
1812
+ }
1813
+ this.pendingTools.clear();
1814
+ await this.checkShutdownRequested();
1815
+ this.ui.requestRender();
1816
+ break;
1817
+ case "auto_compaction_start": {
1818
+ // Keep editor active; submissions are queued during compaction.
1819
+ // Set up escape to abort auto-compaction
1820
+ this.autoCompactionEscapeHandler = this.defaultEditor.onEscape;
1821
+ this.defaultEditor.onEscape = () => {
1822
+ this.session.abortCompaction();
1823
+ };
1824
+ // Show compacting indicator with reason
1825
+ this.statusContainer.clear();
1826
+ const reasonText = event.reason === "overflow" ? "Context overflow detected, " : "";
1827
+ this.autoCompactionLoader = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), `${reasonText}Auto-compacting... (${appKey(this.keybindings, "interrupt")} to cancel)`);
1828
+ this.statusContainer.addChild(this.autoCompactionLoader);
1829
+ this.ui.requestRender();
1830
+ break;
1831
+ }
1832
+ case "auto_compaction_end": {
1833
+ // Restore escape handler
1834
+ if (this.autoCompactionEscapeHandler) {
1835
+ this.defaultEditor.onEscape = this.autoCompactionEscapeHandler;
1836
+ this.autoCompactionEscapeHandler = undefined;
1837
+ }
1838
+ // Stop loader
1839
+ if (this.autoCompactionLoader) {
1840
+ this.autoCompactionLoader.stop();
1841
+ this.autoCompactionLoader = undefined;
1842
+ this.statusContainer.clear();
1843
+ }
1844
+ // Handle result
1845
+ if (event.aborted) {
1846
+ this.showStatus("Auto-compaction cancelled");
1847
+ }
1848
+ else if (event.result) {
1849
+ // Rebuild chat to show compacted state
1850
+ this.chatContainer.clear();
1851
+ this.rebuildChatFromMessages();
1852
+ // Add compaction component at bottom so user sees it without scrolling
1853
+ this.addMessageToChat({
1854
+ role: "compactionSummary",
1855
+ tokensBefore: event.result.tokensBefore,
1856
+ summary: event.result.summary,
1857
+ timestamp: Date.now(),
1858
+ });
1859
+ this.footer.invalidate();
1860
+ }
1861
+ else if (event.errorMessage) {
1862
+ // Compaction failed (e.g., quota exceeded, API error)
1863
+ this.chatContainer.addChild(new Spacer(1));
1864
+ this.chatContainer.addChild(new Text(theme.fg("error", event.errorMessage), 1, 0));
1865
+ }
1866
+ void this.flushCompactionQueue({ willRetry: event.willRetry });
1867
+ this.ui.requestRender();
1868
+ break;
1869
+ }
1870
+ case "auto_retry_start": {
1871
+ // Set up escape to abort retry
1872
+ this.retryEscapeHandler = this.defaultEditor.onEscape;
1873
+ this.defaultEditor.onEscape = () => {
1874
+ this.session.abortRetry();
1875
+ };
1876
+ // Show retry indicator
1877
+ this.statusContainer.clear();
1878
+ const delaySeconds = Math.round(event.delayMs / 1000);
1879
+ this.retryLoader = new Loader(this.ui, (spinner) => theme.fg("warning", spinner), (text) => theme.fg("muted", text), `Retrying (${event.attempt}/${event.maxAttempts}) in ${delaySeconds}s... (${appKey(this.keybindings, "interrupt")} to cancel)`);
1880
+ this.statusContainer.addChild(this.retryLoader);
1881
+ this.ui.requestRender();
1882
+ break;
1883
+ }
1884
+ case "auto_retry_end": {
1885
+ // Restore escape handler
1886
+ if (this.retryEscapeHandler) {
1887
+ this.defaultEditor.onEscape = this.retryEscapeHandler;
1888
+ this.retryEscapeHandler = undefined;
1889
+ }
1890
+ // Stop loader
1891
+ if (this.retryLoader) {
1892
+ this.retryLoader.stop();
1893
+ this.retryLoader = undefined;
1894
+ this.statusContainer.clear();
1895
+ }
1896
+ // Show error only on final failure (success shows normal response)
1897
+ if (!event.success) {
1898
+ this.showError(`Retry failed after ${event.attempt} attempts: ${event.finalError || "Unknown error"}`);
1899
+ }
1900
+ this.ui.requestRender();
1901
+ break;
1902
+ }
1903
+ }
1904
+ }
1905
+ /** Extract text content from a user message */
1906
+ getUserMessageText(message) {
1907
+ if (message.role !== "user")
1908
+ return "";
1909
+ const textBlocks = typeof message.content === "string"
1910
+ ? [{ type: "text", text: message.content }]
1911
+ : message.content.filter((c) => c.type === "text");
1912
+ return textBlocks.map((c) => c.text).join("");
1913
+ }
1914
+ /**
1915
+ * Show a status message in the chat.
1916
+ *
1917
+ * If multiple status messages are emitted back-to-back (without anything else being added to the chat),
1918
+ * we update the previous status line instead of appending new ones to avoid log spam.
1919
+ */
1920
+ showStatus(message) {
1921
+ const children = this.chatContainer.children;
1922
+ const last = children.length > 0 ? children[children.length - 1] : undefined;
1923
+ const secondLast = children.length > 1 ? children[children.length - 2] : undefined;
1924
+ if (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {
1925
+ this.lastStatusText.setText(theme.fg("dim", message));
1926
+ this.ui.requestRender();
1927
+ return;
1928
+ }
1929
+ const spacer = new Spacer(1);
1930
+ const text = new Text(theme.fg("dim", message), 1, 0);
1931
+ this.chatContainer.addChild(spacer);
1932
+ this.chatContainer.addChild(text);
1933
+ this.lastStatusSpacer = spacer;
1934
+ this.lastStatusText = text;
1935
+ this.ui.requestRender();
1936
+ }
1937
+ addMessageToChat(message, options) {
1938
+ switch (message.role) {
1939
+ case "bashExecution": {
1940
+ const component = new BashExecutionComponent(message.command, this.ui, message.excludeFromContext);
1941
+ if (message.output) {
1942
+ component.appendOutput(message.output);
1943
+ }
1944
+ component.setComplete(message.exitCode, message.cancelled, message.truncated ? { truncated: true } : undefined, message.fullOutputPath);
1945
+ this.chatContainer.addChild(component);
1946
+ break;
1947
+ }
1948
+ case "custom": {
1949
+ if (message.display) {
1950
+ const renderer = this.session.extensionRunner?.getMessageRenderer(message.customType);
1951
+ const component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings());
1952
+ component.setExpanded(this.toolOutputExpanded);
1953
+ this.chatContainer.addChild(component);
1954
+ }
1955
+ break;
1956
+ }
1957
+ case "compactionSummary": {
1958
+ this.chatContainer.addChild(new Spacer(1));
1959
+ const component = new CompactionSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());
1960
+ component.setExpanded(this.toolOutputExpanded);
1961
+ this.chatContainer.addChild(component);
1962
+ break;
1963
+ }
1964
+ case "branchSummary": {
1965
+ this.chatContainer.addChild(new Spacer(1));
1966
+ const component = new BranchSummaryMessageComponent(message, this.getMarkdownThemeWithSettings());
1967
+ component.setExpanded(this.toolOutputExpanded);
1968
+ this.chatContainer.addChild(component);
1969
+ break;
1970
+ }
1971
+ case "user": {
1972
+ const textContent = this.getUserMessageText(message);
1973
+ if (textContent) {
1974
+ const skillBlock = parseSkillBlock(textContent);
1975
+ if (skillBlock) {
1976
+ // Render skill block (collapsible)
1977
+ this.chatContainer.addChild(new Spacer(1));
1978
+ const component = new SkillInvocationMessageComponent(skillBlock, this.getMarkdownThemeWithSettings());
1979
+ component.setExpanded(this.toolOutputExpanded);
1980
+ this.chatContainer.addChild(component);
1981
+ // Render user message separately if present
1982
+ if (skillBlock.userMessage) {
1983
+ const userComponent = new UserMessageComponent(skillBlock.userMessage, this.getMarkdownThemeWithSettings());
1984
+ this.chatContainer.addChild(userComponent);
1985
+ }
1986
+ }
1987
+ else {
1988
+ const userComponent = new UserMessageComponent(textContent, this.getMarkdownThemeWithSettings());
1989
+ this.chatContainer.addChild(userComponent);
1990
+ }
1991
+ if (options?.populateHistory) {
1992
+ this.editor.addToHistory?.(textContent);
1993
+ }
1994
+ }
1995
+ break;
1996
+ }
1997
+ case "assistant": {
1998
+ const assistantComponent = new AssistantMessageComponent(message, this.hideThinkingBlock, this.getMarkdownThemeWithSettings());
1999
+ this.chatContainer.addChild(assistantComponent);
2000
+ break;
2001
+ }
2002
+ case "toolResult": {
2003
+ // Tool results are rendered inline with tool calls, handled separately
2004
+ break;
2005
+ }
2006
+ default: {
2007
+ const _exhaustive = message;
2008
+ }
2009
+ }
2010
+ }
2011
+ /**
2012
+ * Render session context to chat. Used for initial load and rebuild after compaction.
2013
+ * @param sessionContext Session context to render
2014
+ * @param options.updateFooter Update footer state
2015
+ * @param options.populateHistory Add user messages to editor history
2016
+ */
2017
+ renderSessionContext(sessionContext, options = {}) {
2018
+ this.pendingTools.clear();
2019
+ if (options.updateFooter) {
2020
+ this.footer.invalidate();
2021
+ this.updateEditorBorderColor();
2022
+ }
2023
+ for (const message of sessionContext.messages) {
2024
+ // Assistant messages need special handling for tool calls
2025
+ if (message.role === "assistant") {
2026
+ this.addMessageToChat(message);
2027
+ // Render tool call components
2028
+ for (const content of message.content) {
2029
+ if (content.type === "toolCall") {
2030
+ const component = new ToolExecutionComponent(content.name, content.arguments, { showImages: this.settingsManager.getShowImages() }, this.getRegisteredToolDefinition(content.name), this.ui);
2031
+ component.setExpanded(this.toolOutputExpanded);
2032
+ this.chatContainer.addChild(component);
2033
+ if (message.stopReason === "aborted" || message.stopReason === "error") {
2034
+ let errorMessage;
2035
+ if (message.stopReason === "aborted") {
2036
+ const retryAttempt = this.session.retryAttempt;
2037
+ errorMessage =
2038
+ retryAttempt > 0
2039
+ ? `Aborted after ${retryAttempt} retry attempt${retryAttempt > 1 ? "s" : ""}`
2040
+ : "Operation aborted";
2041
+ }
2042
+ else {
2043
+ errorMessage = message.errorMessage || "Error";
2044
+ }
2045
+ component.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true });
2046
+ }
2047
+ else {
2048
+ this.pendingTools.set(content.id, component);
2049
+ }
2050
+ }
2051
+ }
2052
+ }
2053
+ else if (message.role === "toolResult") {
2054
+ // Match tool results to pending tool components
2055
+ const component = this.pendingTools.get(message.toolCallId);
2056
+ if (component) {
2057
+ component.updateResult(message);
2058
+ this.pendingTools.delete(message.toolCallId);
2059
+ }
2060
+ }
2061
+ else {
2062
+ // All other messages use standard rendering
2063
+ this.addMessageToChat(message, options);
2064
+ }
2065
+ }
2066
+ this.pendingTools.clear();
2067
+ this.ui.requestRender();
2068
+ }
2069
+ renderInitialMessages() {
2070
+ // Get aligned messages and entries from session context
2071
+ const context = this.sessionManager.buildSessionContext();
2072
+ this.renderSessionContext(context, {
2073
+ updateFooter: true,
2074
+ populateHistory: true,
2075
+ });
2076
+ // Show compaction info if session was compacted
2077
+ const allEntries = this.sessionManager.getEntries();
2078
+ const compactionCount = allEntries.filter((e) => e.type === "compaction").length;
2079
+ if (compactionCount > 0) {
2080
+ const times = compactionCount === 1 ? "1 time" : `${compactionCount} times`;
2081
+ this.showStatus(`Session compacted ${times}`);
2082
+ }
2083
+ }
2084
+ async getUserInput() {
2085
+ return new Promise((resolve) => {
2086
+ this.onInputCallback = (text) => {
2087
+ this.onInputCallback = undefined;
2088
+ resolve(text);
2089
+ };
2090
+ });
2091
+ }
2092
+ rebuildChatFromMessages() {
2093
+ this.chatContainer.clear();
2094
+ const context = this.sessionManager.buildSessionContext();
2095
+ this.renderSessionContext(context);
2096
+ }
2097
+ // =========================================================================
2098
+ // Key handlers
2099
+ // =========================================================================
2100
+ handleCtrlC() {
2101
+ const now = Date.now();
2102
+ if (now - this.lastSigintTime < 500) {
2103
+ void this.shutdown();
2104
+ }
2105
+ else {
2106
+ this.clearEditor();
2107
+ this.lastSigintTime = now;
2108
+ }
2109
+ }
2110
+ handleCtrlD() {
2111
+ // Only called when editor is empty (enforced by CustomEditor)
2112
+ void this.shutdown();
2113
+ }
2114
+ async shutdown() {
2115
+ if (this.isShuttingDown)
2116
+ return;
2117
+ this.isShuttingDown = true;
2118
+ // Emit shutdown event to extensions
2119
+ const extensionRunner = this.session.extensionRunner;
2120
+ if (extensionRunner?.hasHandlers("session_shutdown")) {
2121
+ await extensionRunner.emit({
2122
+ type: "session_shutdown",
2123
+ });
2124
+ }
2125
+ // Wait for any pending renders to complete
2126
+ // requestRender() uses process.nextTick(), so we wait one tick
2127
+ await new Promise((resolve) => process.nextTick(resolve));
2128
+ // Drain any in-flight Kitty key release events before stopping.
2129
+ // This prevents escape sequences from leaking to the parent shell over slow SSH.
2130
+ await this.ui.terminal.drainInput(1000);
2131
+ this.stop();
2132
+ process.exit(0);
2133
+ }
2134
+ /**
2135
+ * Check if shutdown was requested and perform shutdown if so.
2136
+ */
2137
+ async checkShutdownRequested() {
2138
+ if (!this.shutdownRequested)
2139
+ return;
2140
+ await this.shutdown();
2141
+ }
2142
+ handleCtrlZ() {
2143
+ // Ignore SIGINT while suspended so Ctrl+C in the terminal does not
2144
+ // kill the backgrounded process. The handler is removed on resume.
2145
+ const ignoreSigint = () => { };
2146
+ process.on("SIGINT", ignoreSigint);
2147
+ // Set up handler to restore TUI when resumed
2148
+ process.once("SIGCONT", () => {
2149
+ process.removeListener("SIGINT", ignoreSigint);
2150
+ this.ui.start();
2151
+ this.ui.requestRender(true);
2152
+ });
2153
+ // Stop the TUI (restore terminal to normal mode)
2154
+ this.ui.stop();
2155
+ // Send SIGTSTP to process group (pid=0 means all processes in group)
2156
+ process.kill(0, "SIGTSTP");
2157
+ }
2158
+ async handleFollowUp() {
2159
+ const text = (this.editor.getExpandedText?.() ?? this.editor.getText()).trim();
2160
+ if (!text)
2161
+ return;
2162
+ // Queue input during compaction (extension commands execute immediately)
2163
+ if (this.session.isCompacting) {
2164
+ if (this.isExtensionCommand(text)) {
2165
+ this.editor.addToHistory?.(text);
2166
+ this.editor.setText("");
2167
+ await this.session.prompt(text);
2168
+ }
2169
+ else {
2170
+ this.queueCompactionMessage(text, "followUp");
2171
+ }
2172
+ return;
2173
+ }
2174
+ // Alt+Enter queues a follow-up message (waits until agent finishes)
2175
+ // This handles extension commands (execute immediately), prompt template expansion, and queueing
2176
+ if (this.session.isStreaming) {
2177
+ this.editor.addToHistory?.(text);
2178
+ this.editor.setText("");
2179
+ await this.session.prompt(text, { streamingBehavior: "followUp" });
2180
+ this.updatePendingMessagesDisplay();
2181
+ this.ui.requestRender();
2182
+ }
2183
+ // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
2184
+ else if (this.editor.onSubmit) {
2185
+ this.editor.onSubmit(text);
2186
+ }
2187
+ }
2188
+ handleDequeue() {
2189
+ const restored = this.restoreQueuedMessagesToEditor();
2190
+ if (restored === 0) {
2191
+ this.showStatus("No queued messages to restore");
2192
+ }
2193
+ else {
2194
+ this.showStatus(`Restored ${restored} queued message${restored > 1 ? "s" : ""} to editor`);
2195
+ }
2196
+ }
2197
+ updateEditorBorderColor() {
2198
+ if (this.isBashMode) {
2199
+ this.editor.borderColor = theme.getBashModeBorderColor();
2200
+ }
2201
+ else {
2202
+ const level = this.session.thinkingLevel || "off";
2203
+ this.editor.borderColor = theme.getThinkingBorderColor(level);
2204
+ }
2205
+ this.ui.requestRender();
2206
+ }
2207
+ cycleThinkingLevel() {
2208
+ const newLevel = this.session.cycleThinkingLevel();
2209
+ if (newLevel === undefined) {
2210
+ this.showStatus("Current model does not support thinking");
2211
+ }
2212
+ else {
2213
+ this.footer.invalidate();
2214
+ this.updateEditorBorderColor();
2215
+ this.showStatus(`Thinking level: ${newLevel}`);
2216
+ }
2217
+ }
2218
+ async cycleModel(direction) {
2219
+ try {
2220
+ const result = await this.session.cycleModel(direction);
2221
+ if (result === undefined) {
2222
+ const msg = this.session.scopedModels.length > 0 ? "Only one model in scope" : "Only one model available";
2223
+ this.showStatus(msg);
2224
+ }
2225
+ else {
2226
+ this.footer.invalidate();
2227
+ this.updateEditorBorderColor();
2228
+ const thinkingStr = result.model.reasoning && result.thinkingLevel !== "off" ? ` (thinking: ${result.thinkingLevel})` : "";
2229
+ this.showStatus(`Switched to ${result.model.name || result.model.id}${thinkingStr}`);
2230
+ }
2231
+ }
2232
+ catch (error) {
2233
+ this.showError(error instanceof Error ? error.message : String(error));
2234
+ }
2235
+ }
2236
+ toggleToolOutputExpansion() {
2237
+ this.setToolsExpanded(!this.toolOutputExpanded);
2238
+ }
2239
+ setToolsExpanded(expanded) {
2240
+ this.toolOutputExpanded = expanded;
2241
+ for (const child of this.chatContainer.children) {
2242
+ if (isExpandable(child)) {
2243
+ child.setExpanded(expanded);
2244
+ }
2245
+ }
2246
+ this.ui.requestRender();
2247
+ }
2248
+ toggleThinkingBlockVisibility() {
2249
+ this.hideThinkingBlock = !this.hideThinkingBlock;
2250
+ this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);
2251
+ // Rebuild chat from session messages
2252
+ this.chatContainer.clear();
2253
+ this.rebuildChatFromMessages();
2254
+ // If streaming, re-add the streaming component with updated visibility and re-render
2255
+ if (this.streamingComponent && this.streamingMessage) {
2256
+ this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);
2257
+ this.streamingComponent.updateContent(this.streamingMessage);
2258
+ this.chatContainer.addChild(this.streamingComponent);
2259
+ }
2260
+ this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
2261
+ }
2262
+ openExternalEditor() {
2263
+ // Determine editor (respect $VISUAL, then $EDITOR)
2264
+ const editorCmd = process.env.VISUAL || process.env.EDITOR;
2265
+ if (!editorCmd) {
2266
+ this.showWarning("No editor configured. Set $VISUAL or $EDITOR environment variable.");
2267
+ return;
2268
+ }
2269
+ const currentText = this.editor.getExpandedText?.() ?? this.editor.getText();
2270
+ const tmpFile = path.join(os.tmpdir(), `pi-editor-${Date.now()}.pi.md`);
2271
+ try {
2272
+ // Write current content to temp file
2273
+ fs.writeFileSync(tmpFile, currentText, "utf-8");
2274
+ // Stop TUI to release terminal
2275
+ this.ui.stop();
2276
+ // Split by space to support editor arguments (e.g., "code --wait")
2277
+ const [editor, ...editorArgs] = editorCmd.split(" ");
2278
+ // Spawn editor synchronously with inherited stdio for interactive editing
2279
+ const result = spawnSync(editor, [...editorArgs, tmpFile], {
2280
+ stdio: "inherit",
2281
+ });
2282
+ // On successful exit (status 0), replace editor content
2283
+ if (result.status === 0) {
2284
+ const newContent = fs.readFileSync(tmpFile, "utf-8").replace(/\n$/, "");
2285
+ this.editor.setText(newContent);
2286
+ }
2287
+ // On non-zero exit, keep original text (no action needed)
2288
+ }
2289
+ finally {
2290
+ // Clean up temp file
2291
+ try {
2292
+ fs.unlinkSync(tmpFile);
2293
+ }
2294
+ catch {
2295
+ // Ignore cleanup errors
2296
+ }
2297
+ // Restart TUI
2298
+ this.ui.start();
2299
+ // Force full re-render since external editor uses alternate screen
2300
+ this.ui.requestRender(true);
2301
+ }
2302
+ }
2303
+ // =========================================================================
2304
+ // UI helpers
2305
+ // =========================================================================
2306
+ clearEditor() {
2307
+ this.editor.setText("");
2308
+ this.ui.requestRender();
2309
+ }
2310
+ showError(errorMessage) {
2311
+ this.chatContainer.addChild(new Spacer(1));
2312
+ this.chatContainer.addChild(new Text(theme.fg("error", `Error: ${errorMessage}`), 1, 0));
2313
+ this.ui.requestRender();
2314
+ }
2315
+ showWarning(warningMessage) {
2316
+ this.chatContainer.addChild(new Spacer(1));
2317
+ this.chatContainer.addChild(new Text(theme.fg("warning", `Warning: ${warningMessage}`), 1, 0));
2318
+ this.ui.requestRender();
2319
+ }
2320
+ showNewVersionNotification(newVersion) {
2321
+ const action = theme.fg("accent", getUpdateInstruction("phi-code"));
2322
+ const updateInstruction = theme.fg("muted", `New version ${newVersion} is available. `) + action;
2323
+ const changelogUrl = theme.fg("accent", "https://github.com/badlogic/pi-mono/blob/main/packages/coding-agent/CHANGELOG.md");
2324
+ const changelogLine = theme.fg("muted", "Changelog: ") + changelogUrl;
2325
+ this.chatContainer.addChild(new Spacer(1));
2326
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
2327
+ this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction}\n${changelogLine}`, 1, 0));
2328
+ this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
2329
+ this.ui.requestRender();
2330
+ }
2331
+ /**
2332
+ * Get all queued messages (read-only).
2333
+ * Combines session queue and compaction queue.
2334
+ */
2335
+ getAllQueuedMessages() {
2336
+ return {
2337
+ steering: [
2338
+ ...this.session.getSteeringMessages(),
2339
+ ...this.compactionQueuedMessages.filter((msg) => msg.mode === "steer").map((msg) => msg.text),
2340
+ ],
2341
+ followUp: [
2342
+ ...this.session.getFollowUpMessages(),
2343
+ ...this.compactionQueuedMessages.filter((msg) => msg.mode === "followUp").map((msg) => msg.text),
2344
+ ],
2345
+ };
2346
+ }
2347
+ /**
2348
+ * Clear all queued messages and return their contents.
2349
+ * Clears both session queue and compaction queue.
2350
+ */
2351
+ clearAllQueues() {
2352
+ const { steering, followUp } = this.session.clearQueue();
2353
+ const compactionSteering = this.compactionQueuedMessages
2354
+ .filter((msg) => msg.mode === "steer")
2355
+ .map((msg) => msg.text);
2356
+ const compactionFollowUp = this.compactionQueuedMessages
2357
+ .filter((msg) => msg.mode === "followUp")
2358
+ .map((msg) => msg.text);
2359
+ this.compactionQueuedMessages = [];
2360
+ return {
2361
+ steering: [...steering, ...compactionSteering],
2362
+ followUp: [...followUp, ...compactionFollowUp],
2363
+ };
2364
+ }
2365
+ updatePendingMessagesDisplay() {
2366
+ this.pendingMessagesContainer.clear();
2367
+ const { steering: steeringMessages, followUp: followUpMessages } = this.getAllQueuedMessages();
2368
+ if (steeringMessages.length > 0 || followUpMessages.length > 0) {
2369
+ this.pendingMessagesContainer.addChild(new Spacer(1));
2370
+ for (const message of steeringMessages) {
2371
+ const text = theme.fg("dim", `Steering: ${message}`);
2372
+ this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
2373
+ }
2374
+ for (const message of followUpMessages) {
2375
+ const text = theme.fg("dim", `Follow-up: ${message}`);
2376
+ this.pendingMessagesContainer.addChild(new TruncatedText(text, 1, 0));
2377
+ }
2378
+ const dequeueHint = this.getAppKeyDisplay("dequeue");
2379
+ const hintText = theme.fg("dim", `↳ ${dequeueHint} to edit all queued messages`);
2380
+ this.pendingMessagesContainer.addChild(new TruncatedText(hintText, 1, 0));
2381
+ }
2382
+ }
2383
+ restoreQueuedMessagesToEditor(options) {
2384
+ const { steering, followUp } = this.clearAllQueues();
2385
+ const allQueued = [...steering, ...followUp];
2386
+ if (allQueued.length === 0) {
2387
+ this.updatePendingMessagesDisplay();
2388
+ if (options?.abort) {
2389
+ this.agent.abort();
2390
+ }
2391
+ return 0;
2392
+ }
2393
+ const queuedText = allQueued.join("\n\n");
2394
+ const currentText = options?.currentText ?? this.editor.getText();
2395
+ const combinedText = [queuedText, currentText].filter((t) => t.trim()).join("\n\n");
2396
+ this.editor.setText(combinedText);
2397
+ this.updatePendingMessagesDisplay();
2398
+ if (options?.abort) {
2399
+ this.agent.abort();
2400
+ }
2401
+ return allQueued.length;
2402
+ }
2403
+ queueCompactionMessage(text, mode) {
2404
+ this.compactionQueuedMessages.push({ text, mode });
2405
+ this.editor.addToHistory?.(text);
2406
+ this.editor.setText("");
2407
+ this.updatePendingMessagesDisplay();
2408
+ this.showStatus("Queued message for after compaction");
2409
+ }
2410
+ isExtensionCommand(text) {
2411
+ if (!text.startsWith("/"))
2412
+ return false;
2413
+ const extensionRunner = this.session.extensionRunner;
2414
+ if (!extensionRunner)
2415
+ return false;
2416
+ const spaceIndex = text.indexOf(" ");
2417
+ const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
2418
+ return !!extensionRunner.getCommand(commandName);
2419
+ }
2420
+ async flushCompactionQueue(options) {
2421
+ if (this.compactionQueuedMessages.length === 0) {
2422
+ return;
2423
+ }
2424
+ const queuedMessages = [...this.compactionQueuedMessages];
2425
+ this.compactionQueuedMessages = [];
2426
+ this.updatePendingMessagesDisplay();
2427
+ const restoreQueue = (error) => {
2428
+ this.session.clearQueue();
2429
+ this.compactionQueuedMessages = queuedMessages;
2430
+ this.updatePendingMessagesDisplay();
2431
+ this.showError(`Failed to send queued message${queuedMessages.length > 1 ? "s" : ""}: ${error instanceof Error ? error.message : String(error)}`);
2432
+ };
2433
+ try {
2434
+ if (options?.willRetry) {
2435
+ // When retry is pending, queue messages for the retry turn
2436
+ for (const message of queuedMessages) {
2437
+ if (this.isExtensionCommand(message.text)) {
2438
+ await this.session.prompt(message.text);
2439
+ }
2440
+ else if (message.mode === "followUp") {
2441
+ await this.session.followUp(message.text);
2442
+ }
2443
+ else {
2444
+ await this.session.steer(message.text);
2445
+ }
2446
+ }
2447
+ this.updatePendingMessagesDisplay();
2448
+ return;
2449
+ }
2450
+ // Find first non-extension-command message to use as prompt
2451
+ const firstPromptIndex = queuedMessages.findIndex((message) => !this.isExtensionCommand(message.text));
2452
+ if (firstPromptIndex === -1) {
2453
+ // All extension commands - execute them all
2454
+ for (const message of queuedMessages) {
2455
+ await this.session.prompt(message.text);
2456
+ }
2457
+ return;
2458
+ }
2459
+ // Execute any extension commands before the first prompt
2460
+ const preCommands = queuedMessages.slice(0, firstPromptIndex);
2461
+ const firstPrompt = queuedMessages[firstPromptIndex];
2462
+ const rest = queuedMessages.slice(firstPromptIndex + 1);
2463
+ for (const message of preCommands) {
2464
+ await this.session.prompt(message.text);
2465
+ }
2466
+ // Send first prompt (starts streaming)
2467
+ const promptPromise = this.session.prompt(firstPrompt.text).catch((error) => {
2468
+ restoreQueue(error);
2469
+ });
2470
+ // Queue remaining messages
2471
+ for (const message of rest) {
2472
+ if (this.isExtensionCommand(message.text)) {
2473
+ await this.session.prompt(message.text);
2474
+ }
2475
+ else if (message.mode === "followUp") {
2476
+ await this.session.followUp(message.text);
2477
+ }
2478
+ else {
2479
+ await this.session.steer(message.text);
2480
+ }
2481
+ }
2482
+ this.updatePendingMessagesDisplay();
2483
+ void promptPromise;
2484
+ }
2485
+ catch (error) {
2486
+ restoreQueue(error);
2487
+ }
2488
+ }
2489
+ /** Move pending bash components from pending area to chat */
2490
+ flushPendingBashComponents() {
2491
+ for (const component of this.pendingBashComponents) {
2492
+ this.pendingMessagesContainer.removeChild(component);
2493
+ this.chatContainer.addChild(component);
2494
+ }
2495
+ this.pendingBashComponents = [];
2496
+ }
2497
+ // =========================================================================
2498
+ // Selectors
2499
+ // =========================================================================
2500
+ /**
2501
+ * Shows a selector component in place of the editor.
2502
+ * @param create Factory that receives a `done` callback and returns the component and focus target
2503
+ */
2504
+ showSelector(create) {
2505
+ const done = () => {
2506
+ this.editorContainer.clear();
2507
+ this.editorContainer.addChild(this.editor);
2508
+ this.ui.setFocus(this.editor);
2509
+ };
2510
+ const { component, focus } = create(done);
2511
+ this.editorContainer.clear();
2512
+ this.editorContainer.addChild(component);
2513
+ this.ui.setFocus(focus);
2514
+ this.ui.requestRender();
2515
+ }
2516
+ showSettingsSelector() {
2517
+ this.showSelector((done) => {
2518
+ const selector = new SettingsSelectorComponent({
2519
+ autoCompact: this.session.autoCompactionEnabled,
2520
+ showImages: this.settingsManager.getShowImages(),
2521
+ autoResizeImages: this.settingsManager.getImageAutoResize(),
2522
+ blockImages: this.settingsManager.getBlockImages(),
2523
+ enableSkillCommands: this.settingsManager.getEnableSkillCommands(),
2524
+ steeringMode: this.session.steeringMode,
2525
+ followUpMode: this.session.followUpMode,
2526
+ transport: this.settingsManager.getTransport(),
2527
+ thinkingLevel: this.session.thinkingLevel,
2528
+ availableThinkingLevels: this.session.getAvailableThinkingLevels(),
2529
+ currentTheme: this.settingsManager.getTheme() || "dark",
2530
+ availableThemes: getAvailableThemes(),
2531
+ hideThinkingBlock: this.hideThinkingBlock,
2532
+ collapseChangelog: this.settingsManager.getCollapseChangelog(),
2533
+ doubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),
2534
+ treeFilterMode: this.settingsManager.getTreeFilterMode(),
2535
+ showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
2536
+ editorPaddingX: this.settingsManager.getEditorPaddingX(),
2537
+ autocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),
2538
+ quietStartup: this.settingsManager.getQuietStartup(),
2539
+ clearOnShrink: this.settingsManager.getClearOnShrink(),
2540
+ }, {
2541
+ onAutoCompactChange: (enabled) => {
2542
+ this.session.setAutoCompactionEnabled(enabled);
2543
+ this.footer.setAutoCompactEnabled(enabled);
2544
+ },
2545
+ onShowImagesChange: (enabled) => {
2546
+ this.settingsManager.setShowImages(enabled);
2547
+ for (const child of this.chatContainer.children) {
2548
+ if (child instanceof ToolExecutionComponent) {
2549
+ child.setShowImages(enabled);
2550
+ }
2551
+ }
2552
+ },
2553
+ onAutoResizeImagesChange: (enabled) => {
2554
+ this.settingsManager.setImageAutoResize(enabled);
2555
+ },
2556
+ onBlockImagesChange: (blocked) => {
2557
+ this.settingsManager.setBlockImages(blocked);
2558
+ },
2559
+ onEnableSkillCommandsChange: (enabled) => {
2560
+ this.settingsManager.setEnableSkillCommands(enabled);
2561
+ this.setupAutocomplete(this.fdPath);
2562
+ },
2563
+ onSteeringModeChange: (mode) => {
2564
+ this.session.setSteeringMode(mode);
2565
+ },
2566
+ onFollowUpModeChange: (mode) => {
2567
+ this.session.setFollowUpMode(mode);
2568
+ },
2569
+ onTransportChange: (transport) => {
2570
+ this.settingsManager.setTransport(transport);
2571
+ this.session.agent.setTransport(transport);
2572
+ },
2573
+ onThinkingLevelChange: (level) => {
2574
+ this.session.setThinkingLevel(level);
2575
+ this.footer.invalidate();
2576
+ this.updateEditorBorderColor();
2577
+ },
2578
+ onThemeChange: (themeName) => {
2579
+ const result = setTheme(themeName, true);
2580
+ this.settingsManager.setTheme(themeName);
2581
+ this.ui.invalidate();
2582
+ if (!result.success) {
2583
+ this.showError(`Failed to load theme "${themeName}": ${result.error}\nFell back to dark theme.`);
2584
+ }
2585
+ },
2586
+ onThemePreview: (themeName) => {
2587
+ const result = setTheme(themeName, true);
2588
+ if (result.success) {
2589
+ this.ui.invalidate();
2590
+ this.ui.requestRender();
2591
+ }
2592
+ },
2593
+ onHideThinkingBlockChange: (hidden) => {
2594
+ this.hideThinkingBlock = hidden;
2595
+ this.settingsManager.setHideThinkingBlock(hidden);
2596
+ for (const child of this.chatContainer.children) {
2597
+ if (child instanceof AssistantMessageComponent) {
2598
+ child.setHideThinkingBlock(hidden);
2599
+ }
2600
+ }
2601
+ this.chatContainer.clear();
2602
+ this.rebuildChatFromMessages();
2603
+ },
2604
+ onCollapseChangelogChange: (collapsed) => {
2605
+ this.settingsManager.setCollapseChangelog(collapsed);
2606
+ },
2607
+ onQuietStartupChange: (enabled) => {
2608
+ this.settingsManager.setQuietStartup(enabled);
2609
+ },
2610
+ onDoubleEscapeActionChange: (action) => {
2611
+ this.settingsManager.setDoubleEscapeAction(action);
2612
+ },
2613
+ onTreeFilterModeChange: (mode) => {
2614
+ this.settingsManager.setTreeFilterMode(mode);
2615
+ },
2616
+ onShowHardwareCursorChange: (enabled) => {
2617
+ this.settingsManager.setShowHardwareCursor(enabled);
2618
+ this.ui.setShowHardwareCursor(enabled);
2619
+ },
2620
+ onEditorPaddingXChange: (padding) => {
2621
+ this.settingsManager.setEditorPaddingX(padding);
2622
+ this.defaultEditor.setPaddingX(padding);
2623
+ if (this.editor !== this.defaultEditor && this.editor.setPaddingX !== undefined) {
2624
+ this.editor.setPaddingX(padding);
2625
+ }
2626
+ },
2627
+ onAutocompleteMaxVisibleChange: (maxVisible) => {
2628
+ this.settingsManager.setAutocompleteMaxVisible(maxVisible);
2629
+ this.defaultEditor.setAutocompleteMaxVisible(maxVisible);
2630
+ if (this.editor !== this.defaultEditor && this.editor.setAutocompleteMaxVisible !== undefined) {
2631
+ this.editor.setAutocompleteMaxVisible(maxVisible);
2632
+ }
2633
+ },
2634
+ onClearOnShrinkChange: (enabled) => {
2635
+ this.settingsManager.setClearOnShrink(enabled);
2636
+ this.ui.setClearOnShrink(enabled);
2637
+ },
2638
+ onCancel: () => {
2639
+ done();
2640
+ this.ui.requestRender();
2641
+ },
2642
+ });
2643
+ return { component: selector, focus: selector.getSettingsList() };
2644
+ });
2645
+ }
2646
+ async handleModelCommand(searchTerm) {
2647
+ if (!searchTerm) {
2648
+ this.showModelSelector();
2649
+ return;
2650
+ }
2651
+ const model = await this.findExactModelMatch(searchTerm);
2652
+ if (model) {
2653
+ try {
2654
+ await this.session.setModel(model);
2655
+ this.footer.invalidate();
2656
+ this.updateEditorBorderColor();
2657
+ this.showStatus(`Model: ${model.id}`);
2658
+ this.checkDaxnutsEasterEgg(model);
2659
+ }
2660
+ catch (error) {
2661
+ this.showError(error instanceof Error ? error.message : String(error));
2662
+ }
2663
+ return;
2664
+ }
2665
+ this.showModelSelector(searchTerm);
2666
+ }
2667
+ async findExactModelMatch(searchTerm) {
2668
+ const term = searchTerm.trim();
2669
+ if (!term)
2670
+ return undefined;
2671
+ let targetProvider;
2672
+ let targetModelId = "";
2673
+ if (term.includes("/")) {
2674
+ const parts = term.split("/", 2);
2675
+ targetProvider = parts[0]?.trim().toLowerCase();
2676
+ targetModelId = parts[1]?.trim().toLowerCase() ?? "";
2677
+ }
2678
+ else {
2679
+ targetModelId = term.toLowerCase();
2680
+ }
2681
+ if (!targetModelId)
2682
+ return undefined;
2683
+ const models = await this.getModelCandidates();
2684
+ const exactMatches = models.filter((item) => {
2685
+ const idMatch = item.id.toLowerCase() === targetModelId;
2686
+ const providerMatch = !targetProvider || item.provider.toLowerCase() === targetProvider;
2687
+ return idMatch && providerMatch;
2688
+ });
2689
+ return exactMatches.length === 1 ? exactMatches[0] : undefined;
2690
+ }
2691
+ async getModelCandidates() {
2692
+ if (this.session.scopedModels.length > 0) {
2693
+ return this.session.scopedModels.map((scoped) => scoped.model);
2694
+ }
2695
+ this.session.modelRegistry.refresh();
2696
+ try {
2697
+ return await this.session.modelRegistry.getAvailable();
2698
+ }
2699
+ catch {
2700
+ return [];
2701
+ }
2702
+ }
2703
+ /** Update the footer's available provider count from current model candidates */
2704
+ async updateAvailableProviderCount() {
2705
+ const models = await this.getModelCandidates();
2706
+ const uniqueProviders = new Set(models.map((m) => m.provider));
2707
+ this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);
2708
+ }
2709
+ showModelSelector(initialSearchInput) {
2710
+ this.showSelector((done) => {
2711
+ const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRegistry, this.session.scopedModels, async (model) => {
2712
+ try {
2713
+ await this.session.setModel(model);
2714
+ this.footer.invalidate();
2715
+ this.updateEditorBorderColor();
2716
+ done();
2717
+ this.showStatus(`Model: ${model.id}`);
2718
+ this.checkDaxnutsEasterEgg(model);
2719
+ }
2720
+ catch (error) {
2721
+ done();
2722
+ this.showError(error instanceof Error ? error.message : String(error));
2723
+ }
2724
+ }, () => {
2725
+ done();
2726
+ this.ui.requestRender();
2727
+ }, initialSearchInput);
2728
+ return { component: selector, focus: selector };
2729
+ });
2730
+ }
2731
+ async showModelsSelector() {
2732
+ // Get all available models
2733
+ this.session.modelRegistry.refresh();
2734
+ const allModels = this.session.modelRegistry.getAvailable();
2735
+ if (allModels.length === 0) {
2736
+ this.showStatus("No models available");
2737
+ return;
2738
+ }
2739
+ // Check if session has scoped models (from previous session-only changes or CLI --models)
2740
+ const sessionScopedModels = this.session.scopedModels;
2741
+ const hasSessionScope = sessionScopedModels.length > 0;
2742
+ // Build enabled model IDs from session state or settings
2743
+ const enabledModelIds = new Set();
2744
+ let hasFilter = false;
2745
+ if (hasSessionScope) {
2746
+ // Use current session's scoped models
2747
+ for (const sm of sessionScopedModels) {
2748
+ enabledModelIds.add(`${sm.model.provider}/${sm.model.id}`);
2749
+ }
2750
+ hasFilter = true;
2751
+ }
2752
+ else {
2753
+ // Fall back to settings
2754
+ const patterns = this.settingsManager.getEnabledModels();
2755
+ if (patterns !== undefined && patterns.length > 0) {
2756
+ hasFilter = true;
2757
+ const scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);
2758
+ for (const sm of scopedModels) {
2759
+ enabledModelIds.add(`${sm.model.provider}/${sm.model.id}`);
2760
+ }
2761
+ }
2762
+ }
2763
+ // Track current enabled state (session-only until persisted)
2764
+ const currentEnabledIds = new Set(enabledModelIds);
2765
+ let currentHasFilter = hasFilter;
2766
+ // Helper to update session's scoped models (session-only, no persist)
2767
+ const updateSessionModels = async (enabledIds) => {
2768
+ if (enabledIds.size > 0 && enabledIds.size < allModels.length) {
2769
+ const newScopedModels = await resolveModelScope(Array.from(enabledIds), this.session.modelRegistry);
2770
+ this.session.setScopedModels(newScopedModels.map((sm) => ({
2771
+ model: sm.model,
2772
+ thinkingLevel: sm.thinkingLevel,
2773
+ })));
2774
+ }
2775
+ else {
2776
+ // All enabled or none enabled = no filter
2777
+ this.session.setScopedModels([]);
2778
+ }
2779
+ await this.updateAvailableProviderCount();
2780
+ this.ui.requestRender();
2781
+ };
2782
+ this.showSelector((done) => {
2783
+ const selector = new ScopedModelsSelectorComponent({
2784
+ allModels,
2785
+ enabledModelIds: currentEnabledIds,
2786
+ hasEnabledModelsFilter: currentHasFilter,
2787
+ }, {
2788
+ onModelToggle: async (modelId, enabled) => {
2789
+ if (enabled) {
2790
+ currentEnabledIds.add(modelId);
2791
+ }
2792
+ else {
2793
+ currentEnabledIds.delete(modelId);
2794
+ }
2795
+ currentHasFilter = true;
2796
+ await updateSessionModels(currentEnabledIds);
2797
+ },
2798
+ onEnableAll: async (allModelIds) => {
2799
+ currentEnabledIds.clear();
2800
+ for (const id of allModelIds) {
2801
+ currentEnabledIds.add(id);
2802
+ }
2803
+ currentHasFilter = false;
2804
+ await updateSessionModels(currentEnabledIds);
2805
+ },
2806
+ onClearAll: async () => {
2807
+ currentEnabledIds.clear();
2808
+ currentHasFilter = true;
2809
+ await updateSessionModels(currentEnabledIds);
2810
+ },
2811
+ onToggleProvider: async (_provider, modelIds, enabled) => {
2812
+ for (const id of modelIds) {
2813
+ if (enabled) {
2814
+ currentEnabledIds.add(id);
2815
+ }
2816
+ else {
2817
+ currentEnabledIds.delete(id);
2818
+ }
2819
+ }
2820
+ currentHasFilter = true;
2821
+ await updateSessionModels(currentEnabledIds);
2822
+ },
2823
+ onPersist: (enabledIds) => {
2824
+ // Persist to settings
2825
+ const newPatterns = enabledIds.length === allModels.length
2826
+ ? undefined // All enabled = clear filter
2827
+ : enabledIds;
2828
+ this.settingsManager.setEnabledModels(newPatterns);
2829
+ this.showStatus("Model selection saved to settings");
2830
+ },
2831
+ onCancel: () => {
2832
+ done();
2833
+ this.ui.requestRender();
2834
+ },
2835
+ });
2836
+ return { component: selector, focus: selector };
2837
+ });
2838
+ }
2839
+ showUserMessageSelector() {
2840
+ const userMessages = this.session.getUserMessagesForForking();
2841
+ if (userMessages.length === 0) {
2842
+ this.showStatus("No messages to fork from");
2843
+ return;
2844
+ }
2845
+ this.showSelector((done) => {
2846
+ const selector = new UserMessageSelectorComponent(userMessages.map((m) => ({ id: m.entryId, text: m.text })), async (entryId) => {
2847
+ const result = await this.session.fork(entryId);
2848
+ if (result.cancelled) {
2849
+ // Extension cancelled the fork
2850
+ done();
2851
+ this.ui.requestRender();
2852
+ return;
2853
+ }
2854
+ this.chatContainer.clear();
2855
+ this.renderInitialMessages();
2856
+ this.editor.setText(result.selectedText);
2857
+ done();
2858
+ this.showStatus("Branched to new session");
2859
+ }, () => {
2860
+ done();
2861
+ this.ui.requestRender();
2862
+ });
2863
+ return { component: selector, focus: selector.getMessageList() };
2864
+ });
2865
+ }
2866
+ showTreeSelector(initialSelectedId) {
2867
+ const tree = this.sessionManager.getTree();
2868
+ const realLeafId = this.sessionManager.getLeafId();
2869
+ const initialFilterMode = this.settingsManager.getTreeFilterMode();
2870
+ if (tree.length === 0) {
2871
+ this.showStatus("No entries in session");
2872
+ return;
2873
+ }
2874
+ this.showSelector((done) => {
2875
+ const selector = new TreeSelectorComponent(tree, realLeafId, this.ui.terminal.rows, async (entryId) => {
2876
+ // Selecting the current leaf is a no-op (already there)
2877
+ if (entryId === realLeafId) {
2878
+ done();
2879
+ this.showStatus("Already at this point");
2880
+ return;
2881
+ }
2882
+ // Ask about summarization
2883
+ done(); // Close selector first
2884
+ // Loop until user makes a complete choice or cancels to tree
2885
+ let wantsSummary = false;
2886
+ let customInstructions;
2887
+ // Check if we should skip the prompt (user preference to always default to no summary)
2888
+ if (!this.settingsManager.getBranchSummarySkipPrompt()) {
2889
+ while (true) {
2890
+ const summaryChoice = await this.showExtensionSelector("Summarize branch?", [
2891
+ "No summary",
2892
+ "Summarize",
2893
+ "Summarize with custom prompt",
2894
+ ]);
2895
+ if (summaryChoice === undefined) {
2896
+ // User pressed escape - re-show tree selector with same selection
2897
+ this.showTreeSelector(entryId);
2898
+ return;
2899
+ }
2900
+ wantsSummary = summaryChoice !== "No summary";
2901
+ if (summaryChoice === "Summarize with custom prompt") {
2902
+ customInstructions = await this.showExtensionEditor("Custom summarization instructions");
2903
+ if (customInstructions === undefined) {
2904
+ // User cancelled - loop back to summary selector
2905
+ continue;
2906
+ }
2907
+ }
2908
+ // User made a complete choice
2909
+ break;
2910
+ }
2911
+ }
2912
+ // Set up escape handler and loader if summarizing
2913
+ let summaryLoader;
2914
+ const originalOnEscape = this.defaultEditor.onEscape;
2915
+ if (wantsSummary) {
2916
+ this.defaultEditor.onEscape = () => {
2917
+ this.session.abortBranchSummary();
2918
+ };
2919
+ this.chatContainer.addChild(new Spacer(1));
2920
+ summaryLoader = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), `Summarizing branch... (${appKey(this.keybindings, "interrupt")} to cancel)`);
2921
+ this.statusContainer.addChild(summaryLoader);
2922
+ this.ui.requestRender();
2923
+ }
2924
+ try {
2925
+ const result = await this.session.navigateTree(entryId, {
2926
+ summarize: wantsSummary,
2927
+ customInstructions,
2928
+ });
2929
+ if (result.aborted) {
2930
+ // Summarization aborted - re-show tree selector with same selection
2931
+ this.showStatus("Branch summarization cancelled");
2932
+ this.showTreeSelector(entryId);
2933
+ return;
2934
+ }
2935
+ if (result.cancelled) {
2936
+ this.showStatus("Navigation cancelled");
2937
+ return;
2938
+ }
2939
+ // Update UI
2940
+ this.chatContainer.clear();
2941
+ this.renderInitialMessages();
2942
+ if (result.editorText && !this.editor.getText().trim()) {
2943
+ this.editor.setText(result.editorText);
2944
+ }
2945
+ this.showStatus("Navigated to selected point");
2946
+ }
2947
+ catch (error) {
2948
+ this.showError(error instanceof Error ? error.message : String(error));
2949
+ }
2950
+ finally {
2951
+ if (summaryLoader) {
2952
+ summaryLoader.stop();
2953
+ this.statusContainer.clear();
2954
+ }
2955
+ this.defaultEditor.onEscape = originalOnEscape;
2956
+ }
2957
+ }, () => {
2958
+ done();
2959
+ this.ui.requestRender();
2960
+ }, (entryId, label) => {
2961
+ this.sessionManager.appendLabelChange(entryId, label);
2962
+ this.ui.requestRender();
2963
+ }, initialSelectedId, initialFilterMode);
2964
+ return { component: selector, focus: selector };
2965
+ });
2966
+ }
2967
+ showSessionSelector() {
2968
+ this.showSelector((done) => {
2969
+ const selector = new SessionSelectorComponent((onProgress) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress), SessionManager.listAll, async (sessionPath) => {
2970
+ done();
2971
+ await this.handleResumeSession(sessionPath);
2972
+ }, () => {
2973
+ done();
2974
+ this.ui.requestRender();
2975
+ }, () => {
2976
+ void this.shutdown();
2977
+ }, () => this.ui.requestRender(), {
2978
+ renameSession: async (sessionFilePath, nextName) => {
2979
+ const next = (nextName ?? "").trim();
2980
+ if (!next)
2981
+ return;
2982
+ const mgr = SessionManager.open(sessionFilePath);
2983
+ mgr.appendSessionInfo(next);
2984
+ },
2985
+ showRenameHint: true,
2986
+ keybindings: this.keybindings,
2987
+ }, this.sessionManager.getSessionFile());
2988
+ return { component: selector, focus: selector };
2989
+ });
2990
+ }
2991
+ async handleResumeSession(sessionPath) {
2992
+ // Stop loading animation
2993
+ if (this.loadingAnimation) {
2994
+ this.loadingAnimation.stop();
2995
+ this.loadingAnimation = undefined;
2996
+ }
2997
+ this.statusContainer.clear();
2998
+ // Clear UI state
2999
+ this.pendingMessagesContainer.clear();
3000
+ this.compactionQueuedMessages = [];
3001
+ this.streamingComponent = undefined;
3002
+ this.streamingMessage = undefined;
3003
+ this.pendingTools.clear();
3004
+ // Switch session via AgentSession (emits extension session events)
3005
+ await this.session.switchSession(sessionPath);
3006
+ // Clear and re-render the chat
3007
+ this.chatContainer.clear();
3008
+ this.renderInitialMessages();
3009
+ this.showStatus("Resumed session");
3010
+ }
3011
+ async showOAuthSelector(mode) {
3012
+ if (mode === "logout") {
3013
+ const providers = this.session.modelRegistry.authStorage.list();
3014
+ const loggedInProviders = providers.filter((p) => this.session.modelRegistry.authStorage.get(p)?.type === "oauth");
3015
+ if (loggedInProviders.length === 0) {
3016
+ this.showStatus("No OAuth providers logged in. Use /login first.");
3017
+ return;
3018
+ }
3019
+ }
3020
+ this.showSelector((done) => {
3021
+ const selector = new OAuthSelectorComponent(mode, this.session.modelRegistry.authStorage, async (providerId) => {
3022
+ done();
3023
+ if (mode === "login") {
3024
+ await this.showLoginDialog(providerId);
3025
+ }
3026
+ else {
3027
+ // Logout flow
3028
+ const providerInfo = this.session.modelRegistry.authStorage
3029
+ .getOAuthProviders()
3030
+ .find((p) => p.id === providerId);
3031
+ const providerName = providerInfo?.name || providerId;
3032
+ try {
3033
+ this.session.modelRegistry.authStorage.logout(providerId);
3034
+ this.session.modelRegistry.refresh();
3035
+ await this.updateAvailableProviderCount();
3036
+ this.showStatus(`Logged out of ${providerName}`);
3037
+ }
3038
+ catch (error) {
3039
+ this.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);
3040
+ }
3041
+ }
3042
+ }, () => {
3043
+ done();
3044
+ this.ui.requestRender();
3045
+ });
3046
+ return { component: selector, focus: selector };
3047
+ });
3048
+ }
3049
+ async showLoginDialog(providerId) {
3050
+ const providerInfo = this.session.modelRegistry.authStorage.getOAuthProviders().find((p) => p.id === providerId);
3051
+ const providerName = providerInfo?.name || providerId;
3052
+ // Providers that use callback servers (can paste redirect URL)
3053
+ const usesCallbackServer = providerInfo?.usesCallbackServer ?? false;
3054
+ // Create login dialog component
3055
+ const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
3056
+ // Completion handled below
3057
+ });
3058
+ // Show dialog in editor container
3059
+ this.editorContainer.clear();
3060
+ this.editorContainer.addChild(dialog);
3061
+ this.ui.setFocus(dialog);
3062
+ this.ui.requestRender();
3063
+ // Promise for manual code input (racing with callback server)
3064
+ let manualCodeResolve;
3065
+ let manualCodeReject;
3066
+ const manualCodePromise = new Promise((resolve, reject) => {
3067
+ manualCodeResolve = resolve;
3068
+ manualCodeReject = reject;
3069
+ });
3070
+ // Restore editor helper
3071
+ const restoreEditor = () => {
3072
+ this.editorContainer.clear();
3073
+ this.editorContainer.addChild(this.editor);
3074
+ this.ui.setFocus(this.editor);
3075
+ this.ui.requestRender();
3076
+ };
3077
+ try {
3078
+ await this.session.modelRegistry.authStorage.login(providerId, {
3079
+ onAuth: (info) => {
3080
+ dialog.showAuth(info.url, info.instructions);
3081
+ if (usesCallbackServer) {
3082
+ // Show input for manual paste, racing with callback
3083
+ dialog
3084
+ .showManualInput("Paste redirect URL below, or complete login in browser:")
3085
+ .then((value) => {
3086
+ if (value && manualCodeResolve) {
3087
+ manualCodeResolve(value);
3088
+ manualCodeResolve = undefined;
3089
+ }
3090
+ })
3091
+ .catch(() => {
3092
+ if (manualCodeReject) {
3093
+ manualCodeReject(new Error("Login cancelled"));
3094
+ manualCodeReject = undefined;
3095
+ }
3096
+ });
3097
+ }
3098
+ else if (providerId === "github-copilot") {
3099
+ // GitHub Copilot polls after onAuth
3100
+ dialog.showWaiting("Waiting for browser authentication...");
3101
+ }
3102
+ // For Anthropic: onPrompt is called immediately after
3103
+ },
3104
+ onPrompt: async (prompt) => {
3105
+ return dialog.showPrompt(prompt.message, prompt.placeholder);
3106
+ },
3107
+ onProgress: (message) => {
3108
+ dialog.showProgress(message);
3109
+ },
3110
+ onManualCodeInput: () => manualCodePromise,
3111
+ signal: dialog.signal,
3112
+ });
3113
+ // Success
3114
+ restoreEditor();
3115
+ this.session.modelRegistry.refresh();
3116
+ await this.updateAvailableProviderCount();
3117
+ this.showStatus(`Logged in to ${providerName}. Credentials saved to ${getAuthPath()}`);
3118
+ }
3119
+ catch (error) {
3120
+ restoreEditor();
3121
+ const errorMsg = error instanceof Error ? error.message : String(error);
3122
+ if (errorMsg !== "Login cancelled") {
3123
+ this.showError(`Failed to login to ${providerName}: ${errorMsg}`);
3124
+ }
3125
+ }
3126
+ }
3127
+ // =========================================================================
3128
+ // Command handlers
3129
+ // =========================================================================
3130
+ async handleReloadCommand() {
3131
+ if (this.session.isStreaming) {
3132
+ this.showWarning("Wait for the current response to finish before reloading.");
3133
+ return;
3134
+ }
3135
+ if (this.session.isCompacting) {
3136
+ this.showWarning("Wait for compaction to finish before reloading.");
3137
+ return;
3138
+ }
3139
+ this.resetExtensionUI();
3140
+ const loader = new BorderedLoader(this.ui, theme, "Reloading extensions, skills, prompts, themes...", {
3141
+ cancellable: false,
3142
+ });
3143
+ const previousEditor = this.editor;
3144
+ this.editorContainer.clear();
3145
+ this.editorContainer.addChild(loader);
3146
+ this.ui.setFocus(loader);
3147
+ this.ui.requestRender();
3148
+ const dismissLoader = (editor) => {
3149
+ loader.dispose();
3150
+ this.editorContainer.clear();
3151
+ this.editorContainer.addChild(editor);
3152
+ this.ui.setFocus(editor);
3153
+ this.ui.requestRender();
3154
+ };
3155
+ try {
3156
+ await this.session.reload();
3157
+ setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
3158
+ this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
3159
+ const themeName = this.settingsManager.getTheme();
3160
+ const themeResult = themeName ? setTheme(themeName, true) : { success: true };
3161
+ if (!themeResult.success) {
3162
+ this.showError(`Failed to load theme "${themeName}": ${themeResult.error}\nFell back to dark theme.`);
3163
+ }
3164
+ const editorPaddingX = this.settingsManager.getEditorPaddingX();
3165
+ const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();
3166
+ this.defaultEditor.setPaddingX(editorPaddingX);
3167
+ this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);
3168
+ if (this.editor !== this.defaultEditor) {
3169
+ this.editor.setPaddingX?.(editorPaddingX);
3170
+ this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);
3171
+ }
3172
+ this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());
3173
+ this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
3174
+ this.setupAutocomplete(this.fdPath);
3175
+ const runner = this.session.extensionRunner;
3176
+ if (runner) {
3177
+ this.setupExtensionShortcuts(runner);
3178
+ }
3179
+ this.rebuildChatFromMessages();
3180
+ dismissLoader(this.editor);
3181
+ this.showLoadedResources({
3182
+ extensionPaths: runner?.getExtensionPaths() ?? [],
3183
+ force: false,
3184
+ showDiagnosticsWhenQuiet: true,
3185
+ });
3186
+ const modelsJsonError = this.session.modelRegistry.getError();
3187
+ if (modelsJsonError) {
3188
+ this.showError(`models.json error: ${modelsJsonError}`);
3189
+ }
3190
+ this.showStatus("Reloaded extensions, skills, prompts, themes");
3191
+ }
3192
+ catch (error) {
3193
+ dismissLoader(previousEditor);
3194
+ this.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);
3195
+ }
3196
+ }
3197
+ async handleExportCommand(text) {
3198
+ const parts = text.split(/\s+/);
3199
+ const outputPath = parts.length > 1 ? parts[1] : undefined;
3200
+ try {
3201
+ const filePath = await this.session.exportToHtml(outputPath);
3202
+ this.showStatus(`Session exported to: ${filePath}`);
3203
+ }
3204
+ catch (error) {
3205
+ this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
3206
+ }
3207
+ }
3208
+ async handleShareCommand() {
3209
+ // Check if gh is available and logged in
3210
+ try {
3211
+ const authResult = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
3212
+ if (authResult.status !== 0) {
3213
+ this.showError("GitHub CLI is not logged in. Run 'gh auth login' first.");
3214
+ return;
3215
+ }
3216
+ }
3217
+ catch {
3218
+ this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");
3219
+ return;
3220
+ }
3221
+ // Export to a temp file
3222
+ const tmpFile = path.join(os.tmpdir(), "session.html");
3223
+ try {
3224
+ await this.session.exportToHtml(tmpFile);
3225
+ }
3226
+ catch (error) {
3227
+ this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
3228
+ return;
3229
+ }
3230
+ // Show cancellable loader, replacing the editor
3231
+ const loader = new BorderedLoader(this.ui, theme, "Creating gist...");
3232
+ this.editorContainer.clear();
3233
+ this.editorContainer.addChild(loader);
3234
+ this.ui.setFocus(loader);
3235
+ this.ui.requestRender();
3236
+ const restoreEditor = () => {
3237
+ loader.dispose();
3238
+ this.editorContainer.clear();
3239
+ this.editorContainer.addChild(this.editor);
3240
+ this.ui.setFocus(this.editor);
3241
+ try {
3242
+ fs.unlinkSync(tmpFile);
3243
+ }
3244
+ catch {
3245
+ // Ignore cleanup errors
3246
+ }
3247
+ };
3248
+ // Create a secret gist asynchronously
3249
+ let proc = null;
3250
+ loader.onAbort = () => {
3251
+ proc?.kill();
3252
+ restoreEditor();
3253
+ this.showStatus("Share cancelled");
3254
+ };
3255
+ try {
3256
+ const result = await new Promise((resolve) => {
3257
+ proc = spawn("gh", ["gist", "create", "--public=false", tmpFile]);
3258
+ let stdout = "";
3259
+ let stderr = "";
3260
+ proc.stdout?.on("data", (data) => {
3261
+ stdout += data.toString();
3262
+ });
3263
+ proc.stderr?.on("data", (data) => {
3264
+ stderr += data.toString();
3265
+ });
3266
+ proc.on("close", (code) => resolve({ stdout, stderr, code }));
3267
+ });
3268
+ if (loader.signal.aborted)
3269
+ return;
3270
+ restoreEditor();
3271
+ if (result.code !== 0) {
3272
+ const errorMsg = result.stderr?.trim() || "Unknown error";
3273
+ this.showError(`Failed to create gist: ${errorMsg}`);
3274
+ return;
3275
+ }
3276
+ // Extract gist ID from the URL returned by gh
3277
+ // gh returns something like: https://gist.github.com/username/GIST_ID
3278
+ const gistUrl = result.stdout?.trim();
3279
+ const gistId = gistUrl?.split("/").pop();
3280
+ if (!gistId) {
3281
+ this.showError("Failed to parse gist ID from gh output");
3282
+ return;
3283
+ }
3284
+ // Create the preview URL
3285
+ const previewUrl = getShareViewerUrl(gistId);
3286
+ this.showStatus(`Share URL: ${previewUrl}\nGist: ${gistUrl}`);
3287
+ }
3288
+ catch (error) {
3289
+ if (!loader.signal.aborted) {
3290
+ restoreEditor();
3291
+ this.showError(`Failed to create gist: ${error instanceof Error ? error.message : "Unknown error"}`);
3292
+ }
3293
+ }
3294
+ }
3295
+ handleCopyCommand() {
3296
+ const text = this.session.getLastAssistantText();
3297
+ if (!text) {
3298
+ this.showError("No agent messages to copy yet.");
3299
+ return;
3300
+ }
3301
+ try {
3302
+ copyToClipboard(text);
3303
+ this.showStatus("Copied last agent message to clipboard");
3304
+ }
3305
+ catch (error) {
3306
+ this.showError(error instanceof Error ? error.message : String(error));
3307
+ }
3308
+ }
3309
+ handleNameCommand(text) {
3310
+ const name = text.replace(/^\/name\s*/, "").trim();
3311
+ if (!name) {
3312
+ const currentName = this.sessionManager.getSessionName();
3313
+ if (currentName) {
3314
+ this.chatContainer.addChild(new Spacer(1));
3315
+ this.chatContainer.addChild(new Text(theme.fg("dim", `Session name: ${currentName}`), 1, 0));
3316
+ }
3317
+ else {
3318
+ this.showWarning("Usage: /name <name>");
3319
+ }
3320
+ this.ui.requestRender();
3321
+ return;
3322
+ }
3323
+ this.sessionManager.appendSessionInfo(name);
3324
+ this.updateTerminalTitle();
3325
+ this.chatContainer.addChild(new Spacer(1));
3326
+ this.chatContainer.addChild(new Text(theme.fg("dim", `Session name set: ${name}`), 1, 0));
3327
+ this.ui.requestRender();
3328
+ }
3329
+ handleSessionCommand() {
3330
+ const stats = this.session.getSessionStats();
3331
+ const sessionName = this.sessionManager.getSessionName();
3332
+ let info = `${theme.bold("Session Info")}\n\n`;
3333
+ if (sessionName) {
3334
+ info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
3335
+ }
3336
+ info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`;
3337
+ info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`;
3338
+ info += `${theme.bold("Messages")}\n`;
3339
+ info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`;
3340
+ info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`;
3341
+ info += `${theme.fg("dim", "Tool Calls:")} ${stats.toolCalls}\n`;
3342
+ info += `${theme.fg("dim", "Tool Results:")} ${stats.toolResults}\n`;
3343
+ info += `${theme.fg("dim", "Total:")} ${stats.totalMessages}\n\n`;
3344
+ info += `${theme.bold("Tokens")}\n`;
3345
+ info += `${theme.fg("dim", "Input:")} ${stats.tokens.input.toLocaleString()}\n`;
3346
+ info += `${theme.fg("dim", "Output:")} ${stats.tokens.output.toLocaleString()}\n`;
3347
+ if (stats.tokens.cacheRead > 0) {
3348
+ info += `${theme.fg("dim", "Cache Read:")} ${stats.tokens.cacheRead.toLocaleString()}\n`;
3349
+ }
3350
+ if (stats.tokens.cacheWrite > 0) {
3351
+ info += `${theme.fg("dim", "Cache Write:")} ${stats.tokens.cacheWrite.toLocaleString()}\n`;
3352
+ }
3353
+ info += `${theme.fg("dim", "Total:")} ${stats.tokens.total.toLocaleString()}\n`;
3354
+ if (stats.cost > 0) {
3355
+ info += `\n${theme.bold("Cost")}\n`;
3356
+ info += `${theme.fg("dim", "Total:")} ${stats.cost.toFixed(4)}`;
3357
+ }
3358
+ this.chatContainer.addChild(new Spacer(1));
3359
+ this.chatContainer.addChild(new Text(info, 1, 0));
3360
+ this.ui.requestRender();
3361
+ }
3362
+ handleChangelogCommand() {
3363
+ const changelogPath = getChangelogPath();
3364
+ const allEntries = parseChangelog(changelogPath);
3365
+ const changelogMarkdown = allEntries.length > 0
3366
+ ? allEntries
3367
+ .reverse()
3368
+ .map((e) => e.content)
3369
+ .join("\n\n")
3370
+ : "No changelog entries found.";
3371
+ this.chatContainer.addChild(new Spacer(1));
3372
+ this.chatContainer.addChild(new DynamicBorder());
3373
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
3374
+ this.chatContainer.addChild(new Spacer(1));
3375
+ this.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));
3376
+ this.chatContainer.addChild(new DynamicBorder());
3377
+ this.ui.requestRender();
3378
+ }
3379
+ /**
3380
+ * Capitalize keybinding for display (e.g., "ctrl+c" -> "Ctrl+C").
3381
+ */
3382
+ capitalizeKey(key) {
3383
+ return key
3384
+ .split("/")
3385
+ .map((k) => k
3386
+ .split("+")
3387
+ .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
3388
+ .join("+"))
3389
+ .join("/");
3390
+ }
3391
+ /**
3392
+ * Get capitalized display string for an app keybinding action.
3393
+ */
3394
+ getAppKeyDisplay(action) {
3395
+ return this.capitalizeKey(appKey(this.keybindings, action));
3396
+ }
3397
+ /**
3398
+ * Get capitalized display string for an editor keybinding action.
3399
+ */
3400
+ getEditorKeyDisplay(action) {
3401
+ return this.capitalizeKey(editorKey(action));
3402
+ }
3403
+ handleHotkeysCommand() {
3404
+ // Navigation keybindings
3405
+ const cursorWordLeft = this.getEditorKeyDisplay("cursorWordLeft");
3406
+ const cursorWordRight = this.getEditorKeyDisplay("cursorWordRight");
3407
+ const cursorLineStart = this.getEditorKeyDisplay("cursorLineStart");
3408
+ const cursorLineEnd = this.getEditorKeyDisplay("cursorLineEnd");
3409
+ const jumpForward = this.getEditorKeyDisplay("jumpForward");
3410
+ const jumpBackward = this.getEditorKeyDisplay("jumpBackward");
3411
+ const pageUp = this.getEditorKeyDisplay("pageUp");
3412
+ const pageDown = this.getEditorKeyDisplay("pageDown");
3413
+ // Editing keybindings
3414
+ const submit = this.getEditorKeyDisplay("submit");
3415
+ const newLine = this.getEditorKeyDisplay("newLine");
3416
+ const deleteWordBackward = this.getEditorKeyDisplay("deleteWordBackward");
3417
+ const deleteWordForward = this.getEditorKeyDisplay("deleteWordForward");
3418
+ const deleteToLineStart = this.getEditorKeyDisplay("deleteToLineStart");
3419
+ const deleteToLineEnd = this.getEditorKeyDisplay("deleteToLineEnd");
3420
+ const yank = this.getEditorKeyDisplay("yank");
3421
+ const yankPop = this.getEditorKeyDisplay("yankPop");
3422
+ const undo = this.getEditorKeyDisplay("undo");
3423
+ const tab = this.getEditorKeyDisplay("tab");
3424
+ // App keybindings
3425
+ const interrupt = this.getAppKeyDisplay("interrupt");
3426
+ const clear = this.getAppKeyDisplay("clear");
3427
+ const exit = this.getAppKeyDisplay("exit");
3428
+ const suspend = this.getAppKeyDisplay("suspend");
3429
+ const cycleThinkingLevel = this.getAppKeyDisplay("cycleThinkingLevel");
3430
+ const cycleModelForward = this.getAppKeyDisplay("cycleModelForward");
3431
+ const selectModel = this.getAppKeyDisplay("selectModel");
3432
+ const expandTools = this.getAppKeyDisplay("expandTools");
3433
+ const toggleThinking = this.getAppKeyDisplay("toggleThinking");
3434
+ const externalEditor = this.getAppKeyDisplay("externalEditor");
3435
+ const followUp = this.getAppKeyDisplay("followUp");
3436
+ const dequeue = this.getAppKeyDisplay("dequeue");
3437
+ let hotkeys = `
3438
+ **Navigation**
3439
+ | Key | Action |
3440
+ |-----|--------|
3441
+ | \`Arrow keys\` | Move cursor / browse history (Up when empty) |
3442
+ | \`${cursorWordLeft}\` / \`${cursorWordRight}\` | Move by word |
3443
+ | \`${cursorLineStart}\` | Start of line |
3444
+ | \`${cursorLineEnd}\` | End of line |
3445
+ | \`${jumpForward}\` | Jump forward to character |
3446
+ | \`${jumpBackward}\` | Jump backward to character |
3447
+ | \`${pageUp}\` / \`${pageDown}\` | Scroll by page |
3448
+
3449
+ **Editing**
3450
+ | Key | Action |
3451
+ |-----|--------|
3452
+ | \`${submit}\` | Send message |
3453
+ | \`${newLine}\` | New line${process.platform === "win32" ? " (Ctrl+Enter on Windows Terminal)" : ""} |
3454
+ | \`${deleteWordBackward}\` | Delete word backwards |
3455
+ | \`${deleteWordForward}\` | Delete word forwards |
3456
+ | \`${deleteToLineStart}\` | Delete to start of line |
3457
+ | \`${deleteToLineEnd}\` | Delete to end of line |
3458
+ | \`${yank}\` | Paste the most-recently-deleted text |
3459
+ | \`${yankPop}\` | Cycle through the deleted text after pasting |
3460
+ | \`${undo}\` | Undo |
3461
+
3462
+ **Other**
3463
+ | Key | Action |
3464
+ |-----|--------|
3465
+ | \`${tab}\` | Path completion / accept autocomplete |
3466
+ | \`${interrupt}\` | Cancel autocomplete / abort streaming |
3467
+ | \`${clear}\` | Clear editor (first) / exit (second) |
3468
+ | \`${exit}\` | Exit (when editor is empty) |
3469
+ | \`${suspend}\` | Suspend to background |
3470
+ | \`${cycleThinkingLevel}\` | Cycle thinking level |
3471
+ | \`${cycleModelForward}\` | Cycle models |
3472
+ | \`${selectModel}\` | Open model selector |
3473
+ | \`${expandTools}\` | Toggle tool output expansion |
3474
+ | \`${toggleThinking}\` | Toggle thinking block visibility |
3475
+ | \`${externalEditor}\` | Edit message in external editor |
3476
+ | \`${followUp}\` | Queue follow-up message |
3477
+ | \`${dequeue}\` | Restore queued messages |
3478
+ | \`Ctrl+V\` | Paste image from clipboard |
3479
+ | \`/\` | Slash commands |
3480
+ | \`!\` | Run bash command |
3481
+ | \`!!\` | Run bash command (excluded from context) |
3482
+ `;
3483
+ // Add extension-registered shortcuts
3484
+ const extensionRunner = this.session.extensionRunner;
3485
+ if (extensionRunner) {
3486
+ const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
3487
+ if (shortcuts.size > 0) {
3488
+ hotkeys += `
3489
+ **Extensions**
3490
+ | Key | Action |
3491
+ |-----|--------|
3492
+ `;
3493
+ for (const [key, shortcut] of shortcuts) {
3494
+ const description = shortcut.description ?? shortcut.extensionPath;
3495
+ const keyDisplay = key.replace(/\b\w/g, (c) => c.toUpperCase());
3496
+ hotkeys += `| \`${keyDisplay}\` | ${description} |\n`;
3497
+ }
3498
+ }
3499
+ }
3500
+ this.chatContainer.addChild(new Spacer(1));
3501
+ this.chatContainer.addChild(new DynamicBorder());
3502
+ this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "Keyboard Shortcuts")), 1, 0));
3503
+ this.chatContainer.addChild(new Spacer(1));
3504
+ this.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));
3505
+ this.chatContainer.addChild(new DynamicBorder());
3506
+ this.ui.requestRender();
3507
+ }
3508
+ async handleClearCommand() {
3509
+ // Stop loading animation
3510
+ if (this.loadingAnimation) {
3511
+ this.loadingAnimation.stop();
3512
+ this.loadingAnimation = undefined;
3513
+ }
3514
+ this.statusContainer.clear();
3515
+ // New session via session (emits extension session events)
3516
+ await this.session.newSession();
3517
+ // Clear UI state
3518
+ this.headerContainer.clear();
3519
+ this.chatContainer.clear();
3520
+ this.pendingMessagesContainer.clear();
3521
+ this.compactionQueuedMessages = [];
3522
+ this.streamingComponent = undefined;
3523
+ this.streamingMessage = undefined;
3524
+ this.pendingTools.clear();
3525
+ this.chatContainer.addChild(new Spacer(1));
3526
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1));
3527
+ this.ui.requestRender();
3528
+ }
3529
+ handleDebugCommand() {
3530
+ const width = this.ui.terminal.columns;
3531
+ const height = this.ui.terminal.rows;
3532
+ const allLines = this.ui.render(width);
3533
+ const debugLogPath = getDebugLogPath();
3534
+ const debugData = [
3535
+ `Debug output at ${new Date().toISOString()}`,
3536
+ `Terminal: ${width}x${height}`,
3537
+ `Total lines: ${allLines.length}`,
3538
+ "",
3539
+ "=== All rendered lines with visible widths ===",
3540
+ ...allLines.map((line, idx) => {
3541
+ const vw = visibleWidth(line);
3542
+ const escaped = JSON.stringify(line);
3543
+ return `[${idx}] (w=${vw}) ${escaped}`;
3544
+ }),
3545
+ "",
3546
+ "=== Agent messages (JSONL) ===",
3547
+ ...this.session.messages.map((msg) => JSON.stringify(msg)),
3548
+ "",
3549
+ ].join("\n");
3550
+ fs.mkdirSync(path.dirname(debugLogPath), { recursive: true });
3551
+ fs.writeFileSync(debugLogPath, debugData);
3552
+ this.chatContainer.addChild(new Spacer(1));
3553
+ this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ Debug log written")}\n${theme.fg("muted", debugLogPath)}`, 1, 1));
3554
+ this.ui.requestRender();
3555
+ }
3556
+ handleArminSaysHi() {
3557
+ this.chatContainer.addChild(new Spacer(1));
3558
+ this.chatContainer.addChild(new ArminComponent(this.ui));
3559
+ this.ui.requestRender();
3560
+ }
3561
+ handleDaxnuts() {
3562
+ this.chatContainer.addChild(new Spacer(1));
3563
+ this.chatContainer.addChild(new DaxnutsComponent(this.ui));
3564
+ this.ui.requestRender();
3565
+ }
3566
+ checkDaxnutsEasterEgg(model) {
3567
+ if (model.provider === "opencode" && model.id.toLowerCase().includes("kimi-k2.5")) {
3568
+ this.handleDaxnuts();
3569
+ }
3570
+ }
3571
+ async handleBashCommand(command, excludeFromContext = false) {
3572
+ const extensionRunner = this.session.extensionRunner;
3573
+ // Emit user_bash event to let extensions intercept
3574
+ const eventResult = extensionRunner
3575
+ ? await extensionRunner.emitUserBash({
3576
+ type: "user_bash",
3577
+ command,
3578
+ excludeFromContext,
3579
+ cwd: process.cwd(),
3580
+ })
3581
+ : undefined;
3582
+ // If extension returned a full result, use it directly
3583
+ if (eventResult?.result) {
3584
+ const result = eventResult.result;
3585
+ // Create UI component for display
3586
+ this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
3587
+ if (this.session.isStreaming) {
3588
+ this.pendingMessagesContainer.addChild(this.bashComponent);
3589
+ this.pendingBashComponents.push(this.bashComponent);
3590
+ }
3591
+ else {
3592
+ this.chatContainer.addChild(this.bashComponent);
3593
+ }
3594
+ // Show output and complete
3595
+ if (result.output) {
3596
+ this.bashComponent.appendOutput(result.output);
3597
+ }
3598
+ this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath);
3599
+ // Record the result in session
3600
+ this.session.recordBashResult(command, result, { excludeFromContext });
3601
+ this.bashComponent = undefined;
3602
+ this.ui.requestRender();
3603
+ return;
3604
+ }
3605
+ // Normal execution path (possibly with custom operations)
3606
+ const isDeferred = this.session.isStreaming;
3607
+ this.bashComponent = new BashExecutionComponent(command, this.ui, excludeFromContext);
3608
+ if (isDeferred) {
3609
+ // Show in pending area when agent is streaming
3610
+ this.pendingMessagesContainer.addChild(this.bashComponent);
3611
+ this.pendingBashComponents.push(this.bashComponent);
3612
+ }
3613
+ else {
3614
+ // Show in chat immediately when agent is idle
3615
+ this.chatContainer.addChild(this.bashComponent);
3616
+ }
3617
+ this.ui.requestRender();
3618
+ try {
3619
+ const result = await this.session.executeBash(command, (chunk) => {
3620
+ if (this.bashComponent) {
3621
+ this.bashComponent.appendOutput(chunk);
3622
+ this.ui.requestRender();
3623
+ }
3624
+ }, { excludeFromContext, operations: eventResult?.operations });
3625
+ if (this.bashComponent) {
3626
+ this.bashComponent.setComplete(result.exitCode, result.cancelled, result.truncated ? { truncated: true, content: result.output } : undefined, result.fullOutputPath);
3627
+ }
3628
+ }
3629
+ catch (error) {
3630
+ if (this.bashComponent) {
3631
+ this.bashComponent.setComplete(undefined, false);
3632
+ }
3633
+ this.showError(`Bash command failed: ${error instanceof Error ? error.message : "Unknown error"}`);
3634
+ }
3635
+ this.bashComponent = undefined;
3636
+ this.ui.requestRender();
3637
+ }
3638
+ async handleCompactCommand(customInstructions) {
3639
+ const entries = this.sessionManager.getEntries();
3640
+ const messageCount = entries.filter((e) => e.type === "message").length;
3641
+ if (messageCount < 2) {
3642
+ this.showWarning("Nothing to compact (no messages yet)");
3643
+ return;
3644
+ }
3645
+ await this.executeCompaction(customInstructions, false);
3646
+ }
3647
+ async executeCompaction(customInstructions, isAuto = false) {
3648
+ // Stop loading animation
3649
+ if (this.loadingAnimation) {
3650
+ this.loadingAnimation.stop();
3651
+ this.loadingAnimation = undefined;
3652
+ }
3653
+ this.statusContainer.clear();
3654
+ // Set up escape handler during compaction
3655
+ const originalOnEscape = this.defaultEditor.onEscape;
3656
+ this.defaultEditor.onEscape = () => {
3657
+ this.session.abortCompaction();
3658
+ };
3659
+ // Show compacting status
3660
+ this.chatContainer.addChild(new Spacer(1));
3661
+ const cancelHint = `(${appKey(this.keybindings, "interrupt")} to cancel)`;
3662
+ const label = isAuto ? `Auto-compacting context... ${cancelHint}` : `Compacting context... ${cancelHint}`;
3663
+ const compactingLoader = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), label);
3664
+ this.statusContainer.addChild(compactingLoader);
3665
+ this.ui.requestRender();
3666
+ let result;
3667
+ try {
3668
+ result = await this.session.compact(customInstructions);
3669
+ // Rebuild UI
3670
+ this.rebuildChatFromMessages();
3671
+ // Add compaction component at bottom so user sees it without scrolling
3672
+ const msg = createCompactionSummaryMessage(result.summary, result.tokensBefore, new Date().toISOString());
3673
+ this.addMessageToChat(msg);
3674
+ this.footer.invalidate();
3675
+ }
3676
+ catch (error) {
3677
+ const message = error instanceof Error ? error.message : String(error);
3678
+ if (message === "Compaction cancelled" || (error instanceof Error && error.name === "AbortError")) {
3679
+ this.showError("Compaction cancelled");
3680
+ }
3681
+ else {
3682
+ this.showError(`Compaction failed: ${message}`);
3683
+ }
3684
+ }
3685
+ finally {
3686
+ compactingLoader.stop();
3687
+ this.statusContainer.clear();
3688
+ this.defaultEditor.onEscape = originalOnEscape;
3689
+ }
3690
+ void this.flushCompactionQueue({ willRetry: false });
3691
+ return result;
3692
+ }
3693
+ stop() {
3694
+ if (this.loadingAnimation) {
3695
+ this.loadingAnimation.stop();
3696
+ this.loadingAnimation = undefined;
3697
+ }
3698
+ this.clearExtensionTerminalInputListeners();
3699
+ this.footer.dispose();
3700
+ this.footerDataProvider.dispose();
3701
+ if (this.unsubscribe) {
3702
+ this.unsubscribe();
3703
+ }
3704
+ if (this.isInitialized) {
3705
+ this.ui.stop();
3706
+ this.isInitialized = false;
3707
+ }
3708
+ }
3709
+ }
3710
+ //# sourceMappingURL=interactive-mode.js.map