@draht/coding-agent 2026.5.12 → 2026.6.11

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 (605) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/bin/draht-tools.cjs +3756 -1
  3. package/dist/bun/cli.d.ts.map +1 -1
  4. package/dist/bun/cli.js +4 -2
  5. package/dist/bun/cli.js.map +1 -1
  6. package/dist/bun/restore-sandbox-env.d.ts +13 -0
  7. package/dist/bun/restore-sandbox-env.d.ts.map +1 -0
  8. package/dist/bun/restore-sandbox-env.js +32 -0
  9. package/dist/bun/restore-sandbox-env.js.map +1 -0
  10. package/dist/cli/args.d.ts +9 -4
  11. package/dist/cli/args.d.ts.map +1 -1
  12. package/dist/cli/args.js +88 -35
  13. package/dist/cli/args.js.map +1 -1
  14. package/dist/cli/config-selector.d.ts +2 -2
  15. package/dist/cli/config-selector.d.ts.map +1 -1
  16. package/dist/cli/config-selector.js +1 -1
  17. package/dist/cli/config-selector.js.map +1 -1
  18. package/dist/cli/file-processor.d.ts.map +1 -1
  19. package/dist/cli/file-processor.js +2 -3
  20. package/dist/cli/file-processor.js.map +1 -1
  21. package/dist/cli/initial-message.d.ts +1 -1
  22. package/dist/cli/initial-message.d.ts.map +1 -1
  23. package/dist/cli/initial-message.js.map +1 -1
  24. package/dist/cli/list-models.d.ts +1 -1
  25. package/dist/cli/list-models.d.ts.map +1 -1
  26. package/dist/cli/list-models.js +7 -1
  27. package/dist/cli/list-models.js.map +1 -1
  28. package/dist/cli/project-trust.d.ts +10 -0
  29. package/dist/cli/project-trust.d.ts.map +1 -0
  30. package/dist/cli/project-trust.js +48 -0
  31. package/dist/cli/project-trust.js.map +1 -0
  32. package/dist/cli/session-picker.d.ts +1 -1
  33. package/dist/cli/session-picker.d.ts.map +1 -1
  34. package/dist/cli/session-picker.js.map +1 -1
  35. package/dist/cli/startup-ui.d.ts +16 -0
  36. package/dist/cli/startup-ui.d.ts.map +1 -0
  37. package/dist/cli/startup-ui.js +112 -0
  38. package/dist/cli/startup-ui.js.map +1 -0
  39. package/dist/cli.d.ts.map +1 -1
  40. package/dist/cli.js +7 -4
  41. package/dist/cli.js.map +1 -1
  42. package/dist/config.d.ts +23 -13
  43. package/dist/config.d.ts.map +1 -1
  44. package/dist/config.js +264 -62
  45. package/dist/config.js.map +1 -1
  46. package/dist/core/agent-session-runtime.d.ts +45 -9
  47. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  48. package/dist/core/agent-session-runtime.js +100 -33
  49. package/dist/core/agent-session-runtime.js.map +1 -1
  50. package/dist/core/agent-session-services.d.ts +6 -4
  51. package/dist/core/agent-session-services.d.ts.map +1 -1
  52. package/dist/core/agent-session-services.js +7 -4
  53. package/dist/core/agent-session-services.js.map +1 -1
  54. package/dist/core/agent-session.d.ts +47 -31
  55. package/dist/core/agent-session.d.ts.map +1 -1
  56. package/dist/core/agent-session.js +470 -443
  57. package/dist/core/agent-session.js.map +1 -1
  58. package/dist/core/auth-guidance.d.ts +5 -0
  59. package/dist/core/auth-guidance.d.ts.map +1 -0
  60. package/dist/core/auth-guidance.js +21 -0
  61. package/dist/core/auth-guidance.js.map +1 -0
  62. package/dist/core/auth-storage.d.ts +10 -1
  63. package/dist/core/auth-storage.d.ts.map +1 -1
  64. package/dist/core/auth-storage.js +27 -6
  65. package/dist/core/auth-storage.js.map +1 -1
  66. package/dist/core/bash-executor.d.ts +1 -15
  67. package/dist/core/bash-executor.d.ts.map +1 -1
  68. package/dist/core/bash-executor.js +10 -24
  69. package/dist/core/bash-executor.js.map +1 -1
  70. package/dist/core/builtins/subagent.d.ts.map +1 -1
  71. package/dist/core/builtins/subagent.js +1 -2
  72. package/dist/core/builtins/subagent.js.map +1 -1
  73. package/dist/core/compaction/branch-summarization.d.ts +6 -4
  74. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  75. package/dist/core/compaction/branch-summarization.js +9 -3
  76. package/dist/core/compaction/branch-summarization.js.map +1 -1
  77. package/dist/core/compaction/compaction.d.ts +5 -5
  78. package/dist/core/compaction/compaction.d.ts.map +1 -1
  79. package/dist/core/compaction/compaction.js +43 -37
  80. package/dist/core/compaction/compaction.js.map +1 -1
  81. package/dist/core/compaction/index.d.ts +3 -3
  82. package/dist/core/compaction/index.d.ts.map +1 -1
  83. package/dist/core/compaction/index.js.map +1 -1
  84. package/dist/core/compaction/utils.d.ts +1 -1
  85. package/dist/core/compaction/utils.d.ts.map +1 -1
  86. package/dist/core/compaction/utils.js +1 -1
  87. package/dist/core/compaction/utils.js.map +1 -1
  88. package/dist/core/exec.d.ts.map +1 -1
  89. package/dist/core/exec.js.map +1 -1
  90. package/dist/core/experimental.d.ts +2 -0
  91. package/dist/core/experimental.d.ts.map +1 -0
  92. package/dist/core/experimental.js +4 -0
  93. package/dist/core/experimental.js.map +1 -0
  94. package/dist/core/export-html/ansi-to-html.d.ts.map +1 -1
  95. package/dist/core/export-html/ansi-to-html.js +1 -1
  96. package/dist/core/export-html/ansi-to-html.js.map +1 -1
  97. package/dist/core/export-html/index.d.ts +1 -1
  98. package/dist/core/export-html/index.d.ts.map +1 -1
  99. package/dist/core/export-html/index.js +13 -11
  100. package/dist/core/export-html/index.js.map +1 -1
  101. package/dist/core/export-html/template.css +69 -4
  102. package/dist/core/export-html/template.js +231 -57
  103. package/dist/core/export-html/tool-renderer.d.ts +0 -6
  104. package/dist/core/export-html/tool-renderer.d.ts.map +1 -1
  105. package/dist/core/export-html/tool-renderer.js +15 -2
  106. package/dist/core/export-html/tool-renderer.js.map +1 -1
  107. package/dist/core/extensions/index.d.ts +8 -8
  108. package/dist/core/extensions/index.d.ts.map +1 -1
  109. package/dist/core/extensions/index.js.map +1 -1
  110. package/dist/core/extensions/loader.d.ts +3 -3
  111. package/dist/core/extensions/loader.d.ts.map +1 -1
  112. package/dist/core/extensions/loader.js +27 -35
  113. package/dist/core/extensions/loader.js.map +1 -1
  114. package/dist/core/extensions/runner.d.ts +30 -12
  115. package/dist/core/extensions/runner.d.ts.map +1 -1
  116. package/dist/core/extensions/runner.js +215 -32
  117. package/dist/core/extensions/runner.js.map +1 -1
  118. package/dist/core/extensions/types.d.ts +163 -35
  119. package/dist/core/extensions/types.d.ts.map +1 -1
  120. package/dist/core/extensions/types.js.map +1 -1
  121. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  122. package/dist/core/extensions/wrapper.js +2 -2
  123. package/dist/core/extensions/wrapper.js.map +1 -1
  124. package/dist/core/footer-data-provider.d.ts +7 -1
  125. package/dist/core/footer-data-provider.d.ts.map +1 -1
  126. package/dist/core/footer-data-provider.js +78 -54
  127. package/dist/core/footer-data-provider.js.map +1 -1
  128. package/dist/core/http-dispatcher.d.ts +21 -0
  129. package/dist/core/http-dispatcher.d.ts.map +1 -0
  130. package/dist/core/http-dispatcher.js +48 -0
  131. package/dist/core/http-dispatcher.js.map +1 -0
  132. package/dist/core/index.d.ts +9 -8
  133. package/dist/core/index.d.ts.map +1 -1
  134. package/dist/core/index.js +2 -1
  135. package/dist/core/index.js.map +1 -1
  136. package/dist/core/keybindings.d.ts +66 -1
  137. package/dist/core/keybindings.d.ts.map +1 -1
  138. package/dist/core/keybindings.js +56 -1
  139. package/dist/core/keybindings.js.map +1 -1
  140. package/dist/core/model-registry.d.ts +22 -4
  141. package/dist/core/model-registry.d.ts.map +1 -1
  142. package/dist/core/model-registry.js +216 -44
  143. package/dist/core/model-registry.js.map +1 -1
  144. package/dist/core/model-resolver.d.ts +2 -1
  145. package/dist/core/model-resolver.d.ts.map +1 -1
  146. package/dist/core/model-resolver.js +48 -21
  147. package/dist/core/model-resolver.js.map +1 -1
  148. package/dist/core/output-guard.d.ts +1 -0
  149. package/dist/core/output-guard.d.ts.map +1 -1
  150. package/dist/core/output-guard.js +52 -22
  151. package/dist/core/output-guard.js.map +1 -1
  152. package/dist/core/package-manager.d.ts +17 -2
  153. package/dist/core/package-manager.d.ts.map +1 -1
  154. package/dist/core/package-manager.js +363 -121
  155. package/dist/core/package-manager.js.map +1 -1
  156. package/dist/core/project-trust.d.ts +15 -0
  157. package/dist/core/project-trust.d.ts.map +1 -0
  158. package/dist/core/project-trust.js +58 -0
  159. package/dist/core/project-trust.js.map +1 -0
  160. package/dist/core/prompt-templates.d.ts +13 -11
  161. package/dist/core/prompt-templates.d.ts.map +1 -1
  162. package/dist/core/prompt-templates.js +67 -76
  163. package/dist/core/prompt-templates.js.map +1 -1
  164. package/dist/core/provider-attribution.d.ts +4 -0
  165. package/dist/core/provider-attribution.d.ts.map +1 -0
  166. package/dist/core/provider-attribution.js +72 -0
  167. package/dist/core/provider-attribution.js.map +1 -0
  168. package/dist/core/provider-display-names.d.ts +2 -0
  169. package/dist/core/provider-display-names.d.ts.map +1 -0
  170. package/dist/core/provider-display-names.js +36 -0
  171. package/dist/core/provider-display-names.js.map +1 -0
  172. package/dist/core/resolve-config-value.d.ts +9 -1
  173. package/dist/core/resolve-config-value.d.ts.map +1 -1
  174. package/dist/core/resolve-config-value.js +134 -11
  175. package/dist/core/resolve-config-value.js.map +1 -1
  176. package/dist/core/resource-loader.d.ts +34 -14
  177. package/dist/core/resource-loader.d.ts.map +1 -1
  178. package/dist/core/resource-loader.js +165 -76
  179. package/dist/core/resource-loader.js.map +1 -1
  180. package/dist/core/sdk.d.ts +26 -10
  181. package/dist/core/sdk.d.ts.map +1 -1
  182. package/dist/core/sdk.js +45 -16
  183. package/dist/core/sdk.js.map +1 -1
  184. package/dist/core/session-manager.d.ts +11 -12
  185. package/dist/core/session-manager.d.ts.map +1 -1
  186. package/dist/core/session-manager.js +245 -132
  187. package/dist/core/session-manager.js.map +1 -1
  188. package/dist/core/settings-manager.d.ts +52 -5
  189. package/dist/core/settings-manager.d.ts.map +1 -1
  190. package/dist/core/settings-manager.js +202 -38
  191. package/dist/core/settings-manager.js.map +1 -1
  192. package/dist/core/skills.d.ts +10 -10
  193. package/dist/core/skills.d.ts.map +1 -1
  194. package/dist/core/skills.js +13 -35
  195. package/dist/core/skills.js.map +1 -1
  196. package/dist/core/slash-commands.d.ts +1 -1
  197. package/dist/core/slash-commands.d.ts.map +1 -1
  198. package/dist/core/slash-commands.js +7 -4
  199. package/dist/core/slash-commands.js.map +1 -1
  200. package/dist/core/source-info.d.ts +1 -1
  201. package/dist/core/source-info.d.ts.map +1 -1
  202. package/dist/core/source-info.js.map +1 -1
  203. package/dist/core/system-prompt.d.ts +4 -4
  204. package/dist/core/system-prompt.d.ts.map +1 -1
  205. package/dist/core/system-prompt.js +14 -10
  206. package/dist/core/system-prompt.js.map +1 -1
  207. package/dist/core/telemetry.d.ts +3 -0
  208. package/dist/core/telemetry.d.ts.map +1 -0
  209. package/dist/core/telemetry.js +9 -0
  210. package/dist/core/telemetry.js.map +1 -0
  211. package/dist/core/tools/bash.d.ts +11 -16
  212. package/dist/core/tools/bash.d.ts.map +1 -1
  213. package/dist/core/tools/bash.js +162 -177
  214. package/dist/core/tools/bash.js.map +1 -1
  215. package/dist/core/tools/edit-diff.d.ts +3 -1
  216. package/dist/core/tools/edit-diff.d.ts.map +1 -1
  217. package/dist/core/tools/edit-diff.js +11 -3
  218. package/dist/core/tools/edit-diff.js.map +1 -1
  219. package/dist/core/tools/edit.d.ts +22 -24
  220. package/dist/core/tools/edit.d.ts.map +1 -1
  221. package/dist/core/tools/edit.js +199 -111
  222. package/dist/core/tools/edit.js.map +1 -1
  223. package/dist/core/tools/file-mutation-queue.d.ts.map +1 -1
  224. package/dist/core/tools/file-mutation-queue.js +27 -12
  225. package/dist/core/tools/file-mutation-queue.js.map +1 -1
  226. package/dist/core/tools/find.d.ts +7 -18
  227. package/dist/core/tools/find.d.ts.map +1 -1
  228. package/dist/core/tools/find.js +134 -95
  229. package/dist/core/tools/find.js.map +1 -1
  230. package/dist/core/tools/grep.d.ts +11 -30
  231. package/dist/core/tools/grep.d.ts.map +1 -1
  232. package/dist/core/tools/grep.js +23 -12
  233. package/dist/core/tools/grep.js.map +1 -1
  234. package/dist/core/tools/index.d.ts +26 -101
  235. package/dist/core/tools/index.d.ts.map +1 -1
  236. package/dist/core/tools/index.js +78 -52
  237. package/dist/core/tools/index.js.map +1 -1
  238. package/dist/core/tools/ls.d.ts +6 -15
  239. package/dist/core/tools/ls.d.ts.map +1 -1
  240. package/dist/core/tools/ls.js +12 -17
  241. package/dist/core/tools/ls.js.map +1 -1
  242. package/dist/core/tools/output-accumulator.d.ts +52 -0
  243. package/dist/core/tools/output-accumulator.d.ts.map +1 -0
  244. package/dist/core/tools/output-accumulator.js +184 -0
  245. package/dist/core/tools/output-accumulator.js.map +1 -0
  246. package/dist/core/tools/path-utils.d.ts +2 -0
  247. package/dist/core/tools/path-utils.d.ts.map +1 -1
  248. package/dist/core/tools/path-utils.js +40 -22
  249. package/dist/core/tools/path-utils.js.map +1 -1
  250. package/dist/core/tools/read.d.ts +7 -18
  251. package/dist/core/tools/read.d.ts.map +1 -1
  252. package/dist/core/tools/read.js +100 -36
  253. package/dist/core/tools/read.js.map +1 -1
  254. package/dist/core/tools/render-utils.d.ts +5 -2
  255. package/dist/core/tools/render-utils.d.ts.map +1 -1
  256. package/dist/core/tools/render-utils.js +18 -2
  257. package/dist/core/tools/render-utils.js.map +1 -1
  258. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  259. package/dist/core/tools/tool-definition-wrapper.js +2 -0
  260. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  261. package/dist/core/tools/truncate.d.ts.map +1 -1
  262. package/dist/core/tools/truncate.js +12 -2
  263. package/dist/core/tools/truncate.js.map +1 -1
  264. package/dist/core/tools/write.d.ts +5 -14
  265. package/dist/core/tools/write.d.ts.map +1 -1
  266. package/dist/core/tools/write.js +27 -46
  267. package/dist/core/tools/write.js.map +1 -1
  268. package/dist/core/trust-manager.d.ts +31 -0
  269. package/dist/core/trust-manager.d.ts.map +1 -0
  270. package/dist/core/trust-manager.js +187 -0
  271. package/dist/core/trust-manager.js.map +1 -0
  272. package/dist/index.d.ts +31 -29
  273. package/dist/index.d.ts.map +1 -1
  274. package/dist/index.js +9 -8
  275. package/dist/index.js.map +1 -1
  276. package/dist/main.d.ts +5 -1
  277. package/dist/main.d.ts.map +1 -1
  278. package/dist/main.js +170 -87
  279. package/dist/main.js.map +1 -1
  280. package/dist/migrations.d.ts +2 -2
  281. package/dist/migrations.d.ts.map +1 -1
  282. package/dist/migrations.js +127 -5
  283. package/dist/migrations.js.map +1 -1
  284. package/dist/modes/index.d.ts +5 -5
  285. package/dist/modes/index.d.ts.map +1 -1
  286. package/dist/modes/index.js.map +1 -1
  287. package/dist/modes/interactive/components/assistant-message.d.ts +2 -0
  288. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  289. package/dist/modes/interactive/components/assistant-message.js +14 -0
  290. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  291. package/dist/modes/interactive/components/bash-execution.d.ts +1 -1
  292. package/dist/modes/interactive/components/bash-execution.d.ts.map +1 -1
  293. package/dist/modes/interactive/components/bash-execution.js +3 -3
  294. package/dist/modes/interactive/components/bash-execution.js.map +1 -1
  295. package/dist/modes/interactive/components/bordered-loader.d.ts.map +1 -1
  296. package/dist/modes/interactive/components/bordered-loader.js +3 -0
  297. package/dist/modes/interactive/components/bordered-loader.js.map +1 -1
  298. package/dist/modes/interactive/components/config-selector.d.ts +4 -4
  299. package/dist/modes/interactive/components/config-selector.d.ts.map +1 -1
  300. package/dist/modes/interactive/components/config-selector.js +38 -11
  301. package/dist/modes/interactive/components/config-selector.js.map +1 -1
  302. package/dist/modes/interactive/components/countdown-timer.d.ts +2 -2
  303. package/dist/modes/interactive/components/countdown-timer.d.ts.map +1 -1
  304. package/dist/modes/interactive/components/countdown-timer.js +2 -2
  305. package/dist/modes/interactive/components/countdown-timer.js.map +1 -1
  306. package/dist/modes/interactive/components/custom-editor.d.ts +1 -1
  307. package/dist/modes/interactive/components/custom-editor.d.ts.map +1 -1
  308. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  309. package/dist/modes/interactive/components/custom-message.d.ts +2 -2
  310. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  311. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  312. package/dist/modes/interactive/components/diff.d.ts.map +1 -1
  313. package/dist/modes/interactive/components/diff.js.map +1 -1
  314. package/dist/modes/interactive/components/earendil-announcement.d.ts.map +1 -1
  315. package/dist/modes/interactive/components/earendil-announcement.js.map +1 -1
  316. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  317. package/dist/modes/interactive/components/extension-editor.js +14 -6
  318. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  319. package/dist/modes/interactive/components/extension-input.d.ts.map +1 -1
  320. package/dist/modes/interactive/components/extension-input.js.map +1 -1
  321. package/dist/modes/interactive/components/extension-selector.d.ts +2 -0
  322. package/dist/modes/interactive/components/extension-selector.d.ts.map +1 -1
  323. package/dist/modes/interactive/components/extension-selector.js +8 -3
  324. package/dist/modes/interactive/components/extension-selector.js.map +1 -1
  325. package/dist/modes/interactive/components/first-time-setup.d.ts +25 -0
  326. package/dist/modes/interactive/components/first-time-setup.d.ts.map +1 -0
  327. package/dist/modes/interactive/components/first-time-setup.js +103 -0
  328. package/dist/modes/interactive/components/first-time-setup.js.map +1 -0
  329. package/dist/modes/interactive/components/footer.d.ts +2 -1
  330. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  331. package/dist/modes/interactive/components/footer.js +23 -7
  332. package/dist/modes/interactive/components/footer.js.map +1 -1
  333. package/dist/modes/interactive/components/index.d.ts +33 -31
  334. package/dist/modes/interactive/components/index.d.ts.map +1 -1
  335. package/dist/modes/interactive/components/index.js +2 -0
  336. package/dist/modes/interactive/components/index.js.map +1 -1
  337. package/dist/modes/interactive/components/keybinding-hints.d.ts +5 -0
  338. package/dist/modes/interactive/components/keybinding-hints.d.ts.map +1 -1
  339. package/dist/modes/interactive/components/keybinding-hints.js +19 -5
  340. package/dist/modes/interactive/components/keybinding-hints.js.map +1 -1
  341. package/dist/modes/interactive/components/login-dialog.d.ts +12 -2
  342. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  343. package/dist/modes/interactive/components/login-dialog.js +46 -11
  344. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  345. package/dist/modes/interactive/components/model-selector.d.ts +2 -2
  346. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  347. package/dist/modes/interactive/components/model-selector.js +8 -5
  348. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  349. package/dist/modes/interactive/components/oauth-selector.d.ts +18 -6
  350. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  351. package/dist/modes/interactive/components/oauth-selector.js +93 -25
  352. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  353. package/dist/modes/interactive/components/scoped-models-selector.d.ts +5 -12
  354. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  355. package/dist/modes/interactive/components/scoped-models-selector.js +45 -30
  356. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  357. package/dist/modes/interactive/components/session-selector.d.ts +2 -1
  358. package/dist/modes/interactive/components/session-selector.d.ts.map +1 -1
  359. package/dist/modes/interactive/components/session-selector.js +20 -7
  360. package/dist/modes/interactive/components/session-selector.js.map +1 -1
  361. package/dist/modes/interactive/components/settings-selector.d.ts +13 -0
  362. package/dist/modes/interactive/components/settings-selector.d.ts.map +1 -1
  363. package/dist/modes/interactive/components/settings-selector.js +113 -4
  364. package/dist/modes/interactive/components/settings-selector.js.map +1 -1
  365. package/dist/modes/interactive/components/skill-invocation-message.d.ts +1 -1
  366. package/dist/modes/interactive/components/skill-invocation-message.d.ts.map +1 -1
  367. package/dist/modes/interactive/components/skill-invocation-message.js.map +1 -1
  368. package/dist/modes/interactive/components/thinking-selector.d.ts.map +1 -1
  369. package/dist/modes/interactive/components/thinking-selector.js +1 -1
  370. package/dist/modes/interactive/components/thinking-selector.js.map +1 -1
  371. package/dist/modes/interactive/components/tool-execution.d.ts +6 -1
  372. package/dist/modes/interactive/components/tool-execution.d.ts.map +1 -1
  373. package/dist/modes/interactive/components/tool-execution.js +57 -14
  374. package/dist/modes/interactive/components/tool-execution.js.map +1 -1
  375. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  376. package/dist/modes/interactive/components/tree-selector.js +18 -9
  377. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  378. package/dist/modes/interactive/components/trust-selector.d.ts +23 -0
  379. package/dist/modes/interactive/components/trust-selector.d.ts.map +1 -0
  380. package/dist/modes/interactive/components/trust-selector.js +91 -0
  381. package/dist/modes/interactive/components/trust-selector.js.map +1 -0
  382. package/dist/modes/interactive/components/user-message-selector.d.ts +2 -2
  383. package/dist/modes/interactive/components/user-message-selector.d.ts.map +1 -1
  384. package/dist/modes/interactive/components/user-message-selector.js +8 -7
  385. package/dist/modes/interactive/components/user-message-selector.js.map +1 -1
  386. package/dist/modes/interactive/components/user-message.d.ts +1 -0
  387. package/dist/modes/interactive/components/user-message.d.ts.map +1 -1
  388. package/dist/modes/interactive/components/user-message.js +8 -7
  389. package/dist/modes/interactive/components/user-message.js.map +1 -1
  390. package/dist/modes/interactive/interactive-mode.d.ts +68 -13
  391. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  392. package/dist/modes/interactive/interactive-mode.js +1100 -319
  393. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  394. package/dist/modes/interactive/theme/dark.json +5 -4
  395. package/dist/modes/interactive/theme/light.json +5 -4
  396. package/dist/modes/interactive/theme/theme.d.ts +22 -3
  397. package/dist/modes/interactive/theme/theme.d.ts.map +1 -1
  398. package/dist/modes/interactive/theme/theme.js +160 -105
  399. package/dist/modes/interactive/theme/theme.js.map +1 -1
  400. package/dist/modes/print-mode.d.ts.map +1 -1
  401. package/dist/modes/print-mode.js +40 -20
  402. package/dist/modes/print-mode.js.map +1 -1
  403. package/dist/modes/rpc/rpc-client.d.ts +11 -1
  404. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  405. package/dist/modes/rpc/rpc-client.js +73 -8
  406. package/dist/modes/rpc/rpc-client.js.map +1 -1
  407. package/dist/modes/rpc/rpc-mode.d.ts +2 -2
  408. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  409. package/dist/modes/rpc/rpc-mode.js +96 -30
  410. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  411. package/dist/modes/rpc/rpc-types.d.ts +16 -4
  412. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  413. package/dist/modes/rpc/rpc-types.js.map +1 -1
  414. package/dist/package-manager-cli.d.ts +6 -2
  415. package/dist/package-manager-cli.d.ts.map +1 -1
  416. package/dist/package-manager-cli.js +396 -21
  417. package/dist/package-manager-cli.js.map +1 -1
  418. package/dist/prompts/commands/map-codebase.md +14 -0
  419. package/dist/utils/ansi.d.ts +2 -0
  420. package/dist/utils/ansi.d.ts.map +1 -0
  421. package/dist/utils/ansi.js +52 -0
  422. package/dist/utils/ansi.js.map +1 -0
  423. package/dist/utils/changelog.d.ts +2 -1
  424. package/dist/utils/changelog.d.ts.map +1 -1
  425. package/dist/utils/changelog.js +78 -0
  426. package/dist/utils/changelog.js.map +1 -1
  427. package/dist/utils/child-process.d.ts +5 -1
  428. package/dist/utils/child-process.d.ts.map +1 -1
  429. package/dist/utils/child-process.js +10 -0
  430. package/dist/utils/child-process.js.map +1 -1
  431. package/dist/utils/clipboard-image.d.ts.map +1 -1
  432. package/dist/utils/clipboard-image.js +2 -2
  433. package/dist/utils/clipboard-image.js.map +1 -1
  434. package/dist/utils/clipboard-native.d.ts +3 -1
  435. package/dist/utils/clipboard-native.d.ts.map +1 -1
  436. package/dist/utils/clipboard-native.js +14 -8
  437. package/dist/utils/clipboard-native.js.map +1 -1
  438. package/dist/utils/clipboard.d.ts.map +1 -1
  439. package/dist/utils/clipboard.js +84 -45
  440. package/dist/utils/clipboard.js.map +1 -1
  441. package/dist/utils/deprecation.d.ts +4 -0
  442. package/dist/utils/deprecation.d.ts.map +1 -0
  443. package/dist/utils/deprecation.js +13 -0
  444. package/dist/utils/deprecation.js.map +1 -0
  445. package/dist/utils/exif-orientation.d.ts +1 -1
  446. package/dist/utils/exif-orientation.d.ts.map +1 -1
  447. package/dist/utils/exif-orientation.js.map +1 -1
  448. package/dist/utils/fs-watch.d.ts +5 -0
  449. package/dist/utils/fs-watch.d.ts.map +1 -0
  450. package/dist/utils/fs-watch.js +25 -0
  451. package/dist/utils/fs-watch.js.map +1 -0
  452. package/dist/utils/git.d.ts.map +1 -1
  453. package/dist/utils/git.js +54 -22
  454. package/dist/utils/git.js.map +1 -1
  455. package/dist/utils/html.d.ts +7 -0
  456. package/dist/utils/html.d.ts.map +1 -0
  457. package/dist/utils/html.js +40 -0
  458. package/dist/utils/html.js.map +1 -0
  459. package/dist/utils/image-convert.d.ts.map +1 -1
  460. package/dist/utils/image-convert.js.map +1 -1
  461. package/dist/utils/image-resize-core.d.ts +30 -0
  462. package/dist/utils/image-resize-core.d.ts.map +1 -0
  463. package/dist/utils/image-resize-core.js +124 -0
  464. package/dist/utils/image-resize-core.js.map +1 -0
  465. package/dist/utils/image-resize-worker.d.ts +2 -0
  466. package/dist/utils/image-resize-worker.d.ts.map +1 -0
  467. package/dist/utils/image-resize-worker.js +31 -0
  468. package/dist/utils/image-resize-worker.js.map +1 -0
  469. package/dist/utils/image-resize.d.ts +7 -27
  470. package/dist/utils/image-resize.d.ts.map +1 -1
  471. package/dist/utils/image-resize.js +75 -115
  472. package/dist/utils/image-resize.js.map +1 -1
  473. package/dist/utils/json.d.ts +3 -0
  474. package/dist/utils/json.d.ts.map +1 -0
  475. package/dist/utils/json.js +7 -0
  476. package/dist/utils/json.js.map +1 -0
  477. package/dist/utils/mime.d.ts +1 -0
  478. package/dist/utils/mime.d.ts.map +1 -1
  479. package/dist/utils/mime.js +59 -16
  480. package/dist/utils/mime.js.map +1 -1
  481. package/dist/utils/open-browser.d.ts +9 -0
  482. package/dist/utils/open-browser.d.ts.map +1 -0
  483. package/dist/utils/open-browser.js +22 -0
  484. package/dist/utils/open-browser.js.map +1 -0
  485. package/dist/utils/paths.d.ts +25 -1
  486. package/dist/utils/paths.d.ts.map +1 -1
  487. package/dist/utils/paths.js +75 -2
  488. package/dist/utils/paths.js.map +1 -1
  489. package/dist/utils/pi-user-agent.d.ts +2 -0
  490. package/dist/utils/pi-user-agent.d.ts.map +1 -0
  491. package/dist/utils/pi-user-agent.js +5 -0
  492. package/dist/utils/pi-user-agent.js.map +1 -0
  493. package/dist/utils/shell.d.ts +10 -6
  494. package/dist/utils/shell.d.ts.map +1 -1
  495. package/dist/utils/shell.js +35 -26
  496. package/dist/utils/shell.js.map +1 -1
  497. package/dist/utils/syntax-highlight.d.ts +12 -0
  498. package/dist/utils/syntax-highlight.d.ts.map +1 -0
  499. package/dist/utils/syntax-highlight.js +118 -0
  500. package/dist/utils/syntax-highlight.js.map +1 -0
  501. package/dist/utils/tools-manager.d.ts.map +1 -1
  502. package/dist/utils/tools-manager.js +86 -10
  503. package/dist/utils/tools-manager.js.map +1 -1
  504. package/dist/utils/version-check.d.ts +15 -0
  505. package/dist/utils/version-check.d.ts.map +1 -0
  506. package/dist/utils/version-check.js +82 -0
  507. package/dist/utils/version-check.js.map +1 -0
  508. package/dist/utils/windows-self-update.d.ts +3 -0
  509. package/dist/utils/windows-self-update.d.ts.map +1 -0
  510. package/dist/utils/windows-self-update.js +77 -0
  511. package/dist/utils/windows-self-update.js.map +1 -0
  512. package/docs/compaction.md +12 -12
  513. package/docs/containerization.md +111 -0
  514. package/docs/custom-provider.md +187 -47
  515. package/docs/development.md +5 -5
  516. package/docs/docs.json +156 -0
  517. package/docs/extensions.md +465 -71
  518. package/docs/index.md +82 -0
  519. package/docs/json.md +4 -4
  520. package/docs/keybindings.md +23 -1
  521. package/docs/models.md +119 -17
  522. package/docs/packages.md +17 -9
  523. package/docs/prompt-templates.md +30 -2
  524. package/docs/providers.md +83 -22
  525. package/docs/quickstart.md +165 -0
  526. package/docs/rpc.md +41 -10
  527. package/docs/sdk.md +68 -50
  528. package/docs/security.md +55 -0
  529. package/docs/{session.md → session-format.md} +11 -11
  530. package/docs/sessions.md +145 -0
  531. package/docs/settings.md +61 -11
  532. package/docs/skills.md +16 -17
  533. package/docs/terminal-setup.md +44 -2
  534. package/docs/termux.md +4 -4
  535. package/docs/themes.md +3 -3
  536. package/docs/tmux.md +4 -2
  537. package/docs/tui.md +44 -4
  538. package/docs/usage.md +305 -0
  539. package/examples/extensions/border-status-editor.ts +145 -0
  540. package/examples/extensions/built-in-tool-renderer.ts +3 -0
  541. package/examples/extensions/custom-header.ts +1 -1
  542. package/examples/extensions/custom-provider-anthropic/index.ts +1 -1
  543. package/examples/extensions/custom-provider-anthropic/package-lock.json +2 -2
  544. package/examples/extensions/custom-provider-anthropic/package.json +2 -2
  545. package/examples/extensions/custom-provider-gitlab-duo/index.ts +55 -4
  546. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  547. package/examples/extensions/custom-provider-gitlab-duo/test.ts +1 -1
  548. package/examples/extensions/doom-overlay/doom-component.ts +2 -2
  549. package/examples/extensions/doom-overlay/index.ts +1 -1
  550. package/examples/extensions/dynamic-resources/dynamic.json +1 -1
  551. package/examples/extensions/dynamic-tools.ts +2 -2
  552. package/examples/extensions/git-merge-and-resolve.ts +115 -0
  553. package/examples/extensions/github-issue-autocomplete.ts +185 -0
  554. package/examples/extensions/gondolin/index.ts +531 -0
  555. package/examples/extensions/gondolin/package-lock.json +185 -0
  556. package/examples/extensions/gondolin/package.json +19 -0
  557. package/examples/extensions/handoff.ts +50 -12
  558. package/examples/extensions/input-transform-streaming.ts +39 -0
  559. package/examples/extensions/interactive-shell.ts +1 -1
  560. package/examples/extensions/notify.ts +2 -9
  561. package/examples/extensions/overlay-qa-tests.ts +240 -138
  562. package/examples/extensions/overlay-test.ts +7 -4
  563. package/examples/extensions/plan-mode/utils.ts +1 -1
  564. package/examples/extensions/preset.ts +36 -3
  565. package/examples/extensions/project-trust.ts +64 -0
  566. package/examples/extensions/prompt-customizer.ts +97 -0
  567. package/examples/extensions/provider-payload.ts +4 -0
  568. package/examples/extensions/qna.ts +1 -1
  569. package/examples/extensions/question.ts +2 -2
  570. package/examples/extensions/questionnaire.ts +2 -2
  571. package/examples/extensions/reload-runtime.ts +1 -1
  572. package/examples/extensions/sandbox/index.ts +4 -4
  573. package/examples/extensions/sandbox/package-lock.json +5 -5
  574. package/examples/extensions/sandbox/package.json +2 -2
  575. package/examples/extensions/shutdown-command.ts +1 -1
  576. package/examples/extensions/snake.ts +1 -1
  577. package/examples/extensions/space-invaders.ts +1 -1
  578. package/examples/extensions/structured-output.ts +65 -0
  579. package/examples/extensions/subagent/index.ts +51 -28
  580. package/examples/extensions/summarize.ts +1 -1
  581. package/examples/extensions/tic-tac-toe.ts +1008 -0
  582. package/examples/extensions/titlebar-spinner.ts +2 -2
  583. package/examples/extensions/todo.ts +2 -2
  584. package/examples/extensions/tool-override.ts +1 -1
  585. package/examples/extensions/tools.ts +5 -0
  586. package/examples/extensions/truncated-tool.ts +1 -1
  587. package/examples/extensions/with-deps/index.ts +1 -1
  588. package/examples/extensions/with-deps/package-lock.json +2 -2
  589. package/examples/extensions/with-deps/package.json +3 -3
  590. package/examples/extensions/working-indicator.ts +123 -0
  591. package/examples/extensions/working-message-test.ts +25 -0
  592. package/examples/sdk/01-minimal.ts +14 -10
  593. package/examples/sdk/02-custom-model.ts +12 -8
  594. package/examples/sdk/03-custom-prompt.ts +32 -17
  595. package/examples/sdk/04-skills.ts +5 -2
  596. package/examples/sdk/05-tools.ts +23 -31
  597. package/examples/sdk/06-extensions.ts +14 -8
  598. package/examples/sdk/07-context-files.ts +5 -3
  599. package/examples/sdk/08-prompt-templates.ts +5 -2
  600. package/examples/sdk/09-api-keys-and-oauth.ts +8 -4
  601. package/examples/sdk/10-settings.ts +8 -6
  602. package/examples/sdk/11-sessions.ts +4 -0
  603. package/examples/sdk/12-full-control.ts +13 -17
  604. package/package.json +13 -6
  605. package/prompts/commands/map-codebase.md +14 -0
