@causyne/agent 1.20.121 → 1.20.122

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 (256) hide show
  1. package/README.md +3 -3
  2. package/package.json +1 -1
  3. package/src/acp/agentCatalog.js +81 -26
  4. package/src/acp/agentCatalog.ts +73 -29
  5. package/src/acp/client.js +210 -53
  6. package/src/acp/client.ts +202 -52
  7. package/src/acp/peerProfiles.js +55 -22
  8. package/src/acp/peerProfiles.ts +51 -22
  9. package/src/acp/protocol.js +37 -8
  10. package/src/acp/protocol.ts +30 -8
  11. package/src/acp/server.js +123 -25
  12. package/src/acp/server.ts +124 -24
  13. package/src/agent/errorClassifier.js +6 -2
  14. package/src/agent/errorClassifier.ts +6 -2
  15. package/src/agentLoop.js +11 -5
  16. package/src/agentLoop.ts +11 -5
  17. package/src/approvalGrants.js +19 -7
  18. package/src/approvalGrants.ts +20 -7
  19. package/src/approvalPolicy.js +48 -15
  20. package/src/approvalPolicy.ts +46 -15
  21. package/src/autoUpdate.js +5 -2
  22. package/src/autoUpdate.ts +5 -2
  23. package/src/browser/causyneBrowser.js +3 -2
  24. package/src/browser/causyneBrowser.ts +3 -2
  25. package/src/browser/searchProviders.js +1 -1
  26. package/src/browser/searchProviders.ts +1 -1
  27. package/src/config.js +287 -250
  28. package/src/config.ts +342 -0
  29. package/src/configVault.js +84 -17
  30. package/src/configVault.ts +77 -17
  31. package/src/continuum/compactor.js +2 -1
  32. package/src/continuum/compactor.ts +2 -1
  33. package/src/continuum/sanitizer.js +10 -3
  34. package/src/continuum/sanitizer.ts +9 -3
  35. package/src/continuum/ui/continuumPickerView.js +3 -2
  36. package/src/continuum/ui/continuumPickerView.ts +3 -2
  37. package/src/cortex/vectorDb.js +26 -15
  38. package/src/cortex/vectorDb.ts +26 -16
  39. package/src/creative/liveBridge.js +7 -5
  40. package/src/creative/liveBridge.ts +7 -5
  41. package/src/creative/studioScripts.js +16 -5
  42. package/src/creative/studioScripts.ts +14 -5
  43. package/src/decisionPolicy.js +16 -4
  44. package/src/decisionPolicy.ts +14 -4
  45. package/src/documentEngine/antiSlopAuditor.js +10 -5
  46. package/src/documentEngine/antiSlopAuditor.ts +11 -5
  47. package/src/documentEngine/documentForge.js +47 -15
  48. package/src/documentEngine/documentForge.ts +43 -14
  49. package/src/engines/design.js +2 -1
  50. package/src/engines/design.ts +2 -1
  51. package/src/engines/film.js +4 -4
  52. package/src/engines/film.ts +2 -2
  53. package/src/engines/light.js +2 -1
  54. package/src/engines/light.ts +2 -1
  55. package/src/engines/registry.js +1 -1
  56. package/src/engines/registry.ts +1 -1
  57. package/src/engines/reverseHarness.js +4 -3
  58. package/src/engines/reverseHarness.ts +4 -3
  59. package/src/headlessCli.js +2 -1
  60. package/src/headlessCli.ts +2 -1
  61. package/src/historyPruner.js +3 -2
  62. package/src/historyPruner.ts +3 -2
  63. package/src/hooks.js +3 -0
  64. package/src/hooks.ts +3 -0
  65. package/src/implementationPlan.js +21 -11
  66. package/src/implementationPlan.ts +21 -11
  67. package/src/infra/atomicWriter.js +4 -1
  68. package/src/infra/atomicWriter.ts +4 -1
  69. package/src/launchIntent.js +1 -1
  70. package/src/launchIntent.ts +1 -1
  71. package/src/memory/scopedFacts.js +1 -1
  72. package/src/memory/scopedFacts.ts +1 -1
  73. package/src/memory/symbolFolder.js +1 -1
  74. package/src/memory/symbolFolder.ts +1 -1
  75. package/src/modelRouter.js +1 -1
  76. package/src/modelRouter.ts +1 -1
  77. package/src/observer/evidence.js +10 -4
  78. package/src/observer/evidence.ts +10 -4
  79. package/src/osKeychain.js +62 -8
  80. package/src/osKeychain.ts +50 -8
  81. package/src/perception.js +3 -2
  82. package/src/perception.ts +3 -2
  83. package/src/planCache.js +2 -2
  84. package/src/planCache.ts +2 -2
  85. package/src/pluginsFactory/pluginsFactory.js +19 -11
  86. package/src/pluginsFactory/pluginsFactory.ts +18 -11
  87. package/src/promptMentions.js +2 -2
  88. package/src/promptMentions.ts +2 -2
  89. package/src/providers/acp.js +1 -1
  90. package/src/providers/acp.ts +1 -1
  91. package/src/providers/anthropic.js +327 -401
  92. package/src/providers/anthropic.ts +386 -0
  93. package/src/providers/antigravity.js +10 -4
  94. package/src/providers/antigravity.ts +10 -4
  95. package/src/providers/base.js +221 -319
  96. package/src/providers/base.ts +340 -0
  97. package/src/providers/byokHttp.js +58 -15
  98. package/src/providers/byokHttp.ts +59 -16
  99. package/src/providers/byokStream.js +142 -51
  100. package/src/providers/byokStream.ts +146 -42
  101. package/src/providers/dashscope-byok.js +97 -89
  102. package/src/providers/dashscope-byok.ts +114 -0
  103. package/src/providers/deepseek.js +73 -72
  104. package/src/providers/deepseek.ts +99 -0
  105. package/src/providers/factory.js +35 -28
  106. package/src/providers/factory.ts +40 -0
  107. package/src/providers/gemini.js +227 -278
  108. package/src/providers/gemini.ts +261 -0
  109. package/src/providers/loopGuard.js +9 -5
  110. package/src/providers/loopGuard.ts +10 -5
  111. package/src/providers/moonshot.js +70 -72
  112. package/src/providers/moonshot.ts +93 -0
  113. package/src/providers/muse.js +82 -152
  114. package/src/providers/muse.ts +122 -0
  115. package/src/providers/ollama.js +114 -106
  116. package/src/providers/ollama.ts +135 -0
  117. package/src/providers/openai-compatible.js +113 -96
  118. package/src/providers/openai-compatible.ts +139 -0
  119. package/src/providers/openai.js +22 -15
  120. package/src/providers/openai.ts +30 -0
  121. package/src/providers/openrouter.js +136 -74
  122. package/src/providers/openrouter.ts +133 -72
  123. package/src/providers/pi.js +6 -0
  124. package/src/providers/pi.ts +6 -0
  125. package/src/providers/qwen-byok.js +96 -87
  126. package/src/providers/qwen-byok.ts +113 -0
  127. package/src/providers/toolContracts.js +40 -14
  128. package/src/providers/toolContracts.ts +35 -14
  129. package/src/providers/wireNormalizer.js +78 -11
  130. package/src/providers/wireNormalizer.ts +68 -12
  131. package/src/providers/xai.js +73 -72
  132. package/src/providers/xai.ts +97 -0
  133. package/src/reliability/assetEvidence.js +4 -2
  134. package/src/reliability/assetEvidence.ts +4 -2
  135. package/src/sandbox.js +489 -554
  136. package/src/sandbox.ts +552 -0
  137. package/src/sandboxPolicy.js +95 -16
  138. package/src/sandboxPolicy.ts +97 -16
  139. package/src/sessionJournal.js +8 -3
  140. package/src/sessionJournal.ts +9 -3
  141. package/src/skills/skillResourceSafety.js +19 -8
  142. package/src/skills/skillResourceSafety.ts +16 -7
  143. package/src/skillsManager.js +3 -3
  144. package/src/skillsManager.ts +3 -3
  145. package/src/smartToolsUse.js +28 -4
  146. package/src/smartToolsUse.ts +29 -7
  147. package/src/stallGuard.js +45 -22
  148. package/src/stallGuard.ts +46 -22
  149. package/src/subagentJournal.js +6 -4
  150. package/src/subagentJournal.ts +6 -4
  151. package/src/textDiff.js +6 -1
  152. package/src/textDiff.ts +6 -1
  153. package/src/timeMachine.js +7 -1
  154. package/src/timeMachine.ts +7 -1
  155. package/src/tokenTracker.js +43 -28
  156. package/src/tokenTracker.ts +44 -30
  157. package/src/toolPacks.js +3 -1
  158. package/src/toolPacks.ts +3 -1
  159. package/src/tools/archive.js +245 -35
  160. package/src/tools/archive.ts +244 -35
  161. package/src/tools/computerUse.js +7 -3
  162. package/src/tools/computerUse.ts +7 -3
  163. package/src/tools/creativeApps.js +13 -8
  164. package/src/tools/creativeApps.ts +22 -9
  165. package/src/tools/deferredMcpSearch.js +26 -14
  166. package/src/tools/deferredMcpSearch.ts +26 -14
  167. package/src/tools/desktopOpen.js +69 -10
  168. package/src/tools/desktopOpen.ts +70 -11
  169. package/src/tools/documentForge.js +167 -82
  170. package/src/tools/documentForge.ts +169 -84
  171. package/src/tools/fsEdit.js +101 -30
  172. package/src/tools/fsEdit.ts +105 -32
  173. package/src/tools/fsFind.js +8 -5
  174. package/src/tools/fsFind.ts +7 -4
  175. package/src/tools/fsRead.js +119 -13
  176. package/src/tools/fsRead.ts +124 -13
  177. package/src/tools/fsWrite.js +17 -5
  178. package/src/tools/fsWrite.ts +17 -7
  179. package/src/tools/generateMediaViaApi.js +82 -19
  180. package/src/tools/generateMediaViaApi.ts +80 -19
  181. package/src/tools/memoryRecall.js +62 -11
  182. package/src/tools/memoryRecall.ts +70 -13
  183. package/src/tools/memoryWrite.js +27 -14
  184. package/src/tools/memoryWrite.ts +30 -14
  185. package/src/tools/multiEdit.js +100 -30
  186. package/src/tools/multiEdit.ts +104 -32
  187. package/src/tools/nativeEngine.js +33 -18
  188. package/src/tools/nativeEngine.ts +31 -18
  189. package/src/tools/openSourceToolProvisioner.js +49 -14
  190. package/src/tools/openSourceToolProvisioner.ts +54 -15
  191. package/src/tools/osSandbox.js +54 -14
  192. package/src/tools/osSandbox.ts +48 -14
  193. package/src/tools/payloadSanitizer.js +40 -8
  194. package/src/tools/payloadSanitizer.ts +39 -8
  195. package/src/tools/peerAgent.js +96 -34
  196. package/src/tools/peerAgent.ts +114 -37
  197. package/src/tools/pluginsFactory.js +38 -6
  198. package/src/tools/pluginsFactory.ts +42 -6
  199. package/src/tools/readNativeSkill.js +10 -8
  200. package/src/tools/readNativeSkill.ts +10 -8
  201. package/src/tools/requestDecision.js +10 -3
  202. package/src/tools/requestDecision.ts +10 -3
  203. package/src/tools/resolveAutomator.js +91 -17
  204. package/src/tools/resolveAutomator.ts +102 -17
  205. package/src/tools/reverseEngineering.js +168 -41
  206. package/src/tools/reverseEngineering.ts +161 -41
  207. package/src/tools/sysRun.js +69 -29
  208. package/src/tools/sysRun.ts +66 -24
  209. package/src/tools/toolDispatch.js +24 -1
  210. package/src/tools/toolDispatch.ts +21 -1
  211. package/src/tools/toolOutputStore.js +62 -23
  212. package/src/tools/toolOutputStore.ts +56 -23
  213. package/src/tools/toolScanner.js +13 -10
  214. package/src/tools/toolScanner.ts +13 -10
  215. package/src/tools/toolSelfRepair.js +94 -28
  216. package/src/tools/toolSelfRepair.ts +96 -28
  217. package/src/tools/uiForge.js +71 -6
  218. package/src/tools/uiForge.ts +74 -6
  219. package/src/tools/viewImage.js +62 -17
  220. package/src/tools/viewImage.ts +57 -12
  221. package/src/tools/visionInspector.js +15 -3
  222. package/src/tools/visionInspector.ts +15 -3
  223. package/src/tools/walkerSafety.js +2 -0
  224. package/src/tools/walkerSafety.ts +1 -0
  225. package/src/tools/webFetch.js +105 -10
  226. package/src/tools/webFetch.ts +105 -11
  227. package/src/tui/banner.js +3 -2
  228. package/src/tui/banner.ts +3 -2
  229. package/src/tui/consoleGuard.js +12 -4
  230. package/src/tui/consoleGuard.ts +9 -4
  231. package/src/tui/messageInteraction.js +2 -3
  232. package/src/tui/messageInteraction.ts +2 -3
  233. package/src/tui/modelPicker.js +1 -0
  234. package/src/tui/modelPicker.ts +1 -0
  235. package/src/tui/overlay.js +3 -1
  236. package/src/tui/overlay.ts +3 -1
  237. package/src/tui/sessionPicker.js +3 -2
  238. package/src/tui/sessionPicker.ts +3 -2
  239. package/src/tui/sessionPickerView.js +7 -1
  240. package/src/tui/sessionPickerView.ts +6 -1
  241. package/src/tui/toolOutputNormalizer.js +2 -3
  242. package/src/tui/toolOutputNormalizer.ts +4 -3
  243. package/src/tui/viewport.js +4 -4
  244. package/src/tui/viewport.ts +5 -5
  245. package/src/tui/workspaceIdentity.js +2 -1
  246. package/src/tui/workspaceIdentity.ts +2 -1
  247. package/src/uncertainty.js +8 -3
  248. package/src/uncertainty.ts +8 -3
  249. package/src/utils/paths.js +8 -5
  250. package/src/utils/paths.ts +9 -7
  251. package/src/vfeTracker.js +9 -3
  252. package/src/vfeTracker.ts +9 -3
  253. package/src/config.d.ts +0 -2
  254. package/src/providers/base.d.ts +0 -94
  255. package/src/providers/factory.d.ts +0 -1
  256. package/src/sandbox.d.ts +0 -1
