@mrquake/quakecode-cli 0.64.0

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