@eminent337/aery 0.1.57 → 0.1.58

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