@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
|
@@ -8,9 +8,11 @@
|
|
|
8
8
|
*/
|
|
9
9
|
import { LLMProvider } from './base.js';
|
|
10
10
|
import { canonicalModelId } from '../modelIds.js';
|
|
11
|
-
import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
11
|
+
import { scanAndAdaptToolsForProvider, normalizeToolName } from '../tools/toolScanner.js';
|
|
12
|
+
import { stripToolCallMarkup } from '../implementationPlan.js';
|
|
13
|
+
import { extractTextToolCalls, normalizeOpenAIChatChoiceResponse, sanitizeProviderToolId, serializeAndDecodeArguments } from './wireNormalizer.js';
|
|
14
|
+
import { MAX_PROVIDER_ERROR_BYTES, MAX_PROVIDER_JSON_BYTES, MAX_SSE_BUFFER_BYTES, ProviderHttpError, parseRetryAfterMs, readBoundedResponseText, redactProviderSecrets, resolveTemperature, safeProviderFetch } from './byokHttp.js';
|
|
15
|
+
import { wantsStreaming } from './byokStream.js';
|
|
14
16
|
export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
|
|
15
17
|
export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
|
|
16
18
|
export const OPENROUTER_DEFAULT_FREE_MODEL = 'openrouter/free';
|
|
@@ -21,9 +23,12 @@ export class FreeModeCostGuardError extends Error {
|
|
|
21
23
|
}
|
|
22
24
|
}
|
|
23
25
|
export class OpenRouterRateLimitError extends Error {
|
|
24
|
-
|
|
26
|
+
status = 429;
|
|
27
|
+
retryAfterMs;
|
|
28
|
+
constructor(message, retryAfterMs) {
|
|
25
29
|
super(message);
|
|
26
30
|
this.name = 'OpenRouterRateLimitError';
|
|
31
|
+
this.retryAfterMs = retryAfterMs;
|
|
27
32
|
}
|
|
28
33
|
}
|
|
29
34
|
export class OpenRouterPrivacyConstraintError extends Error {
|
|
@@ -35,9 +40,11 @@ export class OpenRouterPrivacyConstraintError extends Error {
|
|
|
35
40
|
export class OpenRouterProvider extends LLMProvider {
|
|
36
41
|
dataCollection;
|
|
37
42
|
freeOnly;
|
|
43
|
+
allowInsecureHttp;
|
|
38
44
|
constructor(config = {}) {
|
|
39
45
|
super(config);
|
|
40
46
|
this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
|
|
47
|
+
this.allowInsecureHttp = config['allowInsecureHttp'] === true;
|
|
41
48
|
this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
|
|
42
49
|
this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
|
|
43
50
|
this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
|
|
@@ -51,10 +58,14 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
51
58
|
*/
|
|
52
59
|
isFreeModel(modelId) {
|
|
53
60
|
const clean = (modelId || '').trim().toLowerCase();
|
|
61
|
+
if (!clean || /[\s?#\x00-\x1f]/.test(clean))
|
|
62
|
+
return false;
|
|
54
63
|
if (clean === 'openrouter/free' || clean === 'free')
|
|
55
64
|
return true;
|
|
56
|
-
if (clean.endsWith(':free'))
|
|
57
|
-
|
|
65
|
+
if (clean.endsWith(':free')) {
|
|
66
|
+
const slug = clean.slice(0, -5);
|
|
67
|
+
return slug.length > 0 && !slug.startsWith('/') && !slug.endsWith('/');
|
|
68
|
+
}
|
|
58
69
|
return false;
|
|
59
70
|
}
|
|
60
71
|
/**
|
|
@@ -72,21 +83,25 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
72
83
|
if (this.freeOnly) {
|
|
73
84
|
this.assertFreeModel(this.model);
|
|
74
85
|
}
|
|
75
|
-
const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
|
|
86
|
+
const apiKey = String(this.apiKey || process.env.OPENROUTER_API_KEY || '').trim();
|
|
76
87
|
if (!apiKey) {
|
|
77
88
|
throw new Error('OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.');
|
|
78
89
|
}
|
|
79
90
|
const preparedMessages = this.prepareMessages(messages);
|
|
80
|
-
const shouldStream =
|
|
91
|
+
const shouldStream = wantsStreaming(options);
|
|
81
92
|
const payload = {
|
|
82
93
|
model: this.model,
|
|
83
94
|
messages: preparedMessages,
|
|
84
|
-
temperature: options.temperature
|
|
95
|
+
temperature: resolveTemperature(options.temperature, 0.1),
|
|
85
96
|
stream: shouldStream,
|
|
97
|
+
...(shouldStream ? { stream_options: { include_usage: true } } : {}),
|
|
86
98
|
provider: {
|
|
87
99
|
data_collection: this.dataCollection
|
|
88
100
|
}
|
|
89
101
|
};
|
|
102
|
+
if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
|
|
103
|
+
payload['max_tokens'] = Math.floor(options.maxTokens);
|
|
104
|
+
}
|
|
90
105
|
if (options['jsonMode']) {
|
|
91
106
|
payload['response_format'] = { type: 'json_object' };
|
|
92
107
|
}
|
|
@@ -103,42 +118,60 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
103
118
|
'HTTP-Referer': 'https://causyne.com',
|
|
104
119
|
'X-Title': 'Causyne Agent'
|
|
105
120
|
};
|
|
106
|
-
let response;
|
|
107
121
|
const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
|
|
108
|
-
const
|
|
122
|
+
const { response, cleanup } = await safeProviderFetch({
|
|
123
|
+
url: endpoint,
|
|
109
124
|
method: 'POST',
|
|
110
125
|
headers,
|
|
111
|
-
body: JSON.stringify(payload)
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
126
|
+
body: JSON.stringify(payload),
|
|
127
|
+
signal: options.signal,
|
|
128
|
+
timeoutMs: typeof options['timeoutMs'] === 'number' ? options['timeoutMs'] : undefined,
|
|
129
|
+
providerLabel: 'OpenRouter',
|
|
130
|
+
secrets: [apiKey],
|
|
131
|
+
hasApiKey: true,
|
|
132
|
+
allowInsecureHttp: this.allowInsecureHttp
|
|
133
|
+
});
|
|
116
134
|
try {
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
135
|
+
if (!response.ok) {
|
|
136
|
+
const rawError = await readBoundedResponseText(response, MAX_PROVIDER_ERROR_BYTES, {
|
|
137
|
+
truncate: true,
|
|
138
|
+
label: 'OpenRouter'
|
|
139
|
+
}).catch(() => '');
|
|
140
|
+
const cleanError = redactProviderSecrets(rawError, [apiKey]);
|
|
141
|
+
const retryAfterHeader = response.headers?.get?.('retry-after');
|
|
142
|
+
const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
|
|
143
|
+
this.handleHttpErrors(response.status, cleanError, retryAfterMs);
|
|
144
|
+
}
|
|
145
|
+
const contentType = (response.headers?.get?.('content-type') ?? '')
|
|
146
|
+
.split(';')[0]?.trim().toLowerCase() ?? '';
|
|
147
|
+
const isJsonReply = contentType === 'application/json' || contentType.endsWith('+json');
|
|
148
|
+
if (shouldStream && response.body && !isJsonReply) {
|
|
149
|
+
return await this.handleStreamingResponse(response, options, freeFormPaths, apiKey);
|
|
150
|
+
}
|
|
151
|
+
else {
|
|
152
|
+
const res = await this.handleJsonResponse(response, freeFormPaths, apiKey);
|
|
153
|
+
if (shouldStream) {
|
|
154
|
+
if (res.reasoningContent)
|
|
155
|
+
options.onReasoningChunk?.(res.reasoningContent);
|
|
156
|
+
if (res.content)
|
|
157
|
+
options.onChunk?.(res.content);
|
|
158
|
+
}
|
|
159
|
+
return res;
|
|
122
160
|
}
|
|
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
161
|
}
|
|
132
|
-
|
|
133
|
-
|
|
162
|
+
finally {
|
|
163
|
+
cleanup();
|
|
134
164
|
}
|
|
135
165
|
}
|
|
136
166
|
/**
|
|
137
167
|
* Map HTTP error codes into user-friendly and security-preserving exceptions.
|
|
138
168
|
*/
|
|
139
|
-
handleHttpErrors(status, errorText) {
|
|
169
|
+
handleHttpErrors(status, errorText, retryAfterMs) {
|
|
140
170
|
if (status === 429) {
|
|
141
|
-
|
|
171
|
+
const retryNote = retryAfterMs !== undefined
|
|
172
|
+
? ` Retry after ${Math.ceil(retryAfterMs / 1000)}s.`
|
|
173
|
+
: '';
|
|
174
|
+
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
175
|
}
|
|
143
176
|
const lowered = (errorText || '').toLowerCase();
|
|
144
177
|
if (status === 400 || status === 404) {
|
|
@@ -148,16 +181,39 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
148
181
|
`Run "/openrouter allow" to permit free model routing, or inspect your preference with /openrouter status.`);
|
|
149
182
|
}
|
|
150
183
|
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.');
|
|
184
|
+
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
185
|
}
|
|
153
186
|
}
|
|
154
|
-
throw new
|
|
187
|
+
throw new ProviderHttpError(`OpenRouter API Error (${status}): ${errorText}`, { status, retryAfterMs });
|
|
155
188
|
}
|
|
156
189
|
/**
|
|
157
190
|
* Process a non-streaming JSON response from OpenRouter.
|
|
158
191
|
*/
|
|
159
|
-
async handleJsonResponse(response, freeFormPaths) {
|
|
160
|
-
|
|
192
|
+
async handleJsonResponse(response, freeFormPaths, apiKey) {
|
|
193
|
+
let data;
|
|
194
|
+
if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
|
|
195
|
+
data = await response.json();
|
|
196
|
+
}
|
|
197
|
+
else {
|
|
198
|
+
const rawText = await readBoundedResponseText(response, MAX_PROVIDER_JSON_BYTES, {
|
|
199
|
+
truncate: false,
|
|
200
|
+
label: 'OpenRouter'
|
|
201
|
+
});
|
|
202
|
+
const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
203
|
+
try {
|
|
204
|
+
data = JSON.parse(cleanText);
|
|
205
|
+
}
|
|
206
|
+
catch {
|
|
207
|
+
const preview = redactProviderSecrets(rawText.slice(0, 240), [apiKey]);
|
|
208
|
+
throw new Error(`OpenRouter returned a non-JSON response (HTTP ${response.status}): ${preview}`);
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
if (data && typeof data === 'object' && data.error && typeof data.error === 'object') {
|
|
212
|
+
const rawErr = typeof data.error.message === 'string' ? data.error.message : JSON.stringify(data.error);
|
|
213
|
+
const cleanErr = redactProviderSecrets(rawErr, [apiKey]);
|
|
214
|
+
const code = typeof data.error.code === 'number' ? data.error.code : 502;
|
|
215
|
+
this.handleHttpErrors(code, cleanErr);
|
|
216
|
+
}
|
|
161
217
|
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
162
218
|
prefix: 'call_openrouter',
|
|
163
219
|
...(freeFormPaths ? { freeFormPaths } : {})
|
|
@@ -173,83 +229,119 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
173
229
|
/**
|
|
174
230
|
* Process a streaming SSE response from OpenRouter.
|
|
175
231
|
*/
|
|
176
|
-
async handleStreamingResponse(response, options, freeFormPaths) {
|
|
232
|
+
async handleStreamingResponse(response, options, freeFormPaths, apiKey) {
|
|
177
233
|
const reader = response.body.getReader();
|
|
178
234
|
const decoder = new TextDecoder('utf-8');
|
|
179
235
|
let content = '';
|
|
180
236
|
let reasoningContent = '';
|
|
181
237
|
let buffer = '';
|
|
238
|
+
let totalBytes = 0;
|
|
182
239
|
const toolCallsMap = new Map();
|
|
183
240
|
let rawUsage = null;
|
|
241
|
+
const processLine = (line) => {
|
|
242
|
+
const stripped = line.charCodeAt(0) === 0xfeff ? line.slice(1) : line;
|
|
243
|
+
const trimmed = stripped.trim();
|
|
244
|
+
if (!trimmed || trimmed.startsWith(':'))
|
|
245
|
+
return; // Skip comments/keepalive
|
|
246
|
+
if (trimmed === 'data: [DONE]' || trimmed === 'data:[DONE]')
|
|
247
|
+
return;
|
|
248
|
+
if (trimmed.startsWith('data:')) {
|
|
249
|
+
const jsonStr = trimmed.slice(5).replace(/^ /, '');
|
|
250
|
+
let parsed;
|
|
251
|
+
try {
|
|
252
|
+
parsed = JSON.parse(jsonStr);
|
|
253
|
+
}
|
|
254
|
+
catch {
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
if (!parsed || typeof parsed !== 'object')
|
|
258
|
+
return;
|
|
259
|
+
if (parsed.error && typeof parsed.error === 'object') {
|
|
260
|
+
const rawErr = typeof parsed.error.message === 'string' ? parsed.error.message : JSON.stringify(parsed.error);
|
|
261
|
+
const cleanErr = redactProviderSecrets(rawErr, [apiKey]);
|
|
262
|
+
const code = typeof parsed.error.code === 'number' ? parsed.error.code : 502;
|
|
263
|
+
this.handleHttpErrors(code, cleanErr);
|
|
264
|
+
}
|
|
265
|
+
if (parsed.usage) {
|
|
266
|
+
rawUsage = parsed.usage;
|
|
267
|
+
}
|
|
268
|
+
const choice = parsed.choices?.[0];
|
|
269
|
+
if (!choice)
|
|
270
|
+
return;
|
|
271
|
+
const delta = choice.delta;
|
|
272
|
+
if (delta) {
|
|
273
|
+
// 1. Text chunk
|
|
274
|
+
if (delta.content) {
|
|
275
|
+
content += delta.content;
|
|
276
|
+
if (options.onChunk) {
|
|
277
|
+
options.onChunk(delta.content);
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
// 2. Reasoning chunk
|
|
281
|
+
const reasoning = delta.reasoning || delta.reasoning_content;
|
|
282
|
+
if (reasoning) {
|
|
283
|
+
reasoningContent += reasoning;
|
|
284
|
+
if (options.onReasoningChunk) {
|
|
285
|
+
options.onReasoningChunk(reasoning);
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
// 3. Tool calls assembly
|
|
289
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
290
|
+
for (const tc of delta.tool_calls) {
|
|
291
|
+
if (!tc || typeof tc !== 'object')
|
|
292
|
+
continue;
|
|
293
|
+
const idx = typeof tc.index === 'number' && Number.isInteger(tc.index) && tc.index >= 0
|
|
294
|
+
? tc.index
|
|
295
|
+
: Math.max(-1, ...toolCallsMap.keys()) + 1;
|
|
296
|
+
let existing = toolCallsMap.get(idx);
|
|
297
|
+
if (!existing) {
|
|
298
|
+
existing = { id: sanitizeProviderToolId(tc.id, 'call_openrouter', idx), name: '', arguments: '' };
|
|
299
|
+
toolCallsMap.set(idx, existing);
|
|
300
|
+
}
|
|
301
|
+
if (typeof tc.id === 'string' && tc.id)
|
|
302
|
+
existing.id = sanitizeProviderToolId(tc.id, 'call_openrouter', idx);
|
|
303
|
+
if (typeof tc.function?.name === 'string')
|
|
304
|
+
existing.name += tc.function.name;
|
|
305
|
+
if (typeof tc.function?.arguments === 'string')
|
|
306
|
+
existing.arguments += tc.function.arguments;
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
};
|
|
184
312
|
try {
|
|
185
313
|
while (true) {
|
|
186
314
|
if (options.signal?.aborted) {
|
|
187
315
|
await reader.cancel().catch(() => { });
|
|
188
|
-
|
|
316
|
+
const abortErr = new Error('OpenRouter request aborted');
|
|
317
|
+
abortErr.name = 'AbortError';
|
|
318
|
+
throw abortErr;
|
|
189
319
|
}
|
|
190
320
|
const { done, value } = await reader.read();
|
|
191
321
|
if (done)
|
|
192
322
|
break;
|
|
323
|
+
if (!value)
|
|
324
|
+
continue;
|
|
325
|
+
totalBytes += value.byteLength;
|
|
326
|
+
if (totalBytes > MAX_PROVIDER_JSON_BYTES) {
|
|
327
|
+
await reader.cancel().catch(() => { });
|
|
328
|
+
throw new Error(`OpenRouter stream exceeded maximum allowed size (${MAX_PROVIDER_JSON_BYTES} bytes).`);
|
|
329
|
+
}
|
|
193
330
|
buffer += decoder.decode(value, { stream: true });
|
|
331
|
+
if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
|
|
332
|
+
await reader.cancel().catch(() => { });
|
|
333
|
+
throw new Error(`OpenRouter SSE buffer exceeded maximum allowed size (${MAX_SSE_BUFFER_BYTES} bytes).`);
|
|
334
|
+
}
|
|
194
335
|
const lines = buffer.split('\n');
|
|
195
336
|
buffer = lines.pop() || '';
|
|
196
337
|
for (const line of lines) {
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
let parsed;
|
|
205
|
-
try {
|
|
206
|
-
parsed = JSON.parse(jsonStr);
|
|
207
|
-
}
|
|
208
|
-
catch {
|
|
209
|
-
continue;
|
|
210
|
-
}
|
|
211
|
-
if (parsed.usage) {
|
|
212
|
-
rawUsage = parsed.usage;
|
|
213
|
-
}
|
|
214
|
-
const choice = parsed.choices?.[0];
|
|
215
|
-
if (!choice)
|
|
216
|
-
continue;
|
|
217
|
-
const delta = choice.delta;
|
|
218
|
-
if (delta) {
|
|
219
|
-
// 1. Text chunk
|
|
220
|
-
if (delta.content) {
|
|
221
|
-
content += delta.content;
|
|
222
|
-
if (options.onChunk) {
|
|
223
|
-
options.onChunk(delta.content);
|
|
224
|
-
}
|
|
225
|
-
}
|
|
226
|
-
// 2. Reasoning chunk
|
|
227
|
-
const reasoning = delta.reasoning || delta.reasoning_content;
|
|
228
|
-
if (reasoning) {
|
|
229
|
-
reasoningContent += reasoning;
|
|
230
|
-
if (options.onReasoningChunk) {
|
|
231
|
-
options.onReasoningChunk(reasoning);
|
|
232
|
-
}
|
|
233
|
-
}
|
|
234
|
-
// 3. Tool calls assembly
|
|
235
|
-
if (Array.isArray(delta.tool_calls)) {
|
|
236
|
-
for (const tc of delta.tool_calls) {
|
|
237
|
-
const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
|
|
238
|
-
let existing = toolCallsMap.get(idx);
|
|
239
|
-
if (!existing) {
|
|
240
|
-
existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
|
|
241
|
-
toolCallsMap.set(idx, existing);
|
|
242
|
-
}
|
|
243
|
-
if (tc.id)
|
|
244
|
-
existing.id = tc.id;
|
|
245
|
-
if (tc.function?.name)
|
|
246
|
-
existing.name += tc.function.name;
|
|
247
|
-
if (tc.function?.arguments)
|
|
248
|
-
existing.arguments += tc.function.arguments;
|
|
249
|
-
}
|
|
250
|
-
}
|
|
251
|
-
}
|
|
252
|
-
}
|
|
338
|
+
processLine(line);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
buffer += decoder.decode();
|
|
342
|
+
if (buffer.trim()) {
|
|
343
|
+
for (const line of buffer.split('\n')) {
|
|
344
|
+
processLine(line);
|
|
253
345
|
}
|
|
254
346
|
}
|
|
255
347
|
}
|
|
@@ -257,11 +349,14 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
257
349
|
reader.releaseLock();
|
|
258
350
|
}
|
|
259
351
|
const toolCalls = [];
|
|
260
|
-
|
|
352
|
+
const sortedItems = [...toolCallsMap.entries()].sort((a, b) => a[0] - b[0]);
|
|
353
|
+
for (const [idx, item] of sortedItems) {
|
|
261
354
|
if (item.name) {
|
|
262
355
|
const cleanName = normalizeToolName(item.name);
|
|
356
|
+
if (!cleanName)
|
|
357
|
+
continue;
|
|
263
358
|
toolCalls.push({
|
|
264
|
-
id: item.id,
|
|
359
|
+
id: sanitizeProviderToolId(item.id, 'call_openrouter', idx),
|
|
265
360
|
type: 'function',
|
|
266
361
|
function: {
|
|
267
362
|
name: cleanName,
|
|
@@ -271,9 +366,10 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
271
366
|
}
|
|
272
367
|
}
|
|
273
368
|
if (toolCalls.length === 0 && content) {
|
|
274
|
-
const extracted = extractTextToolCalls(content, '
|
|
369
|
+
const extracted = extractTextToolCalls(content, 'call_openrouter_text', freeFormPaths);
|
|
275
370
|
if (extracted.length > 0) {
|
|
276
371
|
toolCalls.push(...extracted);
|
|
372
|
+
content = stripToolCallMarkup(content).trim();
|
|
277
373
|
}
|
|
278
374
|
}
|
|
279
375
|
const usage = this.normalizeUsage(rawUsage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
|