@draht/coding-agent 2026.7.13-1 → 2026.7.30

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 (288) hide show
  1. package/CHANGELOG.md +87 -0
  2. package/README.md +1 -0
  3. package/dist/bun/cli.js +2 -0
  4. package/dist/bun/cli.js.map +1 -1
  5. package/dist/cli/args.d.ts.map +1 -1
  6. package/dist/cli/args.js +12 -2
  7. package/dist/cli/args.js.map +1 -1
  8. package/dist/cli/config-selector.js +1 -1
  9. package/dist/cli/config-selector.js.map +1 -1
  10. package/dist/cli/credential-print.d.ts +23 -0
  11. package/dist/cli/credential-print.d.ts.map +1 -0
  12. package/dist/cli/credential-print.js +116 -0
  13. package/dist/cli/credential-print.js.map +1 -0
  14. package/dist/cli/list-models.d.ts +2 -2
  15. package/dist/cli/list-models.d.ts.map +1 -1
  16. package/dist/cli/list-models.js +3 -3
  17. package/dist/cli/list-models.js.map +1 -1
  18. package/dist/cli/startup-ui.js +1 -1
  19. package/dist/cli/startup-ui.js.map +1 -1
  20. package/dist/core/agent-session-runtime.d.ts.map +1 -1
  21. package/dist/core/agent-session-runtime.js +3 -0
  22. package/dist/core/agent-session-runtime.js.map +1 -1
  23. package/dist/core/agent-session-services.d.ts +3 -6
  24. package/dist/core/agent-session-services.d.ts.map +1 -1
  25. package/dist/core/agent-session-services.js +23 -9
  26. package/dist/core/agent-session-services.js.map +1 -1
  27. package/dist/core/agent-session.d.ts +52 -11
  28. package/dist/core/agent-session.d.ts.map +1 -1
  29. package/dist/core/agent-session.js +199 -101
  30. package/dist/core/agent-session.js.map +1 -1
  31. package/dist/core/auth-storage.d.ts +15 -103
  32. package/dist/core/auth-storage.d.ts.map +1 -1
  33. package/dist/core/auth-storage.js +46 -259
  34. package/dist/core/auth-storage.js.map +1 -1
  35. package/dist/core/cache-stats.d.ts +2 -2
  36. package/dist/core/cache-stats.d.ts.map +1 -1
  37. package/dist/core/cache-stats.js +1 -1
  38. package/dist/core/cache-stats.js.map +1 -1
  39. package/dist/core/compaction/branch-summarization.d.ts +8 -2
  40. package/dist/core/compaction/branch-summarization.d.ts.map +1 -1
  41. package/dist/core/compaction/branch-summarization.js +8 -11
  42. package/dist/core/compaction/branch-summarization.js.map +1 -1
  43. package/dist/core/compaction/compaction.d.ts +19 -3
  44. package/dist/core/compaction/compaction.d.ts.map +1 -1
  45. package/dist/core/compaction/compaction.js +71 -26
  46. package/dist/core/compaction/compaction.js.map +1 -1
  47. package/dist/core/compaction/utils.d.ts +1 -1
  48. package/dist/core/compaction/utils.d.ts.map +1 -1
  49. package/dist/core/compaction/utils.js +6 -17
  50. package/dist/core/compaction/utils.js.map +1 -1
  51. package/dist/core/context-windows.d.ts +7 -0
  52. package/dist/core/context-windows.d.ts.map +1 -0
  53. package/dist/core/context-windows.js +35 -0
  54. package/dist/core/context-windows.js.map +1 -0
  55. package/dist/core/extensions/index.d.ts +1 -1
  56. package/dist/core/extensions/index.d.ts.map +1 -1
  57. package/dist/core/extensions/index.js.map +1 -1
  58. package/dist/core/extensions/loader.d.ts.map +1 -1
  59. package/dist/core/extensions/loader.js +18 -3
  60. package/dist/core/extensions/loader.js.map +1 -1
  61. package/dist/core/extensions/runner.d.ts +6 -1
  62. package/dist/core/extensions/runner.d.ts.map +1 -1
  63. package/dist/core/extensions/runner.js +80 -0
  64. package/dist/core/extensions/runner.js.map +1 -1
  65. package/dist/core/extensions/types.d.ts +48 -4
  66. package/dist/core/extensions/types.d.ts.map +1 -1
  67. package/dist/core/extensions/types.js.map +1 -1
  68. package/dist/core/extensions/wrapper.d.ts.map +1 -1
  69. package/dist/core/extensions/wrapper.js +22 -3
  70. package/dist/core/extensions/wrapper.js.map +1 -1
  71. package/dist/core/footer-data-provider.d.ts +10 -0
  72. package/dist/core/footer-data-provider.d.ts.map +1 -1
  73. package/dist/core/footer-data-provider.js +1 -1
  74. package/dist/core/footer-data-provider.js.map +1 -1
  75. package/dist/core/keybindings.d.ts +13 -3
  76. package/dist/core/keybindings.d.ts.map +1 -1
  77. package/dist/core/keybindings.js +11 -3
  78. package/dist/core/keybindings.js.map +1 -1
  79. package/dist/core/model-config.d.ts +542 -0
  80. package/dist/core/model-config.d.ts.map +1 -0
  81. package/dist/core/model-config.js +247 -0
  82. package/dist/core/model-config.js.map +1 -0
  83. package/dist/core/model-registry.d.ts +17 -123
  84. package/dist/core/model-registry.d.ts.map +1 -1
  85. package/dist/core/model-registry.js +59 -730
  86. package/dist/core/model-registry.js.map +1 -1
  87. package/dist/core/model-resolver.d.ts +7 -6
  88. package/dist/core/model-resolver.d.ts.map +1 -1
  89. package/dist/core/model-resolver.js +41 -21
  90. package/dist/core/model-resolver.js.map +1 -1
  91. package/dist/core/model-runtime.d.ts +83 -0
  92. package/dist/core/model-runtime.d.ts.map +1 -0
  93. package/dist/core/model-runtime.js +431 -0
  94. package/dist/core/model-runtime.js.map +1 -0
  95. package/dist/core/models-store.d.ts +17 -0
  96. package/dist/core/models-store.d.ts.map +1 -0
  97. package/dist/core/models-store.js +46 -0
  98. package/dist/core/models-store.js.map +1 -0
  99. package/dist/core/package-manager.d.ts.map +1 -1
  100. package/dist/core/package-manager.js +31 -12
  101. package/dist/core/package-manager.js.map +1 -1
  102. package/dist/core/prompt-templates.d.ts +1 -0
  103. package/dist/core/prompt-templates.d.ts.map +1 -1
  104. package/dist/core/prompt-templates.js +4 -4
  105. package/dist/core/prompt-templates.js.map +1 -1
  106. package/dist/core/provider-composer.d.ts +55 -0
  107. package/dist/core/provider-composer.d.ts.map +1 -0
  108. package/dist/core/provider-composer.js +375 -0
  109. package/dist/core/provider-composer.js.map +1 -0
  110. package/dist/core/radius.d.ts +2 -0
  111. package/dist/core/radius.d.ts.map +1 -0
  112. package/dist/core/radius.js +2 -0
  113. package/dist/core/radius.js.map +1 -0
  114. package/dist/core/remote-catalog-provider.d.ts +5 -0
  115. package/dist/core/remote-catalog-provider.d.ts.map +1 -0
  116. package/dist/core/remote-catalog-provider.js +115 -0
  117. package/dist/core/remote-catalog-provider.js.map +1 -0
  118. package/dist/core/resource-loader.d.ts +15 -0
  119. package/dist/core/resource-loader.d.ts.map +1 -1
  120. package/dist/core/resource-loader.js +64 -9
  121. package/dist/core/resource-loader.js.map +1 -1
  122. package/dist/core/runtime-credentials.d.ts +15 -0
  123. package/dist/core/runtime-credentials.d.ts.map +1 -0
  124. package/dist/core/runtime-credentials.js +35 -0
  125. package/dist/core/runtime-credentials.js.map +1 -0
  126. package/dist/core/sdk.d.ts +3 -6
  127. package/dist/core/sdk.d.ts.map +1 -1
  128. package/dist/core/sdk.js +22 -21
  129. package/dist/core/sdk.js.map +1 -1
  130. package/dist/core/session-manager.d.ts +14 -6
  131. package/dist/core/session-manager.d.ts.map +1 -1
  132. package/dist/core/session-manager.js +116 -28
  133. package/dist/core/session-manager.js.map +1 -1
  134. package/dist/core/settings-manager.d.ts +1 -1
  135. package/dist/core/settings-manager.d.ts.map +1 -1
  136. package/dist/core/settings-manager.js.map +1 -1
  137. package/dist/core/system-prompt.d.ts.map +1 -1
  138. package/dist/core/system-prompt.js +2 -12
  139. package/dist/core/system-prompt.js.map +1 -1
  140. package/dist/core/tools/bash.d.ts +2 -0
  141. package/dist/core/tools/bash.d.ts.map +1 -1
  142. package/dist/core/tools/bash.js +34 -5
  143. package/dist/core/tools/bash.js.map +1 -1
  144. package/dist/core/tools/read.js +1 -1
  145. package/dist/core/tools/read.js.map +1 -1
  146. package/dist/core/tools/tool-definition-wrapper.d.ts.map +1 -1
  147. package/dist/core/tools/tool-definition-wrapper.js +3 -1
  148. package/dist/core/tools/tool-definition-wrapper.js.map +1 -1
  149. package/dist/core/usage-totals.d.ts +19 -0
  150. package/dist/core/usage-totals.d.ts.map +1 -0
  151. package/dist/core/usage-totals.js +52 -0
  152. package/dist/core/usage-totals.js.map +1 -0
  153. package/dist/extensions/index.d.ts +3 -0
  154. package/dist/extensions/index.d.ts.map +1 -0
  155. package/dist/extensions/index.js +3 -0
  156. package/dist/extensions/index.js.map +1 -0
  157. package/dist/extensions/llama/client.d.ts +61 -0
  158. package/dist/extensions/llama/client.d.ts.map +1 -0
  159. package/dist/extensions/llama/client.js +300 -0
  160. package/dist/extensions/llama/client.js.map +1 -0
  161. package/dist/extensions/llama/huggingface.d.ts +23 -0
  162. package/dist/extensions/llama/huggingface.d.ts.map +1 -0
  163. package/dist/extensions/llama/huggingface.js +139 -0
  164. package/dist/extensions/llama/huggingface.js.map +1 -0
  165. package/dist/extensions/llama/index.d.ts +3 -0
  166. package/dist/extensions/llama/index.d.ts.map +1 -0
  167. package/dist/extensions/llama/index.js +208 -0
  168. package/dist/extensions/llama/index.js.map +1 -0
  169. package/dist/extensions/llama/provider.d.ts +10 -0
  170. package/dist/extensions/llama/provider.d.ts.map +1 -0
  171. package/dist/extensions/llama/provider.js +107 -0
  172. package/dist/extensions/llama/provider.js.map +1 -0
  173. package/dist/extensions/llama/ui.d.ts +42 -0
  174. package/dist/extensions/llama/ui.d.ts.map +1 -0
  175. package/dist/extensions/llama/ui.js +400 -0
  176. package/dist/extensions/llama/ui.js.map +1 -0
  177. package/dist/index.d.ts +4 -3
  178. package/dist/index.d.ts.map +1 -1
  179. package/dist/index.js +3 -3
  180. package/dist/index.js.map +1 -1
  181. package/dist/main.d.ts.map +1 -1
  182. package/dist/main.js +63 -16
  183. package/dist/main.js.map +1 -1
  184. package/dist/modes/interactive/components/assistant-message.d.ts.map +1 -1
  185. package/dist/modes/interactive/components/assistant-message.js +22 -10
  186. package/dist/modes/interactive/components/assistant-message.js.map +1 -1
  187. package/dist/modes/interactive/components/custom-editor.js +1 -1
  188. package/dist/modes/interactive/components/custom-editor.js.map +1 -1
  189. package/dist/modes/interactive/components/custom-message.d.ts +3 -1
  190. package/dist/modes/interactive/components/custom-message.d.ts.map +1 -1
  191. package/dist/modes/interactive/components/custom-message.js +9 -2
  192. package/dist/modes/interactive/components/custom-message.js.map +1 -1
  193. package/dist/modes/interactive/components/extension-editor.d.ts +1 -2
  194. package/dist/modes/interactive/components/extension-editor.d.ts.map +1 -1
  195. package/dist/modes/interactive/components/extension-editor.js +16 -46
  196. package/dist/modes/interactive/components/extension-editor.js.map +1 -1
  197. package/dist/modes/interactive/components/footer.d.ts.map +1 -1
  198. package/dist/modes/interactive/components/footer.js +24 -23
  199. package/dist/modes/interactive/components/footer.js.map +1 -1
  200. package/dist/modes/interactive/components/login-dialog.d.ts +5 -5
  201. package/dist/modes/interactive/components/login-dialog.d.ts.map +1 -1
  202. package/dist/modes/interactive/components/login-dialog.js +17 -8
  203. package/dist/modes/interactive/components/login-dialog.js.map +1 -1
  204. package/dist/modes/interactive/components/model-selector.d.ts +11 -4
  205. package/dist/modes/interactive/components/model-selector.d.ts.map +1 -1
  206. package/dist/modes/interactive/components/model-selector.js +74 -41
  207. package/dist/modes/interactive/components/model-selector.js.map +1 -1
  208. package/dist/modes/interactive/components/oauth-selector.d.ts +4 -4
  209. package/dist/modes/interactive/components/oauth-selector.d.ts.map +1 -1
  210. package/dist/modes/interactive/components/oauth-selector.js +14 -25
  211. package/dist/modes/interactive/components/oauth-selector.js.map +1 -1
  212. package/dist/modes/interactive/components/scoped-models-selector.d.ts.map +1 -1
  213. package/dist/modes/interactive/components/scoped-models-selector.js +22 -13
  214. package/dist/modes/interactive/components/scoped-models-selector.js.map +1 -1
  215. package/dist/modes/interactive/components/tree-selector.d.ts +5 -0
  216. package/dist/modes/interactive/components/tree-selector.d.ts.map +1 -1
  217. package/dist/modes/interactive/components/tree-selector.js +47 -12
  218. package/dist/modes/interactive/components/tree-selector.js.map +1 -1
  219. package/dist/modes/interactive/external-editor.d.ts +12 -0
  220. package/dist/modes/interactive/external-editor.d.ts.map +1 -0
  221. package/dist/modes/interactive/external-editor.js +37 -0
  222. package/dist/modes/interactive/external-editor.js.map +1 -0
  223. package/dist/modes/interactive/interactive-mode.d.ts +10 -7
  224. package/dist/modes/interactive/interactive-mode.d.ts.map +1 -1
  225. package/dist/modes/interactive/interactive-mode.js +369 -261
  226. package/dist/modes/interactive/interactive-mode.js.map +1 -1
  227. package/dist/modes/rpc/rpc-client.d.ts +4 -0
  228. package/dist/modes/rpc/rpc-client.d.ts.map +1 -1
  229. package/dist/modes/rpc/rpc-client.js +7 -0
  230. package/dist/modes/rpc/rpc-client.js.map +1 -1
  231. package/dist/modes/rpc/rpc-mode.d.ts.map +1 -1
  232. package/dist/modes/rpc/rpc-mode.js +20 -2
  233. package/dist/modes/rpc/rpc-mode.js.map +1 -1
  234. package/dist/modes/rpc/rpc-types.d.ts +11 -0
  235. package/dist/modes/rpc/rpc-types.d.ts.map +1 -1
  236. package/dist/modes/rpc/rpc-types.js.map +1 -1
  237. package/dist/package-manager-cli.d.ts.map +1 -1
  238. package/dist/package-manager-cli.js +67 -5
  239. package/dist/package-manager-cli.js.map +1 -1
  240. package/dist/utils/clipboard-native.d.ts +1 -0
  241. package/dist/utils/clipboard-native.d.ts.map +1 -1
  242. package/dist/utils/clipboard-native.js.map +1 -1
  243. package/dist/utils/clipboard.d.ts +2 -0
  244. package/dist/utils/clipboard.d.ts.map +1 -1
  245. package/dist/utils/clipboard.js +32 -8
  246. package/dist/utils/clipboard.js.map +1 -1
  247. package/dist/utils/version-check.d.ts.map +1 -1
  248. package/dist/utils/version-check.js +3 -1
  249. package/dist/utils/version-check.js.map +1 -1
  250. package/docs/compaction.md +9 -4
  251. package/docs/custom-provider.md +50 -16
  252. package/docs/environment-variables.md +88 -0
  253. package/docs/extensions.md +228 -15
  254. package/docs/index.md +2 -0
  255. package/docs/json.md +5 -1
  256. package/docs/keybindings.md +2 -0
  257. package/docs/llama-cpp.md +99 -0
  258. package/docs/models.md +13 -2
  259. package/docs/packages.md +1 -0
  260. package/docs/prompt-templates.md +1 -0
  261. package/docs/providers.md +36 -2
  262. package/docs/quickstart.md +1 -1
  263. package/docs/rpc.md +107 -7
  264. package/docs/sdk.md +3 -0
  265. package/docs/session-format.md +19 -3
  266. package/docs/settings.md +1 -1
  267. package/docs/tui.md +41 -26
  268. package/docs/usage.md +4 -14
  269. package/examples/extensions/custom-compaction.ts +4 -0
  270. package/examples/extensions/custom-provider-anthropic/index.ts +9 -3
  271. package/examples/extensions/custom-provider-anthropic/package.json +1 -1
  272. package/examples/extensions/custom-provider-gitlab-duo/package.json +1 -1
  273. package/examples/extensions/custom-provider-qwen-cli/package.json +1 -1
  274. package/examples/extensions/gondolin/package.json +2 -2
  275. package/examples/extensions/handoff.ts +9 -1
  276. package/examples/extensions/kimi-deferred-tools.ts +61 -0
  277. package/examples/extensions/message-renderer.ts +2 -2
  278. package/examples/extensions/sandbox/package.json +1 -1
  279. package/examples/extensions/summarize.ts +3 -0
  280. package/examples/extensions/with-deps/package.json +1 -1
  281. package/examples/sdk/02-custom-model.ts +5 -8
  282. package/examples/sdk/09-api-keys-and-oauth.ts +15 -31
  283. package/examples/sdk/12-full-control.ts +9 -12
  284. package/package.json +10 -8
  285. package/dist/core/provider-display-names.d.ts +0 -2
  286. package/dist/core/provider-display-names.d.ts.map +0 -1
  287. package/dist/core/provider-display-names.js +0 -36
  288. package/dist/core/provider-display-names.js.map +0 -1
