@tomsun28/pizza 0.0.9 → 0.1.1

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