@causyne/agent 1.20.118 → 1.20.121

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 (101) hide show
  1. package/package.json +1 -1
  2. package/src/agent/errorClassifier.js +113 -0
  3. package/src/agent/errorClassifier.ts +161 -0
  4. package/src/agent/promptIntent.js +200 -0
  5. package/src/agent/promptIntent.ts +203 -0
  6. package/src/agent/toolArgValidator.js +97 -0
  7. package/src/agent/toolArgValidator.ts +112 -0
  8. package/src/agentLoop.js +51 -351
  9. package/src/agentLoop.ts +69 -363
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/browser/causyneBrowser.js +231 -136
  13. package/src/browser/causyneBrowser.ts +229 -140
  14. package/src/browser/searchProviders.js +41 -30
  15. package/src/browser/searchProviders.ts +24 -14
  16. package/src/browser/workspacePathSafety.js +50 -0
  17. package/src/browser/workspacePathSafety.ts +50 -0
  18. package/src/browser/workspacePreview.js +27 -4
  19. package/src/browser/workspacePreview.ts +28 -4
  20. package/src/cliMode.js +17 -3
  21. package/src/commands.js +15 -22
  22. package/src/config.js +42 -63
  23. package/src/configVault.js +204 -0
  24. package/src/configVault.ts +213 -0
  25. package/src/core/contextCompactor.js +70 -11
  26. package/src/core/contextCompactor.ts +83 -11
  27. package/src/creative/liveBridge.js +34 -1
  28. package/src/creative/liveBridge.ts +28 -1
  29. package/src/dynamicCatalogue.js +42 -73
  30. package/src/dynamicCatalogue.ts +74 -60
  31. package/src/entrypoint.js +77 -4
  32. package/src/headlessCli.js +304 -0
  33. package/src/headlessCli.ts +380 -0
  34. package/src/mcp/mcpClient.js +38 -11
  35. package/src/mcp/mcpClient.ts +44 -11
  36. package/src/mcp/mcpRegistry.js +2 -5
  37. package/src/mcp/mcpRegistry.ts +2 -5
  38. package/src/mcp/mcpSecurity.js +189 -0
  39. package/src/mcp/mcpSecurity.ts +190 -0
  40. package/src/observer/evidence.js +23 -0
  41. package/src/observer/evidence.ts +21 -0
  42. package/src/osKeychain.js +209 -0
  43. package/src/osKeychain.ts +245 -0
  44. package/src/providers/anthropic.js +61 -28
  45. package/src/providers/base.js +14 -0
  46. package/src/providers/byokHttp.js +354 -0
  47. package/src/providers/byokHttp.ts +454 -0
  48. package/src/providers/byokStream.js +657 -0
  49. package/src/providers/byokStream.ts +759 -0
  50. package/src/providers/dashscope-byok.js +47 -32
  51. package/src/providers/deepseek.js +43 -39
  52. package/src/providers/gemini.js +73 -38
  53. package/src/providers/moonshot.js +43 -33
  54. package/src/providers/muse.js +10 -10
  55. package/src/providers/ollama.js +46 -31
  56. package/src/providers/openai-compatible.js +57 -32
  57. package/src/providers/openrouter.js +77 -113
  58. package/src/providers/openrouter.ts +99 -118
  59. package/src/providers/qwen-byok.js +46 -23
  60. package/src/providers/toolContracts.js +9 -3
  61. package/src/providers/toolContracts.ts +9 -3
  62. package/src/providers/wireNormalizer.js +238 -0
  63. package/src/providers/wireNormalizer.ts +279 -0
  64. package/src/providers/xai.js +43 -33
  65. package/src/sandbox.js +77 -56
  66. package/src/sandboxPolicy.js +1208 -0
  67. package/src/sandboxPolicy.ts +1300 -0
  68. package/src/sessionJournal.js +47 -0
  69. package/src/sessionJournal.ts +49 -0
  70. package/src/tools/browserAutomator.js +13 -1
  71. package/src/tools/browserAutomator.ts +13 -0
  72. package/src/tools/creativeApps.js +2 -1
  73. package/src/tools/creativeApps.ts +2 -1
  74. package/src/tools/gameAssetFetcher.js +130 -26
  75. package/src/tools/gameAssetHarvester.js +80 -58
  76. package/src/tools/nativeEngine.js +1 -1
  77. package/src/tools/nativeEngine.ts +1 -1
  78. package/src/tools/osSandbox.js +473 -0
  79. package/src/tools/osSandbox.ts +554 -0
  80. package/src/tools/persistentShell.js +8 -3
  81. package/src/tools/registry.js +13 -0
  82. package/src/tools/subprocessEnv.js +197 -0
  83. package/src/tools/subprocessEnv.ts +212 -0
  84. package/src/tools/sysRun.js +39 -6
  85. package/src/tools/sysRun.ts +53 -7
  86. package/src/tools/toolScanner.js +596 -140
  87. package/src/tools/toolScanner.ts +665 -147
  88. package/src/tools/toolSelfRepair.js +243 -114
  89. package/src/tools/toolSelfRepair.ts +262 -111
  90. package/src/tools/webFetch.js +161 -24
  91. package/src/tools/webFetch.ts +157 -22
  92. package/src/tools/webSearch.js +33 -4
  93. package/src/tools/webSearch.ts +27 -4
  94. package/src/tui/sessionPicker.js +132 -35
  95. package/src/tui/sessionPicker.ts +153 -32
  96. package/src/tui/sessionPickerView.js +277 -34
  97. package/src/tui/sessionPickerView.ts +328 -34
  98. package/src/tui/statusLine.js +3 -0
  99. package/src/tui/statusLine.ts +5 -0
  100. package/src/tui/workspaceIdentity.js +133 -0
  101. package/src/tui/workspaceIdentity.ts +146 -0
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Causyne Agent — Optional OS Keychain Master-Key Backend (Sector 6C)
3
+ *
4
+ * Stores and retrieves the 32-byte AES-256-GCM vault master key in the host
5
+ * operating system's credential store when enabled via `CAUSYNE_KEYCHAIN=on|auto|strict`:
6
+ * - macOS (`darwin`): Keychain Services (`/usr/bin/security -i` via stdin, never argv)
7
+ * - Linux (`linux`): libsecret (`secret-tool` via stdin, never argv)
8
+ * - Windows (`win32`): DPAPI `CurrentUser` encrypted blob (`.vault_key.dpapi` via stdin)
9
+ *
10
+ * Defaults to `'off'` so headless CI runners, containers, and existing `.vault_key`
11
+ * users experience zero unexpected OS prompts.
12
+ */
13
+
14
+ import { spawnSync, type SpawnSyncReturns } from 'node:child_process';
15
+ import crypto from 'node:crypto';
16
+ import fs from 'node:fs';
17
+ import path from 'node:path';
18
+
19
+ export type OsKeychainMode = 'off' | 'auto' | 'on' | 'strict';
20
+ export type OsKeychainBackend = 'macos-keychain' | 'linux-secret-service' | 'windows-dpapi' | 'none';
21
+
22
+ export interface OsKeychainCapabilities {
23
+ backend: OsKeychainBackend;
24
+ platform: NodeJS.Platform;
25
+ available: boolean;
26
+ reason: string;
27
+ }
28
+
29
+ export interface KeychainSpawnOptions {
30
+ platform?: NodeJS.Platform | undefined;
31
+ env?: NodeJS.ProcessEnv | undefined;
32
+ spawnSyncImpl?: ((command: string, args: readonly string[], options: Record<string, unknown>) => SpawnSyncReturns<string>) | undefined;
33
+ }
34
+
35
+ const KEYCHAIN_SERVICE = 'causyne-agent';
36
+ const EXPECTED_KEY_BYTES = 32;
37
+ const EXPECTED_KEY_HEX_LEN = EXPECTED_KEY_BYTES * 2;
38
+ const MACOS_SECURITY_BIN = '/usr/bin/security';
39
+
40
+ export function resolveKeychainMode(env: NodeJS.ProcessEnv = process.env): OsKeychainMode {
41
+ const raw = typeof env.CAUSYNE_KEYCHAIN === 'string' ? env.CAUSYNE_KEYCHAIN.trim().toLowerCase() : '';
42
+ if (raw === 'strict') return 'strict';
43
+ if (raw === 'on' || raw === '1' || raw === 'true') return 'on';
44
+ if (raw === 'auto') return 'auto';
45
+ return 'off';
46
+ }
47
+
48
+ export function keychainAccountForVaultDir(vaultDir: string): string {
49
+ const digest = crypto.createHash('sha256').update(path.resolve(vaultDir)).digest('hex').slice(0, 12);
50
+ return `vault-key-${digest}`;
51
+ }
52
+
53
+ function isValidHexKey(raw: string): boolean {
54
+ return raw.length === EXPECTED_KEY_HEX_LEN && /^[0-9a-fA-F]+$/.test(raw);
55
+ }
56
+
57
+ function findInPath(binary: string, env: NodeJS.ProcessEnv = process.env): string | null {
58
+ const pathVal = env.PATH || env.Path || '';
59
+ for (const dir of pathVal.split(path.delimiter)) {
60
+ if (!dir) continue;
61
+ const full = path.join(dir, binary);
62
+ try {
63
+ fs.accessSync(full, fs.constants.X_OK);
64
+ if (fs.statSync(full).isFile()) return full;
65
+ } catch {
66
+ continue;
67
+ }
68
+ }
69
+ return null;
70
+ }
71
+
72
+ export function probeOsKeychain(options: KeychainSpawnOptions = {}): OsKeychainCapabilities {
73
+ const platform = options.platform ?? process.platform;
74
+ const env = options.env ?? process.env;
75
+
76
+ if (platform === 'darwin') {
77
+ const exists = fs.existsSync(MACOS_SECURITY_BIN);
78
+ return {
79
+ backend: exists ? 'macos-keychain' : 'none',
80
+ platform,
81
+ available: exists,
82
+ reason: exists ? 'macOS Keychain Services (/usr/bin/security) available.' : 'macOS security CLI not found.'
83
+ };
84
+ }
85
+
86
+ if (platform === 'linux') {
87
+ const secretTool = findInPath('secret-tool', env);
88
+ return {
89
+ backend: secretTool ? 'linux-secret-service' : 'none',
90
+ platform,
91
+ available: Boolean(secretTool),
92
+ reason: secretTool ? 'Linux Secret Service (secret-tool) available.' : 'secret-tool not installed.'
93
+ };
94
+ }
95
+
96
+ if (platform === 'win32') {
97
+ return {
98
+ backend: 'windows-dpapi',
99
+ platform,
100
+ available: true,
101
+ reason: 'Windows DPAPI (CurrentUser scope) available.'
102
+ };
103
+ }
104
+
105
+ return {
106
+ backend: 'none',
107
+ platform,
108
+ available: false,
109
+ reason: `No OS keychain backend implemented for platform "${platform}".`
110
+ };
111
+ }
112
+
113
+ function dpapiBlobPath(vaultDir: string): string {
114
+ return path.join(path.resolve(vaultDir), '.vault_key.dpapi');
115
+ }
116
+
117
+ /**
118
+ * Loads the 32-byte vault key from the OS credential store, or returns `null` if absent/unavailable.
119
+ */
120
+ export function loadVaultKeyFromKeychain(
121
+ vaultDir: string,
122
+ options: KeychainSpawnOptions = {}
123
+ ): Buffer | null {
124
+ const platform = options.platform ?? process.platform;
125
+ const runner = options.spawnSyncImpl ?? (spawnSync as unknown as NonNullable<KeychainSpawnOptions['spawnSyncImpl']>);
126
+ const account = keychainAccountForVaultDir(vaultDir);
127
+
128
+ if (platform === 'darwin') {
129
+ const res = runner(MACOS_SECURITY_BIN, ['find-generic-password', '-s', KEYCHAIN_SERVICE, '-a', account, '-w'], {
130
+ encoding: 'utf8',
131
+ stdio: ['ignore', 'pipe', 'pipe'],
132
+ timeout: 5000,
133
+ shell: false
134
+ });
135
+ if (res.status !== 0 || typeof res.stdout !== 'string') return null;
136
+ const hex = res.stdout.trim();
137
+ return isValidHexKey(hex) ? Buffer.from(hex, 'hex') : null;
138
+ }
139
+
140
+ if (platform === 'linux') {
141
+ const res = runner('secret-tool', ['lookup', 'service', KEYCHAIN_SERVICE, 'account', account], {
142
+ encoding: 'utf8',
143
+ stdio: ['ignore', 'pipe', 'pipe'],
144
+ timeout: 5000,
145
+ shell: false
146
+ });
147
+ if (res.status !== 0 || typeof res.stdout !== 'string') return null;
148
+ const hex = res.stdout.trim();
149
+ return isValidHexKey(hex) ? Buffer.from(hex, 'hex') : null;
150
+ }
151
+
152
+ if (platform === 'win32') {
153
+ const blobFile = dpapiBlobPath(vaultDir);
154
+ if (!fs.existsSync(blobFile)) return null;
155
+ const protectedBase64 = fs.readFileSync(blobFile, 'utf8').trim();
156
+ if (!protectedBase64) return null;
157
+ const script = [
158
+ 'Add-Type -AssemblyName System.Security',
159
+ '$b64 = [Console]::In.ReadToEnd().Trim()',
160
+ '$enc = [Convert]::FromBase64String($b64)',
161
+ '$plain = [System.Security.Cryptography.ProtectedData]::Unprotect($enc, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)',
162
+ '[Console]::Out.Write([System.Text.Encoding]::UTF8.GetString($plain))'
163
+ ].join('; ');
164
+ const res = runner('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
165
+ input: protectedBase64,
166
+ encoding: 'utf8',
167
+ stdio: ['pipe', 'pipe', 'pipe'],
168
+ timeout: 8000,
169
+ shell: false
170
+ });
171
+ if (res.status !== 0 || typeof res.stdout !== 'string') return null;
172
+ const hex = res.stdout.trim();
173
+ return isValidHexKey(hex) ? Buffer.from(hex, 'hex') : null;
174
+ }
175
+
176
+ return null;
177
+ }
178
+
179
+ /**
180
+ * Persists a 32-byte vault key into the OS credential store without passing
181
+ * secret material on command-line argv (always delivered via stdin).
182
+ */
183
+ export function saveVaultKeyToKeychain(
184
+ vaultDir: string,
185
+ key: Buffer,
186
+ options: KeychainSpawnOptions = {}
187
+ ): boolean {
188
+ if (!Buffer.isBuffer(key) || key.length !== EXPECTED_KEY_BYTES) return false;
189
+ const platform = options.platform ?? process.platform;
190
+ const runner = options.spawnSyncImpl ?? (spawnSync as unknown as NonNullable<KeychainSpawnOptions['spawnSyncImpl']>);
191
+ const account = keychainAccountForVaultDir(vaultDir);
192
+ const hexKey = key.toString('hex');
193
+
194
+ if (platform === 'darwin') {
195
+ // Use interactive `-i` stdin mode so the hex key never appears in process argv (`ps`)
196
+ const stdinCmd = `add-generic-password -U -s "${KEYCHAIN_SERVICE}" -a "${account}" -w "${hexKey}"\n`;
197
+ const res = runner(MACOS_SECURITY_BIN, ['-i'], {
198
+ input: stdinCmd,
199
+ encoding: 'utf8',
200
+ stdio: ['pipe', 'pipe', 'pipe'],
201
+ timeout: 5000,
202
+ shell: false
203
+ });
204
+ return res.status === 0;
205
+ }
206
+
207
+ if (platform === 'linux') {
208
+ const res = runner(
209
+ 'secret-tool',
210
+ ['store', '--label', 'Causyne Agent Vault Key', 'service', KEYCHAIN_SERVICE, 'account', account],
211
+ {
212
+ input: hexKey,
213
+ encoding: 'utf8',
214
+ stdio: ['pipe', 'pipe', 'pipe'],
215
+ timeout: 5000,
216
+ shell: false
217
+ }
218
+ );
219
+ return res.status === 0;
220
+ }
221
+
222
+ if (platform === 'win32') {
223
+ const script = [
224
+ 'Add-Type -AssemblyName System.Security',
225
+ '$hex = [Console]::In.ReadToEnd().Trim()',
226
+ '$bytes = [System.Text.Encoding]::UTF8.GetBytes($hex)',
227
+ '$enc = [System.Security.Cryptography.ProtectedData]::Protect($bytes, $null, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)',
228
+ '[Console]::Out.Write([Convert]::ToBase64String($enc))'
229
+ ].join('; ');
230
+ const res = runner('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
231
+ input: hexKey,
232
+ encoding: 'utf8',
233
+ stdio: ['pipe', 'pipe', 'pipe'],
234
+ timeout: 8000,
235
+ shell: false
236
+ });
237
+ if (res.status !== 0 || typeof res.stdout !== 'string' || !res.stdout.trim()) return false;
238
+ const blobFile = dpapiBlobPath(vaultDir);
239
+ fs.mkdirSync(path.dirname(blobFile), { recursive: true });
240
+ fs.writeFileSync(blobFile, `${res.stdout.trim()}\n`, { encoding: 'utf8', mode: 0o600 });
241
+ return true;
242
+ }
243
+
244
+ return false;
245
+ }
@@ -1,7 +1,19 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
- import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.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';
5
17
 
