@causyne/agent 1.20.120 → 1.20.122
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.
- package/README.md +3 -3
- package/package.json +1 -1
- package/src/acp/agentCatalog.js +81 -26
- package/src/acp/agentCatalog.ts +73 -29
- package/src/acp/client.js +210 -53
- package/src/acp/client.ts +202 -52
- package/src/acp/peerProfiles.js +55 -22
- package/src/acp/peerProfiles.ts +51 -22
- package/src/acp/protocol.js +37 -8
- package/src/acp/protocol.ts +30 -8
- package/src/acp/server.js +123 -25
- package/src/acp/server.ts +124 -24
- package/src/agent/errorClassifier.js +117 -0
- package/src/agent/errorClassifier.ts +165 -0
- package/src/agent/promptIntent.js +200 -0
- package/src/agent/promptIntent.ts +203 -0
- package/src/agent/toolArgValidator.js +97 -0
- package/src/agent/toolArgValidator.ts +112 -0
- package/src/agentLoop.js +33 -344
- package/src/agentLoop.ts +51 -352
- package/src/approvalGrants.js +19 -7
- package/src/approvalGrants.ts +20 -7
- package/src/approvalPolicy.js +48 -15
- package/src/approvalPolicy.ts +46 -15
- package/src/autoUpdate.js +116 -10
- package/src/autoUpdate.ts +149 -10
- package/src/browser/causyneBrowser.js +3 -2
- package/src/browser/causyneBrowser.ts +3 -2
- package/src/browser/searchProviders.js +1 -1
- package/src/browser/searchProviders.ts +1 -1
- package/src/cliMode.js +16 -2
- package/src/commands.js +10 -9
- package/src/config.js +288 -272
- package/src/config.ts +342 -0
- package/src/configVault.js +271 -0
- package/src/configVault.ts +273 -0
- package/src/continuum/compactor.js +2 -1
- package/src/continuum/compactor.ts +2 -1
- package/src/continuum/sanitizer.js +10 -3
- package/src/continuum/sanitizer.ts +9 -3
- package/src/continuum/ui/continuumPickerView.js +3 -2
- package/src/continuum/ui/continuumPickerView.ts +3 -2
- package/src/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- package/src/cortex/vectorDb.js +26 -15
- package/src/cortex/vectorDb.ts +26 -16
- package/src/creative/liveBridge.js +7 -5
- package/src/creative/liveBridge.ts +7 -5
- package/src/creative/studioScripts.js +16 -5
- package/src/creative/studioScripts.ts +14 -5
- package/src/decisionPolicy.js +16 -4
- package/src/decisionPolicy.ts +14 -4
- package/src/documentEngine/antiSlopAuditor.js +10 -5
- package/src/documentEngine/antiSlopAuditor.ts +11 -5
- package/src/documentEngine/documentForge.js +47 -15
- package/src/documentEngine/documentForge.ts +43 -14
- package/src/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- package/src/engines/design.js +2 -1
- package/src/engines/design.ts +2 -1
- package/src/engines/film.js +4 -4
- package/src/engines/film.ts +2 -2
- package/src/engines/light.js +2 -1
- package/src/engines/light.ts +2 -1
- package/src/engines/registry.js +1 -1
- package/src/engines/registry.ts +1 -1
- package/src/engines/reverseHarness.js +4 -3
- package/src/engines/reverseHarness.ts +4 -3
- package/src/entrypoint.js +77 -4
- package/src/headlessCli.js +305 -0
- package/src/headlessCli.ts +381 -0
- package/src/historyPruner.js +3 -2
- package/src/historyPruner.ts +3 -2
- package/src/hooks.js +3 -0
- package/src/hooks.ts +3 -0
- package/src/implementationPlan.js +21 -11
- package/src/implementationPlan.ts +21 -11
- package/src/infra/atomicWriter.js +4 -1
- package/src/infra/atomicWriter.ts +4 -1
- package/src/launchIntent.js +1 -1
- package/src/launchIntent.ts +1 -1
- package/src/mcp/mcpClient.js +38 -11
- package/src/mcp/mcpClient.ts +44 -11
- package/src/mcp/mcpRegistry.js +2 -5
- package/src/mcp/mcpRegistry.ts +2 -5
- package/src/mcp/mcpSecurity.js +189 -0
- package/src/mcp/mcpSecurity.ts +190 -0
- package/src/memory/scopedFacts.js +1 -1
- package/src/memory/scopedFacts.ts +1 -1
- package/src/memory/symbolFolder.js +1 -1
- package/src/memory/symbolFolder.ts +1 -1
- package/src/modelRouter.js +1 -1
- package/src/modelRouter.ts +1 -1
- package/src/observer/evidence.js +10 -4
- package/src/observer/evidence.ts +10 -4
- package/src/osKeychain.js +263 -0
- package/src/osKeychain.ts +287 -0
- package/src/perception.js +3 -2
- package/src/perception.ts +3 -2
- package/src/planCache.js +2 -2
- package/src/planCache.ts +2 -2
- package/src/pluginsFactory/pluginsFactory.js +19 -11
- package/src/pluginsFactory/pluginsFactory.ts +18 -11
- package/src/promptMentions.js +2 -2
- package/src/promptMentions.ts +2 -2
- package/src/providers/acp.js +1 -1
- package/src/providers/acp.ts +1 -1
- package/src/providers/anthropic.js +328 -385
- package/src/providers/anthropic.ts +386 -0
- package/src/providers/antigravity.js +10 -4
- package/src/providers/antigravity.ts +10 -4
- package/src/providers/base.js +221 -319
- package/src/providers/base.ts +340 -0
- package/src/providers/byokHttp.js +397 -0
- package/src/providers/byokHttp.ts +497 -0
- package/src/providers/byokStream.js +748 -0
- package/src/providers/byokStream.ts +863 -0
- package/src/providers/dashscope-byok.js +98 -81
- package/src/providers/dashscope-byok.ts +114 -0
- package/src/providers/deepseek.js +74 -64
- package/src/providers/deepseek.ts +99 -0
- package/src/providers/factory.js +35 -28
- package/src/providers/factory.ts +40 -0
- package/src/providers/gemini.js +229 -253
- package/src/providers/gemini.ts +261 -0
- package/src/providers/loopGuard.js +9 -5
- package/src/providers/loopGuard.ts +10 -5
- package/src/providers/moonshot.js +71 -64
- package/src/providers/moonshot.ts +93 -0
- package/src/providers/muse.js +82 -152
- package/src/providers/muse.ts +122 -0
- package/src/providers/ollama.js +116 -93
- package/src/providers/ollama.ts +135 -0
- package/src/providers/openai-compatible.js +114 -65
- package/src/providers/openai-compatible.ts +139 -0
- package/src/providers/openai.js +22 -15
- package/src/providers/openai.ts +30 -0
- package/src/providers/openrouter.js +194 -98
- package/src/providers/openrouter.ts +202 -97
- package/src/providers/pi.js +6 -0
- package/src/providers/pi.ts +6 -0
- package/src/providers/qwen-byok.js +97 -71
- package/src/providers/qwen-byok.ts +113 -0
- package/src/providers/toolContracts.js +40 -14
- package/src/providers/toolContracts.ts +35 -14
- package/src/providers/wireNormalizer.js +78 -11
- package/src/providers/wireNormalizer.ts +68 -12
- package/src/providers/xai.js +74 -64
- package/src/providers/xai.ts +97 -0
- package/src/reliability/assetEvidence.js +4 -2
- package/src/reliability/assetEvidence.ts +4 -2
- package/src/sandbox.js +486 -530
- package/src/sandbox.ts +552 -0
- package/src/sandboxPolicy.js +1287 -0
- package/src/sandboxPolicy.ts +1381 -0
- package/src/sessionJournal.js +55 -3
- package/src/sessionJournal.ts +58 -3
- package/src/skills/skillResourceSafety.js +19 -8
- package/src/skills/skillResourceSafety.ts +16 -7
- package/src/skillsManager.js +3 -3
- package/src/skillsManager.ts +3 -3
- package/src/smartToolsUse.js +28 -4
- package/src/smartToolsUse.ts +29 -7
- package/src/stallGuard.js +45 -22
- package/src/stallGuard.ts +46 -22
- package/src/subagentJournal.js +6 -4
- package/src/subagentJournal.ts +6 -4
- package/src/textDiff.js +6 -1
- package/src/textDiff.ts +6 -1
- package/src/timeMachine.js +7 -1
- package/src/timeMachine.ts +7 -1
- package/src/tokenTracker.js +43 -28
- package/src/tokenTracker.ts +44 -30
- package/src/toolPacks.js +3 -1
- package/src/toolPacks.ts +3 -1
- package/src/tools/archive.js +245 -35
- package/src/tools/archive.ts +244 -35
- package/src/tools/computerUse.js +7 -3
- package/src/tools/computerUse.ts +7 -3
- package/src/tools/creativeApps.js +13 -8
- package/src/tools/creativeApps.ts +22 -9
- package/src/tools/deferredMcpSearch.js +26 -14
- package/src/tools/deferredMcpSearch.ts +26 -14
- package/src/tools/desktopOpen.js +69 -10
- package/src/tools/desktopOpen.ts +70 -11
- package/src/tools/documentForge.js +167 -82
- package/src/tools/documentForge.ts +169 -84
- package/src/tools/fsEdit.js +101 -30
- package/src/tools/fsEdit.ts +105 -32
- package/src/tools/fsFind.js +8 -5
- package/src/tools/fsFind.ts +7 -4
- package/src/tools/fsRead.js +119 -13
- package/src/tools/fsRead.ts +124 -13
- package/src/tools/fsWrite.js +17 -5
- package/src/tools/fsWrite.ts +17 -7
- package/src/tools/generateMediaViaApi.js +82 -19
- package/src/tools/generateMediaViaApi.ts +80 -19
- package/src/tools/memoryRecall.js +62 -11
- package/src/tools/memoryRecall.ts +70 -13
- package/src/tools/memoryWrite.js +27 -14
- package/src/tools/memoryWrite.ts +30 -14
- package/src/tools/multiEdit.js +100 -30
- package/src/tools/multiEdit.ts +104 -32
- package/src/tools/nativeEngine.js +33 -18
- package/src/tools/nativeEngine.ts +31 -18
- package/src/tools/openSourceToolProvisioner.js +49 -14
- package/src/tools/openSourceToolProvisioner.ts +54 -15
- package/src/tools/osSandbox.js +513 -0
- package/src/tools/osSandbox.ts +588 -0
- package/src/tools/payloadSanitizer.js +40 -8
- package/src/tools/payloadSanitizer.ts +39 -8
- package/src/tools/peerAgent.js +96 -34
- package/src/tools/peerAgent.ts +114 -37
- package/src/tools/persistentShell.js +8 -3
- package/src/tools/pluginsFactory.js +38 -6
- package/src/tools/pluginsFactory.ts +42 -6
- package/src/tools/readNativeSkill.js +10 -8
- package/src/tools/readNativeSkill.ts +10 -8
- package/src/tools/requestDecision.js +10 -3
- package/src/tools/requestDecision.ts +10 -3
- package/src/tools/resolveAutomator.js +91 -17
- package/src/tools/resolveAutomator.ts +102 -17
- package/src/tools/reverseEngineering.js +168 -41
- package/src/tools/reverseEngineering.ts +161 -41
- package/src/tools/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +108 -35
- package/src/tools/sysRun.ts +119 -31
- package/src/tools/toolDispatch.js +24 -1
- package/src/tools/toolDispatch.ts +21 -1
- package/src/tools/toolOutputStore.js +62 -23
- package/src/tools/toolOutputStore.ts +56 -23
- package/src/tools/toolScanner.js +13 -10
- package/src/tools/toolScanner.ts +13 -10
- package/src/tools/toolSelfRepair.js +94 -28
- package/src/tools/toolSelfRepair.ts +96 -28
- package/src/tools/uiForge.js +71 -6
- package/src/tools/uiForge.ts +74 -6
- package/src/tools/viewImage.js +62 -17
- package/src/tools/viewImage.ts +57 -12
- package/src/tools/visionInspector.js +15 -3
- package/src/tools/visionInspector.ts +15 -3
- package/src/tools/walkerSafety.js +2 -0
- package/src/tools/walkerSafety.ts +1 -0
- package/src/tools/webFetch.js +105 -10
- package/src/tools/webFetch.ts +105 -11
- package/src/tui/banner.js +3 -2
- package/src/tui/banner.ts +3 -2
- package/src/tui/consoleGuard.js +12 -4
- package/src/tui/consoleGuard.ts +9 -4
- package/src/tui/messageInteraction.js +2 -3
- package/src/tui/messageInteraction.ts +2 -3
- package/src/tui/modelPicker.js +1 -0
- package/src/tui/modelPicker.ts +1 -0
- package/src/tui/overlay.js +3 -1
- package/src/tui/overlay.ts +3 -1
- package/src/tui/sessionPicker.js +3 -2
- package/src/tui/sessionPicker.ts +3 -2
- package/src/tui/sessionPickerView.js +7 -1
- package/src/tui/sessionPickerView.ts +6 -1
- package/src/tui/toolOutputNormalizer.js +2 -3
- package/src/tui/toolOutputNormalizer.ts +4 -3
- package/src/tui/viewport.js +4 -4
- package/src/tui/viewport.ts +5 -5
- package/src/tui/workspaceIdentity.js +2 -1
- package/src/tui/workspaceIdentity.ts +2 -1
- package/src/uncertainty.js +8 -3
- package/src/uncertainty.ts +8 -3
- package/src/utils/paths.js +8 -5
- package/src/utils/paths.ts +9 -7
- package/src/vfeTracker.js +9 -3
- package/src/vfeTracker.ts +9 -3
- package/src/config.d.ts +0 -2
- package/src/providers/base.d.ts +0 -94
- package/src/providers/factory.d.ts +0 -1
- package/src/sandbox.d.ts +0 -1
|
@@ -7,16 +7,28 @@
|
|
|
7
7
|
* streaming SSE, and safe tool-call parsing without paid model fallbacks.
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
|
-
import { LLMProvider } from './base.js';
|
|
10
|
+
import { LLMProvider, type ChatOptions, type ChatResponse, type ChatResponseUsage, type ChatResponseToolCall } from './base.js';
|
|
11
11
|
import { canonicalModelId } from '../modelIds.js';
|
|
12
|
-
import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
|
|
12
|
+
import { scanAndAdaptToolsForProvider, normalizeToolName } from '../tools/toolScanner.js';
|
|
13
|
+
import { stripToolCallMarkup } from '../implementationPlan.js';
|
|
13
14
|
import {
|
|
14
15
|
extractTextToolCalls,
|
|
15
16
|
normalizeOpenAIChatChoiceResponse,
|
|
17
|
+
sanitizeProviderToolId,
|
|
16
18
|
serializeAndDecodeArguments
|
|
17
19
|
} from './wireNormalizer.js';
|
|
18
|
-
import {
|
|
19
|
-
|
|
20
|
+
import {
|
|
21
|
+
MAX_PROVIDER_ERROR_BYTES,
|
|
22
|
+
MAX_PROVIDER_JSON_BYTES,
|
|
23
|
+
MAX_SSE_BUFFER_BYTES,
|
|
24
|
+
ProviderHttpError,
|
|
25
|
+
parseRetryAfterMs,
|
|
26
|
+
readBoundedResponseText,
|
|
27
|
+
redactProviderSecrets,
|
|
28
|
+
resolveTemperature,
|
|
29
|
+
safeProviderFetch
|
|
30
|
+
} from './byokHttp.js';
|
|
31
|
+
import { wantsStreaming } from './byokStream.js';
|
|
20
32
|
|
|
21
33
|
export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
|
|
22
34
|
export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
|
|
@@ -30,9 +42,13 @@ export class FreeModeCostGuardError extends Error {
|
|
|
30
42
|
}
|
|
31
43
|
|
|
32
44
|
export class OpenRouterRateLimitError extends Error {
|
|
33
|
-
|
|
45
|
+
public readonly status = 429;
|
|
46
|
+
public readonly retryAfterMs?: number | undefined;
|
|
47
|
+
|
|
48
|
+
constructor(message: string, retryAfterMs?: number | undefined) {
|
|
34
49
|
super(message);
|
|
35
50
|
this.name = 'OpenRouterRateLimitError';
|
|
51
|
+
this.retryAfterMs = retryAfterMs;
|
|
36
52
|
}
|
|
37
53
|
}
|
|
38
54
|
|
|
@@ -46,10 +62,12 @@ export class OpenRouterPrivacyConstraintError extends Error {
|
|
|
46
62
|
export class OpenRouterProvider extends LLMProvider {
|
|
47
63
|
public dataCollection: 'deny' | 'allow';
|
|
48
64
|
public freeOnly: boolean;
|
|
65
|
+
public allowInsecureHttp: boolean;
|
|
49
66
|
|
|
50
67
|
constructor(config: Record<string, any> = {}) {
|
|
51
68
|
super(config);
|
|
52
69
|
this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
|
|
70
|
+
this.allowInsecureHttp = config['allowInsecureHttp'] === true;
|
|
53
71
|
this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
|
|
54
72
|
this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
|
|
55
73
|
this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
|
|
@@ -65,8 +83,12 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
65
83
|
*/
|
|
66
84
|
public isFreeModel(modelId: string): boolean {
|
|
67
85
|
const clean = (modelId || '').trim().toLowerCase();
|
|
86
|
+
if (!clean || /[\s?#\x00-\x1f]/.test(clean)) return false;
|
|
68
87
|
if (clean === 'openrouter/free' || clean === 'free') return true;
|
|
69
|
-
if (clean.endsWith(':free'))
|
|
88
|
+
if (clean.endsWith(':free')) {
|
|
89
|
+
const slug = clean.slice(0, -5);
|
|
90
|
+
return slug.length > 0 && !slug.startsWith('/') && !slug.endsWith('/');
|
|
91
|
+
}
|
|
70
92
|
return false;
|
|
71
93
|
}
|
|
72
94
|
|
|
@@ -89,7 +111,7 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
89
111
|
this.assertFreeModel(this.model);
|
|
90
112
|
}
|
|
91
113
|
|
|
92
|
-
const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
|
|
114
|
+
const apiKey = String(this.apiKey || process.env.OPENROUTER_API_KEY || '').trim();
|
|
93
115
|
if (!apiKey) {
|
|
94
116
|
throw new Error(
|
|
95
117
|
'OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.'
|
|
@@ -97,18 +119,23 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
97
119
|
}
|
|
98
120
|
|
|
99
121
|
const preparedMessages = this.prepareMessages(messages);
|
|
100
|
-
const shouldStream =
|
|
122
|
+
const shouldStream = wantsStreaming(options);
|
|
101
123
|
|
|
102
124
|
const payload: Record<string, any> = {
|
|
103
125
|
model: this.model,
|
|
104
126
|
messages: preparedMessages,
|
|
105
|
-
temperature: options.temperature
|
|
127
|
+
temperature: resolveTemperature(options.temperature, 0.1),
|
|
106
128
|
stream: shouldStream,
|
|
129
|
+
...(shouldStream ? { stream_options: { include_usage: true } } : {}),
|
|
107
130
|
provider: {
|
|
108
131
|
data_collection: this.dataCollection
|
|
109
132
|
}
|
|
110
133
|
};
|
|
111
134
|
|
|
135
|
+
if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
|
|
136
|
+
payload['max_tokens'] = Math.floor(options.maxTokens);
|
|
137
|
+
}
|
|
138
|
+
|
|
112
139
|
if (options['jsonMode']) {
|
|
113
140
|
payload['response_format'] = { type: 'json_object' };
|
|
114
141
|
}
|
|
@@ -128,45 +155,61 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
128
155
|
'X-Title': 'Causyne Agent'
|
|
129
156
|
};
|
|
130
157
|
|
|
131
|
-
let response: Response;
|
|
132
158
|
const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
|
|
133
|
-
const
|
|
159
|
+
const { response, cleanup } = await safeProviderFetch({
|
|
160
|
+
url: endpoint,
|
|
134
161
|
method: 'POST',
|
|
135
162
|
headers,
|
|
136
|
-
body: JSON.stringify(payload)
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
163
|
+
body: JSON.stringify(payload),
|
|
164
|
+
signal: options.signal,
|
|
165
|
+
timeoutMs: typeof options['timeoutMs'] === 'number' ? options['timeoutMs'] : undefined,
|
|
166
|
+
providerLabel: 'OpenRouter',
|
|
167
|
+
secrets: [apiKey],
|
|
168
|
+
hasApiKey: true,
|
|
169
|
+
allowInsecureHttp: this.allowInsecureHttp
|
|
170
|
+
});
|
|
141
171
|
|
|
142
172
|
try {
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
173
|
+
if (!response.ok) {
|
|
174
|
+
const rawError = await readBoundedResponseText(response, MAX_PROVIDER_ERROR_BYTES, {
|
|
175
|
+
truncate: true,
|
|
176
|
+
label: 'OpenRouter'
|
|
177
|
+
}).catch(() => '');
|
|
178
|
+
const cleanError = redactProviderSecrets(rawError, [apiKey]);
|
|
179
|
+
const retryAfterHeader = (response as unknown as { headers?: { get?: (k: string) => string | null } }).headers?.get?.('retry-after');
|
|
180
|
+
const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
|
|
181
|
+
this.handleHttpErrors(response.status, cleanError, retryAfterMs);
|
|
147
182
|
}
|
|
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
183
|
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
184
|
+
const contentType = ((response as unknown as { headers?: { get?: (k: string) => string | null } }).headers?.get?.('content-type') ?? '')
|
|
185
|
+
.split(';')[0]?.trim().toLowerCase() ?? '';
|
|
186
|
+
const isJsonReply = contentType === 'application/json' || contentType.endsWith('+json');
|
|
187
|
+
if (shouldStream && response.body && !isJsonReply) {
|
|
188
|
+
return await this.handleStreamingResponse(response, options, freeFormPaths, apiKey);
|
|
189
|
+
} else {
|
|
190
|
+
const res = await this.handleJsonResponse(response, freeFormPaths, apiKey);
|
|
191
|
+
if (shouldStream) {
|
|
192
|
+
if (res.reasoningContent) options.onReasoningChunk?.(res.reasoningContent);
|
|
193
|
+
if (res.content) options.onChunk?.(res.content);
|
|
194
|
+
}
|
|
195
|
+
return res;
|
|
196
|
+
}
|
|
197
|
+
} finally {
|
|
198
|
+
cleanup();
|
|
160
199
|
}
|
|
161
200
|
}
|
|
162
201
|
|
|
163
202
|
/**
|
|
164
203
|
* Map HTTP error codes into user-friendly and security-preserving exceptions.
|
|
165
204
|
*/
|
|
166
|
-
private handleHttpErrors(status: number, errorText: string): never {
|
|
205
|
+
private handleHttpErrors(status: number, errorText: string, retryAfterMs?: number): never {
|
|
167
206
|
if (status === 429) {
|
|
207
|
+
const retryNote = retryAfterMs !== undefined
|
|
208
|
+
? ` Retry after ${Math.ceil(retryAfterMs / 1000)}s.`
|
|
209
|
+
: '';
|
|
168
210
|
throw new OpenRouterRateLimitError(
|
|
169
|
-
|
|
211
|
+
`OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.${retryNote}`,
|
|
212
|
+
retryAfterMs
|
|
170
213
|
);
|
|
171
214
|
}
|
|
172
215
|
|
|
@@ -181,12 +224,13 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
181
224
|
}
|
|
182
225
|
if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
|
|
183
226
|
throw new OpenRouterRateLimitError(
|
|
184
|
-
'OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.'
|
|
227
|
+
'OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.',
|
|
228
|
+
retryAfterMs
|
|
185
229
|
);
|
|
186
230
|
}
|
|
187
231
|
}
|
|
188
232
|
|
|
189
|
-
throw new
|
|
233
|
+
throw new ProviderHttpError(`OpenRouter API Error (${status}): ${errorText}`, { status, retryAfterMs });
|
|
190
234
|
}
|
|
191
235
|
|
|
192
236
|
/**
|
|
@@ -194,9 +238,31 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
194
238
|
*/
|
|
195
239
|
private async handleJsonResponse(
|
|
196
240
|
response: Response,
|
|
197
|
-
freeFormPaths?: Map<string, string[][]
|
|
241
|
+
freeFormPaths?: Map<string, string[][]>,
|
|
242
|
+
apiKey?: string
|
|
198
243
|
): Promise<ChatResponse> {
|
|
199
|
-
|
|
244
|
+
let data: any;
|
|
245
|
+
if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
|
|
246
|
+
data = await response.json();
|
|
247
|
+
} else {
|
|
248
|
+
const rawText = await readBoundedResponseText(response, MAX_PROVIDER_JSON_BYTES, {
|
|
249
|
+
truncate: false,
|
|
250
|
+
label: 'OpenRouter'
|
|
251
|
+
});
|
|
252
|
+
const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
253
|
+
try {
|
|
254
|
+
data = JSON.parse(cleanText);
|
|
255
|
+
} catch {
|
|
256
|
+
const preview = redactProviderSecrets(rawText.slice(0, 240), [apiKey]);
|
|
257
|
+
throw new Error(`OpenRouter returned a non-JSON response (HTTP ${response.status}): ${preview}`);
|
|
258
|
+
}
|
|
259
|
+
}
|
|
260
|
+
if (data && typeof data === 'object' && data.error && typeof data.error === 'object') {
|
|
261
|
+
const rawErr = typeof data.error.message === 'string' ? data.error.message : JSON.stringify(data.error);
|
|
262
|
+
const cleanErr = redactProviderSecrets(rawErr, [apiKey]);
|
|
263
|
+
const code = typeof data.error.code === 'number' ? data.error.code : 502;
|
|
264
|
+
this.handleHttpErrors(code, cleanErr);
|
|
265
|
+
}
|
|
200
266
|
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
201
267
|
prefix: 'call_openrouter',
|
|
202
268
|
...(freeFormPaths ? { freeFormPaths } : {})
|
|
@@ -217,7 +283,8 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
217
283
|
private async handleStreamingResponse(
|
|
218
284
|
response: Response,
|
|
219
285
|
options: ChatOptions,
|
|
220
|
-
freeFormPaths?: Map<string, string[][]
|
|
286
|
+
freeFormPaths?: Map<string, string[][]>,
|
|
287
|
+
apiKey?: string
|
|
221
288
|
): Promise<ChatResponse> {
|
|
222
289
|
const reader = response.body!.getReader();
|
|
223
290
|
const decoder = new TextDecoder('utf-8');
|
|
@@ -225,79 +292,114 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
225
292
|
let content = '';
|
|
226
293
|
let reasoningContent = '';
|
|
227
294
|
let buffer = '';
|
|
295
|
+
let totalBytes = 0;
|
|
228
296
|
const toolCallsMap = new Map<number, { id: string; name: string; arguments: string }>();
|
|
229
297
|
let rawUsage: any = null;
|
|
230
298
|
|
|
299
|
+
const processLine = (line: string): void => {
|
|
300
|
+
const stripped = line.charCodeAt(0) === 0xfeff ? line.slice(1) : line;
|
|
301
|
+
const trimmed = stripped.trim();
|
|
302
|
+
if (!trimmed || trimmed.startsWith(':')) return; // Skip comments/keepalive
|
|
303
|
+
if (trimmed === 'data: [DONE]' || trimmed === 'data:[DONE]') return;
|
|
304
|
+
|
|
305
|
+
if (trimmed.startsWith('data:')) {
|
|
306
|
+
const jsonStr = trimmed.slice(5).replace(/^ /, '');
|
|
307
|
+
let parsed: any;
|
|
308
|
+
try {
|
|
309
|
+
parsed = JSON.parse(jsonStr);
|
|
310
|
+
} catch {
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
if (!parsed || typeof parsed !== 'object') return;
|
|
314
|
+
if (parsed.error && typeof parsed.error === 'object') {
|
|
315
|
+
const rawErr = typeof parsed.error.message === 'string' ? parsed.error.message : JSON.stringify(parsed.error);
|
|
316
|
+
const cleanErr = redactProviderSecrets(rawErr, [apiKey]);
|
|
317
|
+
const code = typeof parsed.error.code === 'number' ? parsed.error.code : 502;
|
|
318
|
+
this.handleHttpErrors(code, cleanErr);
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
if (parsed.usage) {
|
|
322
|
+
rawUsage = parsed.usage;
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
const choice = parsed.choices?.[0];
|
|
326
|
+
if (!choice) return;
|
|
327
|
+
|
|
328
|
+
const delta = choice.delta;
|
|
329
|
+
if (delta) {
|
|
330
|
+
// 1. Text chunk
|
|
331
|
+
if (delta.content) {
|
|
332
|
+
content += delta.content;
|
|
333
|
+
if (options.onChunk) {
|
|
334
|
+
options.onChunk(delta.content);
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
// 2. Reasoning chunk
|
|
339
|
+
const reasoning = delta.reasoning || delta.reasoning_content;
|
|
340
|
+
if (reasoning) {
|
|
341
|
+
reasoningContent += reasoning;
|
|
342
|
+
if (options.onReasoningChunk) {
|
|
343
|
+
options.onReasoningChunk(reasoning);
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// 3. Tool calls assembly
|
|
348
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
349
|
+
for (const tc of delta.tool_calls) {
|
|
350
|
+
if (!tc || typeof tc !== 'object') continue;
|
|
351
|
+
const idx = typeof tc.index === 'number' && Number.isInteger(tc.index) && tc.index >= 0
|
|
352
|
+
? tc.index
|
|
353
|
+
: Math.max(-1, ...toolCallsMap.keys()) + 1;
|
|
354
|
+
let existing = toolCallsMap.get(idx);
|
|
355
|
+
if (!existing) {
|
|
356
|
+
existing = { id: sanitizeProviderToolId(tc.id, 'call_openrouter', idx), name: '', arguments: '' };
|
|
357
|
+
toolCallsMap.set(idx, existing);
|
|
358
|
+
}
|
|
359
|
+
if (typeof tc.id === 'string' && tc.id) existing.id = sanitizeProviderToolId(tc.id, 'call_openrouter', idx);
|
|
360
|
+
if (typeof tc.function?.name === 'string') existing.name += tc.function.name;
|
|
361
|
+
if (typeof tc.function?.arguments === 'string') existing.arguments += tc.function.arguments;
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
}
|
|
365
|
+
}
|
|
366
|
+
};
|
|
367
|
+
|
|
231
368
|
try {
|
|
232
369
|
while (true) {
|
|
233
370
|
if (options.signal?.aborted) {
|
|
234
371
|
await reader.cancel().catch(() => {});
|
|
235
|
-
|
|
372
|
+
const abortErr = new Error('OpenRouter request aborted');
|
|
373
|
+
abortErr.name = 'AbortError';
|
|
374
|
+
throw abortErr;
|
|
236
375
|
}
|
|
237
376
|
|
|
238
377
|
const { done, value } = await reader.read();
|
|
239
378
|
if (done) break;
|
|
379
|
+
if (!value) continue;
|
|
380
|
+
|
|
381
|
+
totalBytes += value.byteLength;
|
|
382
|
+
if (totalBytes > MAX_PROVIDER_JSON_BYTES) {
|
|
383
|
+
await reader.cancel().catch(() => {});
|
|
384
|
+
throw new Error(`OpenRouter stream exceeded maximum allowed size (${MAX_PROVIDER_JSON_BYTES} bytes).`);
|
|
385
|
+
}
|
|
240
386
|
|
|
241
387
|
buffer += decoder.decode(value, { stream: true });
|
|
388
|
+
if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
|
|
389
|
+
await reader.cancel().catch(() => {});
|
|
390
|
+
throw new Error(`OpenRouter SSE buffer exceeded maximum allowed size (${MAX_SSE_BUFFER_BYTES} bytes).`);
|
|
391
|
+
}
|
|
242
392
|
const lines = buffer.split('\n');
|
|
243
393
|
buffer = lines.pop() || '';
|
|
244
394
|
|
|
245
395
|
for (const line of lines) {
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
try {
|
|
254
|
-
parsed = JSON.parse(jsonStr);
|
|
255
|
-
} catch {
|
|
256
|
-
continue;
|
|
257
|
-
}
|
|
258
|
-
|
|
259
|
-
if (parsed.usage) {
|
|
260
|
-
rawUsage = parsed.usage;
|
|
261
|
-
}
|
|
262
|
-
|
|
263
|
-
const choice = parsed.choices?.[0];
|
|
264
|
-
if (!choice) continue;
|
|
265
|
-
|
|
266
|
-
const delta = choice.delta;
|
|
267
|
-
if (delta) {
|
|
268
|
-
// 1. Text chunk
|
|
269
|
-
if (delta.content) {
|
|
270
|
-
content += delta.content;
|
|
271
|
-
if (options.onChunk) {
|
|
272
|
-
options.onChunk(delta.content);
|
|
273
|
-
}
|
|
274
|
-
}
|
|
275
|
-
|
|
276
|
-
// 2. Reasoning chunk
|
|
277
|
-
const reasoning = delta.reasoning || delta.reasoning_content;
|
|
278
|
-
if (reasoning) {
|
|
279
|
-
reasoningContent += reasoning;
|
|
280
|
-
if (options.onReasoningChunk) {
|
|
281
|
-
options.onReasoningChunk(reasoning);
|
|
282
|
-
}
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
// 3. Tool calls assembly
|
|
286
|
-
if (Array.isArray(delta.tool_calls)) {
|
|
287
|
-
for (const tc of delta.tool_calls) {
|
|
288
|
-
const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
|
|
289
|
-
let existing = toolCallsMap.get(idx);
|
|
290
|
-
if (!existing) {
|
|
291
|
-
existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
|
|
292
|
-
toolCallsMap.set(idx, existing);
|
|
293
|
-
}
|
|
294
|
-
if (tc.id) existing.id = tc.id;
|
|
295
|
-
if (tc.function?.name) existing.name += tc.function.name;
|
|
296
|
-
if (tc.function?.arguments) existing.arguments += tc.function.arguments;
|
|
297
|
-
}
|
|
298
|
-
}
|
|
299
|
-
}
|
|
300
|
-
}
|
|
396
|
+
processLine(line);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
buffer += decoder.decode();
|
|
400
|
+
if (buffer.trim()) {
|
|
401
|
+
for (const line of buffer.split('\n')) {
|
|
402
|
+
processLine(line);
|
|
301
403
|
}
|
|
302
404
|
}
|
|
303
405
|
} finally {
|
|
@@ -305,11 +407,13 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
305
407
|
}
|
|
306
408
|
|
|
307
409
|
const toolCalls: ChatResponseToolCall[] = [];
|
|
308
|
-
|
|
410
|
+
const sortedItems = [...toolCallsMap.entries()].sort((a, b) => a[0] - b[0]);
|
|
411
|
+
for (const [idx, item] of sortedItems) {
|
|
309
412
|
if (item.name) {
|
|
310
413
|
const cleanName = normalizeToolName(item.name);
|
|
414
|
+
if (!cleanName) continue;
|
|
311
415
|
toolCalls.push({
|
|
312
|
-
id: item.id,
|
|
416
|
+
id: sanitizeProviderToolId(item.id, 'call_openrouter', idx),
|
|
313
417
|
type: 'function',
|
|
314
418
|
function: {
|
|
315
419
|
name: cleanName,
|
|
@@ -320,9 +424,10 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
320
424
|
}
|
|
321
425
|
|
|
322
426
|
if (toolCalls.length === 0 && content) {
|
|
323
|
-
const extracted = extractTextToolCalls(content, '
|
|
427
|
+
const extracted = extractTextToolCalls(content, 'call_openrouter_text', freeFormPaths);
|
|
324
428
|
if (extracted.length > 0) {
|
|
325
429
|
toolCalls.push(...extracted);
|
|
430
|
+
content = stripToolCallMarkup(content).trim();
|
|
326
431
|
}
|
|
327
432
|
}
|
|
328
433
|
|
package/src/providers/pi.js
CHANGED
|
@@ -29,6 +29,12 @@ export class PiProvider extends LLMProvider {
|
|
|
29
29
|
const prompt = this.formatter.formatConversation(messages, options.tools || [])
|
|
30
30
|
.replace('over ACP.', 'over Pi RPC.');
|
|
31
31
|
return new Promise((resolve, reject) => {
|
|
32
|
+
if (options.signal?.aborted) {
|
|
33
|
+
const err = new Error('Pi request aborted');
|
|
34
|
+
err.name = 'AbortError';
|
|
35
|
+
reject(err);
|
|
36
|
+
return;
|
|
37
|
+
}
|
|
32
38
|
const child = spawn(this.command, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'],
|
|
33
39
|
env: process.env, shell: false });
|
|
34
40
|
let buffer = '';
|
package/src/providers/pi.ts
CHANGED
|
@@ -34,6 +34,12 @@ export class PiProvider extends LLMProvider {
|
|
|
34
34
|
.replace('over ACP.', 'over Pi RPC.');
|
|
35
35
|
|
|
36
36
|
return new Promise<ChatResponse>((resolve, reject) => {
|
|
37
|
+
if (options.signal?.aborted) {
|
|
38
|
+
const err = new Error('Pi request aborted');
|
|
39
|
+
err.name = 'AbortError';
|
|
40
|
+
reject(err);
|
|
41
|
+
return;
|
|
42
|
+
}
|
|
37
43
|
const child = spawn(this.command, args, { cwd, stdio: ['pipe', 'pipe', 'pipe'],
|
|
38
44
|
env: process.env, shell: false });
|
|
39
45
|
let buffer = '';
|
|
@@ -3,79 +3,105 @@ 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
|
-
|
|
7
|
-
|
|
6
|
+
import { requireApiKey, resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
|
|
7
|
+
import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
|
|
8
8
|
export class QwenByokProvider extends LLMProvider {
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
let freeFormPaths = new Map();
|
|
39
|
-
if (options.tools && options.tools.length > 0) {
|
|
40
|
-
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'qwen');
|
|
41
|
-
payload.tools = scanReport.adaptedTools;
|
|
42
|
-
payload.tool_choice = "auto";
|
|
43
|
-
freeFormPaths = scanReport.freeFormPaths;
|
|
9
|
+
allowInsecureHttp;
|
|
10
|
+
constructor(config = {}) {
|
|
11
|
+
super(config);
|
|
12
|
+
let url = (typeof config.baseUrl === 'string' ? config.baseUrl.trim() : '') || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
|
|
13
|
+
try {
|
|
14
|
+
const parsed = new URL(url);
|
|
15
|
+
if (parsed.pathname.endsWith('/v1')) {
|
|
16
|
+
parsed.pathname += '/chat/completions';
|
|
17
|
+
url = parsed.toString();
|
|
18
|
+
}
|
|
19
|
+
else if (parsed.pathname.endsWith('/v1/')) {
|
|
20
|
+
parsed.pathname += 'chat/completions';
|
|
21
|
+
url = parsed.toString();
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
catch {
|
|
25
|
+
if (url.endsWith('/v1'))
|
|
26
|
+
url += '/chat/completions';
|
|
27
|
+
else if (url.endsWith('/v1/'))
|
|
28
|
+
url += 'chat/completions';
|
|
29
|
+
}
|
|
30
|
+
this.baseUrl = url;
|
|
31
|
+
this.allowInsecureHttp = config.allowInsecureHttp === true;
|
|
32
|
+
this.model = String(canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['qwen']) || '');
|
|
33
|
+
this.apiKey = config.apiKey;
|
|
34
|
+
this.visionModels = ['-vl-', '-vl', 'qwen3.6', 'qwen3.7'];
|
|
35
|
+
this.audioModels = ['-omni', 'qwen-audio', 'qwen2-audio'];
|
|
44
36
|
}
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
if (
|
|
61
|
-
|
|
37
|
+
async chat(messages, options = {}) {
|
|
38
|
+
const apiKey = requireApiKey(this.apiKey, 'Qwen DashScope');
|
|
39
|
+
const sanitizedMessages = this.prepareMessages(messages);
|
|
40
|
+
const payload = {
|
|
41
|
+
model: this.model,
|
|
42
|
+
messages: sanitizedMessages,
|
|
43
|
+
temperature: resolveTemperature(options.temperature, 0.1)
|
|
44
|
+
};
|
|
45
|
+
if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
|
|
46
|
+
payload['max_tokens'] = Math.floor(options.maxTokens);
|
|
47
|
+
}
|
|
48
|
+
if (options.jsonMode) {
|
|
49
|
+
payload['response_format'] = { type: 'json_object' };
|
|
50
|
+
}
|
|
51
|
+
let freeFormPaths = new Map();
|
|
52
|
+
if (options.tools && options.tools.length > 0) {
|
|
53
|
+
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'qwen');
|
|
54
|
+
payload['tools'] = scanReport.adaptedTools;
|
|
55
|
+
payload['tool_choice'] = 'auto';
|
|
56
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
62
57
|
}
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
58
|
+
const endpoint = this.baseUrl || 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
|
|
59
|
+
const requestOpts = {
|
|
60
|
+
url: endpoint,
|
|
61
|
+
method: 'POST',
|
|
62
|
+
headers: {
|
|
63
|
+
'Content-Type': 'application/json',
|
|
64
|
+
'Authorization': `Bearer ${apiKey}`
|
|
65
|
+
},
|
|
66
|
+
signal: options.signal,
|
|
67
|
+
timeoutMs: options.timeoutMs,
|
|
68
|
+
providerLabel: 'Qwen DashScope',
|
|
69
|
+
secrets: [apiKey],
|
|
70
|
+
hasApiKey: true,
|
|
71
|
+
allowInsecureHttp: this.allowInsecureHttp,
|
|
72
|
+
onHttpError: ({ status }) => {
|
|
73
|
+
let hostHasWorkspace = false;
|
|
74
|
+
try {
|
|
75
|
+
hostHasWorkspace = new URL(endpoint).hostname.includes('ws-');
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
hostHasWorkspace = false;
|
|
79
|
+
}
|
|
80
|
+
if (status === 401 && apiKey.startsWith('sk-ws-') && !hostHasWorkspace) {
|
|
81
|
+
throw new Error('\n[QWEN WORKSPACE CONFIGURATION ERROR]\n\nYou are using a Workspace-bound API Key (starts with sk-ws-), but you have not 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 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.');
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
};
|
|
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
|
+
});
|
|
96
|
+
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
97
|
+
prefix: 'call_qwen',
|
|
98
|
+
freeFormPaths
|
|
99
|
+
});
|
|
100
|
+
return {
|
|
101
|
+
content: normalized.content,
|
|
102
|
+
toolCalls: normalized.toolCalls,
|
|
103
|
+
reasoningContent: normalized.reasoningContent,
|
|
104
|
+
usage: this.normalizeUsage(normalized.rawUsage)
|
|
105
|
+
};
|
|
66
106
|
}
|
|
67
|
-
|
|
68
|
-
const data = await response.json();
|
|
69
|
-
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
70
|
-
prefix: 'call_qwen',
|
|
71
|
-
freeFormPaths
|
|
72
|
-
});
|
|
73
|
-
|
|
74
|
-
return {
|
|
75
|
-
content: normalized.content,
|
|
76
|
-
toolCalls: normalized.toolCalls,
|
|
77
|
-
reasoningContent: normalized.reasoningContent,
|
|
78
|
-
usage: this.normalizeUsage(normalized.rawUsage)
|
|
79
|
-
};
|
|
80
|
-
}
|
|
81
107
|
}
|