@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
@@ -10,6 +10,7 @@ import { LLMProvider } from './base.js';
10
10
  import { canonicalModelId } from '../modelIds.js';
11
11
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
12
12
  import { extractTextToolCalls, normalizeOpenAIChatChoiceResponse, serializeAndDecodeArguments } from './wireNormalizer.js';
13
+ import { MAX_PROVIDER_ERROR_BYTES, MAX_PROVIDER_JSON_BYTES, MAX_SSE_BUFFER_BYTES, parseRetryAfterMs, readBoundedResponseText, redactProviderSecrets, resolveTemperature, safeProviderFetch } from './byokHttp.js';
13
14
  import { normalizeToolName } from '../tools/toolScanner.js';
14
15
  export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
15
16
  export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
@@ -21,9 +22,12 @@ export class FreeModeCostGuardError extends Error {
21
22
  }
22
23
  }
23
24
  export class OpenRouterRateLimitError extends Error {
24
- constructor(message) {
25
+ status = 429;
26
+ retryAfterMs;
27
+ constructor(message, retryAfterMs) {
25
28
  super(message);
26
29
  this.name = 'OpenRouterRateLimitError';
30
+ this.retryAfterMs = retryAfterMs;
27
31
  }
28
32
  }
29
33
  export class OpenRouterPrivacyConstraintError extends Error {
@@ -35,9 +39,11 @@ export class OpenRouterPrivacyConstraintError extends Error {
35
39
  export class OpenRouterProvider extends LLMProvider {
36
40
  dataCollection;
37
41
  freeOnly;
42
+ allowInsecureHttp;
38
43
  constructor(config = {}) {
39
44
  super(config);
40
45
  this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
46
+ this.allowInsecureHttp = config['allowInsecureHttp'] === true;
41
47
  this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
42
48
  this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
43
49
  this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
@@ -81,7 +87,7 @@ export class OpenRouterProvider extends LLMProvider {
81
87
  const payload = {
82
88
  model: this.model,
83
89
  messages: preparedMessages,
84
- temperature: options.temperature ?? 0.1,
90
+ temperature: resolveTemperature(options.temperature, 0.1),
85
91
  stream: shouldStream,
86
92
  provider: {
87
93
  data_collection: this.dataCollection
@@ -103,42 +109,50 @@ export class OpenRouterProvider extends LLMProvider {
103
109
  'HTTP-Referer': 'https://causyne.com',
104
110
  'X-Title': 'Causyne Agent'
105
111
  };
106
- let response;
107
112
  const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
108
- const fetchInit = {
113
+ const { response, cleanup } = await safeProviderFetch({
114
+ url: endpoint,
109
115
  method: 'POST',
110
116
  headers,
111
- body: JSON.stringify(payload)
112
- };
113
- if (options.signal) {
114
- fetchInit.signal = options.signal;
115
- }
117
+ body: JSON.stringify(payload),
118
+ signal: options.signal,
119
+ timeoutMs: typeof options['timeoutMs'] === 'number' ? options['timeoutMs'] : undefined,
120
+ providerLabel: 'OpenRouter',
121
+ secrets: [apiKey],
122
+ hasApiKey: true,
123
+ allowInsecureHttp: this.allowInsecureHttp
124
+ });
116
125
  try {
117
- response = await fetch(endpoint, fetchInit);
118
- }
119
- catch (err) {
120
- if (err?.name === 'AbortError' || options.signal?.aborted) {
121
- throw err;
126
+ if (!response.ok) {
127
+ const rawError = await readBoundedResponseText(response, MAX_PROVIDER_ERROR_BYTES, {
128
+ truncate: true,
129
+ label: 'OpenRouter'
130
+ }).catch(() => '');
131
+ const cleanError = redactProviderSecrets(rawError, [apiKey]);
132
+ const retryAfterHeader = response.headers?.get?.('retry-after');
133
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
134
+ this.handleHttpErrors(response.status, cleanError, retryAfterMs);
135
+ }
136
+ if (shouldStream && response.body) {
137
+ return await this.handleStreamingResponse(response, options, freeFormPaths);
138
+ }
139
+ else {
140
+ return await this.handleJsonResponse(response, freeFormPaths, apiKey);
122
141
  }
123
- throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
124
- }
125
- if (!response.ok) {
126
- const errorText = await response.text().catch(() => '');
127
- this.handleHttpErrors(response.status, errorText);
128
- }
129
- if (shouldStream && response.body) {
130
- return this.handleStreamingResponse(response, options, freeFormPaths);
131
142
  }
132
- else {
133
- return this.handleJsonResponse(response, freeFormPaths);
143
+ finally {
144
+ cleanup();
134
145
  }
135
146
  }
136
147
  /**
137
148
  * Map HTTP error codes into user-friendly and security-preserving exceptions.
138
149
  */
139
- handleHttpErrors(status, errorText) {
150
+ handleHttpErrors(status, errorText, retryAfterMs) {
140
151
  if (status === 429) {
141
- throw new OpenRouterRateLimitError('OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.');
152
+ const retryNote = retryAfterMs !== undefined
153
+ ? ` Retry after ${Math.ceil(retryAfterMs / 1000)}s.`
154
+ : '';
155
+ throw new OpenRouterRateLimitError(`OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.${retryNote}`, retryAfterMs);
142
156
  }
143
157
  const lowered = (errorText || '').toLowerCase();
144
158
  if (status === 400 || status === 404) {
@@ -148,7 +162,7 @@ export class OpenRouterProvider extends LLMProvider {
148
162
  `Run "/openrouter allow" to permit free model routing, or inspect your preference with /openrouter status.`);
149
163
  }
150
164
  if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
151
- throw new OpenRouterRateLimitError('OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.');
165
+ throw new OpenRouterRateLimitError('OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.', retryAfterMs);
152
166
  }
153
167
  }
154
168
  throw new Error(`OpenRouter API Error (${status}): ${errorText}`);
@@ -156,8 +170,24 @@ export class OpenRouterProvider extends LLMProvider {
156
170
  /**
157
171
  * Process a non-streaming JSON response from OpenRouter.
158
172
  */
159
- async handleJsonResponse(response, freeFormPaths) {
160
- const data = (await response.json());
173
+ async handleJsonResponse(response, freeFormPaths, apiKey) {
174
+ let data;
175
+ if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
176
+ data = await response.json();
177
+ }
178
+ else {
179
+ const rawText = await readBoundedResponseText(response, MAX_PROVIDER_JSON_BYTES, {
180
+ truncate: false,
181
+ label: 'OpenRouter'
182
+ });
183
+ try {
184
+ data = JSON.parse(rawText);
185
+ }
186
+ catch {
187
+ const preview = redactProviderSecrets(rawText.slice(0, 240), [apiKey]);
188
+ throw new Error(`OpenRouter returned a non-JSON response (HTTP ${response.status}): ${preview}`);
189
+ }
190
+ }
161
191
  const normalized = normalizeOpenAIChatChoiceResponse(data, {
162
192
  prefix: 'call_openrouter',
163
193
  ...(freeFormPaths ? { freeFormPaths } : {})
@@ -191,6 +221,10 @@ export class OpenRouterProvider extends LLMProvider {
191
221
  if (done)
192
222
  break;
193
223
  buffer += decoder.decode(value, { stream: true });
224
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
225
+ await reader.cancel().catch(() => { });
226
+ throw new Error(`OpenRouter SSE buffer exceeded maximum allowed size (${MAX_SSE_BUFFER_BYTES} bytes).`);
227
+ }
194
228
  const lines = buffer.split('\n');
195
229
  buffer = lines.pop() || '';
196
230
  for (const line of lines) {
@@ -15,6 +15,16 @@ import {
15
15
  normalizeOpenAIChatChoiceResponse,
16
16
  serializeAndDecodeArguments
17
17
  } from './wireNormalizer.js';
18
+ import {
19
+ MAX_PROVIDER_ERROR_BYTES,
20
+ MAX_PROVIDER_JSON_BYTES,
21
+ MAX_SSE_BUFFER_BYTES,
22
+ parseRetryAfterMs,
23
+ readBoundedResponseText,
24
+ redactProviderSecrets,
25
+ resolveTemperature,
26
+ safeProviderFetch
27
+ } from './byokHttp.js';
18
28
  import { normalizeToolName } from '../tools/toolScanner.js';
19
29
  import type { ChatOptions, ChatResponse, ChatResponseUsage, ChatResponseToolCall } from './base.d.js';
20
30
 
@@ -30,9 +40,13 @@ export class FreeModeCostGuardError extends Error {
30
40
  }
31
41
 
32
42
  export class OpenRouterRateLimitError extends Error {
33
- constructor(message: string) {
43
+ public readonly status = 429;
44
+ public readonly retryAfterMs?: number | undefined;
45
+
46
+ constructor(message: string, retryAfterMs?: number | undefined) {
34
47
  super(message);
35
48
  this.name = 'OpenRouterRateLimitError';
49
+ this.retryAfterMs = retryAfterMs;
36
50
  }
37
51
  }
38
52
 
@@ -46,10 +60,12 @@ export class OpenRouterPrivacyConstraintError extends Error {
46
60
  export class OpenRouterProvider extends LLMProvider {
47
61
  public dataCollection: 'deny' | 'allow';
48
62
  public freeOnly: boolean;
63
+ public allowInsecureHttp: boolean;
49
64
 
50
65
  constructor(config: Record<string, any> = {}) {
51
66
  super(config);
52
67
  this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
68
+ this.allowInsecureHttp = config['allowInsecureHttp'] === true;
53
69
  this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
54
70
  this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
55
71
  this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
@@ -102,7 +118,7 @@ export class OpenRouterProvider extends LLMProvider {
102
118
  const payload: Record<string, any> = {
103
119
  model: this.model,
104
120
  messages: preparedMessages,
105
- temperature: options.temperature ?? 0.1,
121
+ temperature: resolveTemperature(options.temperature, 0.1),
106
122
  stream: shouldStream,
107
123
  provider: {
108
124
  data_collection: this.dataCollection
@@ -128,45 +144,53 @@ export class OpenRouterProvider extends LLMProvider {
128
144
  'X-Title': 'Causyne Agent'
129
145
  };
130
146
 
131
- let response: Response;
132
147
  const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
133
- const fetchInit: RequestInit = {
148
+ const { response, cleanup } = await safeProviderFetch({
149
+ url: endpoint,
134
150
  method: 'POST',
135
151
  headers,
136
- body: JSON.stringify(payload)
137
- };
138
- if (options.signal) {
139
- fetchInit.signal = options.signal;
140
- }
152
+ body: JSON.stringify(payload),
153
+ signal: options.signal,
154
+ timeoutMs: typeof options['timeoutMs'] === 'number' ? options['timeoutMs'] : undefined,
155
+ providerLabel: 'OpenRouter',
156
+ secrets: [apiKey],
157
+ hasApiKey: true,
158
+ allowInsecureHttp: this.allowInsecureHttp
159
+ });
141
160
 
142
161
  try {
143
- response = await fetch(endpoint, fetchInit);
144
- } catch (err: any) {
145
- if (err?.name === 'AbortError' || options.signal?.aborted) {
146
- throw err;
162
+ if (!response.ok) {
163
+ const rawError = await readBoundedResponseText(response, MAX_PROVIDER_ERROR_BYTES, {
164
+ truncate: true,
165
+ label: 'OpenRouter'
166
+ }).catch(() => '');
167
+ const cleanError = redactProviderSecrets(rawError, [apiKey]);
168
+ const retryAfterHeader = (response as unknown as { headers?: { get?: (k: string) => string | null } }).headers?.get?.('retry-after');
169
+ const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
170
+ this.handleHttpErrors(response.status, cleanError, retryAfterMs);
147
171
  }
148
- throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
149
- }
150
-
151
- if (!response.ok) {
152
- const errorText = await response.text().catch(() => '');
153
- this.handleHttpErrors(response.status, errorText);
154
- }
155
172
 
156
- if (shouldStream && response.body) {
157
- return this.handleStreamingResponse(response, options, freeFormPaths);
158
- } else {
159
- return this.handleJsonResponse(response, freeFormPaths);
173
+ if (shouldStream && response.body) {
174
+ return await this.handleStreamingResponse(response, options, freeFormPaths);
175
+ } else {
176
+ return await this.handleJsonResponse(response, freeFormPaths, apiKey);
177
+ }
178
+ } finally {
179
+ cleanup();
160
180
  }
161
181
  }
162
182
 
163
183
  /**
164
184
  * Map HTTP error codes into user-friendly and security-preserving exceptions.
165
185
  */
166
- private handleHttpErrors(status: number, errorText: string): never {
186
+ private handleHttpErrors(status: number, errorText: string, retryAfterMs?: number): never {
167
187
  if (status === 429) {
188
+ const retryNote = retryAfterMs !== undefined
189
+ ? ` Retry after ${Math.ceil(retryAfterMs / 1000)}s.`
190
+ : '';
168
191
  throw new OpenRouterRateLimitError(
169
- 'OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.'
192
+ `OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.${retryNote}`,
193
+ retryAfterMs
170
194
  );
171
195
  }
172
196
 
@@ -181,7 +205,8 @@ export class OpenRouterProvider extends LLMProvider {
181
205
  }
182
206
  if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
183
207
  throw new OpenRouterRateLimitError(
184
- 'OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.'
208
+ 'OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.',
209
+ retryAfterMs
185
210
  );
186
211
  }
187
212
  }
@@ -194,9 +219,24 @@ export class OpenRouterProvider extends LLMProvider {
194
219
  */
195
220
  private async handleJsonResponse(
196
221
  response: Response,
197
- freeFormPaths?: Map<string, string[][]>
222
+ freeFormPaths?: Map<string, string[][]>,
223
+ apiKey?: string
198
224
  ): Promise<ChatResponse> {
199
- const data = (await response.json()) as any;
225
+ let data: any;
226
+ if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
227
+ data = await response.json();
228
+ } else {
229
+ const rawText = await readBoundedResponseText(response, MAX_PROVIDER_JSON_BYTES, {
230
+ truncate: false,
231
+ label: 'OpenRouter'
232
+ });
233
+ try {
234
+ data = JSON.parse(rawText);
235
+ } catch {
236
+ const preview = redactProviderSecrets(rawText.slice(0, 240), [apiKey]);
237
+ throw new Error(`OpenRouter returned a non-JSON response (HTTP ${response.status}): ${preview}`);
238
+ }
239
+ }
200
240
  const normalized = normalizeOpenAIChatChoiceResponse(data, {
201
241
  prefix: 'call_openrouter',
202
242
  ...(freeFormPaths ? { freeFormPaths } : {})
@@ -239,6 +279,10 @@ export class OpenRouterProvider extends LLMProvider {
239
279
  if (done) break;
240
280
 
241
281
  buffer += decoder.decode(value, { stream: true });
282
+ if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
283
+ await reader.cancel().catch(() => {});
284
+ throw new Error(`OpenRouter SSE buffer exceeded maximum allowed size (${MAX_SSE_BUFFER_BYTES} bytes).`);
285
+ }
242
286
  const lines = buffer.split('\n');
243
287
  buffer = lines.pop() || '';
244
288
 
@@ -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 QwenByokProvider extends LLMProvider {
@@ -14,6 +20,7 @@ export class QwenByokProvider 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['qwen']);
18
25
  this.apiKey = config.apiKey;
19
26
  this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7'];
@@ -23,12 +30,13 @@ export class QwenByokProvider extends LLMProvider {
23
30
  }
24
31
 
25
32
  async chat(messages, options = {}) {
33
+ const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
26
34
  const sanitizedMessages = this.prepareMessages(messages);
27
35
 
28
36
  const payload = {
29
37
  model: this.model,
30
38
  messages: sanitizedMessages,
31
- temperature: options.temperature || 0.1,
39
+ temperature: resolveTemperature(options.temperature, 0.1),
32
40
  };
33
41
 
34
42
  if (options.jsonMode) {
@@ -43,29 +51,38 @@ export class QwenByokProvider extends LLMProvider {
43
51
  freeFormPaths = scanReport.freeFormPaths;
44
52
  }
45
53
 
46
- const response = await fetch(this.baseUrl, {
54
+ const requestOpts = {
55
+ url: this.baseUrl,
47
56
  method: 'POST',
48
57
  headers: {
49
58
  'Content-Type': 'application/json',
50
- 'Authorization': `Bearer ${this.apiKey}`
59
+ 'Authorization': `Bearer ${apiKey}`
51
60
  },
52
- body: JSON.stringify(payload)
53
- });
54
-
55
- if (!response.ok) {
56
- const errorData = await response.text();
57
-
58
- // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
59
- if (response.status === 401 && this.apiKey && this.apiKey.startsWith('sk-ws-')) {
60
- if (!this.baseUrl.includes('ws-')) {
61
+ signal: options.signal,
62
+ timeoutMs: options.timeoutMs,
63
+ providerLabel: 'Qwen DashScope',
64
+ secrets: [apiKey],
65
+ hasApiKey: true,
66
+ allowInsecureHttp: this.allowInsecureHttp,
67
+ onHttpError: ({ status }) => {
68
+ // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
69
+ if (status === 401 && apiKey.startsWith('sk-ws-') && !this.baseUrl.includes('ws-')) {
61
70
  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.`);
62
71
  }
63
72
  }
64
-
65
- throw new Error(`Qwen DashScope API Error (${response.status}): ${errorData}`);
66
- }
73
+ };
67
74
 
68
- const data = await response.json();
75
+ const data = wantsStreaming(options)
76
+ ? await streamOpenAICompatibleChat({
77
+ ...requestOpts,
78
+ payload,
79
+ onChunk: options.onChunk,
80
+ onReasoningChunk: options.onReasoningChunk
81
+ })
82
+ : await safeProviderFetchJson({
83
+ ...requestOpts,
84
+ body: JSON.stringify(payload)
85
+ });
69
86
  const normalized = normalizeOpenAIChatChoiceResponse(data, {
70
87
  prefix: 'call_qwen',
71
88
  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 XAIProvider extends LLMProvider {
8
14
  constructor(config) {
@@ -15,28 +21,18 @@ export class XAIProvider extends LLMProvider {
15
21
  }
16
22
 
17
23
  async chat(messages, options = {}) {
24
+ const apiKey = requireApiKey(this.apiKey, 'xAI (Grok)');
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(`xAI (Grok) 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 XAIProvider 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(`xAI 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: 'xAI',
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_xai',
63
72
  freeFormPaths