@@ -6,29 +6,41 @@ 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, Loader, Markdown, matchesKey, ProcessTerminal, Spacer, setKeybindings, Text, TruncatedText, TUI, visibleWidth, } from "@draht/tui";
9
+ import { getProviders, } from "@draht/ai";
10
+ import { CombinedAutocompleteProvider, Container, fuzzyFilter, getCapabilities, hyperlink, Loader, Markdown, matchesKey, ProcessTerminal, Spacer, setKeybindings, Text, TruncatedText, TUI, visibleWidth, } from "@draht/tui";
11
+ import chalk from "chalk";
10
12
  import { spawn, spawnSync } from "child_process";
11
- import { APP_NAME, getAgentDir, getAuthPath, getDebugLogPath, getShareViewerUrl, getUpdateInstruction, VERSION, } from "../../config.js";
13
+ import { APP_NAME, APP_TITLE, DISPLAY_VERSION, getAgentDir, getAuthPath, getDebugLogPath, getDocsPath, getShareViewerUrl, VERSION, } from "../../config.js";
12
14
  import { parseSkillBlock } from "../../core/agent-session.js";
15
+ import { SessionImportFileNotFoundError } from "../../core/agent-session-runtime.js";
13
16
  import { FooterDataProvider } from "../../core/footer-data-provider.js";
17
+ import { configureHttpDispatcher, formatHttpIdleTimeoutMs } from "../../core/http-dispatcher.js";
14
18
  import { KeybindingsManager } from "../../core/keybindings.js";
15
19
  import { createCompactionSummaryMessage } from "../../core/messages.js";
16
- import { findExactModelReferenceMatch, resolveModelScope } from "../../core/model-resolver.js";
20
+ import { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope } from "../../core/model-resolver.js";
17
21
  import { DefaultPackageManager } from "../../core/package-manager.js";
22
+ import { BUILT_IN_PROVIDER_DISPLAY_NAMES } from "../../core/provider-display-names.js";
18
23
  import { formatMissingSessionCwdPrompt, MissingSessionCwdError } from "../../core/session-cwd.js";
19
24
  import { SessionManager } from "../../core/session-manager.js";
20
25
  import { BUILTIN_SLASH_COMMANDS } from "../../core/slash-commands.js";
21
- import { getChangelogPath, getNewEntries, parseChangelog } from "../../utils/changelog.js";
26
+ import { isInstallTelemetryEnabled } from "../../core/telemetry.js";
27
+ import { hasProjectConfigDir, hasProjectTrustInputs, ProjectTrustStore } from "../../core/trust-manager.js";
28
+ import { getChangelogPath, getNewEntries, normalizeChangelogLinks, parseChangelog } from "../../utils/changelog.js";
22
29
  import { copyToClipboard } from "../../utils/clipboard.js";
23
30
  import { extensionForImageMimeType, readClipboardImage } from "../../utils/clipboard-image.js";
24
31
  import { parseGitUrl } from "../../utils/git.js";
32
+ import { getCwdRelativePath } from "../../utils/paths.js";
33
+ import { getPiUserAgent } from "../../utils/pi-user-agent.js";
34
+ import { killTrackedDetachedChildren } from "../../utils/shell.js";
25
35
  import { ensureTool } from "../../utils/tools-manager.js";
