meetsoma 0.3.2 → 0.3.3

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