@@ -6,7 +6,6 @@ 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 { getProviders, } from "@draht/ai/compat";
10
9
  import { CombinedAutocompleteProvider, Container, fuzzyFilter, getCapabilities, hyperlink, Markdown, matchesKey, ProcessTerminal, Spacer, setKeybindings, Text, TruncatedText, TUI, visibleWidth, } from "@draht/tui";
11
10
  import chalk from "chalk";
12
11
  import { spawn, spawnSync } from "child_process";
@@ -14,20 +13,21 @@ import { APP_NAME, APP_TITLE, CONFIG_DIR_NAME, DISPLAY_VERSION, getAgentDir, get
14
13
  import { parseSkillBlock } from "../../core/agent-session.js";
15
14
  import { SessionImportFileNotFoundError } from "../../core/agent-session-runtime.js";
16
15
  import { CACHE_TTL_MS, collectCacheMisses, computeCacheWaste, detectCacheMiss, } from "../../core/cache-stats.js";
16
+ import { formatContextWindow } from "../../core/context-windows.js";
17
17
  import { FooterDataProvider } from "../../core/footer-data-provider.js";
18
18
  import { configureHttpDispatcher, formatHttpIdleTimeoutMs } from "../../core/http-dispatcher.js";
19
19
  import { KeybindingsManager } from "../../core/keybindings.js";
20
20
  import { createCompactionSummaryMessage } from "../../core/messages.js";
21
- import { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope } from "../../core/model-resolver.js";
21
+ import { defaultModelPerProvider, findExactModelReferenceMatch, resolveModelScope, resolveModelScopeWithDiagnostics, } from "../../core/model-resolver.js";
22
22
  import { DefaultPackageManager } from "../../core/package-manager.js";
23
- import { BUILT_IN_PROVIDER_DISPLAY_NAMES } from "../../core/provider-display-names.js";
24
23
  import { formatMissingSessionCwdPrompt, MissingSessionCwdError } from "../../core/session-cwd.js";
25
24
  import { SessionManager, sessionEntryToContextMessages } from "../../core/session-manager.js";
26
25
  import { BUILTIN_SLASH_COMMANDS } from "../../core/slash-commands.js";
27
26
  import { isInstallTelemetryEnabled } from "../../core/telemetry.js";
28
27
  import { hasTrustRequiringProjectResources, ProjectTrustStore } from "../../core/trust-manager.js";
28
+ import { getUsageCostBreakdown } from "../../core/usage-totals.js";
29
29
  import { getChangelogPath, getNewEntries, normalizeChangelogLinks, parseChangelog } from "../../utils/changelog.js";
30
- import { copyToClipboard } from "../../utils/clipboard.js";
30
+ import { copyToClipboard, readClipboardText } from "../../utils/clipboard.js";
31
31
  import { extensionForImageMimeType, readClipboardImage } from "../../utils/clipboard-image.js";
32
32
  import { parseGitUrl } from "../../utils/git.js";
33
33
  import { sendTerminalNotification } from "../../utils/notify.js";
@@ -66,6 +66,7 @@ import { TreeSelectorComponent } from "./components/tree-selector.js";
66
66
  import { TrustSelectorComponent } from "./components/trust-selector.js";
67
67
  import { UserMessageComponent } from "./components/user-message.js";
68
68
  import { UserMessageSelectorComponent } from "./components/user-message-selector.js";
69
+ import { editInExternalEditor } from "./external-editor.js";
69
70
  import { getModelSearchText } from "./model-search.js";
70
71
  import { getAvailableThemes, getAvailableThemesWithPaths, getEditorTheme, getMarkdownTheme, getThemeByName, onThemeChange, setRegisteredThemes, stopThemeWatcher, Theme, theme, } from "./theme/theme.js";
71
72
  import { InteractiveThemeController } from "./theme/theme-controller.js";
@@ -93,7 +94,7 @@ function isDeadTerminalError(error) {
93
94
  const code = error.code;
94
95
  return code !== undefined && DEAD_TERMINAL_ERROR_CODES.has(code);
95
96
  }
96
- 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.";
97
+ const ANTHROPIC_SUBSCRIPTION_AUTH_WARNING = "Anthropic subscription auth is active. Third-party harness usage draws from extra usage and is billed per token, not your Claude plan limits. Manage extra usage at https://claude.ai/settings/usage. Disable this warning in /settings.";
97
98
  function isAnthropicSubscriptionAuthKey(apiKey) {
98
99
  return typeof apiKey === "string" && apiKey.startsWith("sk-ant-oat");
99
100
  }
@@ -124,17 +125,6 @@ export function formatResumeCommand(sessionManager) {
124
125
  function hasDefaultModelProvider(providerId) {
125
126
  return providerId in defaultModelPerProvider;
126
127
  }
127
- const BEDROCK_PROVIDER_ID = "amazon-bedrock";
128
- const BUILT_IN_MODEL_PROVIDERS = new Set(getProviders());
129
- export function isApiKeyLoginProvider(providerId, oauthProviderIds, builtInProviderIds = BUILT_IN_MODEL_PROVIDERS) {
130
- if (BUILT_IN_PROVIDER_DISPLAY_NAMES[providerId]) {
131
- return true;
132
- }
133
- if (builtInProviderIds.has(providerId)) {
134
- return false;
135
- }
136
- return !oauthProviderIds.has(providerId);
137
- }
138
128
  const AUTH_TYPE_ORDER = { oauth: 0, api_key: 1 };
139
129
  function createFuzzyAutocompleteItems(items, prefix, getSearchText, toAutocompleteItem) {
140
130
  const filtered = fuzzyFilter(items, prefix, getSearchText);
@@ -258,7 +248,7 @@ export class InteractiveMode {
258
248
  await this.rebindCurrentSession({ renderBeforeBind: true });
259
249
  });
260
250
  this.version = VERSION;
261
- this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor());
251
+ this.ui = new TUI(new ProcessTerminal(), this.settingsManager.getShowHardwareCursor(), getAgentDir());
262
252
  this.ui.setClearOnShrink(this.settingsManager.getClearOnShrink());
263
253
  this.headerContainer = new Container();
264
254
  this.loadedResourcesContainer = new Container();
@@ -336,11 +326,11 @@ export class InteractiveMode {
336
326
  }));
