@causyne/agent 1.20.118 → 1.20.120

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 (58) hide show
  1. package/package.json +1 -1
  2. package/src/agentLoop.js +29 -12
  3. package/src/agentLoop.ts +29 -16
  4. package/src/browser/causyneBrowser.js +231 -136
  5. package/src/browser/causyneBrowser.ts +229 -140
  6. package/src/browser/searchProviders.js +41 -30
  7. package/src/browser/searchProviders.ts +24 -14
  8. package/src/browser/workspacePathSafety.js +50 -0
  9. package/src/browser/workspacePathSafety.ts +50 -0
  10. package/src/browser/workspacePreview.js +27 -4
  11. package/src/browser/workspacePreview.ts +28 -4
  12. package/src/cliMode.js +1 -1
  13. package/src/commands.js +5 -13
  14. package/src/creative/liveBridge.js +34 -1
  15. package/src/creative/liveBridge.ts +28 -1
  16. package/src/observer/evidence.js +23 -0
  17. package/src/observer/evidence.ts +21 -0
  18. package/src/providers/anthropic.js +33 -17
  19. package/src/providers/base.js +14 -0
  20. package/src/providers/dashscope-byok.js +13 -7
  21. package/src/providers/deepseek.js +13 -18
  22. package/src/providers/gemini.js +33 -25
  23. package/src/providers/moonshot.js +13 -12
  24. package/src/providers/ollama.js +21 -21
  25. package/src/providers/openai-compatible.js +12 -19
  26. package/src/providers/openrouter.js +20 -90
  27. package/src/providers/openrouter.ts +31 -94
  28. package/src/providers/qwen-byok.js +13 -7
  29. package/src/providers/toolContracts.js +9 -3
  30. package/src/providers/toolContracts.ts +9 -3
  31. package/src/providers/wireNormalizer.js +238 -0
  32. package/src/providers/wireNormalizer.ts +279 -0
  33. package/src/providers/xai.js +13 -12
  34. package/src/tools/browserAutomator.js +13 -1
  35. package/src/tools/browserAutomator.ts +13 -0
  36. package/src/tools/creativeApps.js +2 -1
  37. package/src/tools/creativeApps.ts +2 -1
  38. package/src/tools/gameAssetFetcher.js +130 -26
  39. package/src/tools/gameAssetHarvester.js +80 -58
  40. package/src/tools/nativeEngine.js +1 -1
  41. package/src/tools/nativeEngine.ts +1 -1
  42. package/src/tools/registry.js +13 -0
  43. package/src/tools/toolScanner.js +596 -140
  44. package/src/tools/toolScanner.ts +665 -147
  45. package/src/tools/toolSelfRepair.js +243 -114
  46. package/src/tools/toolSelfRepair.ts +262 -111
  47. package/src/tools/webFetch.js +161 -24
  48. package/src/tools/webFetch.ts +157 -22
  49. package/src/tools/webSearch.js +33 -4
  50. package/src/tools/webSearch.ts +27 -4
  51. package/src/tui/sessionPicker.js +132 -35
  52. package/src/tui/sessionPicker.ts +153 -32
  53. package/src/tui/sessionPickerView.js +277 -34
  54. package/src/tui/sessionPickerView.ts +328 -34
  55. package/src/tui/statusLine.js +3 -0
  56. package/src/tui/statusLine.ts +5 -0
  57. package/src/tui/workspaceIdentity.js +133 -0
  58. package/src/tui/workspaceIdentity.ts +146 -0
@@ -1,7 +1,13 @@
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';
5
11
 
6
12
  // Models that support server-side tool search (defer_loading + tool_reference
7
13
  // expansion). On these, Causyne hands Anthropic the complete 69-tool catalogue
@@ -203,6 +209,7 @@ export class AnthropicProvider extends LLMProvider {
203
209
  }
204
210
 
