@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
@@ -10,7 +10,22 @@
10
10
  import { LLMProvider } from './base.js';
11
11
  import { canonicalModelId } from '../modelIds.js';
12
12
  import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
13
- import { extractToolCallJsonObjects, resolveToolCallEnvelopeArguments } from '../implementationPlan.js';
13
+ import {
14
+ extractTextToolCalls,
15
+ normalizeOpenAIChatChoiceResponse,
16
+ serializeAndDecodeArguments
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';
28
+ import { normalizeToolName } from '../tools/toolScanner.js';
14
29
  import type { ChatOptions, ChatResponse, ChatResponseUsage, ChatResponseToolCall } from './base.d.js';
15
30
 
16
31
  export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
@@ -25,9 +40,13 @@ export class FreeModeCostGuardError extends Error {
25
40
  }
26
41
 
27
42
  export class OpenRouterRateLimitError extends Error {
28
- constructor(message: string) {
43
+ public readonly status = 429;
44
+ public readonly retryAfterMs?: number | undefined;
45
+
46
+ constructor(message: string, retryAfterMs?: number | undefined) {
29
47
  super(message);
30
48
  this.name = 'OpenRouterRateLimitError';
49
+ this.retryAfterMs = retryAfterMs;
31
50
  }
32
51
  }
33
52
 
@@ -41,10 +60,12 @@ export class OpenRouterPrivacyConstraintError extends Error {
41
60
  export class OpenRouterProvider extends LLMProvider {
42
61
  public dataCollection: 'deny' | 'allow';
43
62
  public freeOnly: boolean;
63
+ public allowInsecureHttp: boolean;
44
64
 
45
65
  constructor(config: Record<string, any> = {}) {
46
66
  super(config);
47
67
  this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
68
+ this.allowInsecureHttp = config['allowInsecureHttp'] === true;
48
69
  this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
49
70
  this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
50
71
  this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
@@ -97,7 +118,7 @@ export class OpenRouterProvider extends LLMProvider {
97
118
  const payload: Record<string, any> = {
98
119
  model: this.model,
99
120
  messages: preparedMessages,
100
- temperature: options.temperature ?? 0.1,
121
+ temperature: resolveTemperature(options.temperature, 0.1),
101
122
  stream: shouldStream,
102
123
  provider: {
103
124
  data_collection: this.dataCollection
@@ -108,10 +129,12 @@ export class OpenRouterProvider extends LLMProvider {
108
129
  payload['response_format'] = { type: 'json_object' };
109
130
  }
110
131
 
132
+ let freeFormPaths = new Map<string, string[][]>();
111
133
  if (options.tools && Array.isArray(options.tools) && options.tools.length > 0) {
112
134
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
113
135
  payload['tools'] = scanReport.adaptedTools;
114
136
  payload['tool_choice'] = 'auto';
137
+ freeFormPaths = scanReport.freeFormPaths;
115
138
  }
116
139
 
117
140
  const headers: Record<string, string> = {
@@ -121,45 +144,53 @@ export class OpenRouterProvider extends LLMProvider {
121
144
  'X-Title': 'Causyne Agent'
122
145
  };
123
146
 
124
- let response: Response;
125
147
  const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
126
- const fetchInit: RequestInit = {
148
+ const { response, cleanup } = await safeProviderFetch({
149
+ url: endpoint,
127
150
  method: 'POST',
128
151
  headers,
129
- body: JSON.stringify(payload)
130
- };
131
- if (options.signal) {
132
- fetchInit.signal = options.signal;
133
- }
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
+ });
134
160
 
135
161
  try {
136
- response = await fetch(endpoint, fetchInit);
137
- } catch (err: any) {
138
- if (err?.name === 'AbortError' || options.signal?.aborted) {
139
- 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);
140
171
  }
141
- throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
142
- }
143
172
 
144
- if (!response.ok) {
145
- const errorText = await response.text().catch(() => '');
146
- this.handleHttpErrors(response.status, errorText);
147
- }
148
-
149
- if (shouldStream && response.body) {
150
- return this.handleStreamingResponse(response, options);
151
- } else {
152
- return this.handleJsonResponse(response);
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();
153
180
  }
154
181
  }
155
182
 
156
183
  /**
157
184
  * Map HTTP error codes into user-friendly and security-preserving exceptions.
158
185
  */
159
- private handleHttpErrors(status: number, errorText: string): never {
186
+ private handleHttpErrors(status: number, errorText: string, retryAfterMs?: number): never {
160
187
  if (status === 429) {
188
+ const retryNote = retryAfterMs !== undefined
189
+ ? ` Retry after ${Math.ceil(retryAfterMs / 1000)}s.`
190
+ : '';
161
191
  throw new OpenRouterRateLimitError(
162
- '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
163
194
  );
164
195
  }
165
196
 
@@ -174,7 +205,8 @@ export class OpenRouterProvider extends LLMProvider {
174
205
  }
175
206
  if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
176
207
  throw new OpenRouterRateLimitError(
177
- '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
178
210
  );
179
211
  }
180
212
  }
@@ -185,33 +217,36 @@ export class OpenRouterProvider extends LLMProvider {
185
217
  /**
186
218
  * Process a non-streaming JSON response from OpenRouter.
187
219
  */
188
- private async handleJsonResponse(response: Response): Promise<ChatResponse> {
189
- const data = (await response.json()) as any;
190
- let content = '';
191
- let toolCalls: ChatResponseToolCall[] = [];
192
- let reasoningContent = '';
193
-
194
- if (data.choices && Array.isArray(data.choices) && data.choices[0]?.message) {
195
- const message = data.choices[0].message;
196
- content = message.content || '';
197
- toolCalls = this.normalizeToolCalls(message.tool_calls);
198
- reasoningContent = message.reasoning || message.reasoning_content || '';
199
- }
200
-
201
- if (toolCalls.length === 0 && content) {
202
- const extracted = this.extractToolCallsFromContent(content);
203
- if (extracted.length > 0) {
204
- toolCalls = extracted;
220
+ private async handleJsonResponse(
221
+ response: Response,
222
+ freeFormPaths?: Map<string, string[][]>,
223
+ apiKey?: string
224
+ ): Promise<ChatResponse> {
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}`);
205
238
  }
206
239
  }
207
-
208
- const rawUsage = data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
209
- const usage: ChatResponseUsage = this.normalizeUsage(rawUsage);
240
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
241
+ prefix: 'call_openrouter',
242
+ ...(freeFormPaths ? { freeFormPaths } : {})
243
+ });
244
+ const usage: ChatResponseUsage = this.normalizeUsage(normalized.rawUsage);
210
245
 
211
246
  return {
212
- content,
213
- toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
214
- reasoningContent: reasoningContent || undefined,
247
+ content: normalized.content,
248
+ toolCalls: normalized.toolCalls,
249
+ reasoningContent: normalized.reasoningContent,
215
250
  usage
216
251
  };
217
252
  }
@@ -219,7 +254,11 @@ export class OpenRouterProvider extends LLMProvider {
219
254
  /**
220
255
  * Process a streaming SSE response from OpenRouter.
221
256
  */
222
- private async handleStreamingResponse(response: Response, options: ChatOptions): Promise<ChatResponse> {
257
+ private async handleStreamingResponse(
258
+ response: Response,
259
+ options: ChatOptions,
260
+ freeFormPaths?: Map<string, string[][]>
261
+ ): Promise<ChatResponse> {
223
262
  const reader = response.body!.getReader();
224
263
  const decoder = new TextDecoder('utf-8');
225
264
 
@@ -240,6 +279,10 @@ export class OpenRouterProvider extends LLMProvider {
240
279
  if (done) break;
241
280
 
242
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
+ }
243
286
  const lines = buffer.split('\n');
244
287
  buffer = lines.pop() || '';
245
288
 
@@ -308,19 +351,20 @@ export class OpenRouterProvider extends LLMProvider {
308
351
  const toolCalls: ChatResponseToolCall[] = [];
309
352
  for (const item of toolCallsMap.values()) {
310
353
  if (item.name) {
354
+ const cleanName = normalizeToolName(item.name);
311
355
  toolCalls.push({
312
356
  id: item.id,
313
357
  type: 'function',
314
358
  function: {
315
- name: item.name,
316
- arguments: item.arguments || '{}'
359
+ name: cleanName,
360
+ arguments: serializeAndDecodeArguments(item.arguments || '{}', cleanName, freeFormPaths)
317
361
  }
318
362
  });
319
363
  }
320
364
  }
321
365
 
322
366
  if (toolCalls.length === 0 && content) {
323
- const extracted = this.extractToolCallsFromContent(content);
367
+ const extracted = extractTextToolCalls(content, 'call_text', freeFormPaths);
324
368
  if (extracted.length > 0) {
325
369
  toolCalls.push(...extracted);
326
370
  }
@@ -337,67 +381,4 @@ export class OpenRouterProvider extends LLMProvider {
337
381
  usage
338
382
  };
339
383
  }
340
-
341
- /**
342
- * Extract tool calls embedded in content text (e.g. <tool_call> envelopes).
343
- */
344
- private extractToolCallsFromContent(text: string): ChatResponseToolCall[] {
345
- const calls: ChatResponseToolCall[] = [];
346
- if (!text || typeof text !== 'string') return calls;
347
- let index = 0;
348
- for (const parsed of extractToolCallJsonObjects(text)) {
349
- const fnObj = parsed.function && typeof parsed.function === 'object'
350
- ? (parsed.function as Record<string, unknown>)
351
- : null;
352
- const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
353
- if (!name) continue;
354
- const rawArgs = resolveToolCallEnvelopeArguments(parsed);
355
- calls.push({
356
- id: `call_text_${Date.now()}_${index++}`,
357
- type: 'function',
358
- function: {
359
- name,
360
- arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
361
- }
362
- });
363
- }
364
- return calls;
365
- }
366
-
367
- /**
368
- * Safely normalize tool calls from provider message.
369
- */
370
- private normalizeToolCalls(rawCalls: any[]): ChatResponseToolCall[] {
371
- if (!Array.isArray(rawCalls)) return [];
372
- const normalized: ChatResponseToolCall[] = [];
373
-
374
- for (let i = 0; i < rawCalls.length; i++) {
375
- const tc = rawCalls[i];
376
- if (!tc || typeof tc !== 'object') continue;
377
-
378
- const id = typeof tc.id === 'string' && tc.id ? tc.id : `call_${i}_${Date.now()}`;
379
- const name = tc.function?.name || tc.name || '';
380
- if (!name || typeof name !== 'string') continue;
381
-
382
- let args = tc.function?.arguments;
383
- if (typeof args !== 'string') {
384
- try {
385
- args = JSON.stringify(args || {});
386
- } catch {
387
- args = '{}';
388
- }
389
- }
390
-
391
- normalized.push({
392
- id,
393
- type: 'function',
394
- function: {
395
- name,
396
- arguments: args
397
- }
398
- });
399
- }
400
-
401
- return normalized;
402
- }
403
384
  }
@@ -2,6 +2,13 @@ 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';
6
+ import {
7
+ requireApiKey,
8
+ resolveTemperature,
9
+ safeProviderFetchJson
10
+ } from './byokHttp.js';
11
+ import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
5
12
 
6
13
  // Direct DashScope API connection for BYOK (unlike dashscope.js which is the proxy for Free Demo)
7
14
  export class QwenByokProvider extends LLMProvider {
@@ -13,6 +20,7 @@ export class QwenByokProvider extends LLMProvider {
13
20
  else if (url.endsWith('/v1/')) url += 'chat/completions';
14
21
 
15
22
  this.baseUrl = url;
23
+ this.allowInsecureHttp = config.allowInsecureHttp === true;
16
24
  this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['qwen']);
17
25
  this.apiKey = config.apiKey;
18
26
  this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7'];
@@ -22,54 +30,69 @@ export class QwenByokProvider extends LLMProvider {
22
30
  }
23
31
 
24
32
  async chat(messages, options = {}) {
33
+ const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
25
34
  const sanitizedMessages = this.prepareMessages(messages);
26
35
 
27
36
  const payload = {
28
37
  model: this.model,
29
38
  messages: sanitizedMessages,
30
- temperature: options.temperature || 0.1,
39
+ temperature: resolveTemperature(options.temperature, 0.1),
31
40
  };
32
41
 
33
42
  if (options.jsonMode) {
34
43
  payload.response_format = { type: 'json_object' };
35
44
  }
36
45
 
37
- if (options.tools) {
46
+ let freeFormPaths = new Map();
47
+ if (options.tools && options.tools.length > 0) {
38
48
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'qwen');
39
49
  payload.tools = scanReport.adaptedTools;
40
50
  payload.tool_choice = "auto";
51
+ freeFormPaths = scanReport.freeFormPaths;
41
52
  }
42
53
 
43
- const response = await fetch(this.baseUrl, {
54
+ const requestOpts = {
55
+ url: this.baseUrl,
44
56
  method: 'POST',
45
57
  headers: {
46
58
  'Content-Type': 'application/json',
47
- 'Authorization': `Bearer ${this.apiKey}`
59
+ 'Authorization': `Bearer ${apiKey}`
48
60
  },
49
- body: JSON.stringify(payload)
50
- });
51
-
52
- if (!response.ok) {
53
- const errorData = await response.text();
54
-
55
- // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
56
- if (response.status === 401 && this.apiKey && this.apiKey.startsWith('sk-ws-')) {
57
- 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-')) {
58
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.`);
59
71
  }
60
72
  }
61
-
62
- throw new Error(`Qwen DashScope API Error (${response.status}): ${errorData}`);
63
- }
73
+ };
74
+
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
+ });
86
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
87
+ prefix: 'call_qwen',
88
+ freeFormPaths
89
+ });
64
90
 
65
- const data = await response.json();
66
- const content = data.choices[0].message.content;
67
- const toolCalls = data.choices[0].message.tool_calls;
68
-
69
91
  return {
70
- content: content || '',
71
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
72
- usage: this.normalizeUsage(data.usage)
92
+ content: normalized.content,
93
+ toolCalls: normalized.toolCalls,
94
+ reasoningContent: normalized.reasoningContent,
95
+ usage: this.normalizeUsage(normalized.rawUsage)
73
96
  };
74
97
  }
75
98
  }