@@ -2,436 +2,362 @@ import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
4
  import { scanAndAdaptToolsForProvider, normalizeToolName } from '../tools/toolScanner.js';
5
- import {
6
- prepareMessagesForAnthropic,
7
- safeParseJsonObject,
8
- sanitizeProviderToolId,
9
- serializeAndDecodeArguments
10
- } from './wireNormalizer.js';
11
- import {
12
- requireApiKey,
13
- resolveTemperature,
14
- safeProviderFetchJson
15
- } from './byokHttp.js';
5
+ import { prepareMessagesForAnthropic, safeParseJsonObject, sanitizeProviderToolId, serializeAndDecodeArguments } from './wireNormalizer.js';
6
+ import { requireApiKey, resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
16
7
  import { streamAnthropicMessages, wantsStreaming } from './byokStream.js';
17
-
18
- // Models that support server-side tool search (defer_loading + tool_reference
19
- // expansion). On these, Causyne hands Anthropic the complete 69-tool catalogue
20
- // and lets the API keep deferred schemas out of the context window entirely —
21
- // full capability, none of the token cost. Older models fall back to the
22
- // client-side progressive disclosure in src/toolPacks.js.
23
8
  const TOOL_SEARCH_MODELS = [
24
- 'claude-3-7-sonnet',
25
- 'claude-3-5-sonnet',
26
- 'claude-3-5-haiku',
27
- 'claude-3-opus',
28
- 'claude-fable-5',
29
- 'claude-mythos-5',
30
- 'claude-opus-5',
31
- 'claude-opus-4-8',
32
- 'claude-opus-4-7',
33
- 'claude-opus-4-6',
34
- 'claude-sonnet-4-6',
35
- 'claude-opus-4-5',
36
- 'claude-sonnet-4-5',
37
- 'claude-haiku-4-5'
9
+ 'claude-3-7-sonnet',
10
+ 'claude-3-5-sonnet',
11
+ 'claude-3-5-haiku',
12
+ 'claude-3-opus',
13
+ 'claude-fable-5',
14
+ 'claude-mythos-5',
15
+ 'claude-opus-5',
16
+ 'claude-opus-4-8',
17
+ 'claude-opus-4-7',
18
+ 'claude-opus-4-6',
19
+ 'claude-sonnet-4-6',
20
+ 'claude-opus-4-5',
21
+ 'claude-sonnet-4-5',
22
+ 'claude-haiku-4-5'
38
23
  ];
39
-
40
- // Sampling parameters (temperature / top_p / top_k) were removed from these
41
- // models and now return a 400. Sending temperature unconditionally meant every
42
- // request on the current frontier line-up failed outright — the very models
43
- // listed in TOOL_SEARCH_MODELS above. Depth is controlled with effort instead.
44
24
  const NO_SAMPLING_MODELS = [
45
- 'claude-fable-5',
46
- 'claude-mythos-5',
47
- 'claude-opus-5',
48
- 'claude-opus-4-8',
49
- 'claude-opus-4-7',
50
- 'claude-sonnet-5'
25
+ 'claude-fable-5',
26
+ 'claude-mythos-5',
27
+ 'claude-opus-5',
28
+ 'claude-opus-4-8',
29
+ 'claude-opus-4-7',
30
+ 'claude-sonnet-5'
51
31
  ];
52
-
53
- // Models that accept an operator instruction as a `system` entry inside
54
- // messages[] rather than only in the top-level system block. Keeping a
55
- // mid-conversation nudge in sequence preserves both its meaning and the cached
56
- // prefix; hoisting it to the front changed when the model thought it applied.
57
32
  const MID_CONVERSATION_SYSTEM_MODELS = [
58
- 'claude-fable-5',
59
- 'claude-mythos-5',
60
- 'claude-opus-5',
61
- 'claude-opus-4-8'
33
+ 'claude-fable-5',
34
+ 'claude-mythos-5',
35
+ 'claude-opus-5',
36
+ 'claude-opus-4-8'
62
37
  ];
63
-
64
- // Models that take adaptive thinking. On these, `budget_tokens` is REJECTED
65
- // with a 400 — the fixed-budget parameter many agents still send was removed,
66
- // and depth is controlled with `output_config.effort` instead.
67
- //
68
- // Two of these behave differently on omission, which is the whole reason this
69
- // list exists: Claude Opus 5 and Fable 5 think by default, but Opus 4.8/4.7,
70
- // Sonnet 5 and the 4.6 pair run with NO thinking unless `{type:'adaptive'}` is
71
- // sent explicitly. Causyne was sending nothing, so on those models the single
72
- // largest lever on frontier-model quality was simply switched off — directly
73
- // which prevents the configured model from using its intended reasoning mode.
74
38
  const ADAPTIVE_THINKING_MODELS = [
75
- 'claude-fable-5',
76
- 'claude-mythos-5',
77
- 'claude-opus-5',
78
- 'claude-opus-4-8',
79
- 'claude-opus-4-7',
80
- 'claude-opus-4-6',
81
- 'claude-sonnet-5',
82
- 'claude-sonnet-4-6'
39
+ 'claude-fable-5',
40
+ 'claude-mythos-5',
41
+ 'claude-opus-5',
42
+ 'claude-opus-4-8',
43
+ 'claude-opus-4-7',
44
+ 'claude-opus-4-6',
45
+ 'claude-sonnet-5',
46
+ 'claude-sonnet-4-6'
83
47
  ];
84
-
85
- // Models that think by default, so adaptive need not be requested. Sending it
86
- // anyway is harmless; sending {type:'disabled'} to them is what changes
87
- // behaviour, and on Fable 5 that is a 400.
88
48
  const THINKS_BY_DEFAULT_MODELS = [
89
- 'claude-fable-5',
90
- 'claude-mythos-5',
91
- 'claude-opus-5'
49
+ 'claude-fable-5',
50
+ 'claude-mythos-5',
51
+ 'claude-opus-5'
92
52
  ];
93
-
94
- // Models that reject any explicit thinking configuration at all.
95
53
  const THINKING_ALWAYS_ON_MODELS = [
96
- 'claude-fable-5',
97
- 'claude-mythos-5'
54
+ 'claude-fable-5',
55
+ 'claude-mythos-5'
98
56
  ];
99
-
100
- // `output_config.effort`. Opus 4.5 accepts only low/medium/high; the adaptive
101
- // family adds xhigh and max. Sonnet 4.5 and Haiku 4.5 reject effort outright.
102
57
  const EFFORT_MODELS = [...ADAPTIVE_THINKING_MODELS, 'claude-opus-4-5'];
103
58
  const LIMITED_EFFORT_MODELS = ['claude-opus-4-5', 'claude-opus-4-6', 'claude-sonnet-4-6'];
104
59
  const EFFORT_LEVELS = ['low', 'medium', 'high', 'xhigh', 'max'];
105
-
106
60
  function modelMatches(model, list) {
107
- const normalized = (model || '').toLowerCase();
108
- return list.some(supported => normalized.startsWith(supported));
61
+ const normalized = (model || '').toLowerCase();
62
+ return list.some(supported => normalized.startsWith(supported));
109
63
  }
110
-
111
64
  export class AnthropicProvider extends LLMProvider {
112
- constructor(config) {
113
- super(config);
114
- this.baseUrl = 'https://api.anthropic.com/v1/messages';
115
- this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['anthropic']);
116
- this.visionModels = ['*'];
117
- // Anthropic reads images on every model but accepts no audio input at all.
118
- this.audioModels = [];
119
- this.imagePayloadFormat = 'anthropic';
120
- this.enableToolSearch = config.enableToolSearch !== false;
121
- this.enableCaching = config.enablePromptCaching !== false;
122
- // Agent tasks routinely run far longer than the 5-minute default cache
123
- // lifetime. Re-writing a ~5,000-token prefix at 1.25x every time the window
124
- // lapses costs more than writing it once at 2.0x with a 1-hour lifetime, so
125
- // the extended TTL is the cheaper default for this workload.
126
- this.cacheTtl = config.promptCacheTtl || '1h';
127
-
128
- // 'low' | 'medium' | 'high' | 'xhigh' | 'max' | 'off'. Unset means: let the
129
- // API pick its own default depth, and still turn thinking ON for the models
130
- // where omission would silently disable it.
131
- this.reasoningEffort = config.reasoningEffort || null;
132
- // Surface the reasoning summary to the user. Off by default — it is extra
133
- // output tokens on every turn, and this project runs on the user's own key.
134
- this.showReasoning = config.showReasoning === true;
135
- // Only consulted for pre-adaptive models.
136
- this.reasoningBudgetTokens = config.reasoningBudgetTokens || null;
137
- }
138
-
139
- cacheControl() {
140
- return this.cacheTtl === '5m'
141
- ? { type: 'ephemeral' }
142
- : { type: 'ephemeral', ttl: this.cacheTtl };
143
- }
144
-
145
- supportsToolSearch() {
146
- if (!this.enableToolSearch) return false;
147
- return modelMatches(this.model, TOOL_SEARCH_MODELS);
148
- }
149
-
150
- /** True when this model rejects temperature / top_p / top_k with a 400. */
151
- rejectsSamplingParameters() {
152
- return modelMatches(this.model, NO_SAMPLING_MODELS);
153
- }
154
-
155
- /** True when this model takes `thinking: {type:'adaptive'}`. */
156
- supportsAdaptiveThinking() {
157
- return modelMatches(this.model, ADAPTIVE_THINKING_MODELS);
158
- }
159
-
160
- /**
161
- * Resolve the configured reasoning effort to something this model accepts.
162
- * Returns null when effort must not be sent at all.
163
- */
164
- resolveEffort() {
165
- if (!modelMatches(this.model, EFFORT_MODELS)) return null;
166
- const requested = String(this.reasoningEffort || '').toLowerCase();
167
- if (!EFFORT_LEVELS.includes(requested)) return null;
168
- if (modelMatches(this.model, LIMITED_EFFORT_MODELS) && (requested === 'xhigh' || requested === 'max')) {
169
- // These models stop at 'high'; asking for more is a 400, so clamp rather
170
- // than fail the whole request over a preference.
171
- return 'high';
65
+ enableToolSearch;
66
+ enableCaching;
67
+ cacheTtl;
68
+ reasoningEffort;
69
+ showReasoning;
70
+ reasoningBudgetTokens;
71
+ allowInsecureHttp;
72
+ constructor(config = {}) {
73
+ super(config);
74
+ const customUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
75
+ this.baseUrl = customUrl || 'https://api.anthropic.com/v1/messages';
76
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
77
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['anthropic']) || '');
78
+ this.visionModels = ['*'];
79
+ this.audioModels = [];
80
+ this.imagePayloadFormat = 'anthropic';
81
+ this.preserveThinkingBlocks = true;
82
+ this.enableToolSearch = config.enableToolSearch !== false;
83
+ this.enableCaching = config.enablePromptCaching !== false;
84
+ this.cacheTtl = config.promptCacheTtl === '5m' ? '5m' : '1h';
85
+ this.reasoningEffort = config.reasoningEffort || null;
86
+ this.showReasoning = config.showReasoning === true;
87
+ this.reasoningBudgetTokens = typeof config.reasoningBudgetTokens === 'number' ? config.reasoningBudgetTokens : null;
172
88
  }
173
- return requested;
174
- }
175
-
176
- /**
177
- * The `thinking` parameter for this model, or null to omit it.
178
- *
179
- * Omission is meaningful and model-dependent, which is why this is a method
180
- * and not a constant: on Fable 5 any explicit value is a 400; on Opus 5
181
- * omitting still thinks; on Opus 4.8/4.7 and the Sonnets omitting means no
182
- * thinking at all.
183
- */
184
- buildThinking() {
185
- if (modelMatches(this.model, THINKING_ALWAYS_ON_MODELS)) return null;
186
-
187
- if (this.reasoningEffort === 'off') {
188
- // Only meaningful where thinking would otherwise be on. Note the Opus 5
189
- // caveat: disabling is accepted only at effort 'high' or below.
190
- if (!modelMatches(this.model, THINKS_BY_DEFAULT_MODELS)) return null;
191
- const effort = this.resolveEffort();
192
- if (effort === 'xhigh' || effort === 'max') return null;
193
- return { type: 'disabled' };
89
+ cacheControl() {
90
+ return this.cacheTtl === '5m'
91
+ ? { type: 'ephemeral' }
92
+ : { type: 'ephemeral', ttl: this.cacheTtl };
194
93
  }
195
-
196
- if (this.supportsAdaptiveThinking()) {
197
- const thinking = { type: 'adaptive' };
198
-
199
- // long silence instead of the agent's reasoning.
200
- if (this.showReasoning) thinking.display = 'summarized';
201
- return thinking;
94
+ supportsToolSearch() {
95
+ if (!this.enableToolSearch)
96
+ return false;
97
+ return modelMatches(this.model, TOOL_SEARCH_MODELS);
202
98
  }
203
-
204
- // Pre-adaptive models still use a fixed budget. It must be below max_tokens
205
- // and at least 1024, or the request errors.
206
- if (this.reasoningBudgetTokens) {
207
- return { type: 'enabled', budget_tokens: this.reasoningBudgetTokens };
99
+ rejectsSamplingParameters() {
100
+ return modelMatches(this.model, NO_SAMPLING_MODELS);
208
101
  }
209
- return null;
210
- }
211
-
212
- /** True when a mid-conversation operator instruction may stay in sequence. */
213
- supportsMidConversationSystem() {
214
- return modelMatches(this.model, MID_CONVERSATION_SYSTEM_MODELS);
215
- }
216
-
217
- async chat(messages, options = {}) {
218
- messages = prepareMessagesForAnthropic(this, messages);
219
- // Anthropic separates the system prompt from the message list.
220
- const systemBlocks = [];
221
- const anthropicMessages = [];
222
-
223
- // Anthropic accepts at most 4 cache_control breakpoints per request. The
224
- // agent loop anchors up to three stable system blocks and one is reserved
225
- // for the last tool, so system anchors are capped at 3 here — an extra
226
- // anchor added upstream can never push the request over the limit (a 400).
227
- const MAX_SYSTEM_CACHE_BREAKPOINTS = 3;
228
- let systemCacheBreakpoints = 0;
229
-
230
- const allowInlineSystem = this.supportsMidConversationSystem();
231
-
232
- for (const msg of messages) {
233
- if (msg.role === 'system') {
234
- // The leading system stack is the prompt itself and always belongs in
235
- // the top-level `system` field. A system message that arrives *after*
236
- // the conversation has started is an operator nudge; hoisting it to the
237
- // front moved it out of the sequence it was meant to apply to. On models
238
- // that accept it, keep it in place — it must follow a user turn and sit
239
- // last, which is exactly where the agent loop emits it.
240
- const isMidConversation = anthropicMessages.length > 0;
241
- const lastEmitted = anthropicMessages[anthropicMessages.length - 1];
242
- if (isMidConversation && allowInlineSystem && lastEmitted?.role === 'user') {
243
- anthropicMessages.push({ role: 'system', content: String(msg.content ?? '') });
244
- continue;
245
- }
246
-
247
- const block = { type: 'text', text: String(msg.content ?? '') };
248
- // Stable system blocks are cache anchors; everything volatile is ordered
249
- // after them by the agent loop, which is what makes the prefix cacheable.
250
- // Capped so the reserved tool breakpoint always fits within Anthropic's 4.
251
- if (msg.cacheAnchor && this.enableCaching && systemCacheBreakpoints < MAX_SYSTEM_CACHE_BREAKPOINTS) {
252
- block.cache_control = this.cacheControl();
253
- systemCacheBreakpoints++;
254
- }
255
- systemBlocks.push(block);
256
- } else if (msg.role === 'tool') {
257
- // Translate OpenAI tool response → Anthropic tool_result block
258
- const toolResultBlock = {
259
- type: 'tool_result',
260
- tool_use_id: sanitizeProviderToolId(msg.tool_call_id, 'toolu', 0),
261
- content: msg.content ?? ''
262
- };
263
- // Anthropic requires consecutive tool_results to be grouped into a single 'user' message
264
- const lastMsg = anthropicMessages[anthropicMessages.length - 1];
265
- if (lastMsg && lastMsg.role === 'user' && Array.isArray(lastMsg.content) && lastMsg.content[0]?.type === 'tool_result') {
266
- lastMsg.content.push(toolResultBlock);
267
- } else {
268
- anthropicMessages.push({ role: 'user', content: [toolResultBlock] });
102
+ supportsAdaptiveThinking() {
103
+ return modelMatches(this.model, ADAPTIVE_THINKING_MODELS);
104
+ }
105
+ resolveEffort() {
106
+ if (!modelMatches(this.model, EFFORT_MODELS))
107
+ return null;
108
+ const requested = String(this.reasoningEffort || '').toLowerCase();
109
+ if (!EFFORT_LEVELS.includes(requested))
110
+ return null;
111
+ if (modelMatches(this.model, LIMITED_EFFORT_MODELS) && (requested === 'xhigh' || requested === 'max')) {
112
+ return 'high';
269
113
  }
270
- } else if (msg.role === 'assistant' && msg.tool_calls) {
271
- // Translate OpenAI assistant tool_calls → Anthropic tool_use content blocks
272
- const contentBlocks = [];
273
- // Thinking blocks must be echoed back UNCHANGED and FIRST when the turn
274
- // they belong to carries tool_use. Dropping them is what breaks a
275
- // thinking-enabled tool loop; other models ignore them silently, so
276
- // replaying them is safe in every direction.
277
- if (Array.isArray(msg.thinking_blocks)) {
278
- contentBlocks.push(...msg.thinking_blocks);
114
+ return requested;
115
+ }
116
+ buildThinking() {
117
+ if (modelMatches(this.model, THINKING_ALWAYS_ON_MODELS))
118
+ return null;
119
+ if (this.reasoningEffort === 'off') {
120
+ if (!modelMatches(this.model, THINKS_BY_DEFAULT_MODELS))
121
+ return null;
122
+ const effort = this.resolveEffort();
123
+ if (effort === 'xhigh' || effort === 'max')
124
+ return null;
125
+ return { type: 'disabled' };
279
126
  }
280
- if (msg.content) {
281
- contentBlocks.push({ type: 'text', text: msg.content });
127
+ if (this.supportsAdaptiveThinking()) {
128
+ const thinking = { type: 'adaptive' };
129
+ if (this.showReasoning)
130
+ thinking['display'] = 'summarized';
131
+ return thinking;
282
132
  }
283
- for (let idx = 0; idx < msg.tool_calls.length; idx++) {
284
- const tc = msg.tool_calls[idx];
285
- contentBlocks.push({
286
- type: 'tool_use',
287
- id: sanitizeProviderToolId(tc.id, 'toolu', idx),
288
- name: normalizeToolName(tc.function?.name || ''),
289
- input: safeParseJsonObject(tc.function?.arguments)
290
- });
133
+ if (this.reasoningBudgetTokens) {
134
+ return { type: 'enabled', budget_tokens: this.reasoningBudgetTokens };
291
135
  }
292
- anthropicMessages.push({ role: 'assistant', content: contentBlocks });
293
- } else {
294
- // These are the loop's own bookkeeping. The API rejects unknown message
295
- // properties, so every one of them has to be stripped here.
296
- const { cacheAnchor, thinking_blocks, reasoning_content, spillPath, ...clean } = msg;
297
- anthropicMessages.push({ ...clean, content: clean.content ?? '' });
298
- }
299
- }
300
-
301
- const apiKey = requireApiKey(this.apiKey, 'Anthropic');
302
- const payload = {
303
- model: this.model,
304
- system: systemBlocks,
305
- messages: anthropicMessages,
306
- // 4096 truncated long tool-heavy turns mid-thought and forced a retry.
307
- max_tokens: options.maxTokens || 16000
308
- };
309
-
310
- if (!this.rejectsSamplingParameters()) {
311
- payload.temperature = resolveTemperature(options.temperature, 0.1);
136
+ return null;
312
137
  }
313
-
314
- const thinking = this.buildThinking();
315
- if (thinking) {
316
- if (thinking.type === 'enabled' && typeof thinking.budget_tokens === 'number' && payload.max_tokens > 1024) {
317
- thinking.budget_tokens = Math.max(1024, Math.min(thinking.budget_tokens, payload.max_tokens - 1));
318
- }
319
- payload.thinking = thinking;
138
+ supportsMidConversationSystem() {
139
+ return modelMatches(this.model, MID_CONVERSATION_SYSTEM_MODELS);
320
140
  }
321
-
322
- const effort = this.resolveEffort();
323
- // effort lives inside output_config, not at the top level.
324
- if (effort) payload.output_config = { ...(payload.output_config || {}), effort };
325
-
326
- let freeFormPaths = new Map();
327
- if (options.tools && options.tools.length > 0) {
328
- const useToolSearch = this.supportsToolSearch();
329
- const coreToolCount = Number.isInteger(options.coreToolCount) ? options.coreToolCount : options.tools.length;
330
-
331
- const scanReport = scanAndAdaptToolsForProvider(options.tools, 'anthropic', {
332
- useToolSearch,
333
- coreToolCount
334
- });
335
- const converted = scanReport.adaptedTools;
336
- freeFormPaths = scanReport.freeFormPaths;
337
-
338
- if (useToolSearch) {
339
- payload.tools = [
340
- { type: 'tool_search_tool_regex_20251119', name: 'tool_search_tool_regex' },
341
- ...converted
342
- ];
343
- } else {
344
- payload.tools = converted;
345
- }
346
-
347
- // Cache breakpoint on the last non-deferred tool. A deferred tool cannot
348
- // also carry cache_control — the API rejects that combination.
349
- if (this.enableCaching) {
350
- const anchorIndex = useToolSearch
351
- ? Math.min(coreToolCount, payload.tools.length - 1)
352
- : payload.tools.length - 1;
353
- const anchor = payload.tools[anchorIndex];
354
- if (anchor && !anchor.defer_loading && !anchor.type) {
355
- anchor.cache_control = this.cacheControl();
141
+ async chat(messages, options = {}) {
142
+ messages = prepareMessagesForAnthropic(this, messages);
143
+ const systemBlocks = [];
144
+ const anthropicMessages = [];
145
+ const MAX_SYSTEM_CACHE_BREAKPOINTS = 3;
146
+ let systemCacheBreakpoints = 0;
147
+ const allowInlineSystem = this.supportsMidConversationSystem();
148
+ for (const msg of messages) {
149
+ if (msg.role === 'system') {
150
+ const isMidConversation = anthropicMessages.length > 0;
151
+ const lastEmitted = anthropicMessages[anthropicMessages.length - 1];
152
+ if (isMidConversation && allowInlineSystem && lastEmitted?.['role'] === 'user') {
153
+ anthropicMessages.push({ role: 'system', content: String(msg.content ?? '') });
154
+ continue;
155
+ }
156
+ const sysText = String(msg.content ?? '');
157
+ if (!sysText.trim())
158
+ continue;
159
+ const block = { type: 'text', text: sysText };
160
+ if (msg.cacheAnchor && this.enableCaching && systemCacheBreakpoints < MAX_SYSTEM_CACHE_BREAKPOINTS) {
161
+ block['cache_control'] = this.cacheControl();
162
+ systemCacheBreakpoints++;
163
+ }
164
+ systemBlocks.push(block);
165
+ }
166
+ else if (msg.role === 'tool') {
167
+ let toolContent = msg.content ?? '';
168
+ if (typeof toolContent !== 'string' && !Array.isArray(toolContent)) {
169
+ try {
170
+ toolContent = JSON.stringify(toolContent);
171
+ }
172
+ catch {
173
+ toolContent = String(toolContent);
174
+ }
175
+ }
176
+ const toolResultBlock = {
177
+ type: 'tool_result',
178
+ tool_use_id: sanitizeProviderToolId(msg.tool_call_id, 'toolu', 0),
179
+ content: toolContent
180
+ };
181
+ const lastMsg = anthropicMessages[anthropicMessages.length - 1];
182
+ if (lastMsg && lastMsg['role'] === 'user' && Array.isArray(lastMsg['content']) && lastMsg['content'][0]?.type === 'tool_result') {
183
+ lastMsg['content'].push(toolResultBlock);
184
+ }
185
+ else {
186
+ anthropicMessages.push({ role: 'user', content: [toolResultBlock] });
187
+ }
188
+ }
189
+ else if (msg.role === 'assistant' && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
190
+ const contentBlocks = [];
191
+ if (Array.isArray(msg.thinking_blocks)) {
192
+ contentBlocks.push(...msg.thinking_blocks);
193
+ }
194
+ if (typeof msg.content === 'string' && msg.content.length > 0) {
195
+ contentBlocks.push({ type: 'text', text: msg.content });
196
+ }
197
+ for (let idx = 0; idx < msg.tool_calls.length; idx++) {
198
+ const tc = msg.tool_calls[idx];
199
+ if (!tc || typeof tc !== 'object')
200
+ continue;
201
+ const toolName = normalizeToolName(tc.function?.name || '');
202
+ if (!toolName)
203
+ continue;
204
+ contentBlocks.push({
205
+ type: 'tool_use',
206
+ id: sanitizeProviderToolId(tc.id, 'toolu', idx),
207
+ name: toolName,
208
+ input: safeParseJsonObject(tc.function?.arguments)
209
+ });
210
+ }
211
+ if (contentBlocks.length > 0) {
212
+ anthropicMessages.push({ role: 'assistant', content: contentBlocks });
213
+ }
214
+ }
215
+ else {
216
+ const { cacheAnchor: _c, thinking_blocks: _tb, reasoning_content: _rc, spillPath: _sp, ...clean } = msg;
217
+ const nextContent = clean.content ?? '';
218
+ const prev = anthropicMessages[anthropicMessages.length - 1];
219
+ if (clean.role === 'user' && prev && prev['role'] === 'user') {
220
+ const prevBlocks = Array.isArray(prev['content'])
221
+ ? prev['content']
222
+ : (typeof prev['content'] === 'string' && prev['content'] ? [{ type: 'text', text: prev['content'] }] : []);
223
+ const nextBlocks = Array.isArray(nextContent)
224
+ ? nextContent
225
+ : (typeof nextContent === 'string' && nextContent ? [{ type: 'text', text: nextContent }] : []);
226
+ prev['content'] = [...prevBlocks, ...nextBlocks];
227
+ }
228
+ else {
229
+ anthropicMessages.push({ ...clean, content: nextContent });
230
+ }
231
+ }
356
232
  }
357
- }
358
- }
359
-
360
- const requestOpts = {
361
- url: this.baseUrl,
362
- method: 'POST',
363
- headers: {
364
- 'Content-Type': 'application/json',
365
- 'x-api-key': apiKey,
366
- 'anthropic-version': '2023-06-01'
367
- },
368
- signal: options.signal,
369
- timeoutMs: options.timeoutMs,
370
- providerLabel: 'Anthropic',
371
- secrets: [apiKey],
372
- hasApiKey: true
373
- };
374
-
375
- const data = wantsStreaming(options)
376
- ? await streamAnthropicMessages({
377
- ...requestOpts,
378
- payload,
379
- onChunk: options.onChunk,
380
- onReasoningChunk: options.onReasoningChunk
381
- })
382
- : await safeProviderFetchJson({
383
- ...requestOpts,
384
- body: JSON.stringify(payload)
385
- });
386
-
387
- // Extract text content and tool calls
388
- let content = '';
389
- let toolCalls = [];
390
- const thinkingBlocks = [];
391
- let reasoningContent = '';
392
-
393
- for (const block of (Array.isArray(data.content) ? data.content : [])) {
394
- if (block.type === 'thinking' || block.type === 'redacted_thinking') {
395
- // Kept verbatim for the echo above. The readable summary, when the user
396
- // asked for one, is surfaced separately.
397
- thinkingBlocks.push(block);
398
- if (typeof block.thinking === 'string') reasoningContent += block.thinking;
399
- } else if (block.type === 'text') {
400
- content += block.text || '';
401
- } else if (block.type === 'tool_use') {
402
- const callName = normalizeToolName(block.name || '');
403
- toolCalls.push({
404
- id: sanitizeProviderToolId(block.id, 'toolu', toolCalls.length),
405
- type: 'function',
406
- function: {
407
- name: callName,
408
- arguments: serializeAndDecodeArguments(block.input || {}, callName, freeFormPaths)
409
- }
410
- });
411
- }
412
- // server_tool_use and tool_search_tool_result blocks are handled entirely
413
- // by the API: the discovered tools are expanded before Claude sees them,
414
- // and we must never return a tool_result for a srvtoolu_ id.
233
+ const apiKey = requireApiKey(this.apiKey, 'Anthropic');
234
+ const payload = {
235
+ model: this.model,
236
+ ...(systemBlocks.length > 0 ? { system: systemBlocks } : {}),
237
+ messages: anthropicMessages,
238
+ max_tokens: typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1
239
+ ? Math.floor(options.maxTokens)
240
+ : 16000
241
+ };
242
+ const thinking = this.buildThinking();
243
+ const thinkingActive = Boolean(thinking && thinking['type'] !== 'disabled');
244
+ if (!this.rejectsSamplingParameters() && !thinkingActive) {
245
+ payload['temperature'] = resolveTemperature(options.temperature, 0.1);
246
+ }
247
+ if (thinking) {
248
+ if (thinking['type'] === 'enabled' && typeof thinking['budget_tokens'] === 'number' && Number.isFinite(thinking['budget_tokens'])) {
249
+ if (payload['max_tokens'] <= 1024)
250
+ payload['max_tokens'] = 2048;
251
+ thinking['budget_tokens'] = Math.max(1024, Math.min(Math.floor(thinking['budget_tokens']), payload['max_tokens'] - 1));
252
+ }
253
+ payload['thinking'] = thinking;
254
+ }
255
+ const effort = this.resolveEffort();
256
+ if (effort)
257
+ payload['output_config'] = { ...(payload['output_config'] || {}), effort };
258
+ let freeFormPaths = new Map();
259
+ if (options.tools && options.tools.length > 0) {
260
+ const useToolSearch = this.supportsToolSearch();
261
+ const coreToolCount = Number.isInteger(options.coreToolCount) ? options.coreToolCount : options.tools.length;
262
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'anthropic', {
263
+ useToolSearch,
264
+ coreToolCount
265
+ });
266
+ const converted = scanReport.adaptedTools;
267
+ freeFormPaths = scanReport.freeFormPaths;
268
+ if (useToolSearch) {
269
+ payload['tools'] = [
270
+ { type: 'tool_search_tool_regex_20251119', name: 'tool_search_tool_regex' },
271
+ ...converted
272
+ ];
273
+ }
274
+ else {
275
+ payload['tools'] = converted;
276
+ }
277
+ if (this.enableCaching) {
278
+ const anchorIndex = useToolSearch
279
+ ? Math.min(coreToolCount, payload['tools'].length - 1)
280
+ : payload['tools'].length - 1;
281
+ const anchor = payload['tools'][anchorIndex];
282
+ if (anchor && !anchor.defer_loading && !anchor.type) {
283
+ anchor.cache_control = this.cacheControl();
284
+ }
285
+ }
286
+ }
287
+ const endpoint = this.baseUrl || 'https://api.anthropic.com/v1/messages';
288
+ const requestOpts = {
289
+ url: endpoint,
290
+ method: 'POST',
291
+ headers: {
292
+ 'Content-Type': 'application/json',
293
+ 'x-api-key': apiKey,
294
+ 'anthropic-version': '2023-06-01'
295
+ },
296
+ signal: options.signal,
297
+ timeoutMs: options.timeoutMs,
298
+ providerLabel: 'Anthropic',
299
+ secrets: [apiKey],
300
+ hasApiKey: true,
301
+ allowInsecureHttp: this.allowInsecureHttp
302
+ };
303
+ const data = wantsStreaming(options)
304
+ ? await streamAnthropicMessages({
305
+ ...requestOpts,
306
+ payload,
307
+ onChunk: options.onChunk,
308
+ onReasoningChunk: options.onReasoningChunk
309
+ })
310
+ : await safeProviderFetchJson({
311
+ ...requestOpts,
312
+ body: JSON.stringify(payload)
313
+ });
314
+ let content = '';
315
+ const toolCalls = [];
316
+ const thinkingBlocks = [];
317
+ let reasoningContent = '';
318
+ for (const block of (Array.isArray(data['content']) ? data['content'] : [])) {
319
+ if (!block || typeof block !== 'object')
320
+ continue;
321
+ if (block.type === 'thinking' || block.type === 'redacted_thinking') {
322
+ thinkingBlocks.push(block);
323
+ if (typeof block.thinking === 'string')
324
+ reasoningContent += block.thinking;
325
+ }
326
+ else if (block.type === 'text') {
327
+ content += typeof block.text === 'string' ? block.text : '';
328
+ }
329
+ else if (block.type === 'tool_use') {
330
+ const callName = normalizeToolName(block.name || '');
331
+ if (!callName)
332
+ continue;
333
+ toolCalls.push({
334
+ id: sanitizeProviderToolId(block.id, 'toolu', toolCalls.length),
335
+ type: 'function',
336
+ function: {
337
+ name: callName,
338
+ arguments: serializeAndDecodeArguments(block.input || {}, callName, freeFormPaths)
339
+ }
340
+ });
341
+ }
342
+ }
343
+ const rawUsage = data['usage'];
344
+ const nonNeg = (v) => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
345
+ const inputTokens = nonNeg(rawUsage?.input_tokens);
346
+ const cacheReadTokens = nonNeg(rawUsage?.cache_read_input_tokens);
347
+ const cacheCreateTokens = nonNeg(rawUsage?.cache_creation_input_tokens);
348
+ const outputTokens = nonNeg(rawUsage?.output_tokens);
349
+ return {
350
+ content: content.trim(),
351
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
352
+ thinkingBlocks: thinkingBlocks.length > 0 ? thinkingBlocks : undefined,
353
+ reasoningContent: reasoningContent.trim() || undefined,
354
+ usage: {
355
+ promptTokens: inputTokens + cacheReadTokens + cacheCreateTokens,
356
+ completionTokens: outputTokens,
357
+ cachedPromptTokens: cacheReadTokens,
358
+ cacheWriteMultiplier: this.cacheTtl === '5m' ? 1.25 : 2.0,
359
+ cacheWriteTokens: cacheCreateTokens
360
+ }
361
+ };
415
362
  }
416
-
417
- return {
418
- content: content.trim(),
419
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
420
- thinkingBlocks: thinkingBlocks.length > 0 ? thinkingBlocks : undefined,
421
- reasoningContent: reasoningContent.trim() || undefined,
422
- usage: {
423
- // Cache reads are billed at 0.1x and cache writes at 1.25x, so they are
424
- // reported separately for the token tracker to price correctly.
425
- promptTokens:
426
- (data.usage?.input_tokens || 0) +
427
- (data.usage?.cache_read_input_tokens || 0) +
428
- (data.usage?.cache_creation_input_tokens || 0),
429
- completionTokens: data.usage?.output_tokens || 0,
430
- cachedPromptTokens: data.usage?.cache_read_input_tokens || 0,
431
- // A 1-hour cache write is billed at 2.0x, a 5-minute one at 1.25x.
432
- cacheWriteMultiplier: this.cacheTtl === '5m' ? 1.25 : 2.0,
433
- cacheWriteTokens: data.usage?.cache_creation_input_tokens || 0
434
- }
435
- };
436
- }
437
363
  }