open-pi-coding-agent 0.57.1

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