36
+ import { checkForNewPiVersion } from "../../utils/version-check.js";
26
37
  import { ArminComponent } from "./components/armin.js";
27
38
  import { AssistantMessageComponent } from "./components/assistant-message.js";
28
39
  import { BashExecutionComponent } from "./components/bash-execution.js";
29
40
  import { BorderedLoader } from "./components/bordered-loader.js";
30
41
  import { BranchSummaryMessageComponent } from "./components/branch-summary-message.js";
31
42
  import { CompactionSummaryMessageComponent } from "./components/compaction-summary-message.js";
43
+ import { CountdownTimer } from "./components/countdown-timer.js";
32
44
  import { CustomEditor } from "./components/custom-editor.js";
33
45
  import { CustomMessageComponent } from "./components/custom-message.js";
34
46
  import { DaxnutsComponent } from "./components/daxnuts.js";
@@ -38,7 +50,7 @@ import { ExtensionEditorComponent } from "./components/extension-editor.js";
38
50
  import { ExtensionInputComponent } from "./components/extension-input.js";
39
51
  import { ExtensionSelectorComponent } from "./components/extension-selector.js";
40
52
  import { FooterComponent } from "./components/footer.js";
41
- import { keyHint, keyText, rawKeyHint } from "./components/keybinding-hints.js";
53
+ import { formatKeyText, keyDisplayText, keyHint, keyText, rawKeyHint } from "./components/keybinding-hints.js";
42
54
  import { LoginDialogComponent } from "./components/login-dialog.js";
43
55
  import { ModelSelectorComponent } from "./components/model-selector.js";
44
56
  import { OAuthSelectorComponent } from "./components/oauth-selector.js";
@@ -48,18 +60,76 @@ import { SettingsSelectorComponent } from "./components/settings-selector.js";
48
60
  import { SkillInvocationMessageComponent } from "./components/skill-invocation-message.js";
49
61
  import { ToolExecutionComponent } from "./components/tool-execution.js";
50
62
  import { TreeSelectorComponent } from "./components/tree-selector.js";
63
+ import { TrustSelectorComponent } from "./components/trust-selector.js";
51
64
  import { UserMessageComponent } from "./components/user-message.js";
52
65
  import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
53
66
  import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getThemeByName, initTheme, onThemeChange, setRegisteredThemes, setTheme, setThemeInstance, stopThemeWatcher, Theme, theme, } from "./theme/theme.js";
54
67
  function isExpandable(obj) {
55
68
  return typeof obj === "object" && obj !== null && "setExpanded" in obj && typeof obj.setExpanded === "function";
56
69
  }
57
- const ANTHROPIC_SUBSCRIPTION_AUTH_WARNING = "Anthropic subscription auth is active. Third-party usage now draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage.";
70
+ class ExpandableText extends Text {
71
+ getCollapsedText;
72
+ getExpandedText;
73
+ constructor(getCollapsedText, getExpandedText, expanded = false, paddingX = 0, paddingY = 0) {
74
+ super(expanded ? getExpandedText() : getCollapsedText(), paddingX, paddingY);
75
+ this.getCollapsedText = getCollapsedText;
76
+ this.getExpandedText = getExpandedText;
77
+ }
78
+ setExpanded(expanded) {
79
+ this.setText(expanded ? this.getExpandedText() : this.getCollapsedText());
80
+ }
81
+ }
82
+ const DEAD_TERMINAL_ERROR_CODES = new Set(["EIO", "EPIPE", "ENOTCONN"]);
83
+ function isDeadTerminalError(error) {
84
+ if (!error || typeof error !== "object" || !("code" in error)) {
85
+ return false;
86
+ }
87
+ const code = error.code;
88
+ return code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);
89
+ }
90
+ 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.";
58
91
  function isAnthropicSubscriptionAuthKey(apiKey) {
59
92
  return typeof apiKey === "string" && apiKey.startsWith("sk-ant-oat");
60
93
  }
94
+ function isUnknownModel(model) {
95
+ return !!model && model.provider === "unknown" && model.id === "unknown" && model.api === "unknown";
96
+ }
97
+ function quoteIfNeeded(value) {
98
+ if (value.length > 0 && !/[^a-zA-Z0-9_\-./~:@]/.test(value)) {
99
+ return value;
100
+ }
101
+ return `'${value.replace(/'/g, `'\\''`)}'`;
102
+ }
103
+ export function formatResumeCommand(sessionManager) {
104
+ if (!process.stdout.isTTY)
105
+ return undefined;
106
+ if (!sessionManager.isPersisted())
107
+ return undefined;
108
+ const sessionFile = sessionManager.getSessionFile();
109
+ if (!sessionFile || !fs.existsSync(sessionFile))
110
+ return undefined;
111
+ const args = [APP_NAME];
112
+ if (!sessionManager.usesDefaultSessionDir()) {
113
+ args.push("--session-dir", quoteIfNeeded(sessionManager.getSessionDir()));
114
+ }
115
+ args.push("--session", sessionManager.getSessionId());
116
+ return args.join(" ");
117
+ }
118
+ function hasDefaultModelProvider(providerId) {
119
+ return providerId in defaultModelPerProvider;
120
+ }
121
+ const BEDROCK_PROVIDER_ID = "amazon-bedrock";
122
+ const BUILT_IN_MODEL_PROVIDERS = new Set(getProviders());
123
+ export function isApiKeyLoginProvider(providerId, oauthProviderIds, builtInProviderIds = BUILT_IN_MODEL_PROVIDERS) {
124
+ if (BUILT_IN_PROVIDER_DISPLAY_NAMES[providerId]) {
125
+ return true;
126
+ }
127
+ if (builtInProviderIds.has(providerId)) {
128
+ return false;
129
+ }
130
+ return !oauthProviderIds.has(providerId);
131
+ }
61
132
  export class InteractiveMode {
62
- options;
63
133
  runtimeHost;
64
134
  ui;
65
135
  chatContainer;
@@ -67,7 +137,9 @@ export class InteractiveMode {
67
137
  statusContainer;
68
138
  defaultEditor;
69
139
  editor;
140
+ editorComponentFactory;
70
141
  autocompleteProvider;
142
+ autocompleteProviderWrappers = [];
71
143
  fdPath;
72
144
  editorContainer;
73
145
  footer;
@@ -77,8 +149,11 @@ export class InteractiveMode {
77
149
  version;
78
150
  isInitialized = false;
79
151
  onInputCallback;
152
+ pendingUserInputs = [];
80
153
  loadingAnimation = undefined;
81
- pendingWorkingMessage = undefined;
154
+ workingMessage = undefined;
155
+ workingVisible = true;
156
+ workingIndicatorOptions = undefined;
82
157
  defaultWorkingMessage = "Working...";
83
158
  defaultHiddenThinkingLabel = "Thinking...";
84
159
  hiddenThinkingLabel = this.defaultHiddenThinkingLabel;
@@ -103,6 +178,7 @@ export class InteractiveMode {
103
178
  skillCommands = new Map();
104
179
  // Agent subscription unsubscribe function
105
180
  unsubscribe;
181
+ signalCleanupHandlers = [];
106
182
  // Track if editor is in bash mode (text starts with !)
107
183
  isBashMode = false;
108
184
  // Track current bash execution component
@@ -114,6 +190,7 @@ export class InteractiveMode {
114
190
  autoCompactionEscapeHandler;
115
191
  // Auto-retry state
116
192
  retryLoader = undefined;
193
+ retryCountdown = undefined;
117
194
  retryEscapeHandler;
118
195
  // Messages queued while compaction is running
119
196
  compactionQueuedMessages = [];
@@ -137,6 +214,8 @@ export class InteractiveMode {
137
214
  builtInHeader = undefined;
138
215
  // Custom header from extension (undefined = use built-in header)
139
216
  customHeader = undefined;
217
+ options;
218
+ autoTrustOnReloadCwd;
140
219
  // Convenience accessors
141
220
  get session() {
142
221
  return this.runtimeHost.session;
@@ -151,8 +230,15 @@ export class InteractiveMode {
151
230
  return this.session.settingsManager;
152
231
  }
153
232
  constructor(runtimeHost, options = {}) {
154
- this.options = options;
155
233
  this.runtimeHost = runtimeHost;
234
+ this.options = options;
235
+ this.autoTrustOnReloadCwd = options.autoTrustOnReloadCwd;
236
+ this.runtimeHost.setBeforeSessionInvalidate(() => {
237
+ this.resetExtensionUI();
238
+ });
239
+ this.runtimeHost.setRebindSession(async () => {
240
+ await this.rebindCurrentSession();
241
+ });
156
242
  this.version = VERSION;
157
243
  this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor());
158
244
  this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
@@ -209,9 +295,6 @@ export class InteractiveMode {
209
295
  return description ? `[${sourceTag}] ${description}` : `[${sourceTag}]`;
210
296
  }
211
297
  getBuiltInCommandConflictDiagnostics(extensionRunner) {
212
- if (!extensionRunner) {
213
- return [];
214
- }
215
298
  const builtinNames = new Set(BUILTIN_SLASH_COMMANDS.map((command) => command.name));
216
299
  return extensionRunner
217
300
  .getRegisteredCommands()
@@ -224,7 +307,7 @@ export class InteractiveMode {
224
307
  path: command.sourceInfo.path,
225
308
  }));
226
309
  }
227
- setupAutocomplete(fdPath) {
310
+ createBaseAutocompleteProvider() {
228
311
  // Define commands for autocomplete
229
312
  const slashCommands = BUILTIN_SLASH_COMMANDS.map((command) => ({
230
313
  name: command.name,
@@ -260,10 +343,14 @@ export class InteractiveMode {
260
343
  const templateCommands = this.session.promptTemplates.map((cmd) => ({
261
344
  name: cmd.name,
262
345
  description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),
346
+ ...(cmd.argumentHint && { argumentHint: cmd.argumentHint }),
263
347
  }));
264
348
  // Convert extension commands to SlashCommand format
265
349
  const builtinCommandNames = new Set(slashCommands.map((c) => c.name));
266
- const extensionCommands = (this.session.extensionRunner?.getRegisteredCommands().filter((cmd) => !builtinCommandNames.has(cmd.name)) ?? []).map((cmd) => ({
350
+ const extensionCommands = this.session.extensionRunner
351
+ .getRegisteredCommands()
352
+ .filter((cmd) => !builtinCommandNames.has(cmd.name))
353
+ .map((cmd) => ({
267
354
  name: cmd.invocationName,
268
355
  description: this.prefixAutocompleteDescription(cmd.description, cmd.sourceInfo),
269
356
  getArgumentCompletions: cmd.getArgumentCompletions,
@@ -281,11 +368,22 @@ export class InteractiveMode {
281
368
  });
282
369
  }
283
370
  }
284
- // Setup autocomplete
285
- this.autocompleteProvider = new CombinedAutocompleteProvider([...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList], this.sessionManager.getCwd(), fdPath);
286
- this.defaultEditor.setAutocompleteProvider(this.autocompleteProvider);
371
+ return new CombinedAutocompleteProvider([...slashCommands, ...templateCommands, ...extensionCommands, ...skillCommandList], this.sessionManager.getCwd(), this.fdPath);
372
+ }
373
+ setupAutocompleteProvider() {
374
+ let provider = this.createBaseAutocompleteProvider();
375
+ const triggerCharacters = [];
376
+ for (const wrapProvider of this.autocompleteProviderWrappers) {
377
+ provider = wrapProvider(provider);
378
+ triggerCharacters.push(...(provider.triggerCharacters ?? []));
379
+ }
380
+ if (triggerCharacters.length > 0) {
381
+ provider.triggerCharacters = [...new Set(triggerCharacters)];
382
+ }
383
+ this.autocompleteProvider = provider;
384
+ this.defaultEditor.setAutocompleteProvider(provider);
287
385
  if (this.editor !== this.defaultEditor) {
288
- this.editor.setAutocompleteProvider?.(this.autocompleteProvider);
386
+ this.editor.setAutocompleteProvider?.(provider);
289
387
  }
290
388
  }
291
389
  showStartupNoticesIfNeeded() {
@@ -317,12 +415,26 @@ export class InteractiveMode {
317
415
  async init() {
318
416
  if (this.isInitialized)
319
417
  return;
418
+ this.registerSignalHandlers();
320
419
  // Load changelog (only show new entries, skip for resumed sessions)
321
420
  this.changelogMarkdown = this.getChangelogForDisplay();
322
421
  // Ensure fd and rg are available (downloads if missing, adds to PATH via getBinDir)
323
422
  // Both are needed: fd for autocomplete, rg for grep tool and bash commands
324
423
  const [fdPath] = await Promise.all([ensureTool("fd"), ensureTool("rg")]);
325
424
  this.fdPath = fdPath;
425
+ if (this.session.scopedModels.length > 0 && (this.options.verbose || !this.settingsManager.getQuietStartup())) {
426
+ const modelList = this.session.scopedModels
427
+ .map((sm) => {
428
+ const thinkingStr = sm.thinkingLevel ? `:${sm.thinkingLevel}` : "";
429
+ return `${sm.model.id}${thinkingStr}`;
430
+ })
431
+ .join(", ");
432
+ const cycleKeys = this.keybindings.getKeys("app.model.cycleForward");
433
+ const cycleHint = cycleKeys.length > 0
434
+ ? theme.fg("muted", ` (${formatKeyText(cycleKeys.join("/"), { capitalize: true })} to cycle)`)
435
+ : "";
436
+ console.log(theme.fg("dim", `Model scope: ${modelList}${cycleHint}`));
437
+ }
326
438
  // Add header container as first child
327
439
  this.ui.addChild(this.headerContainer);
328
440
  // Add header with keybindings from config (unless silenced)
@@ -338,11 +450,11 @@ export class InteractiveMode {
338
450
  ]
339
451
  .map((line) => theme.fg("border", line))
340
452
  .join("\n");
341
- const wordmark = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${this.version} · /dʁaːt/`);
453
+ const wordmark = theme.bold(theme.fg("accent", APP_NAME)) + theme.fg("dim", ` v${DISPLAY_VERSION} · /dʁaːt/`);
342
454
  const logo = `${asciiArt}\n${wordmark}`;
343
455
  // Build startup instructions using keybinding hint helpers
344
456
  const hint = (keybinding, description) => keyHint(keybinding, description);
345
- const instructions = [
457
+ const expandedInstructions = [
346
458
  hint("app.interrupt", "to interrupt"),
347
459
  hint("app.clear", "to clear"),
348
460
  rawKeyHint(`${keyText("app.clear")} twice`, "to exit"),
@@ -363,8 +475,16 @@ export class InteractiveMode {
363
475
  hint("app.clipboard.pasteImage", "to paste image"),
364
476
  rawKeyHint("drop files", "to attach"),
365
477
  ].join("\n");
366
- const onboarding = theme.fg("dim", `Draht can explain its own features and look up its docs. Ask it how to use or extend draht.`);
367
- this.builtInHeader = new Text(`${logo}\n${instructions}\n\n${onboarding}`, 1, 0);
478
+ const compactInstructions = [
479
+ hint("app.interrupt", "interrupt"),
480
+ rawKeyHint(`${keyText("app.clear")}/${keyText("app.exit")}`, "clear/exit"),
481
+ rawKeyHint("/", "commands"),
482
+ rawKeyHint("!", "bash"),
483
+ hint("app.tools.expand", "more"),
484
+ ].join(theme.fg("muted", " · "));
485
+ const compactOnboarding = theme.fg("dim", `Press ${keyText("app.tools.expand")} to show full startup help and loaded resources.`);
486
+ 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}.`);
487
+ this.builtInHeader = new ExpandableText(() => `${logo}\n${compactInstructions}\n${compactOnboarding}\n\n${onboarding}`, () => `${logo}\n${expandedInstructions}\n\n${onboarding}`, this.getStartupExpansionState(), 1, 0);
368
488
  // Setup UI layout
369
489
  this.headerContainer.addChild(new Spacer(1));
370
490
  this.headerContainer.addChild(this.builtInHeader);
@@ -390,13 +510,9 @@ export class InteractiveMode {
390
510
  this.ui.start();
391
511
  this.isInitialized = true;
392
512
  // Initialize extensions first so resources are shown before messages
393
- await this.bindCurrentSessionExtensions();
513
+ await this.rebindCurrentSession();
394
514
  // Render initial messages AFTER showing loaded resources
395
515
  this.renderInitialMessages();
396
- // Set terminal title
397
- this.updateTerminalTitle();
398
- // Subscribe to agent events
399
- this.subscribeToAgent();
400
516
  // Set up theme file watcher
401
517
  onThemeChange(() => {
402
518
  this.ui.invalidate();
@@ -417,10 +533,10 @@ export class InteractiveMode {
417
533
  const cwdBasename = path.basename(this.sessionManager.getCwd());
418
534
  const sessionName = this.sessionManager.getSessionName();
419
535
  if (sessionName) {
420
- this.ui.terminal.setTitle(`draht - ${sessionName} - ${cwdBasename}`);
536
+ this.ui.terminal.setTitle(`${APP_TITLE} - ${sessionName} - ${cwdBasename}`);
421
537
  }
422
538
  else {
423
- this.ui.terminal.setTitle(`draht - ${cwdBasename}`);
539
+ this.ui.terminal.setTitle(`${APP_TITLE} - ${cwdBasename}`);
424
540
  }
425
541
  }
426
542
  /**
@@ -430,9 +546,9 @@ export class InteractiveMode {
430
546
  async run() {
431
547
  await this.init();
432
548
  // Start version check asynchronously
433
- this.checkForNewVersion().then((newVersion) => {
434
- if (newVersion) {
435
- this.showNewVersionNotification(newVersion);
549
+ checkForNewPiVersion(this.version).then((newRelease) => {
550
+ if (newRelease) {
551
+ this.showNewVersionNotification(newRelease);
436
552
  }
437
553
  });
438
554
  // Start package update check asynchronously
@@ -493,31 +609,8 @@ export class InteractiveMode {
493
609
  }
494
610
  }
495
611
  }
496
- /**
497
- * Check npm registry for a newer version.
498
- */
499
- async checkForNewVersion() {
500
- if (process.env.PI_SKIP_VERSION_CHECK || process.env.PI_OFFLINE)
501
- return undefined;
502
- try {
503
- const response = await fetch("https://registry.npmjs.org/@draht/coding-agent/latest", {
504
- signal: AbortSignal.timeout(10000),
505
- });
506
- if (!response.ok)
507
- return undefined;
508
- const data = (await response.json());
509
- const latestVersion = data.version;
510
- if (latestVersion && latestVersion !== this.version) {
511
- return latestVersion;
512
- }
513
- return undefined;
514
- }
515
- catch {
516
- return undefined;
517
- }
518
- }
519
612
  async checkForPackageUpdates() {
520
- if (process.env.PI_OFFLINE) {
613
+ if (process.env.DRAHT_OFFLINE) {
521
614
  return [];
522
615
  }
523
616
  try {
@@ -583,27 +676,39 @@ export class InteractiveMode {
583
676
  if (this.session.state.messages.length > 0) {
584
677
  return undefined;
585
678
  }
586
- // Skip changelog in dev mode — "dev" parses as 0.0.0 and would surface every entry.
587
- if (VERSION === "dev") {
588
- return undefined;
589
- }
590
679
  const lastVersion = this.settingsManager.getLastChangelogVersion();
591
680
  const changelogPath = getChangelogPath();
592
681
  const entries = parseChangelog(changelogPath);
593
682
  if (!lastVersion) {
594
- // Fresh install - just record the version, don't show changelog
683
+ // Fresh install - record the version, send telemetry, don't show changelog
595
684
  this.settingsManager.setLastChangelogVersion(VERSION);
685
+ this.reportInstallTelemetry(VERSION);
596
686
  return undefined;
597
687
  }
598
- else {
599
- const newEntries = getNewEntries(entries, lastVersion);
600
- if (newEntries.length > 0) {
601
- this.settingsManager.setLastChangelogVersion(VERSION);
602
- return newEntries.map((e) => e.content).join("\n\n");
603
- }
688
+ const newEntries = getNewEntries(entries, lastVersion);
689
+ if (newEntries.length > 0) {
690
+ this.settingsManager.setLastChangelogVersion(VERSION);
691
+ this.reportInstallTelemetry(VERSION);
692
+ return newEntries.map((e) => normalizeChangelogLinks(e.content, e)).join("\n\n");
604
693
  }
605
694
  return undefined;
606
695
  }
696
+ reportInstallTelemetry(version) {
697
+ if (process.env.DRAHT_OFFLINE) {
698
+ return;
699
+ }
700
+ if (!isInstallTelemetryEnabled(this.settingsManager)) {
701
+ return;
702
+ }
703
+ void fetch(`https://pi.dev/api/report-install?version=${encodeURIComponent(version)}`, {
704
+ headers: {
705
+ "User-Agent": getPiUserAgent(version),
706
+ },
707
+ signal: AbortSignal.timeout(5000),
708
+ })
709
+ .then(() => undefined)
710
+ .catch(() => undefined);
711
+ }
607
712
  getMarkdownThemeWithSettings() {
608
713
  return {
609
714
  ...getMarkdownTheme(),
@@ -622,10 +727,38 @@ export class InteractiveMode {
622
727
  }
623
728
  return result;
624
729
  }
730
+ formatExtensionDisplayPath(path) {
731
+ let result = this.formatDisplayPath(path);
732
+ result = result.replace(/\/index\.ts$/, "").replace(/\/index\.js$/, "");
733
+ return result;
734
+ }
735
+ formatContextPath(p) {
736
+ const cwd = path.resolve(this.sessionManager.getCwd());
737
+ const absolutePath = path.isAbsolute(p) ? path.resolve(p) : path.resolve(cwd, p);
738
+ const relativePath = getCwdRelativePath(absolutePath, cwd);
739
+ if (relativePath !== undefined) {
740
+ return relativePath;
741
+ }
742
+ return this.formatDisplayPath(absolutePath);
743
+ }
744
+ getStartupExpansionState() {
745
+ return this.options.verbose || this.toolOutputExpanded;
746
+ }
625
747
  /**
626
748
  * Get a short path relative to the package root for display.
627
749
  */
628
750
  getShortPath(fullPath, sourceInfo) {
751
+ const baseDir = sourceInfo?.baseDir;
752
+ if (baseDir && this.isPackageSource(sourceInfo)) {
753
+ const relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));
754
+ if (relativePath &&
755
+ relativePath !== "." &&
756
+ !relativePath.startsWith("..") &&
757
+ !relativePath.startsWith(`..${path.sep}`) &&
758
+ !path.isAbsolute(relativePath)) {
759
+ return relativePath.replace(/\\/g, "/");
760
+ }
761
+ }
629
762
  const source = sourceInfo?.source ?? "";
