@draht/coding-agent 2026.7.30 → 2026.10.4-2

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 (1229) hide show
  1. package/CHANGELOG.md +606 -0
  2. package/README.md +46 -2
  3. package/agents/debugger.md +12 -1
  4. package/agents/git-committer.md +1 -0
  5. package/agents/implementer.md +20 -0
  6. package/agents/investigator.md +75 -0
  7. package/agents/reviewer.md +7 -0
  8. package/agents/spec-reviewer.md +66 -0
  9. package/agents/verifier.md +4 -3
  10. package/bin/draht-tools.cjs +472 -41
  11. package/dist/agents/debugger.md +12 -1
  12. package/dist/agents/git-committer.md +1 -0
  13. package/dist/agents/implementer.md +20 -0
  14. package/dist/agents/investigator.md +75 -0
  15. package/dist/agents/reviewer.md +7 -0
  16. package/dist/agents/spec-reviewer.md +66 -0
  17. package/dist/agents/verifier.md +4 -3
  18. package/dist/bun/cli.d.ts +1 -1
  19. package/dist/bun/cli.d.ts.map +1 -1
  20. package/dist/bun/cli.js +6 -3
  21. package/dist/bun/cli.js.map +1 -1
  22. package/dist/bun/sandbox-env-setup.d.ts +2 -0
  23. package/dist/bun/sandbox-env-setup.d.ts.map +1 -0
  24. package/dist/bun/sandbox-env-setup.js +4 -0
  25. package/dist/bun/sandbox-env-setup.js.map +1 -0
  26. package/dist/bundle/chunks/anthropic-messages-GAKYXF65.js +6 -0
  27. package/dist/bundle/chunks/anthropic.js +75 -0
  28. package/dist/bundle/chunks/azure-openai-responses-ZIXMK6JO.js +2 -0
  29. package/dist/bundle/chunks/bedrock-converse-stream.js +79 -0
  30. package/dist/bundle/chunks/chunk-2E5VODES.js +2 -0
  31. package/dist/bundle/chunks/chunk-2FBJKY7F.js +2 -0
  32. package/dist/bundle/chunks/chunk-2N4I6WXC.js +2 -0
  33. package/dist/bundle/chunks/chunk-5VZWYVZB.js +82 -0
  34. package/dist/bundle/chunks/chunk-63BK6WK2.js +2 -0
  35. package/dist/bundle/chunks/chunk-6MSE6LZ3.js +6 -0
  36. package/dist/bundle/chunks/chunk-6ZJKIMU7.js +2 -0
  37. package/dist/bundle/chunks/chunk-736QBNUZ.js +12 -0
  38. package/dist/bundle/chunks/chunk-BXSHCX3G.js +11 -0
  39. package/dist/bundle/chunks/chunk-CEJJ5XF2.js +170 -0
  40. package/dist/bundle/chunks/chunk-COF5JT7R.js +4 -0
  41. package/dist/bundle/chunks/chunk-D6TMD5Q2.js +44 -0
  42. package/dist/bundle/chunks/chunk-DPE4ALPU.js +146 -0
  43. package/dist/bundle/chunks/chunk-EBVYI75P.js +2 -0
  44. package/dist/bundle/chunks/chunk-GVXA72ZA.js +2 -0
  45. package/dist/bundle/chunks/chunk-H6FT43VC.js +137 -0
  46. package/dist/bundle/chunks/chunk-HJ72RANT.js +2 -0
  47. package/dist/bundle/chunks/chunk-HTJ3L72O.js +2 -0
  48. package/dist/bundle/chunks/chunk-HZ2UHMBT.js +2 -0
  49. package/dist/bundle/chunks/chunk-I5OKY6RH.js +11 -0
  50. package/dist/bundle/chunks/chunk-IWTUBX6V.js +4 -0
  51. package/dist/bundle/chunks/chunk-KPO5375S.js +2 -0
  52. package/dist/bundle/chunks/chunk-KVH4HR57.js +31 -0
  53. package/dist/bundle/chunks/chunk-LDAOC5RB.js +18 -0
  54. package/dist/bundle/chunks/chunk-ON6XU6AG.js +2 -0
  55. package/dist/bundle/chunks/chunk-QMN7OD6G.js +2 -0
  56. package/dist/bundle/chunks/chunk-RZKPFWMH.js +42 -0
  57. package/dist/bundle/chunks/chunk-SDRCE6OP.js +2 -0
  58. package/dist/bundle/chunks/chunk-SVNWI7EV.js +8 -0
  59. package/dist/bundle/chunks/chunk-TIA2T6EO.js +3 -0
  60. package/dist/bundle/chunks/chunk-VOFPZOUQ.js +1472 -0
  61. package/dist/bundle/chunks/chunk-XBUEMKIY.js +2 -0
  62. package/dist/bundle/chunks/chunk-XOGEYN4Q.js +2 -0
  63. package/dist/bundle/chunks/chunk-ZZD35WKM.js +2 -0
  64. package/dist/bundle/chunks/cli-SR5QBZH4.js +51 -0
  65. package/dist/bundle/chunks/cloudflare-workers-ai-system-one-MJKOAE5S.js +2 -0
  66. package/dist/bundle/chunks/codemode-worker.js +315 -0
  67. package/dist/bundle/chunks/execute-VCYDHEYA.js +328 -0
  68. package/dist/bundle/chunks/github-copilot.js +2 -0
  69. package/dist/bundle/chunks/google-antigravity.js +75 -0
  70. package/dist/bundle/chunks/google-gemini-cli.js +75 -0
  71. package/dist/bundle/chunks/google-generative-ai-RPUPQ6PM.js +2 -0
  72. package/dist/bundle/chunks/google-vertex-EZES5QVQ.js +2 -0
  73. package/dist/bundle/chunks/https-proxy-agent-O2PVUIOI.js +13 -0
  74. package/dist/bundle/chunks/image-resize-worker.js +2 -0
  75. package/dist/bundle/chunks/jiti-loader-RKXLMQV2.js +2 -0
  76. package/dist/bundle/chunks/kimi-coding.js +2 -0
  77. package/dist/bundle/chunks/lib-XOG5PI3Y.js +9 -0
  78. package/dist/bundle/chunks/llama-cpp-classify-EJ5XMSQL.js +22 -0
  79. package/dist/bundle/chunks/meta.js +2 -0
  80. package/dist/bundle/chunks/mistral-conversations-AOYGU43Y.js +5 -0
  81. package/dist/bundle/chunks/multipart-parser-AZP5BX2W.js +3 -0
  82. package/dist/bundle/chunks/node-C2JGH2OB.js +2 -0
  83. package/dist/bundle/chunks/node-LQ52KV6B.js +16 -0
  84. package/dist/bundle/chunks/openai-chatgpt.js +75 -0
  85. package/dist/bundle/chunks/openai-codex-responses-M2Y77JEQ.js +10 -0
  86. package/dist/bundle/chunks/openai-codex.js +75 -0
  87. package/dist/bundle/chunks/openai-completions-A4OKYOYV.js +7 -0
  88. package/dist/bundle/chunks/openai-responses-6IXV53T3.js +3 -0
  89. package/dist/bundle/chunks/opencode-go.js +2 -0
  90. package/dist/bundle/chunks/openrouter-images-LYV4NKFM.js +2 -0
  91. package/dist/bundle/chunks/openrouter.js +75 -0
  92. package/dist/bundle/chunks/pi-messages-KKMEUT3Z.js +8 -0
  93. package/dist/bundle/chunks/radius.js +75 -0
  94. package/dist/bundle/chunks/runtime-6YJPGSP7.js +2 -0
  95. package/dist/bundle/chunks/settings-manager-D2EG7WDO.js +2 -0
  96. package/dist/bundle/chunks/src-TIBHS42X.js +4 -0
  97. package/dist/bundle/chunks/typesafe-system-one-YBEEY5XU.js +2 -0
  98. package/dist/bundle/chunks/virtual-modules-CBOAFAFT.js +2 -0
  99. package/dist/bundle/chunks/xai.js +75 -0
  100. package/dist/bundle/cli-runtime.js +3 -0
  101. package/dist/bundle/cli.js +5 -0
  102. package/dist/bundle/index.js +2 -0
  103. package/dist/bundle/rpc-entry.js +3 -0
  104. package/dist/cli/args.d.ts +14 -0
  105. package/dist/cli/args.d.ts.map +1 -1
  106. package/dist/cli/args.js +140 -22
  107. package/dist/cli/args.js.map +1 -1
  108. package/dist/cli/attach-mode.d.ts +61 -0
  109. package/dist/cli/attach-mode.d.ts.map +1 -1
  110. package/dist/cli/attach-mode.js +243 -5
  111. package/dist/cli/attach-mode.js.map +1 -1
  112. package/dist/cli/auth-check.d.ts +19 -0
  113. package/dist/cli/auth-check.d.ts.map +1 -0
  114. package/dist/cli/auth-check.js +50 -0
  115. package/dist/cli/auth-check.js.map +1 -0
  116. package/dist/cli/auth-command.d.ts +24 -0
  117. package/dist/cli/auth-command.d.ts.map +1 -0
  118. package/dist/cli/auth-command.js +103 -0
  119. package/dist/cli/auth-command.js.map +1 -0
  120. package/dist/cli/config-selector.d.ts.map +1 -1
  121. package/dist/cli/config-selector.js +3 -2
  122. package/dist/cli/config-selector.js.map +1 -1
  123. package/dist/cli/credential-print.d.ts +6 -4
  124. package/dist/cli/credential-print.d.ts.map +1 -1
  125. package/dist/cli/credential-print.js +47 -34
  126. package/dist/cli/credential-print.js.map +1 -1
  127. package/dist/cli/file-processor.d.ts +1 -1
  128. package/dist/cli/file-processor.d.ts.map +1 -1
  129. package/dist/cli/file-processor.js +2 -1
  130. package/dist/cli/file-processor.js.map +1 -1
  131. package/dist/cli/list-models.d.ts +1 -1
  132. package/dist/cli/list-models.d.ts.map +1 -1
  133. package/dist/cli/list-models.js +2 -2
  134. package/dist/cli/list-models.js.map +1 -1
  135. package/dist/cli/session-picker.d.ts +1 -1
  136. package/dist/cli/session-picker.d.ts.map +1 -1
  137. package/dist/cli/session-picker.js.map +1 -1
  138. package/dist/cli/setup.d.ts +2 -0
  139. package/dist/cli/setup.d.ts.map +1 -0
  140. package/dist/cli/setup.js +12 -0
  141. package/dist/cli/setup.js.map +1 -0
  142. package/dist/cli/startup-ui.d.ts +2 -2
  143. package/dist/cli/startup-ui.d.ts.map +1 -1
  144. package/dist/cli/startup-ui.js +42 -33
  145. package/dist/cli/startup-ui.js.map +1 -1
  146. package/dist/cli.js +3 -12
  147. package/dist/cli.js.map +1 -1
  148. package/dist/config.d.ts +29 -4
  149. package/dist/config.d.ts.map +1 -1
  150. package/dist/config.js +73 -10
  151. package/dist/config.js.map +1 -1
  152. package/dist/core/agent-session-runtime.d.ts +17 -1
  153. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  154. package/dist/core/agent-session-runtime.js +98 -32
  155. package/dist/core/agent-session-runtime.js.map +1 -1
  156. package/dist/core/agent-session-services.d.ts +2 -1
  157. package/dist/core/agent-session-services.d.ts.map +1 -1
  158. package/dist/core/agent-session-services.js +15 -0
  159. package/dist/core/agent-session-services.js.map +1 -1
  160. package/dist/core/agent-session.d.ts +266 -49
  161. package/dist/core/agent-session.d.ts.map +1 -1
  162. package/dist/core/agent-session.js +1503 -597
  163. package/dist/core/agent-session.js.map +1 -1
  164. package/dist/core/auth-storage.d.ts +25 -9
  165. package/dist/core/auth-storage.d.ts.map +1 -1
  166. package/dist/core/auth-storage.js +245 -45
  167. package/dist/core/auth-storage.js.map +1 -1
  168. package/dist/core/bug-report-upload.d.ts +11 -0
  169. package/dist/core/bug-report-upload.d.ts.map +1 -0
  170. package/dist/core/bug-report-upload.js +20 -0
  171. package/dist/core/bug-report-upload.js.map +1 -0
  172. package/dist/core/bug-report.d.ts +176 -0
  173. package/dist/core/bug-report.d.ts.map +1 -0
  174. package/dist/core/bug-report.js +292 -0
  175. package/dist/core/bug-report.js.map +1 -0
  176. package/dist/core/builtins/checkpoints.d.ts +20 -0
  177. package/dist/core/builtins/checkpoints.d.ts.map +1 -0
  178. package/dist/core/builtins/checkpoints.js +161 -0
  179. package/dist/core/builtins/checkpoints.js.map +1 -0
  180. package/dist/core/builtins/duet.d.ts +26 -0
  181. package/dist/core/builtins/duet.d.ts.map +1 -0
  182. package/dist/core/builtins/duet.js +660 -0
  183. package/dist/core/builtins/duet.js.map +1 -0
  184. package/dist/core/builtins/index.d.ts.map +1 -1
  185. package/dist/core/builtins/index.js +7 -1
  186. package/dist/core/builtins/index.js.map +1 -1
  187. package/dist/core/builtins/subagent.d.ts +24 -4
  188. package/dist/core/builtins/subagent.d.ts.map +1 -1
  189. package/dist/core/builtins/subagent.js +278 -35
  190. package/dist/core/builtins/subagent.js.map +1 -1
  191. package/dist/core/cache-stats.d.ts.map +1 -1
  192. package/dist/core/cache-stats.js +12 -1
  193. package/dist/core/cache-stats.js.map +1 -1
  194. package/dist/core/cache-warmer.d.ts +103 -0
  195. package/dist/core/cache-warmer.d.ts.map +1 -0
  196. package/dist/core/cache-warmer.js +356 -0
  197. package/dist/core/cache-warmer.js.map +1 -0
  198. package/dist/core/checkpoints/checkpoint-cli.d.ts +17 -0
  199. package/dist/core/checkpoints/checkpoint-cli.d.ts.map +1 -0
  200. package/dist/core/checkpoints/checkpoint-cli.js +78 -0
  201. package/dist/core/checkpoints/checkpoint-cli.js.map +1 -0
  202. package/dist/core/checkpoints/checkpoint-manager.d.ts +298 -0
  203. package/dist/core/checkpoints/checkpoint-manager.d.ts.map +1 -0
  204. package/dist/core/checkpoints/checkpoint-manager.js +901 -0
  205. package/dist/core/checkpoints/checkpoint-manager.js.map +1 -0
  206. package/dist/core/checkpoints/rewind.d.ts +143 -0
  207. package/dist/core/checkpoints/rewind.d.ts.map +1 -0
  208. package/dist/core/checkpoints/rewind.js +247 -0
  209. package/dist/core/checkpoints/rewind.js.map +1 -0
  210. package/dist/core/compaction/branch-summarization.d.ts +1 -1
  211. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  212. package/dist/core/compaction/branch-summarization.js +11 -6
  213. package/dist/core/compaction/branch-summarization.js.map +1 -1
  214. package/dist/core/compaction/compaction.d.ts +14 -6
  215. package/dist/core/compaction/compaction.d.ts.map +1 -1
  216. package/dist/core/compaction/compaction.js +221 -122
  217. package/dist/core/compaction/compaction.js.map +1 -1
  218. package/dist/core/compaction/utils.d.ts +2 -1
  219. package/dist/core/compaction/utils.d.ts.map +1 -1
  220. package/dist/core/compaction/utils.js +25 -18
  221. package/dist/core/compaction/utils.js.map +1 -1
  222. package/dist/core/crash-log.d.ts +27 -0
  223. package/dist/core/crash-log.d.ts.map +1 -0
  224. package/dist/core/crash-log.js +140 -0
  225. package/dist/core/crash-log.js.map +1 -0
  226. package/dist/core/defaults.d.ts +1 -0
  227. package/dist/core/defaults.d.ts.map +1 -1
  228. package/dist/core/defaults.js +9 -0
  229. package/dist/core/defaults.js.map +1 -1
  230. package/dist/core/experimental.js +1 -1
  231. package/dist/core/experimental.js.map +1 -1
  232. package/dist/core/export-html/template.css +10 -0
  233. package/dist/core/export-html/template.js +72 -18
  234. package/dist/core/extensions/index.d.ts +2 -2
  235. package/dist/core/extensions/index.d.ts.map +1 -1
  236. package/dist/core/extensions/index.js +1 -1
  237. package/dist/core/extensions/index.js.map +1 -1
  238. package/dist/core/extensions/jiti-loader.d.ts +2 -0
  239. package/dist/core/extensions/jiti-loader.d.ts.map +1 -0
  240. package/dist/core/extensions/jiti-loader.js +5 -0
  241. package/dist/core/extensions/jiti-loader.js.map +1 -0
  242. package/dist/core/extensions/loader.d.ts.map +1 -1
  243. package/dist/core/extensions/loader.js +298 -96
  244. package/dist/core/extensions/loader.js.map +1 -1
  245. package/dist/core/extensions/runner.d.ts +59 -9
  246. package/dist/core/extensions/runner.d.ts.map +1 -1
  247. package/dist/core/extensions/runner.js +410 -103
  248. package/dist/core/extensions/runner.js.map +1 -1
  249. package/dist/core/extensions/types.d.ts +701 -85
  250. package/dist/core/extensions/types.d.ts.map +1 -1
  251. package/dist/core/extensions/types.js +3 -0
  252. package/dist/core/extensions/types.js.map +1 -1
  253. package/dist/core/extensions/virtual-modules.d.ts +3 -0
  254. package/dist/core/extensions/virtual-modules.d.ts.map +1 -0
  255. package/dist/core/extensions/virtual-modules.js +37 -0
  256. package/dist/core/extensions/virtual-modules.js.map +1 -0
  257. package/dist/core/extensions/wrapper.d.ts +2 -2
  258. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  259. package/dist/core/extensions/wrapper.js +3 -22
  260. package/dist/core/extensions/wrapper.js.map +1 -1
  261. package/dist/core/footer-data-provider.d.ts +1 -1
  262. package/dist/core/footer-data-provider.js +19 -18
  263. package/dist/core/footer-data-provider.js.map +1 -1
  264. package/dist/core/http-dispatcher.d.ts.map +1 -1
  265. package/dist/core/http-dispatcher.js +7 -0
  266. package/dist/core/http-dispatcher.js.map +1 -1
  267. package/dist/core/index.d.ts +2 -1
  268. package/dist/core/index.d.ts.map +1 -1
  269. package/dist/core/index.js.map +1 -1
  270. package/dist/core/keybindings.d.ts +88 -13
  271. package/dist/core/keybindings.d.ts.map +1 -1
  272. package/dist/core/keybindings.js +34 -7
  273. package/dist/core/keybindings.js.map +1 -1
  274. package/dist/core/mcp-servers.d.ts +119 -0
  275. package/dist/core/mcp-servers.d.ts.map +1 -0
  276. package/dist/core/mcp-servers.js +191 -0
  277. package/dist/core/mcp-servers.js.map +1 -0
  278. package/dist/core/messages.d.ts +1 -1
  279. package/dist/core/messages.d.ts.map +1 -1
  280. package/dist/core/messages.js +1 -0
  281. package/dist/core/messages.js.map +1 -1
  282. package/dist/core/model-config.d.ts +202 -20
  283. package/dist/core/model-config.d.ts.map +1 -1
  284. package/dist/core/model-config.js +53 -18
  285. package/dist/core/model-config.js.map +1 -1
  286. package/dist/core/model-registry.d.ts +21 -3
  287. package/dist/core/model-registry.d.ts.map +1 -1
  288. package/dist/core/model-registry.js +47 -10
  289. package/dist/core/model-registry.js.map +1 -1
  290. package/dist/core/model-resolver.d.ts +7 -5
  291. package/dist/core/model-resolver.d.ts.map +1 -1
  292. package/dist/core/model-resolver.js +62 -23
  293. package/dist/core/model-resolver.js.map +1 -1
  294. package/dist/core/model-runtime.d.ts +80 -15
  295. package/dist/core/model-runtime.d.ts.map +1 -1
  296. package/dist/core/model-runtime.js +466 -120
  297. package/dist/core/model-runtime.js.map +1 -1
  298. package/dist/core/models-store.d.ts +12 -7
  299. package/dist/core/models-store.d.ts.map +1 -1
  300. package/dist/core/models-store.js +87 -18
  301. package/dist/core/models-store.js.map +1 -1
  302. package/dist/core/multi-agent/fsm.js +8 -3
  303. package/dist/core/multi-agent/fsm.js.map +1 -1
  304. package/dist/core/multi-agent/mailbox.js +1 -3
  305. package/dist/core/multi-agent/mailbox.js.map +1 -1
  306. package/dist/core/multi-agent/permission-gate.d.ts +5 -2
  307. package/dist/core/multi-agent/permission-gate.d.ts.map +1 -1
  308. package/dist/core/multi-agent/permission-gate.js +601 -37
  309. package/dist/core/multi-agent/permission-gate.js.map +1 -1
  310. package/dist/core/multi-agent/task-board.js +2 -4
  311. package/dist/core/multi-agent/task-board.js.map +1 -1
  312. package/dist/core/multi-agent/worktree.d.ts +2 -0
  313. package/dist/core/multi-agent/worktree.d.ts.map +1 -1
  314. package/dist/core/multi-agent/worktree.js +3 -5
  315. package/dist/core/multi-agent/worktree.js.map +1 -1
  316. package/dist/core/nested-tool-calls.d.ts +102 -0
  317. package/dist/core/nested-tool-calls.d.ts.map +1 -0
  318. package/dist/core/nested-tool-calls.js +178 -0
  319. package/dist/core/nested-tool-calls.js.map +1 -0
  320. package/dist/core/package-manager.d.ts +16 -0
  321. package/dist/core/package-manager.d.ts.map +1 -1
  322. package/dist/core/package-manager.js +162 -69
  323. package/dist/core/package-manager.js.map +1 -1
  324. package/dist/core/permission-relay/index.d.ts +19 -0
  325. package/dist/core/permission-relay/index.d.ts.map +1 -0
  326. package/dist/core/permission-relay/index.js +49 -0
  327. package/dist/core/permission-relay/index.js.map +1 -0
  328. package/dist/core/permission-relay/relay-ui-context.d.ts +39 -0
  329. package/dist/core/permission-relay/relay-ui-context.d.ts.map +1 -0
  330. package/dist/core/permission-relay/relay-ui-context.js +788 -0
  331. package/dist/core/permission-relay/relay-ui-context.js.map +1 -0
  332. package/dist/core/permission-relay/types.d.ts +222 -0
  333. package/dist/core/permission-relay/types.d.ts.map +1 -0
  334. package/dist/core/permission-relay/types.js +15 -0
  335. package/dist/core/permission-relay/types.js.map +1 -0
  336. package/dist/core/pi-manifest.d.ts +14 -0
  337. package/dist/core/pi-manifest.d.ts.map +1 -0
  338. package/dist/core/pi-manifest.js +36 -0
  339. package/dist/core/pi-manifest.js.map +1 -0
  340. package/dist/core/project-trust.js +2 -2
  341. package/dist/core/project-trust.js.map +1 -1
  342. package/dist/core/prompt-templates.d.ts +6 -1
  343. package/dist/core/prompt-templates.d.ts.map +1 -1
  344. package/dist/core/prompt-templates.js +63 -37
  345. package/dist/core/prompt-templates.js.map +1 -1
  346. package/dist/core/provider-attribution.js +5 -5
  347. package/dist/core/provider-attribution.js.map +1 -1
  348. package/dist/core/provider-composer.d.ts +44 -20
  349. package/dist/core/provider-composer.d.ts.map +1 -1
  350. package/dist/core/provider-composer.js +151 -51
  351. package/dist/core/provider-composer.js.map +1 -1
  352. package/dist/core/radius.d.ts +13 -0
  353. package/dist/core/radius.d.ts.map +1 -1
  354. package/dist/core/radius.js +19 -0
  355. package/dist/core/radius.js.map +1 -1
  356. package/dist/core/remote-catalog-provider.d.ts +10 -3
  357. package/dist/core/remote-catalog-provider.d.ts.map +1 -1
  358. package/dist/core/remote-catalog-provider.js +105 -81
  359. package/dist/core/remote-catalog-provider.js.map +1 -1
  360. package/dist/core/resource-loader.d.ts +28 -1
  361. package/dist/core/resource-loader.d.ts.map +1 -1
  362. package/dist/core/resource-loader.js +319 -65
  363. package/dist/core/resource-loader.js.map +1 -1
  364. package/dist/core/runtime-credentials.d.ts +5 -5
  365. package/dist/core/runtime-credentials.d.ts.map +1 -1
  366. package/dist/core/runtime-credentials.js +13 -9
  367. package/dist/core/runtime-credentials.js.map +1 -1
  368. package/dist/core/sandbox/bash-operations.d.ts +149 -0
  369. package/dist/core/sandbox/bash-operations.d.ts.map +1 -0
  370. package/dist/core/sandbox/bash-operations.js +163 -0
  371. package/dist/core/sandbox/bash-operations.js.map +1 -0
  372. package/dist/core/sandbox/env.d.ts +83 -0
  373. package/dist/core/sandbox/env.d.ts.map +1 -0
  374. package/dist/core/sandbox/env.js +123 -0
  375. package/dist/core/sandbox/env.js.map +1 -0
  376. package/dist/core/sandbox/executor.d.ts +104 -0
  377. package/dist/core/sandbox/executor.d.ts.map +1 -0
  378. package/dist/core/sandbox/executor.js +93 -0
  379. package/dist/core/sandbox/executor.js.map +1 -0
  380. package/dist/core/sandbox/index.d.ts +36 -0
  381. package/dist/core/sandbox/index.d.ts.map +1 -0
  382. package/dist/core/sandbox/index.js +36 -0
  383. package/dist/core/sandbox/index.js.map +1 -0
  384. package/dist/core/sandbox/linux.d.ts +121 -0
  385. package/dist/core/sandbox/linux.d.ts.map +1 -0
  386. package/dist/core/sandbox/linux.js +260 -0
  387. package/dist/core/sandbox/linux.js.map +1 -0
  388. package/dist/core/sandbox/policy.d.ts +142 -0
  389. package/dist/core/sandbox/policy.d.ts.map +1 -0
  390. package/dist/core/sandbox/policy.js +297 -0
  391. package/dist/core/sandbox/policy.js.map +1 -0
  392. package/dist/core/sandbox/real-path.d.ts +112 -0
  393. package/dist/core/sandbox/real-path.d.ts.map +1 -0
  394. package/dist/core/sandbox/real-path.js +158 -0
  395. package/dist/core/sandbox/real-path.js.map +1 -0
  396. package/dist/core/sandbox/seatbelt-profile.d.ts +95 -0
  397. package/dist/core/sandbox/seatbelt-profile.d.ts.map +1 -0
  398. package/dist/core/sandbox/seatbelt-profile.js +239 -0
  399. package/dist/core/sandbox/seatbelt-profile.js.map +1 -0
  400. package/dist/core/sandbox/seatbelt.d.ts +95 -0
  401. package/dist/core/sandbox/seatbelt.d.ts.map +1 -0
  402. package/dist/core/sandbox/seatbelt.js +154 -0
  403. package/dist/core/sandbox/seatbelt.js.map +1 -0
  404. package/dist/core/sandbox/self-test.d.ts +109 -0
  405. package/dist/core/sandbox/self-test.d.ts.map +1 -0
  406. package/dist/core/sandbox/self-test.js +369 -0
  407. package/dist/core/sandbox/self-test.js.map +1 -0
  408. package/dist/core/sandbox/spawn.d.ts +33 -0
  409. package/dist/core/sandbox/spawn.d.ts.map +1 -0
  410. package/dist/core/sandbox/spawn.js +87 -0
  411. package/dist/core/sandbox/spawn.js.map +1 -0
  412. package/dist/core/sdk.d.ts +7 -5
  413. package/dist/core/sdk.d.ts.map +1 -1
  414. package/dist/core/sdk.js +103 -53
  415. package/dist/core/sdk.js.map +1 -1
  416. package/dist/core/session-cwd.js +1 -0
  417. package/dist/core/session-cwd.js.map +1 -1
  418. package/dist/core/session-export.d.ts +8 -0
  419. package/dist/core/session-export.d.ts.map +1 -0
  420. package/dist/core/session-export.js +33 -0
  421. package/dist/core/session-export.js.map +1 -0
  422. package/dist/core/session-manager.d.ts +134 -15
  423. package/dist/core/session-manager.d.ts.map +1 -1
  424. package/dist/core/session-manager.js +366 -149
  425. package/dist/core/session-manager.js.map +1 -1
  426. package/dist/core/settings-diagnostics.d.ts +9 -0
  427. package/dist/core/settings-diagnostics.d.ts.map +1 -0
  428. package/dist/core/settings-diagnostics.js +21 -0
  429. package/dist/core/settings-diagnostics.js.map +1 -0
  430. package/dist/core/settings-manager.d.ts +105 -4
  431. package/dist/core/settings-manager.d.ts.map +1 -1
  432. package/dist/core/settings-manager.js +274 -40
  433. package/dist/core/settings-manager.js.map +1 -1
  434. package/dist/core/skills.d.ts +3 -1
  435. package/dist/core/skills.d.ts.map +1 -1
  436. package/dist/core/skills.js +70 -39
  437. package/dist/core/skills.js.map +1 -1
  438. package/dist/core/slash-commands.d.ts.map +1 -1
  439. package/dist/core/slash-commands.js +4 -1
  440. package/dist/core/slash-commands.js.map +1 -1
  441. package/dist/core/soak/soak-log.d.ts +298 -0
  442. package/dist/core/soak/soak-log.d.ts.map +1 -0
  443. package/dist/core/soak/soak-log.js +666 -0
  444. package/dist/core/soak/soak-log.js.map +1 -0
  445. package/dist/core/soak/soak-reader.d.ts +60 -0
  446. package/dist/core/soak/soak-reader.d.ts.map +1 -0
  447. package/dist/core/soak/soak-reader.js +106 -0
  448. package/dist/core/soak/soak-reader.js.map +1 -0
  449. package/dist/core/socket-server/discovery.d.ts +78 -1
  450. package/dist/core/socket-server/discovery.d.ts.map +1 -1
  451. package/dist/core/socket-server/discovery.js +356 -37
  452. package/dist/core/socket-server/discovery.js.map +1 -1
  453. package/dist/core/socket-server/index.d.ts +10 -4
  454. package/dist/core/socket-server/index.d.ts.map +1 -1
  455. package/dist/core/socket-server/index.js +6 -3
  456. package/dist/core/socket-server/index.js.map +1 -1
  457. package/dist/core/socket-server/permission-delivery.d.ts +125 -0
  458. package/dist/core/socket-server/permission-delivery.d.ts.map +1 -0
  459. package/dist/core/socket-server/permission-delivery.js +152 -0
  460. package/dist/core/socket-server/permission-delivery.js.map +1 -0
  461. package/dist/core/socket-server/permission-registry.d.ts +301 -0
  462. package/dist/core/socket-server/permission-registry.d.ts.map +1 -0
  463. package/dist/core/socket-server/permission-registry.js +410 -0
  464. package/dist/core/socket-server/permission-registry.js.map +1 -0
  465. package/dist/core/socket-server/permission-relay.d.ts +81 -0
  466. package/dist/core/socket-server/permission-relay.d.ts.map +1 -0
  467. package/dist/core/socket-server/permission-relay.js +528 -0
  468. package/dist/core/socket-server/permission-relay.js.map +1 -0
  469. package/dist/core/socket-server/safe-text.d.ts +83 -0
  470. package/dist/core/socket-server/safe-text.d.ts.map +1 -0
  471. package/dist/core/socket-server/safe-text.js +277 -0
  472. package/dist/core/socket-server/safe-text.js.map +1 -0
  473. package/dist/core/socket-server/session-integration.d.ts +65 -2
  474. package/dist/core/socket-server/session-integration.d.ts.map +1 -1
  475. package/dist/core/socket-server/session-integration.js +434 -32
  476. package/dist/core/socket-server/session-integration.js.map +1 -1
  477. package/dist/core/socket-server/socket-client.d.ts +21 -2
  478. package/dist/core/socket-server/socket-client.d.ts.map +1 -1
  479. package/dist/core/socket-server/socket-client.js +52 -1
  480. package/dist/core/socket-server/socket-client.js.map +1 -1
  481. package/dist/core/socket-server/socket-server.d.ts +152 -1
  482. package/dist/core/socket-server/socket-server.d.ts.map +1 -1
  483. package/dist/core/socket-server/socket-server.js +786 -26
  484. package/dist/core/socket-server/socket-server.js.map +1 -1
  485. package/dist/core/socket-server/types.d.ts +108 -3
  486. package/dist/core/socket-server/types.d.ts.map +1 -1
  487. package/dist/core/socket-server/types.js +13 -1
  488. package/dist/core/socket-server/types.js.map +1 -1
  489. package/dist/core/source-info.d.ts +8 -0
  490. package/dist/core/source-info.d.ts.map +1 -1
  491. package/dist/core/source-info.js +16 -0
  492. package/dist/core/source-info.js.map +1 -1
  493. package/dist/core/system-prompt.d.ts +49 -6
  494. package/dist/core/system-prompt.d.ts.map +1 -1
  495. package/dist/core/system-prompt.js +126 -90
  496. package/dist/core/system-prompt.js.map +1 -1
  497. package/dist/core/tools/bash.d.ts +32 -2
  498. package/dist/core/tools/bash.d.ts.map +1 -1
  499. package/dist/core/tools/bash.js +83 -141
  500. package/dist/core/tools/bash.js.map +1 -1
  501. package/dist/core/tools/edit-diff.d.ts +0 -5
  502. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  503. package/dist/core/tools/edit-diff.js +2 -5
  504. package/dist/core/tools/edit-diff.js.map +1 -1
  505. package/dist/core/tools/edit.d.ts +5 -12
  506. package/dist/core/tools/edit.d.ts.map +1 -1
  507. package/dist/core/tools/edit.js +36 -173
  508. package/dist/core/tools/edit.js.map +1 -1
  509. package/dist/core/tools/find.d.ts +7 -0
  510. package/dist/core/tools/find.d.ts.map +1 -1
  511. package/dist/core/tools/find.js +22 -76
  512. package/dist/core/tools/find.js.map +1 -1
  513. package/dist/core/tools/grep.d.ts +4 -0
  514. package/dist/core/tools/grep.d.ts.map +1 -1
  515. package/dist/core/tools/grep.js +10 -62
  516. package/dist/core/tools/grep.js.map +1 -1
  517. package/dist/core/tools/index.d.ts +4 -1
  518. package/dist/core/tools/index.d.ts.map +1 -1
  519. package/dist/core/tools/index.js +18 -1
  520. package/dist/core/tools/index.js.map +1 -1
  521. package/dist/core/tools/ls.d.ts +4 -0
  522. package/dist/core/tools/ls.d.ts.map +1 -1
  523. package/dist/core/tools/ls.js +9 -50
  524. package/dist/core/tools/ls.js.map +1 -1
  525. package/dist/core/tools/output-accumulator.d.ts +11 -0
  526. package/dist/core/tools/output-accumulator.d.ts.map +1 -1
  527. package/dist/core/tools/output-accumulator.js +54 -12
  528. package/dist/core/tools/output-accumulator.js.map +1 -1
  529. package/dist/core/tools/powershell.d.ts +16 -0
  530. package/dist/core/tools/powershell.d.ts.map +1 -0
  531. package/dist/core/tools/powershell.js +39 -0
  532. package/dist/core/tools/powershell.js.map +1 -0
  533. package/dist/core/tools/read.d.ts +8 -1
  534. package/dist/core/tools/read.d.ts.map +1 -1
  535. package/dist/core/tools/read.js +16 -123
  536. package/dist/core/tools/read.js.map +1 -1
  537. package/dist/core/tools/render-utils.d.ts +6 -0
  538. package/dist/core/tools/render-utils.d.ts.map +1 -1
  539. package/dist/core/tools/render-utils.js +26 -0
  540. package/dist/core/tools/render-utils.js.map +1 -1
  541. package/dist/core/tools/renderers/bash.d.ts +12 -0
  542. package/dist/core/tools/renderers/bash.d.ts.map +1 -0
  543. package/dist/core/tools/renderers/bash.js +117 -0
  544. package/dist/core/tools/renderers/bash.js.map +1 -0
  545. package/dist/core/tools/renderers/edit.d.ts +23 -0
  546. package/dist/core/tools/renderers/edit.d.ts.map +1 -0
  547. package/dist/core/tools/renderers/edit.js +167 -0
  548. package/dist/core/tools/renderers/edit.js.map +1 -0
  549. package/dist/core/tools/renderers/find.d.ts +10 -0
  550. package/dist/core/tools/renderers/find.d.ts.map +1 -0
  551. package/dist/core/tools/renderers/find.js +64 -0
  552. package/dist/core/tools/renderers/find.js.map +1 -0
  553. package/dist/core/tools/renderers/grep.d.ts +10 -0
  554. package/dist/core/tools/renderers/grep.d.ts.map +1 -0
  555. package/dist/core/tools/renderers/grep.js +69 -0
  556. package/dist/core/tools/renderers/grep.js.map +1 -0
  557. package/dist/core/tools/renderers/index.d.ts +28 -0
  558. package/dist/core/tools/renderers/index.d.ts.map +1 -0
  559. package/dist/core/tools/renderers/index.js +47 -0
  560. package/dist/core/tools/renderers/index.js.map +1 -0
  561. package/dist/core/tools/renderers/ls.d.ts +10 -0
  562. package/dist/core/tools/renderers/ls.d.ts.map +1 -0
  563. package/dist/core/tools/renderers/ls.js +58 -0
  564. package/dist/core/tools/renderers/ls.js.map +1 -0
  565. package/dist/core/tools/renderers/read.d.ts +11 -0
  566. package/dist/core/tools/renderers/read.d.ts.map +1 -0
  567. package/dist/core/tools/renderers/read.js +130 -0
  568. package/dist/core/tools/renderers/read.js.map +1 -0
  569. package/dist/core/tools/renderers/write.d.ts +10 -0
  570. package/dist/core/tools/renderers/write.d.ts.map +1 -0
  571. package/dist/core/tools/renderers/write.js +153 -0
  572. package/dist/core/tools/renderers/write.js.map +1 -0
  573. package/dist/core/tools/tool-definition-wrapper.d.ts +5 -3
  574. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  575. package/dist/core/tools/tool-definition-wrapper.js +3 -1
  576. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  577. package/dist/core/tools/truncate.d.ts +14 -0
  578. package/dist/core/tools/truncate.d.ts.map +1 -1
  579. package/dist/core/tools/truncate.js +29 -0
  580. package/dist/core/tools/truncate.js.map +1 -1
  581. package/dist/core/tools/write.d.ts +4 -0
  582. package/dist/core/tools/write.d.ts.map +1 -1
  583. package/dist/core/tools/write.js +12 -147
  584. package/dist/core/tools/write.js.map +1 -1
  585. package/dist/core/trust-manager.d.ts +6 -4
  586. package/dist/core/trust-manager.d.ts.map +1 -1
  587. package/dist/core/trust-manager.js +59 -22
  588. package/dist/core/trust-manager.js.map +1 -1
  589. package/dist/core/usage-totals.d.ts +3 -1
  590. package/dist/core/usage-totals.d.ts.map +1 -1
  591. package/dist/core/usage-totals.js +28 -1
  592. package/dist/core/usage-totals.js.map +1 -1
  593. package/dist/core/virtual-models.d.ts +117 -0
  594. package/dist/core/virtual-models.d.ts.map +1 -0
  595. package/dist/core/virtual-models.js +124 -0
  596. package/dist/core/virtual-models.js.map +1 -0
  597. package/dist/experimental/micro/api.d.ts +81 -0
  598. package/dist/experimental/micro/api.d.ts.map +1 -0
  599. package/dist/experimental/micro/api.js +2 -0
  600. package/dist/experimental/micro/api.js.map +1 -0
  601. package/dist/experimental/micro/main.d.ts +3 -0
  602. package/dist/experimental/micro/main.d.ts.map +1 -0
  603. package/dist/experimental/micro/main.js +21 -0
  604. package/dist/experimental/micro/main.js.map +1 -0
  605. package/dist/experimental/micro/models.d.ts +11 -0
  606. package/dist/experimental/micro/models.d.ts.map +1 -0
  607. package/dist/experimental/micro/models.js +95 -0
  608. package/dist/experimental/micro/models.js.map +1 -0
  609. package/dist/experimental/micro/runtime.d.ts +12 -0
  610. package/dist/experimental/micro/runtime.d.ts.map +1 -0
  611. package/dist/experimental/micro/runtime.js +465 -0
  612. package/dist/experimental/micro/runtime.js.map +1 -0
  613. package/dist/experimental/micro/sessions.d.ts +10 -0
  614. package/dist/experimental/micro/sessions.d.ts.map +1 -0
  615. package/dist/experimental/micro/sessions.js +41 -0
  616. package/dist/experimental/micro/sessions.js.map +1 -0
  617. package/dist/experimental/micro/tools.d.ts +10 -0
  618. package/dist/experimental/micro/tools.d.ts.map +1 -0
  619. package/dist/experimental/micro/tools.js +96 -0
  620. package/dist/experimental/micro/tools.js.map +1 -0
  621. package/dist/experimental/micro/tui.d.ts +3 -0
  622. package/dist/experimental/micro/tui.d.ts.map +1 -0
  623. package/dist/experimental/micro/tui.js +510 -0
  624. package/dist/experimental/micro/tui.js.map +1 -0
  625. package/dist/experimental/mini/main.d.ts +7 -0
  626. package/dist/experimental/mini/main.d.ts.map +1 -0
  627. package/dist/experimental/mini/main.js +21 -0
  628. package/dist/experimental/mini/main.js.map +1 -0
  629. package/dist/experimental/mini/server/entry.d.ts +3 -0
  630. package/dist/experimental/mini/server/entry.d.ts.map +1 -0
  631. package/dist/experimental/mini/server/entry.js +11 -0
  632. package/dist/experimental/mini/server/entry.js.map +1 -0
  633. package/dist/experimental/mini/server/run.d.ts +13 -0
  634. package/dist/experimental/mini/server/run.d.ts.map +1 -0
  635. package/dist/experimental/mini/server/run.js +150 -0
  636. package/dist/experimental/mini/server/run.js.map +1 -0
  637. package/dist/experimental/mini/shared/protocol.d.ts +127 -0
  638. package/dist/experimental/mini/shared/protocol.d.ts.map +1 -0
  639. package/dist/experimental/mini/shared/protocol.js +13 -0
  640. package/dist/experimental/mini/shared/protocol.js.map +1 -0
  641. package/dist/experimental/mini/shared/rpc.d.ts +49 -0
  642. package/dist/experimental/mini/shared/rpc.d.ts.map +1 -0
  643. package/dist/experimental/mini/shared/rpc.js +171 -0
  644. package/dist/experimental/mini/shared/rpc.js.map +1 -0
  645. package/dist/experimental/mini/shared/transport.d.ts +35 -0
  646. package/dist/experimental/mini/shared/transport.d.ts.map +1 -0
  647. package/dist/experimental/mini/shared/transport.js +94 -0
  648. package/dist/experimental/mini/shared/transport.js.map +1 -0
  649. package/dist/experimental/mini/tui/run.d.ts +9 -0
  650. package/dist/experimental/mini/tui/run.d.ts.map +1 -0
  651. package/dist/experimental/mini/tui/run.js +62 -0
  652. package/dist/experimental/mini/tui/run.js.map +1 -0
  653. package/dist/experimental/mini/tui/session.d.ts +26 -0
  654. package/dist/experimental/mini/tui/session.d.ts.map +1 -0
  655. package/dist/experimental/mini/tui/session.js +94 -0
  656. package/dist/experimental/mini/tui/session.js.map +1 -0
  657. package/dist/experimental/mini/tui/view.d.ts +10 -0
  658. package/dist/experimental/mini/tui/view.d.ts.map +1 -0
  659. package/dist/experimental/mini/tui/view.js +461 -0
  660. package/dist/experimental/mini/tui/view.js.map +1 -0
  661. package/dist/experimental/mini/worker/entry.d.ts +3 -0
  662. package/dist/experimental/mini/worker/entry.d.ts.map +1 -0
  663. package/dist/experimental/mini/worker/entry.js +10 -0
  664. package/dist/experimental/mini/worker/entry.js.map +1 -0
  665. package/dist/experimental/mini/worker/lane-service.d.ts +44 -0
  666. package/dist/experimental/mini/worker/lane-service.d.ts.map +1 -0
  667. package/dist/experimental/mini/worker/lane-service.js +97 -0
  668. package/dist/experimental/mini/worker/lane-service.js.map +1 -0
  669. package/dist/experimental/mini/worker/models-service.d.ts +19 -0
  670. package/dist/experimental/mini/worker/models-service.d.ts.map +1 -0
  671. package/dist/experimental/mini/worker/models-service.js +136 -0
  672. package/dist/experimental/mini/worker/models-service.js.map +1 -0
  673. package/dist/experimental/mini/worker/run.d.ts +14 -0
  674. package/dist/experimental/mini/worker/run.d.ts.map +1 -0
  675. package/dist/experimental/mini/worker/run.js +88 -0
  676. package/dist/experimental/mini/worker/run.js.map +1 -0
  677. package/dist/extensions/codemode/execute.d.ts +16 -0
  678. package/dist/extensions/codemode/execute.d.ts.map +1 -0
  679. package/dist/extensions/codemode/execute.js +429 -0
  680. package/dist/extensions/codemode/execute.js.map +1 -0
  681. package/dist/extensions/codemode/execute.lazy.d.ts +3 -0
  682. package/dist/extensions/codemode/execute.lazy.d.ts.map +1 -0
  683. package/dist/extensions/codemode/execute.lazy.js +3 -0
  684. package/dist/extensions/codemode/execute.lazy.js.map +1 -0
  685. package/dist/extensions/codemode/index.d.ts +21 -0
  686. package/dist/extensions/codemode/index.d.ts.map +1 -0
  687. package/dist/extensions/codemode/index.js +31 -0
  688. package/dist/extensions/codemode/index.js.map +1 -0
  689. package/dist/extensions/codemode/renderer.d.ts +12 -0
  690. package/dist/extensions/codemode/renderer.d.ts.map +1 -0
  691. package/dist/extensions/codemode/renderer.js +137 -0
  692. package/dist/extensions/codemode/renderer.js.map +1 -0
  693. package/dist/extensions/codemode/tool.d.ts +123 -0
  694. package/dist/extensions/codemode/tool.d.ts.map +1 -0
  695. package/dist/extensions/codemode/tool.js +315 -0
  696. package/dist/extensions/codemode/tool.js.map +1 -0
  697. package/dist/extensions/codemode/worker.d.ts +7 -0
  698. package/dist/extensions/codemode/worker.d.ts.map +1 -0
  699. package/dist/extensions/codemode/worker.js +7 -0
  700. package/dist/extensions/codemode/worker.js.map +1 -0
  701. package/dist/extensions/index.d.ts.map +1 -1
  702. package/dist/extensions/index.js +13 -1
  703. package/dist/extensions/index.js.map +1 -1
  704. package/dist/extensions/llama/client.d.ts +8 -0
  705. package/dist/extensions/llama/client.d.ts.map +1 -1
  706. package/dist/extensions/llama/client.js +13 -0
  707. package/dist/extensions/llama/client.js.map +1 -1
  708. package/dist/extensions/llama/huggingface.js +2 -0
  709. package/dist/extensions/llama/huggingface.js.map +1 -1
  710. package/dist/extensions/llama/index.d.ts.map +1 -1
  711. package/dist/extensions/llama/index.js +13 -2
  712. package/dist/extensions/llama/index.js.map +1 -1
  713. package/dist/extensions/llama/provider.d.ts +4 -2
  714. package/dist/extensions/llama/provider.d.ts.map +1 -1
  715. package/dist/extensions/llama/provider.js +121 -15
  716. package/dist/extensions/llama/provider.js.map +1 -1
  717. package/dist/extensions/llama/ui.js +28 -12
  718. package/dist/extensions/llama/ui.js.map +1 -1
  719. package/dist/extensions/mcp/cli.d.ts +21 -0
  720. package/dist/extensions/mcp/cli.d.ts.map +1 -0
  721. package/dist/extensions/mcp/cli.js +500 -0
  722. package/dist/extensions/mcp/cli.js.map +1 -0
  723. package/dist/extensions/mcp/cli.lazy.d.ts +3 -0
  724. package/dist/extensions/mcp/cli.lazy.d.ts.map +1 -0
  725. package/dist/extensions/mcp/cli.lazy.js +3 -0
  726. package/dist/extensions/mcp/cli.lazy.js.map +1 -0
  727. package/dist/extensions/mcp/config.d.ts +72 -0
  728. package/dist/extensions/mcp/config.d.ts.map +1 -0
  729. package/dist/extensions/mcp/config.js +158 -0
  730. package/dist/extensions/mcp/config.js.map +1 -0
  731. package/dist/extensions/mcp/index.d.ts +76 -0
  732. package/dist/extensions/mcp/index.d.ts.map +1 -0
  733. package/dist/extensions/mcp/index.js +1055 -0
  734. package/dist/extensions/mcp/index.js.map +1 -0
  735. package/dist/extensions/mcp/log.d.ts +16 -0
  736. package/dist/extensions/mcp/log.d.ts.map +1 -0
  737. package/dist/extensions/mcp/log.js +66 -0
  738. package/dist/extensions/mcp/log.js.map +1 -0
  739. package/dist/extensions/mcp/oauth.d.ts +96 -0
  740. package/dist/extensions/mcp/oauth.d.ts.map +1 -0
  741. package/dist/extensions/mcp/oauth.js +333 -0
  742. package/dist/extensions/mcp/oauth.js.map +1 -0
  743. package/dist/extensions/mcp/resources.d.ts +43 -0
  744. package/dist/extensions/mcp/resources.d.ts.map +1 -0
  745. package/dist/extensions/mcp/resources.js +262 -0
  746. package/dist/extensions/mcp/resources.js.map +1 -0
  747. package/dist/extensions/mcp/runtime.d.ts +98 -0
  748. package/dist/extensions/mcp/runtime.d.ts.map +1 -0
  749. package/dist/extensions/mcp/runtime.js +394 -0
  750. package/dist/extensions/mcp/runtime.js.map +1 -0
  751. package/dist/extensions/mcp/runtime.lazy.d.ts +3 -0
  752. package/dist/extensions/mcp/runtime.lazy.d.ts.map +1 -0
  753. package/dist/extensions/mcp/runtime.lazy.js +3 -0
  754. package/dist/extensions/mcp/runtime.lazy.js.map +1 -0
  755. package/dist/extensions/mcp/tools.d.ts +84 -0
  756. package/dist/extensions/mcp/tools.d.ts.map +1 -0
  757. package/dist/extensions/mcp/tools.js +251 -0
  758. package/dist/extensions/mcp/tools.js.map +1 -0
  759. package/dist/extensions/mcp/ui.d.ts +60 -0
  760. package/dist/extensions/mcp/ui.d.ts.map +1 -0
  761. package/dist/extensions/mcp/ui.js +174 -0
  762. package/dist/extensions/mcp/ui.js.map +1 -0
  763. package/dist/extensions/stub-provider/index.d.ts +9 -0
  764. package/dist/extensions/stub-provider/index.d.ts.map +1 -0
  765. package/dist/extensions/stub-provider/index.js +13 -0
  766. package/dist/extensions/stub-provider/index.js.map +1 -0
  767. package/dist/extensions/stub-provider/provider.d.ts +77 -0
  768. package/dist/extensions/stub-provider/provider.d.ts.map +1 -0
  769. package/dist/extensions/stub-provider/provider.js +194 -0
  770. package/dist/extensions/stub-provider/provider.js.map +1 -0
  771. package/dist/extensions/tool-search/index.d.ts +12 -0
  772. package/dist/extensions/tool-search/index.d.ts.map +1 -0
  773. package/dist/extensions/tool-search/index.js +15 -0
  774. package/dist/extensions/tool-search/index.js.map +1 -0
  775. package/dist/extensions/tool-search/tool.d.ts +73 -0
  776. package/dist/extensions/tool-search/tool.d.ts.map +1 -0
  777. package/dist/extensions/tool-search/tool.js +189 -0
  778. package/dist/extensions/tool-search/tool.js.map +1 -0
  779. package/dist/hooks/gsd/draht-quality-gate.js +3 -3
  780. package/dist/index.d.ts +20 -11
  781. package/dist/index.d.ts.map +1 -1
  782. package/dist/index.js +12 -6
  783. package/dist/index.js.map +1 -1
  784. package/dist/main.d.ts +4 -0
  785. package/dist/main.d.ts.map +1 -1
  786. package/dist/main.js +365 -96
  787. package/dist/main.js.map +1 -1
  788. package/dist/migrations.d.ts +1 -1
  789. package/dist/migrations.js +7 -6
  790. package/dist/migrations.js.map +1 -1
  791. package/dist/modes/index.d.ts +1 -0
  792. package/dist/modes/index.d.ts.map +1 -1
  793. package/dist/modes/index.js.map +1 -1
  794. package/dist/modes/interactive/bug-report.d.ts +19 -0
  795. package/dist/modes/interactive/bug-report.d.ts.map +1 -0
  796. package/dist/modes/interactive/bug-report.js +211 -0
  797. package/dist/modes/interactive/bug-report.js.map +1 -0
  798. package/dist/modes/interactive/chat-viewport.d.ts +20 -0
  799. package/dist/modes/interactive/chat-viewport.d.ts.map +1 -0
  800. package/dist/modes/interactive/chat-viewport.js +28 -0
  801. package/dist/modes/interactive/chat-viewport.js.map +1 -0
  802. package/dist/modes/interactive/components/armin.js +10 -6
  803. package/dist/modes/interactive/components/armin.js.map +1 -1
  804. package/dist/modes/interactive/components/assistant-message.d.ts +6 -2
  805. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  806. package/dist/modes/interactive/components/assistant-message.js +38 -15
  807. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  808. package/dist/modes/interactive/components/bash-execution.js +9 -4
  809. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  810. package/dist/modes/interactive/components/bordered-loader.js +3 -0
  811. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  812. package/dist/modes/interactive/components/branch-summary-message.d.ts +1 -1
  813. package/dist/modes/interactive/components/branch-summary-message.d.ts.map +1 -1
  814. package/dist/modes/interactive/components/branch-summary-message.js +15 -6
  815. package/dist/modes/interactive/components/branch-summary-message.js.map +1 -1
  816. package/dist/modes/interactive/components/compaction-summary-message.d.ts +1 -1
  817. package/dist/modes/interactive/components/compaction-summary-message.d.ts.map +1 -1
  818. package/dist/modes/interactive/components/compaction-summary-message.js +15 -6
  819. package/dist/modes/interactive/components/compaction-summary-message.js.map +1 -1
  820. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  821. package/dist/modes/interactive/components/config-selector.js +38 -10
  822. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  823. package/dist/modes/interactive/components/countdown-timer.js +5 -0
  824. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  825. package/dist/modes/interactive/components/custom-editor.d.ts +10 -1
  826. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  827. package/dist/modes/interactive/components/custom-editor.js +54 -2
  828. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  829. package/dist/modes/interactive/components/custom-entry.js +4 -1
  830. package/dist/modes/interactive/components/custom-entry.js.map +1 -1
  831. package/dist/modes/interactive/components/custom-message.js +7 -1
  832. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  833. package/dist/modes/interactive/components/daxnuts.js +8 -6
  834. package/dist/modes/interactive/components/daxnuts.js.map +1 -1
  835. package/dist/modes/interactive/components/dynamic-border.js +1 -0
  836. package/dist/modes/interactive/components/dynamic-border.js.map +1 -1
  837. package/dist/modes/interactive/components/extension-editor.d.ts +4 -1
  838. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  839. package/dist/modes/interactive/components/extension-editor.js +14 -3
  840. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  841. package/dist/modes/interactive/components/extension-input.d.ts +2 -0
  842. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  843. package/dist/modes/interactive/components/extension-input.js +14 -2
  844. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  845. package/dist/modes/interactive/components/extension-selector.d.ts +50 -0
  846. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  847. package/dist/modes/interactive/components/extension-selector.js +218 -6
  848. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  849. package/dist/modes/interactive/components/first-time-setup.d.ts +4 -4
  850. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -1
  851. package/dist/modes/interactive/components/first-time-setup.js +12 -4
  852. package/dist/modes/interactive/components/first-time-setup.js.map +1 -1
  853. package/dist/modes/interactive/components/footer.d.ts +7 -0
  854. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  855. package/dist/modes/interactive/components/footer.js +51 -6
  856. package/dist/modes/interactive/components/footer.js.map +1 -1
  857. package/dist/modes/interactive/components/index.d.ts +1 -1
  858. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  859. package/dist/modes/interactive/components/index.js.map +1 -1
  860. package/dist/modes/interactive/components/login-dialog.js +9 -3
  861. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  862. package/dist/modes/interactive/components/markdown-transform.d.ts +3 -0
  863. package/dist/modes/interactive/components/markdown-transform.d.ts.map +1 -0
  864. package/dist/modes/interactive/components/markdown-transform.js +19 -0
  865. package/dist/modes/interactive/components/markdown-transform.js.map +1 -0
  866. package/dist/modes/interactive/components/mermaid.d.ts +11 -0
  867. package/dist/modes/interactive/components/mermaid.d.ts.map +1 -0
  868. package/dist/modes/interactive/components/mermaid.js +75 -0
  869. package/dist/modes/interactive/components/mermaid.js.map +1 -0
  870. package/dist/modes/interactive/components/model-selector.d.ts +10 -4
  871. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  872. package/dist/modes/interactive/components/model-selector.js +101 -40
  873. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  874. package/dist/modes/interactive/components/oauth-selector.js +11 -3
  875. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  876. package/dist/modes/interactive/components/scoped-models-selector.d.ts +4 -0
  877. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  878. package/dist/modes/interactive/components/scoped-models-selector.js +60 -32
  879. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  880. package/dist/modes/interactive/components/session-selector.d.ts +5 -5
  881. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  882. package/dist/modes/interactive/components/session-selector.js +138 -80
  883. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  884. package/dist/modes/interactive/components/settings-selector.d.ts +25 -4
  885. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  886. package/dist/modes/interactive/components/settings-selector.js +240 -67
  887. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  888. package/dist/modes/interactive/components/settings-submenu.d.ts +72 -0
  889. package/dist/modes/interactive/components/settings-submenu.d.ts.map +1 -0
  890. package/dist/modes/interactive/components/settings-submenu.js +165 -0
  891. package/dist/modes/interactive/components/settings-submenu.js.map +1 -0
  892. package/dist/modes/interactive/components/show-images-selector.js +1 -0
  893. package/dist/modes/interactive/components/show-images-selector.js.map +1 -1
  894. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  895. package/dist/modes/interactive/components/skill-invocation-message.js +14 -5
  896. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  897. package/dist/modes/interactive/components/status-indicator.d.ts +3 -1
  898. package/dist/modes/interactive/components/status-indicator.d.ts.map +1 -1
  899. package/dist/modes/interactive/components/status-indicator.js +12 -3
  900. package/dist/modes/interactive/components/status-indicator.js.map +1 -1
  901. package/dist/modes/interactive/components/theme-selector.js +2 -0
  902. package/dist/modes/interactive/components/theme-selector.js.map +1 -1
  903. package/dist/modes/interactive/components/themed-text.d.ts +17 -0
  904. package/dist/modes/interactive/components/themed-text.d.ts.map +1 -0
  905. package/dist/modes/interactive/components/themed-text.js +29 -0
  906. package/dist/modes/interactive/components/themed-text.js.map +1 -0
  907. package/dist/modes/interactive/components/thinking-selector.d.ts +15 -3
  908. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  909. package/dist/modes/interactive/components/thinking-selector.js +76 -18
  910. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  911. package/dist/modes/interactive/components/tool-execution.d.ts +21 -4
  912. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  913. package/dist/modes/interactive/components/tool-execution.js +88 -53
  914. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  915. package/dist/modes/interactive/components/tree-selector.d.ts +20 -2
  916. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  917. package/dist/modes/interactive/components/tree-selector.js +65 -23
  918. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  919. package/dist/modes/interactive/components/trust-selector.js +8 -2
  920. package/dist/modes/interactive/components/trust-selector.js.map +1 -1
  921. package/dist/modes/interactive/components/user-message-selector.js +6 -3
  922. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  923. package/dist/modes/interactive/components/user-message.d.ts +3 -1
  924. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  925. package/dist/modes/interactive/components/user-message.js +12 -2
  926. package/dist/modes/interactive/components/user-message.js.map +1 -1
  927. package/dist/modes/interactive/components/visual-truncate.d.ts +27 -3
  928. package/dist/modes/interactive/components/visual-truncate.d.ts.map +1 -1
  929. package/dist/modes/interactive/components/visual-truncate.js +39 -6
  930. package/dist/modes/interactive/components/visual-truncate.js.map +1 -1
  931. package/dist/modes/interactive/external-editor.d.ts.map +1 -1
  932. package/dist/modes/interactive/external-editor.js +2 -1
  933. package/dist/modes/interactive/external-editor.js.map +1 -1
  934. package/dist/modes/interactive/interactive-mode.d.ts +166 -8
  935. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  936. package/dist/modes/interactive/interactive-mode.js +1690 -599
  937. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  938. package/dist/modes/interactive/model-catalog-refresh.d.ts +7 -0
  939. package/dist/modes/interactive/model-catalog-refresh.d.ts.map +1 -0
  940. package/dist/modes/interactive/model-catalog-refresh.js +34 -0
  941. package/dist/modes/interactive/model-catalog-refresh.js.map +1 -0
  942. package/dist/modes/interactive/session-share.d.ts +23 -0
  943. package/dist/modes/interactive/session-share.d.ts.map +1 -0
  944. package/dist/modes/interactive/session-share.js +130 -0
  945. package/dist/modes/interactive/session-share.js.map +1 -0
  946. package/dist/modes/interactive/theme/dark.json +54 -63
  947. package/dist/modes/interactive/theme/light.json +52 -60
  948. package/dist/modes/interactive/theme/system-theme.d.ts +54 -0
  949. package/dist/modes/interactive/theme/system-theme.d.ts.map +1 -0
  950. package/dist/modes/interactive/theme/system-theme.js +535 -0
  951. package/dist/modes/interactive/theme/system-theme.js.map +1 -0
  952. package/dist/modes/interactive/theme/theme-controller.d.ts +59 -7
  953. package/dist/modes/interactive/theme/theme-controller.d.ts.map +1 -1
  954. package/dist/modes/interactive/theme/theme-controller.js +164 -51
  955. package/dist/modes/interactive/theme/theme-controller.js.map +1 -1
  956. package/dist/modes/interactive/theme/theme-json.d.ts +85 -0
  957. package/dist/modes/interactive/theme/theme-json.d.ts.map +1 -0
  958. package/dist/modes/interactive/theme/theme-json.js +132 -0
  959. package/dist/modes/interactive/theme/theme-json.js.map +1 -0
  960. package/dist/modes/interactive/theme/theme-schema.json +24 -3
  961. package/dist/modes/interactive/theme/theme.d.ts +80 -42
  962. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  963. package/dist/modes/interactive/theme/theme.js +274 -417
  964. package/dist/modes/interactive/theme/theme.js.map +1 -1
  965. package/dist/modes/interactive/tui-renderer.d.ts +22 -0
  966. package/dist/modes/interactive/tui-renderer.d.ts.map +1 -0
  967. package/dist/modes/interactive/tui-renderer.js +67 -0
  968. package/dist/modes/interactive/tui-renderer.js.map +1 -0
  969. package/dist/modes/json-event.d.ts +34 -0
  970. package/dist/modes/json-event.d.ts.map +1 -0
  971. package/dist/modes/json-event.js +29 -0
  972. package/dist/modes/json-event.js.map +1 -0
  973. package/dist/modes/print-mode.d.ts +1 -1
  974. package/dist/modes/print-mode.d.ts.map +1 -1
  975. package/dist/modes/print-mode.js +12 -2
  976. package/dist/modes/print-mode.js.map +1 -1
  977. package/dist/modes/rpc/rpc-client.d.ts +17 -9
  978. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  979. package/dist/modes/rpc/rpc-client.js +27 -15
  980. package/dist/modes/rpc/rpc-client.js.map +1 -1
  981. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  982. package/dist/modes/rpc/rpc-mode.js +179 -19
  983. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  984. package/dist/modes/rpc/rpc-types.d.ts +90 -2
  985. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  986. package/dist/modes/rpc/rpc-types.js.map +1 -1
  987. package/dist/package-manager-cli.d.ts +1 -0
  988. package/dist/package-manager-cli.d.ts.map +1 -1
  989. package/dist/package-manager-cli.js +217 -63
  990. package/dist/package-manager-cli.js.map +1 -1
  991. package/dist/prompts/commands/atomic-commit.md +1 -12
  992. package/dist/prompts/commands/brainstorm.md +12 -15
  993. package/dist/prompts/commands/create-verification-skill.md +108 -0
  994. package/dist/prompts/commands/discuss-phase.md +3 -14
  995. package/dist/prompts/commands/execute-phase.md +3 -11
  996. package/dist/prompts/commands/fix.md +41 -18
  997. package/dist/prompts/commands/grill.md +66 -0
  998. package/dist/prompts/commands/init-project.md +5 -15
  999. package/dist/prompts/commands/map-codebase.md +1 -13
  1000. package/dist/prompts/commands/new-project.md +5 -15
  1001. package/dist/prompts/commands/next-milestone.md +1 -13
  1002. package/dist/prompts/commands/orchestrate.md +1 -1
  1003. package/dist/prompts/commands/pause-work.md +1 -13
  1004. package/dist/prompts/commands/plan-phase.md +3 -11
  1005. package/dist/prompts/commands/progress.md +0 -13
  1006. package/dist/prompts/commands/quick.md +3 -11
  1007. package/dist/prompts/commands/resolve-conflicts.md +71 -0
  1008. package/dist/prompts/commands/resume-work.md +0 -13
  1009. package/dist/prompts/commands/review.md +6 -13
  1010. package/dist/prompts/commands/triage.md +159 -0
  1011. package/dist/prompts/commands/verify-work.md +5 -14
  1012. package/dist/prompts/commands/why.md +139 -0
  1013. package/dist/rpc-entry.js +1 -0
  1014. package/dist/rpc-entry.js.map +1 -1
  1015. package/dist/skills/atomic-reasoning/SKILL.md +115 -0
  1016. package/dist/skills/blast-radius/SKILL.md +56 -0
  1017. package/dist/skills/epistemics/SKILL.md +99 -0
  1018. package/dist/skills/explainers/SKILL.md +65 -0
  1019. package/dist/skills/hexagon-animation/SKILL.md +49 -0
  1020. package/dist/skills/hexagon-animation/generate.mjs +81 -0
  1021. package/dist/skills/hexagon-animation/template.html +361 -0
  1022. package/dist/skills/typescript-discipline/SKILL.md +50 -0
  1023. package/dist/skills/typescript-discipline/references/patterns.md +294 -0
  1024. package/dist/skills/unslop/SKILL.md +119 -0
  1025. package/dist/utils/abort.d.ts +5 -0
  1026. package/dist/utils/abort.d.ts.map +1 -0
  1027. package/dist/utils/abort.js +48 -0
  1028. package/dist/utils/abort.js.map +1 -0
  1029. package/dist/utils/canonical-path.d.ts +28 -0
  1030. package/dist/utils/canonical-path.d.ts.map +1 -0
  1031. package/dist/utils/canonical-path.js +90 -0
  1032. package/dist/utils/canonical-path.js.map +1 -0
  1033. package/dist/utils/changelog.js +1 -1
  1034. package/dist/utils/changelog.js.map +1 -1
  1035. package/dist/utils/child-process.d.ts +13 -2
  1036. package/dist/utils/child-process.d.ts.map +1 -1
  1037. package/dist/utils/child-process.js +26 -9
  1038. package/dist/utils/child-process.js.map +1 -1
  1039. package/dist/utils/clipboard-command.d.ts +7 -0
  1040. package/dist/utils/clipboard-command.d.ts.map +1 -0
  1041. package/dist/utils/clipboard-command.js +45 -0
  1042. package/dist/utils/clipboard-command.js.map +1 -0
  1043. package/dist/utils/clipboard-image.d.ts.map +1 -1
  1044. package/dist/utils/clipboard-image.js +60 -91
  1045. package/dist/utils/clipboard-image.js.map +1 -1
  1046. package/dist/utils/clipboard.d.ts +3 -1
  1047. package/dist/utils/clipboard.d.ts.map +1 -1
  1048. package/dist/utils/clipboard.js +123 -108
  1049. package/dist/utils/clipboard.js.map +1 -1
  1050. package/dist/utils/draht-user-agent.d.ts +2 -0
  1051. package/dist/utils/draht-user-agent.d.ts.map +1 -0
  1052. package/dist/utils/draht-user-agent.js +5 -0
  1053. package/dist/utils/draht-user-agent.js.map +1 -0
  1054. package/dist/utils/exif-orientation.d.ts +2 -1
  1055. package/dist/utils/exif-orientation.d.ts.map +1 -1
  1056. package/dist/utils/exif-orientation.js +2 -3
  1057. package/dist/utils/exif-orientation.js.map +1 -1
  1058. package/dist/utils/frontmatter.d.ts.map +1 -1
  1059. package/dist/utils/frontmatter.js +2 -1
  1060. package/dist/utils/frontmatter.js.map +1 -1
  1061. package/dist/utils/management-http.d.ts +25 -0
  1062. package/dist/utils/management-http.d.ts.map +1 -0
  1063. package/dist/utils/management-http.js +54 -0
  1064. package/dist/utils/management-http.js.map +1 -0
  1065. package/dist/utils/mime.js +1 -1
  1066. package/dist/utils/mime.js.map +1 -1
  1067. package/dist/utils/paths.d.ts +6 -10
  1068. package/dist/utils/paths.d.ts.map +1 -1
  1069. package/dist/utils/paths.js +23 -14
  1070. package/dist/utils/paths.js.map +1 -1
  1071. package/dist/utils/photon.d.ts +2 -1
  1072. package/dist/utils/photon.d.ts.map +1 -1
  1073. package/dist/utils/photon.js.map +1 -1
  1074. package/dist/utils/shell.d.ts +4 -3
  1075. package/dist/utils/shell.d.ts.map +1 -1
  1076. package/dist/utils/shell.js +26 -39
  1077. package/dist/utils/shell.js.map +1 -1
  1078. package/dist/utils/syntax-highlight.d.ts +1 -0
  1079. package/dist/utils/syntax-highlight.d.ts.map +1 -1
  1080. package/dist/utils/syntax-highlight.js +62 -1
  1081. package/dist/utils/syntax-highlight.js.map +1 -1
  1082. package/dist/utils/text.d.ts +8 -0
  1083. package/dist/utils/text.d.ts.map +1 -0
  1084. package/dist/utils/text.js +9 -0
  1085. package/dist/utils/text.js.map +1 -0
  1086. package/dist/utils/tool-result-images.d.ts +21 -0
  1087. package/dist/utils/tool-result-images.d.ts.map +1 -0
  1088. package/dist/utils/tool-result-images.js +48 -0
  1089. package/dist/utils/tool-result-images.js.map +1 -0
  1090. package/dist/utils/tools-manager.d.ts +11 -1
  1091. package/dist/utils/tools-manager.d.ts.map +1 -1
  1092. package/dist/utils/tools-manager.js +56 -41
  1093. package/dist/utils/tools-manager.js.map +1 -1
  1094. package/dist/utils/version-check.d.ts +4 -1
  1095. package/dist/utils/version-check.d.ts.map +1 -1
  1096. package/dist/utils/version-check.js +30 -9
  1097. package/dist/utils/version-check.js.map +1 -1
  1098. package/dist/utils/wsl.d.ts +3 -0
  1099. package/dist/utils/wsl.d.ts.map +1 -0
  1100. package/dist/utils/wsl.js +15 -0
  1101. package/dist/utils/wsl.js.map +1 -0
  1102. package/dist/utils/zip.d.ts +7 -0
  1103. package/dist/utils/zip.d.ts.map +1 -0
  1104. package/dist/utils/zip.js +60 -0
  1105. package/dist/utils/zip.js.map +1 -0
  1106. package/docs/attachable-sessions.md +79 -0
  1107. package/docs/cli-integration.md +106 -0
  1108. package/docs/cli.md +374 -0
  1109. package/docs/compaction.md +107 -45
  1110. package/docs/configuration.md +47 -0
  1111. package/docs/containerization.md +100 -66
  1112. package/docs/custom-provider.md +109 -707
  1113. package/docs/docs.json +155 -95
  1114. package/docs/duet.md +42 -0
  1115. package/docs/environment-variables.md +30 -17
  1116. package/docs/extensions.md +169 -2811
  1117. package/docs/how-pi-works.md +53 -0
  1118. package/docs/images/interactive-mode.png +0 -0
  1119. package/docs/index.md +25 -69
  1120. package/docs/json.md +198 -57
  1121. package/docs/keybindings.md +89 -92
  1122. package/docs/llama-cpp.md +23 -8
  1123. package/docs/mcp.md +231 -0
  1124. package/docs/message-types.md +261 -0
  1125. package/docs/models.md +94 -478
  1126. package/docs/packages.md +68 -164
  1127. package/docs/prompt-templates.md +31 -68
  1128. package/docs/providers.md +118 -215
  1129. package/docs/quickstart.md +56 -109
  1130. package/docs/rpc-commands.md +860 -0
  1131. package/docs/rpc-extension-ui.md +200 -0
  1132. package/docs/rpc.md +186 -1494
  1133. package/docs/sdk.md +79 -1127
  1134. package/docs/security.md +77 -33
  1135. package/docs/session-format.md +98 -222
  1136. package/docs/sessions.md +36 -113
  1137. package/docs/settings.md +125 -251
  1138. package/docs/shell-aliases.md +85 -5
  1139. package/docs/skills.md +52 -188
  1140. package/docs/slash-commands.md +61 -0
  1141. package/docs/terminal-setup.md +132 -61
  1142. package/docs/termux.md +74 -84
  1143. package/docs/themes.md +91 -252
  1144. package/docs/tmux.md +31 -39
  1145. package/docs/tui.md +74 -891
  1146. package/docs/usage.md +54 -255
  1147. package/docs/virtual-models.md +114 -0
  1148. package/docs/windows.md +57 -7
  1149. package/examples/extensions/antigravity-image-gen.ts +9 -9
  1150. package/examples/extensions/bash-spawn-hook.ts +1 -1
  1151. package/examples/extensions/border-status-editor.ts +1 -1
  1152. package/examples/extensions/built-in-tool-renderer.ts +16 -40
  1153. package/examples/extensions/custom-compaction.ts +1 -16
  1154. package/examples/extensions/custom-provider-anthropic/index.ts +20 -13
  1155. package/examples/extensions/custom-provider-gitlab-duo/index.ts +4 -3
  1156. package/examples/extensions/custom-provider-gitlab-duo/test.ts +5 -5
  1157. package/examples/extensions/debug-provider.ts +90 -0
  1158. package/examples/extensions/doom-overlay/wad-finder.ts +7 -3
  1159. package/examples/extensions/dynamic-resources/dynamic.json +3 -1
  1160. package/examples/extensions/git-checkpoint.ts +2 -2
  1161. package/examples/extensions/handoff.ts +2 -11
  1162. package/examples/extensions/jev-router.ts +113 -0
  1163. package/examples/extensions/minimal-mode.ts +24 -96
  1164. package/examples/extensions/notify.ts +3 -1
  1165. package/examples/extensions/overlay-qa-tests.ts +3 -3
  1166. package/examples/extensions/prompt-customizer.ts +19 -67
  1167. package/examples/extensions/qna.ts +3 -7
  1168. package/examples/extensions/subagent/agents.ts +40 -9
  1169. package/examples/extensions/subagent/index.ts +27 -4
  1170. package/examples/extensions/summarize.ts +7 -18
  1171. package/examples/extensions/titlebar-spinner.ts +1 -1
  1172. package/examples/rpc-client.ts +35 -0
  1173. package/examples/rpc-extension-ui.ts +38 -9
  1174. package/examples/sdk/02-custom-model.ts +1 -2
  1175. package/examples/sdk/06-extensions.ts +1 -1
  1176. package/examples/sdk/09-api-keys-and-oauth.ts +1 -1
  1177. package/examples/sdk/12-full-control.ts +1 -1
  1178. package/examples/sdk/14-codemode-mcp.ts +61 -0
  1179. package/hooks/gsd/draht-quality-gate.js +3 -3
  1180. package/package.json +28 -32
  1181. package/prompts/commands/atomic-commit.md +1 -12
  1182. package/prompts/commands/brainstorm.md +12 -15
  1183. package/prompts/commands/create-verification-skill.md +108 -0
  1184. package/prompts/commands/discuss-phase.md +3 -14
  1185. package/prompts/commands/execute-phase.md +3 -11
  1186. package/prompts/commands/fix.md +41 -18
  1187. package/prompts/commands/grill.md +66 -0
  1188. package/prompts/commands/init-project.md +5 -15
  1189. package/prompts/commands/map-codebase.md +1 -13
  1190. package/prompts/commands/new-project.md +5 -15
  1191. package/prompts/commands/next-milestone.md +1 -13
  1192. package/prompts/commands/orchestrate.md +1 -1
  1193. package/prompts/commands/pause-work.md +1 -13
  1194. package/prompts/commands/plan-phase.md +3 -11
  1195. package/prompts/commands/progress.md +0 -13
  1196. package/prompts/commands/quick.md +3 -11
  1197. package/prompts/commands/resolve-conflicts.md +71 -0
  1198. package/prompts/commands/resume-work.md +0 -13
  1199. package/prompts/commands/review.md +6 -13
  1200. package/prompts/commands/triage.md +159 -0
  1201. package/prompts/commands/verify-work.md +5 -14
  1202. package/prompts/commands/why.md +139 -0
  1203. package/skills/atomic-reasoning/SKILL.md +115 -0
  1204. package/skills/blast-radius/SKILL.md +56 -0
  1205. package/skills/epistemics/SKILL.md +99 -0
  1206. package/skills/explainers/SKILL.md +65 -0
  1207. package/skills/hexagon-animation/SKILL.md +49 -0
  1208. package/skills/hexagon-animation/generate.mjs +81 -0
  1209. package/skills/hexagon-animation/template.html +361 -0
  1210. package/skills/typescript-discipline/SKILL.md +50 -0
  1211. package/skills/typescript-discipline/references/patterns.md +294 -0
  1212. package/skills/unslop/SKILL.md +119 -0
  1213. package/dist/prompts/agents/build.md +0 -86
  1214. package/dist/prompts/agents/plan.md +0 -79
  1215. package/dist/prompts/agents/verify.md +0 -69
  1216. package/dist/utils/clipboard-native.d.ts +0 -11
  1217. package/dist/utils/clipboard-native.d.ts.map +0 -1
  1218. package/dist/utils/clipboard-native.js +0 -20
  1219. package/dist/utils/clipboard-native.js.map +0 -1
  1220. package/dist/utils/pi-user-agent.d.ts +0 -2
  1221. package/dist/utils/pi-user-agent.d.ts.map +0 -1
  1222. package/dist/utils/pi-user-agent.js +0 -5
  1223. package/dist/utils/pi-user-agent.js.map +0 -1
  1224. package/docs/development.md +0 -71
  1225. package/docs/tree.md +0 -231
  1226. package/examples/extensions/kimi-deferred-tools.ts +0 -61
  1227. package/prompts/agents/build.md +0 -86
  1228. package/prompts/agents/plan.md +0 -79
  1229. package/prompts/agents/verify.md +0 -69