6
18
  // Models that support server-side tool search (defer_loading + tool_reference
7
19
  // expansion). On these, Causyne hands Anthropic the complete 69-tool catalogue
@@ -203,6 +215,7 @@ export class AnthropicProvider extends LLMProvider {
203
215
  }
204
216
 
205
217
  async chat(messages, options = {}) {
218
+ messages = prepareMessagesForAnthropic(this, messages);
206
219
  // Anthropic separates the system prompt from the message list.
207
220
  const systemBlocks = [];
208
221
  const anthropicMessages = [];
@@ -227,11 +240,11 @@ export class AnthropicProvider extends LLMProvider {
227
240
  const isMidConversation = anthropicMessages.length > 0;
228
241
  const lastEmitted = anthropicMessages[anthropicMessages.length - 1];
229
242
  if (isMidConversation && allowInlineSystem && lastEmitted?.role === 'user') {
230
- anthropicMessages.push({ role: 'system', content: String(msg.content) });
243
+ anthropicMessages.push({ role: 'system', content: String(msg.content ?? '') });
231
244
  continue;
232
245
  }
233
246
 
234
- const block = { type: 'text', text: String(msg.content) };
247
+ const block = { type: 'text', text: String(msg.content ?? '') };
235
248
  // Stable system blocks are cache anchors; everything volatile is ordered
236
249
  // after them by the agent loop, which is what makes the prefix cacheable.
237
250
  // Capped so the reserved tool breakpoint always fits within Anthropic's 4.
@@ -244,8 +257,8 @@ export class AnthropicProvider extends LLMProvider {
244
257
  // Translate OpenAI tool response → Anthropic tool_result block
245
258
  const toolResultBlock = {
246
259
  type: 'tool_result',
247
- tool_use_id: msg.tool_call_id,
248
- content: msg.content
260
+ tool_use_id: sanitizeProviderToolId(msg.tool_call_id, 'toolu', 0),
261
+ content: msg.content ?? ''
249
262
  };
250
263
  // Anthropic requires consecutive tool_results to be grouped into a single 'user' message
251
264
  const lastMsg = anthropicMessages[anthropicMessages.length - 1];
@@ -267,23 +280,25 @@ export class AnthropicProvider extends LLMProvider {
267
280
  if (msg.content) {
268
281
  contentBlocks.push({ type: 'text', text: msg.content });
269
282
  }
270
- for (const tc of msg.tool_calls) {
283
+ for (let idx = 0; idx < msg.tool_calls.length; idx++) {
284
+ const tc = msg.tool_calls[idx];
271
285
  contentBlocks.push({
272
286
  type: 'tool_use',
273
- id: tc.id,
274
- name: tc.function.name,
275
- input: typeof tc.function.arguments === 'string' ? JSON.parse(tc.function.arguments || '{}') : (tc.function.arguments || {})
287
+ id: sanitizeProviderToolId(tc.id, 'toolu', idx),
288
+ name: normalizeToolName(tc.function?.name || ''),
289
+ input: safeParseJsonObject(tc.function?.arguments)
276
290
  });
277
291
  }
278
292
  anthropicMessages.push({ role: 'assistant', content: contentBlocks });
279
293
  } else {
280
294
  // These are the loop's own bookkeeping. The API rejects unknown message
281
295
  // properties, so every one of them has to be stripped here.
282
- const { cacheAnchor, thinking_blocks, reasoning_content, ...clean } = msg;
283
- anthropicMessages.push(clean);
296
+ const { cacheAnchor, thinking_blocks, reasoning_content, spillPath, ...clean } = msg;
297
+ anthropicMessages.push({ ...clean, content: clean.content ?? '' });
284
298
  }
285
299
  }
286
300
 
301
+ const apiKey = requireApiKey(this.apiKey, 'Anthropic');
287
302
  const payload = {
288
303
  model: this.model,
289
304
  system: systemBlocks,
@@ -293,16 +308,22 @@ export class AnthropicProvider extends LLMProvider {
293
308
  };
294
309
 
295
310
  if (!this.rejectsSamplingParameters()) {
296
- payload.temperature = options.temperature || 0.1;
311
+ payload.temperature = resolveTemperature(options.temperature, 0.1);
297
312
  }
298
313
 
299
314
  const thinking = this.buildThinking();
300
- if (thinking) payload.thinking = thinking;
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;
320
+ }
301
321
 
302
322
  const effort = this.resolveEffort();
303
323
  // effort lives inside output_config, not at the top level.
304
324
  if (effort) payload.output_config = { ...(payload.output_config || {}), effort };
305
325
 
326
+ let freeFormPaths = new Map();
306
327
  if (options.tools && options.tools.length > 0) {
307
328
  const useToolSearch = this.supportsToolSearch();
308
329
  const coreToolCount = Number.isInteger(options.coreToolCount) ? options.coreToolCount : options.tools.length;
@@ -312,6 +333,7 @@ export class AnthropicProvider extends LLMProvider {
312
333
  coreToolCount
313
334
  });
314
335
  const converted = scanReport.adaptedTools;
336
+ freeFormPaths = scanReport.freeFormPaths;
315
337
 
316
338
  if (useToolSearch) {
317
339
  payload.tools = [
@@ -335,22 +357,32 @@ export class AnthropicProvider extends LLMProvider {
335
357
  }
336
358
  }
337
359
 
338
- const response = await fetch(this.baseUrl, {
360
+ const requestOpts = {
361
+ url: this.baseUrl,
339
362
  method: 'POST',
340
363
  headers: {
341
364
  'Content-Type': 'application/json',
342
- 'x-api-key': this.apiKey,
365
+ 'x-api-key': apiKey,
343
366
  'anthropic-version': '2023-06-01'
344
367
  },
345
- body: JSON.stringify(payload)
346
- });
347
-
348
- if (!response.ok) {
349
- const errorData = await response.text();
350
- throw new Error(`Anthropic API Error (${response.status}): ${errorData}`);
351
- }
368
+ signal: options.signal,
369
+ timeoutMs: options.timeoutMs,
370
+ providerLabel: 'Anthropic',
371
+ secrets: [apiKey],
372
+ hasApiKey: true
373
+ };
352
374
 
353
- const data = await response.json();
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
+ });
354
386
 
355
387
  // Extract text content and tool calls
356
388
  let content = '';
@@ -358,21 +390,22 @@ export class AnthropicProvider extends LLMProvider {
358
390
  const thinkingBlocks = [];
359
391
  let reasoningContent = '';
360
392
 
361
- for (const block of data.content) {
393
+ for (const block of (Array.isArray(data.content) ? data.content : [])) {
362
394
  if (block.type === 'thinking' || block.type === 'redacted_thinking') {
363
395
  // Kept verbatim for the echo above. The readable summary, when the user
364
396
  // asked for one, is surfaced separately.
365
397
  thinkingBlocks.push(block);
366
398
  if (typeof block.thinking === 'string') reasoningContent += block.thinking;
367
399
  } else if (block.type === 'text') {
368
- content += block.text;
400
+ content += block.text || '';
369
401
  } else if (block.type === 'tool_use') {
402
+ const callName = normalizeToolName(block.name || '');
370
403
  toolCalls.push({
371
- id: block.id,
404
+ id: sanitizeProviderToolId(block.id, 'toolu', toolCalls.length),
372
405
  type: 'function',
373
406
  function: {
374
- name: block.name,
375
- arguments: JSON.stringify(block.input)
407
+ name: callName,
408
+ arguments: serializeAndDecodeArguments(block.input || {}, callName, freeFormPaths)
376
409
  }
377
410
  });
378
411
  }
@@ -250,6 +250,20 @@ export class LLMProvider {
250
250
  */
251
251
  normalizeImageBlocks(msg) {
252
252
  if (!Array.isArray(msg.content)) return msg;
253
+ if (this.imagePayloadFormat === 'anthropic') {
254
+ const content = msg.content.map(block => {
255
+ if (block && block.type === 'image_url' && typeof block.image_url?.url === 'string') {
256
+ const commaIdx = block.image_url.url.indexOf('base64,');
257
+ if (commaIdx !== -1 && block.image_url.url.startsWith('data:')) {
258
+ const mediaType = block.image_url.url.slice(5, commaIdx).split(';')[0] || 'image/png';
259
+ const data = block.image_url.url.slice(commaIdx + 7);
260
+ return { type: 'image', source: { type: 'base64', media_type: mediaType, data } };
261
+ }
262
+ }
263
+ return block;
264
+ });
265
+ return { ...msg, content };
266
+ }
253
267
  if (this.imagePayloadFormat !== 'openai') return msg;
254
268
 
255
269
  const content = msg.content.map(block => {