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