@@ -1,14 +1,20 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { normalizeToolName, normalizeUniversalSchema } from '../tools/toolScanner.js';
2
3
  const object = (value) => value !== null && typeof value === 'object' && !Array.isArray(value) ? value : {};
3
- /** Preserve constraints and nested schemas; text peers need more than parameter names. */
4
+ /** Preserve constraints and nested schemas while compiling union/combinator edge cases safely. */
4
5
  export function normalizeToolContracts(tools) {
5
6
  return tools.map(raw => {
6
7
  const tool = object(raw);
7
8
  const fn = object(tool.function);
9
+ const rawName = String(tool.name || fn.name || '');
10
+ const rawParams = object(tool.parameters || tool.input_schema || fn.parameters);
11
+ const cleanParams = Object.keys(rawParams).length > 0
12
+ ? object(normalizeUniversalSchema(rawParams, [], [], 'strict_json'))
13
+ : rawParams;
8
14
  return {
9
- name: String(tool.name || fn.name || ''),
15
+ name: rawName ? normalizeToolName(rawName) : '',
10
16
  description: String(tool.description || fn.description || ''),
11
- parameters: object(tool.parameters || tool.input_schema || fn.parameters)
17
+ parameters: cleanParams
12
18
  };
13
19
  }).filter(tool => tool.name).sort((a, b) => a.name.localeCompare(b.name));
14
20
  }
