@causyne/agent 1.20.120 → 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 (59) 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 +22 -339
  9. package/src/agentLoop.ts +40 -347
  10. package/src/autoUpdate.js +111 -8
  11. package/src/autoUpdate.ts +144 -8
  12. package/src/cliMode.js +16 -2
  13. package/src/commands.js +10 -9
  14. package/src/config.js +42 -63
  15. package/src/configVault.js +204 -0
  16. package/src/configVault.ts +213 -0
  17. package/src/core/contextCompactor.js +70 -11
  18. package/src/core/contextCompactor.ts +83 -11
  19. package/src/dynamicCatalogue.js +42 -73
  20. package/src/dynamicCatalogue.ts +74 -60
  21. package/src/entrypoint.js +77 -4
  22. package/src/headlessCli.js +304 -0
  23. package/src/headlessCli.ts +380 -0
  24. package/src/mcp/mcpClient.js +38 -11
  25. package/src/mcp/mcpClient.ts +44 -11
  26. package/src/mcp/mcpRegistry.js +2 -5
  27. package/src/mcp/mcpRegistry.ts +2 -5
  28. package/src/mcp/mcpSecurity.js +189 -0
  29. package/src/mcp/mcpSecurity.ts +190 -0
  30. package/src/osKeychain.js +209 -0
  31. package/src/osKeychain.ts +245 -0
  32. package/src/providers/anthropic.js +28 -11
  33. package/src/providers/byokHttp.js +354 -0
  34. package/src/providers/byokHttp.ts +454 -0
  35. package/src/providers/byokStream.js +657 -0
  36. package/src/providers/byokStream.ts +759 -0
  37. package/src/providers/dashscope-byok.js +34 -25
  38. package/src/providers/deepseek.js +31 -22
  39. package/src/providers/gemini.js +40 -13
  40. package/src/providers/moonshot.js +31 -22
  41. package/src/providers/muse.js +10 -10
  42. package/src/providers/ollama.js +25 -10
  43. package/src/providers/openai-compatible.js +46 -14
  44. package/src/providers/openrouter.js +63 -29
  45. package/src/providers/openrouter.ts +73 -29
  46. package/src/providers/qwen-byok.js +33 -16
  47. package/src/providers/xai.js +31 -22
  48. package/src/sandbox.js +77 -56
  49. package/src/sandboxPolicy.js +1208 -0
  50. package/src/sandboxPolicy.ts +1300 -0
  51. package/src/sessionJournal.js +47 -0
  52. package/src/sessionJournal.ts +49 -0
  53. package/src/tools/osSandbox.js +473 -0
  54. package/src/tools/osSandbox.ts +554 -0
  55. package/src/tools/persistentShell.js +8 -3
  56. package/src/tools/subprocessEnv.js +197 -0
  57. package/src/tools/subprocessEnv.ts +212 -0
  58. package/src/tools/sysRun.js +39 -6
  59. package/src/tools/sysRun.ts +53 -7
@@ -3,6 +3,12 @@ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
4
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
5
5
  import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
6
+ import {
7
+ requireApiKey,
8
+ resolveTemperature,
9
+ safeProviderFetchJson
10
+ } from './byokHttp.js';
11
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
6
12
 
7
13
  // Direct DashScope API connection for BYOK (unlike dashscope.js which is the proxy for Free Demo)