@@ -6,40 +6,50 @@ import * as crypto from "node:crypto";
6
6
  import * as fs from "node:fs";
7
7
  import * as os from "node:os";
8
8
  import * as path from "node:path";
9
- import { CombinedAutocompleteProvider, Container, fuzzyFilter, getCapabilities, hyperlink, Markdown, matchesKey, ProcessTerminal, Spacer, setKeybindings, Text, TruncatedText, TUI, visibleWidth, } from "@draht/tui";
9
+ import { isRetryableAssistantError, } from "@draht/ai/compat";
10
+ import * as TuiLayouts from "@draht/tui";
11
+ import { CombinedAutocompleteProvider, Container, fuzzyFilter, getCapabilities, hyperlink, Markdown, matchesKey, Spacer, setCapabilityOverrides, setKeybindings, Text, TruncatedText, TuiAltScreen, TuiMainScreen, visibleWidth, } from "@draht/tui";
10
12
  import chalk from "chalk";
11
- import { spawn, spawnSync } from "child_process";
12
- import { APP_NAME, APP_TITLE, CONFIG_DIR_NAME, DISPLAY_VERSION, getAgentDir, getAuthPath, getDebugLogPath, getDocsPath, getShareViewerUrl, VERSION, } from "../../config.js";
13
+ import { spawn } from "child_process";
14
+ import { APP_NAME, APP_TITLE, CONFIG_DIR_NAME, DISPLAY_VERSION, getAgentDir, getAuthPath, getDebugLogPath, getDocsPath, VERSION, } from "../../config.js";
13
15
  import { parseSkillBlock } from "../../core/agent-session.js";
