@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
@@ -0,0 +1,386 @@
1
+ import { canonicalModelId } from '../modelIds.js';
2
+ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
+ import { LLMProvider, type ChatOptions, type ChatResponse, type ChatResponseToolCall, type ProviderConfig } from './base.js';
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';
16
+ import { streamAnthropicMessages, wantsStreaming } from './byokStream.js';
17
+
18
+ const TOOL_SEARCH_MODELS: readonly string[] = [
19
+ 'claude-3-7-sonnet',
20
+ 'claude-3-5-sonnet',
21
+ 'claude-3-5-haiku',
22
+ 'claude-3-opus',
23
+ 'claude-fable-5',
24
+ 'claude-mythos-5',
25
+ 'claude-opus-5',
26
+ 'claude-opus-4-8',
27
+ 'claude-opus-4-7',
28
+ 'claude-opus-4-6',
29
+ 'claude-sonnet-4-6',
30
+ 'claude-opus-4-5',
31
+ 'claude-sonnet-4-5',
32
+ 'claude-haiku-4-5'
33
+ ];
34
+
35
+ const NO_SAMPLING_MODELS: readonly string[] = [
36
+ 'claude-fable-5',
37
+ 'claude-mythos-5',
38
+ 'claude-opus-5',
39
+ 'claude-opus-4-8',
40
+ 'claude-opus-4-7',
41
+ 'claude-sonnet-5'
42
+ ];
43
+
44
+ const MID_CONVERSATION_SYSTEM_MODELS: readonly string[] = [
45
+ 'claude-fable-5',
46
+ 'claude-mythos-5',
47
+ 'claude-opus-5',
48
+ 'claude-opus-4-8'
49
+ ];
50
+
51
+ const ADAPTIVE_THINKING_MODELS: readonly string[] = [
52
+ 'claude-fable-5',
53
+ 'claude-mythos-5',
54
+ 'claude-opus-5',
55
+ 'claude-opus-4-8',
56
+ 'claude-opus-4-7',
57
+ 'claude-opus-4-6',
58
+ 'claude-sonnet-5',
59
+ 'claude-sonnet-4-6'
60
+ ];
61
+
62
+ const THINKS_BY_DEFAULT_MODELS: readonly string[] = [
63
+ 'claude-fable-5',
64
+ 'claude-mythos-5',
65
+ 'claude-opus-5'
66
+ ];
67
+
68
+ const THINKING_ALWAYS_ON_MODELS: readonly string[] = [
69
+ 'claude-fable-5',
70
+ 'claude-mythos-5'
71
+ ];
72
+
73
+ const EFFORT_MODELS: readonly string[] = [...ADAPTIVE_THINKING_MODELS, 'claude-opus-4-5'];
74
+ const LIMITED_EFFORT_MODELS: readonly string[] = ['claude-opus-4-5', 'claude-opus-4-6', 'claude-sonnet-4-6'];
75
+ const EFFORT_LEVELS: readonly string[] = ['low', 'medium', 'high', 'xhigh', 'max'];
76
+
77
+ function modelMatches(model: string, list: readonly string[]): boolean {
78
+ const normalized = (model || '').toLowerCase();
79
+ return list.some(supported => normalized.startsWith(supported));
80
+ }
81
+
82
+ export class AnthropicProvider extends LLMProvider {
83
+ enableToolSearch: boolean;
84
+ enableCaching: boolean;
85
+ cacheTtl: string;
86
+ reasoningEffort: string | null;
87
+ showReasoning: boolean;
88
+ reasoningBudgetTokens: number | null;
89
+ allowInsecureHttp: boolean;
90
+
91
+ constructor(config: ProviderConfig = {}) {
92
+ super(config);
93
+ const customUrl = typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '';
94
+ this.baseUrl = customUrl || 'https://api.anthropic.com/v1/messages';
95
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
96
+ this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['anthropic']) || '');
97
+ this.visionModels = ['*'];
98
+ this.audioModels = [];
99
+ this.imagePayloadFormat = 'anthropic';
100
+ this.preserveThinkingBlocks = true;
101
+ this.enableToolSearch = config.enableToolSearch !== false;
102
+ this.enableCaching = config.enablePromptCaching !== false;
103
+ this.cacheTtl = config.promptCacheTtl === '5m' ? '5m' : '1h';
104
+ this.reasoningEffort = config.reasoningEffort || null;
105
+ this.showReasoning = config.showReasoning === true;
106
+ this.reasoningBudgetTokens = typeof config.reasoningBudgetTokens === 'number' ? config.reasoningBudgetTokens : null;
107
+ }
108
+
109
+ cacheControl(): { type: 'ephemeral'; ttl?: string } {
110
+ return this.cacheTtl === '5m'
111
+ ? { type: 'ephemeral' }
112
+ : { type: 'ephemeral', ttl: this.cacheTtl };
113
+ }
114
+
115
+ supportsToolSearch(): boolean {
116
+ if (!this.enableToolSearch) return false;
117
+ return modelMatches(this.model, TOOL_SEARCH_MODELS);
118
+ }
119
+
120
+ rejectsSamplingParameters(): boolean {
121
+ return modelMatches(this.model, NO_SAMPLING_MODELS);
122
+ }
123
+
124
+ supportsAdaptiveThinking(): boolean {
125
+ return modelMatches(this.model, ADAPTIVE_THINKING_MODELS);
126
+ }
127
+
128
+ resolveEffort(): string | null {
129
+ if (!modelMatches(this.model, EFFORT_MODELS)) return null;
130
+ const requested = String(this.reasoningEffort || '').toLowerCase();
131
+ if (!EFFORT_LEVELS.includes(requested)) return null;
132
+ if (modelMatches(this.model, LIMITED_EFFORT_MODELS) && (requested === 'xhigh' || requested === 'max')) {
133
+ return 'high';
134
+ }
135
+ return requested;
136
+ }
137
+
138
+ buildThinking(): Record<string, any> | null {
139
+ if (modelMatches(this.model, THINKING_ALWAYS_ON_MODELS)) return null;
140
+
141
+ if (this.reasoningEffort === 'off') {
142
+ if (!modelMatches(this.model, THINKS_BY_DEFAULT_MODELS)) return null;
143
+ const effort = this.resolveEffort();
144
+ if (effort === 'xhigh' || effort === 'max') return null;
145
+ return { type: 'disabled' };
146
+ }
147
+
148
+ if (this.supportsAdaptiveThinking()) {
149
+ const thinking: Record<string, any> = { type: 'adaptive' };
150
+ if (this.showReasoning) thinking['display'] = 'summarized';
151
+ return thinking;
152
+ }
153
+
154
+ if (this.reasoningBudgetTokens) {
155
+ return { type: 'enabled', budget_tokens: this.reasoningBudgetTokens };
156
+ }
157
+ return null;
158
+ }
159
+
160
+ supportsMidConversationSystem(): boolean {
161
+ return modelMatches(this.model, MID_CONVERSATION_SYSTEM_MODELS);
162
+ }
163
+
164
+ override async chat(messages: any[], options: ChatOptions = {}): Promise<ChatResponse> {
165
+ messages = prepareMessagesForAnthropic(this, messages);
166
+ const systemBlocks: Array<Record<string, any>> = [];
167
+ const anthropicMessages: Array<Record<string, any>> = [];
168
+
169
+ const MAX_SYSTEM_CACHE_BREAKPOINTS = 3;
170
+ let systemCacheBreakpoints = 0;
171
+
172
+ const allowInlineSystem = this.supportsMidConversationSystem();
173
+
174
+ for (const msg of messages) {
175
+ if (msg.role === 'system') {
176
+ const isMidConversation = anthropicMessages.length > 0;
177
+ const lastEmitted = anthropicMessages[anthropicMessages.length - 1];
178
+ if (isMidConversation && allowInlineSystem && lastEmitted?.['role'] === 'user') {
179
+ anthropicMessages.push({ role: 'system', content: String(msg.content ?? '') });
180
+ continue;
181
+ }
182
+
183
+ const sysText = String(msg.content ?? '');
184
+ if (!sysText.trim()) continue;
185
+ const block: Record<string, any> = { type: 'text', text: sysText };
186
+ if (msg.cacheAnchor && this.enableCaching && systemCacheBreakpoints < MAX_SYSTEM_CACHE_BREAKPOINTS) {
187
+ block['cache_control'] = this.cacheControl();
188
+ systemCacheBreakpoints++;
189
+ }
190
+ systemBlocks.push(block);
191
+ } else if (msg.role === 'tool') {
192
+ let toolContent: unknown = msg.content ?? '';
193
+ if (typeof toolContent !== 'string' && !Array.isArray(toolContent)) {
194
+ try {
195
+ toolContent = JSON.stringify(toolContent);
196
+ } catch {
197
+ toolContent = String(toolContent);
198
+ }
199
+ }
200
+ const toolResultBlock = {
201
+ type: 'tool_result',
202
+ tool_use_id: sanitizeProviderToolId(msg.tool_call_id, 'toolu', 0),
203
+ content: toolContent
204
+ };
205
+ const lastMsg = anthropicMessages[anthropicMessages.length - 1];
206
+ if (lastMsg && lastMsg['role'] === 'user' && Array.isArray(lastMsg['content']) && lastMsg['content'][0]?.type === 'tool_result') {
207
+ lastMsg['content'].push(toolResultBlock);
208
+ } else {
209
+ anthropicMessages.push({ role: 'user', content: [toolResultBlock] });
210
+ }
211
+ } else if (msg.role === 'assistant' && Array.isArray(msg.tool_calls) && msg.tool_calls.length > 0) {
212
+ const contentBlocks: Array<Record<string, any>> = [];
213
+ if (Array.isArray(msg.thinking_blocks)) {
214
+ contentBlocks.push(...msg.thinking_blocks);
215
+ }
216
+ if (typeof msg.content === 'string' && msg.content.length > 0) {
217
+ contentBlocks.push({ type: 'text', text: msg.content });
218
+ }
219
+ for (let idx = 0; idx < msg.tool_calls.length; idx++) {
220
+ const tc = msg.tool_calls[idx];
221
+ if (!tc || typeof tc !== 'object') continue;
222
+ const toolName = normalizeToolName(tc.function?.name || '');
223
+ if (!toolName) continue;
224
+ contentBlocks.push({
225
+ type: 'tool_use',
226
+ id: sanitizeProviderToolId(tc.id, 'toolu', idx),
227
+ name: toolName,
228
+ input: safeParseJsonObject(tc.function?.arguments)
229
+ });
230
+ }
231
+ if (contentBlocks.length > 0) {
232
+ anthropicMessages.push({ role: 'assistant', content: contentBlocks });
233
+ }
234
+ } else {
235
+ const { cacheAnchor: _c, thinking_blocks: _tb, reasoning_content: _rc, spillPath: _sp, ...clean } = msg;
236
+ const nextContent = clean.content ?? '';
237
+ const prev = anthropicMessages[anthropicMessages.length - 1];
238
+ if (clean.role === 'user' && prev && prev['role'] === 'user') {
239
+ const prevBlocks = Array.isArray(prev['content'])
240
+ ? prev['content']
241
+ : (typeof prev['content'] === 'string' && prev['content'] ? [{ type: 'text', text: prev['content'] }] : []);
242
+ const nextBlocks = Array.isArray(nextContent)
243
+ ? nextContent
244
+ : (typeof nextContent === 'string' && nextContent ? [{ type: 'text', text: nextContent }] : []);
245
+ prev['content'] = [...prevBlocks, ...nextBlocks];
246
+ } else {
247
+ anthropicMessages.push({ ...clean, content: nextContent });
248
+ }
249
+ }
250
+ }
251
+
252
+ const apiKey = requireApiKey(this.apiKey, 'Anthropic');
253
+ const payload: Record<string, any> = {
254
+ model: this.model,
255
+ ...(systemBlocks.length > 0 ? { system: systemBlocks } : {}),
256
+ messages: anthropicMessages,
257
+ max_tokens: typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1
258
+ ? Math.floor(options.maxTokens)
259
+ : 16000
260
+ };
261
+
262
+ const thinking = this.buildThinking();
263
+ const thinkingActive = Boolean(thinking && thinking['type'] !== 'disabled');
264
+ if (!this.rejectsSamplingParameters() && !thinkingActive) {
265
+ payload['temperature'] = resolveTemperature(options.temperature, 0.1);
266
+ }
267
+
268
+ if (thinking) {
269
+ if (thinking['type'] === 'enabled' && typeof thinking['budget_tokens'] === 'number' && Number.isFinite(thinking['budget_tokens'])) {
270
+ if (payload['max_tokens'] <= 1024) payload['max_tokens'] = 2048;
271
+ thinking['budget_tokens'] = Math.max(1024, Math.min(Math.floor(thinking['budget_tokens']), payload['max_tokens'] - 1));
272
+ }
273
+ payload['thinking'] = thinking;
274
+ }
275
+
276
+ const effort = this.resolveEffort();
277
+ if (effort) payload['output_config'] = { ...(payload['output_config'] || {}), effort };
278
+
279
+ let freeFormPaths = new Map<string, string[][]>();
280
+ if (options.tools && options.tools.length > 0) {
281
+ const useToolSearch = this.supportsToolSearch();
282
+ const coreToolCount = Number.isInteger(options.coreToolCount) ? (options.coreToolCount as number) : options.tools.length;
283
+
284
+ const scanReport = scanAndAdaptToolsForProvider(options.tools, 'anthropic', {
285
+ useToolSearch,
286
+ coreToolCount
287
+ });
288
+ const converted = scanReport.adaptedTools;
289
+ freeFormPaths = scanReport.freeFormPaths;
290
+
291
+ if (useToolSearch) {
292
+ payload['tools'] = [
293
+ { type: 'tool_search_tool_regex_20251119', name: 'tool_search_tool_regex' },
294
+ ...converted
295
+ ];
296
+ } else {
297
+ payload['tools'] = converted;
298
+ }
299
+
300
+ if (this.enableCaching) {
301
+ const anchorIndex = useToolSearch
302
+ ? Math.min(coreToolCount, payload['tools'].length - 1)
303
+ : payload['tools'].length - 1;
304
+ const anchor = payload['tools'][anchorIndex];
305
+ if (anchor && !anchor.defer_loading && !anchor.type) {
306
+ anchor.cache_control = this.cacheControl();
307
+ }
308
+ }
309
+ }
310
+
311
+ const endpoint = this.baseUrl || 'https://api.anthropic.com/v1/messages';
312
+ const requestOpts = {
313
+ url: endpoint,
314
+ method: 'POST',
315
+ headers: {
316
+ 'Content-Type': 'application/json',
317
+ 'x-api-key': apiKey,
318
+ 'anthropic-version': '2023-06-01'
319
+ },
320
+ signal: options.signal,
321
+ timeoutMs: options.timeoutMs,
322
+ providerLabel: 'Anthropic',
323
+ secrets: [apiKey],
324
+ hasApiKey: true,
325
+ allowInsecureHttp: this.allowInsecureHttp
326
+ };
327
+
328
+ const data: Record<string, any> = wantsStreaming(options)
329
+ ? await streamAnthropicMessages({
330
+ ...requestOpts,
331
+ payload,
332
+ onChunk: options.onChunk,
333
+ onReasoningChunk: options.onReasoningChunk
334
+ })
335
+ : await safeProviderFetchJson({
336
+ ...requestOpts,
337
+ body: JSON.stringify(payload)
338
+ });
339
+
340
+ let content = '';
341
+ const toolCalls: ChatResponseToolCall[] = [];
342
+ const thinkingBlocks: any[] = [];
343
+ let reasoningContent = '';
344
+
345
+ for (const block of (Array.isArray(data['content']) ? data['content'] : [])) {
346
+ if (!block || typeof block !== 'object') continue;
347
+ if (block.type === 'thinking' || block.type === 'redacted_thinking') {
348
+ thinkingBlocks.push(block);
349
+ if (typeof block.thinking === 'string') reasoningContent += block.thinking;
350
+ } else if (block.type === 'text') {
351
+ content += typeof block.text === 'string' ? block.text : '';
352
+ } else if (block.type === 'tool_use') {
353
+ const callName = normalizeToolName(block.name || '');
354
+ if (!callName) continue;
355
+ toolCalls.push({
356
+ id: sanitizeProviderToolId(block.id, 'toolu', toolCalls.length),
357
+ type: 'function',
358
+ function: {
359
+ name: callName,
360
+ arguments: serializeAndDecodeArguments(block.input || {}, callName, freeFormPaths)
361
+ }
362
+ });
363
+ }
364
+ }
365
+
366
+ const rawUsage = data['usage'];
367
+ const nonNeg = (v: unknown): number => (typeof v === 'number' && Number.isFinite(v) && v > 0 ? v : 0);
368
+ const inputTokens = nonNeg(rawUsage?.input_tokens);
369
+ const cacheReadTokens = nonNeg(rawUsage?.cache_read_input_tokens);
370
+ const cacheCreateTokens = nonNeg(rawUsage?.cache_creation_input_tokens);
371
+ const outputTokens = nonNeg(rawUsage?.output_tokens);
372
+ return {
373
+ content: content.trim(),
374
+ toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
375
+ thinkingBlocks: thinkingBlocks.length > 0 ? thinkingBlocks : undefined,
376
+ reasoningContent: reasoningContent.trim() || undefined,
377
+ usage: {
378
+ promptTokens: inputTokens + cacheReadTokens + cacheCreateTokens,
379
+ completionTokens: outputTokens,
380
+ cachedPromptTokens: cacheReadTokens,
381
+ cacheWriteMultiplier: this.cacheTtl === '5m' ? 1.25 : 2.0,
382
+ cacheWriteTokens: cacheCreateTokens
383
+ }
384
+ };
385
+ }
386
+ }
@@ -756,8 +756,11 @@ export class AntigravityProvider extends LLMProvider {
756
756
  if (c?.text)
757
757
  return c.text;
758
758
  if (c?.type === 'image_url' || c?.type === 'image') {
759
- const url = c?.image_url?.url || '';
760
- const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
759
+ const url = typeof c?.image_url?.url === 'string' ? c.image_url.url : '';
760
+ const semi = url.indexOf(';');
761
+ const comma = url.indexOf(',');
762
+ const end = semi >= 5 && (comma < 0 || semi < comma) ? semi : comma;
763
+ const mime = c?.source?.media_type || (url.startsWith('data:') && end > 5 ? url.slice(5, end) : 'image');
761
764
  return `[Visual Content: ${mime}]`;
762
765
  }
763
766
  return '';
@@ -822,8 +825,11 @@ export class AntigravityProvider extends LLMProvider {
822
825
  if (c?.text)
823
826
  return c.text;
824
827
  if (c?.type === 'image_url' || c?.type === 'image') {
825
- const url = c?.image_url?.url || '';
826
- const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
828
+ const url = typeof c?.image_url?.url === 'string' ? c.image_url.url : '';
829
+ const semi = url.indexOf(';');
830
+ const comma = url.indexOf(',');
831
+ const end = semi >= 5 && (comma < 0 || semi < comma) ? semi : comma;
832
+ const mime = c?.source?.media_type || (url.startsWith('data:') && end > 5 ? url.slice(5, end) : 'image');
827
833
  return `[Visual Content: ${mime}]`;
828
834
  }
829
835
  return '';
@@ -772,8 +772,11 @@ export class AntigravityProvider extends LLMProvider {
772
772
  if (typeof c === 'string') return c;
773
773
  if (c?.text) return c.text;
774
774
  if (c?.type === 'image_url' || c?.type === 'image') {
775
- const url = c?.image_url?.url || '';
776
- const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
775
+ const url = typeof c?.image_url?.url === 'string' ? c.image_url.url : '';
776
+ const semi = url.indexOf(';');
777
+ const comma = url.indexOf(',');
778
+ const end = semi >= 5 && (comma < 0 || semi < comma) ? semi : comma;
779
+ const mime = c?.source?.media_type || (url.startsWith('data:') && end > 5 ? url.slice(5, end) : 'image');
777
780
  return `[Visual Content: ${mime}]`;
778
781
  }
779
782
  return '';
@@ -846,8 +849,11 @@ export class AntigravityProvider extends LLMProvider {
846
849
  if (typeof c === 'string') return c;
847
850
  if (c?.text) return c.text;
848
851
  if (c?.type === 'image_url' || c?.type === 'image') {
849
- const url = c?.image_url?.url || '';
850
- const mime = c?.source?.media_type || (url.startsWith('data:') ? url.slice(5, url.indexOf(';')) : 'image');
852
+ const url = typeof c?.image_url?.url === 'string' ? c.image_url.url : '';
853
+ const semi = url.indexOf(';');
854
+ const comma = url.indexOf(',');
855
+ const end = semi >= 5 && (comma < 0 || semi < comma) ? semi : comma;
856
+ const mime = c?.source?.media_type || (url.startsWith('data:') && end > 5 ? url.slice(5, end) : 'image');
851
857
  return `[Visual Content: ${mime}]`;
852
858
  }
853
859
  return '';