337
327
  const modelCommand = slashCommands.find((command) => command.name === "model");
338
328
  if (modelCommand) {
339
- modelCommand.getArgumentCompletions = (prefix) => {
329
+ modelCommand.getArgumentCompletions = async (prefix) => {
340
330
  // Get available models (scoped or from registry)
341
331
  const models = this.session.scopedModels.length > 0
342
332
  ? this.session.scopedModels.map((s) => s.model)
343
- : this.session.modelRegistry.getAvailable();
333
+ : await this.session.modelRuntime.getAvailable();
344
334
  if (models.length === 0)
345
335
  return null;
346
336
  // Create items with provider/id format
@@ -508,6 +498,9 @@ export class InteractiveMode {
508
498
  hint("app.suspend", "to suspend"),
509
499
  keyHint("tui.editor.deleteToLineEnd", "to delete to end"),
510
500
  hint("app.thinking.cycle", "to cycle thinking level"),
501
+ ...(this.keybindings.getKeys("app.context.cycle").length > 0
502
+ ? [hint("app.context.cycle", "to cycle context window")]
503
+ : []),
511
504
  rawKeyHint(`${keyText("app.model.cycleForward")}/${keyText("app.model.cycleBackward")}`, "to cycle models"),
512
505
  hint("app.model.select", "to select model"),
513
506
  hint("app.tools.expand", "to expand tools"),
@@ -518,7 +511,7 @@ export class InteractiveMode {
518
511
  rawKeyHint("!!", "to run bash (no context)"),
519
512
  hint("app.message.followUp", "to queue follow-up"),
520
513
  hint("app.message.dequeue", "to edit all queued messages"),
521
- hint("app.clipboard.pasteImage", "to paste image"),
514
+ hint("app.clipboard.pasteImage", "to paste image (with text fallback)"),
522
515
  rawKeyHint("drop files", "to attach"),
523
516
  ].join("\n");
524
517
  const compactInstructions = [
@@ -578,6 +571,12 @@ export class InteractiveMode {
578
571
  */
579
572
  async run() {
580
573
  await this.init();
574
+ if (!process.env.DRAHT_OFFLINE) {
575
+ void this.session.modelRuntime
576
+ .refresh()
577
+ .then(() => this.updateAvailableProviderCount())
578
+ .catch(() => { });
579
+ }
581
580
  // Start version check asynchronously
582
581
  checkForNewPiVersion(this.version).then((newRelease) => {
583
582
  if (newRelease) {
@@ -585,10 +584,18 @@ export class InteractiveMode {
585
584
  }
586
585
  });
587
586
  // Start package update check asynchronously
588
- this.checkForPackageUpdates().then((updates) => {
587
+ this.checkForPackageUpdates()
588
+ .then((updates) => {
589
589
  if (updates.length > 0) {
590
590
  this.showPackageUpdateNotification(updates);
591
591
  }
592
+ })
593
+ .finally(() => {
594
+ // On Windows, npm can overwrite the shared console title while checking
595
+ // extension package versions. Restore Pi's title after the startup check.
596
+ if (process.platform === "win32" && this.isInitialized) {
597
+ this.updateTerminalTitle();
598
+ }
592
599
  });
593
600
  // Check tmux keyboard setup asynchronously
594
601
  this.checkTmuxKeyboardSetup().then((warning) => {
@@ -601,7 +608,7 @@ export class InteractiveMode {
601
608
  if (migratedProviders && migratedProviders.length > 0) {
602
609
  this.showWarning(`Migrated credentials to auth.json: ${migratedProviders.join(", ")}`);
603
610
  }
604
- const modelsJsonError = this.session.modelRegistry.getError();
611
+ const modelsJsonError = this.session.modelRuntime.getError();
605
612
  if (modelsJsonError) {
606
613
  this.showError(`models.json error: ${modelsJsonError}`);
607
614
  }
@@ -781,8 +788,15 @@ export class InteractiveMode {
781
788
  * Get a short path relative to the package root for display.
782
789
  */
783
790
  getShortPath(fullPath, sourceInfo) {
791
+ const normalizedFullPath = fullPath.replace(/\\/g, "/");
784
792
  const baseDir = sourceInfo?.baseDir;
785
793
  if (baseDir && this.isPackageSource(sourceInfo)) {
794
+ const normalizedBaseDir = baseDir.replace(/\\/g, "/");
795
+ const npmRootMatch = normalizedBaseDir.match(/^(.*\/node_modules)\/(@?[^/]+(?:\/[^/]+)?)$/);
796
+ // If fullPath is under the same node_modules root as baseDir, preserve that relative topology.
797
+ if (npmRootMatch?.[1] && normalizedFullPath.startsWith(`${npmRootMatch[1]}/`)) {
798
+ return path.posix.relative(normalizedBaseDir, normalizedFullPath);
799
+ }
786
800
  const relativePath = path.relative(path.resolve(baseDir), path.resolve(fullPath));
787
801
  if (relativePath &&
788
802
  relativePath !== "." &&
@@ -793,11 +807,11 @@ export class InteractiveMode {
793
807
  }
794
808
  }
795
809
  const source = sourceInfo?.source ?? "";
796
- const npmMatch = fullPath.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);
810
+ const npmMatch = normalizedFullPath.match(/node_modules\/(@?[^/]+(?:\/[^/]+)?)\/(.*)/);
797
811
  if (npmMatch && source.startsWith("npm:")) {
798
812
  return npmMatch[2];
799
813
  }
800
- const gitMatch = fullPath.match(/git\/[^/]+\/[^/]+\/(.*)/);
814
+ const gitMatch = normalizedFullPath.match(/git\/[^/]+\/[^/]+\/(.*)/);
801
815
  if (gitMatch && source.startsWith("git:")) {
802
816
  return gitMatch[1];
803
817
  }
@@ -1053,7 +1067,10 @@ export class InteractiveMode {
1053
1067
  const promptsResult = this.session.resourceLoader.getPrompts();
1054
1068
  const themesResult = this.session.resourceLoader.getThemes();
1055
1069
  const extensions = options?.extensions ??
1056
- this.session.resourceLoader.getExtensions().extensions.map((extension) => ({
1070
+ this.session.resourceLoader
1071
+ .getExtensions()
1072
+ .extensions.filter((extension) => !extension.hidden)
1073
+ .map((extension) => ({
1057
1074
  path: extension.path,
1058
1075
  sourceInfo: extension.sourceInfo,
1059
1076
  }));
@@ -1079,7 +1096,12 @@ export class InteractiveMode {
1079
1096
  }
1080
1097
  }
1081
1098
  if (showListing) {
1082
- const contextFiles = this.session.resourceLoader.getAgentsFiles().agentsFiles;
1099
+ const systemPromptSource = this.session.resourceLoader.getSystemPromptSource();
1100
+ const contextFiles = [
1101
+ ...(systemPromptSource ? [systemPromptSource] : []),
1102
+ ...this.session.resourceLoader.getAppendSystemPromptSources(),
1103
+ ...this.session.resourceLoader.getAgentsFiles().agentsFiles,
1104
+ ];
1083
1105
  if (contextFiles.length > 0) {
1084
1106
  this.loadedResourcesContainer.addChild(new Spacer(1));
1085
1107
  const contextList = contextFiles
@@ -1279,16 +1301,19 @@ export class InteractiveMode {
1279
1301
  }
1280
1302
  }
1281
1303
  async rebindCurrentSession(options = {}) {
1304
+ const session = this.session;
1282
1305
  this.unsubscribe?.();
1283
1306
  this.unsubscribe = undefined;
1284
1307
  this.applyRuntimeSettings();
1285
1308
  if (options.renderBeforeBind) {
1286
1309
  this.renderCurrentSessionState();
1287
1310
  this.subscribeToAgent();
1288
- await this.bindCurrentSessionExtensions();
1289
1311
  }
1290
- else {
1291
- await this.bindCurrentSessionExtensions();
1312
+ await this.bindCurrentSessionExtensions();
1313
+ if (this.session !== session) {
1314
+ return;
1315
+ }
1316
+ if (!options.renderBeforeBind) {
1292
1317
  this.subscribeToAgent();
1293
1318
  }
1294
1319
  await this.updateAvailableProviderCount();
@@ -1332,8 +1357,10 @@ export class InteractiveMode {
1332
1357
  hasUI: true,
1333
1358
  cwd: this.sessionManager.getCwd(),
1334
1359
  sessionManager: this.sessionManager,
1335
- modelRegistry: this.session.modelRegistry,
1360
+ modelRegistry: extensionRunner.getModelRegistry(),
1336
1361
  model: this.session.model,
1362
+ scopedModels: this.session.scopedModels,
1363
+ thinkingLevel: this.session.thinkingLevel,
1337
1364
  isIdle: () => this.session.isIdle,
1338
1365
  isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
1339
1366
  signal: this.session.agent.signal,
@@ -2012,6 +2039,7 @@ export class InteractiveMode {
2012
2039
  this.defaultEditor.onCtrlD = () => this.handleCtrlD();
2013
2040
  this.defaultEditor.onAction("app.suspend", () => this.handleCtrlZ());
2014
2041
  this.defaultEditor.onAction("app.thinking.cycle", () => this.cycleThinkingLevel());
2042
+ this.defaultEditor.onAction("app.context.cycle", () => void this.cycleContextWindow());
2015
2043
  this.defaultEditor.onAction("app.model.cycleForward", () => this.cycleModel("forward"));
2016
2044
  this.defaultEditor.onAction("app.model.cycleBackward", () => this.cycleModel("backward"));
2017
2045
  // Global debug handler on TUI (works regardless of focus)
@@ -2019,7 +2047,8 @@ export class InteractiveMode {
2019
2047
  this.defaultEditor.onAction("app.model.select", () => this.showModelSelector());
2020
2048
  this.defaultEditor.onAction("app.tools.expand", () => this.toggleToolOutputExpansion());
2021
2049
  this.defaultEditor.onAction("app.thinking.toggle", () => this.toggleThinkingBlockVisibility());
2022
- this.defaultEditor.onAction("app.editor.external", () => this.openExternalEditor());
2050
+ this.defaultEditor.onAction("app.editor.external", () => void this.handleOpenExternalEditor());
2051
+ this.defaultEditor.onAction("app.message.copy", () => void this.handleCopyCommand());
2023
2052
  this.defaultEditor.onAction("app.message.followUp", () => this.handleFollowUp());
2024
2053
  this.defaultEditor.onAction("app.message.dequeue", () => this.handleDequeue());
2025
2054
  this.defaultEditor.onAction("app.session.new", () => this.handleClearCommand());
@@ -2033,26 +2062,30 @@ export class InteractiveMode {
2033
2062
  this.updateEditorBorderColor();
2034
2063
  }
2035
2064
  };
2036
- // Handle clipboard image paste (triggered on Ctrl+V)
2065
+ // Handle clipboard paste (triggered on Ctrl+V). Images are attached by path;
2066
+ // otherwise, paste plain text from the system clipboard.
2037
2067
  this.defaultEditor.onPasteImage = () => {
2038
- this.handleClipboardImagePaste();
2068
+ void this.handleClipboardPaste();
2039
2069
  };
2040
2070
  }
2041
- async handleClipboardImagePaste() {
2071
+ async handleClipboardPaste() {
2042
2072
  try {
2043
2073
  const image = await readClipboardImage();
2044
- if (!image) {
2074
+ if (image) {
2075
+ const tmpDir = os.tmpdir();
2076
+ const ext = extensionForImageMimeType(image.mimeType) ?? "png";
2077
+ const fileName = `pi-clipboard-${crypto.randomUUID()}.${ext}`;
2078
+ const filePath = path.join(tmpDir, fileName);
2079
+ fs.writeFileSync(filePath, Buffer.from(image.bytes));
2080
+ this.editor.insertTextAtCursor?.(filePath);
2081
+ this.ui.requestRender();
2045
2082
  return;
2046
2083
  }
2047
- // Write to temp file
2048
- const tmpDir = os.tmpdir();
2049
- const ext = extensionForImageMimeType(image.mimeType) ?? "png";
2050
- const fileName = `pi-clipboard-${crypto.randomUUID()}.${ext}`;
2051
- const filePath = path.join(tmpDir, fileName);
2052
- fs.writeFileSync(filePath, Buffer.from(image.bytes));
2053
- // Insert file path directly
2054
- this.editor.insertTextAtCursor?.(filePath);
2055
- this.ui.requestRender();
2084
+ const text = await readClipboardText();
2085
+ if (text) {
2086
+ this.editor.insertTextAtCursor?.(text);
2087
+ this.ui.requestRender();
2088
+ }
2056
2089
  }
2057
2090
  catch {
2058
2091
  // Silently ignore clipboard errors (may not have permission, etc.)
@@ -2292,6 +2325,10 @@ export class InteractiveMode {
2292
2325
  this.footer.invalidate();
2293
2326
  this.updateEditorBorderColor();
2294
2327
  break;
2328
+ case "context_window_changed":
2329
+ this.footer.invalidate();
2330
+ this.ui.requestRender();
2331
+ break;
2295
2332
  case "message_start":
2296
2333
  if (event.message.role === "custom") {
2297
2334
  this.addMessageToChat(event.message);
@@ -2376,6 +2413,9 @@ export class InteractiveMode {
2376
2413
  }
2377
2414
  this.ui.requestRender();
2378
2415
  break;
2416
+ case "bash_execution_update":
2417
+ // The bash execution callback handles TUI output rendering.
2418
+ break;
2379
2419
  case "tool_execution_start": {
2380
2420
  let component = this.pendingTools.get(event.toolCallId);
2381
2421
  if (!component) {
@@ -2498,6 +2538,28 @@ export class InteractiveMode {
2498
2538
  this.ui.requestRender();
2499
2539
  break;
2500
2540
  }
2541
+ case "summarization_retry_scheduled": {
2542
+ this.showError(event.errorMessage);
2543
+ this.showStatusIndicator(new RetryStatusIndicator(this.ui, event.attempt, event.maxAttempts, event.delayMs));
2544
+ this.ui.requestRender();
2545
+ break;
2546
+ }
2547
+ case "summarization_retry_attempt_start": {
2548
+ this.clearStatusIndicator("retry");
2549
+ if (event.source === "branchSummary") {
2550
+ this.showStatusIndicator(new BranchSummaryStatusIndicator(this.ui));
2551
+ }
2552
+ else {
2553
+ this.showStatusIndicator(new CompactionStatusIndicator(this.ui, event.reason));
2554
+ }
2555
+ this.ui.requestRender();
2556
+ break;
2557
+ }
2558
+ case "summarization_retry_finished": {
2559
+ this.clearStatusIndicator("retry");
2560
+ this.ui.requestRender();
2561
+ break;
2562
+ }
2501
2563
  }
2502
2564
  }
2503
2565
  /** Extract text content from a user message */
@@ -2565,7 +2627,7 @@ export class InteractiveMode {
2565
2627
  case "custom": {
2566
2628
  if (message.display) {
2567
2629
  const renderer = this.session.extensionRunner.getMessageRenderer(message.customType);
2568
- const component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings());
2630
+ const component = new CustomMessageComponent(message, renderer, this.getMarkdownThemeWithSettings(), this.outputPad);
2569
2631
  component.setExpanded(this.toolOutputExpanded);
2570
2632
  this.chatContainer.addChild(component);
2571
2633
  }
@@ -2634,7 +2696,7 @@ export class InteractiveMode {
2634
2696
  // Cache-miss notices are not persisted; re-derive them from the full entry
2635
2697
  // list and re-inject them after the assistant messages that paid for them.
2636
2698
  const cacheMisses = this.settingsManager.getShowCacheMissNotices()
2637
- ? collectCacheMisses(this.sessionManager.getEntries(), this.session.modelRegistry)
2699
+ ? collectCacheMisses(this.sessionManager.getEntries(), this.session.modelRuntime)
2638
2700
  : new Map();
2639
2701
  if (options.updateFooter) {
2640
2702
  this.footer.invalidate();
@@ -2725,7 +2787,7 @@ export class InteractiveMode {
2725
2787
  if (!this.settingsManager.getShowCacheMissNotices())
2726
2788
  return;
2727
2789
  // Entries don't contain `message` yet: message_end fires before persistence.
2728
- const miss = detectCacheMiss(this.sessionManager.getEntries(), message, this.session.modelRegistry);
2790
+ const miss = detectCacheMiss(this.sessionManager.getEntries(), message, this.session.modelRuntime);
2729
2791
  if (miss)
2730
2792
  this.addCacheMissNotice(miss);
2731
2793
  }
@@ -3020,6 +3082,56 @@ export class InteractiveMode {
3020
3082
  this.showStatus(`Thinking level: ${newLevel}`);
3021
3083
  }
3022
3084
  }
3085
+ async cycleContextWindow() {
3086
+ const model = this.session.model;
3087
+ const nextContextWindow = this.session.getNextContextWindow();
3088
+ if (!model || nextContextWindow === undefined) {
3089
+ this.showStatus("Current model has only one context window");
3090
+ return;
3091
+ }
3092
+ if (this.session.isStreaming || this.session.isCompacting) {
3093
+ this.showWarning("Wait for the current response or compaction to finish before changing the context window.");
3094
+ return;
3095
+ }
3096
+ const reserveTokens = this.settingsManager.getCompactionSettings().reserveTokens;
3097
+ const usableContextWindow = nextContextWindow - reserveTokens;
3098
+ const contextUsage = this.session.getContextUsage();
3099
+ if (nextContextWindow < model.contextWindow &&
3100
+ contextUsage?.tokens !== null &&
3101
+ contextUsage?.tokens !== undefined &&
3102
+ contextUsage.tokens > usableContextWindow) {
3103
+ const confirmed = await this.showExtensionConfirm("Compact context?", `The current context (${formatContextWindow(contextUsage.tokens)}) does not fit the ${formatContextWindow(nextContextWindow)} window with ${formatContextWindow(reserveTokens)} reserved for the response. Compact before switching?`);
3104
+ if (!confirmed) {
3105
+ this.showStatus("Context window unchanged");
3106
+ return;
3107
+ }
3108
+ try {
3109
+ const result = await this.session.compact();
3110
+ if (result.estimatedTokensAfter !== undefined && result.estimatedTokensAfter > usableContextWindow) {
3111
+ this.showWarning(`Compacted context is still too large for the ${formatContextWindow(nextContextWindow)} window.`);
3112
+ return;
3113
+ }
3114
+ }
3115
+ catch {
3116
+ return;
3117
+ }
3118
+ }
3119
+ try {
3120
+ const previousContextWindow = model.contextWindow;
3121
+ this.session.setContextWindow(nextContextWindow);
3122
+ const pricingThreshold = model.cost.tiers
3123
+ ?.map((tier) => tier.inputTokensAbove)
3124
+ .filter((threshold) => threshold >= previousContextWindow && threshold < nextContextWindow)
3125
+ .sort((a, b) => a - b)[0];
3126
+ const pricingNotice = pricingThreshold === undefined
3127
+ ? ""
3128
+ : `; higher pricing above ${formatContextWindow(pricingThreshold)} input`;
3129
+ this.showStatus(`Context window: ${formatContextWindow(nextContextWindow)}${pricingNotice}`);
3130
+ }
3131
+ catch (error) {
3132
+ this.showError(error instanceof Error ? error.message : String(error));
3133
+ }
3134
+ }
3023
3135
  async cycleModel(direction) {
3024
3136
  try {
3025
3137
  const result = await this.session.cycleModel(direction);
@@ -3055,7 +3167,7 @@ export class InteractiveMode {
3055
3167
  }
3056
3168
  }
3057
3169
  }
3058
- this.ui.requestRender();
3170
+ this.showStatus(`Tool output: ${expanded ? "expanded" : "collapsed"}`);
3059
3171
  }
3060
3172
  toggleThinkingBlockVisibility() {
3061
3173
  this.hideThinkingBlock = !this.hideThinkingBlock;
@@ -3071,51 +3183,21 @@ export class InteractiveMode {
3071
3183
  }
3072
3184
  this.showStatus(`Thinking blocks: ${this.hideThinkingBlock ? "hidden" : "visible"}`);
3073
3185
  }
3074
- async openExternalEditor() {
3186
+ async handleOpenExternalEditor() {
3075
3187
  const editorCmd = this.settingsManager.getExternalEditorCommand();
3076
- if (!editorCmd) {
3077
- this.showWarning("No editor configured. Set externalEditor in settings.json or $VISUAL/$EDITOR.");
3078
- return;
3079
- }
3080
- const currentText = this.editor.getExpandedText?.() ?? this.editor.getText();
3081
- const tmpFile = path.join(os.tmpdir(), `pi-editor-${Date.now()}.pi.md`);
3188
+ const content = this.editor.getExpandedText?.() ?? this.editor.getText();
3189
+ this.ui.stop();
3082
3190
  try {
3083
- // Write current content to temp file
3084
- fs.writeFileSync(tmpFile, currentText, "utf-8");
3085
- // Stop TUI to release terminal
3086
- this.ui.stop();
3087
- // Split by space to support editor arguments (e.g., "code --wait")
3088
- const [editor, ...editorArgs] = editorCmd.split(" ");
3089
- process.stdout.write(`Launching external editor: ${editorCmd}\nPi will resume when the editor exits.\n`);
3090
- // Do not use spawnSync here. On Windows, synchronous child_process calls can keep
3091
- // Node/libuv's console input read active after ui.stop() pauses stdin, racing
3092
- // vim/nvim for the console input buffer until Ctrl+C cancels the pending read.
3093
- const status = await new Promise((resolve) => {
3094
- const child = spawn(editor, [...editorArgs, tmpFile], {
3095
- stdio: "inherit",
3096
- shell: process.platform === "win32",
3097
- });
3098
- child.on("error", () => resolve(null));
3099
- child.on("close", (code) => resolve(code));
3191
+ const result = await editInExternalEditor({
3192
+ command: editorCmd,
3193
+ content,
3100
3194
  });
3101
- // On successful exit (status 0), replace editor content
3102
- if (status === 0) {
3103
- const newContent = fs.readFileSync(tmpFile, "utf-8").replace(/\n$/, "");
3104
- this.editor.setText(newContent);
3195
+ if (result.status === "complete") {
3196
+ this.editor.setText(result.content);
3105
3197
  }
3106
- // On non-zero exit, keep original text (no action needed)
3107
3198
  }
3108
3199
  finally {
3109
- // Clean up temp file
3110
- try {
3111
- fs.unlinkSync(tmpFile);
3112
- }
3113
- catch {
3114
- // Ignore cleanup errors
3115
- }
3116
- // Restart TUI
3117
3200
  this.ui.start();
3118
- // Force full re-render since external editor uses alternate screen
3119
3201
  this.ui.requestRender(true);
3120
3202
  }
3121
3203
  }
@@ -3302,8 +3384,10 @@ export class InteractiveMode {
3302
3384
  for (const message of preCommands) {
3303
3385
  await this.session.prompt(message.text);
3304
3386
  }
3305
- // Send first prompt (starts streaming)
3306
- const promptPromise = this.session.prompt(firstPrompt.text).catch((error) => {
3387
+ // Start a prompt when idle, or queue it into a run still finishing compaction.
3388
+ const promptPromise = this.session
3389
+ .prompt(firstPrompt.text, { streamingBehavior: firstPrompt.mode })
3390
+ .catch((error) => {
3307
3391
  restoreQueue(error);
3308
3392
  });
3309
3393
  // Queue remaining messages
@@ -3490,7 +3574,9 @@ export class InteractiveMode {
3490
3574
  this.outputPad = padding;
3491
3575
  if (this.streamingComponent || this.session.isStreaming) {
3492
3576
  for (const child of this.chatContainer.children) {
3493
- if (child instanceof AssistantMessageComponent || child instanceof UserMessageComponent) {
3577
+ if (child instanceof AssistantMessageComponent ||
3578
+ child instanceof CustomMessageComponent ||
3579
+ child instanceof UserMessageComponent) {
3494
3580
  child.setOutputPad(padding);
3495
3581
  }
3496
3582
  }
@@ -3560,18 +3646,20 @@ export class InteractiveMode {
3560
3646
  if (this.session.scopedModels.length > 0) {
3561
3647
  return this.session.scopedModels.map((scoped) => scoped.model);
3562
3648
  }
3563
- this.session.modelRegistry.refresh();
3564
3649
  try {
3565
- return await this.session.modelRegistry.getAvailable();
3650
+ await this.session.modelRuntime.refresh();
3651
+ return [...(await this.session.modelRuntime.getAvailable())];
3566
3652
  }
3567
3653
  catch {
3568
3654
  return [];
3569
3655
  }
3570
3656
  }
3571
- /** Update the footer's available provider count from current model candidates */
3572
- async updateAvailableProviderCount() {
3573
- const models = await this.getModelCandidates();
3574
- const uniqueProviders = new Set(models.map((m) => m.provider));
3657
+ /** Update the footer's available provider count from the current snapshot without refreshing catalogs. */
3658
+ updateAvailableProviderCount() {
3659
+ const models = this.session.scopedModels.length > 0
3660
+ ? this.session.scopedModels.map((scoped) => scoped.model)
3661
+ : this.session.modelRuntime.getAvailableSnapshot();
3662
+ const uniqueProviders = new Set(models.map((model) => model.provider));
3575
3663
  this.footerDataProvider.setAvailableProviderCount(uniqueProviders.size);
3576
3664
  }
3577
3665
  async maybeWarnAboutAnthropicSubscriptionAuth(model = this.session.model) {
@@ -3584,14 +3672,13 @@ export class InteractiveMode {
3584
3672
  if (!model || model.provider !== "anthropic") {
3585
3673
  return;
3586
3674
  }
3587
- const storedCredential = this.session.modelRegistry.authStorage.get("anthropic");
3588
- if (storedCredential?.type === "oauth") {
3589
- this.anthropicSubscriptionWarningShown = true;
3590
- this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);
3591
- return;
3592
- }
3593
3675
  try {
3594
- const apiKey = await this.session.modelRegistry.getApiKeyForProvider(model.provider);
3676
+ if ((await this.session.modelRuntime.checkAuth("anthropic"))?.type === "oauth") {
3677
+ this.anthropicSubscriptionWarningShown = true;
3678
+ this.showWarning(ANTHROPIC_SUBSCRIPTION_AUTH_WARNING);
3679
+ return;
3680
+ }
3681
+ const apiKey = (await this.session.modelRuntime.getAuth(model.provider))?.auth.apiKey;
3595
3682
  if (!isAnthropicSubscriptionAuthKey(apiKey)) {
3596
3683
  return;
3597
3684
  }
@@ -3649,7 +3736,7 @@ export class InteractiveMode {
3649
3736
  }
3650
3737
  showModelSelector(initialSearchInput) {
3651
3738
  this.showSelector((done) => {
3652
- const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRegistry, this.session.scopedModels, async (model) => {
3739
+ const selector = new ModelSelectorComponent(this.ui, this.session.model, this.settingsManager, this.session.modelRuntime, this.session.scopedModels, async (model) => {
3653
3740
  try {
3654
3741
  await this.session.setModel(model);
3655
3742
  this.footer.invalidate();
@@ -3672,14 +3759,19 @@ export class InteractiveMode {
3672
3759
  }
3673
3760
  async showModelsSelector() {
3674
3761
  // Get all available models
3675
- this.session.modelRegistry.refresh();
3676
- const allModels = this.session.modelRegistry.getAvailable();
3677
- if (allModels.length === 0) {
3762
+ await this.session.modelRuntime.refresh();
3763
+ const allModels = [...(await this.session.modelRuntime.getAvailable())];
3764
+ const allModelIds = new Set(allModels.map((model) => `${model.provider}/${model.id}`));
3765
+ const configuredPatterns = this.settingsManager.getEnabledModels();
3766
+ const sessionScopedModels = this.session.scopedModels;
3767
+ if (allModels.length === 0 && !configuredPatterns?.length && sessionScopedModels.length === 0) {
3678
3768
  this.showStatus("No models available");
3679
3769
  return;
3680
3770
  }
3771
+ const configuredScope = configuredPatterns?.length
3772
+ ? await resolveModelScopeWithDiagnostics(configuredPatterns, this.session.modelRuntime)
3773
+ : undefined;
3681
3774
  // Check if session has scoped models (from previous session-only changes or CLI --models)
3682
- const sessionScopedModels = this.session.scopedModels;
3683
3775
  const hasSessionScope = sessionScopedModels.length > 0;
3684
3776
  // Build enabled model IDs from session state or settings
3685
3777
  let currentEnabledIds = null;
@@ -3687,19 +3779,23 @@ export class InteractiveMode {
3687
3779
  // Use current session's scoped models
3688
3780
  currentEnabledIds = sessionScopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3689
3781
  }
3690
- else {
3691
- // Fall back to settings
3692
- const patterns = this.settingsManager.getEnabledModels();
3693
- if (patterns !== undefined && patterns.length > 0) {
3694
- const scopedModels = await resolveModelScope(patterns, this.session.modelRegistry);
3695
- currentEnabledIds = scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3696
- }
3782
+ else if (configuredScope) {
3783
+ currentEnabledIds = configuredScope.scopedModels.map((scoped) => `${scoped.model.provider}/${scoped.model.id}`);
3784
+ }
3785
+ for (const diagnostic of configuredScope?.diagnostics ?? []) {
3786
+ if (diagnostic.code !== "no-match")
3787
+ continue;
3788
+ currentEnabledIds ??= [];
3789
+ if (!currentEnabledIds.includes(diagnostic.pattern))
3790
+ currentEnabledIds.push(diagnostic.pattern);
3697
3791
  }
3698
3792
  // Helper to update session's scoped models (session-only, no persist)
3699
3793
  const updateSessionModels = async (enabledIds) => {
3700
3794
  currentEnabledIds = enabledIds === null ? null : [...enabledIds];
3701
- if (enabledIds && enabledIds.length > 0 && enabledIds.length < allModels.length) {
3702
- const newScopedModels = await resolveModelScope(enabledIds, this.session.modelRegistry);
3795
+ const hasEnabledAvailableModel = enabledIds?.some((id) => allModelIds.has(id)) ?? false;
3796
+ const allAvailableModelsEnabled = enabledIds !== null && [...allModelIds].every((id) => enabledIds.includes(id));
3797
+ if (enabledIds && hasEnabledAvailableModel && !allAvailableModelsEnabled) {
3798
+ const newScopedModels = await resolveModelScope(enabledIds, this.session.modelRuntime);
3703
3799
  this.session.setScopedModels(newScopedModels.map((sm) => ({
3704
3800
  model: sm.model,
3705
3801
  thinkingLevel: sm.thinkingLevel,
@@ -3722,9 +3818,10 @@ export class InteractiveMode {
3722
3818
  },
3723
3819
  onPersist: (enabledIds) => {
3724
3820
  // Persist to settings
3725
- const newPatterns = enabledIds === null || enabledIds.length === allModels.length
3726
- ? undefined // All enabled = clear filter
3727
- : enabledIds;
3821
+ const allEnabled = enabledIds !== null &&
3822
+ enabledIds.length === allModels.length &&
3823
+ enabledIds.every((id) => allModelIds.has(id));
3824
+ const newPatterns = enabledIds === null || allEnabled ? undefined : enabledIds;
3728
3825
  this.settingsManager.setEnabledModels(newPatterns ? [...newPatterns] : undefined);
3729
3826
  this.showStatus("Model selection saved to settings");
3730
3827
  },
@@ -3795,7 +3892,7 @@ export class InteractiveMode {
3795
3892
  this.showSelector((done) => {
3796
3893
  const selector = new TreeSelectorComponent(tree, realLeafId, this.ui.terminal.rows, async (entryId) => {
3797
3894
  // Selecting the current leaf is a no-op (already there)
3798
- if (entryId === realLeafId) {
3895
+ if (entryId === this.sessionManager.getLeafId()) {
3799
3896
  done();
3800
3897
  this.showStatus("Already at this point");
3801
3898
  return;
@@ -3830,6 +3927,11 @@ export class InteractiveMode {
3830
3927
  break;
3831
3928
  }
3832
3929
  }
3930
+ // The user committed to navigating: stop the active response first.
3931
+ if (this.session.isStreaming) {
3932
+ this.restoreQueuedMessagesToEditor();
3933
+ await this.session.abort();
3934
+ }
3833
3935
  // Set up escape handler and status indicator if summarizing
3834
3936
  let showingSummaryIndicator = false;
3835
3937
  const originalOnEscape = this.defaultEditor.onEscape;
@@ -3882,6 +3984,19 @@ export class InteractiveMode {
3882
3984
  this.sessionManager.appendLabelChange(entryId, label);
3883
3985
  this.ui.requestRender();
3884
3986
  }, initialSelectedId, initialFilterMode);
3987
+ selector.onCopy = async (text) => {
3988
+ if (!text) {
3989
+ this.showError("Selected entry has no text to copy");
3990
+ return;
3991
+ }
3992
+ try {
3993
+ await copyToClipboard(text);
3994
+ this.showStatus("Copied selected message to clipboard");
3995
+ }
3996
+ catch (error) {
3997
+ this.showError(error instanceof Error ? error.message : String(error));
3998
+ }
3999
+ };
3885
4000
  return { component: selector, focus: selector };
3886
4001
  });
3887
4002
  }
@@ -3946,44 +4061,46 @@ export class InteractiveMode {
3946
4061
  }
3947
4062
  }
3948
4063
  getLoginProviderOptions(authType) {
3949
- const authStorage = this.session.modelRegistry.authStorage;
3950
- const oauthProviders = authStorage.getOAuthProviders();
3951
- const oauthProviderIds = new Set(oauthProviders.map((provider) => provider.id));
3952
- const options = oauthProviders.map((provider) => ({
3953
- id: provider.id,
3954
- name: provider.name,
3955
- authType: "oauth",
3956
- }));
3957
- const modelProviders = new Set(this.session.modelRegistry.getAll().map((model) => model.provider));
3958
- for (const providerId of modelProviders) {
3959
- if (!isApiKeyLoginProvider(providerId, oauthProviderIds)) {
3960
- continue;
3961
- }
3962
- options.push({
3963
- id: providerId,
3964
- name: this.session.modelRegistry.getProviderDisplayName(providerId),
3965
- authType: "api_key",
3966
- });
3967
- }
3968
- const filteredOptions = authType ? options.filter((option) => option.authType === authType) : options;
3969
- return filteredOptions.sort((a, b) => a.name.localeCompare(b.name));
3970
- }
3971
- getLogoutProviderOptions() {
3972
- const authStorage = this.session.modelRegistry.authStorage;
3973
4064
  const options = [];
3974
- for (const providerId of authStorage.list()) {
3975
- const credential = authStorage.get(providerId);
3976
- if (!credential) {
3977
- continue;
4065
+ for (const provider of this.session.modelRuntime.getProviders()) {
4066
+ const authStatus = this.session.modelRuntime.getProviderAuthStatus(provider.id);
4067
+ const status = authStatus.configured
4068
+ ? {
4069
+ type: this.session.modelRuntime.isUsingOAuth(provider.id) ? "oauth" : "api_key",
4070
+ source: authStatus.label ?? authStatus.source,
4071
+ }
4072
+ : undefined;
4073
+ if ((!authType || authType === "oauth") && provider.auth.oauth) {
4074
+ options.push({
4075
+ id: provider.id,
4076
+ name: provider.name,
4077
+ authType: "oauth",
4078
+ method: provider.auth.oauth,
4079
+ status,
4080
+ });
4081
+ }
4082
+ if ((!authType || authType === "api_key") && provider.auth.apiKey) {
4083
+ options.push({
4084
+ id: provider.id,
4085
+ name: provider.name,
4086
+ authType: "api_key",
4087
+ method: provider.auth.apiKey,
4088
+ status,
4089
+ });
3978
4090
  }
3979
- options.push({
3980
- id: providerId,
3981
- name: this.session.modelRegistry.getProviderDisplayName(providerId),
3982
- authType: credential.type,
3983
- });
3984
4091
  }
3985
4092
  return options.sort((a, b) => a.name.localeCompare(b.name));
3986
4093
  }
4094
+ async getLogoutProviderOptions() {
4095
+ return (await this.session.modelRuntime.listCredentials())
4096
+ .map(({ providerId, type }) => ({
4097
+ id: providerId,
4098
+ name: this.session.modelRuntime.getProvider(providerId)?.name ?? providerId,
4099
+ authType: type,
4100
+ status: { type, source: "stored credential" },
4101
+ }))
4102
+ .sort((a, b) => a.name.localeCompare(b.name));
4103
+ }
3987
4104
  findLoginProviderOptions(providerRef) {
3988
4105
  const normalizedProviderRef = providerRef.trim().toLowerCase();
3989
4106
  if (!normalizedProviderRef) {
@@ -3993,6 +4110,7 @@ export class InteractiveMode {
3993
4110
  provider.name.toLowerCase() === normalizedProviderRef);
3994
4111
  }
3995
4112
  async handleLoginCommand(providerRef) {
4113
+ await this.session.modelRuntime.getAvailable();
3996
4114
  if (!providerRef) {
3997
4115
  this.showLoginAuthTypeSelector();
3998
4116
  return;
@@ -4015,16 +4133,18 @@ export class InteractiveMode {
4015
4133
  if (providerOption.authType === "oauth") {
4016
4134
  await this.showLoginDialog(providerOption.id, providerOption.name);
4017
4135
  }
4018
- else if (providerOption.id === BEDROCK_PROVIDER_ID) {
4019
- this.showBedrockSetupDialog(providerOption.id, providerOption.name);
4136
+ else if (providerOption.method?.login) {
4137
+ await this.showApiKeyLoginDialog(providerOption.id, providerOption.name);
4020
4138
  }
4021
4139
  else {
4022
- await this.showApiKeyLoginDialog(providerOption.id, providerOption.name);
4140
+ this.showAmbientAuthDialog(providerOption);
4023
4141
  }
4024
4142
  }
4025
4143
  showLoginAuthTypeSelector(providerOptions) {
4026
- const subscriptionLabel = "Use a subscription";
4027
- const apiKeyLabel = "Use an API key";
4144
+ const oauthProvider = providerOptions?.find((provider) => provider.authType === "oauth");
4145
+ const oauthLoginLabel = oauthProvider?.method && "loginLabel" in oauthProvider.method ? oauthProvider.method.loginLabel : undefined;
4146
+ const subscriptionLabel = oauthLoginLabel ?? "Sign in with an account";
4147
+ const apiKeyLabel = "Sign in with an API key";
4028
4148
  const availableAuthTypes = providerOptions
4029
4149
  ? new Set(providerOptions.map((provider) => provider.authType))
4030
4150
  : new Set(["oauth", "api_key"]);
@@ -4080,7 +4200,7 @@ export class InteractiveMode {
4080
4200
  return;
4081
4201
  }
4082
4202
  this.showSelector((done) => {
4083
- const selector = new OAuthSelectorComponent("login", this.session.modelRegistry.authStorage, providerOptions, async (providerId, selectedAuthType) => {
4203
+ const selector = new OAuthSelectorComponent("login", providerOptions, async (providerId, selectedAuthType) => {
4084
4204
  done();
4085
4205
  const providerOption = providerOptions.find((provider) => provider.id === providerId && provider.authType === selectedAuthType);
4086
4206
  if (!providerOption) {
@@ -4095,7 +4215,7 @@ export class InteractiveMode {
4095
4215
  else {
4096
4216
  this.ui.requestRender();
4097
4217
  }
4098
- }, (providerId) => this.session.modelRegistry.getProviderAuthStatus(providerId), initialSearchInput);
4218
+ }, initialSearchInput);
4099
4219
  return { component: selector, focus: selector };
4100
4220
  });
4101
4221
  }
@@ -4104,21 +4224,20 @@ export class InteractiveMode {
4104
4224
  this.showLoginAuthTypeSelector();
4105
4225
  return;
4106
4226
  }
4107
- const providerOptions = this.getLogoutProviderOptions();
4227
+ const providerOptions = await this.getLogoutProviderOptions();
4108
4228
  if (providerOptions.length === 0) {
4109
4229
  this.showStatus("No stored credentials to remove. /logout only removes credentials saved by /login; environment variables and models.json config are unchanged.");
4110
4230
  return;
4111
4231
  }
4112
4232
  this.showSelector((done) => {
4113
- const selector = new OAuthSelectorComponent(mode, this.session.modelRegistry.authStorage, providerOptions, async (providerId) => {
4233
+ const selector = new OAuthSelectorComponent(mode, providerOptions, async (providerId) => {
4114
4234
  done();
4115
4235
  const providerOption = providerOptions.find((provider) => provider.id === providerId);
4116
4236
  if (!providerOption) {
4117
4237
  return;
4118
4238
  }
4119
4239
  try {
4120
- this.session.modelRegistry.authStorage.logout(providerOption.id);
4121
- this.session.modelRegistry.refresh();
4240
+ await this.session.modelRuntime.logout(providerOption.id);
4122
4241
  await this.updateAvailableProviderCount();
4123
4242
  const message = providerOption.authType === "oauth"
4124
4243
  ? `Logged out of ${providerOption.name}`
@@ -4136,12 +4255,12 @@ export class InteractiveMode {
4136
4255
  });
4137
4256
  }
4138
4257
  async completeProviderAuthentication(providerId, providerName, authType, previousModel) {
4139
- this.session.modelRegistry.refresh();
4258
+ await this.session.modelRuntime.getAvailable();
4140
4259
  const actionLabel = authType === "oauth" ? `Logged in to ${providerName}` : `Saved API key for ${providerName}`;
4141
4260
  let selectedModel;
4142
4261
  let selectionError;
4143
4262
  if (isUnknownModel(previousModel)) {
4144
- const availableModels = this.session.modelRegistry.getAvailable();
4263
+ const availableModels = await this.session.modelRuntime.getAvailable();
4145
4264
  const providerModels = availableModels.filter((model) => model.provider === providerId);
4146
4265
  if (!hasDefaultModelProvider(providerId)) {
4147
4266
  selectionError = `${actionLabel}, but no default model is configured for provider "${providerId}". Use /model to select a model.`;
@@ -4185,20 +4304,15 @@ export class InteractiveMode {
4185
4304
  }
4186
4305
  }
4187
4306
  }
4188
- showBedrockSetupDialog(providerId, providerName) {
4307
+ showAmbientAuthDialog(providerOption) {
4189
4308
  const restoreEditor = () => {
4190
4309
  this.editorContainer.clear();
4191
4310
  this.editorContainer.addChild(this.editor);
4192
4311
  this.ui.setFocus(this.editor);
4193
4312
  this.ui.requestRender();
4194
4313
  };
4195
- const dialog = new LoginDialogComponent(this.ui, providerId, () => restoreEditor(), providerName, "Amazon Bedrock setup");
4196
- dialog.showInfo([
4197
- theme.fg("text", "Amazon Bedrock uses AWS credentials instead of a single API key."),
4198
- theme.fg("text", "Configure an AWS profile, IAM keys, bearer token, or role-based credentials."),
4199
- theme.fg("muted", "See:"),
4200
- theme.fg("accent", ` ${path.join(getDocsPath(), "providers.md")}`),
4201
- ]);
4314
+ const dialog = new LoginDialogComponent(this.ui, providerOption.id, () => restoreEditor(), providerOption.name, `${providerOption.name} setup`);
4315
+ dialog.showInfo(`${providerOption.method?.name ?? "Authentication"} is configured outside pi.`, [], true);
4202
4316
  this.editorContainer.clear();
4203
4317
  this.editorContainer.addChild(dialog);
4204
4318
  this.ui.setFocus(dialog);
@@ -4209,6 +4323,13 @@ export class InteractiveMode {
4209
4323
  const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
4210
4324
  // Completion handled below
4211
4325
  }, providerName);
4326
+ if (providerId === "amazon-bedrock") {
4327
+ dialog.showDetails([
4328
+ theme.fg("text", "You can also use an AWS profile, IAM keys, or role-based credentials."),
4329
+ theme.fg("muted", "See:"),
4330
+ theme.fg("accent", ` ${path.join(getDocsPath(), "providers.md")}`),
4331
+ ]);
4332
+ }
4212
4333
  this.editorContainer.clear();
4213
4334
  this.editorContainer.addChild(dialog);
4214
4335
  this.ui.setFocus(dialog);
@@ -4220,11 +4341,7 @@ export class InteractiveMode {
4220
4341
  this.ui.requestRender();
4221
4342
  };
4222
4343
  try {
4223
- const apiKey = (await dialog.showPrompt("Enter API key:")).trim();
4224
- if (!apiKey) {
4225
- throw new Error("API key cannot be empty.");
4226
- }
4227
- this.session.modelRegistry.authStorage.set(providerId, { type: "api_key", key: apiKey });
4344
+ await this.loginProvider(dialog, providerId, "api_key");
4228
4345
  restoreEditor();
4229
4346
  await this.completeProviderAuthentication(providerId, providerName, "api_key", previousModel);
4230
4347
  }
@@ -4236,8 +4353,8 @@ export class InteractiveMode {
4236
4353
  }
4237
4354
  }
4238
4355
  }
4239
- showOAuthLoginSelect(dialog, prompt) {
4240
- return new Promise((resolve) => {
4356
+ showAuthSelect(dialog, prompt) {
4357
+ return new Promise((resolve, reject) => {
4241
4358
  const restoreDialog = () => {
4242
4359
  this.editorContainer.clear();
4243
4360
  this.editorContainer.addChild(dialog);
@@ -4247,10 +4364,14 @@ export class InteractiveMode {
4247
4364
  const labels = prompt.options.map((option) => option.label);
4248
4365
  const selector = new ExtensionSelectorComponent(prompt.message, labels, (optionLabel) => {
4249
4366
  restoreDialog();
4250
- resolve(prompt.options.find((option) => option.label === optionLabel)?.id);
4367
+ const id = prompt.options.find((option) => option.label === optionLabel)?.id;
4368
+ if (id)
4369
+ resolve(id);
4370
+ else
4371
+ reject(new Error("Login cancelled"));
4251
4372
  }, () => {
4252
4373
  restoreDialog();
4253
- resolve(undefined);
4374
+ reject(new Error("Login cancelled"));
4254
4375
  });
4255
4376
  this.editorContainer.clear();
4256
4377
  this.editorContainer.addChild(selector);
@@ -4258,30 +4379,64 @@ export class InteractiveMode {
4258
4379
  this.ui.requestRender();
4259
4380
  });
4260
4381
  }
4382
+ async showAuthPrompt(dialog, prompt) {
4383
+ let response;
4384
+ if (prompt.type === "select") {
4385
+ response = this.showAuthSelect(dialog, prompt);
4386
+ }
4387
+ else if (prompt.type === "manual_code") {
4388
+ response = dialog.showManualInput(prompt.message);
4389
+ }
4390
+ else {
4391
+ response = dialog.showPrompt(prompt.message, prompt.placeholder);
4392
+ }
4393
+ if (!prompt.signal)
4394
+ return response;
4395
+ if (prompt.signal.aborted)
4396
+ throw new Error("Login cancelled");
4397
+ const signal = prompt.signal;
4398
+ let onAbort;
4399
+ const aborted = new Promise((_resolve, reject) => {
4400
+ onAbort = () => reject(new Error("Login cancelled"));
4401
+ signal.addEventListener("abort", onAbort, { once: true });
4402
+ });
4403
+ try {
4404
+ return await Promise.race([response, aborted]);
4405
+ }
4406
+ finally {
4407
+ if (onAbort)
4408
+ signal.removeEventListener("abort", onAbort);
4409
+ }
4410
+ }
4411
+ notifyAuthDialog(dialog, event) {
4412
+ if (event.type === "auth_url") {
4413
+ dialog.showAuth(event.url, event.instructions);
4414
+ }
4415
+ else if (event.type === "device_code") {
4416
+ dialog.showDeviceCode(event);
4417
+ dialog.showWaiting("Waiting for authentication...");
4418
+ }
4419
+ else if (event.type === "info") {
4420
+ dialog.showInfo(event.message, event.links);
4421
+ }
4422
+ else {
4423
+ dialog.showProgress(event.message);
4424
+ }
4425
+ }
4426
+ async loginProvider(dialog, providerId, method) {
4427
+ await this.session.modelRuntime.login(providerId, method, {
4428
+ signal: dialog.signal,
4429
+ prompt: (prompt) => this.showAuthPrompt(dialog, prompt),
4430
+ notify: (event) => this.notifyAuthDialog(dialog, event),
4431
+ });
4432
+ }
4261
4433
  async showLoginDialog(providerId, providerName) {
4262
- const providerInfo = this.session.modelRegistry.authStorage
4263
- .getOAuthProviders()
4264
- .find((provider) => provider.id === providerId);
4265
4434
  const previousModel = this.session.model;
4266
- // Providers that use callback servers (can paste redirect URL)
4267
- const usesCallbackServer = providerInfo?.usesCallbackServer ?? false;
4268
- // Create login dialog component
4269
- const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => {
4270
- // Completion handled below
4271
- }, providerName);
4272
- // Show dialog in editor container
4435
+ const dialog = new LoginDialogComponent(this.ui, providerId, (_success, _message) => { }, providerName);
4273
4436
  this.editorContainer.clear();
4274
4437
  this.editorContainer.addChild(dialog);
4275
4438
  this.ui.setFocus(dialog);
4276
4439
  this.ui.requestRender();
4277
- // Promise for manual code input (racing with callback server)
4278
- let manualCodeResolve;
4279
- let manualCodeReject;
4280
- const manualCodePromise = new Promise((resolve, reject) => {
4281
- manualCodeResolve = resolve;
4282
- manualCodeReject = reject;
4283
- });
4284
- // Restore editor helper
4285
4440
  const restoreEditor = () => {
4286
4441
  this.editorContainer.clear();
4287
4442
  this.editorContainer.addChild(this.editor);
@@ -4289,43 +4444,7 @@ export class InteractiveMode {
4289
4444
  this.ui.requestRender();
4290
4445
  };
4291
4446
  try {
4292
- await this.session.modelRegistry.authStorage.login(providerId, {
4293
- onAuth: (info) => {
4294
- dialog.showAuth(info.url, info.instructions);
4295
- if (usesCallbackServer) {
4296
- // Show input for manual paste, racing with callback
4297
- dialog
4298
- .showManualInput("Paste redirect URL below, or complete login in browser:")
4299
- .then((value) => {
4300
- if (value && manualCodeResolve) {
4301
- manualCodeResolve(value);
4302
- manualCodeResolve = undefined;
4303
- }
4304
- })
4305
- .catch(() => {
4306
- if (manualCodeReject) {
4307
- manualCodeReject(new Error("Login cancelled"));
4308
- manualCodeReject = undefined;
4309
- }
4310
- });
4311
- }
4312
- // For Anthropic: onPrompt is called immediately after
4313
- },
4314
- onDeviceCode: (info) => {
4315
- dialog.showDeviceCode(info);
4316
- dialog.showWaiting("Waiting for authentication...");
4317
- },
4318
- onPrompt: async (prompt) => {
4319
- return dialog.showPrompt(prompt.message, prompt.placeholder);
4320
- },
4321
- onProgress: (message) => {
4322
- dialog.showProgress(message);
4323
- },
4324
- onSelect: (prompt) => this.showOAuthLoginSelect(dialog, prompt),
4325
- onManualCodeInput: () => manualCodePromise,
4326
- signal: dialog.signal,
4327
- });
4328
- // Success
4447
+ await this.loginProvider(dialog, providerId, "oauth");
4329
4448
  restoreEditor();
4330
4449
  await this.completeProviderAuthentication(providerId, providerName, "oauth", previousModel);
4331
4450
  }
@@ -4413,7 +4532,7 @@ export class InteractiveMode {
4413
4532
  showDiagnosticsWhenQuiet: true,
4414
4533
  });
4415
4534
  const savedImplicitProjectTrust = this.maybeSaveImplicitProjectTrustAfterReload();
4416
- const modelsJsonError = this.session.modelRegistry.getError();
4535
+ const modelsJsonError = this.session.modelRuntime.getError();
4417
4536
  if (modelsJsonError) {
4418
4537
  this.showError(`models.json error: ${modelsJsonError}`);
4419
4538
  }
@@ -4641,25 +4760,11 @@ export class InteractiveMode {
4641
4760
  const stats = this.session.getSessionStats();
4642
4761
  const sessionName = this.sessionManager.getSessionName();
4643
4762
  const entries = this.sessionManager.getEntries();
4644
- const cacheWaste = computeCacheWaste(entries, this.session.modelRegistry);
4763
+ const cacheWaste = computeCacheWaste(entries, this.session.modelRuntime);
4645
4764
  // Cost/token totals per provider/model actually used (e.g. OpenRouter `auto`
4646
- // resolves to a concrete responseModel), sorted by cost descending.
4647
- const perModelMap = new Map();
4648
- for (const entry of entries) {
4649
- if (entry.type !== "message" || entry.message.role !== "assistant")
4650
- continue;
4651
- const message = entry.message;
4652
- const usage = message.usage;
4653
- const key = `${message.provider}/${message.responseModel ?? message.model}`;
4654
- let bucket = perModelMap.get(key);
4655
- if (!bucket) {
4656
- bucket = { key, cost: 0, tokens: 0 };
4657
- perModelMap.set(key, bucket);
4658
- }
4659
- bucket.cost += usage.cost.total;
4660
- bucket.tokens += usage.input + usage.output + usage.cacheRead + usage.cacheWrite;
4661
- }
4662
- const perModel = Array.from(perModelMap.values()).sort((a, b) => b.cost - a.cost);
4765
+ // resolves to a concrete responseModel). Usage without model attribution is
4766
+ // grouped separately so the breakdown reconciles with the session total.
4767
+ const usageBreakdown = getUsageCostBreakdown(entries);
4663
4768
  let info = `${theme.bold("Session Info")}\n\n`;
4664
4769
  if (sessionName) {
4665
4770
  info += `${theme.fg("dim", "Name:")} ${sessionName}\n`;
@@ -4690,8 +4795,8 @@ export class InteractiveMode {
4690
4795
  if (stats.cost > 0 || cacheWaste.missedTokens > 0) {
4691
4796
  info += `\n${theme.bold("Cost")}\n`;
4692
4797
  info += `${theme.fg("dim", "Total:")} $${stats.cost.toFixed(3)}`;
4693
- if (perModel.length > 1) {
4694
- for (const entry of perModel) {
4798
+ if (usageBreakdown.length > 1) {
4799
+ for (const entry of usageBreakdown) {
4695
4800
  info += `\n ${theme.fg("dim", `${entry.key}:`)} $${entry.cost.toFixed(3)} ${theme.fg("dim", `(${formatTokens(entry.tokens)} tokens)`)}`;
4696
4801
  }
4697
4802
  }
@@ -4768,12 +4873,14 @@ export class InteractiveMode {
4768
4873
  const exit = this.getAppKeyDisplay("app.exit");
4769
4874
  const suspend = this.getAppKeyDisplay("app.suspend");
4770
4875
  const cycleThinkingLevel = this.getAppKeyDisplay("app.thinking.cycle");
4876
+ const cycleContextWindow = this.getAppKeyDisplay("app.context.cycle");
4771
4877
  const cycleModelForward = this.getAppKeyDisplay("app.model.cycleForward");
4772
4878
  const selectModel = this.getAppKeyDisplay("app.model.select");
4773
4879
  const expandTools = this.getAppKeyDisplay("app.tools.expand");
4774
4880
  const toggleThinking = this.getAppKeyDisplay("app.thinking.toggle");
4775
4881
  const externalEditor = this.getAppKeyDisplay("app.editor.external");
4776
4882
  const cycleModelBackward = this.getAppKeyDisplay("app.model.cycleBackward");
4883
+ const copyMessage = this.getAppKeyDisplay("app.message.copy");
4777
4884
  const followUp = this.getAppKeyDisplay("app.message.followUp");
4778
4885
  const dequeue = this.getAppKeyDisplay("app.message.dequeue");
4779
4886
  const pasteImage = this.getAppKeyDisplay("app.clipboard.pasteImage");
@@ -4811,14 +4918,15 @@ export class InteractiveMode {
4811
4918
  | \`${exit}\` | Exit (when editor is empty) |
4812
4919
  | \`${suspend}\` | Suspend to background |
4813
4920
  | \`${cycleThinkingLevel}\` | Cycle thinking level |
4814
- | \`${cycleModelForward}\` / \`${cycleModelBackward}\` | Cycle models |
4921
+ ${cycleContextWindow ? `| \`${cycleContextWindow}\` | Cycle context window |\n` : ""}| \`${cycleModelForward}\` / \`${cycleModelBackward}\` | Cycle models |
4815
4922
  | \`${selectModel}\` | Open model selector |
4816
4923
  | \`${expandTools}\` | Toggle tool output expansion |
4817
4924
  | \`${toggleThinking}\` | Toggle thinking block visibility |
4818
4925
  | \`${externalEditor}\` | Edit message in external editor |
4926
+ | \`${copyMessage}\` | Copy last assistant message |
4819
4927
  | \`${followUp}\` | Queue follow-up message |
4820
4928
  | \`${dequeue}\` | Restore queued messages |
4821
- | \`${pasteImage}\` | Paste image from clipboard |
4929
+ | \`${pasteImage}\` | Paste image or text from clipboard |
4822
4930
  | \`/\` | Slash commands |
4823
4931
  | \`!\` | Run bash command |
4824
4932
  | \`!!\` | Run bash command (excluded from context) |