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