@hyperspaceng/neural-coding-agent 0.61.2 → 0.61.3

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