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