205
211
  async chat(messages, options = {}) {
212
+ messages = prepareMessagesForAnthropic(this, messages);
206
213
  // Anthropic separates the system prompt from the message list.
207
214
  const systemBlocks = [];
208
215
  const anthropicMessages = [];
@@ -227,11 +234,11 @@ export class AnthropicProvider extends LLMProvider {
227
234
  const isMidConversation = anthropicMessages.length > 0;
228
235
  const lastEmitted = anthropicMessages[anthropicMessages.length - 1];
229
236
  if (isMidConversation && allowInlineSystem && lastEmitted?.role === 'user') {
230
- anthropicMessages.push({ role: 'system', content: String(msg.content) });
237
+ anthropicMessages.push({ role: 'system', content: String(msg.content ?? '') });
231
238
  continue;
232
239
  }
233
240
 
234
- const block = { type: 'text', text: String(msg.content) };
241
+ const block = { type: 'text', text: String(msg.content ?? '') };
235
242
  // Stable system blocks are cache anchors; everything volatile is ordered
236
243
  // after them by the agent loop, which is what makes the prefix cacheable.
237
244
  // Capped so the reserved tool breakpoint always fits within Anthropic's 4.
@@ -244,8 +251,8 @@ export class AnthropicProvider extends LLMProvider {
244
251
  // Translate OpenAI tool response → Anthropic tool_result block
245
252
  const toolResultBlock = {
246
253
  type: 'tool_result',
247
- tool_use_id: msg.tool_call_id,
248
- content: msg.content
254
+ tool_use_id: sanitizeProviderToolId(msg.tool_call_id, 'toolu', 0),
255
+ content: msg.content ?? ''
249
256
  };
250
257
  // Anthropic requires consecutive tool_results to be grouped into a single 'user' message
251
258
  const lastMsg = anthropicMessages[anthropicMessages.length - 1];
@@ -267,20 +274,21 @@ export class AnthropicProvider extends LLMProvider {
267
274
  if (msg.content) {
268
275
  contentBlocks.push({ type: 'text', text: msg.content });
269
276
  }
270
- for (const tc of msg.tool_calls) {
277
+ for (let idx = 0; idx < msg.tool_calls.length; idx++) {
278
+ const tc = msg.tool_calls[idx];
271
279
  contentBlocks.push({
272
280
  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 || {})
281
+ id: sanitizeProviderToolId(tc.id, 'toolu', idx),
282
+ name: normalizeToolName(tc.function?.name || ''),
283
+ input: safeParseJsonObject(tc.function?.arguments)
276
284
  });
277
285
  }
278
286
  anthropicMessages.push({ role: 'assistant', content: contentBlocks });
279
287
  } else {
280
288
  // These are the loop's own bookkeeping. The API rejects unknown message
281
289
  // properties, so every one of them has to be stripped here.
282
- const { cacheAnchor, thinking_blocks, reasoning_content, ...clean } = msg;
283
- anthropicMessages.push(clean);
290
+ const { cacheAnchor, thinking_blocks, reasoning_content, spillPath, ...clean } = msg;
291
+ anthropicMessages.push({ ...clean, content: clean.content ?? '' });
284
292
  }
285
293
  }
286
294
 
@@ -297,12 +305,18 @@ export class AnthropicProvider extends LLMProvider {
297
305
  }
298
306
 
299
307
  const thinking = this.buildThinking();
300
- if (thinking) payload.thinking = thinking;
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;
313
+ }
301
314
 
302
315
  const effort = this.resolveEffort();
303
316
  // effort lives inside output_config, not at the top level.
304
317
  if (effort) payload.output_config = { ...(payload.output_config || {}), effort };
305
318
 
319
+ let freeFormPaths = new Map();
306
320
  if (options.tools && options.tools.length > 0) {
307
321
  const useToolSearch = this.supportsToolSearch();
308
322
  const coreToolCount = Number.isInteger(options.coreToolCount) ? options.coreToolCount : options.tools.length;
@@ -312,6 +326,7 @@ export class AnthropicProvider extends LLMProvider {
312
326
  coreToolCount
313
327
  });
314
328
  const converted = scanReport.adaptedTools;
329
+ freeFormPaths = scanReport.freeFormPaths;
315
330
 
316
331
  if (useToolSearch) {
317
332
  payload.tools = [
@@ -358,21 +373,22 @@ export class AnthropicProvider extends LLMProvider {
358
373
  const thinkingBlocks = [];
359
374
  let reasoningContent = '';
360
375
 
361
- for (const block of data.content) {
376
+ for (const block of (Array.isArray(data.content) ? data.content : [])) {
362
377
  if (block.type === 'thinking' || block.type === 'redacted_thinking') {
363
378
  // Kept verbatim for the echo above. The readable summary, when the user
364
379
  // asked for one, is surfaced separately.
365
380
  thinkingBlocks.push(block);
366
381
  if (typeof block.thinking === 'string') reasoningContent += block.thinking;
367
382
  } else if (block.type === 'text') {
368
- content += block.text;
383
+ content += block.text || '';
369
384
  } else if (block.type === 'tool_use') {
385
+ const callName = normalizeToolName(block.name || '');
370
386
  toolCalls.push({
371
- id: block.id,
387
+ id: sanitizeProviderToolId(block.id, 'toolu', toolCalls.length),
372
388
  type: 'function',
373
389
  function: {
374
- name: block.name,
375
- arguments: JSON.stringify(block.input)
390
+ name: callName,
391
+ arguments: serializeAndDecodeArguments(block.input || {}, callName, freeFormPaths)
376
392
  }
377
393
  });
378
394
  }
@@ -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 => {
@@ -2,6 +2,7 @@ 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 } from '../tools/toolScanner.js';
5
+ import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
5
6
 
6
7
  // Direct DashScope API connection for BYOK (unlike dashscope.js which is the proxy for Free Demo)
7
8
  export class DashscopeByokProvider extends LLMProvider {
@@ -44,10 +45,12 @@ export class DashscopeByokProvider extends LLMProvider {
44
45
  payload.response_format = { type: 'json_object' };
45
46
  }
46
47
 
47
- if (options.tools) {
48
+ let freeFormPaths = new Map();
49
+ if (options.tools && options.tools.length > 0) {
48
50
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'dashscope');
49
51
  payload.tools = scanReport.adaptedTools;
50
52
  payload.tool_choice = "auto";
53
+ freeFormPaths = scanReport.freeFormPaths;
51
54
  }
52
55
 
53
56
  const response = await fetch(this.baseUrl, {
@@ -73,13 +76,16 @@ export class DashscopeByokProvider extends LLMProvider {
73
76
  }
74
77
 
75
78
  const data = await response.json();
76
- const content = data.choices[0].message.content;
77
- const toolCalls = data.choices[0].message.tool_calls;
78
-
79
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
80
+ prefix: 'call_dashscope',
81
+ freeFormPaths
82
+ });
83
+
79
84
  return {
80
- content: content || '',
81
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
82
- usage: this.normalizeUsage(data.usage)
85
+ content: normalized.content,
86
+ toolCalls: normalized.toolCalls,
87
+ reasoningContent: normalized.reasoningContent,
88
+ usage: this.normalizeUsage(normalized.rawUsage)
83
89
  };
84
90
  }
85
91
  }
@@ -2,6 +2,7 @@ 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 } from '../tools/toolScanner.js';
5
+ import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
5
6
 
6
7
  export class DeepSeekProvider extends LLMProvider {
7
8
  constructor(config) {
@@ -38,10 +39,12 @@ export class DeepSeekProvider extends LLMProvider {
38
39
  throw new Error("API key is required.");
39
40
  }
40
41
 
41
- if (options.tools) {
42
+ let freeFormPaths = new Map();
43
+ if (options.tools && options.tools.length > 0) {
42
44
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'deepseek');
43
45
  payload.tools = scanReport.adaptedTools;
44
46
  payload.tool_choice = "auto";
47
+ freeFormPaths = scanReport.freeFormPaths;
45
48
  }
46
49
 
47
50
  const response = await fetch(targetUrl, {
@@ -56,24 +59,16 @@ export class DeepSeekProvider extends LLMProvider {
56
59
  }
57
60
 
58
61
  const data = await response.json();
59
- let content = '';
60
- let toolCalls = [];
61
-
62
- // Support both direct DeepSeek API format and our Cloudflare Proxy format
63
- if (data.reply !== undefined) {
64
- // Proxy Format
65
- content = data.reply || '';
66
- toolCalls = data.tool_calls || [];
67
- } else if (data.choices && data.choices[0] && data.choices[0].message) {
68
- // Direct API Format
69
- content = data.choices[0].message.content || '';
70
- toolCalls = data.choices[0].message.tool_calls || [];
71
- }
72
-
62
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
63
+ prefix: 'call_deepseek',
64
+ freeFormPaths
65
+ });
66
+
73
67
  return {
74
- content: content,
75
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
76
- usage: this.normalizeUsage(data.usage || { prompt_tokens: 0, completion_tokens: 0 })
68
+ content: normalized.content,
69
+ toolCalls: normalized.toolCalls,
70
+ reasoningContent: normalized.reasoningContent,
71
+ usage: this.normalizeUsage(normalized.rawUsage)
77
72
  };
78
73
  }
79
74
  }
@@ -5,8 +5,14 @@ import {
5
5
  scanAndAdaptToolsForProvider,
6
6
  decodeFreeFormArguments,
7
7
  adaptSchemaForGemini,
8
- isEmptyObjectSchema
8
+ isEmptyObjectSchema,
9
+ normalizeToolName
9
10
  } from '../tools/toolScanner.js';
11
+ import {
12
+ safeParseJsonObject,
13
+ sanitizeProviderToolId,
14
+ serializeAndDecodeArguments
15
+ } from './wireNormalizer.js';
10
16
 
11
17
  export { adaptSchemaForGemini, isEmptyObjectSchema };
12
18
 
@@ -134,25 +140,29 @@ export class GeminiProvider extends LLMProvider {
134
140
  for (const tc of msg.tool_calls) {
135
141
  parts.push({
136
142
  functionCall: {
137
- name: tc.function.name,
138
- args: typeof tc.function.arguments === 'string'
139
- ? JSON.parse(tc.function.arguments || '{}')
140
- : (tc.function.arguments || {})
143
+ name: normalizeToolName(tc.function?.name || ''),
144
+ args: safeParseJsonObject(tc.function?.arguments)
141
145
  }
142
146
  });
143
147
  }
144
148
  contents.push({ role, parts });
145
149
  } else if (msg.role === 'tool') {
146
- // Add tool response
147
- contents.push({
148
- role: 'user', // Gemini expects tool responses to come from 'user' or 'function'
149
- parts: [{
150
- functionResponse: {
151
- name: msg.name,
152
- response: { result: msg.content }
153
- }
154
- }]
155
- });
150
+ // Batch consecutive tool responses into a single 'user' message for parallel calls.
151
+ const responsePart = {
152
+ functionResponse: {
153
+ name: normalizeToolName(msg.name || ''),
154
+ response: { result: msg.content ?? '' }
155
+ }
156
+ };
157
+ const lastEntry = contents[contents.length - 1];
158
+ if (lastEntry && lastEntry.role === 'user' && Array.isArray(lastEntry.parts) && lastEntry.parts[0]?.functionResponse) {
159
+ lastEntry.parts.push(responsePart);
160
+ } else {
161
+ contents.push({
162
+ role: 'user',
163
+ parts: [responsePart]
164
+ });
165
+ }
156
166
  } else {
157
167
  if (Array.isArray(msg.content)) {
158
168
  const mappedParts = msg.content.map(part => {
@@ -185,7 +195,7 @@ export class GeminiProvider extends LLMProvider {
185
195
  });
186
196
  contents.push({ role, parts: mappedParts });
187
197
  } else {
188
- contents.push({ role, parts: [{ text: msg.content }] });
198
+ contents.push({ role, parts: [{ text: msg.content ?? '' }] });
189
199
  }
190
200
  }
191
201
  }
@@ -232,22 +242,20 @@ export class GeminiProvider extends LLMProvider {
232
242
 
233
243
  let content = '';
234
244
  let toolCalls = [];
245
+ const candidateParts = Array.isArray(firstCandidate.content?.parts) ? firstCandidate.content.parts : [];
235
246
 
236
- for (const part of firstCandidate.content.parts) {
247
+ for (const part of candidateParts) {
237
248
  if (part.text) {
238
249
  content += part.text;
239
250
  } else if (part.functionCall) {
240
- const paths = freeFormPaths.get(part.functionCall.name) || [];
241
- const args = decodeFreeFormArguments(
242
- part.functionCall.args || {},
243
- paths
244
- );
251
+ const callName = normalizeToolName(part.functionCall.name || '');
252
+ const serializedArgs = serializeAndDecodeArguments(part.functionCall.args || {}, callName, freeFormPaths);
245
253
  toolCalls.push({
246
- id: `call_${Math.random().toString(36).substr(2, 9)}`,
254
+ id: sanitizeProviderToolId(part.functionCall.id, 'call_gemini', toolCalls.length),
247
255
  type: 'function',
248
256
  function: {
249
- name: part.functionCall.name,
250
- arguments: JSON.stringify(args)
257
+ name: callName,
258
+ arguments: serializedArgs
251
259
  }
252
260
  });
253
261
  }
@@ -2,6 +2,7 @@ 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 } from '../tools/toolScanner.js';
5
+ import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
5
6
 
6
7
  export class MoonshotProvider extends LLMProvider {
7
8
  constructor(config) {
@@ -37,10 +38,12 @@ export class MoonshotProvider extends LLMProvider {
37
38
  throw new Error(`Moonshot AI (Kimi) API requires a valid API key (BYOK mode). Please set it in your configuration.`);
38
39
  }
39
40
 
40
- if (options.tools) {
41
+ let freeFormPaths = new Map();
42
+ if (options.tools && options.tools.length > 0) {
41
43
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'moonshot');
42
44
  payload.tools = scanReport.adaptedTools;
43
45
  payload.tool_choice = "auto";
46
+ freeFormPaths = scanReport.freeFormPaths;
44
47
  }
45
48
 
46
49
  const response = await fetch(this.baseUrl, {
@@ -55,18 +58,16 @@ export class MoonshotProvider extends LLMProvider {
55
58
  }
56
59
 
57
60
  const data = await response.json();
58
- let content = '';
59
- let toolCalls = [];
60
-
61
- if (data.choices && data.choices[0] && data.choices[0].message) {
62
- content = data.choices[0].message.content || '';
63
- toolCalls = data.choices[0].message.tool_calls || [];
64
- }
65
-
61
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
62
+ prefix: 'call_moonshot',
63
+ freeFormPaths
64
+ });
65
+
66
66
  return {
67
- content: content,
68
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
69
- usage: this.normalizeUsage(data.usage || { prompt_tokens: 0, completion_tokens: 0 })
67
+ content: normalized.content,
68
+ toolCalls: normalized.toolCalls,
69
+ reasoningContent: normalized.reasoningContent,
70
+ usage: this.normalizeUsage(normalized.rawUsage)
70
71
  };
71
72
  }
72
73
  }
@@ -2,6 +2,12 @@ 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 } from '../tools/toolScanner.js';
5
+ import {
6
+ normalizeMessagesForOllama,
7
+ normalizeOpenAIToolCalls,
8
+ extractTextToolCalls
9
+ } from './wireNormalizer.js';
10
+ import { stripToolCallMarkup } from '../implementationPlan.js';
5
11
 
6
12
  export class OllamaProvider extends LLMProvider {
7
13
  constructor(config) {
@@ -42,7 +48,7 @@ export class OllamaProvider extends LLMProvider {
42
48
  }
43
49
 
44
50
  async chat(messages, options = {}) {
45
- const sanitizedMessages = this.prepareMessages(messages);
51
+ const sanitizedMessages = normalizeMessagesForOllama(this.prepareMessages(messages));
46
52
 
47
53
  const payload = {
48
54
  model: this.model,
@@ -53,9 +59,11 @@ export class OllamaProvider extends LLMProvider {
53
59
  }
54
60
  };
55
61
 
56
- if (options.tools) {
62
+ let freeFormPaths = new Map();
63
+ if (options.tools && options.tools.length > 0) {
57
64
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'ollama');
58
65
  payload.tools = scanReport.adaptedTools;
66
+ freeFormPaths = scanReport.freeFormPaths;
59
67
  }
60
68
 
61
69
  const response = await fetch(this.baseUrl, {
@@ -71,28 +79,20 @@ export class OllamaProvider extends LLMProvider {
71
79
 
72
80
  const data = await response.json();
73
81
 
74
- // Ollama returns tool calls with no id. Every stage downstream — the tool
75
- // result messages, the approval map, and sanitizeSequences, which filters an
76
- // assistant turn's tool_calls against the ids of the results that follow it —
77
- // keys on that id. Without one, sanitizeSequences matched nothing and
78
- // stripped every tool call out of the history on the very next step, so a
79
- // local model lost all memory of the actions it had just taken.
80
- const rawToolCalls = data.message?.tool_calls || [];
81
- const toolCalls = rawToolCalls.map((call, index) => ({
82
- id: call.id || `call_ollama_${Date.now()}_${index}`,
83
- type: 'function',
84
- function: {
85
- name: call.function?.name,
86
- // Ollama hands back a parsed object where the OpenAI shape carries a
87
- // JSON string. Normalise so the whole pipeline sees one contract.
88
- arguments: typeof call.function?.arguments === 'string'
89
- ? call.function.arguments
90
- : JSON.stringify(call.function?.arguments || {})
82
+ // Ollama returns tool calls with no id and object arguments instead of JSON strings.
83
+ // Normalize through wireNormalizer so sanitizeSequences and toolSelfRepair see one contract.
84
+ let content = typeof data.message?.content === 'string' ? data.message.content : '';
85
+ let toolCalls = normalizeOpenAIToolCalls(data.message?.tool_calls, freeFormPaths, 'call_ollama');
86
+ if (toolCalls.length === 0 && content) {
87
+ const extracted = extractTextToolCalls(content, 'call_ollama_text', freeFormPaths);
88
+ if (extracted.length > 0) {
89
+ toolCalls = extracted;
90
+ content = stripToolCallMarkup(content).trim();
91
91
  }
92
- }));
92
+ }
93
93
 
94
94
  return {
95
- content: data.message?.content || '',
95
+ content,
96
96
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
97
97
  usage: {
98
98
  promptTokens: data.prompt_eval_count || 0,
@@ -2,6 +2,7 @@ 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 } from '../tools/toolScanner.js';
5
+ import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
5
6
 
6
7
  export class OpenAICompatibleProvider extends LLMProvider {
7
8
  constructor(config) {
@@ -37,10 +38,12 @@ export class OpenAICompatibleProvider extends LLMProvider {
37
38
  payload.response_format = { type: 'json_object' };
38
39
  }
39
40
 
40
- if (options.tools) {
41
+ let freeFormPaths = new Map();
42
+ if (options.tools && options.tools.length > 0) {
41
43
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
42
44
  payload.tools = scanReport.adaptedTools;
43
45
  payload.tool_choice = "auto";
46
+ freeFormPaths = scanReport.freeFormPaths;
44
47
  }
45
48
 
46
49
  const response = await fetch(this.baseUrl, {
@@ -58,26 +61,16 @@ export class OpenAICompatibleProvider extends LLMProvider {
58
61
  }
59
62
 
60
63
  const data = await response.json();
61
- let content = '';
62
- let toolCalls = [];
63
-
64
- let reasoningContent = '';
65
-
66
- if (data.choices && data.choices[0] && data.choices[0].message) {
67
- const message = data.choices[0].message;
68
- content = message.content || '';
69
- toolCalls = message.tool_calls || [];
70
- // DeepSeek and several compatible endpoints return the chain of thought
71
- // in a sibling field. It was being discarded, so the reasoning the user
72
- // paid for never reached them.
73
- reasoningContent = message.reasoning_content || message.reasoning || '';
74
- }
64
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
65
+ prefix: 'call_oai',
66
+ freeFormPaths
67
+ });
75
68
 
76
69
  return {
77
- content: content,
78
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
79
- reasoningContent: reasoningContent || undefined,
80
- usage: this.normalizeUsage(data.usage || { prompt_tokens: 0, completion_tokens: 0 })
70
+ content: normalized.content,
71
+ toolCalls: normalized.toolCalls,
72
+ reasoningContent: normalized.reasoningContent,
73
+ usage: this.normalizeUsage(normalized.rawUsage)
81
74
  };
82
75
  }
83
76
  }