@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
@@ -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 DashscopeByokProvider extends LLMProvider {
@@ -13,6 +20,7 @@ export class DashscopeByokProvider 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['dashscope-byok']);
17
25
  this.apiKey = config.apiKey;
18
26
  this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7', 'kimi-k2.5', 'kimi-k2.7'];
@@ -22,64 +30,71 @@ export class DashscopeByokProvider extends LLMProvider {
22
30
  }
23
31
 
24
32
  async chat(messages, options = {}) {
25
- const ALLOWED = [
26
- "qwen3.7-max", "qwen3.7-plus", "kimi-k2.7-code", "kimi-k2.6",
27
- "kimi-k2.5", "kimi-k2-thinking", "Moonshot-Kimi-K2-Instruct",
28
- "deepseek-v4-flash", "deepseek-v4-pro"
29
- ];
30
- let activeModel = this.model;
31
- if (!ALLOWED.includes(activeModel)) {
32
- activeModel = 'qwen3.7-plus';
33
- }
33
+ const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
34
+ const activeModel = this.model || DEFAULT_MODEL_BY_PROVIDER['dashscope-byok'] || 'qwen3.7-plus';
34
35
 
35
36
  const sanitizedMessages = this.prepareMessages(messages);
36
37
 
37
38
  const payload = {
38
39
  model: activeModel,
39
40
  messages: sanitizedMessages,
40
- temperature: options.temperature || 0.1,
41
+ temperature: resolveTemperature(options.temperature, 0.1),
41
42
  };
42
43
 
43
44
  if (options.jsonMode) {
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
- const response = await fetch(this.baseUrl, {
56
+ const requestOpts = {
57
+ url: this.baseUrl,
54
58
  method: 'POST',
55
59
  headers: {
56
60
  'Content-Type': 'application/json',
57
- 'Authorization': `Bearer ${this.apiKey}`
61
+ 'Authorization': `Bearer ${apiKey}`
58
62
  },
59
- body: JSON.stringify(payload)
60
- });
61
-
62
- if (!response.ok) {
63
- const errorData = await response.text();
64
-
65
- // Enterprise Error Handling: Detect Workspace-bound API Key configuration errors
66
- if (response.status === 401 && this.apiKey && this.apiKey.startsWith('sk-ws-')) {
67
- 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-')) {
68
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.`);
69
73
  }
70
74
  }
71
-
72
- throw new Error(`Qwen DashScope API Error (${response.status}): ${errorData}`);
73
- }
75
+ };
76
+
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
+ });
88
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
89
+ prefix: 'call_dashscope',
90
+ freeFormPaths
91
+ });
74
92
 
75
- const data = await response.json();
76
- const content = data.choices[0].message.content;
77
- const toolCalls = data.choices[0].message.tool_calls;
78
-
79
93
  return {
80
- content: content || '',
81
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
82
- usage: this.normalizeUsage(data.usage)
94
+ content: normalized.content,
95
+ toolCalls: normalized.toolCalls,
96
+ reasoningContent: normalized.reasoningContent,
97
+ usage: this.normalizeUsage(normalized.rawUsage)
83
98
  };
84
99
  }
85
100
  }
@@ -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
  export class DeepSeekProvider extends LLMProvider {
7
14
  constructor(config) {
@@ -15,65 +22,62 @@ export class DeepSeekProvider extends LLMProvider {
15
22
  }
16
23
 
17
24
  async chat(messages, options = {}) {
25
+ const apiKey = requireApiKey(this.apiKey, 'DeepSeek');
18
26
  const sanitizedMessages = this.prepareMessages(messages);
19
27
 
20
28
  const payload = {
21
29
  model: this.model,
22
30
  messages: sanitizedMessages,
23
- temperature: options.temperature || 0.1,
31
+ temperature: resolveTemperature(options.temperature, 0.1),
24
32
  };
25
33
 
26
34
  if (options.jsonMode) {
27
35
  payload.response_format = { type: 'json_object' };
28
36
  }
29
-
30
- let targetUrl = this.baseUrl;
31
- let headers = {
32
- 'Content-Type': 'application/json'
33
- };
34
-
35
- if (this.apiKey) {
36
- headers['Authorization'] = `Bearer ${this.apiKey}`;
37
- } else {
38
- throw new Error("API key is required.");
39
- }
40
37
 
41
- if (options.tools) {
38
+ let freeFormPaths = new Map();
39
+ if (options.tools && options.tools.length > 0) {
42
40
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'deepseek');
43
41
  payload.tools = scanReport.adaptedTools;
44
42
  payload.tool_choice = "auto";
43
+ freeFormPaths = scanReport.freeFormPaths;
45
44
  }
46
45
 
47
- const response = await fetch(targetUrl, {
46
+ const requestOpts = {
47
+ url: this.baseUrl,
48
48
  method: 'POST',
49
- headers: headers,
50
- body: JSON.stringify(payload)
51
- });
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
+ };
52
59
 
53
- if (!response.ok) {
54
- const errorData = await response.text();
55
- throw new Error(`DeepSeek API Error (${response.status}): ${errorData}`);
56
- }
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
+ });
71
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
72
+ prefix: 'call_deepseek',
73
+ freeFormPaths
74
+ });
57
75
 
58
- 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
-
73
76
  return {
74
- content: content,
75
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
76
- usage: this.normalizeUsage(data.usage || { prompt_tokens: 0, completion_tokens: 0 })
77
+ content: normalized.content,
78
+ toolCalls: normalized.toolCalls,
79
+ reasoningContent: normalized.reasoningContent,
80
+ usage: this.normalizeUsage(normalized.rawUsage)
77
81
  };
78
82
  }
79
83
  }
@@ -5,8 +5,20 @@ 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';
16
+ import {
17
+ requireApiKey,
18
+ resolveTemperature,
19
+ safeProviderFetchJson
20
+ } from './byokHttp.js';
21
+ import { streamGeminiGenerateContent, wantsStreaming } from './byokStream.js';
10
22
 
11
23
  export { adaptSchemaForGemini, isEmptyObjectSchema };
12
24
 
@@ -93,7 +105,8 @@ export class GeminiProvider extends LLMProvider {
93
105
  constructor(config) {
94
106
  super(config);
95
107
  this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['gemini']);
96
- 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`;
97
110
  // Every Gemini model from 1.5 onward accepts image input.
98
111
  this.visionModels = ['gemini-'];
99
112
  this.imagePayloadFormat = 'gemini';
@@ -134,25 +147,29 @@ export class GeminiProvider extends LLMProvider {
134
147
  for (const tc of msg.tool_calls) {
135
148
  parts.push({
136
149
  functionCall: {
137
- name: tc.function.name,
138
- args: typeof tc.function.arguments === 'string'
139
- ? JSON.parse(tc.function.arguments || '{}')
140
- : (tc.function.arguments || {})
150
+ name: normalizeToolName(tc.function?.name || ''),
151
+ args: safeParseJsonObject(tc.function?.arguments)
141
152
  }
142
153
  });
143
154
  }
144
155
  contents.push({ role, parts });
145
156
  } 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
- });
157
+ // Batch consecutive tool responses into a single 'user' message for parallel calls.
158
+ const responsePart = {
159
+ functionResponse: {
160
+ name: normalizeToolName(msg.name || ''),
161
+ response: { result: msg.content ?? '' }
162
+ }
163
+ };
164
+ const lastEntry = contents[contents.length - 1];
165
+ if (lastEntry && lastEntry.role === 'user' && Array.isArray(lastEntry.parts) && lastEntry.parts[0]?.functionResponse) {
166
+ lastEntry.parts.push(responsePart);
167
+ } else {
168
+ contents.push({
169
+ role: 'user',
170
+ parts: [responsePart]
171
+ });
172
+ }
156
173
  } else {
157
174
  if (Array.isArray(msg.content)) {
158
175
  const mappedParts = msg.content.map(part => {
@@ -185,15 +202,16 @@ export class GeminiProvider extends LLMProvider {
185
202
  });
186
203
  contents.push({ role, parts: mappedParts });
187
204
  } else {
188
- contents.push({ role, parts: [{ text: msg.content }] });
205
+ contents.push({ role, parts: [{ text: msg.content ?? '' }] });
189
206
  }
190
207
  }
191
208
  }
192
209
 
210
+ const apiKey = requireApiKey(this.apiKey, 'Gemini');
193
211
  const payload = {
194
212
  contents,
195
213
  generationConfig: {
196
- temperature: options.temperature || 0.1,
214
+ temperature: resolveTemperature(options.temperature, 0.1),
197
215
  }
198
216
  };
199
217
 
@@ -212,18 +230,31 @@ export class GeminiProvider extends LLMProvider {
212
230
  freeFormPaths = scanReport.freeFormPaths;
213
231
  }
214
232
 
215
- const response = await fetch(this.baseUrl, {
233
+ const requestOpts = {
234
+ url: this.baseUrl,
216
235
  method: 'POST',
217
- headers: { 'Content-Type': 'application/json' },
218
- body: JSON.stringify(payload)
219
- });
220
-
221
- if (!response.ok) {
222
- const errorData = await response.text();
223
- throw new Error(`Gemini API Error (${response.status}): ${errorData}`);
224
- }
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
+ };
225
246
 
226
- 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
+ });
227
258
 