630
763
  const npmMatch = fullPath.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);
631
764
  if (npmMatch && source.startsWith("npm:")) {
@@ -637,6 +770,93 @@ export class InteractiveMode {
637
770
  }
638
771
  return this.formatDisplayPath(fullPath);
639
772
  }
773
+ getCompactPathLabel(resourcePath, sourceInfo) {
774
+ const shortPath = this.getShortPath(resourcePath, sourceInfo);
775
+ const normalizedPath = shortPath.replace(/\\/g, "/");
776
+ const segments = normalizedPath.split("/").filter((segment) => segment.length > 0 && segment !== "~");
777
+ if (segments.length > 0) {
778
+ return segments[segments.length - 1];
779
+ }
780
+ return shortPath;
781
+ }
782
+ getCompactPackageSourceLabel(sourceInfo) {
783
+ const source = sourceInfo?.source ?? "";
784
+ if (source.startsWith("npm:")) {
785
+ return source.slice("npm:".length) || source;
786
+ }
787
+ const gitSource = parseGitUrl(source);
788
+ if (gitSource) {
789
+ return gitSource.path || source;
790
+ }
791
+ return source;
792
+ }
793
+ getCompactExtensionLabel(resourcePath, sourceInfo) {
794
+ if (!this.isPackageSource(sourceInfo)) {
795
+ return this.getCompactPathLabel(resourcePath, sourceInfo);
796
+ }
797
+ const sourceLabel = this.getCompactPackageSourceLabel(sourceInfo);
798
+ if (!sourceLabel) {
799
+ return this.getCompactPathLabel(resourcePath, sourceInfo);
800
+ }
801
+ const shortPath = this.getShortPath(resourcePath, sourceInfo).replace(/\\/g, "/");
802
+ const packagePath = shortPath.startsWith("extensions/") ? shortPath.slice("extensions/".length) : shortPath;
803
+ const parsedPath = path.posix.parse(packagePath);
804
+ if (parsedPath.name === "index") {
805
+ return !parsedPath.dir || parsedPath.dir === "." ? sourceLabel : `${sourceLabel}:${parsedPath.dir}`;
806
+ }
807
+ return `${sourceLabel}:${packagePath}`;
808
+ }
809
+ getCompactDisplayPathSegments(resourcePath) {
810
+ return this.formatDisplayPath(resourcePath)
811
+ .replace(/\\/g, "/")
812
+ .split("/")
813
+ .filter((segment) => segment.length > 0 && segment !== "~");
814
+ }
815
+ getCompactNonPackageExtensionLabel(resourcePath, index, allPaths) {
816
+ const segments = allPaths[index]?.segments;
817
+ if (!segments || segments.length === 0) {
818
+ return this.getCompactPathLabel(resourcePath);
819
+ }
820
+ for (let segmentCount = 1; segmentCount <= segments.length; segmentCount += 1) {
821
+ const candidate = segments.slice(-segmentCount).join("/");
822
+ const isUnique = allPaths.every((item, itemIndex) => {
823
+ if (itemIndex === index) {
824
+ return true;
825
+ }
826
+ return item.segments.slice(-segmentCount).join("/") !== candidate;
827
+ });
828
+ if (isUnique) {
829
+ return candidate;
830
+ }
831
+ }
832
+ return segments.join("/");
833
+ }
834
+ getCompactExtensionLabels(extensions) {
835
+ const nonPackageExtensions = extensions
836
+ .map((extension) => {
837
+ const segments = this.getCompactDisplayPathSegments(extension.path);
838
+ const lastSegment = segments[segments.length - 1];
839
+ if (segments.length > 1 && (lastSegment === "index.ts" || lastSegment === "index.js")) {
840
+ segments.pop();
841
+ }
842
+ return {
843
+ path: extension.path,
844
+ sourceInfo: extension.sourceInfo,
845
+ segments,
846
+ };
847
+ })
848
+ .filter((extension) => !this.isPackageSource(extension.sourceInfo));
849
+ return extensions.map((extension) => {
850
+ if (this.isPackageSource(extension.sourceInfo)) {
851
+ return this.getCompactExtensionLabel(extension.path, extension.sourceInfo);
852
+ }
853
+ const nonPackageIndex = nonPackageExtensions.findIndex((item) => item.path === extension.path);
854
+ if (nonPackageIndex === -1) {
855
+ return this.getCompactPathLabel(extension.path, extension.sourceInfo);
856
+ }
857
+ return this.getCompactNonPackageExtensionLabel(extension.path, nonPackageIndex, nonPackageExtensions);
858
+ });
859
+ }
640
860
  getDisplaySourceInfo(sourceInfo) {
641
861
  const source = sourceInfo?.source ?? "local";
642
862
  const scope = sourceInfo?.scope ?? "project";
@@ -782,6 +1002,18 @@ export class InteractiveMode {
782
1002
  return;
783
1003
  }
784
1004
  const sectionHeader = (name, color = "mdHeading") => theme.fg(color, `[${name}]`);
1005
+ const formatCompactList = (items, options) => {
1006
+ const labels = items.map((item) => item.trim()).filter((item) => item.length > 0);
1007
+ if (options?.sort !== false) {
1008
+ labels.sort((a, b) => a.localeCompare(b));
1009
+ }
1010
+ return theme.fg("dim", ` ${labels.join(", ")}`);
1011
+ };
1012
+ const addLoadedSection = (name, collapsedBody, expandedBody = collapsedBody, color = "mdHeading") => {
1013
+ const section = new ExpandableText(() => `${sectionHeader(name, color)}\n${collapsedBody}`, () => `${sectionHeader(name, color)}\n${expandedBody}`, this.getStartupExpansionState(), 0, 0);
1014
+ this.chatContainer.addChild(section);
1015
+ this.chatContainer.addChild(new Spacer(1));
1016
+ };
785
1017
  const skillsResult = this.session.resourceLoader.getSkills();
786
1018
  const promptsResult = this.session.resourceLoader.getPrompts();
787
1019
  const themesResult = this.session.resourceLoader.getThemes();
@@ -818,8 +1050,8 @@ export class InteractiveMode {
818
1050
  const contextList = contextFiles
819
1051
  .map((f) => theme.fg("dim", ` ${this.formatDisplayPath(f.path)}`))
820
1052
  .join("\n");
821
- this.chatContainer.addChild(new Text(`${sectionHeader("Context")}\n${contextList}`, 0, 0));
822
- this.chatContainer.addChild(new Spacer(1));
1053
+ const contextCompactList = formatCompactList(contextFiles.map((contextFile) => this.formatContextPath(contextFile.path)), { sort: false });
1054
+ addLoadedSection("Context", contextCompactList, contextList);
823
1055
  }
824
1056
  const skills = skillsResult.skills;
825
1057
  if (skills.length > 0) {
@@ -828,8 +1060,8 @@ export class InteractiveMode {
828
1060
  formatPath: (item) => this.formatDisplayPath(item.path),
829
1061
  formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),
830
1062
  });
831
- this.chatContainer.addChild(new Text(`${sectionHeader("Skills")}\n${skillList}`, 0, 0));
832
- this.chatContainer.addChild(new Spacer(1));
1063
+ const skillCompactList = formatCompactList(skills.map((skill) => skill.name));
1064
+ addLoadedSection("Skills", skillCompactList, skillList);
833
1065
  }
834
1066
  const templates = this.session.promptTemplates;
835
1067
  if (templates.length > 0) {
@@ -845,17 +1077,17 @@ export class InteractiveMode {
845
1077
  return template ? `/${template.name}` : this.formatDisplayPath(item.path);
846
1078
  },
847
1079
  });
848
- this.chatContainer.addChild(new Text(`${sectionHeader("Prompts")}\n${templateList}`, 0, 0));
849
- this.chatContainer.addChild(new Spacer(1));
1080
+ const promptCompactList = formatCompactList(templates.map((template) => `/${template.name}`));
1081
+ addLoadedSection("Prompts", promptCompactList, templateList);
850
1082
  }
851
1083
  if (extensions.length > 0) {
852
1084
  const groups = this.buildScopeGroups(extensions);
853
1085
  const extList = this.formatScopeGroups(groups, {
854
- formatPath: (item) => this.formatDisplayPath(item.path),
855
- formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),
1086
+ formatPath: (item) => this.formatExtensionDisplayPath(item.path),
1087
+ formatPackagePath: (item) => this.formatExtensionDisplayPath(this.getShortPath(item.path, item.sourceInfo)),
856
1088
  });
857
- this.chatContainer.addChild(new Text(`${sectionHeader("Extensions", "mdHeading")}\n${extList}`, 0, 0));
858
- this.chatContainer.addChild(new Spacer(1));
1089
+ const extensionCompactList = formatCompactList(this.getCompactExtensionLabels(extensions));
1090
+ addLoadedSection("Extensions", extensionCompactList, extList, "mdHeading");
859
1091
  }
860
1092
  // Show loaded themes (excluding built-in)
861
1093
  const loadedThemes = themesResult.themes;
@@ -869,8 +1101,8 @@ export class InteractiveMode {
869
1101
  formatPath: (item) => this.formatDisplayPath(item.path),
870
1102
  formatPackagePath: (item) => this.getShortPath(item.path, item.sourceInfo),
871
1103
  });
872
- this.chatContainer.addChild(new Text(`${sectionHeader("Themes")}\n${themeList}`, 0, 0));
873
- this.chatContainer.addChild(new Spacer(1));
1104
+ const themeCompactList = formatCompactList(customThemes.map((loadedTheme) => loadedTheme.name ?? this.getCompactPathLabel(loadedTheme.sourcePath, loadedTheme.sourceInfo)));
1105
+ addLoadedSection("Themes", themeCompactList, themeList);
874
1106
  }
875
1107
  }
876
1108
  if (showDiagnostics) {
@@ -893,10 +1125,10 @@ export class InteractiveMode {
893
1125
  extensionDiagnostics.push({ type: "error", message: error.error, path: error.path });
894
1126
  }
895
1127
  }
896
- const commandDiagnostics = this.session.extensionRunner?.getCommandDiagnostics() ?? [];
1128
+ const commandDiagnostics = this.session.extensionRunner.getCommandDiagnostics();
897
1129
  extensionDiagnostics.push(...commandDiagnostics);
898
1130
  extensionDiagnostics.push(...this.getBuiltInCommandConflictDiagnostics(this.session.extensionRunner));
899
- const shortcutDiagnostics = this.session.extensionRunner?.getShortcutDiagnostics() ?? [];
1131
+ const shortcutDiagnostics = this.session.extensionRunner.getShortcutDiagnostics();
900
1132
  extensionDiagnostics.push(...shortcutDiagnostics);
