@lenylvt/pi-coding-agent 0.64.0

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