@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
@@ -14,6 +14,7 @@
14
14
  */
15
15
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
16
16
  import { basename, dirname } from "node:path";
17
+ import { contentText } from "@draht/ai";
17
18
  import { clampThinkingLevel, cleanupSessionResources, getSupportedThinkingLevels, isContextOverflow, isRetryableAssistantError, modelsAreEqual, resetApiProviders, streamSimple, } from "@draht/ai/compat";
18
19
  import { getThemeByName, theme } from "../modes/interactive/theme/theme.js";
19
20
  import { stripFrontmatter } from "../utils/frontmatter.js";
@@ -22,11 +23,13 @@ import { sleep } from "../utils/sleep.js";
22
23
  import { formatNoApiKeyFoundMessage, formatNoModelSelectedMessage } from "./auth-guidance.js";
23
24
  import { executeBashWithOperations } from "./bash-executor.js";
24
25
  import { calculateContextTokens, collectEntriesForBranchSummary, compact, estimateContextTokens, estimateTokens, generateBranchSummary, prepareCompaction, shouldCompact, } from "./compaction/index.js";
26
+ import { applyContextWindow, getAvailableContextWindows } from "./context-windows.js";
25
27
  import { DEFAULT_THINKING_LEVEL } from "./defaults.js";
26
28
  import { exportSessionToHtml } from "./export-html/index.js";
27
29
  import { createToolHtmlRenderer } from "./export-html/tool-renderer.js";
28
30
  import { ExtensionRunner, wrapRegisteredTools, } from "./extensions/index.js";
29
31
  import { emitSessionShutdownEvent } from "./extensions/runner.js";
32
+ import { ModelRegistry } from "./model-registry.js";
30
33
  import { expandPromptTemplate } from "./prompt-templates.js";
31
34
  import { CURRENT_SESSION_VERSION, getLatestCompactionEntry } from "./session-manager.js";
32
35
  import { createSyntheticSourceInfo } from "./source-info.js";
@@ -34,6 +37,7 @@ import { buildSystemPrompt } from "./system-prompt.js";
34
37
  import { createLocalBashOperations } from "./tools/bash.js";
35
38
  import { createAllToolDefinitions } from "./tools/index.js";
36
39
  import { createToolDefinitionFromAgentTool } from "./tools/tool-definition-wrapper.js";