14
16
  import { SessionImportFileNotFoundError } from "../../core/agent-session-runtime.js";
15
17
  import { CACHE_TTL_MS, collectCacheMisses, computeCacheWaste, detectCacheMiss, } from "../../core/cache-stats.js";
18
+ import { formatCacheWarmingStatus, formatCacheWarmingUsage } from "../../core/cache-warmer.js";
19
+ import { CheckpointManager } from "../../core/checkpoints/checkpoint-manager.js";
20
+ import { DEFAULT_REWIND_SCOPE, listRewindTargets, performRewind, REWIND_SCOPE_CHOICES, rewindScopeForLabel, } from "../../core/checkpoints/rewind.js";
16
21
  import { formatContextWindow } from "../../core/context-windows.js";
22
+ import { findExtensionStackMatches, recordCrash, takeUnnotifiedCrash } from "../../core/crash-log.js";
23
+ import { DEFAULT_THINKING_LEVEL, THINKING_LEVEL_OPTIONS } from "../../core/defaults.js";
17
24
  import { FooterDataProvider } from "../../core/footer-data-provider.js";
18
25
  import { configureHttpDispatcher, formatHttpIdleTimeoutMs } from "../../core/http-dispatcher.js";
19
26
  import { KeybindingsManager } from "../../core/keybindings.js";
20
- import { createCompactionSummaryMessage } from "../../core/messages.js";
21
- import { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope, resolveModelScopeWithDiagnostics, } from "../../core/model-resolver.js";
27
+ import { createCompactionSummaryMessage, createCustomMessage } from "../../core/messages.js";
28
+ import { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScopeFromModels, } from "../../core/model-resolver.js";
29
+ import { CredentialSynchronizationError } from "../../core/model-runtime.js";
22
30
  import { DefaultPackageManager } from "../../core/package-manager.js";
23
31
  import { formatMissingSessionCwdPrompt, MissingSessionCwdError } from "../../core/session-cwd.js";
24
- import { SessionManager, sessionEntryToContextMessages } from "../../core/session-manager.js";
32
+ import { SessionManager, sessionEntryToContextMessages, } from "../../core/session-manager.js";
25
33
  import { BUILTIN_SLASH_COMMANDS } from "../../core/slash-commands.js";
26
- import { isInstallTelemetryEnabled } from "../../core/telemetry.js";
34
+ import { boundedSafeText } from "../../core/socket-server/safe-text.js";
35
+ import { withBuiltInRenderers } from "../../core/tools/renderers/index.js";
27
36
  import { hasTrustRequiringProjectResources, ProjectTrustStore } from "../../core/trust-manager.js";
28
37
  import { getUsageCostBreakdown } from "../../core/usage-totals.js";
29
38
  import { getChangelogPath, getNewEntries, normalizeChangelogLinks, parseChangelog } from "../../utils/changelog.js";
30
- import { copyToClipboard, readClipboardText } from "../../utils/clipboard.js";
39
+ import { copyToClipboard, readClipboardFilePaths, readClipboardText } from "../../utils/clipboard.js";
31
40
  import { extensionForImageMimeType, readClipboardImage } from "../../utils/clipboard-image.js";
32
41
  import { parseGitUrl } from "../../utils/git.js";
33
42
  import { sendTerminalNotification } from "../../utils/notify.js";
34
43
  import { getCwdRelativePath } from "../../utils/paths.js";
35
- import { getPiUserAgent } from "../../utils/pi-user-agent.js";
36
44
  import { killTrackedDetachedChildren } from "../../utils/shell.js";
45
+ import { loadAllHighlightLanguages } from "../../utils/syntax-highlight.js";
37
46
  import { ensureTool } from "../../utils/tools-manager.js";
38
47
  import { checkForNewPiVersion } from "../../utils/version-check.js";
48
+ import { reportBug } from "./bug-report.js";
49
+ import { createChatViewport } from "./chat-viewport.js";
39
50
  import { ArminComponent } from "./components/armin.js";
40
51
  import { AssistantMessageComponent } from "./components/assistant-message.js";
41
52
  import { BashExecutionComponent } from "./components/bash-execution.js";
42
- import { BorderedLoader } from "./components/bordered-loader.js";
43
53
  import { BranchSummaryMessageComponent } from "./components/branch-summary-message.js";
44
54
  import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";
45
55
  import { CustomEditor } from "./components/custom-editor.js";
@@ -50,10 +60,11 @@ import { DynamicBorder } from "./components/dynamic-border.js";
50
60
  import { EarendilAnnouncementComponent } from "./components/earendil-announcement.js";
51
61
  import { ExtensionEditorComponent } from "./components/extension-editor.js";
52
62
  import { ExtensionInputComponent } from "./components/extension-input.js";
53
- import { ExtensionSelectorComponent } from "./components/extension-selector.js";
63
+ import { boundDialogText, ExtensionSelectorComponent, MAX_DETAIL_ROWS } from "./components/extension-selector.js";
54
64
  import { FooterComponent, formatTokens } from "./components/footer.js";
55
65
  import { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from "./components/keybinding-hints.js";
56
66
  import { LoginDialogComponent } from "./components/login-dialog.js";
67
+ import { createMermaidMarkdownTransformer } from "./components/mermaid.js";
57
68
  import { ModelSelectorComponent } from "./components/model-selector.js";
58
69
  import { formatAuthSelectorProviderType, OAuthSelectorComponent, } from "./components/oauth-selector.js";
59
70
  import { ScopedModelsSelectorComponent } from "./components/scoped-models-selector.js";
@@ -61,31 +72,51 @@ import { SessionSelectorComponent } from "./components/session-selector.js";
61
72
  import { SettingsSelectorComponent } from "./components/settings-selector.js";
62
73
  import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
63
74
  import { BranchSummaryStatusIndicator, CompactionStatusIndicator, IdleStatus, RetryStatusIndicator, WorkingStatusIndicator, } from "./components/status-indicator.js";
75
+ import { ThemedText } from "./components/themed-text.js";
76
+ import { ThinkingSelectorComponent } from "./components/thinking-selector.js";
64
77
  import { ToolExecutionComponent } from "./components/tool-execution.js";
65
78
  import { TreeSelectorComponent } from "./components/tree-selector.js";
66
79
  import { TrustSelectorComponent } from "./components/trust-selector.js";
67
80
  import { UserMessageComponent } from "./components/user-message.js";
68
81
  import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
69
82
  import { editInExternalEditor } from "./external-editor.js";
83
+ import { refreshModelCatalogs } from "./model-catalog-refresh.js";
70
84
  import { getModelSearchText } from "./model-search.js";
71
- import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getThemeByName, onThemeChange, setRegisteredThemes, stopThemeWatcher, Theme, theme, } from "./theme/theme.js";
85
+ import { shareSession } from "./session-share.js";
86
+ import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getThemeByName, onThemeChange, SYSTEM_THEME_NAME, setRegisteredThemes, stopThemeWatcher, Theme, theme, } from "./theme/theme.js";
72
87
  import { InteractiveThemeController } from "./theme/theme-controller.js";
88
+ import { createInteractiveTui, createInteractiveTuiReference } from "./tui-renderer.js";
89
+ export { createInteractiveTui, createInteractiveTuiReference } from "./tui-renderer.js";
90
+ function isWorkingStatusEditor(editor) {
91
+ return ("embedWorkingStatus" in editor &&
92
+ editor.embedWorkingStatus === true &&
93
+ "setWorkingStatusIndicator" in editor &&
94
+ typeof editor.setWorkingStatusIndicator === "function");
95
+ }
73
96
  function isExpandable(obj) {
74
97
  return typeof obj === "object" && obj !== null && "setExpanded" in obj && typeof obj.setExpanded === "function";
75
98
  }