228
259
  const firstCandidate = data.candidates?.[0];
229
260
  if (!firstCandidate) {
@@ -231,23 +262,26 @@ export class GeminiProvider extends LLMProvider {
231
262
  }
232
263
 
233
264
  let content = '';
265
+ let reasoningContent = typeof data.reasoningContent === 'string' ? data.reasoningContent : '';
234
266
  let toolCalls = [];
267
+ const candidateParts = Array.isArray(firstCandidate.content?.parts) ? firstCandidate.content.parts : [];
235
268
 
236
- for (const part of firstCandidate.content.parts) {
269
+ for (const part of candidateParts) {
237
270
  if (part.text) {
238
- content += part.text;
271
+ if (part.thought === true) {
272
+ reasoningContent += part.text;
273
+ } else {
274
+ content += part.text;
275
+ }
239
276
  } else if (part.functionCall) {
240
- const paths = freeFormPaths.get(part.functionCall.name) || [];
241
- const args = decodeFreeFormArguments(
242
- part.functionCall.args || {},
243
- paths
244
- );
277
+ const callName = normalizeToolName(part.functionCall.name || '');
278
+ const serializedArgs = serializeAndDecodeArguments(part.functionCall.args || {}, callName, freeFormPaths);
245
279
  toolCalls.push({
246
- id: `call_${Math.random().toString(36).substr(2, 9)}`,
280
+ id: sanitizeProviderToolId(part.functionCall.id, 'call_gemini', toolCalls.length),
247
281
  type: 'function',
248
282
  function: {
249
- name: part.functionCall.name,
250
- arguments: JSON.stringify(args)
283
+ name: callName,
284
+ arguments: serializedArgs
251
285
  }
252
286
  });
253
287
  }
@@ -256,6 +290,7 @@ export class GeminiProvider extends LLMProvider {
256
290
  return {
257
291
  content: content.trim(),
258
292
  toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
293
+ ...(reasoningContent.trim() ? { reasoningContent: reasoningContent.trim() } : {}),
259
294
  usage: this.normalizeUsage(geminiUsageToOpenAIShape(data.usageMetadata))
260
295
  };
261
296
  }
@@ -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
  export class MoonshotProvider extends LLMProvider {
7
14
  constructor(config) {
@@ -14,59 +21,62 @@ export class MoonshotProvider extends LLMProvider {
14
21
  }
15
22
 
16
23
  async chat(messages, options = {}) {
24
+ const apiKey = requireApiKey(this.apiKey, 'Moonshot AI (Kimi)');
17
25
  const sanitizedMessages = this.prepareMessages(messages);
18
26
 
19
27
  const payload = {
20
28
  model: this.model,
21
29
  messages: sanitizedMessages,
22
- temperature: options.temperature || 0.1,
30
+ temperature: resolveTemperature(options.temperature, 0.1),
23
31
  };
24
32
 
25
33
  if (options.jsonMode) {
26
34
  payload.response_format = { type: 'json_object' };
27
35
  }
28
-
29
- let headers = {
30
- 'Content-Type': 'application/json'
31
- };
32
-
33
- if (this.apiKey) {
34
- headers['Authorization'] = `Bearer ${this.apiKey}`;
35
- } else {
36
- // EXPLICIT BYOK CONSTRAINT
37
- throw new Error(`Moonshot AI (Kimi) API requires a valid API key (BYOK mode). Please set it in your configuration.`);
38
- }
39
36
 
40
- if (options.tools) {
37
+ let freeFormPaths = new Map();
38
+ if (options.tools && options.tools.length > 0) {
41
39
  const scanReport = scanAndAdaptToolsForProvider(options.tools, 'moonshot');
42
40
  payload.tools = scanReport.adaptedTools;
43
41
  payload.tool_choice = "auto";
42
+ freeFormPaths = scanReport.freeFormPaths;
44
43
  }
45
44
 
46
- const response = await fetch(this.baseUrl, {
45
+ const requestOpts = {
46
+ url: this.baseUrl,
47
47
  method: 'POST',
48
- headers: headers,
49
- body: JSON.stringify(payload)
50
- });
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
+ };
51
58
 
52
- if (!response.ok) {
53
- const errorData = await response.text();
54
- throw new Error(`Moonshot AI API Error (${response.status}): ${errorData}`);
55
- }
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
+ });
70
+ const normalized = normalizeOpenAIChatChoiceResponse(data, {
71
+ prefix: 'call_moonshot',
72
+ freeFormPaths
73
+ });
56
74
 
57
- 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
-
66
75
  return {
67
- content: content,
68
- toolCalls: (toolCalls && toolCalls.length > 0) ? toolCalls : undefined,
69
- usage: this.normalizeUsage(data.usage || { prompt_tokens: 0, completion_tokens: 0 })
76
+ content: normalized.content,
77
+ toolCalls: normalized.toolCalls,
78
+ reasoningContent: normalized.reasoningContent,
79
+ usage: this.normalizeUsage(normalized.rawUsage)
70
80
  };
71
81
  }
72
82
  }
@@ -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