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