8
14
  export class DashscopeByokProvider extends LLMProvider {
@@ -14,6 +20,7 @@ export class DashscopeByokProvider extends LLMProvider {
14
20
  else if (url.endsWith('/v1/')) url += 'chat/completions';
15
21
 
16
22
  this.baseUrl = url;
23
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
17
24
  this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['dashscope-byok']);
18
25
  this.apiKey = config.apiKey;
19
26
  this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7', 'kimi-k2.5', 'kimi-k2.7'];
@@ -23,22 +30,15 @@ export class DashscopeByokProvider extends LLMProvider {
23
30
  }
24
31
 
25
32
  async chat(messages, options = {}) {
26
- const ALLOWED = [
27
- "qwen3.7-max", "qwen3.7-plus", "kimi-k2.7-code", "kimi-k2.6",
28
- "kimi-k2.5", "kimi-k2-thinking", "Moonshot-Kimi-K2-Instruct",
29
- "deepseek-v4-flash", "deepseek-v4-pro"
30
- ];
31
- let activeModel = this.model;
32
- if (!ALLOWED.includes(activeModel)) {
33
- activeModel = 'qwen3.7-plus';
34
- }
33
+ const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
34
+ const activeModel = this.model || DEFAULT_MODEL_BY_PROVIDER['dashscope-byok'] || 'qwen3.7-plus';
35
35
 
36
36
  const sanitizedMessages = this.prepareMessages(messages);
37
37
 
38
38
  const payload = {
39
39
  model: activeModel,
40
40
  messages: sanitizedMessages,
41
- temperature: options.temperature || 0.1,
41
+ temperature: resolveTemperature(options.temperature, 0.1),
42
42
  };
43
43
 
44
44
  if (options.jsonMode) {
@@ -53,29 +53,38 @@ export class DashscopeByokProvider extends LLMProvider {
53
53
  freeFormPaths = scanReport.freeFormPaths;
54
54
  }
55
55
 
56
- const response = await fetch(this.baseUrl, {
56
+ const requestOpts = {
57
+ url: this.baseUrl,
57
58
  method: 'POST',
58
59
  headers: {
59
60
  'Content-Type': 'application/json',
60
- 'Authorization': `Bearer ${this.apiKey}`
61
+ 'Authorization': `Bearer ${apiKey}`
61
62
  },
62
- body: JSON.stringify(payload)
63
- });
64
-
65
- if (!response.ok) {
66
- const errorData = await response.text();
67
-
68
- // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
69
- if (response.status === 401 && this.apiKey && this.apiKey.startsWith('sk-ws-')) {
70
- if (!this.baseUrl.includes('ws-')) {
63
+ signal: options.signal,
64
+ timeoutMs: options.timeoutMs,
65
+ providerLabel: 'Qwen DashScope',
66
+ secrets: [apiKey],
67
+ hasApiKey: true,
68
+ allowInsecureHttp: this.allowInsecureHttp,
69
+ onHttpError: ({ status }) => {
70
+ // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
71
+ if (status === 401 && apiKey.startsWith('sk-ws-') && !this.baseUrl.includes('ws-')) {
71
72
  throw new Error(`\n[QWEN WORKSPACE CONFIGURATION ERROR]\n\nYou are using a Workspace-bound API Key (starts with sk-ws-), but you haven't configured your Workspace Base URL!\n\nAlibaba requires a specific URL for these keys.\n\nHOW TO FIX THIS:\n1. Open your computer terminal.\n2. Run command: causyne-agent config\n3. When asked for 'Custom Base URL', paste your Workspace URL from Alibaba (e.g. https://{Your-Workspace-ID}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions).\n\nAlternatively, use a Standard API Key (starts with sk-) which does not require a custom URL.`);
72
73
  }
73
74
  }
74
-
75
- throw new Error(`Qwen DashScope API Error (${response.status}): ${errorData}`);
76
- }
75
+ };
77
76
 
78
- const data = await response.json();
77
+ const data = wantsStreaming(options)
78
+ ? await streamOpenAICompatibleChat({
79
+ ...requestOpts,
80
+ payload,
81
+ onChunk: options.onChunk,
82
+ onReasoningChunk: options.onReasoningChunk
83
+ })
84
+ : await safeProviderFetchJson({
85
+ ...requestOpts,
86
+ body: JSON.stringify(payload)
87
+ });
79
88
  const normalized = normalizeOpenAIChatChoiceResponse(data, {
80
89
  prefix: 'call_dashscope',
81
90
  freeFormPaths
@@ -3,6 +3,12 @@ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
4
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
5
5
  import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
6
+ import {
7
+ requireApiKey,
8
+ resolveTemperature,
9
+ safeProviderFetchJson
10
+ } from './byokHttp.js';
11
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
6
12
 
7
13
  export class DeepSeekProvider extends LLMProvider {
8
14
  constructor(config) {
@@ -16,28 +22,18 @@ export class DeepSeekProvider extends LLMProvider {
16
22
  }
17
23
 
18
24
  async chat(messages, options = {}) {
25
+ const apiKey = requireApiKey(this.apiKey, 'DeepSeek');
19
26
  const sanitizedMessages = this.prepareMessages(messages);
20
27
 
21
28
  const payload = {
22
29
  model: this.model,
23
30
  messages: sanitizedMessages,
24
- temperature: options.temperature || 0.1,
31
+ temperature: resolveTemperature(options.temperature, 0.1),
25
32
  };
26
33
 
27
34
  if (options.jsonMode) {
28
35
  payload.response_format = { type: 'json_object' };
29
36
  }
30
-
31
- let targetUrl = this.baseUrl;
32
- let headers = {
33
- 'Content-Type': 'application/json'
34
- };
35
-
36
- if (this.apiKey) {
37
- headers['Authorization'] = `Bearer ${this.apiKey}`;
38
- } else {
39
- throw new Error("API key is required.");
40
- }
41
37
 
42
38
  let freeFormPaths = new Map();
43
39
  if (options.tools && options.tools.length > 0) {
@@ -47,18 +43,31 @@ export class DeepSeekProvider extends LLMProvider {
47
43
  freeFormPaths = scanReport.freeFormPaths;
48
44
  }
49
45
 
50
- const response = await fetch(targetUrl, {
46
+ const requestOpts = {
47
+ url: this.baseUrl,
51
48
  method: 'POST',
52
- headers: headers,
53
- body: JSON.stringify(payload)
54
- });
55
-
56
- if (!response.ok) {
57
- const errorData = await response.text();
58
- throw new Error(`DeepSeek API Error (${response.status}): ${errorData}`);
59
- }
49
+ headers: {
50
+ 'Content-Type': 'application/json',
51
+ 'Authorization': `Bearer ${apiKey}`
52
+ },
53
+ signal: options.signal,
54
+ timeoutMs: options.timeoutMs,
55
+ providerLabel: 'DeepSeek',
56
+ secrets: [apiKey],
57
+ hasApiKey: true
58
+ };
60
59
 
61
- const data = await response.json();
60
+ const data = wantsStreaming(options)
61
+ ? await streamOpenAICompatibleChat({
62
+ ...requestOpts,
63
+ payload,
64
+ onChunk: options.onChunk,
65
+ onReasoningChunk: options.onReasoningChunk
66
+ })
67
+ : await safeProviderFetchJson({
68
+ ...requestOpts,
69
+ body: JSON.stringify(payload)
70
+ });
62
71
  const normalized = normalizeOpenAIChatChoiceResponse(data, {
63
72
  prefix: 'call_deepseek',
64
73
  freeFormPaths
@@ -13,6 +13,12 @@ import {
13
13
  sanitizeProviderToolId,
14
14
  serializeAndDecodeArguments
15
15
  } from './wireNormalizer.js';
16
+ import {
17
+ requireApiKey,
18
+ resolveTemperature,
19
+ safeProviderFetchJson
20
+ } from './byokHttp.js';
21
+ import { streamGeminiGenerateContent, wantsStreaming } from './byokStream.js';
16
22
 
17
23
  export { adaptSchemaForGemini, isEmptyObjectSchema };
18
24
 
@@ -99,7 +105,8 @@ export class GeminiProvider extends LLMProvider {
99
105
  constructor(config) {
100
106
  super(config);
101
107
  this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['gemini']);
102
- this.baseUrl = `https://generativelanguage.googleapis.com/v1beta/models/${this.model}:generateContent?key=${this.apiKey}`;
108
+ // Never embed the API key in the URL query string (CWE-598); send it via x-goog-api-key header.
109
+ this.baseUrl = `https://generativelanguage.googleapis.com/v1beta/models/${encodeURIComponent(this.model)}:generateContent`;
103
110
  // Every Gemini model from 1.5 onward accepts image input.
104
111
  this.visionModels = ['gemini-'];
105
112
  this.imagePayloadFormat = 'gemini';
@@ -200,10 +207,11 @@ export class GeminiProvider extends LLMProvider {
200
207
  }
201
208
  }
202
209
 
210
+ const apiKey = requireApiKey(this.apiKey, 'Gemini');
203
211
  const payload = {
204
212
  contents,
205
213
  generationConfig: {
206
- temperature: options.temperature || 0.1,
214
+ temperature: resolveTemperature(options.temperature, 0.1),
207
215
  }
208
216
  };
209
217
 
@@ -222,18 +230,31 @@ export class GeminiProvider extends LLMProvider {
222
230
  freeFormPaths = scanReport.freeFormPaths;
223
231
  }
224
232
 
225
- const response = await fetch(this.baseUrl, {
233
+ const requestOpts = {
234
+ url: this.baseUrl,
226
235
  method: 'POST',
227
- headers: { 'Content-Type': 'application/json' },
228
- body: JSON.stringify(payload)
229
- });
230
-
231
- if (!response.ok) {
232
- const errorData = await response.text();
233
- throw new Error(`Gemini API Error (${response.status}): ${errorData}`);
234
- }
236
+ headers: {
237
+ 'Content-Type': 'application/json',
238
+ 'x-goog-api-key': apiKey
239
+ },
240
+ signal: options.signal,
241
+ timeoutMs: options.timeoutMs,
242
+ providerLabel: 'Gemini',
243
+ secrets: [apiKey],
244
+ hasApiKey: true
245
+ };
235
246
 
236
- const data = await response.json();
247
+ const data = wantsStreaming(options)
248
+ ? await streamGeminiGenerateContent({
249
+ ...requestOpts,
250
+ payload,
251
+ onChunk: options.onChunk,
252
+ onReasoningChunk: options.onReasoningChunk
253
+ })
254
+ : await safeProviderFetchJson({
255
+ ...requestOpts,
256
+ body: JSON.stringify(payload)
257
+ });
237
258
 
238
259
  const firstCandidate = data.candidates?.[0];
239
260
  if (!firstCandidate) {
@@ -241,12 +262,17 @@ export class GeminiProvider extends LLMProvider {
241
262
  }
242
263
 
243
264
  let content = '';
265
+ let reasoningContent = typeof data.reasoningContent === 'string' ? data.reasoningContent : '';
244
266
  let toolCalls = [];
245
267
  const candidateParts = Array.isArray(firstCandidate.content?.parts) ? firstCandidate.content.parts : [];
246
268
 
247
269
  for (const part of candidateParts) {
248
270
  if (part.text) {
249
- content += part.text;
271
+ if (part.thought === true) {
272
+ reasoningContent += part.text;
273
+ } else {
274
+ content += part.text;
275
+ }
250
276
  } else if (part.functionCall) {
251
277
  const callName = normalizeToolName(part.functionCall.name || '');
252
278
  const serializedArgs = serializeAndDecodeArguments(part.functionCall.args || {}, callName, freeFormPaths);
@@ -264,6 +290,7 @@ export class GeminiProvider extends LLMProvider {
264
290
  return {
265
291
  content: content.trim(),
266
292
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
293
+ ...(reasoningContent.trim() ? { reasoningContent: reasoningContent.trim() } : {}),
267
294
  usage: this.normalizeUsage(geminiUsageToOpenAIShape(data.usageMetadata))
268
295
  };
269
296
  }
@@ -3,6 +3,12 @@ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
4
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
5
5
  import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
6
+ import {
7
+ requireApiKey,
8
+ resolveTemperature,
9
+ safeProviderFetchJson
10
+ } from './byokHttp.js';
11
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
6
12
 
7
13
  export class MoonshotProvider extends LLMProvider {
8
14
  constructor(config) {
@@ -15,28 +21,18 @@ export class MoonshotProvider extends LLMProvider {
15
21
  }
16
22
 
17
23
  async chat(messages, options = {}) {
24
+ const apiKey = requireApiKey(this.apiKey, 'Moonshot AI (Kimi)');
18
25
  const sanitizedMessages = this.prepareMessages(messages);
19
26
 
20
27
  const payload = {
21
28
  model: this.model,
22
29
  messages: sanitizedMessages,
23
- temperature: options.temperature || 0.1,
30
+ temperature: resolveTemperature(options.temperature, 0.1),
24
31
  };
25
32
 
26
33
  if (options.jsonMode) {
27
34
  payload.response_format = { type: 'json_object' };
28
35
  }
29
-
30
- let headers = {
31
- 'Content-Type': 'application/json'
32
- };
33
-
34
- if (this.apiKey) {
35
- headers['Authorization'] = `Bearer ${this.apiKey}`;
36
- } else {
37
- // EXPLICIT BYOK CONSTRAINT
38
- throw new Error(`Moonshot AI (Kimi) API requires a valid API key (BYOK mode). Please set it in your configuration.`);
39
- }
40
36
 
41
37
  let freeFormPaths = new Map();
42
38
  if (options.tools && options.tools.length > 0) {
@@ -46,18 +42,31 @@ export class MoonshotProvider extends LLMProvider {
46
42
  freeFormPaths = scanReport.freeFormPaths;
47
43
  }
48
44
 
49
- const response = await fetch(this.baseUrl, {
45
+ const requestOpts = {
46
+ url: this.baseUrl,
50
47
  method: 'POST',
51
- headers: headers,
52
- body: JSON.stringify(payload)
53
- });
54
-
55
- if (!response.ok) {
56
- const errorData = await response.text();
57
- throw new Error(`Moonshot AI API Error (${response.status}): ${errorData}`);
58
- }
48
+ headers: {
49
+ 'Content-Type': 'application/json',
50
+ 'Authorization': `Bearer ${apiKey}`
51
+ },
52
+ signal: options.signal,
53
+ timeoutMs: options.timeoutMs,
54
+ providerLabel: 'Moonshot AI',
55
+ secrets: [apiKey],
56
+ hasApiKey: true
57
+ };
59
58
 
60
- const data = await response.json();
59
+ const data = wantsStreaming(options)
60
+ ? await streamOpenAICompatibleChat({
61
+ ...requestOpts,
62
+ payload,
63
+ onChunk: options.onChunk,
64
+ onReasoningChunk: options.onReasoningChunk
65
+ })
66
+ : await safeProviderFetchJson({
67
+ ...requestOpts,
68
+ body: JSON.stringify(payload)
69
+ });
61
70
  const normalized = normalizeOpenAIChatChoiceResponse(data, {
62
71
  prefix: 'call_moonshot',
63
72
  freeFormPaths
@@ -1,6 +1,7 @@
1
1
  import { canonicalModelId } from '../modelIds.js';
2
2
  import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { OpenAICompatibleProvider } from './openai-compatible.js';
4
+ import { safeProviderFetchJson } from './byokHttp.js';
4
5
 
5
6
  /**
6
7
  * Meta Model API — the Muse family.
@@ -134,7 +135,7 @@ export class MuseProvider extends OpenAICompatibleProvider {
134
135
  return Boolean(this.apiKey) && process.env.CAUSYNE_MUSE_ASR === '1';
135
136
  }
136
137
 
137
- async transcribeAudio(base64, mimeType = 'audio/wav') {
138
+ async transcribeAudio(base64, mimeType = 'audio/wav', options = {}) {
138
139
  if (!base64 || !this.apiKey) return null;
139
140
 
140
141
  const extension = String(mimeType).includes('mp3') ? 'mp3'
@@ -147,18 +148,17 @@ export class MuseProvider extends OpenAICompatibleProvider {
147
148
  form.append('model', MUSE_TRANSCRIBE_MODEL);
148
149
  form.append('file', new Blob([Buffer.from(base64, 'base64')], { type: mimeType }), `clip.${extension}`);
149
150
 
150
- const response = await fetch(this.transcribeUrl, {
151
+ const data = await safeProviderFetchJson({
152
+ url: this.transcribeUrl,
151
153
  method: 'POST',
152
154
  headers: { Authorization: `Bearer ${this.apiKey}` },
153
- body: form
155
+ body: form,
156
+ signal: options.signal,
157
+ timeoutMs: options.timeoutMs,
158
+ providerLabel: 'Muse Voice Transcribe',
159
+ secrets: [this.apiKey],
160
+ hasApiKey: true
154
161
  });
155
-
156
- if (!response.ok) {
157
- const detail = await response.text();
158
- throw new Error(`Muse Voice Transcribe (${response.status}): ${detail.slice(0, 400)}`);
159
- }
160
-
161
- const data = await response.json();
162
162
  // Accept the shapes a transcription endpoint plausibly answers in, rather
163
163
  // than betting the feature on one field name.
164
164
  const text = data.text
@@ -8,11 +8,14 @@ import {
8
8
  extractTextToolCalls
9
9
  } from './wireNormalizer.js';
10
10
  import { stripToolCallMarkup } from '../implementationPlan.js';
11
+ import { resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
12
+ import { streamOllamaChat, wantsStreaming } from './byokStream.js';
11
13
 
12
14
  export class OllamaProvider extends LLMProvider {
13
15
  constructor(config) {
14
16
  super(config);
15
17
  this.baseUrl = config.baseUrl || 'http://localhost:11434/api/chat';
18
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
16
19
  this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['ollama']);
17
20
  // Locally installable vision models. Anything else stays text-only, and a
18
21
  // user on an unlisted build can set config.supportsVision explicitly.
@@ -55,7 +58,7 @@ export class OllamaProvider extends LLMProvider {
55
58
  messages: sanitizedMessages,
56
59
  stream: false,
57
60
  options: {
58
- temperature: options.temperature || 0.1
61
+ temperature: resolveTemperature(options.temperature, 0.1)
59
62
  }
60
63
  };
61
64
 
@@ -66,22 +69,33 @@ export class OllamaProvider extends LLMProvider {
66
69
  freeFormPaths = scanReport.freeFormPaths;
67
70
  }
68
71
 
69
- const response = await fetch(this.baseUrl, {
72
+ const requestOpts = {
73
+ url: this.baseUrl,
70
74
  method: 'POST',
71
75
  headers: { 'Content-Type': 'application/json' },
72
- body: JSON.stringify(payload)
73
- });
74
-
75
- if (!response.ok) {
76
- const errorData = await response.text();
77
- throw new Error(`Ollama API Error (${response.status}): ${errorData}`);
78
- }
76
+ signal: options.signal,
77
+ timeoutMs: options.timeoutMs,
78
+ providerLabel: 'Ollama',
79
+ hasApiKey: false,
80
+ allowInsecureHttp: this.allowInsecureHttp
81
+ };
79
82
 
80
- const data = await response.json();
83
+ const data = wantsStreaming(options)
84
+ ? await streamOllamaChat({
85
+ ...requestOpts,
86
+ payload,
87
+ onChunk: options.onChunk,
88
+ onReasoningChunk: options.onReasoningChunk
89
+ })
90
+ : await safeProviderFetchJson({
91
+ ...requestOpts,
92
+ body: JSON.stringify(payload)
93
+ });
81
94
 
82
95
  // Ollama returns tool calls with no id and object arguments instead of JSON strings.
83
96
  // Normalize through wireNormalizer so sanitizeSequences and toolSelfRepair see one contract.
84
97
  let content = typeof data.message?.content === 'string' ? data.message.content : '';
98
+ const reasoningContent = typeof data.message?.thinking === 'string' ? data.message.thinking.trim() : '';
85
99
  let toolCalls = normalizeOpenAIToolCalls(data.message?.tool_calls, freeFormPaths, 'call_ollama');
86
100
  if (toolCalls.length === 0 && content) {
87
101
  const extracted = extractTextToolCalls(content, 'call_ollama_text', freeFormPaths);
@@ -94,6 +108,7 @@ export class OllamaProvider extends LLMProvider {
94
108
  return {
95
109
  content,
96
110
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
111
+ ...(reasoningContent ? { reasoningContent } : {}),
97
112
  usage: {
98
113
  promptTokens: data.prompt_eval_count || 0,
99
114
  completionTokens: data.eval_count || 0
@@ -3,6 +3,13 @@ import { DEFAULT_MODEL_BY_PROVIDER } from '../modelCatalogue.js';
3
3
  import { LLMProvider } from './base.js';
4
4
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
5
5
  import { normalizeOpenAIChatChoiceResponse } from './wireNormalizer.js';
6
+ import {
7
+ isLoopbackHost,
8
+ requireApiKey,
9
+ resolveTemperature,
10
+ safeProviderFetchJson
11
+ } from './byokHttp.js';
12
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
6
13
 
7
14
  export class OpenAICompatibleProvider extends LLMProvider {
8
15
  constructor(config) {
@@ -15,6 +22,7 @@ export class OpenAICompatibleProvider extends LLMProvider {
15
22
  // 'low' | 'medium' | 'high' | 'off'. Unset means: do not send the parameter.
16
23
  this.reasoningEffort = config.reasoningEffort || null;
17
24
  this.baseUrl = config.baseUrl || 'https://api.openai.com/v1/chat/completions';
25
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
18
26
  this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['openai']);
19
27
  }
20
28
 
@@ -23,7 +31,7 @@ export class OpenAICompatibleProvider extends LLMProvider {
23
31
  const payload = {
24
32
  model: this.model,
25
33
  messages: preparedMessages,
26
- temperature: options.temperature || 0.1,
34
+ temperature: resolveTemperature(options.temperature, 0.1),
27
35
  };
28
36
 
29
37
  // Reasoning models take an effort dial. Sending it to a model that does not
@@ -46,21 +54,45 @@ export class OpenAICompatibleProvider extends LLMProvider {
46
54
  freeFormPaths = scanReport.freeFormPaths;
47
55
  }
48
56
 
49
- const response = await fetch(this.baseUrl, {
50
- method: 'POST',
51
- headers: {
52
- 'Content-Type': 'application/json',
53
- 'Authorization': `Bearer ${this.apiKey}`
54
- },
55
- body: JSON.stringify(payload)
56
- });
57
-
58
- if (!response.ok) {
59
- const errorData = await response.text();
60
- throw new Error(`OpenAI-Compatible API Error (${response.status}): ${errorData}`);
57
+ const headers = {
58
+ 'Content-Type': 'application/json'
59
+ };
60
+ const trimmedKey = typeof this.apiKey === 'string' ? this.apiKey.trim() : '';
61
+ let isLocalEndpoint = false;
62
+ try {
63
+ isLocalEndpoint = isLoopbackHost(new URL(this.baseUrl).hostname);
64
+ } catch {
65
+ isLocalEndpoint = false;
61
66
  }
67
+ if (trimmedKey) {
68
+ headers['Authorization'] = `Bearer ${trimmedKey}`;
69
+ } else if (!isLocalEndpoint) {
70
+ requireApiKey(this.apiKey, 'OpenAI-Compatible');
71
+ }
72
+
73
+ const requestOpts = {
74
+ url: this.baseUrl,
75
+ method: 'POST',
76
+ headers,
77
+ signal: options.signal,
78
+ timeoutMs: options.timeoutMs,
79
+ providerLabel: 'OpenAI-Compatible',
80
+ secrets: trimmedKey ? [trimmedKey] : [],
81
+ hasApiKey: Boolean(trimmedKey),
82
+ allowInsecureHttp: this.allowInsecureHttp
83
+ };
62
84
 
63
- const data = await response.json();
85
+ const data = wantsStreaming(options)
86
+ ? await streamOpenAICompatibleChat({
87
+ ...requestOpts,
88
+ payload,
89
+ onChunk: options.onChunk,
90
+ onReasoningChunk: options.onReasoningChunk
91
+ })
92
+ : await safeProviderFetchJson({
93
+ ...requestOpts,
94
+ body: JSON.stringify(payload)
95
+ });
64
96
  const normalized = normalizeOpenAIChatChoiceResponse(data, {
65
97
  prefix: 'call_oai',
66
98
  freeFormPaths