@eminent337/aery 0.1.11 → 1.0.0

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