@@ -1,4 +1,5 @@
1
1
  import { createHash } from 'node:crypto';
2
+ import { normalizeToolName, normalizeUniversalSchema } from '../tools/toolScanner.js';
2
3
 
3
4
  type JsonObject = Record<string, unknown>;
4
5
  export interface ToolContract {
@@ -10,15 +11,20 @@ export interface ToolContract {
10
11
  const object = (value: unknown): JsonObject =>
11
12
  value !== null && typeof value === 'object' && !Array.isArray(value) ? value as JsonObject : {};
12
13
 
13
- /** Preserve constraints and nested schemas; text peers need more than parameter names. */
14
+ /** Preserve constraints and nested schemas while compiling union/combinator edge cases safely. */
14
15
  export function normalizeToolContracts(tools: readonly unknown[]): ToolContract[] {
15
16
  return tools.map(raw => {
16
17
  const tool = object(raw);
17
18
  const fn = object(tool.function);
19
+ const rawName = String(tool.name || fn.name || '');
20
+ const rawParams = object(tool.parameters || tool.input_schema || fn.parameters);
21
+ const cleanParams = Object.keys(rawParams).length > 0
22
+ ? object(normalizeUniversalSchema(rawParams, [], [], 'strict_json'))
23
+ : rawParams;
18
24
  return {
19
- name: String(tool.name || fn.name || ''),
25
+ name: rawName ? normalizeToolName(rawName) : '',
20
26
  description: String(tool.description || fn.description || ''),
21
- parameters: object(tool.parameters || tool.input_schema || fn.parameters)
27
+ parameters: cleanParams
22
28
  };
23
29
  }).filter(tool => tool.name).sort((a, b) => a.name.localeCompare(b.name));
24
30
  }