@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.
- package/package.json +1 -1
- package/src/agent/errorClassifier.js +113 -0
- package/src/agent/errorClassifier.ts +161 -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 +51 -351
- package/src/agentLoop.ts +69 -363
- package/src/autoUpdate.js +111 -8
- package/src/autoUpdate.ts +144 -8
- package/src/browser/causyneBrowser.js +231 -136
- package/src/browser/causyneBrowser.ts +229 -140
- package/src/browser/searchProviders.js +41 -30
- package/src/browser/searchProviders.ts +24 -14
- package/src/browser/workspacePathSafety.js +50 -0
- package/src/browser/workspacePathSafety.ts +50 -0
- package/src/browser/workspacePreview.js +27 -4
- package/src/browser/workspacePreview.ts +28 -4
- package/src/cliMode.js +17 -3
- package/src/commands.js +15 -22
- package/src/config.js +42 -63
- package/src/configVault.js +204 -0
- package/src/configVault.ts +213 -0
- package/src/core/contextCompactor.js +70 -11
- package/src/core/contextCompactor.ts +83 -11
- package/src/creative/liveBridge.js +34 -1
- package/src/creative/liveBridge.ts +28 -1
- package/src/dynamicCatalogue.js +42 -73
- package/src/dynamicCatalogue.ts +74 -60
- package/src/entrypoint.js +77 -4
- package/src/headlessCli.js +304 -0
- package/src/headlessCli.ts +380 -0
- 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/observer/evidence.js +23 -0
- package/src/observer/evidence.ts +21 -0
- package/src/osKeychain.js +209 -0
- package/src/osKeychain.ts +245 -0
- package/src/providers/anthropic.js +61 -28
- package/src/providers/base.js +14 -0
- package/src/providers/byokHttp.js +354 -0
- package/src/providers/byokHttp.ts +454 -0
- package/src/providers/byokStream.js +657 -0
- package/src/providers/byokStream.ts +759 -0
- package/src/providers/dashscope-byok.js +47 -32
- package/src/providers/deepseek.js +43 -39
- package/src/providers/gemini.js +73 -38
- package/src/providers/moonshot.js +43 -33
- package/src/providers/muse.js +10 -10
- package/src/providers/ollama.js +46 -31
- package/src/providers/openai-compatible.js +57 -32
- package/src/providers/openrouter.js +77 -113
- package/src/providers/openrouter.ts +99 -118
- package/src/providers/qwen-byok.js +46 -23
- package/src/providers/toolContracts.js +9 -3
- package/src/providers/toolContracts.ts +9 -3
- package/src/providers/wireNormalizer.js +238 -0
- package/src/providers/wireNormalizer.ts +279 -0
- package/src/providers/xai.js +43 -33
- package/src/sandbox.js +77 -56
- package/src/sandboxPolicy.js +1208 -0
- package/src/sandboxPolicy.ts +1300 -0
- package/src/sessionJournal.js +47 -0
- package/src/sessionJournal.ts +49 -0
- package/src/tools/browserAutomator.js +13 -1
- package/src/tools/browserAutomator.ts +13 -0
- package/src/tools/creativeApps.js +2 -1
- package/src/tools/creativeApps.ts +2 -1
- package/src/tools/gameAssetFetcher.js +130 -26
- package/src/tools/gameAssetHarvester.js +80 -58
- package/src/tools/nativeEngine.js +1 -1
- package/src/tools/nativeEngine.ts +1 -1
- package/src/tools/osSandbox.js +473 -0
- package/src/tools/osSandbox.ts +554 -0
- package/src/tools/persistentShell.js +8 -3
- package/src/tools/registry.js +13 -0
- package/src/tools/subprocessEnv.js +197 -0
- package/src/tools/subprocessEnv.ts +212 -0
- package/src/tools/sysRun.js +39 -6
- package/src/tools/sysRun.ts +53 -7
- package/src/tools/toolScanner.js +596 -140
- package/src/tools/toolScanner.ts +665 -147
- package/src/tools/toolSelfRepair.js +243 -114
- package/src/tools/toolSelfRepair.ts +262 -111
- package/src/tools/webFetch.js +161 -24
- package/src/tools/webFetch.ts +157 -22
- package/src/tools/webSearch.js +33 -4
- package/src/tools/webSearch.ts +27 -4
- package/src/tui/sessionPicker.js +132 -35
- package/src/tui/sessionPicker.ts +153 -32
- package/src/tui/sessionPickerView.js +277 -34
- package/src/tui/sessionPickerView.ts +328 -34
- package/src/tui/statusLine.js +3 -0
- package/src/tui/statusLine.ts +5 -0
- package/src/tui/workspaceIdentity.js +133 -0
- package/src/tui/workspaceIdentity.ts +146 -0
package/src/providers/ollama.js
CHANGED
|
@@ -2,11 +2,20 @@ 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 {
|
|
6
|
+
normalizeMessagesForOllama,
|
|
7
|
+
normalizeOpenAIToolCalls,
|
|
8
|
+
extractTextToolCalls
|
|
9
|
+
} from './wireNormalizer.js';
|
|
10
|
+
import { stripToolCallMarkup } from '../implementationPlan.js';
|
|
11
|
+
import { resolveTemperature, safeProviderFetchJson } from './byokHttp.js';
|
|
12
|
+
import { streamOllamaChat, wantsStreaming } from './byokStream.js';
|
|
5
13
|
|
|
6
14
|
export class OllamaProvider extends LLMProvider {
|
|
7
15
|
constructor(config) {
|
|
8
16
|
super(config);
|
|
9
17
|
this.baseUrl = config.baseUrl || 'http://localhost:11434/api/chat';
|
|
18
|
+
this.allowInsecureHttp = config.allowInsecureHttp === true;
|
|
10
19
|
this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['ollama']);
|
|
11
20
|
// Locally installable vision models. Anything else stays text-only, and a
|
|
12
21
|
// user on an unlisted build can set config.supportsVision explicitly.
|
|
@@ -42,58 +51,64 @@ export class OllamaProvider extends LLMProvider {
|
|
|
42
51
|
}
|
|
43
52
|
|
|
44
53
|
async chat(messages, options = {}) {
|
|
45
|
-
const sanitizedMessages = this.prepareMessages(messages);
|
|
54
|
+
const sanitizedMessages = normalizeMessagesForOllama(this.prepareMessages(messages));
|
|
46
55
|
|
|
47
56
|
const payload = {
|
|
48
57
|
model: this.model,
|
|
49
58
|
messages: sanitizedMessages,
|
|
50
59
|
stream: false,
|
|
51
60
|
options: {
|
|
52
|
-
temperature: options.temperature
|
|
61
|
+
temperature: resolveTemperature(options.temperature, 0.1)
|
|
53
62
|
}
|
|
54
63
|
};
|
|
55
64
|
|
|
56
|
-
|
|
65
|
+
let freeFormPaths = new Map();
|
|
66
|
+
if (options.tools && options.tools.length > 0) {
|
|
57
67
|
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'ollama');
|
|
58
68
|
payload.tools = scanReport.adaptedTools;
|
|
69
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
59
70
|
}
|
|
60
71
|
|
|
61
|
-
const
|
|
72
|
+
const requestOpts = {
|
|
73
|
+
url: this.baseUrl,
|
|
62
74
|
method: 'POST',
|
|
63
75
|
headers: { 'Content-Type': 'application/json' },
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
76
|
+
signal: options.signal,
|
|
77
|
+
timeoutMs: options.timeoutMs,
|
|
78
|
+
providerLabel: 'Ollama',
|
|
79
|
+
hasApiKey: false,
|
|
80
|
+
allowInsecureHttp: this.allowInsecureHttp
|
|
81
|
+
};
|
|
71
82
|
|
|
72
|
-
const data =
|
|
83
|
+
const data = wantsStreaming(options)
|
|
84
|
+
? await streamOllamaChat({
|
|
85
|
+
...requestOpts,
|
|
86
|
+
payload,
|
|
87
|
+
onChunk: options.onChunk,
|
|
88
|
+
onReasoningChunk: options.onReasoningChunk
|
|
89
|
+
})
|
|
90
|
+
: await safeProviderFetchJson({
|
|
91
|
+
...requestOpts,
|
|
92
|
+
body: JSON.stringify(payload)
|
|
93
|
+
});
|
|
73
94
|
|
|
74
|
-
// Ollama returns tool calls with no id
|
|
75
|
-
//
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
function: {
|
|
85
|
-
name: call.function?.name,
|
|
86
|
-
// Ollama hands back a parsed object where the OpenAI shape carries a
|
|
87
|
-
// JSON string. Normalise so the whole pipeline sees one contract.
|
|
88
|
-
arguments: typeof call.function?.arguments === 'string'
|
|
89
|
-
? call.function.arguments
|
|
90
|
-
: JSON.stringify(call.function?.arguments || {})
|
|
95
|
+
// Ollama returns tool calls with no id and object arguments instead of JSON strings.
|
|
96
|
+
// Normalize through wireNormalizer so sanitizeSequences and toolSelfRepair see one contract.
|
|
97
|
+
let content = typeof data.message?.content === 'string' ? data.message.content : '';
|
|
98
|
+
const reasoningContent = typeof data.message?.thinking === 'string' ? data.message.thinking.trim() : '';
|
|
99
|
+
let toolCalls = normalizeOpenAIToolCalls(data.message?.tool_calls, freeFormPaths, 'call_ollama');
|
|
100
|
+
if (toolCalls.length === 0 && content) {
|
|
101
|
+
const extracted = extractTextToolCalls(content, 'call_ollama_text', freeFormPaths);
|
|
102
|
+
if (extracted.length > 0) {
|
|
103
|
+
toolCalls = extracted;
|
|
104
|
+
content = stripToolCallMarkup(content).trim();
|
|
91
105
|
}
|
|
92
|
-
}
|
|
106
|
+
}
|
|
93
107
|
|
|
94
108
|
return {
|
|
95
|
-
content
|
|
109
|
+
content,
|
|
96
110
|
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
111
|
+
...(reasoningContent ? { reasoningContent } : {}),
|
|
97
112
|
usage: {
|
|
98
113
|
promptTokens: data.prompt_eval_count || 0,
|
|
99
114
|
completionTokens: data.eval_count || 0
|
|
@@ -2,6 +2,14 @@ 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
|
+
isLoopbackHost,
|
|
8
|
+
requireApiKey,
|
|
9
|
+
resolveTemperature,
|
|
10
|
+
safeProviderFetchJson
|
|
11
|
+
} from './byokHttp.js';
|
|
12
|
+
import { streamOpenAICompatibleChat, wantsStreaming } from './byokStream.js';
|
|
5
13
|
|
|
6
14
|
export class OpenAICompatibleProvider extends LLMProvider {
|
|
7
15
|
constructor(config) {
|
|
@@ -14,6 +22,7 @@ export class OpenAICompatibleProvider extends LLMProvider {
|
|
|
14
22
|
// 'low' | 'medium' | 'high' | 'off'. Unset means: do not send the parameter.
|
|
15
23
|
this.reasoningEffort = config.reasoningEffort || null;
|
|
16
24
|
this.baseUrl = config.baseUrl || 'https://api.openai.com/v1/chat/completions';
|
|
25
|
+
this.allowInsecureHttp = config.allowInsecureHttp === true;
|
|
17
26
|
this.model = canonicalModelId(config.model || DEFAULT_MODEL_BY_PROVIDER['openai']);
|
|
18
27
|
}
|
|
19
28
|
|
|
@@ -22,7 +31,7 @@ export class OpenAICompatibleProvider extends LLMProvider {
|
|
|
22
31
|
const payload = {
|
|
23
32
|
model: this.model,
|
|
24
33
|
messages: preparedMessages,
|
|
25
|
-
temperature: options.temperature
|
|
34
|
+
temperature: resolveTemperature(options.temperature, 0.1),
|
|
26
35
|
};
|
|
27
36
|
|
|
28
37
|
// Reasoning models take an effort dial. Sending it to a model that does not
|
|
@@ -37,47 +46,63 @@ export class OpenAICompatibleProvider extends LLMProvider {
|
|
|
37
46
|
payload.response_format = { type: 'json_object' };
|
|
38
47
|
}
|
|
39
48
|
|
|
40
|
-
|
|
49
|
+
let freeFormPaths = new Map();
|
|
50
|
+
if (options.tools && options.tools.length > 0) {
|
|
41
51
|
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
|
|
42
52
|
payload.tools = scanReport.adaptedTools;
|
|
43
53
|
payload.tool_choice = "auto";
|
|
54
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
44
55
|
}
|
|
45
56
|
|
|
46
|
-
const
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
57
|
+
const headers = {
|
|
58
|
+
'Content-Type': 'application/json'
|
|
59
|
+
};
|
|
60
|
+
const trimmedKey = typeof this.apiKey === 'string' ? this.apiKey.trim() : '';
|
|
61
|
+
let isLocalEndpoint = false;
|
|
62
|
+
try {
|
|
63
|
+
isLocalEndpoint = isLoopbackHost(new URL(this.baseUrl).hostname);
|
|
64
|
+
} catch {
|
|
65
|
+
isLocalEndpoint = false;
|
|
66
|
+
}
|
|
67
|
+
if (trimmedKey) {
|
|
68
|
+
headers['Authorization'] = `Bearer ${trimmedKey}`;
|
|
69
|
+
} else if (!isLocalEndpoint) {
|
|
70
|
+
requireApiKey(this.apiKey, 'OpenAI-Compatible');
|
|
58
71
|
}
|
|
59
72
|
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
73
|
+
const requestOpts = {
|
|
74
|
+
url: this.baseUrl,
|
|
75
|
+
method: 'POST',
|
|
76
|
+
headers,
|
|
77
|
+
signal: options.signal,
|
|
78
|
+
timeoutMs: options.timeoutMs,
|
|
79
|
+
providerLabel: 'OpenAI-Compatible',
|
|
80
|
+
secrets: trimmedKey ? [trimmedKey] : [],
|
|
81
|
+
hasApiKey: Boolean(trimmedKey),
|
|
82
|
+
allowInsecureHttp: this.allowInsecureHttp
|
|
83
|
+
};
|
|
65
84
|
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
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_oai',
|
|
98
|
+
freeFormPaths
|
|
99
|
+
});
|
|
75
100
|
|
|
76
101
|
return {
|
|
77
|
-
content: content,
|
|
78
|
-
toolCalls:
|
|
79
|
-
reasoningContent: reasoningContent
|
|
80
|
-
usage: this.normalizeUsage(
|
|
102
|
+
content: normalized.content,
|
|
103
|
+
toolCalls: normalized.toolCalls,
|
|
104
|
+
reasoningContent: normalized.reasoningContent,
|
|
105
|
+
usage: this.normalizeUsage(normalized.rawUsage)
|
|
81
106
|
};
|
|
82
107
|
}
|
|
83
108
|
}
|
|
@@ -9,7 +9,9 @@
|
|
|
9
9
|
import { LLMProvider } from './base.js';
|
|
10
10
|
import { canonicalModelId } from '../modelIds.js';
|
|
11
11
|
import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
|
|
12
|
-
import {
|
|
12
|
+
import { extractTextToolCalls, normalizeOpenAIChatChoiceResponse, serializeAndDecodeArguments } from './wireNormalizer.js';
|
|
13
|
+
import { MAX_PROVIDER_ERROR_BYTES, MAX_PROVIDER_JSON_BYTES, MAX_SSE_BUFFER_BYTES, parseRetryAfterMs, readBoundedResponseText, redactProviderSecrets, resolveTemperature, safeProviderFetch } from './byokHttp.js';
|
|
14
|
+
import { normalizeToolName } from '../tools/toolScanner.js';
|
|
13
15
|
export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
|
|
14
16
|
export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
|
|
15
17
|
export const OPENROUTER_DEFAULT_FREE_MODEL = 'openrouter/free';
|
|
@@ -20,9 +22,12 @@ export class FreeModeCostGuardError extends Error {
|
|
|
20
22
|
}
|
|
21
23
|
}
|
|
22
24
|
export class OpenRouterRateLimitError extends Error {
|
|
23
|
-
|
|
25
|
+
status = 429;
|
|
26
|
+
retryAfterMs;
|
|
27
|
+
constructor(message, retryAfterMs) {
|
|
24
28
|
super(message);
|
|
25
29
|
this.name = 'OpenRouterRateLimitError';
|
|
30
|
+
this.retryAfterMs = retryAfterMs;
|
|
26
31
|
}
|
|
27
32
|
}
|
|
28
33
|
export class OpenRouterPrivacyConstraintError extends Error {
|
|
@@ -34,9 +39,11 @@ export class OpenRouterPrivacyConstraintError extends Error {
|
|
|
34
39
|
export class OpenRouterProvider extends LLMProvider {
|
|
35
40
|
dataCollection;
|
|
36
41
|
freeOnly;
|
|
42
|
+
allowInsecureHttp;
|
|
37
43
|
constructor(config = {}) {
|
|
38
44
|
super(config);
|
|
39
45
|
this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
|
|
46
|
+
this.allowInsecureHttp = config['allowInsecureHttp'] === true;
|
|
40
47
|
this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
|
|
41
48
|
this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
|
|
42
49
|
this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
|
|
@@ -80,7 +87,7 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
80
87
|
const payload = {
|
|
81
88
|
model: this.model,
|
|
82
89
|
messages: preparedMessages,
|
|
83
|
-
temperature: options.temperature
|
|
90
|
+
temperature: resolveTemperature(options.temperature, 0.1),
|
|
84
91
|
stream: shouldStream,
|
|
85
92
|
provider: {
|
|
86
93
|
data_collection: this.dataCollection
|
|
@@ -89,10 +96,12 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
89
96
|
if (options['jsonMode']) {
|
|
90
97
|
payload['response_format'] = { type: 'json_object' };
|
|
91
98
|
}
|
|
99
|
+
let freeFormPaths = new Map();
|
|
92
100
|
if (options.tools && Array.isArray(options.tools) && options.tools.length > 0) {
|
|
93
101
|
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
|
|
94
102
|
payload['tools'] = scanReport.adaptedTools;
|
|
95
103
|
payload['tool_choice'] = 'auto';
|
|
104
|
+
freeFormPaths = scanReport.freeFormPaths;
|
|
96
105
|
}
|
|
97
106
|
const headers = {
|
|
98
107
|
'Content-Type': 'application/json',
|
|
@@ -100,42 +109,50 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
100
109
|
'HTTP-Referer': 'https://causyne.com',
|
|
101
110
|
'X-Title': 'Causyne Agent'
|
|
102
111
|
};
|
|
103
|
-
let response;
|
|
104
112
|
const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
|
|
105
|
-
const
|
|
113
|
+
const { response, cleanup } = await safeProviderFetch({
|
|
114
|
+
url: endpoint,
|
|
106
115
|
method: 'POST',
|
|
107
116
|
headers,
|
|
108
|
-
body: JSON.stringify(payload)
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
117
|
+
body: JSON.stringify(payload),
|
|
118
|
+
signal: options.signal,
|
|
119
|
+
timeoutMs: typeof options['timeoutMs'] === 'number' ? options['timeoutMs'] : undefined,
|
|
120
|
+
providerLabel: 'OpenRouter',
|
|
121
|
+
secrets: [apiKey],
|
|
122
|
+
hasApiKey: true,
|
|
123
|
+
allowInsecureHttp: this.allowInsecureHttp
|
|
124
|
+
});
|
|
113
125
|
try {
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
126
|
+
if (!response.ok) {
|
|
127
|
+
const rawError = await readBoundedResponseText(response, MAX_PROVIDER_ERROR_BYTES, {
|
|
128
|
+
truncate: true,
|
|
129
|
+
label: 'OpenRouter'
|
|
130
|
+
}).catch(() => '');
|
|
131
|
+
const cleanError = redactProviderSecrets(rawError, [apiKey]);
|
|
132
|
+
const retryAfterHeader = response.headers?.get?.('retry-after');
|
|
133
|
+
const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
|
|
134
|
+
this.handleHttpErrors(response.status, cleanError, retryAfterMs);
|
|
135
|
+
}
|
|
136
|
+
if (shouldStream && response.body) {
|
|
137
|
+
return await this.handleStreamingResponse(response, options, freeFormPaths);
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
return await this.handleJsonResponse(response, freeFormPaths, apiKey);
|
|
119
141
|
}
|
|
120
|
-
throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
|
|
121
|
-
}
|
|
122
|
-
if (!response.ok) {
|
|
123
|
-
const errorText = await response.text().catch(() => '');
|
|
124
|
-
this.handleHttpErrors(response.status, errorText);
|
|
125
|
-
}
|
|
126
|
-
if (shouldStream && response.body) {
|
|
127
|
-
return this.handleStreamingResponse(response, options);
|
|
128
142
|
}
|
|
129
|
-
|
|
130
|
-
|
|
143
|
+
finally {
|
|
144
|
+
cleanup();
|
|
131
145
|
}
|
|
132
146
|
}
|
|
133
147
|
/**
|
|
134
148
|
* Map HTTP error codes into user-friendly and security-preserving exceptions.
|
|
135
149
|
*/
|
|
136
|
-
handleHttpErrors(status, errorText) {
|
|
150
|
+
handleHttpErrors(status, errorText, retryAfterMs) {
|
|
137
151
|
if (status === 429) {
|
|
138
|
-
|
|
152
|
+
const retryNote = retryAfterMs !== undefined
|
|
153
|
+
? ` Retry after ${Math.ceil(retryAfterMs / 1000)}s.`
|
|
154
|
+
: '';
|
|
155
|
+
throw new OpenRouterRateLimitError(`OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.${retryNote}`, retryAfterMs);
|
|
139
156
|
}
|
|
140
157
|
const lowered = (errorText || '').toLowerCase();
|
|
141
158
|
if (status === 400 || status === 404) {
|
|
@@ -145,7 +162,7 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
145
162
|
`Run "/openrouter allow" to permit free model routing, or inspect your preference with /openrouter status.`);
|
|
146
163
|
}
|
|
147
164
|
if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
|
|
148
|
-
throw new OpenRouterRateLimitError('OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.');
|
|
165
|
+
throw new OpenRouterRateLimitError('OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.', retryAfterMs);
|
|
149
166
|
}
|
|
150
167
|
}
|
|
151
168
|
throw new Error(`OpenRouter API Error (${status}): ${errorText}`);
|
|
@@ -153,36 +170,40 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
153
170
|
/**
|
|
154
171
|
* Process a non-streaming JSON response from OpenRouter.
|
|
155
172
|
*/
|
|
156
|
-
async handleJsonResponse(response) {
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
let reasoningContent = '';
|
|
161
|
-
if (data.choices && Array.isArray(data.choices) && data.choices[0]?.message) {
|
|
162
|
-
const message = data.choices[0].message;
|
|
163
|
-
content = message.content || '';
|
|
164
|
-
toolCalls = this.normalizeToolCalls(message.tool_calls);
|
|
165
|
-
reasoningContent = message.reasoning || message.reasoning_content || '';
|
|
173
|
+
async handleJsonResponse(response, freeFormPaths, apiKey) {
|
|
174
|
+
let data;
|
|
175
|
+
if (!response.body && typeof response.text !== 'function' && typeof response.json === 'function') {
|
|
176
|
+
data = await response.json();
|
|
166
177
|
}
|
|
167
|
-
|
|
168
|
-
const
|
|
169
|
-
|
|
170
|
-
|
|
178
|
+
else {
|
|
179
|
+
const rawText = await readBoundedResponseText(response, MAX_PROVIDER_JSON_BYTES, {
|
|
180
|
+
truncate: false,
|
|
181
|
+
label: 'OpenRouter'
|
|
182
|
+
});
|
|
183
|
+
try {
|
|
184
|
+
data = JSON.parse(rawText);
|
|
185
|
+
}
|
|
186
|
+
catch {
|
|
187
|
+
const preview = redactProviderSecrets(rawText.slice(0, 240), [apiKey]);
|
|
188
|
+
throw new Error(`OpenRouter returned a non-JSON response (HTTP ${response.status}): ${preview}`);
|
|
171
189
|
}
|
|
172
190
|
}
|
|
173
|
-
const
|
|
174
|
-
|
|
191
|
+
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
192
|
+
prefix: 'call_openrouter',
|
|
193
|
+
...(freeFormPaths ? { freeFormPaths } : {})
|
|
194
|
+
});
|
|
195
|
+
const usage = this.normalizeUsage(normalized.rawUsage);
|
|
175
196
|
return {
|
|
176
|
-
content,
|
|
177
|
-
toolCalls:
|
|
178
|
-
reasoningContent: reasoningContent
|
|
197
|
+
content: normalized.content,
|
|
198
|
+
toolCalls: normalized.toolCalls,
|
|
199
|
+
reasoningContent: normalized.reasoningContent,
|
|
179
200
|
usage
|
|
180
201
|
};
|
|
181
202
|
}
|
|
182
203
|
/**
|
|
183
204
|
* Process a streaming SSE response from OpenRouter.
|
|
184
205
|
*/
|
|
185
|
-
async handleStreamingResponse(response, options) {
|
|
206
|
+
async handleStreamingResponse(response, options, freeFormPaths) {
|
|
186
207
|
const reader = response.body.getReader();
|
|
187
208
|
const decoder = new TextDecoder('utf-8');
|
|
188
209
|
let content = '';
|
|
@@ -200,6 +221,10 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
200
221
|
if (done)
|
|
201
222
|
break;
|
|
202
223
|
buffer += decoder.decode(value, { stream: true });
|
|
224
|
+
if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
|
|
225
|
+
await reader.cancel().catch(() => { });
|
|
226
|
+
throw new Error(`OpenRouter SSE buffer exceeded maximum allowed size (${MAX_SSE_BUFFER_BYTES} bytes).`);
|
|
227
|
+
}
|
|
203
228
|
const lines = buffer.split('\n');
|
|
204
229
|
buffer = lines.pop() || '';
|
|
205
230
|
for (const line of lines) {
|
|
@@ -268,18 +293,19 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
268
293
|
const toolCalls = [];
|
|
269
294
|
for (const item of toolCallsMap.values()) {
|
|
270
295
|
if (item.name) {
|
|
296
|
+
const cleanName = normalizeToolName(item.name);
|
|
271
297
|
toolCalls.push({
|
|
272
298
|
id: item.id,
|
|
273
299
|
type: 'function',
|
|
274
300
|
function: {
|
|
275
|
-
name:
|
|
276
|
-
arguments: item.arguments || '{}'
|
|
301
|
+
name: cleanName,
|
|
302
|
+
arguments: serializeAndDecodeArguments(item.arguments || '{}', cleanName, freeFormPaths)
|
|
277
303
|
}
|
|
278
304
|
});
|
|
279
305
|
}
|
|
280
306
|
}
|
|
281
307
|
if (toolCalls.length === 0 && content) {
|
|
282
|
-
const extracted =
|
|
308
|
+
const extracted = extractTextToolCalls(content, 'call_text', freeFormPaths);
|
|
283
309
|
if (extracted.length > 0) {
|
|
284
310
|
toolCalls.push(...extracted);
|
|
285
311
|
}
|
|
@@ -292,66 +318,4 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
292
318
|
usage
|
|
293
319
|
};
|
|
294
320
|
}
|
|
295
|
-
/**
|
|
296
|
-
* Extract tool calls embedded in content text (e.g. <tool_call> envelopes).
|
|
297
|
-
*/
|
|
298
|
-
extractToolCallsFromContent(text) {
|
|
299
|
-
const calls = [];
|
|
300
|
-
if (!text || typeof text !== 'string')
|
|
301
|
-
return calls;
|
|
302
|
-
let index = 0;
|
|
303
|
-
for (const parsed of extractToolCallJsonObjects(text)) {
|
|
304
|
-
const fnObj = parsed.function && typeof parsed.function === 'object'
|
|
305
|
-
? parsed.function
|
|
306
|
-
: null;
|
|
307
|
-
const name = String(parsed.name || parsed.tool || fnObj?.name || '').trim();
|
|
308
|
-
if (!name)
|
|
309
|
-
continue;
|
|
310
|
-
const rawArgs = resolveToolCallEnvelopeArguments(parsed);
|
|
311
|
-
calls.push({
|
|
312
|
-
id: `call_text_${Date.now()}_${index++}`,
|
|
313
|
-
type: 'function',
|
|
314
|
-
function: {
|
|
315
|
-
name,
|
|
316
|
-
arguments: typeof rawArgs === 'string' ? rawArgs : JSON.stringify(rawArgs || {})
|
|
317
|
-
}
|
|
318
|
-
});
|
|
319
|
-
}
|
|
320
|
-
return calls;
|
|
321
|
-
}
|
|
322
|
-
/**
|
|
323
|
-
* Safely normalize tool calls from provider message.
|
|
324
|
-
*/
|
|
325
|
-
normalizeToolCalls(rawCalls) {
|
|
326
|
-
if (!Array.isArray(rawCalls))
|
|
327
|
-
return [];
|
|
328
|
-
const normalized = [];
|
|
329
|
-
for (let i = 0; i < rawCalls.length; i++) {
|
|
330
|
-
const tc = rawCalls[i];
|
|
331
|
-
if (!tc || typeof tc !== 'object')
|
|
332
|
-
continue;
|
|
333
|
-
const id = typeof tc.id === 'string' && tc.id ? tc.id : `call_${i}_${Date.now()}`;
|
|
334
|
-
const name = tc.function?.name || tc.name || '';
|
|
335
|
-
if (!name || typeof name !== 'string')
|
|
336
|
-
continue;
|
|
337
|
-
let args = tc.function?.arguments;
|
|
338
|
-
if (typeof args !== 'string') {
|
|
339
|
-
try {
|
|
340
|
-
args = JSON.stringify(args || {});
|
|
341
|
-
}
|
|
342
|
-
catch {
|
|
343
|
-
args = '{}';
|
|
344
|
-
}
|
|
345
|
-
}
|
|
346
|
-
normalized.push({
|
|
347
|
-
id,
|
|
348
|
-
type: 'function',
|
|
349
|
-
function: {
|
|
350
|
-
name,
|
|
351
|
-
arguments: args
|
|
352
|
-
}
|
|
353
|
-
});
|
|
354
|
-
}
|
|
355
|
-
return normalized;
|
|
356
|
-
}
|
|
357
321
|
}
|