901
1133
  if (extensionDiagnostics.length > 0) {
902
1134
  const warningLines = this.formatDiagnostics(extensionDiagnostics, sourceInfos);
@@ -918,6 +1150,10 @@ export class InteractiveMode {
918
1150
  const uiContext = this.createExtensionUIContext();
919
1151
  await this.session.bindExtensions({
920
1152
  uiContext,
1153
+ mode: "tui",
1154
+ abortHandler: () => {
1155
+ this.restoreQueuedMessagesToEditor({ abort: true });
1156
+ },
921
1157
  commandContextActions: {
922
1158
  waitForIdle: () => this.session.agent.waitForIdle(),
923
1159
  newSession: async (options) => {
@@ -929,7 +1165,6 @@ export class InteractiveMode {
929
1165
  try {
930
1166
  const result = await this.runtimeHost.newSession(options);
931
1167
  if (!result.cancelled) {
932
- await this.handleRuntimeSessionChange();
933
1168
  this.renderCurrentSessionState();
934
1169
  this.ui.requestRender();
935
1170
  }
@@ -939,11 +1174,10 @@ export class InteractiveMode {
939
1174
  return this.handleFatalRuntimeError("Failed to create session", error);
940
1175
  }
941
1176
  },
942
- fork: async (entryId) => {
1177
+ fork: async (entryId, options) => {
943
1178
  try {
944
- const result = await this.runtimeHost.fork(entryId);
1179
+ const result = await this.runtimeHost.fork(entryId, options);
945
1180
  if (!result.cancelled) {
946
- await this.handleRuntimeSessionChange();
947
1181
  this.renderCurrentSessionState();
948
1182
  this.editor.setText(result.selectedText ?? "");
949
1183
  this.showStatus("Forked to new session");
@@ -970,11 +1204,11 @@ export class InteractiveMode {
970
1204
  this.editor.setText(result.editorText);
971
1205
  }
972
1206
  this.showStatus("Navigated to selected point");
1207
+ void this.flushCompactionQueue({ willRetry: false });
973
1208
  return { cancelled: false };
974
1209
  },
975
- switchSession: async (sessionPath) => {
976
- await this.handleResumeSession(sessionPath);
977
- return { cancelled: false };
1210
+ switchSession: async (sessionPath, options) => {
1211
+ return this.handleResumeSession(sessionPath, options);
978
1212
  },
979
1213
  reload: async () => {
980
1214
  await this.handleReloadCommand();
@@ -991,18 +1225,14 @@ export class InteractiveMode {
991
1225
  },
992
1226
  });
993
1227
  setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
994
- this.setupAutocomplete(this.fdPath);
1228
+ this.setupAutocompleteProvider();
995
1229
  const extensionRunner = this.session.extensionRunner;
996
- if (!extensionRunner) {
997
- this.showLoadedResources({ extensions: [], force: false });
998
- this.showStartupNoticesIfNeeded();
999
- return;
1000
- }
1001
1230
  this.setupExtensionShortcuts(extensionRunner);
1002
- this.showLoadedResources({ force: false });
1231
+ this.showLoadedResources({ force: false, showDiagnosticsWhenQuiet: true });
1003
1232
  this.showStartupNoticesIfNeeded();
1004
1233
  }
1005
1234
  applyRuntimeSettings() {
1235
+ configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());
1006
1236
  this.footer.setSession(this.session);
1007
1237
  this.footer.setAutoCompactEnabled(this.session.autoCompactionEnabled);
1008
1238
  this.footerDataProvider.setCwd(this.sessionManager.getCwd());
@@ -1018,8 +1248,7 @@ export class InteractiveMode {
1018
1248
  this.editor.setAutocompleteMaxVisible?.(autocompleteMaxVisible);
1019
1249
  }
1020
1250
  }
1021
- async handleRuntimeSessionChange() {
1022
- this.resetExtensionUI();
1251
+ async rebindCurrentSession() {
1023
1252
  this.unsubscribe?.();
1024
1253
  this.unsubscribe = undefined;
1025
1254
  this.applyRuntimeSettings();
@@ -1061,14 +1290,18 @@ export class InteractiveMode {
1061
1290
  // Create a context for shortcut handlers
1062
1291
  const createContext = () => ({
1063
1292
  ui: this.createExtensionUIContext(),
1293
+ mode: "tui",
1064
1294
  hasUI: true,
1065
1295
  cwd: this.sessionManager.getCwd(),
1066
1296
  sessionManager: this.sessionManager,
1067
1297
  modelRegistry: this.session.modelRegistry,
1068
1298
  model: this.session.model,
1069
1299
  isIdle: () => !this.session.isStreaming,
1300
+ isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
1070
1301
  signal: this.session.agent.signal,
1071
- abort: () => this.session.abort(),
1302
+ abort: () => {
1303
+ this.restoreQueuedMessagesToEditor({ abort: true });
1304
+ },
1072
1305
  hasPendingMessages: () => this.session.pendingMessageCount > 0,
1073
1306
  shutdown: () => {
1074
1307
  this.shutdownRequested = true;
@@ -1110,6 +1343,38 @@ export class InteractiveMode {
1110
1343
  this.footerDataProvider.setExtensionStatus(key, text);
1111
1344
  this.ui.requestRender();
1112
1345
  }
1346
+ getWorkingLoaderMessage() {
1347
+ return this.workingMessage ?? this.defaultWorkingMessage;
1348
+ }
1349
+ createWorkingLoader() {
1350
+ return new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), this.getWorkingLoaderMessage(), this.workingIndicatorOptions);
1351
+ }
1352
+ stopWorkingLoader() {
1353
+ if (this.loadingAnimation) {
1354
+ this.loadingAnimation.stop();
1355
+ this.loadingAnimation = undefined;
1356
+ }
1357
+ this.statusContainer.clear();
1358
+ }
1359
+ setWorkingVisible(visible) {
1360
+ this.workingVisible = visible;
1361
+ if (!visible) {
1362
+ this.stopWorkingLoader();
1363
+ this.ui.requestRender();
1364
+ return;
1365
+ }
1366
+ if (this.session.isStreaming && !this.loadingAnimation) {
1367
+ this.statusContainer.clear();
1368
+ this.loadingAnimation = this.createWorkingLoader();
1369
+ this.statusContainer.addChild(this.loadingAnimation);
1370
+ }
1371
+ this.ui.requestRender();
1372
+ }
1373
+ setWorkingIndicator(options) {
1374
+ this.workingIndicatorOptions = options;
1375
+ this.loadingAnimation?.setIndicator(options);
1376
+ this.ui.requestRender();
1377
+ }
1113
1378
  setHiddenThinkingLabel(label) {
1114
1379
  this.hiddenThinkingLabel = label ?? this.defaultHiddenThinkingLabel;
1115
1380
  for (const child of this.chatContainer.children) {
@@ -1187,9 +1452,14 @@ export class InteractiveMode {
1187
1452
  this.clearExtensionWidgets();
1188
1453
  this.footerDataProvider.clearExtensionStatuses();
1189
1454
  this.footer.invalidate();
1455
+ this.autocompleteProviderWrappers = [];
1190
1456
  this.setCustomEditorComponent(undefined);
1457
+ this.setupAutocompleteProvider();
1191
1458
  this.defaultEditor.onExtensionShortcut = undefined;
1192
1459
  this.updateTerminalTitle();
1460
+ this.workingMessage = undefined;
1461
+ this.workingVisible = true;
1462
+ this.setWorkingIndicator();
1193
1463
  if (this.loadingAnimation) {
1194
1464
  this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${keyText("app.interrupt")} to interrupt)`);
1195
1465
  }
@@ -1267,6 +1537,9 @@ export class InteractiveMode {
1267
1537
  if (factory) {
1268
1538
  // Create and add custom header
1269
1539
  this.customHeader = factory(this.ui, theme);
1540
+ if (isExpandable(this.customHeader)) {
1541
+ this.customHeader.setExpanded(this.toolOutputExpanded);
1542
+ }
1270
1543
  if (index !== -1) {
1271
1544
  this.headerContainer.children[index] = this.customHeader;
1272
1545
  }
@@ -1278,6 +1551,9 @@ export class InteractiveMode {
1278
1551
  else {
1279
1552
  // Restore built-in header
1280
1553
  this.customHeader = undefined;
1554
+ if (isExpandable(this.builtInHeader)) {
1555
+ this.builtInHeader.setExpanded(this.toolOutputExpanded);
1556
+ }
1281
1557
  if (index !== -1) {
1282
1558
  this.headerContainer.children[index] = this.builtInHeader;
1283
1559
  }
@@ -1301,6 +1577,20 @@ export class InteractiveMode {
1301
1577
  /**
1302
1578
  * Create the ExtensionUIContext for extensions.
1303
1579
  */
1580
+ createProjectTrustContext(cwd) {
1581
+ const ui = this.createExtensionUIContext();
1582
+ return {
1583
+ cwd,
1584
+ mode: "tui",
1585
+ hasUI: true,
1586
+ ui: {
1587
+ select: ui.select,
1588
+ confirm: ui.confirm,
1589
+ input: ui.input,
1590
+ notify: ui.notify,
1591
+ },
1592
+ };
1593
+ }
1304
1594
  createExtensionUIContext() {
1305
1595
  return {
1306
1596
  select: (title, options, opts) => this.showExtensionSelector(title, options, opts),
@@ -1310,19 +1600,13 @@ export class InteractiveMode {
1310
1600
  onTerminalInput: (handler) => this.addExtensionTerminalInputListener(handler),
1311
1601
  setStatus: (key, text) => this.setExtensionStatus(key, text),
1312
1602
  setWorkingMessage: (message) => {
1603
+ this.workingMessage = message;
1313
1604
  if (this.loadingAnimation) {
1314
- if (message) {
1315
- this.loadingAnimation.setMessage(message);
1316
- }
1317
- else {
1318
- this.loadingAnimation.setMessage(`${this.defaultWorkingMessage} (${keyText("app.interrupt")} to interrupt)`);
1319
- }
1320
- }
1321
- else {
1322
- // Queue message for when loadingAnimation is created (handles agent_start race)
1323
- this.pendingWorkingMessage = message;
1605
+ this.loadingAnimation.setMessage(message ?? this.defaultWorkingMessage);
1324
1606
  }
1325
1607
  },
1608
+ setWorkingVisible: (visible) => this.setWorkingVisible(visible),
1609
+ setWorkingIndicator: (options) => this.setWorkingIndicator(options),
1326
1610
  setHiddenThinkingLabel: (label) => this.setHiddenThinkingLabel(label),
1327
1611
  setWidget: (key, content, options) => this.setExtensionWidget(key, content, options),
1328
1612
  setFooter: (factory) => this.setExtensionFooter(factory),
@@ -1333,7 +1617,12 @@ export class InteractiveMode {
1333
1617
  setEditorText: (text) => this.editor.setText(text),
1334
1618
  getEditorText: () => this.editor.getExpandedText?.() ?? this.editor.getText(),
1335
1619
  editor: (title, prefill) => this.showExtensionEditor(title, prefill),
1620
+ addAutocompleteProvider: (factory) => {
1621
+ this.autocompleteProviderWrappers.push(factory);
1622
+ this.setupAutocompleteProvider();
1623
+ },
1336
1624
  setEditorComponent: (factory) => this.setCustomEditorComponent(factory),
1625
+ getEditorComponent: () => this.editorComponentFactory,
1337
1626
  get theme() {
1338
1627
  return theme;
1339
1628
  },
@@ -1380,7 +1669,7 @@ export class InteractiveMode {
1380
1669
  opts?.signal?.removeEventListener("abort", onAbort);
1381
1670
  this.hideExtensionSelector();
1382
1671
  resolve(undefined);
1383
- }, { tui: this.ui, timeout: opts?.timeout });
1672
+ }, { tui: this.ui, timeout: opts?.timeout, onToggleToolsExpanded: () => this.toggleToolOutputExpansion() });
1384
1673
  this.editorContainer.clear();
1385
1674
  this.editorContainer.addChild(this.extensionSelector);
1386
1675
  this.ui.setFocus(this.extensionSelector);
@@ -1482,6 +1771,7 @@ export class InteractiveMode {
1482
1771
  * Pass undefined to restore the default editor.
1483
1772
  */
1484
1773
  setCustomEditorComponent(factory) {
1774
+ this.editorComponentFactory = factory;
1485
1775
  // Save text from current editor before switching
1486
1776
  const currentText = this.editor.getText();
1487
1777
  this.editorContainer.clear();
@@ -1646,7 +1936,7 @@ export class InteractiveMode {
1646
1936
  // Set up handlers on defaultEditor - they use this.editor for text access
1647
1937
  // so they work correctly regardless of which editor is active
1648
1938
  this.defaultEditor.onEscape = () => {
1649
- if (this.loadingAnimation) {
1939
+ if (this.session.isStreaming) {
1650
1940
  this.restoreQueuedMessagesToEditor({ abort: true });
1651
1941
  }
1652
1942
  else if (this.session.isBashRunning) {
@@ -1750,12 +2040,12 @@ export class InteractiveMode {
1750
2040
  await this.handleModelCommand(searchTerm);
1751
2041
  return;
1752
2042
  }
1753
- if (text.startsWith("/export")) {
2043
+ if (text === "/export" || text.startsWith("/export ")) {
1754
2044
  await this.handleExportCommand(text);
1755
2045
  this.editor.setText("");
1756
2046
  return;
1757
2047
  }
1758
- if (text.startsWith("/import")) {
2048
+ if (text === "/import" || text.startsWith("/import ")) {
1759
2049
  await this.handleImportCommand(text);
1760
2050
  this.editor.setText("");
1761
2051
  return;
@@ -1795,11 +2085,21 @@ export class InteractiveMode {
1795
2085
  this.editor.setText("");
1796
2086
  return;
1797
2087
  }
2088
+ if (text === "/clone") {
2089
+ this.editor.setText("");
2090
+ await this.handleCloneCommand();
2091
+ return;
2092
+ }
1798
2093
  if (text === "/tree") {
1799
2094
  this.showTreeSelector();
1800
2095
  this.editor.setText("");
1801
2096
  return;
1802
2097
  }
2098
+ if (text === "/trust") {
2099
+ this.showTrustSelector();
2100
+ this.editor.setText("");
2101
+ return;
2102
+ }
1803
2103
  if (text === "/login") {
1804
2104
  this.showOAuthSelector("login");
1805
2105
  this.editor.setText("");
@@ -1896,6 +2196,9 @@ export class InteractiveMode {
1896
2196
  if (this.onInputCallback) {
1897
2197
  this.onInputCallback(text);
1898
2198
  }
2199
+ else {
2200
+ this.pendingUserInputs.push(text);
2201
+ }
1899
2202
  this.editor.addToHistory?.(text);
1900
2203
  };
1901
2204
  }
@@ -1911,28 +2214,28 @@ export class InteractiveMode {
1911
2214
  this.footer.invalidate();
1912
2215
  switch (event.type) {
1913
2216
  case "agent_start":
2217
+ this.pendingTools.clear();
2218
+ if (this.settingsManager.getShowTerminalProgress()) {
2219
+ this.ui.terminal.setProgress(true);
2220
+ }
1914
2221
  // Restore main escape handler if retry handler is still active
1915
2222
  // (retry success event fires later, but we need main handler now)
1916
2223
  if (this.retryEscapeHandler) {
1917
2224
  this.defaultEditor.onEscape = this.retryEscapeHandler;
1918
2225
  this.retryEscapeHandler = undefined;
1919
2226
  }
2227
+ if (this.retryCountdown) {
2228
+ this.retryCountdown.dispose();
2229
+ this.retryCountdown = undefined;
2230
+ }
1920
2231
  if (this.retryLoader) {
1921
2232
  this.retryLoader.stop();
1922
2233
  this.retryLoader = undefined;
1923
2234
  }
1924
- if (this.loadingAnimation) {
1925
- this.loadingAnimation.stop();
1926
- }
1927
- this.statusContainer.clear();
1928
- this.loadingAnimation = new Loader(this.ui, (spinner) => theme.fg("accent", spinner), (text) => theme.fg("muted", text), this.defaultWorkingMessage);
1929
- this.statusContainer.addChild(this.loadingAnimation);
1930
- // Apply any pending working message queued before loader existed
1931
- if (this.pendingWorkingMessage !== undefined) {
1932
- if (this.pendingWorkingMessage) {
1933
- this.loadingAnimation.setMessage(this.pendingWorkingMessage);
1934
- }
1935
- this.pendingWorkingMessage = undefined;
2235
+ this.stopWorkingLoader();
2236
+ if (this.workingVisible) {
2237
+ this.loadingAnimation = this.createWorkingLoader();
2238
+ this.statusContainer.addChild(this.loadingAnimation);
1936
2239
  }
1937
2240
  this.ui.requestRender();
1938
2241
  break;
@@ -1940,6 +2243,15 @@ export class InteractiveMode {
1940
2243
  this.updatePendingMessagesDisplay();
1941
2244
  this.ui.requestRender();
1942
2245
  break;
2246
+ case "session_info_changed":
2247
+ this.updateTerminalTitle();
2248
+ this.footer.invalidate();
2249
+ this.ui.requestRender();
2250
+ break;
2251
+ case "thinking_level_changed":
2252
+ this.footer.invalidate();
2253
+ this.updateEditorBorderColor();
2254
+ break;
1943
2255
  case "message_start":
1944
2256
  if (event.message.role === "custom") {
1945
2257
  this.addMessageToChat(event.message);
@@ -1967,6 +2279,7 @@ export class InteractiveMode {
1967
2279
  if (!this.pendingTools.has(content.id)) {
1968
2280
  const component = new ToolExecutionComponent(content.name, content.id, content.arguments, {
1969
2281
  showImages: this.settingsManager.getShowImages(),
2282
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
1970
2283
  }, this.getRegisteredToolDefinition(content.name), this.ui, this.sessionManager.getCwd());
1971
2284
  component.setExpanded(this.toolOutputExpanded);
1972
2285
  this.chatContainer.addChild(component);
@@ -2027,6 +2340,7 @@ export class InteractiveMode {
2027
2340
  if (!component) {
2028
2341
  component = new ToolExecutionComponent(event.toolName, event.toolCallId, event.args, {
2029
2342
  showImages: this.settingsManager.getShowImages(),
2343
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
2030
2344
  }, this.getRegisteredToolDefinition(event.toolName), this.ui, this.sessionManager.getCwd());
2031
2345
  component.setExpanded(this.toolOutputExpanded);
2032
2346
  this.chatContainer.addChild(component);
@@ -2054,6 +2368,9 @@ export class InteractiveMode {
2054
2368
  break;
2055
2369
  }
2056
2370
  case "agent_end":
2371
+ if (this.settingsManager.getShowTerminalProgress()) {
2372
+ this.ui.terminal.setProgress(false);
2373
+ }
2057
2374
  if (this.loadingAnimation) {
2058
2375
  this.loadingAnimation.stop();
2059
2376
  this.loadingAnimation = undefined;
@@ -2069,6 +2386,9 @@ export class InteractiveMode {
2069
2386
  this.ui.requestRender();
2070
2387
  break;
2071
2388
  case "compaction_start": {
2389
+ if (this.settingsManager.getShowTerminalProgress()) {
2390
+ this.ui.terminal.setProgress(true);
2391
+ }
2072
2392
  // Keep editor active; submissions are queued during compaction.
2073
2393
  this.autoCompactionEscapeHandler = this.defaultEditor.onEscape;
2074
2394
  this.defaultEditor.onEscape = () => {
@@ -2085,6 +2405,9 @@ export class InteractiveMode {
2085
2405
  break;
2086
2406
  }
2087
2407
  case "compaction_end": {
2408
+ if (this.settingsManager.getShowTerminalProgress()) {
2409
+ this.ui.terminal.setProgress(false);
2410
+ }
2088
2411
  if (this.autoCompactionEscapeHandler) {
2089
2412
  this.defaultEditor.onEscape = this.autoCompactionEscapeHandler;
2090
2413
  this.autoCompactionEscapeHandler = undefined;
@@ -2129,8 +2452,14 @@ export class InteractiveMode {
2129
2452
  };
2130
2453
  // Show retry indicator
2131
2454
  this.statusContainer.clear();
2132
- const delaySeconds = Math.round(event.delayMs / 1000);
2133
- this.retryLoader = new Loader(this.ui, (spinner) => theme.fg("warning", spinner), (text) => theme.fg("muted", text), `Retrying (${event.attempt}/${event.maxAttempts}) in ${delaySeconds}s... (${keyText("app.interrupt")} to cancel)`);
2455
+ this.retryCountdown?.dispose();
2456
+ const retryMessage = (seconds) => `Retrying (${event.attempt}/${event.maxAttempts}) in ${seconds}s... (${keyText("app.interrupt")} to cancel)`;
2457
+ this.retryLoader = new Loader(this.ui, (spinner) => theme.fg("warning", spinner), (text) => theme.fg("muted", text), retryMessage(Math.ceil(event.delayMs / 1000)));
2458
+ this.retryCountdown = new CountdownTimer(event.delayMs, this.ui, (seconds) => {
2459
+ this.retryLoader?.setMessage(retryMessage(seconds));
2460
+ }, () => {
2461
+ this.retryCountdown = undefined;
2462
+ });
2134
2463
  this.statusContainer.addChild(this.retryLoader);
2135
2464
  this.ui.requestRender();
2136
2465
  break;
@@ -2141,6 +2470,10 @@ export class InteractiveMode {
2141
2470
  this.defaultEditor.onEscape = this.retryEscapeHandler;
2142
2471
  this.retryEscapeHandler = undefined;
2143
2472
  }
2473
+ if (this.retryCountdown) {
2474
+ this.retryCountdown.dispose();
2475
+ this.retryCountdown = undefined;
2476
+ }
2144
2477
  // Stop loader
2145
2478
  if (this.retryLoader) {
2146
2479
  this.retryLoader.stop();
@@ -2201,7 +2534,7 @@ export class InteractiveMode {
2201
2534
  }
2202
2535
  case "custom": {
2203
2536
  if (message.display) {
2204
- const renderer = this.session.extensionRunner?.getMessageRenderer(message.customType);
2537
+ const renderer = this.session.extensionRunner.getMessageRenderer(message.customType);
2205
2538
  const component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings());
2206
2539
  component.setExpanded(this.toolOutputExpanded);
2207
2540
  this.chatContainer.addChild(component);
@@ -2225,15 +2558,18 @@ export class InteractiveMode {
2225
2558
  case "user": {
2226
2559
  const textContent = this.getUserMessageText(message);
2227
2560
  if (textContent) {
2561
+ if (this.chatContainer.children.length > 0) {
2562
+ this.chatContainer.addChild(new Spacer(1));
2563
+ }
2228
2564
  const skillBlock = parseSkillBlock(textContent);
2229
2565
  if (skillBlock) {
2230
2566
  // Render skill block (collapsible)
2231
- this.chatContainer.addChild(new Spacer(1));
2232
2567
  const component = new SkillInvocationMessageComponent(skillBlock, this.getMarkdownThemeWithSettings());
2233
2568
  component.setExpanded(this.toolOutputExpanded);
2234
2569
  this.chatContainer.addChild(component);
2235
2570
  // Render user message separately if present
2236
2571
  if (skillBlock.userMessage) {
2572
+ this.chatContainer.addChild(new Spacer(1));
2237
2573
  const userComponent = new UserMessageComponent(skillBlock.userMessage, this.getMarkdownThemeWithSettings());
2238
2574
  this.chatContainer.addChild(userComponent);
2239
2575
  }
@@ -2270,6 +2606,7 @@ export class InteractiveMode {
2270
2606
  */
2271
2607
  renderSessionContext(sessionContext, options = {}) {
2272
2608
  this.pendingTools.clear();
2609
+ const renderedPendingTools = new Map();
2273
2610
  if (options.updateFooter) {
2274
2611
  this.footer.invalidate();
2275
2612
  this.updateEditorBorderColor();
@@ -2281,7 +2618,10 @@ export class InteractiveMode {
2281
2618
  // Render tool call components
2282
2619
  for (const content of message.content) {
2283
2620
  if (content.type === "toolCall") {
2284
- const component = new ToolExecutionComponent(content.name, content.id, content.arguments, { showImages: this.settingsManager.getShowImages() }, this.getRegisteredToolDefinition(content.name), this.ui, this.sessionManager.getCwd());
2621
+ const component = new ToolExecutionComponent(content.name, content.id, content.arguments, {
2622
+ showImages: this.settingsManager.getShowImages(),
2623
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
2624
+ }, this.getRegisteredToolDefinition(content.name), this.ui, this.sessionManager.getCwd());
2285
2625
  component.setExpanded(this.toolOutputExpanded);
2286
2626
  this.chatContainer.addChild(component);
2287
2627
  if (message.stopReason === "aborted" || message.stopReason === "error") {
@@ -2299,17 +2639,17 @@ export class InteractiveMode {
2299
2639
  component.updateResult({ content: [{ type: "text", text: errorMessage }], isError: true });
2300
2640
  }
2301
2641
  else {
2302
- this.pendingTools.set(content.id, component);
2642
+ renderedPendingTools.set(content.id, component);
2303
2643
  }
2304
2644
  }
2305
2645
  }
2306
2646
  }
2307
2647
  else if (message.role === "toolResult") {
2308
2648
  // Match tool results to pending tool components
2309
- const component = this.pendingTools.get(message.toolCallId);
2649
+ const component = renderedPendingTools.get(message.toolCallId);
2310
2650
  if (component) {
2311
2651
  component.updateResult(message);
2312
- this.pendingTools.delete(message.toolCallId);
2652
+ renderedPendingTools.delete(message.toolCallId);
2313
2653
  }
2314
2654
  }
2315
2655
  else {
@@ -2317,7 +2657,9 @@ export class InteractiveMode {
2317
2657
  this.addMessageToChat(message, options);
2318
2658
  }
2319
2659
  }
2320
- this.pendingTools.clear();
2660
+ for (const [toolCallId, component] of renderedPendingTools) {
2661
+ this.pendingTools.set(toolCallId, component);
2662
+ }
2321
2663
  this.ui.requestRender();
2322
2664
  }
2323
2665
  renderInitialMessages() {
@@ -2327,6 +2669,7 @@ export class InteractiveMode {
2327
2669
  updateFooter: true,
2328
2670
  populateHistory: true,
2329
2671
  });
2672
+ this.renderProjectTrustWarningIfNeeded();
2330
2673
  // Show compaction info if session was compacted
2331
2674
  const allEntries = this.sessionManager.getEntries();
2332
2675
  const compactionCount = allEntries.filter((e) => e.type === "compaction").length;
@@ -2335,7 +2678,20 @@ export class InteractiveMode {
2335
2678
  this.showStatus(`Session compacted ${times}`);
2336
2679
  }
2337
2680
  }
2681
+ renderProjectTrustWarningIfNeeded() {
2682
+ if (this.settingsManager.isProjectTrusted() || !hasProjectTrustInputs(this.sessionManager.getCwd())) {
2683
+ return;
2684
+ }
2685
+ if (this.chatContainer.children.length > 0) {
2686
+ this.chatContainer.addChild(new Spacer(1));
2687
+ }
2688
+ this.chatContainer.addChild(new Text(theme.fg("warning", "This project is not trusted. Project .pi resources and packages are ignored. Use /trust to save a trust decision, then restart pi."), 1, 0));
2689
+ }
2338
2690
  async getUserInput() {
2691
+ const queuedInput = this.pendingUserInputs.shift();
2692
+ if (queuedInput !== undefined) {
2693
+ return queuedInput;
2694
+ }
2339
2695
  return new Promise((resolve) => {
2340
2696
  this.onInputCallback = (text) => {
2341
2697
  this.onInputCallback = undefined;
@@ -2367,23 +2723,82 @@ export class InteractiveMode {
2367
2723
  }
2368
2724
  /**
2369
2725
  * Gracefully shutdown the agent.
2370
- * Emits shutdown event to extensions, then exits.
2726
+ * Stops the TUI before emitting shutdown events so extension UI cleanup cannot
2727
+ * repaint the final frame while the process is exiting.
2371
2728
  */
2372
2729
  isShuttingDown = false;
2373
- async shutdown() {
2730
+ async shutdown(options) {
2374
2731
  if (this.isShuttingDown)
2375
2732
  return;
2376
2733
  this.isShuttingDown = true;
2377
- await this.runtimeHost.dispose();
2378
- // Wait for any pending renders to complete
2379
- // requestRender() uses process.nextTick(), so we wait one tick
2380
- await new Promise((resolve) => process.nextTick(resolve));
2734
+ this.unregisterSignalHandlers();
2735
+ if (options?.fromSignal) {
2736
+ // Signal-triggered shutdown (SIGTERM/SIGHUP). Emit extension cleanup
2737
+ // (session_shutdown) BEFORE touching the terminal. Extension teardown
2738
+ // such as removing sockets does not write to the tty, so it must not be
2739
+ // skipped if a later terminal-restore write fails on a dead or stalled
2740
+ // terminal. If the terminal is gone, the restore writes below emit EIO,
2741
+ // which the stdout/stderr error handler turns into emergencyTerminalExit;
2742
+ // the render loop is already idle, so this cannot hot-spin (see #4144).
2743
+ await this.runtimeHost.dispose();
2744
+ await this.ui.terminal.drainInput(1000);
2745
+ this.stop();
2746
+ process.exit(0);
2747
+ }
2748
+ // Interactive quit (Ctrl+D, Ctrl+C, /quit, extension shutdown()). Stop the
2749
+ // TUI before emitting shutdown events so extension UI cleanup cannot repaint
2750
+ // the final frame while the process is exiting.
2381
2751
  // Drain any in-flight Kitty key release events before stopping.
2382
2752
  // This prevents escape sequences from leaking to the parent shell over slow SSH.
2383
2753
  await this.ui.terminal.drainInput(1000);
2384
2754
  this.stop();
2755
+ await this.runtimeHost.dispose();
2756
+ const resumeCommand = formatResumeCommand(this.sessionManager);
2757
+ if (resumeCommand) {
2758
+ process.stdout.write(`${chalk.dim("To resume this session:")} ${resumeCommand}\n`);
2759
+ }
2385
2760
  process.exit(0);
2386
2761
  }
2762
+ emergencyTerminalExit() {
2763
+ this.isShuttingDown = true;
2764
+ this.unregisterSignalHandlers();
2765
+ killTrackedDetachedChildren();
2766
+ // The terminal is gone. Do not run normal shutdown because TUI and
2767
+ // extension cleanup can write restore sequences and re-trigger EIO.
2768
+ process.exit(129);
2769
+ }
2770
+ /**
2771
+ * Last-resort handler for uncaught exceptions. The TUI puts stdin into raw
2772
+ * mode and hides the cursor; without this handler, an uncaught throw from
2773
+ * anywhere (e.g. an extension's async `ChildProcess.on("exit")` callback)
2774
+ * tears down the process while leaving the terminal in raw mode with no
2775
+ * cursor, requiring `stty sane && reset` to recover.
2776
+ *
2777
+ * Unlike emergencyTerminalExit, the terminal is still alive here, so we
2778
+ * call ui.stop() to restore cooked mode, the cursor, and disable bracketed
2779
+ * paste / Kitty / modifyOtherKeys sequences.
2780
+ */
2781
+ uncaughtCrash(error) {
2782
+ if (this.isShuttingDown) {
2783
+ process.exit(1);
2784
+ }
2785
+ this.isShuttingDown = true;
2786
+ try {
2787
+ this.unregisterSignalHandlers();
2788
+ }
2789
+ catch { }
2790
+ try {
2791
+ killTrackedDetachedChildren();
2792
+ }
2793
+ catch { }
2794
+ try {
2795
+ this.ui.stop();
2796
+ }
2797
+ catch { }
2798
+ console.error("pi exiting due to uncaughtException:");
2799
+ console.error(error);
2800
+ process.exit(1);
2801
+ }
2387
2802
  /**
2388
2803
  * Check if shutdown was requested and perform shutdown if so.
2389
2804
  */
@@ -2392,7 +2807,52 @@ export class InteractiveMode {
2392
2807
  return;
2393
2808
  await this.shutdown();
2394
2809
  }
2810
+ registerSignalHandlers() {
2811
+ this.unregisterSignalHandlers();
2812
+ const signals = ["SIGTERM"];
2813
+ if (process.platform !== "win32") {
2814
+ signals.push("SIGHUP");
2815
+ }
2816
+ for (const signal of signals) {
2817
+ const handler = () => {
2818
+ // SIGHUP no longer hard-exits: graceful shutdown emits session_shutdown
2819
+ // first, then attempts terminal restore. A genuinely dead terminal
2820
+ // surfaces as an EIO on the restore writes, which the stdout/stderr
2821
+ // error handler converts into emergencyTerminalExit (see #4144, #5080).
2822
+ killTrackedDetachedChildren();
2823
+ void this.shutdown({ fromSignal: true });
2824
+ };
2825
+ process.prependListener(signal, handler);
2826
+ this.signalCleanupHandlers.push(() => process.off(signal, handler));
2827
+ }
2828
+ const terminalErrorHandler = (error) => {
2829
+ if (isDeadTerminalError(error)) {
2830
+ this.emergencyTerminalExit();
2831
+ }
2832
+ throw error;
2833
+ };
2834
+ process.stdout.on("error", terminalErrorHandler);
2835
+ process.stderr.on("error", terminalErrorHandler);
2836
+ this.signalCleanupHandlers.push(() => process.stdout.off("error", terminalErrorHandler));
2837
+ this.signalCleanupHandlers.push(() => process.stderr.off("error", terminalErrorHandler));
2838
+ // Restore the terminal before the process dies on any uncaught throw.
2839
+ // Without this, an unhandled exception from extension code (or anywhere
2840
+ // in pi) leaves the terminal in raw mode with no cursor.
2841
+ const uncaughtExceptionHandler = (error) => this.uncaughtCrash(error);
2842
+ process.prependListener("uncaughtException", uncaughtExceptionHandler);
2843
+ this.signalCleanupHandlers.push(() => process.off("uncaughtException", uncaughtExceptionHandler));
2844
+ }
2845
+ unregisterSignalHandlers() {
2846
+ for (const cleanup of this.signalCleanupHandlers) {
2847
+ cleanup();
2848
+ }
2849
+ this.signalCleanupHandlers = [];
2850
+ }
2395
2851
  handleCtrlZ() {
2852
+ if (process.platform === "win32") {
2853
+ this.showStatus("Suspend to background is not supported on Windows");
2854
+ return;
2855
+ }
2396
2856
  // Keep the event loop alive while suspended. Without this, stopping the TUI
2397
2857
  // can leave Node with no ref'ed handles, causing the process to exit on fg
2398
2858
  // before the SIGCONT handler gets a chance to restore the terminal.
@@ -2447,6 +2907,7 @@ export class InteractiveMode {
2447
2907
  }
2448
2908
  // If not streaming, Alt+Enter acts like regular Enter (trigger onSubmit)
2449
2909
  else if (this.editor.onSubmit) {
2910
+ this.editor.setText("");
2450
2911
  this.editor.onSubmit(text);
2451
2912
  }
2452
2913
  }
@@ -2504,6 +2965,10 @@ export class InteractiveMode {
2504
2965
  }
2505
2966
  setToolsExpanded(expanded) {
2506
2967
  this.toolOutputExpanded = expanded;
2968
+ const activeHeader = this.customHeader ?? this.builtInHeader;
2969
+ if (isExpandable(activeHeader)) {
2970
+ activeHeader.setExpanded(expanded);
2971
+ }
2507
2972
  for (const child of this.chatContainer.children) {
2508
2973
  if (isExpandable(child)) {
2509
2974
  child.setExpanded(expanded);
@@ -2525,7 +2990,7 @@ export class InteractiveMode {
2525
2990
  }
2526
2991
  this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
2527
2992
  }
2528
- openExternalEditor() {
2993
+ async openExternalEditor() {
2529
2994
  // Determine editor (respect $VISUAL, then $EDITOR)
2530
2995
  const editorCmd = process.env.VISUAL || process.env.EDITOR;
2531
2996
  if (!editorCmd) {
@@ -2541,13 +3006,20 @@ export class InteractiveMode {
2541
3006
  this.ui.stop();
2542
3007
  // Split by space to support editor arguments (e.g., "code --wait")
2543
3008
  const [editor, ...editorArgs] = editorCmd.split(" ");
2544
- // Spawn editor synchronously with inherited stdio for interactive editing
2545
- const result = spawnSync(editor, [...editorArgs, tmpFile], {
2546
- stdio: "inherit",
2547
- shell: process.platform === "win32",
3009
+ process.stdout.write(`Launching external editor: ${editorCmd}\nPi will resume when the editor exits.\n`);
3010
+ // Do not use spawnSync here. On Windows, synchronous child_process calls can keep
3011
+ // Node/libuv's console input read active after ui.stop() pauses stdin, racing
3012
+ // vim/nvim for the console input buffer until Ctrl+C cancels the pending read.
3013
+ const status = await new Promise((resolve) => {
3014
+ const child = spawn(editor, [...editorArgs, tmpFile], {
3015
+ stdio: "inherit",
3016
+ shell: process.platform === "win32",
3017
+ });
3018
+ child.on("error", () => resolve(null));
3019
+ child.on("close", (code) => resolve(code));
2548
3020
  });
2549
3021
  // On successful exit (status 0), replace editor content
2550
- if (result.status === 0) {
3022
+ if (status === 0) {
2551
3023
  const newContent = fs.readFileSync(tmpFile, "utf-8").replace(/\n$/, "");
2552
3024
  this.editor.setText(newContent);
2553
3025
  }
@@ -2577,6 +3049,7 @@ export class InteractiveMode {
2577
3049
  showError(errorMessage) {
2578
3050
  this.chatContainer.addChild(new Spacer(1));
2579
3051
  this.chatContainer.addChild(new Text(theme.fg("error", `Error: ${errorMessage}`), 1, 0));
3052
+ this.chatContainer.addChild(new Spacer(1));
2580
3053
  this.ui.requestRender();
2581
3054
  }
2582
3055
  showWarning(warningMessage) {
@@ -2584,14 +3057,26 @@ export class InteractiveMode {
2584
3057
  this.chatContainer.addChild(new Text(theme.fg("warning", `Warning: ${warningMessage}`), 1, 0));
2585
3058
  this.ui.requestRender();
2586
3059
  }
2587
- showNewVersionNotification(newVersion) {
2588
- const action = theme.fg("accent", getUpdateInstruction("@draht/coding-agent"));
2589
- const updateInstruction = theme.fg("muted", `New version ${newVersion} is available. `) + action;
2590
- const changelogUrl = theme.fg("accent", "https://github.com/draht-dev/draht/blob/main/packages/coding-agent/CHANGELOG.md");
2591
- const changelogLine = theme.fg("muted", "Changelog: ") + changelogUrl;
3060
+ showNewVersionNotification(release) {
3061
+ const action = theme.fg("accent", `${APP_NAME} update`);
3062
+ const updateInstruction = theme.fg("muted", `New version ${release.version} is available. Run `) + action;
3063
+ const changelogUrl = "https://pi.dev/changelog";
3064
+ const changelogLink = getCapabilities().hyperlinks
3065
+ ? hyperlink(theme.fg("accent", "open changelog"), changelogUrl)
3066
+ : theme.fg("accent", changelogUrl);
3067
+ const changelogLine = theme.fg("muted", "Changelog: ") + changelogLink;
3068
+ const note = release.note?.trim();
2592
3069
  this.chatContainer.addChild(new Spacer(1));
2593
3070
  this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
2594
- this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction}\n${changelogLine}`, 1, 0));
3071
+ this.chatContainer.addChild(new Text(`${theme.bold(theme.fg("warning", "Update Available"))}\n${updateInstruction}`, 1, 0));
3072
+ if (note) {
3073
+ this.chatContainer.addChild(new Spacer(1));
3074
+ this.chatContainer.addChild(new Markdown(note, 1, 0, this.getMarkdownThemeWithSettings(), {
3075
+ color: (text) => theme.fg("muted", text),
3076
+ }));
3077
+ this.chatContainer.addChild(new Spacer(1));
3078
+ }
3079
+ this.chatContainer.addChild(new Text(changelogLine, 1, 0));
2595
3080
  this.chatContainer.addChild(new DynamicBorder((text) => theme.fg("warning", text)));
2596
3081
  this.ui.requestRender();
2597
3082
  }
@@ -2688,8 +3173,6 @@ export class InteractiveMode {
2688
3173
  if (!text.startsWith("/"))
2689
3174
  return false;
2690
3175
  const extensionRunner = this.session.extensionRunner;
2691
- if (!extensionRunner)
2692
- return false;
2693
3176
  const spaceIndex = text.indexOf(" ");
2694
3177
  const commandName = spaceIndex === -1 ? text.slice(1) : text.slice(1, spaceIndex);
2695
3178
  return !!extensionRunner.getCommand(commandName);
@@ -2795,25 +3278,31 @@ export class InteractiveMode {
2795
3278
  const selector = new SettingsSelectorComponent({
2796
3279
  autoCompact: this.session.autoCompactionEnabled,
2797
3280
  showImages: this.settingsManager.getShowImages(),
3281
+ imageWidthCells: this.settingsManager.getImageWidthCells(),
2798
3282
  autoResizeImages: this.settingsManager.getImageAutoResize(),
2799
3283
  blockImages: this.settingsManager.getBlockImages(),
2800
3284
  enableSkillCommands: this.settingsManager.getEnableSkillCommands(),
2801
3285
  steeringMode: this.session.steeringMode,
2802
3286
  followUpMode: this.session.followUpMode,
2803
3287
  transport: this.settingsManager.getTransport(),
3288
+ httpIdleTimeoutMs: this.settingsManager.getHttpIdleTimeoutMs(),
2804
3289
  thinkingLevel: this.session.thinkingLevel,
2805
3290
  availableThinkingLevels: this.session.getAvailableThinkingLevels(),
2806
3291
  currentTheme: this.settingsManager.getTheme() || "dark",
2807
3292
  availableThemes: getAvailableThemes(),
2808
3293
  hideThinkingBlock: this.hideThinkingBlock,
2809
3294
  collapseChangelog: this.settingsManager.getCollapseChangelog(),
3295
+ enableInstallTelemetry: this.settingsManager.getEnableInstallTelemetry(),
2810
3296
  doubleEscapeAction: this.settingsManager.getDoubleEscapeAction(),
2811
3297
  treeFilterMode: this.settingsManager.getTreeFilterMode(),
2812
3298
  showHardwareCursor: this.settingsManager.getShowHardwareCursor(),
3299
+ defaultProjectTrust: this.settingsManager.getDefaultProjectTrust(),
2813
3300
  editorPaddingX: this.settingsManager.getEditorPaddingX(),
2814
3301
  autocompleteMaxVisible: this.settingsManager.getAutocompleteMaxVisible(),
2815
3302
  quietStartup: this.settingsManager.getQuietStartup(),
2816
3303
  clearOnShrink: this.settingsManager.getClearOnShrink(),
3304
+ showTerminalProgress: this.settingsManager.getShowTerminalProgress(),
3305
+ warnings: this.settingsManager.getWarnings(),
2817
3306
  }, {
2818
3307
  onAutoCompactChange: (enabled) => {
2819
3308
  this.session.setAutoCompactionEnabled(enabled);
@@ -2827,6 +3316,14 @@ export class InteractiveMode {
2827
3316
  }
2828
3317
  }
2829
3318
  },
3319
+ onImageWidthCellsChange: (width) => {
3320
+ this.settingsManager.setImageWidthCells(width);
3321
+ for (const child of this.chatContainer.children) {
3322
+ if (child instanceof ToolExecutionComponent) {
3323
+ child.setImageWidthCells(width);
3324
+ }
3325
+ }
3326
+ },
2830
3327
  onAutoResizeImagesChange: (enabled) => {
2831
3328
  this.settingsManager.setImageAutoResize(enabled);
2832
3329
  },
@@ -2835,7 +3332,7 @@ export class InteractiveMode {
2835
3332
  },
2836
3333
  onEnableSkillCommandsChange: (enabled) => {
2837
3334
  this.settingsManager.setEnableSkillCommands(enabled);
2838
- this.setupAutocomplete(this.fdPath);
3335
+ this.setupAutocompleteProvider();
2839
3336
  },
2840
3337
  onSteeringModeChange: (mode) => {
2841
3338
  this.session.setSteeringMode(mode);
@@ -2847,6 +3344,11 @@ export class InteractiveMode {
2847
3344
  this.settingsManager.setTransport(transport);
2848
3345
  this.session.agent.transport = transport;
2849
3346
  },
3347
+ onHttpIdleTimeoutMsChange: (timeoutMs) => {
3348
+ this.settingsManager.setHttpIdleTimeoutMs(timeoutMs);
3349
+ configureHttpDispatcher(timeoutMs);
3350
+ this.showStatus(`HTTP idle timeout: ${formatHttpIdleTimeoutMs(timeoutMs)}`);
3351
+ },
2850
3352
  onThinkingLevelChange: (level) => {
2851
3353
  this.session.setThinkingLevel(level);
2852
3354
  this.footer.invalidate();
@@ -2881,9 +3383,15 @@ export class InteractiveMode {
2881
3383
  onCollapseChangelogChange: (collapsed) => {
2882
3384
  this.settingsManager.setCollapseChangelog(collapsed);
2883
3385
  },
3386
+ onEnableInstallTelemetryChange: (enabled) => {
3387
+ this.settingsManager.setEnableInstallTelemetry(enabled);
3388
+ },
2884
3389
  onQuietStartupChange: (enabled) => {
2885
3390
  this.settingsManager.setQuietStartup(enabled);
2886
3391
  },
3392
+ onDefaultProjectTrustChange: (defaultProjectTrust) => {
3393
+ this.settingsManager.setDefaultProjectTrust(defaultProjectTrust);
3394
+ },
2887
3395
  onDoubleEscapeActionChange: (action) => {
2888
3396
  this.settingsManager.setDoubleEscapeAction(action);
2889
3397
  },
@@ -2912,6 +3420,12 @@ export class InteractiveMode {
2912
3420
  this.settingsManager.setClearOnShrink(enabled);
2913
3421
  this.ui.setClearOnShrink(enabled);
2914
3422
  },
3423
+ onShowTerminalProgressChange: (enabled) => {
3424
+ this.settingsManager.setShowTerminalProgress(enabled);
3425
+ },
3426
+ onWarningsChange: (warnings) => {
3427
+ this.settingsManager.setWarnings(warnings);
3428
+ },
2915
3429
  onCancel: () => {
2916
3430
  done();
2917
3431
  this.ui.requestRender();
@@ -2965,6 +3479,9 @@ export class InteractiveMode {
2965
3479
  this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);
2966
3480
  }
2967
3481
  async maybeWarnAboutAnthropicSubscriptionAuth(model = this.session.model) {
3482
+ if (this.settingsManager.getWarnings().anthropicExtraUsage === false) {
3483
+ return;
3484
+ }
2968
3485
  if (this.anthropicSubscriptionWarningShown) {
2969
3486
  return;
2970
3487
  }
@@ -2989,6 +3506,51 @@ export class InteractiveMode {
2989
3506
  // Ignore auth lookup failures for warning-only checks.
2990
3507
  }
2991
3508
  }
3509
+ maybeSaveImplicitProjectTrustAfterReload() {
3510
+ const cwd = this.sessionManager.getCwd();
3511
+ if (this.autoTrustOnReloadCwd !== cwd) {
3512
+ return false;
3513
+ }
3514
+ if (!this.settingsManager.isProjectTrusted() || !hasProjectConfigDir(cwd)) {
3515
+ return false;
3516
+ }
3517
+ const trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);
3518
+ try {
3519
+ if (trustStore.get(cwd) !== null) {
3520
+ this.autoTrustOnReloadCwd = undefined;
3521
+ return false;
3522
+ }
3523
+ trustStore.set(cwd, true);
3524
+ this.autoTrustOnReloadCwd = undefined;
3525
+ return true;
3526
+ }
3527
+ catch (error) {
3528
+ this.showWarning(`Could not save project trust after reload: ${error instanceof Error ? error.message : String(error)}`);
3529
+ return false;
3530
+ }
3531
+ }
3532
+ showTrustSelector() {
3533
+ const cwd = this.sessionManager.getCwd();
3534
+ const trustStore = new ProjectTrustStore(this.runtimeHost.services.agentDir);
3535
+ const savedDecision = trustStore.getEntry(cwd);
3536
+ this.showSelector((done) => {
3537
+ const selector = new TrustSelectorComponent({
3538
+ cwd,
3539
+ savedDecision,
3540
+ projectTrusted: this.settingsManager.isProjectTrusted(),
3541
+ onSelect: (selection) => {
3542
+ trustStore.setMany(selection.updates);
3543
+ done();
3544
+ this.showStatus(`Saved trust decision: ${selection.trusted ? "trusted" : "untrusted"}. Restart pi for this to take effect.`);
3545
+ },
3546
+ onCancel: () => {
3547
+ done();
3548
+ this.ui.requestRender();
3549
+ },
3550
+ });
3551
+ return { component: selector, focus: selector };
3552
+ });
3553
+ }
2992
3554
  showModelSelector(initialSearchInput) {
2993
3555
  this.showSelector((done) => {
2994
3556
  const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRegistry, this.session.scopedModels, async (model) => {
@@ -3024,33 +3586,24 @@ export class InteractiveMode {
3024
3586
  const sessionScopedModels = this.session.scopedModels;
3025
3587
  const hasSessionScope = sessionScopedModels.length > 0;
3026
3588
  // Build enabled model IDs from session state or settings
3027
- const enabledModelIds = new Set();
3028
- let hasFilter = false;
3589
+ let currentEnabledIds = null;
3029
3590
  if (hasSessionScope) {
3030
3591
  // Use current session's scoped models
3031
- for (const sm of sessionScopedModels) {
3032
- enabledModelIds.add(`${sm.model.provider}/${sm.model.id}`);
3033
- }
3034
- hasFilter = true;
3592
+ currentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3035
3593
  }
3036
3594
  else {
3037
3595
  // Fall back to settings
3038
3596
  const patterns = this.settingsManager.getEnabledModels();
3039
3597
  if (patterns !== undefined && patterns.length > 0) {
3040
- hasFilter = true;
3041
3598
  const scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);
3042
- for (const sm of scopedModels) {
3043
- enabledModelIds.add(`${sm.model.provider}/${sm.model.id}`);
3044
- }
3599
+ currentEnabledIds = scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3045
3600
  }
3046
3601
  }
3047
- // Track current enabled state (session-only until persisted)
3048
- const currentEnabledIds = new Set(enabledModelIds);
3049
- let currentHasFilter = hasFilter;
3050
3602
  // Helper to update session's scoped models (session-only, no persist)
3051
3603
  const updateSessionModels = async (enabledIds) => {
3052
- if (enabledIds.size > 0 && enabledIds.size < allModels.length) {
3053
- const newScopedModels = await resolveModelScope(Array.from(enabledIds), this.session.modelRegistry);
3604
+ currentEnabledIds = enabledIds === null ? null : [...enabledIds];
3605
+ if (enabledIds && enabledIds.length > 0 && enabledIds.length < allModels.length) {
3606
+ const newScopedModels = await resolveModelScope(enabledIds, this.session.modelRegistry);
3054
3607
  this.session.setScopedModels(newScopedModels.map((sm) => ({
3055
3608
  model: sm.model,
3056
3609
  thinkingLevel: sm.thinkingLevel,
@@ -3067,49 +3620,16 @@ export class InteractiveMode {
3067
3620
  const selector = new ScopedModelsSelectorComponent({
3068
3621
  allModels,
3069
3622
  enabledModelIds: currentEnabledIds,
3070
- hasEnabledModelsFilter: currentHasFilter,
3071
3623
  }, {
3072
- onModelToggle: async (modelId, enabled) => {
3073
- if (enabled) {
3074
- currentEnabledIds.add(modelId);
3075
- }
3076
- else {
3077
- currentEnabledIds.delete(modelId);
3078
- }
3079
- currentHasFilter = true;
3080
- await updateSessionModels(currentEnabledIds);
3081
- },
3082
- onEnableAll: async (allModelIds) => {
3083
- currentEnabledIds.clear();
3084
- for (const id of allModelIds) {
3085
- currentEnabledIds.add(id);
3086
- }
3087
- currentHasFilter = false;
3088
- await updateSessionModels(currentEnabledIds);
3089
- },
3090
- onClearAll: async () => {
3091
- currentEnabledIds.clear();
3092
- currentHasFilter = true;
3093
- await updateSessionModels(currentEnabledIds);
3094
- },
3095
- onToggleProvider: async (_provider, modelIds, enabled) => {
3096
- for (const id of modelIds) {
3097
- if (enabled) {
3098
- currentEnabledIds.add(id);
3099
- }
3100
- else {
3101
- currentEnabledIds.delete(id);
3102
- }
3103
- }
3104
- currentHasFilter = true;
3105
- await updateSessionModels(currentEnabledIds);
3624
+ onChange: async (enabledIds) => {
3625
+ await updateSessionModels(enabledIds);
3106
3626
  },
3107
3627
  onPersist: (enabledIds) => {
3108
3628
  // Persist to settings
3109
- const newPatterns = enabledIds.length === allModels.length
3629
+ const newPatterns = enabledIds === null || enabledIds.length === allModels.length
3110
3630
  ? undefined // All enabled = clear filter
3111
3631
  : enabledIds;
3112
- this.settingsManager.setEnabledModels(newPatterns);
3632
+ this.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);
3113
3633
  this.showStatus("Model selection saved to settings");
3114
3634
  },
3115
3635
  onCancel: () => {
@@ -3126,26 +3646,52 @@ export class InteractiveMode {
3126
3646
  this.showStatus("No messages to fork from");
3127
3647
  return;
3128
3648
  }
3649
+ const initialSelectedId = userMessages[userMessages.length - 1]?.entryId;
3129
3650
  this.showSelector((done) => {
3130
3651
  const selector = new UserMessageSelectorComponent(userMessages.map((m) => ({ id: m.entryId, text: m.text })), async (entryId) => {
3131
- const result = await this.runtimeHost.fork(entryId);
3132
- if (result.cancelled) {
3652
+ try {
3653
+ const result = await this.runtimeHost.fork(entryId);
3654
+ if (result.cancelled) {
3655
+ done();
3656
+ this.ui.requestRender();
3657
+ return;
3658
+ }
3659
+ this.renderCurrentSessionState();
3660
+ this.editor.setText(result.selectedText ?? "");
3133
3661
  done();
3134
- this.ui.requestRender();
3135
- return;
3662
+ this.showStatus("Forked to new session");
3663
+ }
3664
+ catch (error) {
3665
+ done();
3666
+ this.showError(error instanceof Error ? error.message : String(error));
3136
3667
  }
3137
- await this.handleRuntimeSessionChange();
3138
- this.renderCurrentSessionState();
3139
- this.editor.setText(result.selectedText ?? "");
3140
- done();
3141
- this.showStatus("Branched to new session");
3142
3668
  }, () => {
3143
3669
  done();
3144
3670
  this.ui.requestRender();
3145
- });
3671
+ }, initialSelectedId);
3146
3672
  return { component: selector, focus: selector.getMessageList() };
3147
3673
  });
3148
3674
  }
3675
+ async handleCloneCommand() {
3676
+ const leafId = this.sessionManager.getLeafId();
3677
+ if (!leafId) {
3678
+ this.showStatus("Nothing to clone yet");
3679
+ return;
3680
+ }
3681
+ try {
3682
+ const result = await this.runtimeHost.fork(leafId, { position: "at" });
3683
+ if (result.cancelled) {
3684
+ this.ui.requestRender();
3685
+ return;
3686
+ }
3687
+ this.renderCurrentSessionState();
3688
+ this.editor.setText("");
3689
+ this.showStatus("Cloned to new session");
3690
+ }
3691
+ catch (error) {
3692
+ this.showError(error instanceof Error ? error.message : String(error));
3693
+ }
3694
+ }
3149
3695
  showTreeSelector(initialSelectedId) {
3150
3696
  const tree = this.sessionManager.getTree();
3151
3697
  const realLeafId = this.sessionManager.getLeafId();
@@ -3226,6 +3772,7 @@ export class InteractiveMode {
3226
3772
  this.editor.setText(result.editorText);
3227
3773
  }
3228
3774
  this.showStatus("Navigated to selected point");
3775
+ void this.flushCompactionQueue({ willRetry: false });
3229
3776
  }
3230
3777
  catch (error) {
3231
3778
  this.showError(error instanceof Error ? error.message : String(error));
@@ -3249,7 +3796,9 @@ export class InteractiveMode {
3249
3796
  }
3250
3797
  showSessionSelector() {
3251
3798
  this.showSelector((done) => {
3252
- const selector = new SessionSelectorComponent((onProgress) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress), SessionManager.listAll, async (sessionPath) => {
3799
+ const selector = new SessionSelectorComponent((onProgress) => SessionManager.list(this.sessionManager.getCwd(), this.sessionManager.getSessionDir(), onProgress), (onProgress) => this.sessionManager.usesDefaultSessionDir()
3800
+ ? SessionManager.listAll(onProgress)
3801
+ : SessionManager.listAll(this.sessionManager.getSessionDir(), onProgress), async (sessionPath) => {
3253
3802
  done();
3254
3803
  await this.handleResumeSession(sessionPath);
3255
3804
  }, () => {
@@ -3271,87 +3820,299 @@ export class InteractiveMode {
3271
3820
  return { component: selector, focus: selector };
3272
3821
  });
3273
3822
  }
3274
- async handleResumeSession(sessionPath) {
3823
+ async handleResumeSession(sessionPath, options) {
3275
3824
  if (this.loadingAnimation) {
3276
3825
  this.loadingAnimation.stop();
3277
3826
  this.loadingAnimation = undefined;
3278
3827
  }
3279
3828
  this.statusContainer.clear();
3280
3829
  try {
3281
- const result = await this.runtimeHost.switchSession(sessionPath);
3830
+ const result = await this.runtimeHost.switchSession(sessionPath, {
3831
+ withSession: options?.withSession,
3832
+ projectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),
3833
+ });
3282
3834
  if (result.cancelled) {
3283
- return;
3835
+ return result;
3284
3836
  }
3285
- await this.handleRuntimeSessionChange();
3286
3837
  this.renderCurrentSessionState();
3287
3838
  this.showStatus("Resumed session");
3839
+ return result;
3288
3840
  }
3289
3841
  catch (error) {
3290
3842
  if (error instanceof MissingSessionCwdError) {
3291
3843
  const selectedCwd = await this.promptForMissingSessionCwd(error);
3292
3844
  if (!selectedCwd) {
3293
3845
  this.showStatus("Resume cancelled");
3294
- return;
3846
+ return { cancelled: true };
3295
3847
  }
3296
- const result = await this.runtimeHost.switchSession(sessionPath, selectedCwd);
3848
+ const result = await this.runtimeHost.switchSession(sessionPath, {
3849
+ cwdOverride: selectedCwd,
3850
+ withSession: options?.withSession,
3851
+ projectTrustContextFactory: (cwd) => this.createProjectTrustContext(cwd),
3852
+ });
3297
3853
  if (result.cancelled) {
3298
- return;
3854
+ return result;
3299
3855
  }
3300
- await this.handleRuntimeSessionChange();
3301
3856
  this.renderCurrentSessionState();
3302
3857
  this.showStatus("Resumed session in current cwd");
3303
- return;
3858
+ return result;
3304
3859
  }
3305
- await this.handleFatalRuntimeError("Failed to resume session", error);
3860
+ return this.handleFatalRuntimeError("Failed to resume session", error);
3306
3861
  }
3307
3862
  }
3308
- async showOAuthSelector(mode) {
3309
- if (mode === "logout") {
3310
- const providers = this.session.modelRegistry.authStorage.list();
3311
- const loggedInProviders = providers.filter((p) => this.session.modelRegistry.authStorage.get(p)?.type === "oauth");
3312
- if (loggedInProviders.length === 0) {
3313
- this.showStatus("No OAuth providers logged in. Use /login first.");
3314
- return;
3863
+ getLoginProviderOptions(authType) {
3864
+ const authStorage = this.session.modelRegistry.authStorage;
3865
+ const oauthProviders = authStorage.getOAuthProviders();
3866
+ const oauthProviderIds = new Set(oauthProviders.map((provider) => provider.id));
3867
+ const options = oauthProviders.map((provider) => ({
3868
+ id: provider.id,
3869
+ name: provider.name,
3870
+ authType: "oauth",
3871
+ }));
3872
+ const modelProviders = new Set(this.session.modelRegistry.getAll().map((model) => model.provider));
3873
+ for (const providerId of modelProviders) {
3874
+ if (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {
3875
+ continue;
3315
3876
  }
3877
+ options.push({
3878
+ id: providerId,
3879
+ name: this.session.modelRegistry.getProviderDisplayName(providerId),
3880
+ authType: "api_key",
3881
+ });
3882
+ }
3883
+ const filteredOptions = authType ? options.filter((option) => option.authType === authType) : options;
3884
+ return filteredOptions.sort((a, b) => a.name.localeCompare(b.name));
3885
+ }
3886
+ getLogoutProviderOptions() {
3887
+ const authStorage = this.session.modelRegistry.authStorage;
3888
+ const options = [];
3889
+ for (const providerId of authStorage.list()) {
3890
+ const credential = authStorage.get(providerId);
3891
+ if (!credential) {
3892
+ continue;
3893
+ }
3894
+ options.push({
3895
+ id: providerId,
3896
+ name: this.session.modelRegistry.getProviderDisplayName(providerId),
3897
+ authType: credential.type,
3898
+ });
3899
+ }
3900
+ return options.sort((a, b) => a.name.localeCompare(b.name));
3901
+ }
3902
+ showLoginAuthTypeSelector() {
3903
+ const subscriptionLabel = "Use a subscription";
3904
+ const apiKeyLabel = "Use an API key";
3905
+ this.showSelector((done) => {
3906
+ const selector = new ExtensionSelectorComponent("Select authentication method:", [subscriptionLabel, apiKeyLabel], (option) => {
3907
+ done();
3908
+ const authType = option === subscriptionLabel ? "oauth" : "api_key";
3909
+ this.showLoginProviderSelector(authType);
3910
+ }, () => {
3911
+ done();
3912
+ this.ui.requestRender();
3913
+ });
3914
+ return { component: selector, focus: selector };
3915
+ });
3916
+ }
3917
+ showLoginProviderSelector(authType) {
3918
+ const providerOptions = this.getLoginProviderOptions(authType);
3919
+ if (providerOptions.length === 0) {
3920
+ this.showStatus(authType === "oauth" ? "No subscription providers available." : "No API key providers available.");
3921
+ return;
3922
+ }
3923
+ this.showSelector((done) => {
3924
+ const selector = new OAuthSelectorComponent("login", this.session.modelRegistry.authStorage, providerOptions, async (providerId) => {
3925
+ done();
3926
+ const providerOption = providerOptions.find((provider) => provider.id === providerId);
3927
+ if (!providerOption) {
3928
+ return;
3929
+ }
3930
+ if (providerOption.authType === "oauth") {
3931
+ await this.showLoginDialog(providerOption.id, providerOption.name);
3932
+ }
3933
+ else if (providerOption.id === BEDROCK_PROVIDER_ID) {
3934
+ this.showBedrockSetupDialog(providerOption.id, providerOption.name);
3935
+ }
3936
+ else {
3937
+ await this.showApiKeyLoginDialog(providerOption.id, providerOption.name);
3938
+ }
3939
+ }, () => {
3940
+ done();
3941
+ this.showLoginAuthTypeSelector();
3942
+ }, (providerId) => this.session.modelRegistry.getProviderAuthStatus(providerId));
3943
+ return { component: selector, focus: selector };
3944
+ });
3945
+ }
3946
+ async showOAuthSelector(mode) {
3947
+ if (mode === "login") {
3948
+ this.showLoginAuthTypeSelector();
3949
+ return;
3950
+ }
3951
+ const providerOptions = this.getLogoutProviderOptions();
3952
+ if (providerOptions.length === 0) {
3953
+ this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");
3954
+ return;
3316
3955
  }
3317
3956
  this.showSelector((done) => {
3318
- const selector = new OAuthSelectorComponent(mode, this.session.modelRegistry.authStorage, async (providerId) => {
3957
+ const selector = new OAuthSelectorComponent(mode, this.session.modelRegistry.authStorage, providerOptions, async (providerId) => {
3319
3958
  done();
3320
- if (mode === "login") {
3321
- await this.showLoginDialog(providerId);
3959
+ const providerOption = providerOptions.find((provider) => provider.id === providerId);
3960
+ if (!providerOption) {
3961
+ return;
3962
+ }
3963
+ try {
3964
+ this.session.modelRegistry.authStorage.logout(providerOption.id);
3965
+ this.session.modelRegistry.refresh();
3966
+ await this.updateAvailableProviderCount();
3967
+ const message = providerOption.authType === "oauth"
3968
+ ? `Logged out of ${providerOption.name}`
3969
+ : `Removed stored API key for ${providerOption.name}. Environment variables and models.json config are unchanged.`;
3970
+ this.showStatus(message);
3971
+ }
3972
+ catch (error) {
3973
+ this.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);
3974
+ }
3975
+ }, () => {
3976
+ done();
3977
+ this.ui.requestRender();
3978
+ });
3979
+ return { component: selector, focus: selector };
3980
+ });
3981
+ }
3982
+ async completeProviderAuthentication(providerId, providerName, authType, previousModel) {
3983
+ this.session.modelRegistry.refresh();
3984
+ const actionLabel = authType === "oauth" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;
3985
+ let selectedModel;
3986
+ let selectionError;
3987
+ if (isUnknownModel(previousModel)) {
3988
+ const availableModels = this.session.modelRegistry.getAvailable();
3989
+ const providerModels = availableModels.filter((model) => model.provider === providerId);
3990
+ if (!hasDefaultModelProvider(providerId)) {
3991
+ selectionError = `${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;
3992
+ }
3993
+ else if (providerModels.length === 0) {
3994
+ selectionError = `${actionLabel}, but no models are available for that provider. Use /model to select a model.`;
3995
+ }
3996
+ else {
3997
+ const defaultModelId = defaultModelPerProvider[providerId];
3998
+ selectedModel = providerModels.find((model) => model.id === defaultModelId);
3999
+ if (!selectedModel) {
4000
+ selectionError = `${actionLabel}, but its default model "${defaultModelId}" is not available. Use /model to select a model.`;
3322
4001
  }
3323
4002
  else {
3324
- // Logout flow
3325
- const providerInfo = this.session.modelRegistry.authStorage
3326
- .getOAuthProviders()
3327
- .find((p) => p.id === providerId);
3328
- const providerName = providerInfo?.name || providerId;
3329
4003
  try {
3330
- this.session.modelRegistry.authStorage.logout(providerId);
3331
- this.session.modelRegistry.refresh();
3332
- await this.updateAvailableProviderCount();
3333
- this.showStatus(`Logged out of ${providerName}`);
4004
+ await this.session.setModel(selectedModel);
3334
4005
  }
3335
4006
  catch (error) {
3336
- this.showError(`Logout failed: ${error instanceof Error ? error.message : String(error)}`);
4007
+ selectedModel = undefined;
4008
+ const errorMessage = error instanceof Error ? error.message : String(error);
4009
+ selectionError = `${actionLabel}, but selecting its default model failed: ${errorMessage}. Use /model to select a model.`;
3337
4010
  }
3338
4011
  }
3339
- }, () => {
3340
- done();
4012
+ }
4013
+ }
4014
+ await this.updateAvailableProviderCount();
4015
+ this.footer.invalidate();
4016
+ this.updateEditorBorderColor();
4017
+ if (selectedModel) {
4018
+ this.showStatus(`${actionLabel}. Selected ${selectedModel.id}. Credentials saved to ${getAuthPath()}`);
4019
+ void this.maybeWarnAboutAnthropicSubscriptionAuth(selectedModel);
4020
+ this.checkDaxnutsEasterEgg(selectedModel);
4021
+ }
4022
+ else {
4023
+ this.showStatus(`${actionLabel}. Credentials saved to ${getAuthPath()}`);
4024
+ if (selectionError) {
4025
+ this.showError(selectionError);
4026
+ }
4027
+ else {
4028
+ void this.maybeWarnAboutAnthropicSubscriptionAuth();
4029
+ }
4030
+ }
4031
+ }
4032
+ showBedrockSetupDialog(providerId, providerName) {
4033
+ const restoreEditor = () => {
4034
+ this.editorContainer.clear();
4035
+ this.editorContainer.addChild(this.editor);
4036
+ this.ui.setFocus(this.editor);
4037
+ this.ui.requestRender();
4038
+ };
4039
+ const dialog = new LoginDialogComponent(this.ui, providerId, () => restoreEditor(), providerName, "Amazon Bedrock setup");
4040
+ dialog.showInfo([
4041
+ theme.fg("text", "Amazon Bedrock uses AWS credentials instead of a single API key."),
4042
+ theme.fg("text", "Configure an AWS profile, IAM keys, bearer token, or role-based credentials."),
4043
+ theme.fg("muted", "See:"),
4044
+ theme.fg("accent", ` ${path.join(getDocsPath(), "providers.md")}`),
4045
+ ]);
4046
+ this.editorContainer.clear();
4047
+ this.editorContainer.addChild(dialog);
4048
+ this.ui.setFocus(dialog);
4049
+ this.ui.requestRender();
4050
+ }
4051
+ async showApiKeyLoginDialog(providerId, providerName) {
4052
+ const previousModel = this.session.model;
4053
+ const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
4054
+ // Completion handled below
4055
+ }, providerName);
4056
+ this.editorContainer.clear();
4057
+ this.editorContainer.addChild(dialog);
4058
+ this.ui.setFocus(dialog);
4059
+ this.ui.requestRender();
4060
+ const restoreEditor = () => {
4061
+ this.editorContainer.clear();
4062
+ this.editorContainer.addChild(this.editor);
4063
+ this.ui.setFocus(this.editor);
4064
+ this.ui.requestRender();
4065
+ };
4066
+ try {
4067
+ const apiKey = (await dialog.showPrompt("Enter API key:")).trim();
4068
+ if (!apiKey) {
4069
+ throw new Error("API key cannot be empty.");
4070
+ }
4071
+ this.session.modelRegistry.authStorage.set(providerId, { type: "api_key", key: apiKey });
4072
+ restoreEditor();
4073
+ await this.completeProviderAuthentication(providerId, providerName, "api_key", previousModel);
4074
+ }
4075
+ catch (error) {
4076
+ restoreEditor();
4077
+ const errorMsg = error instanceof Error ? error.message : String(error);
4078
+ if (errorMsg !== "Login cancelled") {
4079
+ this.showError(`Failed to save API key for ${providerName}: ${errorMsg}`);
4080
+ }
4081
+ }
4082
+ }
4083
+ showOAuthLoginSelect(dialog, prompt) {
4084
+ return new Promise((resolve) => {
4085
+ const restoreDialog = () => {
4086
+ this.editorContainer.clear();
4087
+ this.editorContainer.addChild(dialog);
4088
+ this.ui.setFocus(dialog);
3341
4089
  this.ui.requestRender();
4090
+ };
4091
+ const labels = prompt.options.map((option) => option.label);
4092
+ const selector = new ExtensionSelectorComponent(prompt.message, labels, (optionLabel) => {
4093
+ restoreDialog();
4094
+ resolve(prompt.options.find((option) => option.label === optionLabel)?.id);
4095
+ }, () => {
4096
+ restoreDialog();
4097
+ resolve(undefined);
3342
4098
  });
3343
- return { component: selector, focus: selector };
4099
+ this.editorContainer.clear();
4100
+ this.editorContainer.addChild(selector);
4101
+ this.ui.setFocus(selector);
4102
+ this.ui.requestRender();
3344
4103
  });
3345
4104
  }
3346
- async showLoginDialog(providerId) {
3347
- const providerInfo = this.session.modelRegistry.authStorage.getOAuthProviders().find((p) => p.id === providerId);
3348
- const providerName = providerInfo?.name || providerId;
4105
+ async showLoginDialog(providerId, providerName) {
4106
+ const providerInfo = this.session.modelRegistry.authStorage
4107
+ .getOAuthProviders()
4108
+ .find((provider) => provider.id === providerId);
4109
+ const previousModel = this.session.model;
3349
4110
  // Providers that use callback servers (can paste redirect URL)
3350
4111
  const usesCallbackServer = providerInfo?.usesCallbackServer ?? false;
3351
4112
  // Create login dialog component
3352
4113
  const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
3353
4114
  // Completion handled below
3354
- });
4115
+ }, providerName);
3355
4116
  // Show dialog in editor container
3356
4117
  this.editorContainer.clear();
3357
4118
  this.editorContainer.addChild(dialog);
@@ -3392,26 +4153,25 @@ export class InteractiveMode {
3392
4153
  }
3393
4154
  });
3394
4155
  }
3395
- else if (providerId === "github-copilot") {
3396
- // GitHub Copilot polls after onAuth
3397
- dialog.showWaiting("Waiting for browser authentication...");
3398
- }
3399
4156
  // For Anthropic: onPrompt is called immediately after
3400
4157
  },
4158
+ onDeviceCode: (info) => {
4159
+ dialog.showDeviceCode(info);
4160
+ dialog.showWaiting("Waiting for authentication...");
4161
+ },
3401
4162
  onPrompt: async (prompt) => {
3402
4163
  return dialog.showPrompt(prompt.message, prompt.placeholder);
3403
4164
  },
3404
4165
  onProgress: (message) => {
3405
4166
  dialog.showProgress(message);
3406
4167
  },
4168
+ onSelect: (prompt) => this.showOAuthLoginSelect(dialog, prompt),
3407
4169
  onManualCodeInput: () => manualCodePromise,
3408
4170
  signal: dialog.signal,
3409
4171
  });
3410
4172
  // Success
3411
4173
  restoreEditor();
3412
- this.session.modelRegistry.refresh();
3413
- await this.updateAvailableProviderCount();
3414
- this.showStatus(`Logged in to ${providerName}. Credentials saved to ${getAuthPath()}`);
4174
+ await this.completeProviderAuthentication(providerId, providerName, "oauth", previousModel);
3415
4175
  }
3416
4176
  catch (error) {
3417
4177
  restoreEditor();
@@ -3434,16 +4194,20 @@ export class InteractiveMode {
3434
4194
  return;
3435
4195
  }
3436
4196
  this.resetExtensionUI();
3437
- const loader = new BorderedLoader(this.ui, theme, "Reloading keybindings, extensions, skills, prompts, themes...", {
3438
- cancellable: false,
3439
- });
4197
+ const reloadBox = new Container();
4198
+ const borderColor = (s) => theme.fg("border", s);
4199
+ reloadBox.addChild(new DynamicBorder(borderColor));
4200
+ reloadBox.addChild(new Spacer(1));
4201
+ reloadBox.addChild(new Text(theme.fg("muted", "Reloading keybindings, extensions, skills, prompts, themes..."), 1, 0));
4202
+ reloadBox.addChild(new Spacer(1));
4203
+ reloadBox.addChild(new DynamicBorder(borderColor));
3440
4204
  const previousEditor = this.editor;
3441
4205
  this.editorContainer.clear();
3442
- this.editorContainer.addChild(loader);
3443
- this.ui.setFocus(loader);
3444
- this.ui.requestRender();
3445
- const dismissLoader = (editor) => {
3446
- loader.dispose();
4206
+ this.editorContainer.addChild(reloadBox);
4207
+ this.ui.setFocus(reloadBox);
4208
+ this.ui.requestRender(true);
4209
+ await new Promise((resolve) => process.nextTick(resolve));
4210
+ const dismissReloadBox = (editor) => {
3447
4211
  this.editorContainer.clear();
3448
4212
  this.editorContainer.addChild(editor);
3449
4213
  this.ui.setFocus(editor);
@@ -3451,7 +4215,12 @@ export class InteractiveMode {
3451
4215
  };
3452
4216
  try {
3453
4217
  await this.session.reload();
4218
+ configureHttpDispatcher(this.settingsManager.getHttpIdleTimeoutMs());
3454
4219
  this.keybindings.reload();
4220
+ const activeHeader = this.customHeader ?? this.builtInHeader;
4221
+ if (isExpandable(activeHeader)) {
4222
+ activeHeader.setExpanded(this.toolOutputExpanded);
4223
+ }
3455
4224
  setRegisteredThemes(this.session.resourceLoader.getThemes().themes);
3456
4225
  this.hideThinkingBlock = this.settingsManager.getHideThinkingBlock();
3457
4226
  const themeName = this.settingsManager.getTheme();
@@ -3469,31 +4238,31 @@ export class InteractiveMode {
3469
4238
  }
3470
4239
  this.ui.setShowHardwareCursor(this.settingsManager.getShowHardwareCursor());
3471
4240
  this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
3472
- this.setupAutocomplete(this.fdPath);
4241
+ this.setupAutocompleteProvider();
3473
4242
  const runner = this.session.extensionRunner;
3474
- if (runner) {
3475
- this.setupExtensionShortcuts(runner);
3476
- }
4243
+ this.setupExtensionShortcuts(runner);
3477
4244
  this.rebuildChatFromMessages();
3478
- dismissLoader(this.editor);
4245
+ dismissReloadBox(this.editor);
3479
4246
  this.showLoadedResources({
3480
4247
  force: false,
3481
4248
  showDiagnosticsWhenQuiet: true,
3482
4249
  });
4250
+ const savedImplicitProjectTrust = this.maybeSaveImplicitProjectTrustAfterReload();
3483
4251
  const modelsJsonError = this.session.modelRegistry.getError();
3484
4252
  if (modelsJsonError) {
3485
4253
  this.showError(`models.json error: ${modelsJsonError}`);
3486
4254
  }
3487
- this.showStatus("Reloaded keybindings, extensions, skills, prompts, themes");
4255
+ this.showStatus(savedImplicitProjectTrust
4256
+ ? "Reloaded keybindings, extensions, skills, prompts, themes; saved project trust"
4257
+ : "Reloaded keybindings, extensions, skills, prompts, themes");
3488
4258
  }
3489
4259
  catch (error) {
3490
- dismissLoader(previousEditor);
4260
+ dismissReloadBox(previousEditor);
3491
4261
  this.showError(`Reload failed: ${error instanceof Error ? error.message : String(error)}`);
3492
4262
  }
3493
4263
  }
3494
4264
  async handleExportCommand(text) {
3495
- const parts = text.split(/\s+/);
3496
- const outputPath = parts.length > 1 ? parts[1] : undefined;
4265
+ const outputPath = this.getPathCommandArgument(text, "/export");
3497
4266
  try {
3498
4267
  if (outputPath?.endsWith(".jsonl")) {
3499
4268
  const filePath = this.session.exportToJsonl(outputPath);
@@ -3508,13 +4277,37 @@ export class InteractiveMode {
3508
4277
  this.showError(`Failed to export session: ${error instanceof Error ? error.message : "Unknown error"}`);
3509
4278
  }
3510
4279
  }
4280
+ getPathCommandArgument(text, command) {
4281
+ if (text === command) {
4282
+ return undefined;
4283
+ }
4284
+ if (!text.startsWith(`${command} `)) {
4285
+ return undefined;
4286
+ }
4287
+ const argsString = text.slice(command.length + 1).trimStart();
4288
+ if (!argsString) {
4289
+ return undefined;
4290
+ }
4291
+ const firstChar = argsString[0];
4292
+ if (firstChar === '"' || firstChar === "'") {
4293
+ const closingQuoteIndex = argsString.indexOf(firstChar, 1);
4294
+ if (closingQuoteIndex < 0) {
4295
+ return undefined;
4296
+ }
4297
+ return argsString.slice(1, closingQuoteIndex);
4298
+ }
4299
+ const firstWhitespaceIndex = argsString.search(/\s/);
4300
+ if (firstWhitespaceIndex < 0) {
4301
+ return argsString;
4302
+ }
4303
+ return argsString.slice(0, firstWhitespaceIndex);
4304
+ }
3511
4305
  async handleImportCommand(text) {
3512
- const parts = text.split(/\s+/);
3513
- if (parts.length < 2 || !parts[1]) {
4306
+ const inputPath = this.getPathCommandArgument(text, "/import");
4307
+ if (!inputPath) {
3514
4308
  this.showError("Usage: /import <path.jsonl>");
3515
4309
  return;
3516
4310
  }
3517
- const inputPath = parts[1];
3518
4311
  const confirmed = await this.showExtensionConfirm("Import session", `Replace current session with ${inputPath}?`);
3519
4312
  if (!confirmed) {
3520
4313
  this.showStatus("Import cancelled");
@@ -3531,7 +4324,6 @@ export class InteractiveMode {
3531
4324
  this.showStatus("Import cancelled");
3532
4325
  return;
3533
4326
  }
3534
- await this.handleRuntimeSessionChange();
3535
4327
  this.renderCurrentSessionState();
3536
4328
  this.showStatus(`Session imported from: ${inputPath}`);
3537
4329
  }
@@ -3547,11 +4339,14 @@ export class InteractiveMode {
3547
4339
  this.showStatus("Import cancelled");
3548
4340
  return;
3549
4341
  }
3550
- await this.handleRuntimeSessionChange();
3551
4342
  this.renderCurrentSessionState();
3552
4343
  this.showStatus(`Session imported from: ${inputPath}`);
3553
4344
  return;
3554
4345
  }
4346
+ if (error instanceof SessionImportFileNotFoundError) {
4347
+ this.showError(`Failed to import session: ${error.message}`);
4348
+ return;
4349
+ }
3555
4350
  await this.handleFatalRuntimeError("Failed to import session", error);
3556
4351
  }
3557
4352
  }
@@ -3670,8 +4465,7 @@ export class InteractiveMode {
3670
4465
  this.ui.requestRender();
3671
4466
  return;
3672
4467
  }
3673
- this.sessionManager.appendSessionInfo(name);
3674
- this.updateTerminalTitle();
4468
+ this.session.setSessionName(name);
3675
4469
  this.chatContainer.addChild(new Spacer(1));
3676
4470
  this.chatContainer.addChild(new Text(theme.fg("dim", `Session name set: ${name}`), 1, 0));
3677
4471
  this.ui.requestRender();
@@ -3715,7 +4509,7 @@ export class InteractiveMode {
3715
4509
  const changelogMarkdown = allEntries.length > 0
3716
4510
  ? allEntries
3717
4511
  .reverse()
3718
- .map((e) => e.content)
4512
+ .map((e) => normalizeChangelogLinks(e.content, e))
3719
4513
  .join("\n\n")
3720
4514
  : "No changelog entries found.";
3721
4515
  this.chatContainer.addChild(new Spacer(1));
@@ -3726,29 +4520,17 @@ export class InteractiveMode {
3726
4520
  this.chatContainer.addChild(new DynamicBorder());
3727
4521
  this.ui.requestRender();
3728
4522
  }
3729
- /**
3730
- * Capitalize keybinding for display (e.g., "ctrl+c" -> "Ctrl+C").
3731
- */
3732
- capitalizeKey(key) {
3733
- return key
3734
- .split("/")
3735
- .map((k) => k
3736
- .split("+")
3737
- .map((part) => part.charAt(0).toUpperCase() + part.slice(1))
3738
- .join("+"))
3739
- .join("/");
3740
- }
3741
4523
  /**
3742
4524
  * Get capitalized display string for an app keybinding action.
3743
4525
  */
3744
4526
  getAppKeyDisplay(action) {
3745
- return this.capitalizeKey(keyText(action));
4527
+ return keyDisplayText(action);
3746
4528
  }
3747
4529
  /**
3748
4530
  * Get capitalized display string for an editor keybinding action.
3749
4531
  */
3750
4532
  getEditorKeyDisplay(action) {
3751
- return this.capitalizeKey(keyText(action));
4533
+ return keyDisplayText(action);
3752
4534
  }
3753
4535
  handleHotkeysCommand() {
3754
4536
  // Navigation keybindings
@@ -3794,7 +4576,7 @@ export class InteractiveMode {
3794
4576
  **Navigation**
3795
4577
  | Key | Action |
3796
4578
  |-----|--------|
3797
- | \`${cursorUp}\` / \`${cursorDown}\` / \`${cursorLeft}\` / \`${cursorRight}\` | Move cursor / browse history (Up when empty) |
4579
+ | \`${cursorUp}\` / \`${cursorDown}\` / \`${cursorLeft}\` / \`${cursorRight}\` | Move cursor / browse history |
3798
4580
  | \`${cursorWordLeft}\` / \`${cursorWordRight}\` | Move by word |
3799
4581
  | \`${cursorLineStart}\` | Start of line |
3800
4582
  | \`${cursorLineEnd}\` | End of line |
@@ -3838,19 +4620,17 @@ export class InteractiveMode {
3838
4620
  `;
3839
4621
  // Add extension-registered shortcuts
3840
4622
  const extensionRunner = this.session.extensionRunner;
3841
- if (extensionRunner) {
3842
- const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
3843
- if (shortcuts.size > 0) {
3844
- hotkeys += `
4623
+ const shortcuts = extensionRunner.getShortcuts(this.keybindings.getEffectiveConfig());
4624
+ if (shortcuts.size > 0) {
4625
+ hotkeys += `
3845
4626
  **Extensions**
3846
4627
  | Key | Action |
3847
4628
  |-----|--------|
3848
4629
  `;
3849
- for (const [key, shortcut] of shortcuts) {
3850
- const description = shortcut.description ?? shortcut.extensionPath;
3851
- const keyDisplay = key.replace(/\b\w/g, (c) => c.toUpperCase());
3852
- hotkeys += `| \`${keyDisplay}\` | ${description} |\n`;
3853
- }
4630
+ for (const [key, shortcut] of shortcuts) {
4631
+ const description = shortcut.description ?? shortcut.extensionPath;
4632
+ const keyDisplay = formatKeyText(key, { capitalize: true });
4633
+ hotkeys += `| \`${keyDisplay}\` | ${description} |\n`;
3854
4634
  }
3855
4635
  }
3856
4636
  this.chatContainer.addChild(new Spacer(1));
@@ -3872,7 +4652,6 @@ export class InteractiveMode {
3872
4652
  if (result.cancelled) {
3873
4653
  return;
3874
4654
  }
3875
- await this.handleRuntimeSessionChange();
3876
4655
  this.renderCurrentSessionState();
3877
4656
  this.chatContainer.addChild(new Spacer(1));
3878
4657
  this.chatContainer.addChild(new Text(`${theme.fg("accent", "✓ New session started")}`, 1, 1));
@@ -3932,14 +4711,12 @@ export class InteractiveMode {
3932
4711
  async handleBashCommand(command, excludeFromContext = false) {
3933
4712
  const extensionRunner = this.session.extensionRunner;
3934
4713
  // Emit user_bash event to let extensions intercept
3935
- const eventResult = extensionRunner
3936
- ? await extensionRunner.emitUserBash({
3937
- type: "user_bash",
3938
- command,
3939
- excludeFromContext,
3940
- cwd: this.sessionManager.getCwd(),
3941
- })
3942
- : undefined;
4714
+ const eventResult = await extensionRunner.emitUserBash({
4715
+ type: "user_bash",
4716
+ command,
4717
+ excludeFromContext,
4718
+ cwd: this.sessionManager.getCwd(),
4719
+ });
3943
4720
  // If extension returned a full result, use it directly
3944
4721
  if (eventResult?.result) {
3945
4722
  const result = eventResult.result;
@@ -4016,6 +4793,10 @@ export class InteractiveMode {
4016
4793
  }
4017
4794
  }
4018
4795
  stop() {
4796
+ this.unregisterSignalHandlers();
4797
+ if (this.settingsManager.getShowTerminalProgress()) {
4798
+ this.ui.terminal.setProgress(false);
4799
+ }
4019
4800
  if (this.loadingAnimation) {
4020
4801
  this.loadingAnimation.stop();
4021
4802
  this.loadingAnimation = undefined;