76
- class ExpandableText extends Text {
99
+ class ExpandableText extends ThemedText {
100
+ state;
77
101
  constructor(getCollapsedText, getExpandedText, expanded = false, paddingX = 0, paddingY = 0) {
78
- super(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);
79
- this.getCollapsedText = getCollapsedText;
80
- this.getExpandedText = getExpandedText;
102
+ const state = { expanded };
103
+ super(() => (state.expanded ? getExpandedText() : getCollapsedText()), paddingX, paddingY);
104
+ this.state = state;
81
105
  }
82
106
  setExpanded(expanded) {
83
- this.setText(expanded ? this.getExpandedText() : this.getCollapsedText());
107
+ this.state.expanded = expanded;
108
+ this.invalidate();
84
109
  }
85
110
  }
86
111
  function isCustomSessionEntry(item) {
87
112
  return "type" in item && item.type === "custom";
88
113
  }
114
+ function isCompactionCostNotice(item) {
115
+ return "type" in item && item.type === "compaction_cost";
116
+ }
117
+ function isUsageSessionEntry(item) {
118
+ return "type" in item && item.type === "usage";
119
+ }
89
120
  const DEAD_TERMINAL_ERROR_CODES = new Set(["EIO", "EPIPE", "ENOTCONN"]);
90
121
  function isDeadTerminalError(error) {
91
122
  if (!error || typeof error !== "object" || !("code" in error)) {
@@ -94,6 +125,22 @@ function isDeadTerminalError(error) {
94
125
  const code = error.code;
95
126
  return code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);
96
127
  }
128
+ export function formatCrashExtensionHint(extensionMatches) {
129
+ const matches = Array.isArray(extensionMatches)
130
+ ? extensionMatches.filter((match) => typeof match === "string" && match.length > 0)
131
+ : [];
132
+ if (matches.length === 0)
133
+ return undefined;
134
+ const quoted = matches.map((match) => `\`${match}\``);
135
+ const labels = quoted.length === 1
136
+ ? quoted[0]
137
+ : quoted.length === 2
138
+ ? quoted.join(" and ")
139
+ : `${quoted.slice(0, -1).join(", ")}, and ${quoted[quoted.length - 1]}`;
140
+ const noun = matches.length === 1 ? "extension" : "extensions";
141
+ const pronoun = matches.length === 1 ? "it" : "them";
142
+ return `A stack frame came from loaded ${noun} ${labels}, which may be involved. Try disabling ${pronoun} with \`${APP_NAME} config\`, or run \`${APP_NAME} -ne\` to confirm.`;
143
+ }
97
144
  const ANTHROPIC_SUBSCRIPTION_AUTH_WARNING = "Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage. Disable this warning in /settings.";
98
145
  function isAnthropicSubscriptionAuthKey(apiKey) {
99
146
  return typeof apiKey === "string" && apiKey.startsWith("sk-ant-oat");
@@ -125,6 +172,11 @@ export function formatResumeCommand(sessionManager) {
125
172
  function hasDefaultModelProvider(providerId) {
126
173
  return providerId in defaultModelPerProvider;
127
174
  }
175
+ function llamaCppPostLoginGuidance(actionLabel, loadedModelCount) {
176
+ return loadedModelCount === 0
177
+ ? `${actionLabel}. No llama.cpp models are loaded. Use /llama to load a model, then /model to select it.`
178
+ : `${actionLabel}. Use /model to select a loaded llama.cpp model, or /llama to manage models.`;
179
+ }
128
180
  const AUTH_TYPE_ORDER = { oauth: 0, api_key: 1 };
129
181
  function createFuzzyAutocompleteItems(items, prefix, getSearchText, toAutocompleteItem) {
130
182
  const filtered = fuzzyFilter(items, prefix, getSearchText);
@@ -162,6 +214,132 @@ function formatLoginProviderCompletionDescription(provider) {
162
214
  return provider.name === provider.id ? authTypes : `${provider.name} · ${authTypes}`;
163
215
  }
164
216
  export class InteractiveMode {
217
+ runtimeHost;
218
+ renderer;
219
+ ui;
220
+ mainScreenRenderState;
221
+ loadedResourcesContainer;
222
+ chatContainer;
223
+ documentContainer;
224
+ transcriptScrollView;
225
+ fullscreenLayoutRoot;
226
+ pendingMessagesContainer;
227
+ statusContainer;
228
+ defaultEditor;
229
+ editor;
230
+ editorComponentFactory;
231
+ autocompleteProvider;
232
+ autocompleteProviderWrappers = [];
233
+ fdPath;
234
+ editorContainer;
235
+ activeSelectorToken;
236
+ activeSelectorDispose;
237
+ footer;
238
+ footerContainer;
239
+ footerDataProvider;
240
+ // Stored so the same manager can be injected into custom editors, selectors, and extension UI.
241
+ keybindings;
242
+ version;
243
+ isInitialized = false;
244
+ onInputCallback;
245
+ pendingUserInputs = [];
246
+ activeStatusIndicator = undefined;
247
+ activeWorkingIndicatorEmbedded = false;
248
+ idleStatus = new IdleStatus();
249
+ workingMessage = undefined;
250
+ workingVisible = true;
251
+ workingIndicatorOptions = undefined;
252
+ defaultWorkingMessage = "Working";
253
+ defaultHiddenThinkingLabel = "Thinking...";
254
+ hiddenThinkingLabel = this.defaultHiddenThinkingLabel;
255
+ lastSigintTime = 0;
256
+ lastEscapeTime = 0;
257
+ changelogMarkdown = undefined;
258
+ startupNoticesShown = false;
259
+ anthropicSubscriptionWarningShown = false;
260
+ // Status line tracking (for mutating immediately-sequential status updates)
261
+ lastStatusSpacer = undefined;
262
+ lastStatusText = undefined;
263
+ lastStatusMessage = "";
264
+ managedToolStatusStarted = false;
265
+ // Streaming message tracking
266
+ streamingComponent = undefined;
267
+ entriesRenderedByBoundaryCompaction = new Set();
268
+ streamingMessage = undefined;
269
+ // Tool execution tracking: toolCallId -> component
270
+ pendingTools = new Map();
271
+ // Tool output expansion state
272
+ toolOutputExpanded = false;
273
+ // Thinking block visibility state
274
+ hideThinkingBlock = false;
275
+ outputPad = 1;
276
+ mermaidMarkdownTransformer = createMermaidMarkdownTransformer({
277
+ getMode: () => this.settingsManager.getMermaidRenderingMode(),
278
+ theme,
279
+ });
280
+ // Skill commands: command name -> skill file path
281
+ skillCommands = new Map();
282
+ // Agent subscription unsubscribe function
283
+ unsubscribe;
284
+ signalCleanupHandlers = [];
285
+ // Track if editor is in bash mode (text starts with !)
286
+ isBashMode = false;
287
+ // True while `/rewind` is rewriting the working tree. The selector hands
288
+ // focus back to the editor before the restore finishes, so submissions have
289
+ // to be gated here or a new prompt runs against a half-restored tree.
290
+ isRewindRunning = false;
291
+ // Track current bash execution component
292
+ bashComponent = undefined;
293
+ // Track pending bash components (shown in pending area, moved to chat on submit)
294
+ pendingBashComponents = [];
295
+ // Auto-compaction state
296
+ autoCompactionEscapeHandler;
297
+ // Auto-retry state
298
+ retryEscapeHandler;
299
+ // Messages queued while compaction is running
300
+ compactionQueuedMessages = [];
301
+ // Shutdown state
302
+ shutdownRequested = false;
303
+ /** The `/bug` hint is shown at most once per session so error output stays readable. */
304
+ bugReportHintShown = false;
305
+ // Extension UI state
306
+ extensionSelector = undefined;
307
+ /**
308
+ * Settles the promise of the dialog currently occupying {@link extensionSelector}.
309
+ *
310
+ * The slot holds at most one dialog, so opening a second one used to overwrite the first without
311
+ * settling it — stranding a promise that `beforeToolCall` is awaiting, which wedges the agent
312
+ * loop forever. Keeping the settle function beside the component makes the slot non-clobbering.
313
+ */
314
+ extensionSelectorSettle = undefined;
315
+ /** Label of the surface that decided the open ask elsewhere, pending a one-line notice. */
316
+ extensionDialogDecidedBy = undefined;
317
+ extensionInput = undefined;
318
+ /** Settles the promise `showExtensionInput` returned. See {@link hideExtensionInput}. */
319
+ extensionInputSettle = undefined;
320
+ extensionEditor = undefined;
321
+ /** Settles the promise `showExtensionEditor` returned. See {@link hideExtensionEditor}. */
322
+ extensionEditorSettle = undefined;
323
+ extensionTerminalInputSubscriptions = new Set();
324
+ // Extension widgets (components rendered above/below the editor)
325
+ extensionWidgetsAbove = new Map();
326
+ extensionWidgetsBelow = new Map();
327
+ widgetContainerAbove;
328
+ widgetContainerBelow;
329
+ // Custom footer from extension (undefined = use built-in footer)
330
+ customFooter = undefined;
331
+ // Header container that holds the built-in or custom header
332
+ headerContainer;
333
+ // Built-in header (logo + keybinding hints + changelog)
334
+ builtInHeader = undefined;
335
+ // Custom header from extension (undefined = use built-in header)
336
+ customHeader = undefined;
337
+ options;
338
+ onRightClickPaste = () => {
339
+ void this.handleRightClickPaste();
340
+ };
341
+ autoTrustOnReloadCwd;
342
+ themeController;
165
343
  // Convenience accessors
166
344
  get session() {
167
345
  return this.runtimeHost.session;
@@ -176,83 +354,37 @@ export class InteractiveMode {
176
354
  return this.session.settingsManager;
177
355
  }
178
356
  constructor(runtimeHost, options = {}) {
179
- this.autocompleteProviderWrappers = [];
180
- this.isInitialized = false;
181
- this.pendingUserInputs = [];
182
- this.activeStatusIndicator = undefined;
183
- this.idleStatus = new IdleStatus();
184
- this.workingMessage = undefined;
185
- this.workingVisible = true;
186
- this.workingIndicatorOptions = undefined;
187
- this.defaultWorkingMessage = "Working...";
188
- this.defaultHiddenThinkingLabel = "Thinking...";
189
- this.hiddenThinkingLabel = this.defaultHiddenThinkingLabel;
190
- this.lastSigintTime = 0;
191
- this.lastEscapeTime = 0;
192
- this.changelogMarkdown = undefined;
193
- this.startupNoticesShown = false;
194
- this.anthropicSubscriptionWarningShown = false;
195
- // Status line tracking (for mutating immediately-sequential status updates)
196
- this.lastStatusSpacer = undefined;
197
- this.lastStatusText = undefined;
198
- // Streaming message tracking
199
- this.streamingComponent = undefined;
200
- this.streamingMessage = undefined;
201
- // Tool execution tracking: toolCallId -> component
202
- this.pendingTools = new Map();
203
- // Tool output expansion state
204
- this.toolOutputExpanded = false;
205
- // Thinking block visibility state
206
- this.hideThinkingBlock = false;
207
- this.outputPad = 1;
208
- // Skill commands: command name -> skill file path
209
- this.skillCommands = new Map();
210
- this.signalCleanupHandlers = [];
211
- // Track if editor is in bash mode (text starts with !)
212
- this.isBashMode = false;
213
- // Track current bash execution component
214
- this.bashComponent = undefined;
215
- // Track pending bash components (shown in pending area, moved to chat on submit)
216
- this.pendingBashComponents = [];
217
- // Messages queued while compaction is running
218
- this.compactionQueuedMessages = [];
219
- // Shutdown state
220
- this.shutdownRequested = false;
221
- // Extension UI state
222
- this.extensionSelector = undefined;
223
- this.extensionInput = undefined;
224
- this.extensionEditor = undefined;
225
- this.extensionTerminalInputUnsubscribers = new Set();
226
- // Extension widgets (components rendered above/below the editor)
227
- this.extensionWidgetsAbove = new Map();
228
- this.extensionWidgetsBelow = new Map();
229
- // Custom footer from extension (undefined = use built-in footer)
230
- this.customFooter = undefined;
231
- // Built-in header (logo + keybinding hints + changelog)
232
- this.builtInHeader = undefined;
233
- // Custom header from extension (undefined = use built-in header)
234
- this.customHeader = undefined;
235
- /**
236
- * Gracefully shutdown the agent.
237
- * Stops the TUI before emitting shutdown events so extension UI cleanup cannot
238
- * repaint the final frame while the process is exiting.
239
- */
240
- this.isShuttingDown = false;
241
357
  this.runtimeHost = runtimeHost;
242
- this.options = options;
358
+ setCapabilityOverrides(this.settingsManager.getTerminalCapabilityOverrides());
359
+ const tuiMode = options.tuiMode ?? this.settingsManager.getTuiMode();
360
+ this.options = { ...options, tuiMode };
243
361
  this.autoTrustOnReloadCwd = options.autoTrustOnReloadCwd;
244
362
  this.runtimeHost.setBeforeSessionInvalidate(() => {
245
363
  this.resetExtensionUI();
246
364
  });
247
365
  this.runtimeHost.setRebindSession(async () => {
248
366
  await this.rebindCurrentSession({ renderBeforeBind: true });
367
+ this.themeController.applyFromSettings();
249
368
  });
250
369
  this.version = VERSION;
251
- this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor(), getAgentDir());
370
+ this.renderer = createInteractiveTui({
371
+ tuiMode,
372
+ showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
373
+ logDirectory: getAgentDir(),
374
+ terminal: options.terminal,
375
+ onRightClickPaste: this.onRightClickPaste,
376
+ fullscreenCopyOnSelect: this.settingsManager.getFullscreenCopyOnSelect(),
377
+ fullscreenWheelScrollLines: this.settingsManager.getFullscreenWheelScrollLines(),
378
+ });
379
+ this.ui = createInteractiveTuiReference(() => this.renderer);
252
380
  this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
253
381
  this.headerContainer = new Container();
254
382
  this.loadedResourcesContainer = new Container();
255
383
  this.chatContainer = new Container();
384
+ this.documentContainer = new Container();
385
+ this.documentContainer.addChild(this.headerContainer);
386
+ this.documentContainer.addChild(this.loadedResourcesContainer);
387
+ this.documentContainer.addChild(this.chatContainer);
256
388
  this.pendingMessagesContainer = new Container();
257
389
  this.statusContainer = new Container();
258
390
  this.widgetContainerAbove = new Container();
@@ -264,6 +396,7 @@ export class InteractiveMode {
264
396
  this.defaultEditor = new CustomEditor(this.ui, getEditorTheme(), this.keybindings, {
265
397
  paddingX: editorPaddingX,
266
398
  autocompleteMaxVisible,
399
+ embedWorkingStatus: true,
267
400
  });
268
401
  this.editor = this.defaultEditor;
269
402
  this.editorContainer = new Container();
@@ -271,15 +404,23 @@ export class InteractiveMode {
271
404
  this.footerDataProvider = new FooterDataProvider(this.sessionManager.getCwd());
272
405
  this.footer = new FooterComponent(this.session, this.footerDataProvider);
273
406
  this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);
407
+ this.footerContainer = new Container();
408
+ this.footerContainer.addChild(this.footer);
274
409
  // Load hide thinking block setting
275
410
  this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
276
411
  this.outputPad = this.settingsManager.getOutputPad();
277
412
  // Register themes from resource loader and initialize
278
413
  setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
279
- this.themeController = new InteractiveThemeController(this.ui, this.settingsManager, (message) => this.showError(message), () => this.updateEditorBorderColor());
414
+ this.themeController = new InteractiveThemeController(this.ui, {
415
+ getSettingsManager: () => this.settingsManager,
416
+ showError: (message) => this.showError(message),
417
+ onChanged: () => this.updateEditorBorderColor(),
418
+ initialThemeSetting: options.initialThemeSetting,
419
+ });
280
420
  }
281
421
  getAutocompleteSourceTag(sourceInfo) {
282
- if (!sourceInfo) {
422
+ // Built-in extension commands are untagged, like built-in commands.
423
+ if (!sourceInfo || sourceInfo.source === "builtin") {
283
424
  return undefined;
284
425
  }
285
426
  const scopePrefix = sourceInfo.scope === "user" ? "u" : sourceInfo.scope === "project" ? "p" : "t";
@@ -326,11 +467,10 @@ export class InteractiveMode {
326
467
  }));
327
468
  const modelCommand = slashCommands.find((command) => command.name === "model");
328
469
  if (modelCommand) {
329
- modelCommand.getArgumentCompletions = async (prefix) => {
330
- // Get available models (scoped or from registry)
470
+ modelCommand.getArgumentCompletions = (prefix) => {
331
471
  const models = this.session.scopedModels.length > 0
332
472
  ? this.session.scopedModels.map((s) => s.model)
333
- : await this.session.modelRuntime.getAvailable();
473
+ : this.session.modelRuntime.getAvailableSnapshot();
334
474
  if (models.length === 0)
335
475
  return null;
336
476
  // Create items with provider/id format
@@ -347,6 +487,15 @@ export class InteractiveMode {
347
487
  }));
348
488
  };
349
489
  }
490
+ const thinkingCommand = slashCommands.find((command) => command.name === "thinking");
491
+ if (thinkingCommand) {
492
+ thinkingCommand.getArgumentCompletions = (prefix) => {
493
+ return createFuzzyAutocompleteItems(this.session.getAvailableThinkingLevels(), prefix, (level) => level, (level) => ({
494
+ value: level,
495
+ label: level,
496
+ }));
497
+ };
498
+ }
350
499
  const loginCommand = slashCommands.find((command) => command.name === "login");
351
500
  if (loginCommand) {
352
501
  loginCommand.getArgumentCompletions = (prefix) => {
@@ -424,23 +573,88 @@ export class InteractiveMode {
424
573
  this.chatContainer.addChild(new Text(condensedText, 1, 0));
425
574
  }
426
575
  else {
427
- this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
576
+ this.chatContainer.addChild(new ThemedText(() => theme.bold(theme.fg("accent", "What's New")), 1, 0));
428
577
  this.chatContainer.addChild(new Spacer(1));
429
578
  this.chatContainer.addChild(new Markdown(this.changelogMarkdown.trim(), 1, 0, this.getMarkdownThemeWithSettings()));
430
579
  this.chatContainer.addChild(new Spacer(1));
431
580
  }
432
581
  this.chatContainer.addChild(new DynamicBorder());
433
582
  }
583
+ mountInteractiveTui(tui, components) {
584
+ for (const component of components)
585
+ tui.addChild(component);
586
+ if (TuiLayouts.isViewportTUI(tui)) {
587
+ if (!this.fullscreenLayoutRoot)
588
+ throw new Error("Fullscreen layout is not initialized");
589
+ tui.setLayoutRoot(this.fullscreenLayoutRoot);
590
+ }
591
+ }
592
+ stopInteractiveTui(fullscreenExitOutput) {
593
+ if (this.renderer.mode === "fullscreen" && fullscreenExitOutput === "transcript") {
594
+ while (this.renderer.hasOverlayEntries)
595
+ this.renderer.hideOverlay();
596
+ this.switchTuiMode("regular", false, false);
597
+ this.renderer.renderNow();
598
+ }
599
+ this.ui.stop({ preserveScreen: this.renderer.mode === "fullscreen" });
600
+ }
601
+ switchTuiMode(mode, restoreProgress = true, startRenderer = true) {
602
+ const previousUi = this.renderer;
603
+ if (mode === previousUi.mode)
604
+ return true;
605
+ if (previousUi.hasOverlayEntries)
606
+ return false;
607
+ const components = [...previousUi.children];
608
+ const focus = previousUi.getFocusedComponent();
609
+ const terminal = previousUi.terminal;
610
+ const showHardwareCursor = previousUi.getShowHardwareCursor();
611
+ const clearOnShrink = previousUi.getClearOnShrink();
612
+ const onDebug = previousUi.onDebug;
613
+ if (previousUi instanceof TuiMainScreen) {
614
+ this.mainScreenRenderState = previousUi.captureRenderState();
615
+ }
616
+ previousUi.stop({ preserveScreen: true });
617
+ previousUi.setFocus(null);
618
+ previousUi.clear();
619
+ if (TuiLayouts.isViewportTUI(previousUi))
620
+ previousUi.setLayoutRoot(undefined);
621
+ const nextUi = createInteractiveTui({
622
+ tuiMode: mode,
623
+ showHardwareCursor,
624
+ logDirectory: getAgentDir(),
625
+ terminal,
626
+ onRightClickPaste: this.onRightClickPaste,
627
+ fullscreenCopyOnSelect: this.settingsManager.getFullscreenCopyOnSelect(),
628
+ fullscreenWheelScrollLines: this.settingsManager.getFullscreenWheelScrollLines(),
629
+ });
630
+ nextUi.setClearOnShrink(clearOnShrink);
631
+ nextUi.onDebug = onDebug;
632
+ if (nextUi instanceof TuiMainScreen && this.mainScreenRenderState) {
633
+ nextUi.restoreRenderState(this.mainScreenRenderState);
634
+ }
635
+ this.renderer = nextUi;
636
+ this.options.tuiMode = mode;
637
+ this.mountInteractiveTui(nextUi, components);
638
+ nextUi.invalidate();
639
+ nextUi.setFocus(focus);
640
+ if (!startRenderer)
641
+ return true;
642
+ nextUi.start();
643
+ this.themeController.rebindTui();
644
+ this.rebindExtensionTerminalInputListeners();
645
+ if (restoreProgress &&
646
+ this.settingsManager.getShowTerminalProgress() &&
647
+ (this.session.isStreaming || this.session.isCompacting)) {
648
+ terminal.setProgress(true);
649
+ }
650
+ return true;
651
+ }
434
652
  async init() {
435
653
  if (this.isInitialized)
436
654
  return;
437
655
  this.registerSignalHandlers();
438
656
  // Load changelog (only show new entries, skip for resumed sessions)
439
657
  this.changelogMarkdown = this.getChangelogForDisplay();
440
- // Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)
441
- // Both are needed: fd for autocomplete, rg for grep tool and bash commands
442
- const [fdPath] = await Promise.all([ensureTool("fd"), ensureTool("rg")]);
443
- this.fdPath = fdPath;
444
658
  if (this.session.scopedModels.length > 0 && (this.options.verbose || !this.settingsManager.getQuietStartup())) {
445
659
  const modelList = this.session.scopedModels
446
660
  .map((sm) => {
@@ -454,43 +668,65 @@ export class InteractiveMode {
454
668
  : "";
455
669
  console.log(theme.fg("dim", `Model scope: ${modelList}${cycleHint}`));
456
670
  }
457
- // Add header container as first child. Populate it after applying theme settings.
458
- // Keep loaded resources before chat so restored session messages never precede them.
459
- this.ui.addChild(this.headerContainer);
460
- this.ui.addChild(this.loadedResourcesContainer);
461
- this.ui.addChild(this.chatContainer);
462
- this.ui.addChild(this.pendingMessagesContainer);
463
- this.ui.addChild(this.statusContainer);
671
+ // Keep one component tree and remount it when changing renderers.
464
672
  this.renderWidgets(); // Initialize with default spacer
465
- this.ui.addChild(this.widgetContainerAbove);
466
- this.ui.addChild(this.editorContainer);
467
- this.ui.addChild(this.widgetContainerBelow);
468
- this.ui.addChild(this.footer);
673
+ const viewport = createChatViewport({
674
+ document: this.documentContainer,
675
+ pendingMessages: this.pendingMessagesContainer,
676
+ status: this.statusContainer,
677
+ widgetsAbove: this.widgetContainerAbove,
678
+ editor: this.editorContainer,
679
+ widgetsBelow: this.widgetContainerBelow,
680
+ footer: this.footerContainer,
681
+ scrollbar: this.settingsManager.getFullscreenScrollbar(),
682
+ scrollbarTrackStyle: (text) => theme.fg("scrollbarTrack", text),
683
+ scrollbarThumbStyle: (text) => theme.fg("scrollbarThumb", text),
684
+ });
685
+ this.transcriptScrollView = viewport.transcript;
686
+ this.fullscreenLayoutRoot = viewport.root;
687
+ this.mountInteractiveTui(this.renderer, [
688
+ this.documentContainer,
689
+ this.pendingMessagesContainer,
690
+ this.statusContainer,
691
+ this.widgetContainerAbove,
692
+ this.editorContainer,
693
+ this.widgetContainerBelow,
694
+ this.footerContainer,
695
+ ]);
696
+ // Accept text while startup completes, but only enable interrupt, exit, and submission feedback.
697
+ this.defaultEditor.onAction("app.clear", () => this.handleCtrlC());
698
+ this.defaultEditor.onCtrlD = () => this.handleCtrlD();
699
+ this.defaultEditor.onSubmit = (text) => this.handleStartupSubmit(text);
469
700
  this.ui.setFocus(this.editor);
470
- this.setupKeyHandlers();
471
- this.setupEditorSubmitHandler();
472
701
  // Start the UI before initializing extensions so session_start handlers can use interactive dialogs
473
702
  this.ui.start();
474
703
  this.isInitialized = true;
475
- await this.themeController.applyFromSettings();
704
+ this.themeController.applyFromSettings();
705
+ // The header and startup notices bake theme colors into their text, so build them once the terminal
706
+ // reported its colors. This ends at the terminal's DA1 reply, or after 100 ms if it answers nothing.
707
+ await this.themeController.waitForTerminalColors();
476
708
  // Add header with keybindings from config (unless silenced)
477
709
  if (this.options.verbose || !this.settingsManager.getQuietStartup()) {
478
- const asciiArt = [
479
- " ╭─╮",
480
- " ╰─┼──────────╮",
481
- " │ ┌──────╮ │",
482
- " │ │ │ │",
483
- " │ │ │ │",
484
- " └─┼──────╯ │",
485
- " └────────╯",
486
- ]
487
- .map((line) => theme.fg("border", line))
488
- .join("\n");
489
- const wordmark = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${DISPLAY_VERSION} · /dʁaːt/`);
490
- const logo = `${asciiArt}\n${wordmark}`;
710
+ // Built on demand so the header follows theme changes.
711
+ const logo = () => {
712
+ const asciiArt = [
713
+ " ╭─╮",
714
+ " ╰─┼──────────╮",
715
+ " │ ┌──────╮ │",
716
+ " │ │ │ │",
717
+ " │ │ │ │",
718
+ " └─┼──────╯ │",
719
+ " └────────╯",
720
+ ]
721
+ .map((line) => theme.fg("border", line))
722
+ .join("\n");
723
+ const wordmark = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${DISPLAY_VERSION} · /dʁaːt/`);
724
+ return `${asciiArt}\n${wordmark}`;
725
+ };
726
+ const withLogo = (hints) => `${logo()}\n${hints}`;
491
727
  // Build startup instructions using keybinding hint helpers
492
728
  const hint = (keybinding, description) => keyHint(keybinding, description);
493
- const expandedInstructions = [
729
+ const expandedInstructions = () => [
494
730
  hint("app.interrupt", "to interrupt"),
495
731
  hint("app.clear", "to clear"),
496
732
  rawKeyHint(`${keyText("app.clear")} twice`, "to exit"),
@@ -511,19 +747,19 @@ export class InteractiveMode {
511
747
  rawKeyHint("!!", "to run bash (no context)"),
512
748
  hint("app.message.followUp", "to queue follow-up"),
513
749
  hint("app.message.dequeue", "to edit all queued messages"),
514
- hint("app.clipboard.pasteImage", "to paste image (with text fallback)"),
750
+ hint("app.clipboard.pasteImage", "to paste files on macOS, images, or text"),
515
751
  rawKeyHint("drop files", "to attach"),
516
752
  ].join("\n");
517
- const compactInstructions = [
753
+ const compactInstructions = () => [
518
754
  hint("app.interrupt", "interrupt"),
519
755
  rawKeyHint(`${keyText("app.clear")}/${keyText("app.exit")}`, "clear/exit"),
520
756
  rawKeyHint("/", "commands"),
521
757
  rawKeyHint("!", "bash"),
522
758
  hint("app.tools.expand", "more"),
523
759
  ].join(theme.fg("muted", " · "));
524
- const compactOnboarding = theme.fg("dim", `Press ${keyText("app.tools.expand")} to show full startup help and loaded resources.`);
525
- const onboarding = theme.fg("dim", `${APP_NAME} can explain its own features and look up its docs. Ask it how to use or extend ${APP_NAME}.`);
526
- this.builtInHeader = new ExpandableText(() => `${logo}\n${compactInstructions}\n${compactOnboarding}\n\n${onboarding}`, () => `${logo}\n${expandedInstructions}\n\n${onboarding}`, this.getStartupExpansionState(), 1, 0);
760
+ const compactOnboarding = () => theme.fg("dim", `Press ${keyText("app.tools.expand")} to show full startup help and loaded resources.`);
761
+ const onboarding = () => theme.fg("dim", `${APP_NAME} can explain its own features and look up its docs. Ask it how to use or extend ${APP_NAME}.`);
762
+ this.builtInHeader = new ExpandableText(() => `${withLogo(compactInstructions())}\n${compactOnboarding()}\n\n${onboarding()}`, () => `${withLogo(expandedInstructions())}\n\n${onboarding()}`, this.getStartupExpansionState(), 1, 0);
527
763
  // Setup UI layout
528
764
  this.headerContainer.addChild(new Spacer(1));
529
765
  this.headerContainer.addChild(this.builtInHeader);
@@ -535,6 +771,18 @@ export class InteractiveMode {
535
771
  this.headerContainer.addChild(this.builtInHeader);
536
772
  }
537
773
  this.ui.requestRender();
774
+ // Ensure fd and rg are available after mounting the TUI (downloads if missing, adds to PATH via getBinDir)
775
+ // so slow downloads do not make startup appear frozen.
776
+ // Both are needed: fd for autocomplete, rg for grep tool and bash commands.
777
+ const [fdPath] = await Promise.all([
778
+ ensureTool("fd", (status) => this.showManagedToolStatus(status)),
779
+ ensureTool("rg", (status) => this.showManagedToolStatus(status)),
780
+ ]);
781
+ this.fdPath = fdPath;
782
+ // Enable the remaining input handlers only after managed-tool setup completes.
783
+ this.setupKeyHandlers();
784
+ this.setupEditorSubmitHandler();
785
+ this.ui.requestRender();
538
786
  // Initialize extensions first so resources are shown before messages
539
787
  await this.rebindCurrentSession();
540
788
  // Render initial messages AFTER showing loaded resources
@@ -551,6 +799,14 @@ export class InteractiveMode {
551
799
  });
552
800
  // Initialize available provider count for footer display
553
801
  await this.updateAvailableProviderCount();
802
+ // Flush the completed startup state before loading the remaining syntax grammars.
803
+ this.ui.renderNow();
804
+ void loadAllHighlightLanguages().then(() => {
805
+ if (!this.isInitialized)
806
+ return;
807
+ this.ui.invalidate();
808
+ this.ui.requestRender();
809
+ });
554
810
  }
555
811
  /**
556
812
  * Update terminal title with session name and cwd.
@@ -572,10 +828,12 @@ export class InteractiveMode {
572
828
  async run() {
573
829
  await this.init();
574
830
  if (!process.env.DRAHT_OFFLINE) {
575
- void this.session.modelRuntime
576
- .refresh()
831
+ const controller = new AbortController();
832
+ const timeout = setTimeout(() => controller.abort(), 15_000);
833
+ void refreshModelCatalogs(this.session.modelRuntime, controller.signal)
577
834
  .then(() => this.updateAvailableProviderCount())
578
- .catch(() => { });
835
+ .catch(() => { })
836
+ .finally(() => clearTimeout(timeout));
579
837
  }
580
838
  // Start version check asynchronously
581
839
  checkForNewPiVersion(this.version).then((newRelease) => {
@@ -604,7 +862,18 @@ export class InteractiveMode {
604
862
  }
605
863
  });
606
864
  // Show startup warnings
607
- const { migratedProviders, modelFallbackMessage, initialMessage, initialImages, initialMessages } = this.options;
865
+ const { migratedProviders, startupDiagnostics, modelFallbackMessage, initialMessage, initialImages, initialMessages, } = this.options;
866
+ for (const diagnostic of startupDiagnostics ?? []) {
867
+ if (diagnostic.type === "error") {
868
+ this.showError(diagnostic.message);
869
+ }
870
+ else if (diagnostic.type === "warning") {
871
+ this.showWarning(diagnostic.message);
872
+ }
873
+ else {
874
+ this.showStatus(diagnostic.message);
875
+ }
876
+ }
608
877
  if (migratedProviders && migratedProviders.length > 0) {
609
878
  this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`);
610
879
  }
@@ -615,6 +884,11 @@ export class InteractiveMode {
615
884
  if (modelFallbackMessage) {
616
885
  this.showWarning(modelFallbackMessage);
617
886
  }
887
+ const crash = takeUnnotifiedCrash();
888
+ if (crash) {
889
+ const when = new Date(crash.timestamp).toLocaleString();
890
+ this.showWarning(`${APP_NAME} crashed on ${when} (${crash.message}). Run /bug to report it; the crash details are attached automatically.`);
891
+ }
618
892
  void this.maybeWarnAboutAnthropicSubscriptionAuth();
619
893
  // Process initial messages
620
894
  if (initialMessage) {
@@ -720,35 +994,17 @@ export class InteractiveMode {
720
994
  const changelogPath = getChangelogPath();
721
995
  const entries = parseChangelog(changelogPath);
722
996
  if (!lastVersion) {
723
- // Fresh install - record the version, send telemetry, don't show changelog
997
+ // Fresh install - record the version, don't show changelog
724
998
  this.settingsManager.setLastChangelogVersion(VERSION);
725
- this.reportInstallTelemetry(VERSION);
726
999
  return undefined;
727
1000
  }
728
1001
  const newEntries = getNewEntries(entries, lastVersion);
729
1002
  if (newEntries.length > 0) {
730
1003
  this.settingsManager.setLastChangelogVersion(VERSION);
731
- this.reportInstallTelemetry(VERSION);
732
1004
  return newEntries.map((e) => normalizeChangelogLinks(e.content, e)).join("\n\n");
733
1005
  }
734
1006
  return undefined;
735
1007
  }
736
- reportInstallTelemetry(version) {
737
- if (process.env.DRAHT_OFFLINE) {
738
- return;
739
- }
740
- if (!isInstallTelemetryEnabled(this.settingsManager)) {
741
- return;
742
- }
743
- void fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {
744
- headers: {
745
- "User-Agent": getPiUserAgent(version),
746
- },
747
- signal: AbortSignal.timeout(5000),
748
- })
749
- .then(() => undefined)
750
- .catch(() => undefined);
751
- }
752
1008
  getMarkdownThemeWithSettings() {
753
1009
  return {
754
1010
  ...getMarkdownTheme(),
@@ -1058,8 +1314,9 @@ export class InteractiveMode {
1058
1314
  }
1059
1315
  return theme.fg("dim", ` ${labels.join(", ")}`);
1060
1316
  };
1317
+ // Bodies are built on demand so the listing follows theme changes.
1061
1318
  const addLoadedSection = (name, collapsedBody, expandedBody = collapsedBody, color = "mdHeading") => {
1062
- const section = new ExpandableText(() => `${sectionHeader(name, color)}\n${collapsedBody}`, () => `${sectionHeader(name, color)}\n${expandedBody}`, this.getStartupExpansionState(), 0, 0);
1319
+ const section = new ExpandableText(() => `${sectionHeader(name, color)}\n${collapsedBody()}`, () => `${sectionHeader(name, color)}\n${expandedBody()}`, this.getStartupExpansionState(), 0, 0);
1063
1320
  this.loadedResourcesContainer.addChild(section);
1064
1321
  this.loadedResourcesContainer.addChild(new Spacer(1));
1065
1322
  };
@@ -1104,27 +1361,25 @@ export class InteractiveMode {
1104
1361
  ];
1105
1362
  if (contextFiles.length > 0) {
1106
1363
  this.loadedResourcesContainer.addChild(new Spacer(1));
1107
- const contextList = contextFiles
1108
- .map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`))
1109
- .join("\n");
1110
- const contextCompactList = formatCompactList(contextFiles.map((contextFile) => this.formatContextPath(contextFile.path)), { sort: false });
1364
+ const contextList = () => contextFiles.map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`)).join("\n");
1365
+ const contextCompactList = () => formatCompactList(contextFiles.map((contextFile) => this.formatContextPath(contextFile.path)), { sort: false });
1111
1366
  addLoadedSection("Context", contextCompactList, contextList);
1112
1367
  }
1113
1368
  const skills = skillsResult.skills;
1114
1369
  if (skills.length > 0) {
1115
1370
  const groups = this.buildScopeGroups(skills.map((skill) => ({ path: skill.filePath, sourceInfo: skill.sourceInfo })));
1116
- const skillList = this.formatScopeGroups(groups, {
1371
+ const skillList = () => this.formatScopeGroups(groups, {
1117
1372
  formatPath: (item) => this.formatDisplayPath(item.path),
1118
1373
  formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),
1119
1374
  });
1120
- const skillCompactList = formatCompactList(skills.map((skill) => skill.name));
1375
+ const skillCompactList = () => formatCompactList(skills.map((skill) => skill.name));
1121
1376
  addLoadedSection("Skills", skillCompactList, skillList);
1122
1377
  }
1123
1378
  const templates = this.session.promptTemplates;
1124
1379
  if (templates.length > 0) {
1125
1380
  const groups = this.buildScopeGroups(templates.map((template) => ({ path: template.filePath, sourceInfo: template.sourceInfo })));
1126
1381
  const templateByPath = new Map(templates.map((t) => [t.filePath, t]));
1127
- const templateList = this.formatScopeGroups(groups, {
1382
+ const templateList = () => this.formatScopeGroups(groups, {
1128
1383
  formatPath: (item) => {
1129
1384
  const template = templateByPath.get(item.path);
1130
1385
  return template ? `/${template.name}` : this.formatDisplayPath(item.path);
@@ -1134,53 +1389,40 @@ export class InteractiveMode {
1134
1389
  return template ? `/${template.name}` : this.formatDisplayPath(item.path);
1135
1390
  },
1136
1391
  });
1137
- const promptCompactList = formatCompactList(templates.map((template) => `/${template.name}`));
1392
+ const promptCompactList = () => formatCompactList(templates.map((template) => `/${template.name}`));
1138
1393
  addLoadedSection("Prompts", promptCompactList, templateList);
1139
1394
  }
1140
1395
  if (extensions.length > 0) {
1141
1396
  const groups = this.buildScopeGroups(extensions);
1142
- const extList = this.formatScopeGroups(groups, {
1397
+ const extList = () => this.formatScopeGroups(groups, {
1143
1398
  formatPath: (item) => this.formatExtensionDisplayPath(item.path),
1144
1399
  formatPackagePath: (item) => this.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)),
1145
1400
  });
1146
- const extensionCompactList = formatCompactList(this.getCompactExtensionLabels(extensions));
1401
+ const extensionLabels = this.getCompactExtensionLabels(extensions);
1402
+ const extensionCompactList = () => formatCompactList(extensionLabels);
1147
1403
  addLoadedSection("Extensions", extensionCompactList, extList, "mdHeading");
1148
1404
  }
1149
- // Show loaded themes (excluding built-in)
1150
- const loadedThemes = themesResult.themes;
1151
- const customThemes = loadedThemes.filter((t) => t.sourcePath);
1152
- if (customThemes.length > 0) {
1153
- const groups = this.buildScopeGroups(customThemes.map((loadedTheme) => ({
1154
- path: loadedTheme.sourcePath,
1155
- sourceInfo: loadedTheme.sourceInfo,
1156
- })));
1157
- const themeList = this.formatScopeGroups(groups, {
1158
- formatPath: (item) => this.formatDisplayPath(item.path),
1159
- formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),
1160
- });
1161
- const themeCompactList = formatCompactList(customThemes.map((loadedTheme) => loadedTheme.name ?? this.getCompactPathLabel(loadedTheme.sourcePath, loadedTheme.sourceInfo)));
1162
- addLoadedSection("Themes", themeCompactList, themeList);
1163
- }
1164
1405
  }
1165
1406
  if (showDiagnostics) {
1166
1407
  const skillDiagnostics = skillsResult.diagnostics;
1167
1408
  if (skillDiagnostics.length > 0) {
1168
- const warningLines = this.formatDiagnostics(skillDiagnostics, sourceInfos);
1169
- this.loadedResourcesContainer.addChild(new Text(`${theme.fg("warning", "[Skill conflicts]")}\n${warningLines}`, 0, 0));
1409
+ const warningLines = () => this.formatDiagnostics(skillDiagnostics, sourceInfos);
1410
+ this.loadedResourcesContainer.addChild(new ThemedText(() => `${theme.fg("warning", "[Skill conflicts]")}\n${warningLines()}`, 0, 0));
1170
1411
  this.loadedResourcesContainer.addChild(new Spacer(1));
1171
1412
  }
1172
1413
  const promptDiagnostics = promptsResult.diagnostics;
1173
1414
  if (promptDiagnostics.length > 0) {
1174
- const warningLines = this.formatDiagnostics(promptDiagnostics, sourceInfos);
1175
- this.loadedResourcesContainer.addChild(new Text(`${theme.fg("warning", "[Prompt conflicts]")}\n${warningLines}`, 0, 0));
1415
+ const warningLines = () => this.formatDiagnostics(promptDiagnostics, sourceInfos);
1416
+ this.loadedResourcesContainer.addChild(new ThemedText(() => `${theme.fg("warning", "[Prompt conflicts]")}\n${warningLines()}`, 0, 0));
1176
1417
  this.loadedResourcesContainer.addChild(new Spacer(1));
1177
1418
  }
1178
1419
  const extensionDiagnostics = [];
1179
- const extensionErrors = this.session.resourceLoader.getExtensions().errors;
1180
- if (extensionErrors.length > 0) {
1181
- for (const error of extensionErrors) {
1182
- extensionDiagnostics.push({ type: "error", message: error.error, path: error.path });
1183
- }
1420
+ const extensionsResult = this.session.resourceLoader.getExtensions();
1421
+ for (const error of extensionsResult.errors) {
1422
+ extensionDiagnostics.push({ type: "error", message: error.error, path: error.path });
1423
+ }
1424
+ for (const warning of extensionsResult.warnings ?? []) {
1425
+ extensionDiagnostics.push({ type: "warning", message: warning.warning, path: warning.path });
1184
1426
  }
1185
1427
  const commandDiagnostics = this.session.extensionRunner.getCommandDiagnostics();
1186
1428
  extensionDiagnostics.push(...commandDiagnostics);
@@ -1188,14 +1430,14 @@ export class InteractiveMode {
1188
1430
  const shortcutDiagnostics = this.session.extensionRunner.getShortcutDiagnostics();
1189
1431
  extensionDiagnostics.push(...shortcutDiagnostics);
1190
1432
  if (extensionDiagnostics.length > 0) {
1191
- const warningLines = this.formatDiagnostics(extensionDiagnostics, sourceInfos);
1192
- this.loadedResourcesContainer.addChild(new Text(`${theme.fg("warning", "[Extension issues]")}\n${warningLines}`, 0, 0));
1433
+ const warningLines = () => this.formatDiagnostics(extensionDiagnostics, sourceInfos);
1434
+ this.loadedResourcesContainer.addChild(new ThemedText(() => `${theme.fg("warning", "[Extension issues]")}\n${warningLines()}`, 0, 0));
1193
1435
  this.loadedResourcesContainer.addChild(new Spacer(1));
1194
1436
  }
1195
1437
  const themeDiagnostics = themesResult.diagnostics;
1196
1438
  if (themeDiagnostics.length > 0) {
1197
- const warningLines = this.formatDiagnostics(themeDiagnostics, sourceInfos);
1198
- this.loadedResourcesContainer.addChild(new Text(`${theme.fg("warning", "[Theme conflicts]")}\n${warningLines}`, 0, 0));
1439
+ const warningLines = () => this.formatDiagnostics(themeDiagnostics, sourceInfos);
1440
+ this.loadedResourcesContainer.addChild(new ThemedText(() => `${theme.fg("warning", "[Theme conflicts]")}\n${warningLines()}`, 0, 0));
1199
1441
  this.loadedResourcesContainer.addChild(new Spacer(1));
1200
1442
  }
1201
1443
  }
@@ -1278,8 +1520,17 @@ export class InteractiveMode {
1278
1520
  this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });
1279
1521
  this.showStartupNoticesIfNeeded();
1280
1522
  }
1523
+ applyFullscreenScrollbarSetting() {
1524
+ this.transcriptScrollView?.setScrollbar(this.settingsManager.getFullscreenScrollbar());
1525
+ }
1281
1526
  applyRuntimeSettings() {
1527
+ setCapabilityOverrides(this.settingsManager.getTerminalCapabilityOverrides());
1282
1528
  configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());
1529
+ this.applyFullscreenScrollbarSetting();
1530
+ if (this.renderer instanceof TuiAltScreen) {
1531
+ this.renderer.setCopyOnSelect(this.settingsManager.getFullscreenCopyOnSelect());
1532
+ this.renderer.setWheelScrollLines(this.settingsManager.getFullscreenWheelScrollLines());
1533
+ }
1283
1534
  this.footer.setSession(this.session);
1284
1535
  this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);
1285
1536
  this.footerDataProvider.setCwd(this.sessionManager.getCwd());
@@ -1323,10 +1574,60 @@ export class InteractiveMode {
1323
1574
  async handleFatalRuntimeError(prefix, error) {
1324
1575
  const message = error instanceof Error ? error.message : String(error);
1325
1576
  this.showError(`${prefix}: ${message}`);
1577
+ const extensionHint = this.getCrashExtensionHint(error);
1578
+ if (extensionHint) {
1579
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", extensionHint), this.outputPad, 0));
1580
+ }
1581
+ if (this.recordCrash("fatal_error", error)) {
1582
+ const instructions = this.crashReportInstructions();
1583
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("muted", instructions), this.outputPad, 0));
1584
+ }
1326
1585
  stopThemeWatcher();
1327
- this.stop();
1586
+ this.stop("transcript");
1328
1587
  process.exit(1);
1329
1588
  }
1589
+ getCrashExtensionHint(error) {
1590
+ try {
1591
+ return formatCrashExtensionHint(findExtensionStackMatches(error instanceof Error ? error.stack : undefined, this.session.resourceLoader.getExtensions().extensions));
1592
+ }
1593
+ catch {
1594
+ return undefined;
1595
+ }
1596
+ }
1597
+ /** Persist a crash so the next start can point the user at `/bug`. Returns false when nothing was written. */
1598
+ recordCrash(kind, error) {
1599
+ try {
1600
+ return (recordCrash({
1601
+ kind,
1602
+ error,
1603
+ sessionFile: this.session.sessionFile,
1604
+ cwd: this.session.sessionManager.getCwd(),
1605
+ }) !== undefined);
1606
+ }
1607
+ catch {
1608
+ return false;
1609
+ }
1610
+ }
1611
+ crashReportInstructions() {
1612
+ const resume = this.session.sessionFile
1613
+ ? `run \`${APP_NAME} -r\` to resume the session, then`
1614
+ : `start ${APP_NAME} and`;
1615
+ return `To report this crash: ${resume} run /bug. The crash details are attached automatically.`;
1616
+ }
1617
+ suggestBugReport() {
1618
+ if (this.bugReportHintShown)
1619
+ return;
1620
+ this.bugReportHintShown = true;
1621
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("muted", `If this looks like a ${APP_NAME} bug, /bug collects a report to the developers.`), this.outputPad, 0));
1622
+ this.ui.requestRender();
1623
+ }
1624
+ maybeSuggestBugReport(message) {
1625
+ if (message.stopReason !== "error" || isRetryableAssistantError(message))
1626
+ return;
1627
+ if (/\b(?:abort(?:ed)?|cancel(?:l?ed)?)\b/i.test(message.errorMessage ?? ""))
1628
+ return;
1629
+ this.suggestBugReport();
1630
+ }
1330
1631
  renderCurrentSessionState() {
1331
1632
  this.loadedResourcesContainer.clear();
1332
1633
  this.chatContainer.clear();
@@ -1340,8 +1641,15 @@ export class InteractiveMode {
1340
1641
  /**
1341
1642
  * Get a registered tool definition by name (for custom rendering).
1342
1643
  */
1644
+ /**
1645
+ * Extension-registered definition, falling back to the built-in one. The renderer components take
1646
+ * whatever this returns, so they never reach into the tool registry themselves.
1647
+ */
1343
1648
  getRegisteredToolDefinition(toolName) {
1344
- return this.session.getToolDefinition(toolName);
1649
+ return withBuiltInRenderers(toolName, this.session.getToolDefinition(toolName));
1650
+ }
1651
+ getMarkdownTransformers() {
1652
+ return [this.mermaidMarkdownTransformer, ...this.session.extensionRunner.getMarkdownTransformers()];
1345
1653
  }
1346
1654
  /**
1347
1655
  * Set up keyboard shortcuts registered by extensions.
@@ -1408,24 +1716,49 @@ export class InteractiveMode {
1408
1716
  this.footerDataProvider.setExtensionStatus(key, text);
1409
1717
  this.ui.requestRender();
1410
1718
  }
1719
+ setEditorWorkingStatusIndicator(indicator) {
1720
+ this.defaultEditor.setWorkingStatusIndicator(undefined);
1721
+ if (!isWorkingStatusEditor(this.editor))
1722
+ return false;
1723
+ this.editor.setWorkingStatusIndicator(indicator);
1724
+ return true;
1725
+ }
1411
1726
  showStatusIndicator(indicator) {
1412
1727
  this.activeStatusIndicator?.dispose();
1413
1728
  this.activeStatusIndicator = indicator;
1729
+ this.activeWorkingIndicatorEmbedded = false;
1414
1730
  this.statusContainer.clear();
1731
+ this.setEditorWorkingStatusIndicator(undefined);
1732
+ if (this.setEditorWorkingStatusIndicator(indicator)) {
1733
+ this.activeWorkingIndicatorEmbedded = true;
1734
+ return;
1735
+ }
1415
1736
  this.statusContainer.addChild(indicator);
1416
1737
  }
1417
1738
  clearStatusIndicator(kind) {
1418
1739
  if (kind && this.activeStatusIndicator?.kind !== kind) {
1419
1740
  return;
1420
1741
  }
1421
- const hadActiveStatusIndicator = this.activeStatusIndicator !== undefined;
1422
- this.activeStatusIndicator?.dispose();
1742
+ const clearedIndicator = this.activeStatusIndicator;
1743
+ const clearedIndicatorWasEmbedded = this.activeWorkingIndicatorEmbedded;
1744
+ clearedIndicator?.dispose();
1423
1745
  this.activeStatusIndicator = undefined;
1746
+ this.activeWorkingIndicatorEmbedded = false;
1424
1747
  this.statusContainer.clear();
1425
- if (hadActiveStatusIndicator && this.ui.getClearOnShrink()) {
1748
+ this.setEditorWorkingStatusIndicator(undefined);
1749
+ if (clearedIndicator &&
1750
+ !clearedIndicatorWasEmbedded &&
1751
+ this.options.tuiMode === "regular" &&
1752
+ this.ui.getClearOnShrink()) {
1426
1753
  this.statusContainer.addChild(this.idleStatus);
1427
1754
  }
1428
1755
  }
1756
+ showWorkingStatusIndicator() {
1757
+ const colorFn = isWorkingStatusEditor(this.editor)
1758
+ ? (text) => (this.editor.borderColor ?? theme.getThinkingBorderColor(this.session.thinkingLevel || "off"))(text)
1759
+ : undefined;
1760
+ this.showStatusIndicator(new WorkingStatusIndicator(this.ui, this.workingMessage ?? this.defaultWorkingMessage, this.workingIndicatorOptions, colorFn));
1761
+ }
1429
1762
  setWorkingVisible(visible) {
1430
1763
  this.workingVisible = visible;
1431
1764
  if (!visible) {
@@ -1434,7 +1767,7 @@ export class InteractiveMode {
1434
1767
  return;
1435
1768
  }
1436
1769
  if (this.session.isStreaming && this.activeStatusIndicator?.kind !== "working") {
1437
- this.showStatusIndicator(new WorkingStatusIndicator(this.ui, this.workingMessage ?? this.defaultWorkingMessage, this.workingIndicatorOptions));
1770
+ this.showWorkingStatusIndicator();
1438
1771
  }
1439
1772
  this.ui.requestRender();
1440
1773
  }
@@ -1482,7 +1815,7 @@ export class InteractiveMode {
1482
1815
  container.addChild(new Text(line, 1, 0));
1483
1816
  }
1484
1817
  if (content.length > InteractiveMode.MAX_WIDGET_LINES) {
1485
- container.addChild(new Text(theme.fg("muted", "... (widget truncated)"), 1, 0));
1818
+ container.addChild(new ThemedText(() => theme.fg("muted", "... (widget truncated)"), 1, 0));
1486
1819
  }
1487
1820
  component = container;
1488
1821
  }
@@ -1536,7 +1869,7 @@ export class InteractiveMode {
1536
1869
  this.setHiddenThinkingLabel();
1537
1870
  }
1538
1871
  // Maximum total widget lines to prevent viewport overflow
1539
- static { this.MAX_WIDGET_LINES = 10; }
1872
+ static MAX_WIDGET_LINES = 10;
1540
1873
  /**
1541
1874
  * Render all extension widgets to the widget container.
1542
1875
  */
@@ -1570,22 +1903,16 @@ export class InteractiveMode {
1570
1903
  if (this.customFooter?.dispose) {
1571
1904
  this.customFooter.dispose();
1572
1905
  }
1573
- // Remove current footer from UI
1574
- if (this.customFooter) {
1575
- this.ui.removeChild(this.customFooter);
1576
- }
1577
- else {
1578
- this.ui.removeChild(this.footer);
1579
- }
1906
+ this.footerContainer.clear();
1580
1907
  if (factory) {
1581
1908
  // Create and add custom footer, passing the data provider
1582
1909
  this.customFooter = factory(this.ui, theme, this.footerDataProvider);
1583
- this.ui.addChild(this.customFooter);
1910
+ this.footerContainer.addChild(this.customFooter);
1584
1911
  }
1585
1912
  else {
1586
1913
  // Restore built-in footer
1587
1914
  this.customFooter = undefined;
1588
- this.ui.addChild(this.footer);
1915
+ this.footerContainer.addChild(this.footer);
1589
1916
  }
1590
1917
  this.ui.requestRender();
1591
1918
  }
@@ -1631,18 +1958,23 @@ export class InteractiveMode {
1631
1958
  this.ui.requestRender();
1632
1959
  }
1633
1960
  addExtensionTerminalInputListener(handler) {
1634
- const unsubscribe = this.ui.addInputListener(handler);
1635
- this.extensionTerminalInputUnsubscribers.add(unsubscribe);
1961
+ const subscription = { handler, unsubscribe: this.ui.addInputListener(handler) };
1962
+ this.extensionTerminalInputSubscriptions.add(subscription);
1636
1963
  return () => {
1637
- unsubscribe();
1638
- this.extensionTerminalInputUnsubscribers.delete(unsubscribe);
1964
+ subscription.unsubscribe();
1965
+ this.extensionTerminalInputSubscriptions.delete(subscription);
1639
1966
  };
1640
1967
  }
1641
- clearExtensionTerminalInputListeners() {
1642
- for (const unsubscribe of this.extensionTerminalInputUnsubscribers) {
1643
- unsubscribe();
1968
+ rebindExtensionTerminalInputListeners() {
1969
+ for (const subscription of this.extensionTerminalInputSubscriptions) {
1970
+ subscription.unsubscribe();
1971
+ subscription.unsubscribe = this.ui.addInputListener(subscription.handler);
1644
1972
  }
1645
- this.extensionTerminalInputUnsubscribers.clear();
1973
+ }
1974
+ clearExtensionTerminalInputListeners() {
1975
+ for (const subscription of this.extensionTerminalInputSubscriptions)
1976
+ subscription.unsubscribe();
1977
+ this.extensionTerminalInputSubscriptions.clear();
1646
1978
  }
1647
1979
  /**
1648
1980
  * Create the ExtensionUIContext for extensions.
@@ -1717,50 +2049,191 @@ export class InteractiveMode {
1717
2049
  /**
1718
2050
  * Show a selector for extensions.
1719
2051
  */
1720
- showExtensionSelector(title, options, opts) {
2052
+ showExtensionSelector(title, options, opts, detailRows) {
1721
2053
  return new Promise((resolve) => {
1722
2054
  if (opts?.signal?.aborted) {
1723
2055
  resolve(undefined);
1724
2056
  return;
1725
2057
  }
2058
+ let settled = false;
2059
+ const settle = (value) => {
2060
+ if (settled)
2061
+ return;
2062
+ settled = true;
2063
+ opts?.signal?.removeEventListener("abort", onAbort);
2064
+ if (this.extensionSelectorSettle === settle)
2065
+ this.extensionSelectorSettle = undefined;
2066
+ // A deciding-surface label that nothing flushed belongs to THIS ask and dies with it.
2067
+ // Left standing it is sticky: the next, unrelated dialog's teardown would emit
2068
+ // "Permission resolved by <whoever>" about an ask that surface never saw.
2069
+ this.extensionDialogDecidedBy = undefined;
2070
+ resolve(value);
2071
+ };
1726
2072
  const onAbort = () => {
1727
- this.hideExtensionSelector();
1728
- resolve(undefined);
2073
+ // A dialog that was already displaced by a newer one must not tear the newer one down.
2074
+ if (!settled) {
2075
+ // Flush BEFORE settling: `settle` drops the pending label, and `hideExtensionSelector`
2076
+ // now settles this dialog fail-closed on its way out.
2077
+ this.flushExtensionDialogDecidedNotice();
2078
+ this.hideExtensionSelector();
2079
+ }
2080
+ settle(undefined);
1729
2081
  };
1730
2082
  opts?.signal?.addEventListener("abort", onAbort, { once: true });
1731
- this.extensionSelector = new ExtensionSelectorComponent(title, options, (option) => {
1732
- opts?.signal?.removeEventListener("abort", onAbort);
2083
+ // Non-clobbering slot. Whatever is already in it is disposed and its promise settled as
2084
+ // cancelled BEFORE the replacement takes over; the previous code overwrote the field and
2085
+ // left the earlier caller awaiting a promise nothing could ever resolve.
2086
+ const displaced = this.extensionSelectorSettle;
2087
+ this.extensionSelector?.dispose();
2088
+ this.extensionSelector = undefined;
2089
+ this.extensionSelectorSettle = undefined;
2090
+ this.extensionSelector = new ExtensionSelectorComponent(title, options,
2091
+ // Settle BEFORE hiding: `hideExtensionSelector` settles whatever is still in the slot
2092
+ // fail-closed, so hiding first would resolve the ask as `undefined` (a denial) and the
2093
+ // human's actual choice would be swallowed by the `settled` guard.
2094
+ (option) => {
2095
+ settle(option);
1733
2096
  this.hideExtensionSelector();
1734
- resolve(option);
1735
2097
  }, () => {
1736
- opts?.signal?.removeEventListener("abort", onAbort);
2098
+ settle(undefined);
1737
2099
  this.hideExtensionSelector();
1738
- resolve(undefined);
1739
- }, { tui: this.ui, timeout: opts?.timeout, onToggleToolsExpanded: () => this.toggleToolOutputExpansion() });
2100
+ }, {
2101
+ tui: this.ui,
2102
+ timeout: opts?.timeout,
2103
+ detailRows,
2104
+ onToggleToolsExpanded: () => this.toggleToolOutputExpansion(),
2105
+ });
2106
+ this.extensionSelectorSettle = settle;
2107
+ this.disposeActiveSelector();
1740
2108
  this.editorContainer.clear();
1741
2109
  this.editorContainer.addChild(this.extensionSelector);
1742
2110
  this.ui.setFocus(this.extensionSelector);
1743
2111
  this.ui.requestRender();
2112
+ // Settle the displaced caller only once the replacement is installed, so its continuation
2113
+ // cannot observe an empty dialog slot.
2114
+ displaced?.(undefined);
1744
2115
  });
1745
2116
  }
1746
2117
  /**
1747
- * Hide the extension selector.
2118
+ * Record that the open ask was decided by another surface (an attached client, the RPC caller).
2119
+ *
2120
+ * This does NOT dismiss the dialog: `opts.signal` already does that, and the relay aborts it
2121
+ * right after calling this. All that is added here is the RENDERING — the operator otherwise
2122
+ * watches a permission dialog vanish with no account of who answered it.
2123
+ */
2124
+ noteExtensionDialogResolvedElsewhere(label) {
2125
+ this.extensionDialogDecidedBy = label;
2126
+ // Nothing is open to abort, so no teardown will flush the notice — emit it now.
2127
+ if (!this.extensionSelector)
2128
+ this.flushExtensionDialogDecidedNotice();
2129
+ }
2130
+ /** Emit the pending deciding-surface notice at most once, then forget it. */
2131
+ flushExtensionDialogDecidedNotice() {
2132
+ const label = this.extensionDialogDecidedBy;
2133
+ if (label === undefined)
2134
+ return;
2135
+ this.extensionDialogDecidedBy = undefined;
2136
+ this.showExtensionNotify(`Permission resolved by ${label}`, "info");
2137
+ }
2138
+ /**
2139
+ * Hide the extension selector, settling its promise FAIL-CLOSED if nothing else has.
2140
+ *
2141
+ * Every teardown path FOR THE SELECTOR funnels through here — {@link hideExtensionInput} and
2142
+ * {@link hideExtensionEditor} are the matching, separate ones for the other two dialog types, and
2143
+ * they need the same treatment for the same reason. This one used to drop the component on the
2144
+ * floor without touching {@link extensionSelectorSettle} when `resetExtensionUI` (reached from
2145
+ * `setBeforeSessionInvalidate` and from `/reload`) called it. A session invalidate while a permission ask
2146
+ * was open therefore stranded the promise `beforeToolCall` awaits and wedged the agent loop
2147
+ * forever: no dialog on screen, no tool call, no way out.
2148
+ *
2149
+ * `undefined` is the fail-closed answer — `showExtensionConfirm` maps it to `false`, i.e. denial.
2150
+ * Callers that carry a real answer must `settle(...)` it BEFORE calling this.
1748
2151
  */
1749
2152
  hideExtensionSelector() {
2153
+ const settle = this.extensionSelectorSettle;
2154
+ this.extensionSelectorSettle = undefined;
1750
2155
  this.extensionSelector?.dispose();
1751
2156
  this.editorContainer.clear();
1752
2157
  this.editorContainer.addChild(this.editor);
1753
2158
  this.extensionSelector = undefined;
1754
2159
  this.ui.setFocus(this.editor);
1755
2160
  this.ui.requestRender();
2161
+ // Last, so the caller's continuation cannot observe a half-torn-down dialog slot.
2162
+ settle?.(undefined);
1756
2163
  }
1757
2164
  /**
1758
2165
  * Show a confirmation dialog for extensions.
2166
+ *
2167
+ * `ui.confirm(title, message, opts)` is a PUBLIC extension surface and the attach relay forwards
2168
+ * the caller's title through unchanged, so `title` is attacker-influenced even when the built-in
2169
+ * permission gate passes a constant. Untreated it carried every defect the detail rows were
2170
+ * hardened against: `ESC[2J` in a title cleared the operator's screen, U+202E survived verbatim,
2171
+ * and `"Approve\nYes\nNo"` rendered four option-looking rows above two real ones.
2172
+ *
2173
+ * TITLE and MESSAGE are bounded DIFFERENTLY, because they are different things:
2174
+ *
2175
+ * - a TITLE is a header, so it stays exactly ONE row on every path and its newlines are
2176
+ * neutralized. That is what stops `"Approve\nYes\nNo"` from drawing option-looking rows above
2177
+ * the real ones, and it costs nothing HERE: no caller of `showExtensionConfirm` writes a
2178
+ * multi-line title. (Two callers elsewhere do — `showStartupSelector` gets the five-line
2179
+ * `formatMissingSessionCwdPrompt` from `main.ts`, and `project-trust.ts` passes
2180
+ * `${title}\n${message}` — but they reach `ExtensionSelectorComponent` directly, where
2181
+ * `TitleRowsComponent` draws one row per line. The reasoning below depends only on the
2182
+ * `showExtensionConfirm` path.)
2183
+ * - a MESSAGE is prose, so it gets a ROW BUDGET and its own newlines are row breaks. Bounding it
2184
+ * to a single row's width instead gutted the `/rewind --fork` consent dialog (215 of its 273
2185
+ * characters elided at 80 columns) and collapsed the deliberately 5-line
2186
+ * `formatMissingSessionCwdPrompt` into one. See {@link boundDialogText}.
1759
2187
  */
1760
2188
  async showExtensionConfirm(title, message, opts) {
1761
- const result = await this.showExtensionSelector(`${title}\n${message}`, ["Yes", "No"], opts);
2189
+ // Grapheme budget for one row of dialog text: the terminal width less the row's `paddingX: 1`
2190
+ // on each side. The floor keeps a very narrow terminal from producing a useless budget.
2191
+ const columns = this.ui?.terminal?.columns ?? 80;
2192
+ const safeTitle = boundedSafeText(title, Math.max(16, columns - 2)).value;
2193
+ const detail = opts?.detail;
2194
+ if (detail !== undefined) {
2195
+ // A permission ask arrives with typed fields, so it is rendered as typed rows. Flattening
2196
+ // it back into `${title}\n${message}` would hand the attacker-influenced command a way to
2197
+ // forge rows, and the human would be deciding about a string rather than about a call.
2198
+ const rows = this.buildPermissionDetailRows(detail);
2199
+ const result = await this.showExtensionSelector(safeTitle, ["Yes", "No"], opts, rows);
2200
+ return result === "Yes";
2201
+ }
2202
+ // Two rows of the header budget are already spoken for: the single-row title above, and the
2203
+ // spacer `ExtensionSelectorComponent` draws between the header and the option list when there
2204
+ // are no detail rows. Both sit above `Yes`, so both have to come out of the same budget.
2205
+ const safeMessage = boundDialogText(message, columns, MAX_DETAIL_ROWS - 2);
2206
+ const result = await this.showExtensionSelector(`${safeTitle}\n${safeMessage}`, ["Yes", "No"], opts);
1762
2207
  return result === "Yes";
1763
2208
  }
2209
+ /**
2210
+ * Turn a {@link PermissionAskDetail} into one bounded, neutralized row per fact.
2211
+ *
2212
+ * The protocol layer neutralizes what arrives from a remote surface, but a LOCALLY raised ask
2213
+ * never crosses the wire — so the rule is applied here too. Note the ORDER: neutralize, then
2214
+ * measure. `visibleWidth` strips ANSI for measurement only and reports zero width for bidi
2215
+ * controls and DEL, so any width budget computed over raw text is a fiction.
2216
+ */
2217
+ buildPermissionDetailRows(detail) {
2218
+ const labels = [
2219
+ ["Tool", detail.toolName],
2220
+ ["Directory", detail.cwd],
2221
+ ["Command", detail.command],
2222
+ ["Path", detail.path],
2223
+ ["Operation", detail.operation],
2224
+ ["Reason", detail.reason],
2225
+ ];
2226
+ const present = labels.filter((entry) => {
2227
+ const value = entry[1];
2228
+ return value !== undefined && value.length > 0;
2229
+ });
2230
+ const labelWidth = present.reduce((max, [label]) => Math.max(max, label.length), 0);
2231
+ // Terminal width minus the row margins, the label column and its ": " separator. The floor
2232
+ // keeps a narrow terminal from producing a zero or negative budget.
2233
+ const columns = this.ui?.terminal?.columns ?? 80;
2234
+ const budget = Math.max(16, columns - 2 - labelWidth - 2);
2235
+ return present.map(([label, value]) => `${label.padEnd(labelWidth)}: ${boundedSafeText(value, budget).value}`);
2236
+ }
1764
2237
  async promptForMissingSessionCwd(error) {
1765
2238
  const confirmed = await this.showExtensionConfirm("Session cwd not found", formatMissingSessionCwdPrompt(error.issue));
1766
2239
  return confirmed ? error.issue.fallbackCwd : undefined;
@@ -1774,64 +2247,127 @@ export class InteractiveMode {
1774
2247
  resolve(undefined);
1775
2248
  return;
1776
2249
  }
2250
+ let settled = false;
2251
+ const settle = (value) => {
2252
+ if (settled)
2253
+ return;
2254
+ settled = true;
2255
+ opts?.signal?.removeEventListener("abort", onAbort);
2256
+ if (this.extensionInputSettle === settle)
2257
+ this.extensionInputSettle = undefined;
2258
+ resolve(value);
2259
+ };
1777
2260
  const onAbort = () => {
1778
- this.hideExtensionInput();
1779
- resolve(undefined);
2261
+ // A dialog already displaced by a newer one must not tear the newer one down.
2262
+ if (!settled)
2263
+ this.hideExtensionInput();
2264
+ settle(undefined);
1780
2265
  };
1781
2266
  opts?.signal?.addEventListener("abort", onAbort, { once: true });
1782
- this.extensionInput = new ExtensionInputComponent(title, placeholder, (value) => {
1783
- opts?.signal?.removeEventListener("abort", onAbort);
2267
+ const displaced = this.extensionInputSettle;
2268
+ this.extensionInput?.dispose();
2269
+ this.extensionInput = undefined;
2270
+ this.extensionInputSettle = undefined;
2271
+ this.extensionInput = new ExtensionInputComponent(title, placeholder,
2272
+ // Settle BEFORE hiding, for the same reason the selector does: `hideExtensionInput`
2273
+ // settles whatever is still in the slot fail-closed, so hiding first would resolve the
2274
+ // ask as `undefined` and the human's actual answer would hit the `settled` guard.
2275
+ (value) => {
2276
+ settle(value);
1784
2277
  this.hideExtensionInput();
1785
- resolve(value);
1786
2278
  }, () => {
1787
- opts?.signal?.removeEventListener("abort", onAbort);
2279
+ settle(undefined);
1788
2280
  this.hideExtensionInput();
1789
- resolve(undefined);
1790
2281
  }, { tui: this.ui, timeout: opts?.timeout });
2282
+ this.extensionInputSettle = settle;
2283
+ this.disposeActiveSelector();
1791
2284
  this.editorContainer.clear();
1792
2285
  this.editorContainer.addChild(this.extensionInput);
1793
2286
  this.ui.setFocus(this.extensionInput);
1794
2287
  this.ui.requestRender();
2288
+ // Only once the replacement is installed, so the displaced caller's continuation cannot
2289
+ // observe an empty dialog slot.
2290
+ displaced?.(undefined);
1795
2291
  });
1796
2292
  }
1797
2293
  /**
1798
- * Hide the extension input.
2294
+ * Hide the extension input, settling its promise FAIL-CLOSED if nothing else has.
2295
+ *
2296
+ * Same defect the selector had: this used to dispose and re-focus without touching the `resolve`
2297
+ * captured in {@link showExtensionInput}'s closure, so `resetExtensionUI` — a session invalidate
2298
+ * or `/reload` — left the extension awaiting `ui.input(...)` hanging forever.
2299
+ *
2300
+ * Callers that carry a real answer must `settle(...)` it BEFORE calling this.
1799
2301
  */
1800
2302
  hideExtensionInput() {
2303
+ const settle = this.extensionInputSettle;
2304
+ this.extensionInputSettle = undefined;
1801
2305
  this.extensionInput?.dispose();
1802
2306
  this.editorContainer.clear();
1803
2307
  this.editorContainer.addChild(this.editor);
1804
2308
  this.extensionInput = undefined;
1805
2309
  this.ui.setFocus(this.editor);
1806
2310
  this.ui.requestRender();
2311
+ // Last, so the caller's continuation cannot observe a half-torn-down dialog slot.
2312
+ settle?.(undefined);
1807
2313
  }
1808
2314
  /**
1809
2315
  * Show a multi-line editor for extensions (with Ctrl+G support).
1810
2316
  */
1811
2317
  showExtensionEditor(title, prefill) {
1812
2318
  return new Promise((resolve) => {
1813
- this.extensionEditor = new ExtensionEditorComponent(this.ui, this.keybindings, title, prefill, (value) => {
1814
- this.hideExtensionEditor();
2319
+ let settled = false;
2320
+ const settle = (value) => {
2321
+ if (settled)
2322
+ return;
2323
+ settled = true;
2324
+ if (this.extensionEditorSettle === settle)
2325
+ this.extensionEditorSettle = undefined;
1815
2326
  resolve(value);
2327
+ };
2328
+ const displaced = this.extensionEditorSettle;
2329
+ this.extensionEditor = undefined;
2330
+ this.extensionEditorSettle = undefined;
2331
+ this.extensionEditor = new ExtensionEditorComponent(this.ui, this.keybindings, title, prefill,
2332
+ // Settle BEFORE hiding: `hideExtensionEditor` settles the slot fail-closed.
2333
+ (value) => {
2334
+ settle(value);
2335
+ this.hideExtensionEditor();
1816
2336
  }, () => {
2337
+ settle(undefined);
1817
2338
  this.hideExtensionEditor();
1818
- resolve(undefined);
1819
2339
  }, undefined, this.settingsManager.getExternalEditorCommand());
2340
+ this.extensionEditorSettle = settle;
2341
+ this.disposeActiveSelector();
1820
2342
  this.editorContainer.clear();
1821
2343
  this.editorContainer.addChild(this.extensionEditor);
1822
2344
  this.ui.setFocus(this.extensionEditor);
1823
2345
  this.ui.requestRender();
2346
+ // Only once the replacement is installed, so the displaced caller's continuation cannot
2347
+ // observe an empty dialog slot.
2348
+ displaced?.(undefined);
1824
2349
  });
1825
2350
  }
1826
2351
  /**
1827
- * Hide the extension editor.
2352
+ * Hide the extension editor, settling its promise FAIL-CLOSED if nothing else has.
2353
+ *
2354
+ * Same defect the selector had: this used to clear the container and re-focus without touching
2355
+ * the `resolve` captured in {@link showExtensionEditor}'s closure, so `resetExtensionUI` — a
2356
+ * session invalidate or `/reload` — stranded whoever was awaiting the editor forever. `/compact`
2357
+ * with custom instructions is one such caller.
2358
+ *
2359
+ * Callers that carry a real answer must `settle(...)` it BEFORE calling this.
1828
2360
  */
1829
2361
  hideExtensionEditor() {
2362
+ const settle = this.extensionEditorSettle;
2363
+ this.extensionEditorSettle = undefined;
1830
2364
  this.editorContainer.clear();
1831
2365
  this.editorContainer.addChild(this.editor);
1832
2366
  this.extensionEditor = undefined;
1833
2367
  this.ui.setFocus(this.editor);
1834
2368
  this.ui.requestRender();
2369
+ // Last, so the caller's continuation cannot observe a half-torn-down dialog slot.
2370
+ settle?.(undefined);
1835
2371
  }
1836
2372
  /**
1837
2373
  * Set a custom editor component from an extension.
@@ -1841,6 +2377,7 @@ export class InteractiveMode {
1841
2377
  this.editorComponentFactory = factory;
1842
2378
  // Save text from current editor before switching
1843
2379
  const currentText = this.editor.getText();
2380
+ this.disposeActiveSelector();
1844
2381
  this.editorContainer.clear();
1845
2382
  if (factory) {
1846
2383
  // Create the custom editor with tui, theme, and keybindings
@@ -1857,6 +2394,9 @@ export class InteractiveMode {
1857
2394
  if (newEditor.setPaddingX !== undefined) {
1858
2395
  newEditor.setPaddingX(this.defaultEditor.getPaddingX());
1859
2396
  }
2397
+ if (newEditor.setAutocompleteMaxVisible !== undefined) {
2398
+ newEditor.setAutocompleteMaxVisible(this.defaultEditor.getAutocompleteMaxVisible());
2399
+ }
1860
2400
  // Set autocomplete if supported
1861
2401
  if (newEditor.setAutocompleteProvider && this.autocompleteProvider) {
1862
2402
  newEditor.setAutocompleteProvider(this.autocompleteProvider);
@@ -1890,6 +2430,13 @@ export class InteractiveMode {
1890
2430
  this.editor = this.defaultEditor;
1891
2431
  }
1892
2432
  this.editorContainer.addChild(this.editor);
2433
+ if (this.activeStatusIndicator) {
2434
+ this.statusContainer.clear();
2435
+ this.activeWorkingIndicatorEmbedded = this.setEditorWorkingStatusIndicator(this.activeStatusIndicator);
2436
+ if (!this.activeWorkingIndicatorEmbedded) {
2437
+ this.statusContainer.addChild(this.activeStatusIndicator);
2438
+ }
2439
+ }
1893
2440
  this.ui.setFocus(this.editor);
1894
2441
  this.ui.requestRender();
1895
2442
  }
@@ -1961,6 +2508,7 @@ export class InteractiveMode {
1961
2508
  options?.onHandle?.(handle);
1962
2509
  }
1963
2510
  else {
2511
+ this.disposeActiveSelector();
1964
2512
  this.editorContainer.clear();
1965
2513
  this.editorContainer.addChild(component);
1966
2514
  this.ui.setFocus(component);
@@ -1981,17 +2529,14 @@ export class InteractiveMode {
1981
2529
  */
1982
2530
  showExtensionError(extensionPath, error, stack) {
1983
2531
  const errorMsg = `Extension "${extensionPath}" error: ${error}`;
1984
- const errorText = new Text(theme.fg("error", errorMsg), 1, 0);
2532
+ const errorText = new ThemedText(() => theme.fg("error", errorMsg), 1, 0);
1985
2533
  this.chatContainer.addChild(errorText);
1986
2534
  if (stack) {
1987
2535
  // Show stack trace in dim color, indented
1988
- const stackLines = stack
1989
- .split("\n")
1990
- .slice(1) // Skip first line (duplicates error message)
1991
- .map((line) => theme.fg("dim", ` ${line.trim()}`))
1992
- .join("\n");
1993
- if (stackLines) {
1994
- this.chatContainer.addChild(new Text(stackLines, 1, 0));
2536
+ const stackLines = stack.split("\n").slice(1); // Skip first line (duplicates error message)
2537
+ if (stackLines.length > 0) {
2538
+ const renderStack = () => stackLines.map((line) => theme.fg("dim", ` ${line.trim()}`)).join("\n");
2539
+ this.chatContainer.addChild(new ThemedText(renderStack, 1, 0));
1995
2540
  }
1996
2541
  }
1997
2542
  this.ui.requestRender();
@@ -2048,11 +2593,12 @@ export class InteractiveMode {
2048
2593
  this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());
2049
2594
  this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());
2050
2595
  this.defaultEditor.onAction("app.editor.external", () => void this.handleOpenExternalEditor());
2051
- this.defaultEditor.onAction("app.message.copy", () => void this.handleCopyCommand());
2596
+ this.defaultEditor.onAction("app.message.copy", () => void this.handleCopyCommand({ flashConfirmation: true, preferSelection: true }));
2052
2597
  this.defaultEditor.onAction("app.message.followUp", () => this.handleFollowUp());
2053
2598
  this.defaultEditor.onAction("app.message.dequeue", () => this.handleDequeue());
2054
2599
  this.defaultEditor.onAction("app.session.new", () => this.handleClearCommand());
2055
2600
  this.defaultEditor.onAction("app.session.tree", () => this.showTreeSelector());
2601
+ this.defaultEditor.onAction("app.session.rewind", () => this.showRewindSelector());
2056
2602
  this.defaultEditor.onAction("app.session.fork", () => this.showUserMessageSelector());
2057
2603
  this.defaultEditor.onAction("app.session.resume", () => this.showSessionSelector());
2058
2604
  this.defaultEditor.onChange = (text) => {
@@ -2062,14 +2608,46 @@ export class InteractiveMode {
2062
2608
  this.updateEditorBorderColor();
2063
2609
  }
2064
2610
  };
2065
- // Handle clipboard paste (triggered on Ctrl+V). Images are attached by path;
2066
- // otherwise, paste plain text from the system clipboard.
2611
+ // Handle clipboard paste (triggered on Ctrl+V). Copied files use their original paths,
2612
+ // images are attached via temporary files, and plain text is the final fallback.
2067
2613
  this.defaultEditor.onPasteImage = () => {
2068
2614
  void this.handleClipboardPaste();
2069
2615
  };
2070
2616
  }
2617
+ async handleRightClickPaste() {
2618
+ const target = this.renderer.getFocusedComponent();
2619
+ const handleInput = target?.handleInput;
2620
+ if (!target || !handleInput)
2621
+ return;
2622
+ try {
2623
+ const text = await readClipboardText();
2624
+ if (!text || this.renderer.getFocusedComponent() !== target)
2625
+ return;
2626
+ handleInput.call(target, `\x1b[200~${text}\x1b[201~`);
2627
+ this.ui.requestRender();
2628
+ }
2629
+ catch {
2630
+ // Silently ignore clipboard errors (may not have permission, etc.)
2631
+ }
2632
+ }
2071
2633
  async handleClipboardPaste() {
2072
2634
  try {
2635
+ const filePaths = await readClipboardFilePaths();
2636
+ if (filePaths) {
2637
+ if (filePaths.some((filePath) => /\p{Cc}/u.test(filePath))) {
2638
+ throw new Error("Clipboard file path contains control characters");
2639
+ }
2640
+ const paths = this.isBashMode ? filePaths.map(quoteIfNeeded).join(" ") : filePaths.join("\n");
2641
+ const cursor = this.editor.getCursor?.();
2642
+ const currentLine = cursor ? (this.editor.getText().split("\n")[cursor.line] ?? "") : "";
2643
+ const characterBeforeCursor = cursor && cursor.col > 0 ? currentLine[cursor.col - 1] : "";
2644
+ const characterAfterCursor = cursor ? currentLine[cursor.col] : "";
2645
+ const leadingSpace = characterBeforeCursor && !/\s/.test(characterBeforeCursor) ? " " : "";
2646
+ const trailingSpace = characterAfterCursor && !/\s/.test(characterAfterCursor) ? " " : "";
2647
+ this.editor.insertTextAtCursor?.(`${leadingSpace}${paths}${trailingSpace}`);
2648
+ this.ui.requestRender();
2649
+ return;
2650
+ }
2073
2651
  const image = await readClipboardImage();
2074
2652
  if (image) {
2075
2653
  const tmpDir = os.tmpdir();
@@ -2087,15 +2665,27 @@ export class InteractiveMode {
2087
2665
  this.ui.requestRender();
2088
2666
  }
2089
2667
  }
2090
- catch {
2091
- // Silently ignore clipboard errors (may not have permission, etc.)
2668
+ catch (error) {
2669
+ this.showError(`Failed to paste from clipboard: ${error instanceof Error ? error.message : String(error)}`);
2092
2670
  }
2093
2671
  }
2672
+ handleStartupSubmit(text) {
2673
+ this.editor.setText(text);
2674
+ this.showStatus("Startup is still in progress");
2675
+ }
2094
2676
  setupEditorSubmitHandler() {
2095
2677
  this.defaultEditor.onSubmit = async (text) => {
2096
2678
  text = text.trim();
2097
2679
  if (!text)
2098
2680
  return;
2681
+ // A `/rewind` is rewriting the working tree right now. Anything
2682
+ // submitted here would run against a tree that is mid-restore, so
2683
+ // hold the text in the editor the way the bash guard below does.
2684
+ if (this.isRewindRunning) {
2685
+ this.showWarning("A rewind is restoring your files. Wait for it to finish.");
2686
+ this.editor.setText(text);
2687
+ return;
2688
+ }
2099
2689
  // Handle commands
2100
2690
  if (text === "/settings") {
2101
2691
  this.showSettingsSelector();
@@ -2113,6 +2703,12 @@ export class InteractiveMode {
2113
2703
  await this.handleModelCommand(searchTerm);
2114
2704
  return;
2115
2705
  }
2706
+ if (text === "/thinking" || text.startsWith("/thinking ")) {
2707
+ const searchTerm = text.startsWith("/thinking ") ? text.slice(10).trim() : undefined;
2708
+ this.editor.setText("");
2709
+ this.handleThinkingCommand(searchTerm);
2710
+ return;
2711
+ }
2116
2712
  if (text === "/export" || text.startsWith("/export ")) {
2117
2713
  await this.handleExportCommand(text);
2118
2714
  this.editor.setText("");
@@ -2128,6 +2724,12 @@ export class InteractiveMode {
2128
2724
  this.editor.setText("");
2129
2725
  return;
2130
2726
  }
2727
+ if (text === "/bug" || text.startsWith("/bug ")) {
2728
+ const hint = text.slice("/bug".length).trim();
2729
+ this.editor.setText("");
2730
+ await this.handleBugCommand(hint ? hint : undefined);
2731
+ return;
2732
+ }
2131
2733
  if (text === "/copy") {
2132
2734
  await this.handleCopyCommand();
2133
2735
  this.editor.setText("");
@@ -2168,6 +2770,11 @@ export class InteractiveMode {
2168
2770
  this.editor.setText("");
2169
2771
  return;
2170
2772
  }
2773
+ if (text === "/rewind") {
2774
+ this.showRewindSelector();
2775
+ this.editor.setText("");
2776
+ return;
2777
+ }
2171
2778
  if (text === "/trust") {
2172
2779
  this.showTrustSelector();
2173
2780
  this.editor.setText("");
@@ -2289,17 +2896,21 @@ export class InteractiveMode {
2289
2896
  switch (event.type) {
2290
2897
  case "agent_start":
2291
2898
  this.pendingTools.clear();
2292
- if (this.settingsManager.getShowTerminalProgress()) {
2293
- this.ui.terminal.setProgress(true);
2294
- }
2295
2899
  // Restore main escape handler if retry handler is still active
2296
2900
  // (retry success event fires later, but we need main handler now)
2297
2901
  if (this.retryEscapeHandler) {
2298
2902
  this.defaultEditor.onEscape = this.retryEscapeHandler;
2299
2903
  this.retryEscapeHandler = undefined;
2300
2904
  }
2905
+ break;
2906
+ case "turn_start":
2907
+ if (this.settingsManager.getShowTerminalProgress()) {
2908
+ this.ui.terminal.setProgress(true);
2909
+ }
2301
2910
  if (this.workingVisible) {
2302
- this.showStatusIndicator(new WorkingStatusIndicator(this.ui, this.workingMessage ?? this.defaultWorkingMessage, this.workingIndicatorOptions));
2911
+ if (this.activeStatusIndicator?.kind !== "working") {
2912
+ this.showWorkingStatusIndicator();
2913
+ }
2303
2914
  }
2304
2915
  else {
2305
2916
  this.clearStatusIndicator();
@@ -2311,10 +2922,44 @@ export class InteractiveMode {
2311
2922
  this.ui.requestRender();
2312
2923
  break;
2313
2924
  case "entry_appended":
2925
+ if (this.entriesRenderedByBoundaryCompaction.delete(event.entry.id))
2926
+ break;
2314
2927
  if (event.entry.type === "custom") {
2315
2928
  this.addCustomEntryToChat(event.entry);
2316
2929
  this.ui.requestRender();
2317
2930
  }
2931
+ else if (event.entry.type === "usage" && event.entry.kind === "cache_warm") {
2932
+ this.addCacheWarmingUsage(event.entry);
2933
+ this.ui.requestRender();
2934
+ }
2935
+ else if (event.entry.type === "custom_message" && event.entry.display) {
2936
+ this.addMessageToChat(createCustomMessage(event.entry.customType, event.entry.content, event.entry.display, event.entry.details, event.entry.timestamp));
2937
+ this.ui.requestRender();
2938
+ }
2939
+ else if (event.entry.type === "compaction") {
2940
+ const entries = this.sessionManager.buildContextEntries();
2941
+ if (entries[0]?.id !== event.entry.id)
2942
+ break;
2943
+ this.chatContainer.clear();
2944
+ const branch = this.sessionManager.getBranch();
2945
+ const compactionIndex = branch.findIndex((entry) => entry.id === event.entry.id);
2946
+ const entriesAfterCompaction = new Set(branch.slice(compactionIndex + 1).map((entry) => entry.id));
2947
+ const retainedEntries = entries.slice(1);
2948
+ this.renderSessionEntries(retainedEntries.filter((entry) => !entriesAfterCompaction.has(entry.id)));
2949
+ this.addMessageToChat(createCompactionSummaryMessage(event.entry.summary, event.entry.tokensBefore, event.entry.timestamp));
2950
+ if (event.entry.usage) {
2951
+ this.addCompactionCostNotice({
2952
+ type: "compaction_cost",
2953
+ kind: "compaction",
2954
+ usage: event.entry.usage,
2955
+ });
2956
+ }
2957
+ this.renderSessionEntries(retainedEntries.filter((entry) => entriesAfterCompaction.has(entry.id)));
2958
+ for (const entryId of entriesAfterCompaction)
2959
+ this.entriesRenderedByBoundaryCompaction.add(entryId);
2960
+ this.footer.invalidate();
2961
+ this.ui.requestRender();
2962
+ }
2318
2963
  break;
2319
2964
  case "session_info_changed":
2320
2965
  this.updateTerminalTitle();
@@ -2340,17 +2985,17 @@ export class InteractiveMode {
2340
2985
  this.ui.requestRender();
2341
2986
  }
2342
2987
  else if (event.message.role === "assistant") {
2343
- this.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad);
2988
+ this.streamingComponent = new AssistantMessageComponent(undefined, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad, this.getMarkdownTransformers());
2344
2989
  this.streamingMessage = event.message;
2345
2990
  this.chatContainer.addChild(this.streamingComponent);
2346
- this.streamingComponent.updateContent(this.streamingMessage);
2991
+ this.streamingComponent.updateContent(this.streamingMessage, true);
2347
2992
  this.ui.requestRender();
2348
2993
  }
2349
2994
  break;
2350
2995
  case "message_update":
2351
2996
  if (this.streamingComponent && event.message.role === "assistant") {
2352
2997
  this.streamingMessage = event.message;
2353
- this.streamingComponent.updateContent(this.streamingMessage);
2998
+ this.streamingComponent.updateContent(this.streamingMessage, true);
2354
2999
  for (const content of this.streamingMessage.content) {
2355
3000
  if (content.type === "toolCall") {
2356
3001
  if (!this.pendingTools.has(content.id)) {
@@ -2387,7 +3032,7 @@ export class InteractiveMode {
2387
3032
  : "Operation aborted";
2388
3033
  this.streamingMessage.errorMessage = errorMessage;
2389
3034
  }
2390
- this.streamingComponent.updateContent(this.streamingMessage);
3035
+ this.streamingComponent.updateContent(this.streamingMessage, false);
2391
3036
  if (this.streamingMessage.stopReason === "aborted" || this.streamingMessage.stopReason === "error") {
2392
3037
  if (!errorMessage) {
2393
3038
  errorMessage = this.streamingMessage.errorMessage || "Error";
@@ -2399,12 +3044,14 @@ export class InteractiveMode {
2399
3044
  });
2400
3045
  }
2401
3046
  this.pendingTools.clear();
3047
+ this.maybeSuggestBugReport(this.streamingMessage);
2402
3048
  }
2403
3049
  else {
2404
3050
  // Args are now complete - trigger diff computation for edit tools
2405
3051
  for (const [, component] of this.pendingTools.entries()) {
2406
3052
  component.setArgsComplete();
2407
3053
  }
3054
+ this.maybeShowThinkingDropNotice(this.streamingMessage);
2408
3055
  this.maybeShowCacheMissNotice(this.streamingMessage);
2409
3056
  }
2410
3057
  this.streamingComponent = undefined;
@@ -2417,6 +3064,9 @@ export class InteractiveMode {
2417
3064
  // The bash execution callback handles TUI output rendering.
2418
3065
  break;
2419
3066
  case "tool_execution_start": {
3067
+ // Nested calls (from codemode scripts) are shown inside their parent's row.
3068
+ if (event.parentToolCallId)
3069
+ break;
2420
3070
  let component = this.pendingTools.get(event.toolCallId);
2421
3071
  if (!component) {
2422
3072
  component = new ToolExecutionComponent(event.toolName, event.toolCallId, event.args, {
@@ -2496,9 +3146,21 @@ export class InteractiveMode {
2496
3146
  }
2497
3147
  }
2498
3148
  else if (event.result) {
3149
+ const entries = this.sessionManager.buildContextEntries();
3150
+ if (entries[0]?.type !== "compaction") {
3151
+ throw new Error("Completed compaction is missing from the session context");
3152
+ }
2499
3153
  this.chatContainer.clear();
2500
- this.rebuildChatFromMessages();
3154
+ // The latest compaction is prepended for model context; append it below at its chronological position.
3155
+ this.renderSessionEntries(entries.slice(1));
2501
3156
  this.addMessageToChat(createCompactionSummaryMessage(event.result.summary, event.result.tokensBefore, new Date().toISOString()));
3157
+ if (event.result.usage) {
3158
+ this.addCompactionCostNotice({
3159
+ type: "compaction_cost",
3160
+ kind: "compaction",
3161
+ usage: event.result.usage,
3162
+ });
3163
+ }
2502
3164
  this.footer.invalidate();
2503
3165
  }
2504
3166
  else if (event.errorMessage) {
@@ -2507,7 +3169,8 @@ export class InteractiveMode {
2507
3169
  }
2508
3170
  else {
2509
3171
  this.chatContainer.addChild(new Spacer(1));
2510
- this.chatContainer.addChild(new Text(theme.fg("error", event.errorMessage), 1, 0));
3172
+ const errorMessage = event.errorMessage;
3173
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("error", errorMessage), 1, 0));
2511
3174
  }
2512
3175
  }
2513
3176
  void this.flushCompactionQueue({ willRetry: event.willRetry });
@@ -2571,6 +3234,19 @@ export class InteractiveMode {
2571
3234
  : message.content.filter((c) => c.type === "text");
2572
3235
  return textBlocks.map((c) => c.text).join("");
2573
3236
  }
3237
+ /** Show a managed-tool status update in the chat. */
3238
+ showManagedToolStatus(status) {
3239
+ if (!this.managedToolStatusStarted) {
3240
+ this.chatContainer.addChild(new Spacer(1));
3241
+ this.managedToolStatusStarted = true;
3242
+ }
3243
+ const message = status.type === "warning" ? `Warning: ${status.message}` : status.message;
3244
+ const color = status.type === "warning" ? "warning" : "dim";
3245
+ this.chatContainer.addChild(new ThemedText(() => theme.fg(color, message), 1, 0));
3246
+ this.lastStatusSpacer = undefined;
3247
+ this.lastStatusText = undefined;
3248
+ this.ui.requestRender();
3249
+ }
2574
3250
  /**
2575
3251
  * Show a status message in the chat.
2576
3252
  *
@@ -2582,12 +3258,14 @@ export class InteractiveMode {
2582
3258
  const last = children.length > 0 ? children[children.length - 1] : undefined;
2583
3259
  const secondLast = children.length > 1 ? children[children.length - 2] : undefined;
2584
3260
  if (last && secondLast && last === this.lastStatusText && secondLast === this.lastStatusSpacer) {
2585
- this.lastStatusText.setText(theme.fg("dim", message));
3261
+ this.lastStatusMessage = message;
3262
+ this.lastStatusText.invalidate();
2586
3263
  this.ui.requestRender();
2587
3264
  return;
2588
3265
  }
2589
3266
  const spacer = new Spacer(1);
2590
- const text = new Text(theme.fg("dim", message), 1, 0);
3267
+ this.lastStatusMessage = message;
3268
+ const text = new ThemedText(() => theme.fg("dim", this.lastStatusMessage), 1, 0);
2591
3269
  this.chatContainer.addChild(spacer);
2592
3270
  this.chatContainer.addChild(text);
2593
3271
  this.lastStatusSpacer = spacer;
@@ -2647,6 +3325,8 @@ export class InteractiveMode {
2647
3325
  this.chatContainer.addChild(component);
2648
3326
  break;
2649
3327
  }
3328
+ case "system":
3329
+ break;
2650
3330
  case "user": {
2651
3331
  const textContent = this.getUserMessageText(message);
2652
3332
  if (textContent) {
@@ -2662,12 +3342,12 @@ export class InteractiveMode {
2662
3342
  // Render user message separately if present
2663
3343
  if (skillBlock.userMessage) {
2664
3344
  this.chatContainer.addChild(new Spacer(1));
2665
- const userComponent = new UserMessageComponent(skillBlock.userMessage, this.getMarkdownThemeWithSettings(), this.outputPad);
3345
+ const userComponent = new UserMessageComponent(skillBlock.userMessage, this.getMarkdownThemeWithSettings(), this.outputPad, this.getMarkdownTransformers());
2666
3346
  this.chatContainer.addChild(userComponent);
2667
3347
  }
2668
3348
  }
2669
3349
  else {
2670
- const userComponent = new UserMessageComponent(textContent, this.getMarkdownThemeWithSettings(), this.outputPad);
3350
+ const userComponent = new UserMessageComponent(textContent, this.getMarkdownThemeWithSettings(), this.outputPad, this.getMarkdownTransformers());
2671
3351
  this.chatContainer.addChild(userComponent);
2672
3352
  }
2673
3353
  if (options?.populateHistory) {
@@ -2677,7 +3357,7 @@ export class InteractiveMode {
2677
3357
  break;
2678
3358
  }
2679
3359
  case "assistant": {
2680
- const assistantComponent = new AssistantMessageComponent(message, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad);
3360
+ const assistantComponent = new AssistantMessageComponent(message, this.hideThinkingBlock, this.getMarkdownThemeWithSettings(), this.hiddenThinkingLabel, this.outputPad, this.getMarkdownTransformers());
2681
3361
  this.chatContainer.addChild(assistantComponent);
2682
3362
  break;
2683
3363
  }
@@ -2693,8 +3373,8 @@ export class InteractiveMode {
2693
3373
  renderSessionItems(items, options = {}) {
2694
3374
  this.pendingTools.clear();
2695
3375
  const renderedPendingTools = new Map();
2696
- // Cache-miss notices are not persisted; re-derive them from the full entry
2697
- // list and re-inject them after the assistant messages that paid for them.
3376
+ // Cache misses are not persisted, unlike successful cache-warming usage.
3377
+ // Re-derive them and inject them after the assistant messages that paid for them.
2698
3378
  const cacheMisses = this.settingsManager.getShowCacheMissNotices()
2699
3379
  ? collectCacheMisses(this.sessionManager.getEntries(), this.session.modelRuntime)
2700
3380
  : new Map();
@@ -2707,6 +3387,14 @@ export class InteractiveMode {
2707
3387
  this.addCustomEntryToChat(item);
2708
3388
  continue;
2709
3389
  }
3390
+ if (isUsageSessionEntry(item)) {
3391
+ this.addCacheWarmingUsage(item);
3392
+ continue;
3393
+ }
3394
+ if (isCompactionCostNotice(item)) {
3395
+ this.addCompactionCostNotice(item);
3396
+ continue;
3397
+ }
2710
3398
  const message = item;
2711
3399
  // Assistant messages need special handling for tool calls
2712
3400
  if (message.role === "assistant") {
@@ -2771,13 +3459,75 @@ export class InteractiveMode {
2771
3459
  */
2772
3460
  renderSessionEntries(entries, options = {}) {
2773
3461
  const items = entries.flatMap((entry) => {
2774
- if (entry.type === "custom") {
3462
+ if (entry.type === "custom" || (entry.type === "usage" && entry.kind === "cache_warm")) {
2775
3463
  return [entry];
2776
3464
  }
2777
- return sessionEntryToContextMessages(entry);
3465
+ const messages = sessionEntryToContextMessages(entry);
3466
+ if ((entry.type === "compaction" || entry.type === "branch_summary") && entry.usage && messages.length > 0) {
3467
+ return [...messages, { type: "compaction_cost", kind: entry.type, usage: entry.usage }];
3468
+ }
3469
+ return messages;
2778
3470
  });
2779
3471
  this.renderSessionItems(items, options);
2780
3472
  }
3473
+ addCacheWarmingUsage(entry) {
3474
+ if (!this.settingsManager.getShowCacheMissNotices())
3475
+ return;
3476
+ this.chatContainer.addChild(new Spacer(1));
3477
+ const usage = formatCacheWarmingUsage(entry);
3478
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("dim", usage), 1, 0));
3479
+ }
3480
+ /**
3481
+ * Render billing usage for a compaction or branch summary. The notice is derived
3482
+ * from persisted summary usage and is not stored as a separate session entry.
3483
+ */
3484
+ addCompactionCostNotice(notice) {
3485
+ if (!this.settingsManager.getShowCacheMissNotices())
3486
+ return;
3487
+ const { usage } = notice;
3488
+ const tokens = usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
3489
+ const cost = usage.cost.total >= 0.01 ? ` (~$${usage.cost.total.toFixed(2)})` : "";
3490
+ const label = notice.kind === "compaction" ? "Compaction" : "Branch summary";
3491
+ this.chatContainer.addChild(new Spacer(1));
3492
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `${label}: ${formatTokens(tokens)} tokens billed${cost}`), 1, 0));
3493
+ }
3494
+ static countDroppedThinkingBlocks(message) {
3495
+ let count = 0;
3496
+ for (const diagnostic of message.diagnostics ?? []) {
3497
+ if (diagnostic.type !== "anthropic_input_transformations")
3498
+ continue;
3499
+ const transformations = diagnostic.details?.transformations;
3500
+ if (!Array.isArray(transformations))
3501
+ continue;
3502
+ count += transformations.filter((transformation) => typeof transformation === "object" &&
3503
+ transformation !== null &&
3504
+ transformation.type === "thinking_dropped").length;
3505
+ }
3506
+ return count;
3507
+ }
3508
+ maybeShowThinkingDropNotice(message) {
3509
+ if (!this.settingsManager.getShowCacheMissNotices())
3510
+ return;
3511
+ const droppedCount = InteractiveMode.countDroppedThinkingBlocks(message);
3512
+ if (droppedCount === 0)
3513
+ return;
3514
+ let previousDroppedCount = 0;
3515
+ // message_end reaches the UI before the current message is persisted,
3516
+ // so the branch's last assistant message is the previous response.
3517
+ const branch = this.sessionManager.getBranch();
3518
+ for (let i = branch.length - 1; i >= 0; i--) {
3519
+ const entry = branch[i];
3520
+ if (entry.type === "message" && entry.message.role === "assistant") {
3521
+ previousDroppedCount = InteractiveMode.countDroppedThinkingBlocks(entry.message);
3522
+ break;
3523
+ }
3524
+ }
3525
+ if (droppedCount <= previousDroppedCount)
3526
+ return;
3527
+ const noun = droppedCount === 1 ? "thinking block" : "thinking blocks";
3528
+ this.chatContainer.addChild(new Spacer(1));
3529
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `Anthropic dropped ${droppedCount} ${noun} (details in session)`), 1, 0));
3530
+ }
2781
3531
  /**
2782
3532
  * Show a transcript notice when a completed assistant message paid for a
2783
3533
  * significant cache miss. Only states observable facts: the miss itself,
@@ -2803,9 +3553,8 @@ export class InteractiveMode {
2803
3553
  else if (miss.idleMs >= CACHE_TTL_MS) {
2804
3554
  label = `Cache miss after ${Math.round(miss.idleMs / 60_000)}m idle`;
2805
3555
  }
2806
- const text = theme.fg("warning", `${label}: ${reBilled}`);
2807
3556
  this.chatContainer.addChild(new Spacer(1));
2808
- this.chatContainer.addChild(new Text(text, 1, 0));
3557
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `${label}: ${reBilled}`), 1, 0));
2809
3558
  }
2810
3559
  renderInitialMessages() {
2811
3560
  const entries = this.sessionManager.buildContextEntries();
@@ -2829,7 +3578,7 @@ export class InteractiveMode {
2829
3578
  if (this.chatContainer.children.length > 0) {
2830
3579
  this.chatContainer.addChild(new Spacer(1));
2831
3580
  }
2832
- this.chatContainer.addChild(new Text(theme.fg("warning", `This project is not trusted. Project ${CONFIG_DIR_NAME} resources and packages are ignored. Use /trust to save a trust decision, then restart pi.`), 1, 0));
3581
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `This project is not trusted. Project ${CONFIG_DIR_NAME} resources and packages are ignored. Use /trust to save a trust decision, then restart ${APP_NAME}.`), 1, 0));
2833
3582
  }
2834
3583
  async getUserInput() {
2835
3584
  const queuedInput = this.pendingUserInputs.shift();
@@ -2864,6 +3613,12 @@ export class InteractiveMode {
2864
3613
  // Only called when editor is empty (enforced by CustomEditor)
2865
3614
  void this.shutdown();
2866
3615
  }
3616
+ /**
3617
+ * Gracefully shutdown the agent.
3618
+ * Stops the TUI before emitting shutdown events so extension UI cleanup cannot
3619
+ * repaint the final frame while the process is exiting.
3620
+ */
3621
+ isShuttingDown = false;
2867
3622
  async shutdown(options) {
2868
3623
  if (this.isShuttingDown)
2869
3624
  return;
@@ -2936,8 +3691,14 @@ export class InteractiveMode {
2936
3691
  this.ui.stop();
2937
3692
  }
2938
3693
  catch { }
2939
- console.error("pi exiting due to uncaughtException:");
3694
+ console.error(`${APP_NAME} exiting due to uncaughtException:`);
2940
3695
  console.error(error);
3696
+ const extensionHint = this.getCrashExtensionHint(error);
3697
+ if (extensionHint)
3698
+ console.error(`\n${extensionHint}`);
3699
+ if (this.recordCrash("uncaught_exception", error)) {
3700
+ console.error(`\n${this.crashReportInstructions()}`);
3701
+ }
2941
3702
  process.exit(1);
2942
3703
  }
2943
3704
  /**
@@ -3069,6 +3830,7 @@ export class InteractiveMode {
3069
3830
  const level = this.session.thinkingLevel || "off";
3070
3831
  this.editor.borderColor = theme.getThinkingBorderColor(level);
3071
3832
  }
3833
+ this.activeStatusIndicator?.invalidate();
3072
3834
  this.ui.requestRender();
3073
3835
  }
3074
3836
  cycleThinkingLevel() {
@@ -3155,6 +3917,8 @@ export class InteractiveMode {
3155
3917
  this.setToolsExpanded(!this.toolOutputExpanded);
3156
3918
  }
3157
3919
  setToolsExpanded(expanded) {
3920
+ if (expanded === this.toolOutputExpanded)
3921
+ return;
3158
3922
  this.toolOutputExpanded = expanded;
3159
3923
  const activeHeader = this.customHeader ?? this.builtInHeader;
3160
3924
  if (isExpandable(activeHeader)) {
@@ -3169,18 +3933,19 @@ export class InteractiveMode {
3169
3933
  }
3170
3934
  this.showStatus(`Tool output: ${expanded ? "expanded" : "collapsed"}`);
3171
3935
  }
3936
+ /** Update rendered assistant messages without rebuilding live tool components. */
3937
+ updateThinkingBlockVisibility() {
3938
+ for (const child of this.chatContainer.children) {
3939
+ if (child instanceof AssistantMessageComponent) {
3940
+ child.setHideThinkingBlock(this.hideThinkingBlock);
3941
+ }
3942
+ }
3943
+ this.ui.requestRender();
3944
+ }
3172
3945
  toggleThinkingBlockVisibility() {
3173
3946
  this.hideThinkingBlock = !this.hideThinkingBlock;
3174
3947
  this.settingsManager.setHideThinkingBlock(this.hideThinkingBlock);
3175
- // Rebuild chat from session messages
3176
- this.chatContainer.clear();
3177
- this.rebuildChatFromMessages();
3178
- // If streaming, re-add the streaming component with updated visibility and re-render
3179
- if (this.streamingComponent && this.streamingMessage) {
3180
- this.streamingComponent.setHideThinkingBlock(this.hideThinkingBlock);
3181
- this.streamingComponent.updateContent(this.streamingMessage);
3182
- this.chatContainer.addChild(this.streamingComponent);
3183
- }
3948
+ this.updateThinkingBlockVisibility();
3184
3949
  this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
3185
3950
  }
3186
3951
  async handleOpenExternalEditor() {
@@ -3210,44 +3975,38 @@ export class InteractiveMode {
3210
3975
  }
3211
3976
  showError(errorMessage) {
3212
3977
  this.chatContainer.addChild(new Spacer(1));
3213
- this.chatContainer.addChild(new Text(theme.fg("error", `Error: ${errorMessage}`), 1, 0));
3978
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("error", `Error: ${errorMessage}`), this.outputPad, 0));
3214
3979
  this.ui.requestRender();
3215
3980
  }
3216
3981
  showWarning(warningMessage) {
3217
3982
  this.chatContainer.addChild(new Spacer(1));
3218
- this.chatContainer.addChild(new Text(theme.fg("warning", `Warning: ${warningMessage}`), 1, 0));
3983
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("warning", `Warning: ${warningMessage}`), 1, 0));
3219
3984
  this.ui.requestRender();
3220
3985
  }
3221
3986
  showNewVersionNotification(release) {
3222
- const action = theme.fg("accent", `${APP_NAME} update`);
3223
- const updateInstruction = theme.fg("muted", `New version ${release.version} is available. Run `) + action;
3224
- const changelogUrl = "https://pi.dev/changelog";
3225
- const changelogLink = getCapabilities().hyperlinks
3226
- ? hyperlink(theme.fg("accent", changelogUrl), changelogUrl)
3227
- : theme.fg("accent", changelogUrl);
3228
- const changelogLine = theme.fg("muted", "Changelog: ") + changelogLink;
3229
- const note = release.note?.trim();
3987
+ const updateInstruction = () => theme.fg("muted", `New version ${release.version} is available. Run `) +
3988
+ theme.fg("accent", `${APP_NAME} update`);
3989
+ const changelogUrl = "https://github.com/draht-dev/draht/blob/main/packages/coding-agent/CHANGELOG.md";
3990
+ const changelogLine = () => {
3991
+ const changelogLink = getCapabilities().hyperlinks
3992
+ ? hyperlink(theme.fg("accent", changelogUrl), changelogUrl)
3993
+ : theme.fg("accent", changelogUrl);
3994
+ return theme.fg("muted", "Changelog: ") + changelogLink;
3995
+ };
3230
3996
  this.chatContainer.addChild(new Spacer(1));
3231
3997
  this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3232
- this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction}`, 1, 0));
3233
- if (note) {
3234
- this.chatContainer.addChild(new Spacer(1));
3235
- this.chatContainer.addChild(new Markdown(note, 1, 0, this.getMarkdownThemeWithSettings(), {
3236
- color: (text) => theme.fg("muted", text),
3237
- }));
3238
- this.chatContainer.addChild(new Spacer(1));
3239
- }
3240
- this.chatContainer.addChild(new Text(changelogLine, 1, 0));
3998
+ this.chatContainer.addChild(new ThemedText(() => `${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction()}`, 1, 0));
3999
+ this.chatContainer.addChild(new ThemedText(changelogLine, 1, 0));
3241
4000
  this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3242
4001
  this.ui.requestRender();
3243
4002
  }
3244
4003
  showPackageUpdateNotification(packages) {
3245
- const action = theme.fg("accent", `${APP_NAME} update --extensions`);
3246
- const updateInstruction = theme.fg("muted", "Package updates are available. Run ") + action;
4004
+ const updateInstruction = () => theme.fg("muted", "Package updates are available. Run ") +
4005
+ theme.fg("accent", `${APP_NAME} update --extensions`);
3247
4006
  const packageLines = packages.map((pkg) => `- ${pkg}`).join("\n");
3248
4007
  this.chatContainer.addChild(new Spacer(1));
3249
4008
  this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3250
- this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Package Updates Available"))}\n${updateInstruction}\n${theme.fg("muted", "Packages:")}\n${packageLines}`, 1, 0));
4009
+ this.chatContainer.addChild(new ThemedText(() => `${theme.bold(theme.fg("warning", "Package Updates Available"))}\n${updateInstruction()}\n${theme.fg("muted", "Packages:")}\n${packageLines}`, 1, 0));
3251
4010
  this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
3252
4011
  this.ui.requestRender();
3253
4012
  }
@@ -3309,7 +4068,7 @@ export class InteractiveMode {
3309
4068
  if (allQueued.length === 0) {
3310
4069
  this.updatePendingMessagesDisplay();
3311
4070
  if (options?.abort) {
3312
- this.agent.abort();
4071
+ void this.session.abort();
3313
4072
  }
3314
4073
  return 0;
3315
4074
  }
@@ -3319,7 +4078,7 @@ export class InteractiveMode {
3319
4078
  this.editor.setText(combinedText);
3320
4079
  this.updatePendingMessagesDisplay();
3321
4080
  if (options?.abort) {
3322
- this.agent.abort();
4081
+ void this.session.abort();
3323
4082
  }
3324
4083
  return allQueued.length;
3325
4084
  }
@@ -3420,26 +4179,50 @@ export class InteractiveMode {
3420
4179
  // =========================================================================
3421
4180
  // Selectors
3422
4181
  // =========================================================================
4182
+ disposeActiveSelector() {
4183
+ const dispose = this.activeSelectorDispose;
4184
+ this.activeSelectorToken = undefined;
4185
+ this.activeSelectorDispose = undefined;
4186
+ dispose?.();
4187
+ }
3423
4188
  /**
3424
4189
  * Shows a selector component in place of the editor.
3425
4190
  * @param create Factory that receives a `done` callback and returns the component and focus target
3426
4191
  */
3427
4192
  showSelector(create) {
4193
+ const token = {};
4194
+ let dispose;
3428
4195
  const done = () => {
4196
+ dispose?.();
4197
+ if (this.activeSelectorToken !== token)
4198
+ return;
4199
+ this.activeSelectorToken = undefined;
4200
+ this.activeSelectorDispose = undefined;
3429
4201
  this.editorContainer.clear();
3430
4202
  this.editorContainer.addChild(this.editor);
3431
4203
  this.ui.setFocus(this.editor);
3432
4204
  };
3433
- const { component, focus } = create(done);
4205
+ const created = create(done);
4206
+ dispose = created.dispose;
4207
+ this.disposeActiveSelector();
4208
+ this.activeSelectorToken = token;
4209
+ this.activeSelectorDispose = dispose;
3434
4210
  this.editorContainer.clear();
3435
- this.editorContainer.addChild(component);
3436
- this.ui.setFocus(focus);
4211
+ this.editorContainer.addChild(created.component);
4212
+ this.ui.setFocus(created.focus);
3437
4213
  this.ui.requestRender();
3438
4214
  }
3439
4215
  showSettingsSelector() {
3440
4216
  this.showSelector((done) => {
3441
- const selector = new SettingsSelectorComponent({
4217
+ let selector;
4218
+ const defaultProvider = this.settingsManager.getDefaultProvider();
4219
+ const defaultModelId = this.settingsManager.getDefaultModel();
4220
+ const defaultModel = defaultProvider && defaultModelId ? `${defaultProvider}/${defaultModelId}` : "not set";
4221
+ selector = new SettingsSelectorComponent({
3442
4222
  autoCompact: this.session.autoCompactionEnabled,
4223
+ defaultModel,
4224
+ currentModel: this.session.model,
4225
+ availableDefaultModels: this.session.modelRuntime.getAvailableSnapshot(),
3443
4226
  showImages: this.settingsManager.getShowImages(),
3444
4227
  imageWidthCells: this.settingsManager.getImageWidthCells(),
3445
4228
  autoResizeImages: this.settingsManager.getImageAutoResize(),
@@ -3449,12 +4232,15 @@ export class InteractiveMode {
3449
4232
  followUpMode: this.session.followUpMode,
3450
4233
  transport: this.settingsManager.getTransport(),
3451
4234
  httpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(),
3452
- thinkingLevel: this.session.thinkingLevel,
3453
- availableThinkingLevels: this.session.getAvailableThinkingLevels(),
3454
- currentTheme: this.settingsManager.getThemeSetting() || "dark",
4235
+ cacheWarmingMode: this.settingsManager.getCacheWarmingMode(),
4236
+ thinkingLevel: this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL,
4237
+ availableThinkingLevels: [...THINKING_LEVEL_OPTIONS],
4238
+ modelThinkingLevels: this.settingsManager.getAllModelThinkingLevels(),
4239
+ currentTheme: this.themeController.getThemeSelection() || SYSTEM_THEME_NAME,
3455
4240
  terminalTheme: this.themeController.getTerminalTheme(),
3456
4241
  availableThemes: getAvailableThemes(),
3457
4242
  hideThinkingBlock: this.hideThinkingBlock,
4243
+ mermaidRenderingMode: this.settingsManager.getMermaidRenderingMode(),
3458
4244
  collapseChangelog: this.settingsManager.getCollapseChangelog(),
3459
4245
  enableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),
3460
4246
  doubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),
@@ -3466,8 +4252,14 @@ export class InteractiveMode {
3466
4252
  outputPad: this.settingsManager.getOutputPad(),
3467
4253
  autocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),
3468
4254
  quietStartup: this.settingsManager.getQuietStartup(),
4255
+ attachableSessions: this.settingsManager.getAttachableSessions(),
3469
4256
  clearOnShrink: this.settingsManager.getClearOnShrink(),
3470
4257
  showTerminalProgress: this.settingsManager.getShowTerminalProgress(),
4258
+ tuiMode: this.ui.mode,
4259
+ fullscreenExitOutput: this.settingsManager.getFullscreenExitOutput(),
4260
+ fullscreenScrollbar: this.settingsManager.getFullscreenScrollbar(),
4261
+ fullscreenCopyOnSelect: this.settingsManager.getFullscreenCopyOnSelect(),
4262
+ fullscreenWheelScrollLines: this.settingsManager.getFullscreenWheelScrollLines(),
3471
4263
  warnings: this.settingsManager.getWarnings(),
3472
4264
  }, {
3473
4265
  onAutoCompactChange: (enabled) => {
@@ -3515,26 +4307,45 @@ export class InteractiveMode {
3515
4307
  configureHttpDispatcher(timeoutMs);
3516
4308
  this.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`);
3517
4309
  },
3518
- onThinkingLevelChange: (level) => {
3519
- this.session.setThinkingLevel(level);
3520
- this.footer.invalidate();
3521
- this.updateEditorBorderColor();
4310
+ onCacheWarmingModeChange: (mode) => {
4311
+ this.session.setCacheWarmingMode(mode);
4312
+ this.showStatus(`Cache warming: ${mode}`);
4313
+ },
4314
+ onModelThinkingLevelChange: (provider, modelId, level) => {
4315
+ this.settingsManager.setModelThinkingLevel(provider, modelId, level);
4316
+ // If the override is for the current model, apply it to the session too
4317
+ const current = this.session.model;
4318
+ if (current && current.provider === provider && current.id === modelId) {
4319
+ this.session.setThinkingLevel(level);
4320
+ this.footer.invalidate();
4321
+ this.updateEditorBorderColor();
4322
+ }
4323
+ },
4324
+ onModelThinkingLevelRemove: (provider, modelId) => {
4325
+ this.settingsManager.removeModelThinkingLevel(provider, modelId);
4326
+ // If the override was for the current model, revert to global default
4327
+ const current = this.session.model;
4328
+ if (current && current.provider === provider && current.id === modelId) {
4329
+ const globalDefault = this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL;
4330
+ this.session.setThinkingLevel(globalDefault);
4331
+ this.footer.invalidate();
4332
+ this.updateEditorBorderColor();
4333
+ }
3522
4334
  },
3523
4335
  onThemeChange: (themeSetting) => {
3524
4336
  this.settingsManager.setTheme(themeSetting);
3525
- void this.themeController.applyFromSettings();
4337
+ this.themeController.setThemeSetting(themeSetting);
3526
4338
  },
3527
4339
  onThemePreview: (themeName) => this.themeController.preview(themeName),
3528
4340
  onHideThinkingBlockChange: (hidden) => {
3529
4341
  this.hideThinkingBlock = hidden;
3530
4342
  this.settingsManager.setHideThinkingBlock(hidden);
3531
- for (const child of this.chatContainer.children) {
3532
- if (child instanceof AssistantMessageComponent) {
3533
- child.setHideThinkingBlock(hidden);
3534
- }
3535
- }
3536
- this.chatContainer.clear();
3537
- this.rebuildChatFromMessages();
4343
+ this.updateThinkingBlockVisibility();
4344
+ },
4345
+ onMermaidRenderingModeChange: (mode) => {
4346
+ this.settingsManager.setMermaidRenderingMode(mode);
4347
+ this.chatContainer.invalidate();
4348
+ this.ui.requestRender();
3538
4349
  },
3539
4350
  onShowCacheMissNoticesChange: (shown) => {
3540
4351
  this.settingsManager.setShowCacheMissNotices(shown);
@@ -3549,6 +4360,10 @@ export class InteractiveMode {
3549
4360
  onQuietStartupChange: (enabled) => {
3550
4361
  this.settingsManager.setQuietStartup(enabled);
3551
4362
  },
4363
+ onAttachableSessionsChange: (enabled) => {
4364
+ // Takes effect on the next session start: this one already bound (or did not).
4365
+ this.settingsManager.setAttachableSessions(enabled);
4366
+ },
3552
4367
  onDefaultProjectTrustChange: (defaultProjectTrust) => {
3553
4368
  this.settingsManager.setDefaultProjectTrust(defaultProjectTrust);
3554
4369
  },
@@ -3605,6 +4420,34 @@ export class InteractiveMode {
3605
4420
  onShowTerminalProgressChange: (enabled) => {
3606
4421
  this.settingsManager.setShowTerminalProgress(enabled);
3607
4422
  },
4423
+ onTuiModeChange: (mode) => {
4424
+ if (!this.switchTuiMode(mode)) {
4425
+ selector?.getSettingsList().updateValue("tui-mode", this.ui.mode);
4426
+ this.showStatus("Close active overlays before changing TUI mode");
4427
+ return;
4428
+ }
4429
+ this.settingsManager.setTuiMode(mode);
4430
+ if (!this.activeStatusIndicator)
4431
+ this.statusContainer.clear();
4432
+ this.showStatus(`TUI mode: ${mode}`);
4433
+ },
4434
+ onFullscreenExitOutputChange: (output) => {
4435
+ this.settingsManager.setFullscreenExitOutput(output);
4436
+ },
4437
+ onFullscreenScrollbarChange: (mode) => {
4438
+ this.settingsManager.setFullscreenScrollbar(mode);
4439
+ this.applyFullscreenScrollbarSetting();
4440
+ },
4441
+ onFullscreenCopyOnSelectChange: (enabled) => {
4442
+ this.settingsManager.setFullscreenCopyOnSelect(enabled);
4443
+ if (this.renderer instanceof TuiAltScreen)
4444
+ this.renderer.setCopyOnSelect(enabled);
4445
+ },
4446
+ onFullscreenWheelScrollLinesChange: (lines) => {
4447
+ this.settingsManager.setFullscreenWheelScrollLines(lines);
4448
+ if (this.renderer instanceof TuiAltScreen)
4449
+ this.renderer.setWheelScrollLines(lines);
4450
+ },
3608
4451
  onWarningsChange: (warnings) => {
3609
4452
  this.settingsManager.setWarnings(warnings);
3610
4453
  },
@@ -3616,6 +4459,44 @@ export class InteractiveMode {
3616
4459
  return { component: selector, focus: selector.getSettingsList() };
3617
4460
  });
3618
4461
  }
4462
+ handleThinkingCommand(searchTerm) {
4463
+ const availableLevels = this.session.getAvailableThinkingLevels();
4464
+ if (!searchTerm) {
4465
+ this.showThinkingSelector();
4466
+ return;
4467
+ }
4468
+ const normalized = searchTerm.trim().toLowerCase();
4469
+ const level = availableLevels.find((candidate) => candidate.toLowerCase() === normalized);
4470
+ if (!level) {
4471
+ this.showError(`Unknown thinking level "${searchTerm}". Available levels: ${availableLevels.join(", ")}.`);
4472
+ return;
4473
+ }
4474
+ this.selectThinkingLevel(level, false);
4475
+ }
4476
+ selectThinkingLevel(level, persist) {
4477
+ try {
4478
+ this.session.setThinkingLevel(level, { persist });
4479
+ this.footer.invalidate();
4480
+ this.updateEditorBorderColor();
4481
+ this.showStatus(persist ? `Default thinking level: ${level}` : `Thinking level: ${level}`);
4482
+ }
4483
+ catch (error) {
4484
+ this.showError(error instanceof Error ? error.message : String(error));
4485
+ }
4486
+ }
4487
+ showThinkingSelector() {
4488
+ this.showSelector((done) => {
4489
+ const selectLevel = (level, persist) => {
4490
+ this.selectThinkingLevel(level, persist);
4491
+ done();
4492
+ };
4493
+ const selector = new ThinkingSelectorComponent(this.session.thinkingLevel ?? DEFAULT_THINKING_LEVEL, this.session.getAvailableThinkingLevels(), (level) => selectLevel(level, false), () => {
4494
+ done();
4495
+ this.ui.requestRender();
4496
+ }, (level) => selectLevel(level, true), this.settingsManager.getDefaultThinkingLevel() ?? DEFAULT_THINKING_LEVEL);
4497
+ return { component: selector, focus: selector };
4498
+ });
4499
+ }
3619
4500
  async handleModelCommand(searchTerm) {
3620
4501
  if (!searchTerm) {
3621
4502
  this.showModelSelector();
@@ -3624,7 +4505,7 @@ export class InteractiveMode {
3624
4505
  const model = await this.findExactModelMatch(searchTerm);
3625
4506
  if (model) {
3626
4507
  try {
3627
- await this.session.setModel(model);
4508
+ await this.session.setModel(model, { persist: false });
3628
4509
  this.footer.invalidate();
3629
4510
  this.updateEditorBorderColor();
3630
4511
  this.showStatus(`Model: ${model.id}`);
@@ -3639,20 +4520,37 @@ export class InteractiveMode {
3639
4520
  this.showModelSelector(searchTerm);
3640
4521
  }
3641
4522
  async findExactModelMatch(searchTerm) {
3642
- const models = await this.getModelCandidates();
3643
- return findExactModelReferenceMatch(searchTerm, models);
3644
- }
3645
- async getModelCandidates() {
3646
- if (this.session.scopedModels.length > 0) {
3647
- return this.session.scopedModels.map((scoped) => scoped.model);
3648
- }
4523
+ const cachedModels = this.session.scopedModels.length > 0
4524
+ ? this.session.scopedModels.map((scoped) => scoped.model)
4525
+ : [...this.session.modelRuntime.getAvailableSnapshot()];
4526
+ const cachedMatch = findExactModelReferenceMatch(searchTerm, cachedModels);
4527
+ if (cachedMatch || this.session.scopedModels.length > 0)
4528
+ return cachedMatch;
4529
+ this.showStatus("Refreshing model catalogs…");
4530
+ const controller = new AbortController();
4531
+ let timedOut = false;
4532
+ const timeout = setTimeout(() => {
4533
+ timedOut = true;
4534
+ controller.abort();
4535
+ }, 15_000);
3649
4536
  try {
3650
- await this.session.modelRuntime.refresh();
3651
- return [...(await this.session.modelRuntime.getAvailable())];
4537
+ const result = await refreshModelCatalogs(this.session.modelRuntime, controller.signal);
4538
+ if (result.aborted && timedOut) {
4539
+ this.showWarning("Model refresh timed out; searching cached models.");
4540
+ }
4541
+ else if (result.errors.size > 0) {
4542
+ this.showWarning(`Could not refresh ${[...result.errors.keys()].join(", ")}; searching cached models.`);
4543
+ }
3652
4544
  }
3653
- catch {
3654
- return [];
4545
+ catch (error) {
4546
+ this.showWarning(timedOut
4547
+ ? "Model refresh timed out; searching cached models."
4548
+ : `Could not refresh model catalogs: ${error instanceof Error ? error.message : String(error)}`);
3655
4549
  }
4550
+ finally {
4551
+ clearTimeout(timeout);
4552
+ }
4553
+ return findExactModelReferenceMatch(searchTerm, [...this.session.modelRuntime.getAvailableSnapshot()]);
3656
4554
  }
3657
4555
  /** Update the footer's available provider count from the current snapshot without refreshing catalogs. */
3658
4556
  updateAvailableProviderCount() {
@@ -3724,7 +4622,7 @@ export class InteractiveMode {
3724
4622
  onSelect: (selection) => {
3725
4623
  trustStore.setMany(selection.updates);
3726
4624
  done();
3727
- this.showStatus(`Saved trust decision: ${selection.trusted ? "trusted" : "untrusted"}. Restart pi for this to take effect.`);
4625
+ this.showStatus(`Saved trust decision: ${selection.trusted ? "trusted" : "untrusted"}. Restart ${APP_NAME} for this to take effect.`);
3728
4626
  },
3729
4627
  onCancel: () => {
3730
4628
  done();
@@ -3736,13 +4634,14 @@ export class InteractiveMode {
3736
4634
  }
3737
4635
  showModelSelector(initialSearchInput) {
3738
4636
  this.showSelector((done) => {
3739
- const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRuntime, this.session.scopedModels, async (model) => {
4637
+ const selectModel = async (model, persist) => {
3740
4638
  try {
3741
- await this.session.setModel(model);
4639
+ await this.session.setModel(model, { persist });
4640
+ this.updateAvailableProviderCount();
3742
4641
  this.footer.invalidate();
3743
4642
  this.updateEditorBorderColor();
3744
4643
  done();
3745
- this.showStatus(`Model: ${model.id}`);
4644
+ this.showStatus(persist ? `Default model: ${model.provider}/${model.id}` : `Model: ${model.id}`);
3746
4645
  void this.maybeWarnAboutAnthropicSubscriptionAuth(model);
3747
4646
  this.checkDaxnutsEasterEgg(model);
3748
4647
  }
@@ -3750,77 +4649,74 @@ export class InteractiveMode {
3750
4649
  done();
3751
4650
  this.showError(error instanceof Error ? error.message : String(error));
3752
4651
  }
3753
- }, () => {
4652
+ };
4653
+ const defaultProvider = this.settingsManager.getDefaultProvider();
4654
+ const defaultModel = this.settingsManager.getDefaultModel();
4655
+ const selector = new ModelSelectorComponent(this.ui, this.session.model, this.session.modelRuntime, this.session.scopedModels, (model) => selectModel(model, false), () => {
3754
4656
  done();
3755
4657
  this.ui.requestRender();
3756
- }, initialSearchInput);
3757
- return { component: selector, focus: selector };
4658
+ }, initialSearchInput, (model) => selectModel(model, true), defaultProvider && defaultModel ? { provider: defaultProvider, id: defaultModel } : undefined);
4659
+ return { component: selector, focus: selector, dispose: () => selector.dispose() };
3758
4660
  });
3759
4661
  }
3760
- async showModelsSelector() {
3761
- // Get all available models
3762
- await this.session.modelRuntime.refresh();
3763
- const allModels = [...(await this.session.modelRuntime.getAvailable())];
3764
- const allModelIds = new Set(allModels.map((model) => `${model.provider}/${model.id}`));
4662
+ showModelsSelector() {
4663
+ let availableModels = [...this.session.modelRuntime.getAvailableSnapshot()];
4664
+ let availableModelIds = new Set(availableModels.map((model) => `${model.provider}/${model.id}`));
3765
4665
  const configuredPatterns = this.settingsManager.getEnabledModels();
3766
4666
  const sessionScopedModels = this.session.scopedModels;
3767
- if (allModels.length === 0 && !configuredPatterns?.length && sessionScopedModels.length === 0) {
3768
- this.showStatus("No models available");
3769
- return;
3770
- }
3771
- const configuredScope = configuredPatterns?.length
3772
- ? await resolveModelScopeWithDiagnostics(configuredPatterns, this.session.modelRuntime)
3773
- : undefined;
3774
- // Check if session has scoped models (from previous session-only changes or CLI --models)
3775
- const hasSessionScope = sessionScopedModels.length > 0;
3776
- // Build enabled model IDs from session state or settings
3777
- let currentEnabledIds = null;
3778
- if (hasSessionScope) {
3779
- // Use current session's scoped models
3780
- currentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3781
- }
3782
- else if (configuredScope) {
3783
- currentEnabledIds = configuredScope.scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3784
- }
3785
- for (const diagnostic of configuredScope?.diagnostics ?? []) {
3786
- if (diagnostic.code !== "no-match")
3787
- continue;
3788
- currentEnabledIds ??= [];
3789
- if (!currentEnabledIds.includes(diagnostic.pattern))
3790
- currentEnabledIds.push(diagnostic.pattern);
3791
- }
3792
- // Helper to update session's scoped models (session-only, no persist)
3793
- const updateSessionModels = async (enabledIds) => {
4667
+ const configuredEnabledIds = (models) => {
4668
+ if (!configuredPatterns?.length)
4669
+ return null;
4670
+ const resolved = resolveModelScopeFromModels(configuredPatterns, models);
4671
+ const ids = resolved.scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
4672
+ for (const diagnostic of resolved.diagnostics) {
4673
+ if (diagnostic.code === "no-match" && !ids.includes(diagnostic.pattern))
4674
+ ids.push(diagnostic.pattern);
4675
+ }
4676
+ return ids;
4677
+ };
4678
+ let currentEnabledIds = sessionScopedModels.length > 0
4679
+ ? sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`)
4680
+ : configuredEnabledIds(availableModels);
4681
+ let selectionChanged = false;
4682
+ const updateSessionModels = (enabledIds) => {
3794
4683
  currentEnabledIds = enabledIds === null ? null : [...enabledIds];
3795
- const hasEnabledAvailableModel = enabledIds?.some((id) => allModelIds.has(id)) ?? false;
3796
- const allAvailableModelsEnabled = enabledIds !== null && [...allModelIds].every((id) => enabledIds.includes(id));
4684
+ const hasEnabledAvailableModel = enabledIds?.some((id) => availableModelIds.has(id)) ?? false;
4685
+ const allAvailableModelsEnabled = enabledIds !== null && [...availableModelIds].every((id) => enabledIds.includes(id));
3797
4686
  if (enabledIds && hasEnabledAvailableModel && !allAvailableModelsEnabled) {
3798
- const newScopedModels = await resolveModelScope(enabledIds, this.session.modelRuntime);
3799
- this.session.setScopedModels(newScopedModels.map((sm) => ({
3800
- model: sm.model,
3801
- thinkingLevel: sm.thinkingLevel,
4687
+ const newScopedModels = resolveModelScopeFromModels(enabledIds, availableModels).scopedModels;
4688
+ this.session.setScopedModels(newScopedModels.map((scoped) => ({
4689
+ model: scoped.model,
4690
+ thinkingLevel: scoped.thinkingLevel,
3802
4691
  })));
3803
4692
  }
3804
4693
  else {
3805
- // All enabled or none enabled = no filter
3806
4694
  this.session.setScopedModels([]);
3807
4695
  }
3808
- await this.updateAvailableProviderCount();
4696
+ this.updateAvailableProviderCount();
3809
4697
  this.ui.requestRender();
3810
4698
  };
3811
4699
  this.showSelector((done) => {
4700
+ let disposed = false;
4701
+ let timedOut = false;
4702
+ const controller = new AbortController();
4703
+ const timeout = setTimeout(() => {
4704
+ timedOut = true;
4705
+ controller.abort();
4706
+ }, 15_000);
3812
4707
  const selector = new ScopedModelsSelectorComponent({
3813
- allModels,
4708
+ allModels: availableModels,
3814
4709
  enabledModelIds: currentEnabledIds,
4710
+ refreshStatus: "Refreshing model catalogs…",
3815
4711
  }, {
3816
- onChange: async (enabledIds) => {
3817
- await updateSessionModels(enabledIds);
4712
+ onChange: (enabledIds) => {
4713
+ selectionChanged = true;
4714
+ updateSessionModels(enabledIds);
3818
4715
  },
3819
4716
  onPersist: (enabledIds) => {
3820
- // Persist to settings
3821
4717
  const allEnabled = enabledIds !== null &&
3822
- enabledIds.length === allModels.length &&
3823
- enabledIds.every((id) => allModelIds.has(id));
4718
+ enabledIds.length === availableModels.length &&
4719
+ enabledIds.every((id) => availableModelIds.has(id));
3824
4720
  const newPatterns = enabledIds === null || allEnabled ? undefined : enabledIds;
3825
4721
  this.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);
3826
4722
  this.showStatus("Model selection saved to settings");
@@ -3830,7 +4726,50 @@ export class InteractiveMode {
3830
4726
  this.ui.requestRender();
3831
4727
  },
3832
4728
  });
3833
- return { component: selector, focus: selector };
4729
+ void refreshModelCatalogs(this.session.modelRuntime, controller.signal)
4730
+ .then((result) => {
4731
+ if (disposed)
4732
+ return;
4733
+ availableModels = [...this.session.modelRuntime.getAvailableSnapshot()];
4734
+ availableModelIds = new Set(availableModels.map((model) => `${model.provider}/${model.id}`));
4735
+ if (!selectionChanged && sessionScopedModels.length === 0) {
4736
+ currentEnabledIds = configuredEnabledIds(availableModels);
4737
+ selector.updateModels(availableModels, currentEnabledIds);
4738
+ }
4739
+ else {
4740
+ selector.updateModels(availableModels);
4741
+ }
4742
+ if (currentEnabledIds !== null)
4743
+ updateSessionModels(currentEnabledIds);
4744
+ if (result.aborted && timedOut) {
4745
+ selector.setRefreshStatus("Model refresh timed out; showing cached models.", "warning");
4746
+ }
4747
+ else if (result.errors.size > 0) {
4748
+ selector.setRefreshStatus(`Could not refresh ${[...result.errors.keys()].join(", ")}; showing cached models.`, "warning");
4749
+ }
4750
+ else {
4751
+ selector.setRefreshStatus("Model catalogs refreshed.", "success");
4752
+ }
4753
+ this.ui.requestRender();
4754
+ })
4755
+ .catch((error) => {
4756
+ if (disposed)
4757
+ return;
4758
+ selector.setRefreshStatus(timedOut
4759
+ ? "Model refresh timed out; showing cached models."
4760
+ : `Could not refresh model catalogs: ${error instanceof Error ? error.message : String(error)}`, "warning");
4761
+ this.ui.requestRender();
4762
+ })
4763
+ .finally(() => clearTimeout(timeout));
4764
+ return {
4765
+ component: selector,
4766
+ focus: selector,
4767
+ dispose: () => {
4768
+ disposed = true;
4769
+ clearTimeout(timeout);
4770
+ controller.abort();
4771
+ },
4772
+ };
3834
4773
  });
3835
4774
  }
3836
4775
  showUserMessageSelector() {
@@ -3843,6 +4782,14 @@ export class InteractiveMode {
3843
4782
  this.showSelector((done) => {
3844
4783
  const selector = new UserMessageSelectorComponent(userMessages.map((m) => ({ id: m.entryId, text: m.text })), async (entryId) => {
3845
4784
  done();
4785
+ // The user committed to forking: stop the active response first,
4786
+ // the same way /tree and /rewind do. The fork fires the
4787
+ // checkpoint restore offer, and that must never rewrite the
4788
+ // working tree while the agent is still writing to it.
4789
+ if (this.session.isStreaming) {
4790
+ this.restoreQueuedMessagesToEditor();
4791
+ await this.session.abort();
4792
+ }
3846
4793
  try {
3847
4794
  const result = await this.runtimeHost.fork(entryId);
3848
4795
  if (result.cancelled) {
@@ -3932,6 +4879,11 @@ export class InteractiveMode {
3932
4879
  this.restoreQueuedMessagesToEditor();
3933
4880
  await this.session.abort();
3934
4881
  }
4882
+ // Recheck after the dialogs and streaming abort, before replacing another operation's UI.
4883
+ if (this.session.isCompacting) {
4884
+ this.showError("Wait for the current compaction or tree navigation to finish before navigating the session tree.");
4885
+ return;
4886
+ }
3935
4887
  // Set up escape handler and status indicator if summarizing
3936
4888
  let showingSummaryIndicator = false;
3937
4889
  const originalOnEscape = this.defaultEditor.onEscape;
@@ -4000,11 +4952,129 @@ export class InteractiveMode {
4000
4952
  return { component: selector, focus: selector };
4001
4953
  });
4002
4954
  }
4955
+ /** Checkpoint manager for the live session; undefined before a session file exists. */
4956
+ createCheckpointManager() {
4957
+ const sessionFile = this.sessionManager.getSessionFile();
4958
+ if (!sessionFile)
4959
+ return undefined;
4960
+ return new CheckpointManager({
4961
+ cwd: this.sessionManager.getCwd(),
4962
+ sessionId: this.sessionManager.getSessionId(),
4963
+ sessionFile,
4964
+ });
4965
+ }
4966
+ /**
4967
+ * `/rewind` (R42-RWD.1): the tree selector, restricted to entries that have a
4968
+ * checkpoint and annotated with its time and dirty-file count, followed by the
4969
+ * restore-scope menu (R42-RWD.2). Entries on abandoned branches keep their
4970
+ * checkpoints, so rewinding forward to one is just another selection (R42-RWD.6).
4971
+ */
4972
+ showRewindSelector(initialSelectedId) {
4973
+ const tree = this.sessionManager.getTree();
4974
+ if (tree.length === 0) {
4975
+ this.showStatus("No entries in session");
4976
+ return;
4977
+ }
4978
+ const manager = this.createCheckpointManager();
4979
+ const targets = manager ? listRewindTargets(manager.list()) : [];
4980
+ const checkpoints = targets.length > 0
4981
+ ? new Map(targets.map((target) => [
4982
+ target.entryId,
4983
+ { timestamp: target.timestamp, dirtyFileCount: target.dirtyFileCount },
4984
+ ]))
4985
+ : undefined;
4986
+ if (!checkpoints) {
4987
+ // No snapshots (e.g. a non-git cwd): still rewind the conversation.
4988
+ this.showStatus("No checkpoints recorded - /rewind will restore the conversation only");
4989
+ }
4990
+ this.showSelector((done) => {
4991
+ const selector = new TreeSelectorComponent(tree, this.sessionManager.getLeafId(), this.ui.terminal.rows, async (entryId) => {
4992
+ done();
4993
+ if (!checkpoints) {
4994
+ await this.runRewind(entryId, "conversation-only", undefined);
4995
+ return;
4996
+ }
4997
+ const label = await this.showExtensionSelector("Restore scope?", REWIND_SCOPE_CHOICES.map((choice) => choice.label));
4998
+ if (label === undefined) {
4999
+ // Escape returns to the selector with the same entry focused.
5000
+ this.showRewindSelector(entryId);
5001
+ return;
5002
+ }
5003
+ await this.runRewind(entryId, rewindScopeForLabel(label) ?? DEFAULT_REWIND_SCOPE, manager);
5004
+ }, () => {
5005
+ done();
5006
+ this.ui.requestRender();
5007
+ }, undefined, initialSelectedId, undefined, { title: "Rewind", checkpoints });
5008
+ return { component: selector, focus: selector };
5009
+ });
5010
+ }
5011
+ /**
5012
+ * Run the rewind under the chosen scope. The conversation leaf is moved by
5013
+ * `performRewind` through this navigate callback, which it only invokes once
5014
+ * the file restore has succeeded (R42-RWD.5).
5015
+ */
5016
+ async runRewind(targetEntryId, scope, manager) {
5017
+ const currentEntryId = this.sessionManager.getLeafId();
5018
+ if (!currentEntryId) {
5019
+ this.showStatus("Nothing to rewind yet");
5020
+ return;
5021
+ }
5022
+ if (targetEntryId === currentEntryId && scope === "conversation-only") {
5023
+ this.showStatus("Already at this point");
5024
+ return;
5025
+ }
5026
+ // The user committed to rewinding: stop the active response first.
5027
+ if (this.session.isStreaming) {
5028
+ this.restoreQueuedMessagesToEditor();
5029
+ await this.session.abort();
5030
+ }
5031
+ // The selector already called `done()`, so the editor has focus again
5032
+ // while this runs. Block submissions until the restore is finished
5033
+ // rather than let a new prompt race the file writes.
5034
+ this.isRewindRunning = true;
5035
+ let result;
5036
+ try {
5037
+ result = await performRewind({
5038
+ manager,
5039
+ scope,
5040
+ // Scopes the in-progress gate to this session (R35-ALWAYS.5).
5041
+ // Read at call time so it follows a session replacement.
5042
+ sessionId: this.sessionManager.getSessionId(),
5043
+ targetEntryId,
5044
+ currentEntryId,
5045
+ // Gives extensions the `session_before_rewind` veto (R42-RWD.8).
5046
+ runner: this.session.extensionRunner,
5047
+ navigate: async () => {
5048
+ if (targetEntryId === currentEntryId)
5049
+ return;
5050
+ const navigation = await this.session.navigateTree(targetEntryId, { summarize: false });
5051
+ if (navigation.cancelled)
5052
+ throw new Error("navigation cancelled");
5053
+ this.chatContainer.clear();
5054
+ this.renderInitialMessages();
5055
+ if (navigation.editorText && !this.editor.getText().trim()) {
5056
+ this.editor.setText(navigation.editorText);
5057
+ }
5058
+ void this.flushCompactionQueue({ willRetry: false });
5059
+ },
5060
+ });
5061
+ }
5062
+ finally {
5063
+ this.isRewindRunning = false;
5064
+ }
5065
+ if (result.ok) {
5066
+ this.showStatus(result.message);
5067
+ }
5068
+ else {
5069
+ this.showError(result.message);
5070
+ }
5071
+ this.ui.requestRender();
5072
+ }
4003
5073
  showSessionSelector() {
4004
5074
  this.showSelector((done) => {
4005
- const selector = new SessionSelectorComponent((onProgress) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress), (onProgress) => this.sessionManager.usesDefaultSessionDir()
4006
- ? SessionManager.listAll(onProgress)
4007
- : SessionManager.listAll(this.sessionManager.getSessionDir(), onProgress), async (sessionPath) => {
5075
+ const selector = new SessionSelectorComponent((onProgress, signal) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress, signal), (onProgress, signal) => this.sessionManager.usesDefaultSessionDir()
5076
+ ? SessionManager.listAll(onProgress, signal)
5077
+ : SessionManager.listAll(this.sessionManager.getSessionDir(), onProgress, signal), async (sessionPath) => {
4008
5078
  done();
4009
5079
  await this.handleResumeSession(sessionPath);
4010
5080
  }, () => {
@@ -4092,7 +5162,7 @@ export class InteractiveMode {
4092
5162
  return options.sort((a, b) => a.name.localeCompare(b.name));
4093
5163
  }
4094
5164
  async getLogoutProviderOptions() {
4095
- return (await this.session.modelRuntime.listCredentials())
5165
+ return (await this.session.modelRuntime.listCredentials({ signal: AbortSignal.timeout(15_000) }))
4096
5166
  .map(({ providerId, type }) => ({
4097
5167
  id: providerId,
4098
5168
  name: this.session.modelRuntime.getProvider(providerId)?.name ?? providerId,
@@ -4110,7 +5180,6 @@ export class InteractiveMode {
4110
5180
  provider.name.toLowerCase() === normalizedProviderRef);
4111
5181
  }
4112
5182
  async handleLoginCommand(providerRef) {
4113
- await this.session.modelRuntime.getAvailable();
4114
5183
  if (!providerRef) {
4115
5184
  this.showLoginAuthTypeSelector();
4116
5185
  return;
@@ -4224,7 +5293,14 @@ export class InteractiveMode {
4224
5293
  this.showLoginAuthTypeSelector();
4225
5294
  return;
4226
5295
  }
4227
- const providerOptions = await this.getLogoutProviderOptions();
5296
+ let providerOptions;
5297
+ try {
5298
+ providerOptions = await this.getLogoutProviderOptions();
5299
+ }
5300
+ catch (error) {
5301
+ this.showError(`Could not read stored credentials: ${error instanceof Error ? error.message : String(error)}`);
5302
+ return;
5303
+ }
4228
5304
  if (providerOptions.length === 0) {
4229
5305
  this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");
4230
5306
  return;
@@ -4237,7 +5313,9 @@ export class InteractiveMode {
4237
5313
  return;
4238
5314
  }
4239
5315
  try {
4240
- await this.session.modelRuntime.logout(providerOption.id);
5316
+ await this.session.modelRuntime.logout(providerOption.id, {
5317
+ signal: AbortSignal.timeout(15_000),
5318
+ });
4241
5319
  await this.updateAvailableProviderCount();
4242
5320
  const message = providerOption.authType === "oauth"
4243
5321
  ? `Logged out of ${providerOption.name}`
@@ -4245,7 +5323,10 @@ export class InteractiveMode {
4245
5323
  this.showStatus(message);
4246
5324
  }
4247
5325
  catch (error) {
4248
- this.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);
5326
+ const message = error instanceof Error ? error.message : String(error);
5327
+ this.showError(error instanceof CredentialSynchronizationError
5328
+ ? `Credentials removed for ${providerOption.name}, but local model state could not be synchronized: ${message}`
5329
+ : `Logout failed: ${message}`);
4249
5330
  }
4250
5331
  }, () => {
4251
5332
  done();
@@ -4255,54 +5336,98 @@ export class InteractiveMode {
4255
5336
  });
4256
5337
  }
4257
5338
  async completeProviderAuthentication(providerId, providerName, authType, previousModel) {
4258
- await this.session.modelRuntime.getAvailable();
4259
5339
  const actionLabel = authType === "oauth" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;
4260
- let selectedModel;
4261
- let selectionError;
4262
- if (isUnknownModel(previousModel)) {
4263
- const availableModels = await this.session.modelRuntime.getAvailable();
4264
- const providerModels = availableModels.filter((model) => model.provider === providerId);
4265
- if (!hasDefaultModelProvider(providerId)) {
4266
- selectionError = `${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;
5340
+ const session = this.session;
5341
+ // Dynamic catalogs may be empty until the first authenticated network refresh.
5342
+ const deferSelection = isUnknownModel(previousModel) &&
5343
+ hasDefaultModelProvider(providerId) &&
5344
+ !session.modelRuntime
5345
+ .getAvailableSnapshot()
5346
+ .some((model) => model.provider === providerId && model.id === defaultModelPerProvider[providerId]);
5347
+ const finishAuthentication = async () => {
5348
+ let selectedModel;
5349
+ let selectionError;
5350
+ if (isUnknownModel(previousModel)) {
5351
+ const availableModels = this.session.modelRuntime.getAvailableSnapshot();
5352
+ const providerModels = availableModels.filter((model) => model.provider === providerId);
5353
+ // Matches LLAMA_PROVIDER_ID from extensions/llama/provider.ts; kept inline to avoid coupling interactive mode to the built-in extension.
5354
+ if (providerId === "llama.cpp") {
5355
+ selectionError = llamaCppPostLoginGuidance(actionLabel, providerModels.length);
5356
+ }
5357
+ else if (!hasDefaultModelProvider(providerId)) {
5358
+ selectionError = `${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;
5359
+ }
5360
+ else if (providerModels.length === 0) {
5361
+ selectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;
5362
+ }
5363
+ else {
5364
+ const defaultModelId = defaultModelPerProvider[providerId];
5365
+ // Radius catalogs vary by account; prefer balanced, then use catalog order.
5366
+ selectedModel =
5367
+ providerModels.find((model) => model.id === defaultModelId) ??
5368
+ (providerId === "radius" ? providerModels[0] : undefined);
5369
+ if (!selectedModel) {
5370
+ selectionError = `${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`;
5371
+ }
5372
+ else {
5373
+ try {
5374
+ await this.session.setModel(selectedModel, { persist: true });
5375
+ }
5376
+ catch (error) {
5377
+ selectedModel = undefined;
5378
+ const errorMessage = error instanceof Error ? error.message : String(error);
5379
+ selectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;
5380
+ }
5381
+ }
5382
+ }
4267
5383
  }
4268
- else if (providerModels.length === 0) {
4269
- selectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;
5384
+ await this.updateAvailableProviderCount();
5385
+ this.footer.invalidate();
5386
+ this.updateEditorBorderColor();
5387
+ if (selectedModel) {
5388
+ this.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);
5389
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);
5390
+ this.checkDaxnutsEasterEgg(selectedModel);
4270
5391
  }
4271
5392
  else {
4272
- const defaultModelId = defaultModelPerProvider[providerId];
4273
- selectedModel = providerModels.find((model) => model.id === defaultModelId);
4274
- if (!selectedModel) {
4275
- selectionError = `${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`;
5393
+ this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);
5394
+ if (selectionError) {
5395
+ this.showError(selectionError);
4276
5396
  }
4277
5397
  else {
4278
- try {
4279
- await this.session.setModel(selectedModel);
4280
- }
4281
- catch (error) {
4282
- selectedModel = undefined;
4283
- const errorMessage = error instanceof Error ? error.message : String(error);
4284
- selectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;
4285
- }
5398
+ void this.maybeWarnAboutAnthropicSubscriptionAuth();
4286
5399
  }
4287
5400
  }
4288
- }
4289
- await this.updateAvailableProviderCount();
4290
- this.footer.invalidate();
4291
- this.updateEditorBorderColor();
4292
- if (selectedModel) {
4293
- this.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);
4294
- void this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);
4295
- this.checkDaxnutsEasterEgg(selectedModel);
5401
+ };
5402
+ if (deferSelection) {
5403
+ this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}. Refreshing model catalog…`);
4296
5404
  }
4297
5405
  else {
4298
- this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);
4299
- if (selectionError) {
4300
- this.showError(selectionError);
5406
+ await finishAuthentication();
5407
+ }
5408
+ const controller = new AbortController();
5409
+ const timeout = setTimeout(() => controller.abort(), 15_000);
5410
+ void session.modelRuntime
5411
+ .refresh({ providers: [providerId], signal: controller.signal })
5412
+ .then(async (result) => {
5413
+ if (result.aborted) {
5414
+ this.showWarning(`${actionLabel}, but its model catalog refresh timed out; using cached models.`);
4301
5415
  }
4302
- else {
4303
- void this.maybeWarnAboutAnthropicSubscriptionAuth();
5416
+ else if (result.errors.size > 0) {
5417
+ this.showWarning(`${actionLabel}, but its model catalog could not be refreshed; using cached models.`);
4304
5418
  }
4305
- }
5419
+ // Do not replace a model or session selected while the refresh was running.
5420
+ if (deferSelection && this.session === session && session.model === previousModel) {
5421
+ await finishAuthentication();
5422
+ }
5423
+ this.updateAvailableProviderCount();
5424
+ this.footer.invalidate();
5425
+ this.ui.requestRender();
5426
+ })
5427
+ .catch((error) => {
5428
+ this.showWarning(`${actionLabel}, but its model catalog could not be refreshed: ${error instanceof Error ? error.message : String(error)}`);
5429
+ })
5430
+ .finally(() => clearTimeout(timeout));
4306
5431
  }
4307
5432
  showAmbientAuthDialog(providerOption) {
4308
5433
  const restoreEditor = () => {
@@ -4312,7 +5437,7 @@ export class InteractiveMode {
4312
5437
  this.ui.requestRender();
4313
5438
  };
4314
5439
  const dialog = new LoginDialogComponent(this.ui, providerOption.id, () => restoreEditor(), providerOption.name, `${providerOption.name} setup`);
4315
- dialog.showInfo(`${providerOption.method?.name ?? "Authentication"} is configured outside pi.`, [], true);
5440
+ dialog.showInfo(`${providerOption.method?.name ?? "Authentication"} is configured outside ${APP_NAME}.`, [], true);
4316
5441
  this.editorContainer.clear();
4317
5442
  this.editorContainer.addChild(dialog);
4318
5443
  this.ui.setFocus(dialog);
@@ -4348,7 +5473,10 @@ export class InteractiveMode {
4348
5473
  catch (error) {
4349
5474
  restoreEditor();
4350
5475
  const errorMsg = error instanceof Error ? error.message : String(error);
4351
- if (errorMsg !== "Login cancelled") {
5476
+ if (error instanceof CredentialSynchronizationError) {
5477
+ this.showError(`Saved API key for ${providerName}, but local model state could not be synchronized: ${errorMsg}`);
5478
+ }
5479
+ else if (errorMsg !== "Login cancelled") {
4352
5480
  this.showError(`Failed to save API key for ${providerName}: ${errorMsg}`);
4353
5481
  }
4354
5482
  }
@@ -4428,7 +5556,7 @@ export class InteractiveMode {
4428
5556
  signal: dialog.signal,
4429
5557
  prompt: (prompt) => this.showAuthPrompt(dialog, prompt),
4430
5558
  notify: (event) => this.notifyAuthDialog(dialog, event),
4431
- });
5559
+ }, { getDeviceId: () => this.settingsManager.getOrCreateDeviceId() });
4432
5560
  }
4433
5561
  async showLoginDialog(providerId, providerName) {
4434
5562
  const previousModel = this.session.model;
@@ -4451,7 +5579,10 @@ export class InteractiveMode {
4451
5579
  catch (error) {
4452
5580
  restoreEditor();
4453
5581
  const errorMsg = error instanceof Error ? error.message : String(error);
4454
- if (errorMsg !== "Login cancelled") {
5582
+ if (error instanceof CredentialSynchronizationError) {
5583
+ this.showError(`Logged in to ${providerName}, but local model state could not be synchronized: ${errorMsg}`);
5584
+ }
5585
+ else if (errorMsg !== "Login cancelled") {
4455
5586
  this.showError(`Failed to login to ${providerName}: ${errorMsg}`);
4456
5587
  }
4457
5588
  }
@@ -4473,7 +5604,7 @@ export class InteractiveMode {
4473
5604
  const borderColor = (s) => theme.fg("border", s);
4474
5605
  reloadBox.addChild(new DynamicBorder(borderColor));
4475
5606
  reloadBox.addChild(new Spacer(1));
4476
- reloadBox.addChild(new Text(theme.fg("muted", "Reloading keybindings, extensions, skills, prompts, themes, and context files..."), 1, 0));
5607
+ reloadBox.addChild(new ThemedText(() => theme.fg("muted", "Reloading keybindings, extensions, skills, prompts, themes, and context files..."), 1, 0));
4477
5608
  reloadBox.addChild(new Spacer(1));
4478
5609
  reloadBox.addChild(new DynamicBorder(borderColor));
4479
5610
  const previousEditor = this.editor;
@@ -4502,28 +5633,14 @@ export class InteractiveMode {
4502
5633
  try {
4503
5634
  await this.session.reload({ beforeSessionStart: restoreChatBeforeSessionStart });
4504
5635
  restoreChatBeforeSessionStart();
4505
- configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());
4506
5636
  this.keybindings.reload();
4507
5637
  const activeHeader = this.customHeader ?? this.builtInHeader;
4508
5638
  if (isExpandable(activeHeader)) {
4509
5639
  activeHeader.setExpanded(this.toolOutputExpanded);
4510
5640
  }
4511
5641
  setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
4512
- await this.themeController.applyFromSettings();
4513
- const editorPaddingX = this.settingsManager.getEditorPaddingX();
4514
- const autocompleteMaxVisible = this.settingsManager.getAutocompleteMaxVisible();
4515
- this.defaultEditor.setPaddingX(editorPaddingX);
4516
- this.defaultEditor.setAutocompleteMaxVisible(autocompleteMaxVisible);
4517
- if (this.editor !== this.defaultEditor) {
4518
- this.editor.setPaddingX?.(editorPaddingX);
4519
- this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);
4520
- }
4521
- this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());
4522
- const clearOnShrink = this.settingsManager.getClearOnShrink();
4523
- this.ui.setClearOnShrink(clearOnShrink);
4524
- if (!clearOnShrink && !this.activeStatusIndicator) {
4525
- this.statusContainer.clear();
4526
- }
5642
+ this.applyRuntimeSettings();
5643
+ this.themeController.applyFromSettings();
4527
5644
  this.setupAutocompleteProvider();
4528
5645
  const runner = this.session.extensionRunner;
4529
5646
  this.setupExtensionShortcuts(runner);
@@ -4557,7 +5674,9 @@ export class InteractiveMode {
4557
5674
  this.showStatus(`Session exported to: ${filePath}`);
4558
5675
  }
4559
5676
  else {
4560
- const filePath = await this.session.exportToHtml(outputPath);
5677
+ const filePath = await this.session.exportToHtml(outputPath, {
5678
+ themeName: theme.name,
5679
+ });
4561
5680
  this.showStatus(`Session exported to: ${filePath}`);
4562
5681
  }
4563
5682
  }
@@ -4633,93 +5752,34 @@ export class InteractiveMode {
4633
5752
  }
4634
5753
  }
4635
5754
  async handleShareCommand() {
4636
- // Check if gh is available and logged in
4637
- try {
4638
- const authResult = spawnSync("gh", ["auth", "status"], { encoding: "utf-8" });
4639
- if (authResult.status !== 0) {
4640
- this.showError("GitHub CLI is not logged in. Run 'gh auth login' first.");
4641
- return;
4642
- }
4643
- }
4644
- catch {
4645
- this.showError("GitHub CLI (gh) is not installed. Install it from https://cli.github.com/");
4646
- return;
4647
- }
4648
- // Export to a temp file
4649
- const tmpFile = path.join(os.tmpdir(), "session.html");
4650
- try {
4651
- await this.session.exportToHtml(tmpFile);
4652
- }
4653
- catch (error) {
4654
- this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
5755
+ await shareSession({
5756
+ session: this.session,
5757
+ ui: this.ui,
5758
+ editorContainer: this.editorContainer,
5759
+ editor: this.editor,
5760
+ showStatus: (message) => this.showStatus(message),
5761
+ showError: (message) => this.showError(message),
5762
+ });
5763
+ }
5764
+ async handleBugCommand(hint) {
5765
+ await reportBug({
5766
+ session: this.session,
5767
+ ui: this.ui,
5768
+ editorContainer: this.editorContainer,
5769
+ editor: this.editor,
5770
+ keybindings: this.keybindings,
5771
+ showStatus: (message) => this.showStatus(message),
5772
+ showError: (message) => this.showError(message),
5773
+ }, hint);
5774
+ }
5775
+ async handleCopyCommand(options = {}) {
5776
+ if (options.preferSelection &&
5777
+ this.ui instanceof TuiAltScreen &&
5778
+ !this.ui.getCopyOnSelect() &&
5779
+ this.ui.hasActiveSelection()) {
5780
+ await this.ui.copyActiveSelectionToClipboard();
4655
5781
  return;
4656
5782
  }
4657
- // Show cancellable loader, replacing the editor
4658
- const loader = new BorderedLoader(this.ui, theme, "Creating gist...");
4659
- this.editorContainer.clear();
4660
- this.editorContainer.addChild(loader);
4661
- this.ui.setFocus(loader);
4662
- this.ui.requestRender();
4663
- const restoreEditor = () => {
4664
- loader.dispose();
4665
- this.editorContainer.clear();
4666
- this.editorContainer.addChild(this.editor);
4667
- this.ui.setFocus(this.editor);
4668
- try {
4669
- fs.unlinkSync(tmpFile);
4670
- }
4671
- catch {
4672
- // Ignore cleanup errors
4673
- }
4674
- };
4675
- // Create a secret gist asynchronously
4676
- let proc = null;
4677
- loader.onAbort = () => {
4678
- proc?.kill();
4679
- restoreEditor();
4680
- this.showStatus("Share cancelled");
4681
- };
4682
- try {
4683
- const result = await new Promise((resolve) => {
4684
- proc = spawn("gh", ["gist", "create", "--public=false", tmpFile]);
4685
- let stdout = "";
4686
- let stderr = "";
4687
- proc.stdout?.on("data", (data) => {
4688
- stdout += data.toString();
4689
- });
4690
- proc.stderr?.on("data", (data) => {
4691
- stderr += data.toString();
4692
- });
4693
- proc.on("close", (code) => resolve({ stdout, stderr, code }));
4694
- });
4695
- if (loader.signal.aborted)
4696
- return;
4697
- restoreEditor();
4698
- if (result.code !== 0) {
4699
- const errorMsg = result.stderr?.trim() || "Unknown error";
4700
- this.showError(`Failed to create gist: ${errorMsg}`);
4701
- return;
4702
- }
4703
- // Extract gist ID from the URL returned by gh
4704
- // gh returns something like: https://gist.github.com/username/GIST_ID
4705
- const gistUrl = result.stdout?.trim();
4706
- const gistId = gistUrl?.split("/").pop();
4707
- if (!gistId) {
4708
- this.showError("Failed to parse gist ID from gh output");
4709
- return;
4710
- }
4711
- // Create the preview URL
4712
- const previewUrl = getShareViewerUrl(gistId);
4713
- this.showStatus(`Share URL: ${previewUrl}\nGist: ${gistUrl}`);
4714
- }
4715
- catch (error) {
4716
- if (!loader.signal.aborted) {
4717
- restoreEditor();
4718
- this.showError(`Failed to create gist: ${error instanceof Error ? error.message : "Unknown error"}`);
4719
- }
4720
- }
4721
- }
4722
- async handleCopyCommand() {
4723
5783
  const text = this.session.getLastAssistantText();
4724
5784
  if (!text) {
4725
5785
  this.showError("No agent messages to copy yet.");
@@ -4727,7 +5787,12 @@ export class InteractiveMode {
4727
5787
  }
4728
5788
  try {
4729
5789
  await copyToClipboard(text);
4730
- this.showStatus("Copied last agent message to clipboard");
5790
+ if (options.flashConfirmation && this.ui instanceof TuiAltScreen) {
5791
+ this.ui.flash("Copied!");
5792
+ }
5793
+ else {
5794
+ this.showStatus("Copied last agent message to clipboard");
5795
+ }
4731
5796
  }
4732
5797
  catch (error) {
4733
5798
  this.showError(error instanceof Error ? error.message : String(error));
@@ -4739,7 +5804,7 @@ export class InteractiveMode {
4739
5804
  const currentName = this.sessionManager.getSessionName();
4740
5805
  if (currentName) {
4741
5806
  this.chatContainer.addChild(new Spacer(1));
4742
- this.chatContainer.addChild(new Text(theme.fg("dim", `Session name: ${currentName}`), 1, 0));
5807
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("dim", `Session name: ${currentName}`), 1, 0));
4743
5808
  }
4744
5809
  else {
4745
5810
  this.showWarning("Usage: /name <name>");
@@ -4753,7 +5818,8 @@ export class InteractiveMode {
4753
5818
  this.showWarning(`Session name was normalized from ${JSON.stringify(name)} to ${JSON.stringify(sessionName)}`);
4754
5819
  }
4755
5820
  this.chatContainer.addChild(new Spacer(1));
4756
- this.chatContainer.addChild(new Text(theme.fg("dim", `Session name set: ${sessionName ?? name}`), 1, 0));
5821
+ const displayName = sessionName ?? name;
5822
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("dim", `Session name set: ${displayName}`), 1, 0));
4757
5823
  this.ui.requestRender();
4758
5824
  }
4759
5825
  handleSessionCommand() {
@@ -4765,52 +5831,69 @@ export class InteractiveMode {
4765
5831
  // resolves to a concrete responseModel). Usage without model attribution is
4766
5832
  // grouped separately so the breakdown reconciles with the session total.
4767
5833
  const usageBreakdown = getUsageCostBreakdown(entries);
4768
- let info = `${theme.bold("Session Info")}\n\n`;
4769
- if (sessionName) {
4770
- info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
4771
- }
4772
- info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`;
4773
- info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`;
4774
- info += `${theme.bold("Messages")}\n`;
4775
- info += `${theme.fg("dim", "Total:")} ${stats.totalMessages}\n`;
4776
- info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`;
4777
- info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`;
4778
- info += `${theme.fg("dim", "Tools:")} ${stats.toolCalls} calls, ${stats.toolResults} results\n\n`;
4779
- info += `${theme.bold("Tokens")}\n`;
4780
- // "Input" is the full prompt volume. With cache activity, split it into
4781
- // cached (served from cache) vs uncached (everything else) - the only
4782
- // provider-independent split. Cache writes, where reported, are a detail
4783
- // of the uncached portion.
4784
- const { input, cacheRead, cacheWrite } = stats.tokens;
4785
- const promptTokens = input + cacheRead + cacheWrite;
4786
- info += `${theme.fg("dim", "Input:")} ${promptTokens.toLocaleString()}\n`;
4787
- if (promptTokens > 0 && (cacheRead > 0 || cacheWrite > 0)) {
4788
- const hitRate = theme.fg("dim", `(${((cacheRead / promptTokens) * 100).toFixed(1)}%)`);
4789
- info += ` ${theme.fg("dim", "Cached:")} ${cacheRead.toLocaleString()} ${hitRate}\n`;
4790
- const written = cacheWrite > 0 ? ` ${theme.fg("dim", `(${cacheWrite.toLocaleString()} written to cache)`)}` : "";
4791
- info += ` ${theme.fg("dim", "Uncached:")} ${(input + cacheWrite).toLocaleString()}${written}\n`;
4792
- }
4793
- info += `${theme.fg("dim", "Output:")} ${stats.tokens.output.toLocaleString()}\n`;
4794
- info += `${theme.fg("dim", "Total:")} ${stats.tokens.total.toLocaleString()}\n`;
4795
- if (stats.cost > 0 || cacheWaste.missedTokens > 0) {
4796
- info += `\n${theme.bold("Cost")}\n`;
4797
- info += `${theme.fg("dim", "Total:")} $${stats.cost.toFixed(3)}`;
4798
- if (usageBreakdown.length > 1) {
4799
- for (const entry of usageBreakdown) {
4800
- info += `\n ${theme.fg("dim", `${entry.key}:`)} $${entry.cost.toFixed(3)} ${theme.fg("dim", `(${formatTokens(entry.tokens)} tokens)`)}`;
5834
+ // Snapshot the stats; the text is built on demand so it follows theme changes.
5835
+ const cacheWarmingStatus = this.session.cacheWarmingStatus;
5836
+ const cacheWarmingMode = this.settingsManager.getCacheWarmingMode();
5837
+ const model = this.session.model;
5838
+ const selectedModelKey = `${model?.provider}/${model?.id}`;
5839
+ const renderInfo = () => {
5840
+ let info = `${theme.bold("Session Info")}\n\n`;
5841
+ if (sessionName) {
5842
+ info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
5843
+ }
5844
+ info += `${theme.fg("dim", "File:")} ${stats.sessionFile ?? "In-memory"}\n`;
5845
+ info += `${theme.fg("dim", "ID:")} ${stats.sessionId}\n\n`;
5846
+ info += `${theme.bold("Messages")}\n`;
5847
+ info += `${theme.fg("dim", "Total:")} ${stats.totalMessages}\n`;
5848
+ info += `${theme.fg("dim", "User:")} ${stats.userMessages}\n`;
5849
+ info += `${theme.fg("dim", "Assistant:")} ${stats.assistantMessages}\n`;
5850
+ info += `${theme.fg("dim", "Tools:")} ${stats.toolCalls} calls, ${stats.toolResults} results\n\n`;
5851
+ info += `${theme.bold("Tokens")}\n`;
5852
+ // "Input" is the full prompt volume. With cache activity, split it into
5853
+ // cached (served from cache) vs uncached (everything else) - the only
5854
+ // provider-independent split. Cache writes, where reported, are a detail
5855
+ // of the uncached portion.
5856
+ const { input, cacheRead, cacheWrite } = stats.tokens;
5857
+ const promptTokens = input + cacheRead + cacheWrite;
5858
+ info += `${theme.fg("dim", "Input:")} ${promptTokens.toLocaleString()}\n`;
5859
+ if (promptTokens > 0 && (cacheRead > 0 || cacheWrite > 0)) {
5860
+ const hitRate = theme.fg("dim", `(${((cacheRead / promptTokens) * 100).toFixed(1)}%)`);
5861
+ info += ` ${theme.fg("dim", "Cached:")} ${cacheRead.toLocaleString()} ${hitRate}\n`;
5862
+ const written = cacheWrite > 0 ? ` ${theme.fg("dim", `(${cacheWrite.toLocaleString()} written to cache)`)}` : "";
5863
+ info += ` ${theme.fg("dim", "Uncached:")} ${(input + cacheWrite).toLocaleString()}${written}\n`;
5864
+ }
5865
+ info += `${theme.fg("dim", "Output:")} ${stats.tokens.output.toLocaleString()}\n`;
5866
+ info += `${theme.fg("dim", "Total:")} ${stats.tokens.total.toLocaleString()}\n`;
5867
+ info += `\n${theme.bold("Cache Warming")}\n`;
5868
+ info += `${theme.fg("dim", "Mode:")} ${cacheWarmingMode}\n`;
5869
+ info += `${theme.fg("dim", "Status:")} ${cacheWarmingStatus ? formatCacheWarmingStatus(cacheWarmingStatus) : "Inactive (cache warming unavailable)"}\n`;
5870
+ const decision = cacheWarmingStatus?.decision;
5871
+ if (decision?.economicsAvailable) {
5872
+ info += `${theme.fg("dim", "Cache miss penalty:")} $${decision.missCost.toFixed(3)}\n`;
5873
+ info += `${theme.fg("dim", "Refresh cost:")} $${decision.warmCost.toFixed(3)}\n`;
5874
+ }
5875
+ if (stats.cost > 0 || cacheWaste.missedTokens > 0) {
5876
+ info += `\n${theme.bold("Cost")}\n`;
5877
+ info += `${theme.fg("dim", "Total:")} $${stats.cost.toFixed(3)}`;
5878
+ // A single entry repeats the total, unless it names a model other than the selected one.
5879
+ if (usageBreakdown.length > 1 || usageBreakdown[0]?.key !== selectedModelKey) {
5880
+ for (const entry of usageBreakdown) {
5881
+ info += `\n ${theme.fg("dim", `${entry.key}:`)} $${entry.cost.toFixed(3)} ${theme.fg("dim", `(${formatTokens(entry.tokens)} tokens)`)}`;
5882
+ }
5883
+ }
5884
+ if (cacheWaste.missedTokens > 0) {
5885
+ const missLabel = cacheWaste.missCount === 1 ? "1 miss" : `${cacheWaste.missCount} misses`;
5886
+ const detail = `${cacheWaste.missedTokens.toLocaleString()} tokens, ${missLabel}`;
5887
+ info +=
5888
+ cacheWaste.missedCost >= 0.0001
5889
+ ? `\n${theme.fg("dim", "Cache Re-billed:")} $${cacheWaste.missedCost.toFixed(3)} ${theme.fg("dim", `(${detail})`)}`
5890
+ : `\n${theme.fg("dim", "Cache Re-billed:")} ${detail}`;
4801
5891
  }
4802
5892
  }
4803
- if (cacheWaste.missedTokens > 0) {
4804
- const missLabel = cacheWaste.missCount === 1 ? "1 miss" : `${cacheWaste.missCount} misses`;
4805
- const detail = `${cacheWaste.missedTokens.toLocaleString()} tokens, ${missLabel}`;
4806
- info +=
4807
- cacheWaste.missedCost >= 0.0001
4808
- ? `\n${theme.fg("dim", "Cache Re-billed:")} $${cacheWaste.missedCost.toFixed(3)} ${theme.fg("dim", `(${detail})`)}`
4809
- : `\n${theme.fg("dim", "Cache Re-billed:")} ${detail}`;
4810
- }
4811
- }
5893
+ return info;
5894
+ };
4812
5895
  this.chatContainer.addChild(new Spacer(1));
4813
- this.chatContainer.addChild(new Text(info, 1, 0));
5896
+ this.chatContainer.addChild(new ThemedText(renderInfo, 1, 0));
4814
5897
  this.ui.requestRender();
4815
5898
  }
4816
5899
  handleChangelogCommand() {
@@ -4824,7 +5907,7 @@ export class InteractiveMode {
4824
5907
  : "No changelog entries found.";
4825
5908
  this.chatContainer.addChild(new Spacer(1));
4826
5909
  this.chatContainer.addChild(new DynamicBorder());
4827
- this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "What's New")), 1, 0));
5910
+ this.chatContainer.addChild(new ThemedText(() => theme.bold(theme.fg("accent", "What's New")), 1, 0));
4828
5911
  this.chatContainer.addChild(new Spacer(1));
4829
5912
  this.chatContainer.addChild(new Markdown(changelogMarkdown, 1, 1, this.getMarkdownThemeWithSettings()));
4830
5913
  this.chatContainer.addChild(new DynamicBorder());
@@ -4923,10 +6006,10 @@ ${cycleContextWindow ? `| \`${cycleContextWindow}\` | Cycle context window |\n`
4923
6006
  | \`${expandTools}\` | Toggle tool output expansion |
4924
6007
  | \`${toggleThinking}\` | Toggle thinking block visibility |
4925
6008
  | \`${externalEditor}\` | Edit message in external editor |
4926
- | \`${copyMessage}\` | Copy last assistant message |
6009
+ | \`${copyMessage}\` | Copy selection or last assistant message |
4927
6010
  | \`${followUp}\` | Queue follow-up message |
4928
6011
  | \`${dequeue}\` | Restore queued messages |
4929
- | \`${pasteImage}\` | Paste image or text from clipboard |
6012
+ | \`${pasteImage}\` | Paste files on macOS, images, or text from clipboard |
4930
6013
  | \`/\` | Slash commands |
4931
6014
  | \`!\` | Run bash command |
4932
6015
  | \`!!\` | Run bash command (excluded from context) |
@@ -4948,7 +6031,7 @@ ${cycleContextWindow ? `| \`${cycleContextWindow}\` | Cycle context window |\n`
4948
6031
  }
4949
6032
  this.chatContainer.addChild(new Spacer(1));
4950
6033
  this.chatContainer.addChild(new DynamicBorder());
4951
- this.chatContainer.addChild(new Text(theme.bold(theme.fg("accent", "Keyboard Shortcuts")), 1, 0));
6034
+ this.chatContainer.addChild(new ThemedText(() => theme.bold(theme.fg("accent", "Keyboard Shortcuts")), 1, 0));
4952
6035
  this.chatContainer.addChild(new Spacer(1));
4953
6036
  this.chatContainer.addChild(new Markdown(hotkeys.trim(), 1, 1, this.getMarkdownThemeWithSettings()));
4954
6037
  this.chatContainer.addChild(new DynamicBorder());
@@ -4962,7 +6045,7 @@ ${cycleContextWindow ? `| \`${cycleContextWindow}\` | Cycle context window |\n`
4962
6045
  return;
4963
6046
  }
4964
6047
  this.chatContainer.addChild(new Spacer(1));
4965
- this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1));
6048
+ this.chatContainer.addChild(new ThemedText(() => theme.fg("accent", "✓ New session started"), 1, 1));
4966
6049
  this.ui.requestRender();
4967
6050
  }
4968
6051
  catch (error) {
@@ -4993,7 +6076,7 @@ ${cycleContextWindow ? `| \`${cycleContextWindow}\` | Cycle context window |\n`
4993
6076
  fs.mkdirSync(path.dirname(debugLogPath), { recursive: true });
4994
6077
  fs.writeFileSync(debugLogPath, debugData);
4995
6078
  this.chatContainer.addChild(new Spacer(1));
4996
- this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ Debug log written")}\n${theme.fg("muted", debugLogPath)}`, 1, 1));
6079
+ this.chatContainer.addChild(new ThemedText(() => `${theme.fg("accent", "✓ Debug log written")}\n${theme.fg("muted", debugLogPath)}`, 1, 1));
4997
6080
  this.ui.requestRender();
4998
6081
  }
4999
6082
  handleArminSaysHi() {
@@ -5019,12 +6102,19 @@ ${cycleContextWindow ? `| \`${cycleContextWindow}\` | Cycle context window |\n`
5019
6102
  async handleBashCommand(command, excludeFromContext = false) {
5020
6103
  const extensionRunner = this.session.extensionRunner;
5021
6104
  // Emit user_bash event to let extensions intercept
5022
- const eventResult = await extensionRunner.emitUserBash({
5023
- type: "user_bash",
5024
- command,
5025
- excludeFromContext,
5026
- cwd: this.sessionManager.getCwd(),
5027
- });
6105
+ let eventResult;
6106
+ try {
6107
+ eventResult = await extensionRunner.emitUserBash({
6108
+ type: "user_bash",
6109
+ command,
6110
+ excludeFromContext,
6111
+ cwd: this.sessionManager.getCwd(),
6112
+ });
6113
+ }
6114
+ catch {
6115
+ // The extension runner already reported the error. Do not fall back to local execution.
6116
+ return;
6117
+ }
5028
6118
  // If extension returned a full result, use it directly
5029
6119
  if (eventResult?.result) {
5030
6120
  const result = eventResult.result;
@@ -5090,7 +6180,8 @@ ${cycleContextWindow ? `| \`${cycleContextWindow}\` | Cycle context window |\n`
5090
6180
  // Ignore, will be emitted as an event
5091
6181
  }
5092
6182
  }
5093
- stop() {
6183
+ stop(fullscreenExitOutput = this.settingsManager.getFullscreenExitOutput()) {
6184
+ this.disposeActiveSelector();
5094
6185
  if (this.settingsManager.getShowTerminalProgress()) {
5095
6186
  this.ui.terminal.setProgress(false);
5096
6187
  }
@@ -5103,7 +6194,7 @@ ${cycleContextWindow ? `| \`${cycleContextWindow}\` | Cycle context window |\n`
5103
6194
  this.unsubscribe();
5104
6195
  }
5105
6196
  if (this.isInitialized) {
5106
- this.ui.stop();
6197
+ this.stopInteractiveTui(fullscreenExitOutput);
5107
6198
  this.isInitialized = false;
5108
6199
  }
5109
6200
  this.unregisterSignalHandlers();