40
+ import { addUsageToTotals, createUsageTotals } from "./usage-totals.js";
37
41
  /**
38
42
  * Parse a skill block from message text.
39
43
  * Returns null if the text doesn't contain a skill block.
@@ -49,6 +53,14 @@ export function parseSkillBlock(text) {
49
53
  userMessage: match[4]?.trim() || undefined,
50
54
  };
51
55
  }
56
+ // ============================================================================
57
+ // Types
58
+ // ============================================================================
59
+ function withoutDeletedHeaders(headers) {
60
+ return headers
61
+ ? Object.fromEntries(Object.entries(headers).filter((entry) => entry[1] !== null))
62
+ : undefined;
63
+ }
52
64
  function estimateMessagesTokens(messages) {
53
65
  let tokens = 0;
54
66
  for (const message of messages) {
@@ -84,7 +96,7 @@ export class AgentSession {
84
96
  this._retryAbortController = undefined;
85
97
  this._retryAttempt = 0;
86
98
  // Bash execution state
87
- this._bashAbortController = undefined;
99
+ this._bashAbortControllers = new Set();
88
100
  this._pendingBashMessages = [];
89
101
  this._turnIndex = 0;
90
102
  this._baseToolDefinitions = new Map();
@@ -104,7 +116,7 @@ export class AgentSession {
104
116
  // This ensures the UI sees the updated queue state
105
117
  if (event.type === "message_start" && event.message.role === "user") {
106
118
  this._overflowRecoveryAttempted = false;
107
- const messageText = this._getUserMessageText(event.message);
119
+ const messageText = contentText(event.message.content, "");
108
120
  if (messageText) {
109
121
  // Check steering queue first
110
122
  const steeringIndex = this._steeringMessages.indexOf(messageText);
@@ -167,7 +179,7 @@ export class AgentSession {
167
179
  this._resourceLoader = config.resourceLoader;
168
180
  this._customTools = config.customTools ?? [];
169
181
  this._cwd = config.cwd;
170
- this._modelRegistry = config.modelRegistry;
182
+ this._modelRuntime = config.modelRuntime;
171
183
  this._extensionRunnerRef = config.extensionRunnerRef;
172
184
  this._initialActiveToolNames = config.initialActiveToolNames;
173
185
  this._allowedToolNames = config.allowedToolNames ? new Set(config.allowedToolNames) : undefined;
@@ -184,22 +196,29 @@ export class AgentSession {
184
196
  includeAllExtensionTools: true,
185
197
  });
186
198
  }
187
- /** Model registry for API key resolution and model discovery */
188
- get modelRegistry() {
189
- return this._modelRegistry;
199
+ get modelRuntime() {
200
+ return this._modelRuntime;
190
201
  }
191
202
  async _getRequiredRequestAuth(model) {
192
- const result = await this._modelRegistry.getApiKeyAndHeaders(model);
193
- if (!result.ok) {
194
- if (result.error.startsWith("No API key found")) {
203
+ let result;
204
+ try {
205
+ result = await this._modelRuntime.getAuth(model);
206
+ }
207
+ catch (error) {
208
+ const cause = error instanceof Error ? error.cause : undefined;
209
+ if (cause instanceof Error && cause.message === "authHeader requires a resolved API key") {
195
210
  throw new Error(formatNoApiKeyFoundMessage(model.provider));
196
211
  }
197
- throw new Error(result.error);
212
+ throw error;
198
213
  }
199
- if (result.apiKey) {
200
- return { apiKey: result.apiKey, headers: result.headers, env: result.env };
214
+ if (result && (result.auth.apiKey || result.auth.headers)) {
215
+ return {
216
+ apiKey: result.auth.apiKey,
217
+ headers: withoutDeletedHeaders(result.auth.headers),
218
+ env: result.env,
219
+ };
201
220
  }
202
- const isOAuth = this._modelRegistry.isUsingOAuth(model);
221
+ const isOAuth = this._modelRuntime.isUsingOAuth(model.provider);
203
222
  if (isOAuth) {
204
223
  throw new Error(`Authentication failed for "${model.provider}". ` +
205
224
  `Credentials may have expired or network is unavailable. ` +
@@ -207,12 +226,19 @@ export class AgentSession {
207
226
  }
208
227
  throw new Error(formatNoApiKeyFoundMessage(model.provider));
209
228
  }
210
- async _getCompactionRequestAuth(model) {
211
- if (this.agent.streamFn === streamSimple) {
229
+ async _getSummarizationRequestAuth(model) {
230
+ if (this.agent.streamFunction === streamSimple) {
212
231
  return this._getRequiredRequestAuth(model);
213
232
  }
214
- const result = await this._modelRegistry.getApiKeyAndHeaders(model);
215
- return result.ok ? { apiKey: result.apiKey, headers: result.headers, env: result.env } : {};
233
+ try {
234
+ const result = await this._modelRuntime.getAuth(model);
235
+ return result
236
+ ? { apiKey: result.auth.apiKey, headers: withoutDeletedHeaders(result.auth.headers), env: result.env }
237
+ : {};
238
+ }
239
+ catch {
240
+ return {};
241
+ }
216
242
  }
217
243
  /**
218
244
  * Install tool hooks once on the Agent instance.
@@ -256,6 +282,7 @@ export class AgentSession {
256
282
  content: result.content,
257
283
  details: result.details,
258
284
  isError,
285
+ usage: result.usage,
259
286
  });
260
287
  if (!hookResult) {
261
288
  return undefined;
@@ -264,6 +291,7 @@ export class AgentSession {
264
291
  content: hookResult.content,
265
292
  details: hookResult.details,
266
293
  isError: hookResult.isError ?? isError,
294
+ usage: hookResult.usage,
267
295
  };
268
296
  };
269
297
  }
@@ -343,16 +371,6 @@ export class AgentSession {
343
371
  }
344
372
  return false;
345
373
  }
346
- /** Extract text content from a message */
347
- _getUserMessageText(message) {
348
- if (message.role !== "user")
349
- return "";
350
- const content = message.content;
351
- if (typeof content === "string")
352
- return content;
353
- const textBlocks = content.filter((c) => c.type === "text");
354
- return textBlocks.map((c) => c.text).join("");
355
- }
356
374
  /** Find the last assistant message in agent state (including aborted ones) */
357
375
  _findLastAssistantMessage() {
358
376
  const messages = this.agent.state.messages;
@@ -799,8 +817,10 @@ export class AgentSession {
799
817
  if (!this.model) {
800
818
  throw new Error(formatNoModelSelectedMessage());
801
819
  }
802
- if (!this._modelRegistry.hasConfiguredAuth(this.model)) {
803
- const isOAuth = this._modelRegistry.isUsingOAuth(this.model);
820
+ const hasConfiguredAuth = this._modelRuntime.hasConfiguredAuth(this.model.provider) ||
821
+ (await this._modelRuntime.checkAuth(this.model.provider)) !== undefined;
822
+ if (!hasConfiguredAuth) {
823
+ const isOAuth = this._modelRuntime.isUsingOAuth(this.model.provider);
804
824
  if (isOAuth) {
805
825
  throw new Error(`Authentication failed for "${this.model.provider}". ` +
806
826
  `Credentials may have expired or network is unavailable. ` +
@@ -1145,13 +1165,13 @@ export class AgentSession {
1145
1165
  * @throws Error if no auth is configured for the model
1146
1166
  */
1147
1167
  async setModel(model) {
1148
- if (!this._modelRegistry.hasConfiguredAuth(model)) {
1168
+ if (!(await this._modelRuntime.checkAuth(model.provider))) {
1149
1169
  throw new Error(`No API key for ${model.provider}/${model.id}`);
1150
1170
  }
1151
1171
  const previousModel = this.model;
1152
1172
  const thinkingLevel = this._getThinkingLevelForModelSwitch();
1153
1173
  this.agent.state.model = model;
1154
- this.sessionManager.appendModelChange(model.provider, model.id);
1174
+ this.sessionManager.appendModelChange(model.provider, model.id, model.contextWindow);
1155
1175
  this.settingsManager.setDefaultModelAndProvider(model.provider, model.id);
1156
1176
  // Re-clamp thinking level for new model's capabilities
1157
1177
  this.setThinkingLevel(thinkingLevel);
@@ -1170,7 +1190,11 @@ export class AgentSession {
1170
1190
  return this._cycleAvailableModel(direction);
1171
1191
  }
1172
1192
  async _cycleScopedModel(direction) {
1173
- const scopedModels = this._scopedModels.filter((scoped) => this._modelRegistry.hasConfiguredAuth(scoped.model));
1193
+ const checks = await Promise.all(this._scopedModels.map(async (scoped) => ({
1194
+ scoped,
1195
+ auth: await this._modelRuntime.checkAuth(scoped.model.provider),
1196
+ })));
1197
+ const scopedModels = checks.filter(({ auth }) => auth !== undefined).map(({ scoped }) => scoped);
1174
1198
  if (scopedModels.length <= 1)
1175
1199
  return undefined;
1176
1200
  const currentModel = this.model;
@@ -1183,7 +1207,7 @@ export class AgentSession {
1183
1207
  const thinkingLevel = this._getThinkingLevelForModelSwitch(next.thinkingLevel);
1184
1208
  // Apply model
1185
1209
  this.agent.state.model = next.model;
1186
- this.sessionManager.appendModelChange(next.model.provider, next.model.id);
1210
+ this.sessionManager.appendModelChange(next.model.provider, next.model.id, next.model.contextWindow);
1187
1211
  this.settingsManager.setDefaultModelAndProvider(next.model.provider, next.model.id);
1188
1212
  // Apply thinking level.
1189
1213
  // - Explicit scoped model thinking level overrides current session level
@@ -1194,7 +1218,7 @@ export class AgentSession {
1194
1218
  return { model: next.model, thinkingLevel: this.thinkingLevel, isScoped: true };
1195
1219
  }
1196
1220
  async _cycleAvailableModel(direction) {
1197
- const availableModels = await this._modelRegistry.getAvailable();
1221
+ const availableModels = await this._modelRuntime.getAvailable();
1198
1222
  if (availableModels.length <= 1)
1199
1223
  return undefined;
1200
1224
  const currentModel = this.model;
@@ -1206,7 +1230,7 @@ export class AgentSession {
1206
1230
  const nextModel = availableModels[nextIndex];
1207
1231
  const thinkingLevel = this._getThinkingLevelForModelSwitch();
1208
1232
  this.agent.state.model = nextModel;
1209
- this.sessionManager.appendModelChange(nextModel.provider, nextModel.id);
1233
+ this.sessionManager.appendModelChange(nextModel.provider, nextModel.id, nextModel.contextWindow);
1210
1234
  this.settingsManager.setDefaultModelAndProvider(nextModel.provider, nextModel.id);
1211
1235
  // Re-clamp thinking level for new model's capabilities
1212
1236
  this.setThinkingLevel(thinkingLevel);
@@ -1214,6 +1238,50 @@ export class AgentSession {
1214
1238
  return { model: nextModel, thinkingLevel: this.thinkingLevel, isScoped: false };
1215
1239
  }
1216
1240
  // =========================================================================
1241
+ // Context Window Management
1242
+ // =========================================================================
1243
+ /** Get the selectable context windows for the current model. */
1244
+ getAvailableContextWindows() {
1245
+ return this.model ? getAvailableContextWindows(this.model) : [];
1246
+ }
1247
+ /** Get the context window that would be selected by the next cycle. */
1248
+ getNextContextWindow() {
1249
+ const model = this.model;
1250
+ if (!model)
1251
+ return undefined;
1252
+ const windows = getAvailableContextWindows(model);
1253
+ if (windows.length <= 1)
1254
+ return undefined;
1255
+ const currentIndex = windows.indexOf(model.contextWindow);
1256
+ return windows[(currentIndex + 1) % windows.length];
1257
+ }
1258
+ /** Set the active context window for the current session and persist it on the session branch. */
1259
+ setContextWindow(contextWindow) {
1260
+ const model = this.model;
1261
+ if (!model)
1262
+ throw new Error(formatNoModelSelectedMessage());
1263
+ if (!this.isIdle || this.isCompacting) {
1264
+ throw new Error("Wait for the current response or compaction to finish before changing the context window");
1265
+ }
1266
+ if (!getAvailableContextWindows(model).includes(contextWindow)) {
1267
+ throw new Error(`${model.provider}/${model.id} does not support a ${contextWindow}-token context window`);
1268
+ }
1269
+ const previousContextWindow = model.contextWindow;
1270
+ if (contextWindow === previousContextWindow)
1271
+ return;
1272
+ this.agent.state.model = { ...model, contextWindow };
1273
+ this.sessionManager.appendModelChange(model.provider, model.id, contextWindow);
1274
+ this._emit({ type: "context_window_changed", contextWindow, previousContextWindow });
1275
+ }
1276
+ /** Cycle to the next context window, or return undefined when the model has only one. */
1277
+ cycleContextWindow() {
1278
+ const nextContextWindow = this.getNextContextWindow();
1279
+ if (nextContextWindow === undefined)
1280
+ return undefined;
1281
+ this.setContextWindow(nextContextWindow);
1282
+ return nextContextWindow;
1283
+ }
1284
+ // =========================================================================
1217
1285
  // Thinking Level Management
1218
1286
  // =========================================================================
1219
1287
  /**
@@ -1322,7 +1390,7 @@ export class AgentSession {
1322
1390
  if (!this.model) {
1323
1391
  throw new Error(formatNoModelSelectedMessage());
1324
1392
  }
1325
- const { apiKey, headers, env } = await this._getCompactionRequestAuth(this.model);
1393
+ const { apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model);
1326
1394
  const pathEntries = this.sessionManager.getBranch();
1327
1395
  const settings = this.settingsManager.getCompactionSettings();
1328
1396
  const preparation = prepareCompaction(pathEntries, settings);
@@ -1357,26 +1425,29 @@ export class AgentSession {
1357
1425
  let summary;
1358
1426
  let firstKeptEntryId;
1359
1427
  let tokensBefore;
1428
+ let usage;
1360
1429
  let details;
1361
1430
  if (extensionCompaction) {
1362
1431
  // Extension provided compaction content
1363
1432
  summary = extensionCompaction.summary;
1364
1433
  firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1365
1434
  tokensBefore = extensionCompaction.tokensBefore;
1435
+ usage = extensionCompaction.usage;
1366
1436
  details = extensionCompaction.details;
1367
1437
  }
1368
1438
  else {
1369
1439
  // Generate compaction result
1370
- const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal, this.thinkingLevel, this.agent.streamFn, env);
1440
+ const result = await compact(preparation, this.model, apiKey, headers, customInstructions, this._compactionAbortController.signal, this.thinkingLevel, this.agent.streamFunction, env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason: "manual" }));
1371
1441
  summary = result.summary;
1372
1442
  firstKeptEntryId = result.firstKeptEntryId;
1373
1443
  tokensBefore = result.tokensBefore;
1444
+ usage = result.usage;
1374
1445
  details = result.details;
1375
1446
  }
1376
1447
  if (this._compactionAbortController.signal.aborted) {
1377
1448
  throw new Error("Compaction cancelled");
1378
1449
  }
1379
- this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1450
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1380
1451
  const newEntries = this.sessionManager.getEntries();
1381
1452
  const sessionContext = this.sessionManager.buildSessionContext();
1382
1453
  this.agent.state.messages = sessionContext.messages;
@@ -1397,6 +1468,7 @@ export class AgentSession {
1397
1468
  firstKeptEntryId,
1398
1469
  tokensBefore,
1399
1470
  estimatedTokensAfter,
1471
+ usage,
1400
1472
  details,
1401
1473
  };
1402
1474
  this._emit({
@@ -1543,17 +1615,11 @@ export class AgentSession {
1543
1615
  let apiKey;
1544
1616
  let headers;
1545
1617
  let env;
1546
- if (this.agent.streamFn === streamSimple) {
1547
- const authResult = await this._modelRegistry.getApiKeyAndHeaders(this.model);
1548
- if (!authResult.ok || !authResult.apiKey) {
1549
- return false;
1550
- }
1551
- apiKey = authResult.apiKey;
1552
- headers = authResult.headers;
1553
- env = authResult.env;
1618
+ if (this.agent.streamFunction === streamSimple) {
1619
+ ({ apiKey, headers, env } = await this._getRequiredRequestAuth(this.model));
1554
1620
  }
1555
1621
  else {
1556
- ({ apiKey, headers, env } = await this._getCompactionRequestAuth(this.model));
1622
+ ({ apiKey, headers, env } = await this._getSummarizationRequestAuth(this.model));
1557
1623
  }
1558
1624
  const pathEntries = this.sessionManager.getBranch();
1559
1625
  const preparation = prepareCompaction(pathEntries, settings);
@@ -1593,20 +1659,23 @@ export class AgentSession {
1593
1659
  let summary;
1594
1660
  let firstKeptEntryId;
1595
1661
  let tokensBefore;
1662
+ let usage;
1596
1663
  let details;
1597
1664
  if (extensionCompaction) {
1598
1665
  // Extension provided compaction content
1599
1666
  summary = extensionCompaction.summary;
1600
1667
  firstKeptEntryId = extensionCompaction.firstKeptEntryId;
1601
1668
  tokensBefore = extensionCompaction.tokensBefore;
1669
+ usage = extensionCompaction.usage;
1602
1670
  details = extensionCompaction.details;
1603
1671
  }
1604
1672
  else {
1605
1673
  // Generate compaction result
1606
- const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal, this.thinkingLevel, this.agent.streamFn, env);
1674
+ const compactResult = await compact(preparation, this.model, apiKey, headers, undefined, this._autoCompactionAbortController.signal, this.thinkingLevel, this.agent.streamFunction, env, this.settingsManager.getRetrySettings(), this._summarizationRetryCallbacks({ source: "compaction", reason }));
1607
1675
  summary = compactResult.summary;
1608
1676
  firstKeptEntryId = compactResult.firstKeptEntryId;
1609
1677
  tokensBefore = compactResult.tokensBefore;
1678
+ usage = compactResult.usage;
1610
1679
  details = compactResult.details;
1611
1680
  }
1612
1681
  if (this._autoCompactionAbortController.signal.aborted) {
@@ -1619,7 +1688,7 @@ export class AgentSession {
1619
1688
  });
1620
1689
  return false;
1621
1690
  }
1622
- this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension);
1691
+ this.sessionManager.appendCompaction(summary, firstKeptEntryId, tokensBefore, details, fromExtension, usage);
1623
1692
  const newEntries = this.sessionManager.getEntries();
1624
1693
  const sessionContext = this.sessionManager.buildSessionContext();
1625
1694
  this.agent.state.messages = sessionContext.messages;
@@ -1640,6 +1709,7 @@ export class AgentSession {
1640
1709
  firstKeptEntryId,
1641
1710
  tokensBefore,
1642
1711
  estimatedTokensAfter,
1712
+ usage,
1643
1713
  details,
1644
1714
  };
1645
1715
  this._emit({ type: "compaction_end", reason, result, aborted: false, willRetry });
@@ -1761,11 +1831,11 @@ export class AgentSession {
1761
1831
  if (!currentModel) {
1762
1832
  return;
1763
1833
  }
1764
- const refreshedModel = this._modelRegistry.find(currentModel.provider, currentModel.id);
1834
+ const refreshedModel = this._modelRuntime.getModel(currentModel.provider, currentModel.id);
1765
1835
  if (!refreshedModel || refreshedModel === currentModel) {
1766
1836
  return;
1767
1837
  }
1768
- this.agent.state.model = refreshedModel;
1838
+ this.agent.state.model = applyContextWindow(refreshedModel, currentModel.contextWindow);
1769
1839
  }
1770
1840
  _bindExtensionCore(runner) {
1771
1841
  const getCommands = () => {
@@ -1830,7 +1900,7 @@ export class AgentSession {
1830
1900
  refreshTools: () => this._refreshToolRegistry(),
1831
1901
  getCommands,
1832
1902
  setModel: async (model) => {
1833
- if (!this.modelRegistry.hasConfiguredAuth(model))
1903
+ if (!this._modelRuntime.hasConfiguredAuth(model.provider))
1834
1904
  return false;
1835
1905
  await this.setModel(model);
1836
1906
  return true;
@@ -1839,6 +1909,7 @@ export class AgentSession {
1839
1909
  setThinkingLevel: (level) => this.setThinkingLevel(level),
1840
1910
  }, {
1841
1911
  getModel: () => this.model,
1912
+ getScopedModels: () => this._scopedModels,
1842
1913
  isIdle: () => this.isIdle,
1843
1914
  isProjectTrusted: () => this.settingsManager.isProjectTrusted(),
1844
1915
  getSignal: () => this.agent.signal,
@@ -1870,11 +1941,15 @@ export class AgentSession {
1870
1941
  getSystemPromptOptions: () => this._baseSystemPromptOptions,
1871
1942
  }, {
1872
1943
  registerProvider: (name, config) => {
1873
- this._modelRegistry.registerProvider(name, config);
1944
+ this._modelRuntime.registerProvider(name, config);
1945
+ this._refreshCurrentModelFromRegistry();
1946
+ },
1947
+ registerNativeProvider: (provider) => {
1948
+ this._modelRuntime.registerNativeProvider(provider);
1874
1949
  this._refreshCurrentModelFromRegistry();
1875
1950
  },
1876
1951
  unregisterProvider: (name) => {
1877
- this._modelRegistry.unregisterProvider(name);
1952
+ this._modelRuntime.unregisterProvider(name);
1878
1953
  this._refreshCurrentModelFromRegistry();
1879
1954
  },
1880
1955
  });
@@ -1976,7 +2051,7 @@ export class AgentSession {
1976
2051
  extensionsResult.runtime.flagValues.set(name, value);
1977
2052
  }
1978
2053
  }
1979
- this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, this._modelRegistry);
2054
+ this._extensionRunner = new ExtensionRunner(extensionsResult.extensions, extensionsResult.runtime, this._cwd, this.sessionManager, new ModelRegistry(this._modelRuntime));
1980
2055
  if (this._extensionRunnerRef) {
1981
2056
  this._extensionRunnerRef.current = this._extensionRunner;
1982
2057
  }
@@ -2026,6 +2101,34 @@ export class AgentSession {
2026
2101
  return false;
2027
2102
  return isRetryableAssistantError(message);
2028
2103
  }
2104
+ /**
2105
+ * Retry policy + callbacks shared by compaction and branch-summary summarization calls.
2106
+ * Uses the same `settings.retry` budget/backoff as agent-turn retries so a single transient
2107
+ * stream drop no longer fails the whole operation. `source` carries the context
2108
+ * the TUI needs to render the retry and recreate the underlying indicator.
2109
+ */
2110
+ _summarizationRetryCallbacks(source) {
2111
+ return {
2112
+ onRetryScheduled: (attempt, maxAttempts, delayMs, errorMessage) => {
2113
+ this._emit({
2114
+ type: "summarization_retry_scheduled",
2115
+ attempt,
2116
+ maxAttempts,
2117
+ delayMs,
2118
+ errorMessage,
2119
+ });
2120
+ },
2121
+ onRetryAttemptStart: () => {
2122
+ this._emit({
2123
+ type: "summarization_retry_attempt_start",
2124
+ ...source,
2125
+ });
2126
+ },
2127
+ onRetryFinished: () => {
2128
+ this._emit({ type: "summarization_retry_finished" });
2129
+ },
2130
+ };
2131
+ }
2029
2132
  /**
2030
2133
  * Prepare a retryable error for continuation with exponential backoff.
2031
2134
  * @returns true if the caller should continue the agent, false otherwise
@@ -2105,24 +2208,29 @@ export class AgentSession {
2105
2208
  * @param command The bash command to execute
2106
2209
  * @param onChunk Optional streaming callback for output
2107
2210
  * @param options.excludeFromContext If true, command output won't be sent to LLM (!! prefix)
2211
+ * @param options.id Optional identifier included in bash execution update events
2108
2212
  * @param options.operations Custom BashOperations for remote execution
2109
2213
  */
2110
2214
  async executeBash(command, onChunk, options) {
2111
- this._bashAbortController = new AbortController();
2215
+ const abortController = new AbortController();
2216
+ this._bashAbortControllers.add(abortController);
2112
2217
  // Apply command prefix if configured (e.g., "shopt -s expand_aliases" for alias support)
2113
2218
  const prefix = this.settingsManager.getShellCommandPrefix();
2114
2219
  const shellPath = this.settingsManager.getShellPath();
2115
2220
  const resolvedCommand = prefix ? `${prefix}\n${command}` : command;
2116
2221
  try {
2117
2222
  const result = await executeBashWithOperations(resolvedCommand, this.sessionManager.getCwd(), options?.operations ?? createLocalBashOperations({ shellPath }), {
2118
- onChunk,
2119
- signal: this._bashAbortController.signal,
2223
+ onChunk: (delta) => {
2224
+ onChunk?.(delta);
2225
+ this._emit({ type: "bash_execution_update", id: options?.id, delta });
2226
+ },
2227
+ signal: abortController.signal,
2120
2228
  });
2121
2229
  this.recordBashResult(command, result, options);
2122
2230
  return result;
2123
2231
  }
2124
2232
  finally {
2125
- this._bashAbortController = undefined;
2233
+ this._bashAbortControllers.delete(abortController);
2126
2234
  }
2127
2235
  }
2128
2236
  /**
@@ -2157,11 +2265,13 @@ export class AgentSession {
2157
2265
  * Cancel running bash command.
2158
2266
  */
2159
2267
  abortBash() {
2160
- this._bashAbortController?.abort();
2268
+ for (const abortController of [...this._bashAbortControllers]) {
2269
+ abortController.abort();
2270
+ }
2161
2271
  }
2162
2272
  /** Whether a bash command is currently running */
2163
2273
  get isBashRunning() {
2164
- return this._bashAbortController !== undefined;
2274
+ return this._bashAbortControllers.size > 0;
2165
2275
  }
2166
2276
  /** Whether there are pending bash messages waiting to be flushed */
2167
2277
  get hasPendingBashMessages() {
@@ -2209,6 +2319,9 @@ export class AgentSession {
2209
2319
  * @returns Result with editorText (if user message) and cancelled status
2210
2320
  */
2211
2321
  async navigateTree(targetId, options = {}) {
2322
+ if (this.isStreaming) {
2323
+ throw new Error("Wait for the current response to finish before navigating the session tree.");
2324
+ }
2212
2325
  const oldLeafId = this.sessionManager.getLeafId();
2213
2326
  // No-op if already at target
2214
2327
  if (targetId === oldLeafId) {
@@ -2271,9 +2384,10 @@ export class AgentSession {
2271
2384
  // Run default summarizer if needed
2272
2385
  let summaryText;
2273
2386
  let summaryDetails;
2387
+ let summaryUsage;
2274
2388
  if (options.summarize && entriesToSummarize.length > 0 && !extensionSummary) {
2275
2389
  const model = this.model;
2276
- const { apiKey, headers, env } = await this._getRequiredRequestAuth(model);
2390
+ const { apiKey, headers, env } = await this._getSummarizationRequestAuth(model);
2277
2391
  const branchSummarySettings = this.settingsManager.getBranchSummarySettings();
2278
2392
  const result = await generateBranchSummary(entriesToSummarize, {
2279
2393
  model,
@@ -2284,7 +2398,9 @@ export class AgentSession {
2284
2398
  customInstructions,
2285
2399
  replaceInstructions,
2286
2400
  reserveTokens: branchSummarySettings.reserveTokens,
2287
- streamFn: this.agent.streamFn,
2401
+ streamFn: this.agent.streamFunction,
2402
+ retry: this.settingsManager.getRetrySettings(),
2403
+ callbacks: this._summarizationRetryCallbacks({ source: "branchSummary" }),
2288
2404
  });
2289
2405
  if (result.aborted) {
2290
2406
  return { cancelled: true, aborted: true };
@@ -2293,6 +2409,7 @@ export class AgentSession {
2293
2409
  throw new Error(result.error);
2294
2410
  }
2295
2411
  summaryText = result.summary;
2412
+ summaryUsage = result.usage;
2296
2413
  summaryDetails = {
2297
2414
  readFiles: result.readFiles || [],
2298
2415
  modifiedFiles: result.modifiedFiles || [],
@@ -2301,6 +2418,7 @@ export class AgentSession {
2301
2418
  else if (extensionSummary) {
2302
2419
  summaryText = extensionSummary.summary;
2303
2420
  summaryDetails = extensionSummary.details;
2421
+ summaryUsage = extensionSummary.usage;
2304
2422
  }
2305
2423
  // Determine the new leaf position based on target type
2306
2424
  let newLeafId;
@@ -2308,18 +2426,12 @@ export class AgentSession {
2308
2426
  if (targetEntry.type === "message" && targetEntry.message.role === "user") {
2309
2427
  // User message: leaf = parent (null if root), text goes to editor
2310
2428
  newLeafId = targetEntry.parentId;
2311
- editorText = this._extractUserMessageText(targetEntry.message.content);
2429
+ editorText = contentText(targetEntry.message.content, "");
2312
2430
  }
2313
2431
  else if (targetEntry.type === "custom_message") {
2314
2432
  // Custom message: leaf = parent (null if root), text goes to editor
2315
2433
  newLeafId = targetEntry.parentId;
2316
- editorText =
2317
- typeof targetEntry.content === "string"
2318
- ? targetEntry.content
2319
- : targetEntry.content
2320
- .filter((c) => c.type === "text")
2321
- .map((c) => c.text)
2322
- .join("");
2434
+ editorText = contentText(targetEntry.content, "");
2323
2435
  }
2324
2436
  else {
2325
2437
  // Non-user message: leaf = selected node
@@ -2330,7 +2442,7 @@ export class AgentSession {
2330
2442
  let summaryEntry;
2331
2443
  if (summaryText) {
2332
2444
  // Create summary at target position (can be null for root)
2333
- const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension);
2445
+ const summaryId = this.sessionManager.branchWithSummary(newLeafId, summaryText, summaryDetails, fromExtension, summaryUsage);
2334
2446
  summaryEntry = this.sessionManager.getEntry(summaryId);
2335
2447
  // Attach label to the summary entry
2336
2448
  if (label) {
@@ -2378,24 +2490,13 @@ export class AgentSession {
2378
2490
  continue;
2379
2491
  if (entry.message.role !== "user")
2380
2492
  continue;
2381
- const text = this._extractUserMessageText(entry.message.content);
2493
+ const text = contentText(entry.message.content, "");
2382
2494
  if (text) {
2383
2495
  result.push({ entryId: entry.id, text });
2384
2496
  }
2385
2497
  }
2386
2498
  return result;
2387
2499
  }
2388
- _extractUserMessageText(content) {
2389
- if (typeof content === "string")
2390
- return content;
2391
- if (Array.isArray(content)) {
2392
- return content
2393
- .filter((c) => c.type === "text")
2394
- .map((c) => c.text)
2395
- .join("");
2396
- }
2397
- return "";
2398
- }
2399
2500
  /**
2400
2501
  * Get session statistics. Aggregates over ALL session entries (including
2401
2502
  * history that was compacted away), so token/cost totals reflect what was
@@ -2407,12 +2508,11 @@ export class AgentSession {
2407
2508
  let toolResults = 0;
2408
2509
  let totalMessages = 0;
2409
2510
  let toolCalls = 0;
2410
- let totalInput = 0;
2411
- let totalOutput = 0;
2412
- let totalCacheRead = 0;
2413
- let totalCacheWrite = 0;
2414
- let totalCost = 0;
2511
+ const usageTotals = createUsageTotals();
2415
2512
  for (const entry of this.sessionManager.getEntries()) {
2513
+ if ((entry.type === "branch_summary" || entry.type === "compaction") && entry.usage) {
2514
+ addUsageToTotals(usageTotals, entry.usage);
2515
+ }
2416
2516
  if (entry.type !== "message")
2417
2517
  continue;
2418
2518
  totalMessages++;
@@ -2422,6 +2522,9 @@ export class AgentSession {
2422
2522
  }
2423
2523
  else if (message.role === "toolResult") {
2424
2524
  toolResults++;
2525
+ if (message.usage) {
2526
+ addUsageToTotals(usageTotals, message.usage);
2527
+ }
2425
2528
  }
2426
2529
  else if (message.role === "assistant") {
2427
2530
  assistantMessages++;
@@ -2429,12 +2532,7 @@ export class AgentSession {
2429
2532
  if (Array.isArray(assistantMsg.content)) {
2430
2533
  toolCalls += assistantMsg.content.filter((c) => c.type === "toolCall").length;
2431
2534
  }
2432
- const usage = assistantMsg.usage;
2433
- totalInput += usage.input;
2434
- totalOutput += usage.output;
2435
- totalCacheRead += usage.cacheRead;
2436
- totalCacheWrite += usage.cacheWrite;
2437
- totalCost += usage.cost.total;
2535
+ addUsageToTotals(usageTotals, assistantMsg.usage);
2438
2536
  }
2439
2537
  }
2440
2538
  return {
@@ -2446,13 +2544,13 @@ export class AgentSession {
2446
2544
  toolResults,
2447
2545
  totalMessages,
2448
2546
  tokens: {
2449
- input: totalInput,
2450
- output: totalOutput,
2451
- cacheRead: totalCacheRead,
2452
- cacheWrite: totalCacheWrite,
2453
- total: totalInput + totalOutput + totalCacheRead + totalCacheWrite,
2547
+ input: usageTotals.input,
2548
+ output: usageTotals.output,
2549
+ cacheRead: usageTotals.cacheRead,
2550
+ cacheWrite: usageTotals.cacheWrite,
2551
+ total: usageTotals.input + usageTotals.output + usageTotals.cacheRead + usageTotals.cacheWrite,
2454
2552
  },
2455
- cost: totalCost,
2553
+ cost: usageTotals.cost,
2456
2554
  contextUsage: this.getContextUsage(),
2457
2555
  };
2458
2556
  }