@causyne/agent 1.20.121 → 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 +6 -2
- package/src/agent/errorClassifier.ts +6 -2
- package/src/agentLoop.js +11 -5
- package/src/agentLoop.ts +11 -5
- 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 +5 -2
- package/src/autoUpdate.ts +5 -2
- 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/config.js +287 -250
- package/src/config.ts +342 -0
- package/src/configVault.js +84 -17
- package/src/configVault.ts +77 -17
- 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/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/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/headlessCli.js +2 -1
- package/src/headlessCli.ts +2 -1
- 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/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 +62 -8
- package/src/osKeychain.ts +50 -8
- 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 +327 -401
- 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 +58 -15
- package/src/providers/byokHttp.ts +59 -16
- package/src/providers/byokStream.js +142 -51
- package/src/providers/byokStream.ts +146 -42
- package/src/providers/dashscope-byok.js +97 -89
- package/src/providers/dashscope-byok.ts +114 -0
- package/src/providers/deepseek.js +73 -72
- 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 +227 -278
- 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 +70 -72
- 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 +114 -106
- package/src/providers/ollama.ts +135 -0
- package/src/providers/openai-compatible.js +113 -96
- 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 +136 -74
- package/src/providers/openrouter.ts +133 -72
- package/src/providers/pi.js +6 -0
- package/src/providers/pi.ts +6 -0
- package/src/providers/qwen-byok.js +96 -87
- 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 +73 -72
- 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 +489 -554
- package/src/sandbox.ts +552 -0
- package/src/sandboxPolicy.js +95 -16
- package/src/sandboxPolicy.ts +97 -16
- package/src/sessionJournal.js +8 -3
- package/src/sessionJournal.ts +9 -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 +54 -14
- package/src/tools/osSandbox.ts +48 -14
- 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/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/sysRun.js +69 -29
- package/src/tools/sysRun.ts +66 -24
- 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,10 +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 {
|
|
14
|
-
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';
|
|
15
16
|
export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
|
|
16
17
|
export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
|
|
17
18
|
export const OPENROUTER_DEFAULT_FREE_MODEL = 'openrouter/free';
|
|
@@ -57,10 +58,14 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
57
58
|
*/
|
|
58
59
|
isFreeModel(modelId) {
|
|
59
60
|
const clean = (modelId || '').trim().toLowerCase();
|
|
61
|
+
if (!clean || /[\s?#\x00-\x1f]/.test(clean))
|
|
62
|
+
return false;
|
|
60
63
|
if (clean === 'openrouter/free' || clean === 'free')
|
|
61
64
|
return true;
|
|
62
|
-
if (clean.endsWith(':free'))
|
|
63
|
-
|
|
65
|
+
if (clean.endsWith(':free')) {
|
|
66
|
+
const slug = clean.slice(0, -5);
|
|
67
|
+
return slug.length > 0 && !slug.startsWith('/') && !slug.endsWith('/');
|
|
68
|
+
}
|
|
64
69
|
return false;
|
|
65
70
|
}
|
|
66
71
|
/**
|
|
@@ -78,21 +83,25 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
78
83
|
if (this.freeOnly) {
|
|
79
84
|
this.assertFreeModel(this.model);
|
|
80
85
|
}
|
|
81
|
-
const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
|
|
86
|
+
const apiKey = String(this.apiKey || process.env.OPENROUTER_API_KEY || '').trim();
|
|
82
87
|
if (!apiKey) {
|
|
83
88
|
throw new Error('OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.');
|
|
84
89
|
}
|
|
85
90
|
const preparedMessages = this.prepareMessages(messages);
|
|
86
|
-
const shouldStream =
|
|
91
|
+
const shouldStream = wantsStreaming(options);
|
|
87
92
|
const payload = {
|
|
88
93
|
model: this.model,
|
|
89
94
|
messages: preparedMessages,
|
|
90
95
|
temperature: resolveTemperature(options.temperature, 0.1),
|
|
91
96
|
stream: shouldStream,
|
|
97
|
+
...(shouldStream ? { stream_options: { include_usage: true } } : {}),
|
|
92
98
|
provider: {
|
|
93
99
|
data_collection: this.dataCollection
|
|
94
100
|
}
|
|
95
101
|
};
|
|
102
|
+
if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
|
|
103
|
+
payload['max_tokens'] = Math.floor(options.maxTokens);
|
|
104
|
+
}
|
|
96
105
|
if (options['jsonMode']) {
|
|
97
106
|
payload['response_format'] = { type: 'json_object' };
|
|
98
107
|
}
|
|
@@ -133,11 +142,21 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
133
142
|
const retryAfterMs = parseRetryAfterMs(retryAfterHeader);
|
|
134
143
|
this.handleHttpErrors(response.status, cleanError, retryAfterMs);
|
|
135
144
|
}
|
|
136
|
-
|
|
137
|
-
|
|
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);
|
|
138
150
|
}
|
|
139
151
|
else {
|
|
140
|
-
|
|
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;
|
|
141
160
|
}
|
|
142
161
|
}
|
|
143
162
|
finally {
|
|
@@ -165,7 +184,7 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
165
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);
|
|
166
185
|
}
|
|
167
186
|
}
|
|
168
|
-
throw new
|
|
187
|
+
throw new ProviderHttpError(`OpenRouter API Error (${status}): ${errorText}`, { status, retryAfterMs });
|
|
169
188
|
}
|
|
170
189
|
/**
|
|
171
190
|
* Process a non-streaming JSON response from OpenRouter.
|
|
@@ -180,14 +199,21 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
180
199
|
truncate: false,
|
|
181
200
|
label: 'OpenRouter'
|
|
182
201
|
});
|
|
202
|
+
const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
183
203
|
try {
|
|
184
|
-
data = JSON.parse(
|
|
204
|
+
data = JSON.parse(cleanText);
|
|
185
205
|
}
|
|
186
206
|
catch {
|
|
187
207
|
const preview = redactProviderSecrets(rawText.slice(0, 240), [apiKey]);
|
|
188
208
|
throw new Error(`OpenRouter returned a non-JSON response (HTTP ${response.status}): ${preview}`);
|
|
189
209
|
}
|
|
190
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
|
+
}
|
|
191
217
|
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
192
218
|
prefix: 'call_openrouter',
|
|
193
219
|
...(freeFormPaths ? { freeFormPaths } : {})
|
|
@@ -203,23 +229,104 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
203
229
|
/**
|
|
204
230
|
* Process a streaming SSE response from OpenRouter.
|
|
205
231
|
*/
|
|
206
|
-
async handleStreamingResponse(response, options, freeFormPaths) {
|
|
232
|
+
async handleStreamingResponse(response, options, freeFormPaths, apiKey) {
|
|
207
233
|
const reader = response.body.getReader();
|
|
208
234
|
const decoder = new TextDecoder('utf-8');
|
|
209
235
|
let content = '';
|
|
210
236
|
let reasoningContent = '';
|
|
211
237
|
let buffer = '';
|
|
238
|
+
let totalBytes = 0;
|
|
212
239
|
const toolCallsMap = new Map();
|
|
213
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
|
+
};
|
|
214
312
|
try {
|
|
215
313
|
while (true) {
|
|
216
314
|
if (options.signal?.aborted) {
|
|
217
315
|
await reader.cancel().catch(() => { });
|
|
218
|
-
|
|
316
|
+
const abortErr = new Error('OpenRouter request aborted');
|
|
317
|
+
abortErr.name = 'AbortError';
|
|
318
|
+
throw abortErr;
|
|
219
319
|
}
|
|
220
320
|
const { done, value } = await reader.read();
|
|
221
321
|
if (done)
|
|
222
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
|
+
}
|
|
223
330
|
buffer += decoder.decode(value, { stream: true });
|
|
224
331
|
if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
|
|
225
332
|
await reader.cancel().catch(() => { });
|
|
@@ -228,62 +335,13 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
228
335
|
const lines = buffer.split('\n');
|
|
229
336
|
buffer = lines.pop() || '';
|
|
230
337
|
for (const line of lines) {
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
let parsed;
|
|
239
|
-
try {
|
|
240
|
-
parsed = JSON.parse(jsonStr);
|
|
241
|
-
}
|
|
242
|
-
catch {
|
|
243
|
-
continue;
|
|
244
|
-
}
|
|
245
|
-
if (parsed.usage) {
|
|
246
|
-
rawUsage = parsed.usage;
|
|
247
|
-
}
|
|
248
|
-
const choice = parsed.choices?.[0];
|
|
249
|
-
if (!choice)
|
|
250
|
-
continue;
|
|
251
|
-
const delta = choice.delta;
|
|
252
|
-
if (delta) {
|
|
253
|
-
// 1. Text chunk
|
|
254
|
-
if (delta.content) {
|
|
255
|
-
content += delta.content;
|
|
256
|
-
if (options.onChunk) {
|
|
257
|
-
options.onChunk(delta.content);
|
|
258
|
-
}
|
|
259
|
-
}
|
|
260
|
-
// 2. Reasoning chunk
|
|
261
|
-
const reasoning = delta.reasoning || delta.reasoning_content;
|
|
262
|
-
if (reasoning) {
|
|
263
|
-
reasoningContent += reasoning;
|
|
264
|
-
if (options.onReasoningChunk) {
|
|
265
|
-
options.onReasoningChunk(reasoning);
|
|
266
|
-
}
|
|
267
|
-
}
|
|
268
|
-
// 3. Tool calls assembly
|
|
269
|
-
if (Array.isArray(delta.tool_calls)) {
|
|
270
|
-
for (const tc of delta.tool_calls) {
|
|
271
|
-
const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
|
|
272
|
-
let existing = toolCallsMap.get(idx);
|
|
273
|
-
if (!existing) {
|
|
274
|
-
existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
|
|
275
|
-
toolCallsMap.set(idx, existing);
|
|
276
|
-
}
|
|
277
|
-
if (tc.id)
|
|
278
|
-
existing.id = tc.id;
|
|
279
|
-
if (tc.function?.name)
|
|
280
|
-
existing.name += tc.function.name;
|
|
281
|
-
if (tc.function?.arguments)
|
|
282
|
-
existing.arguments += tc.function.arguments;
|
|
283
|
-
}
|
|
284
|
-
}
|
|
285
|
-
}
|
|
286
|
-
}
|
|
338
|
+
processLine(line);
|
|
339
|
+
}
|
|
340
|
+
}
|
|
341
|
+
buffer += decoder.decode();
|
|
342
|
+
if (buffer.trim()) {
|
|
343
|
+
for (const line of buffer.split('\n')) {
|
|
344
|
+
processLine(line);
|
|
287
345
|
}
|
|
288
346
|
}
|
|
289
347
|
}
|
|
@@ -291,11 +349,14 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
291
349
|
reader.releaseLock();
|
|
292
350
|
}
|
|
293
351
|
const toolCalls = [];
|
|
294
|
-
|
|
352
|
+
const sortedItems = [...toolCallsMap.entries()].sort((a, b) => a[0] - b[0]);
|
|
353
|
+
for (const [idx, item] of sortedItems) {
|
|
295
354
|
if (item.name) {
|
|
296
355
|
const cleanName = normalizeToolName(item.name);
|
|
356
|
+
if (!cleanName)
|
|
357
|
+
continue;
|
|
297
358
|
toolCalls.push({
|
|
298
|
-
id: item.id,
|
|
359
|
+
id: sanitizeProviderToolId(item.id, 'call_openrouter', idx),
|
|
299
360
|
type: 'function',
|
|
300
361
|
function: {
|
|
301
362
|
name: cleanName,
|
|
@@ -305,9 +366,10 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
305
366
|
}
|
|
306
367
|
}
|
|
307
368
|
if (toolCalls.length === 0 && content) {
|
|
308
|
-
const extracted = extractTextToolCalls(content, '
|
|
369
|
+
const extracted = extractTextToolCalls(content, 'call_openrouter_text', freeFormPaths);
|
|
309
370
|
if (extracted.length > 0) {
|
|
310
371
|
toolCalls.push(...extracted);
|
|
372
|
+
content = stripToolCallMarkup(content).trim();
|
|
311
373
|
}
|
|
312
374
|
}
|
|
313
375
|
const usage = this.normalizeUsage(rawUsage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
|
|
@@ -7,26 +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
20
|
import {
|
|
19
21
|
MAX_PROVIDER_ERROR_BYTES,
|
|
20
22
|
MAX_PROVIDER_JSON_BYTES,
|
|
21
23
|
MAX_SSE_BUFFER_BYTES,
|
|
24
|
+
ProviderHttpError,
|
|
22
25
|
parseRetryAfterMs,
|
|
23
26
|
readBoundedResponseText,
|
|
24
27
|
redactProviderSecrets,
|
|
25
28
|
resolveTemperature,
|
|
26
29
|
safeProviderFetch
|
|
27
30
|
} from './byokHttp.js';
|
|
28
|
-
import {
|
|
29
|
-
import type { ChatOptions, ChatResponse, ChatResponseUsage, ChatResponseToolCall } from './base.d.js';
|
|
31
|
+
import { wantsStreaming } from './byokStream.js';
|
|
30
32
|
|
|
31
33
|
export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
|
|
32
34
|
export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
|
|
@@ -81,8 +83,12 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
81
83
|
*/
|
|
82
84
|
public isFreeModel(modelId: string): boolean {
|
|
83
85
|
const clean = (modelId || '').trim().toLowerCase();
|
|
86
|
+
if (!clean || /[\s?#\x00-\x1f]/.test(clean)) return false;
|
|
84
87
|
if (clean === 'openrouter/free' || clean === 'free') return true;
|
|
85
|
-
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
|
+
}
|
|
86
92
|
return false;
|
|
87
93
|
}
|
|
88
94
|
|
|
@@ -105,7 +111,7 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
105
111
|
this.assertFreeModel(this.model);
|
|
106
112
|
}
|
|
107
113
|
|
|
108
|
-
const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
|
|
114
|
+
const apiKey = String(this.apiKey || process.env.OPENROUTER_API_KEY || '').trim();
|
|
109
115
|
if (!apiKey) {
|
|
110
116
|
throw new Error(
|
|
111
117
|
'OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.'
|
|
@@ -113,18 +119,23 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
113
119
|
}
|
|
114
120
|
|
|
115
121
|
const preparedMessages = this.prepareMessages(messages);
|
|
116
|
-
const shouldStream =
|
|
122
|
+
const shouldStream = wantsStreaming(options);
|
|
117
123
|
|
|
118
124
|
const payload: Record<string, any> = {
|
|
119
125
|
model: this.model,
|
|
120
126
|
messages: preparedMessages,
|
|
121
127
|
temperature: resolveTemperature(options.temperature, 0.1),
|
|
122
128
|
stream: shouldStream,
|
|
129
|
+
...(shouldStream ? { stream_options: { include_usage: true } } : {}),
|
|
123
130
|
provider: {
|
|
124
131
|
data_collection: this.dataCollection
|
|
125
132
|
}
|
|
126
133
|
};
|
|
127
134
|
|
|
135
|
+
if (typeof options.maxTokens === 'number' && Number.isFinite(options.maxTokens) && options.maxTokens >= 1) {
|
|
136
|
+
payload['max_tokens'] = Math.floor(options.maxTokens);
|
|
137
|
+
}
|
|
138
|
+
|
|
128
139
|
if (options['jsonMode']) {
|
|
129
140
|
payload['response_format'] = { type: 'json_object' };
|
|
130
141
|
}
|
|
@@ -170,10 +181,18 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
170
181
|
this.handleHttpErrors(response.status, cleanError, retryAfterMs);
|
|
171
182
|
}
|
|
172
183
|
|
|
173
|
-
|
|
174
|
-
|
|
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);
|
|
175
189
|
} else {
|
|
176
|
-
|
|
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;
|
|
177
196
|
}
|
|
178
197
|
} finally {
|
|
179
198
|
cleanup();
|
|
@@ -211,7 +230,7 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
211
230
|
}
|
|
212
231
|
}
|
|
213
232
|
|
|
214
|
-
throw new
|
|
233
|
+
throw new ProviderHttpError(`OpenRouter API Error (${status}): ${errorText}`, { status, retryAfterMs });
|
|
215
234
|
}
|
|
216
235
|
|
|
217
236
|
/**
|
|
@@ -230,13 +249,20 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
230
249
|
truncate: false,
|
|
231
250
|
label: 'OpenRouter'
|
|
232
251
|
});
|
|
252
|
+
const cleanText = rawText.charCodeAt(0) === 0xfeff ? rawText.slice(1) : rawText;
|
|
233
253
|
try {
|
|
234
|
-
data = JSON.parse(
|
|
254
|
+
data = JSON.parse(cleanText);
|
|
235
255
|
} catch {
|
|
236
256
|
const preview = redactProviderSecrets(rawText.slice(0, 240), [apiKey]);
|
|
237
257
|
throw new Error(`OpenRouter returned a non-JSON response (HTTP ${response.status}): ${preview}`);
|
|
238
258
|
}
|
|
239
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
|
+
}
|
|
240
266
|
const normalized = normalizeOpenAIChatChoiceResponse(data, {
|
|
241
267
|
prefix: 'call_openrouter',
|
|
242
268
|
...(freeFormPaths ? { freeFormPaths } : {})
|
|
@@ -257,7 +283,8 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
257
283
|
private async handleStreamingResponse(
|
|
258
284
|
response: Response,
|
|
259
285
|
options: ChatOptions,
|
|
260
|
-
freeFormPaths?: Map<string, string[][]
|
|
286
|
+
freeFormPaths?: Map<string, string[][]>,
|
|
287
|
+
apiKey?: string
|
|
261
288
|
): Promise<ChatResponse> {
|
|
262
289
|
const reader = response.body!.getReader();
|
|
263
290
|
const decoder = new TextDecoder('utf-8');
|
|
@@ -265,18 +292,97 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
265
292
|
let content = '';
|
|
266
293
|
let reasoningContent = '';
|
|
267
294
|
let buffer = '';
|
|
295
|
+
let totalBytes = 0;
|
|
268
296
|
const toolCallsMap = new Map<number, { id: string; name: string; arguments: string }>();
|
|
269
297
|
let rawUsage: any = null;
|
|
270
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
|
+
|
|
271
368
|
try {
|
|
272
369
|
while (true) {
|
|
273
370
|
if (options.signal?.aborted) {
|
|
274
371
|
await reader.cancel().catch(() => {});
|
|
275
|
-
|
|
372
|
+
const abortErr = new Error('OpenRouter request aborted');
|
|
373
|
+
abortErr.name = 'AbortError';
|
|
374
|
+
throw abortErr;
|
|
276
375
|
}
|
|
277
376
|
|
|
278
377
|
const { done, value } = await reader.read();
|
|
279
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
|
+
}
|
|
280
386
|
|
|
281
387
|
buffer += decoder.decode(value, { stream: true });
|
|
282
388
|
if (Buffer.byteLength(buffer, 'utf8') > MAX_SSE_BUFFER_BYTES) {
|
|
@@ -287,61 +393,13 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
287
393
|
buffer = lines.pop() || '';
|
|
288
394
|
|
|
289
395
|
for (const line of lines) {
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
try {
|
|
298
|
-
parsed = JSON.parse(jsonStr);
|
|
299
|
-
} catch {
|
|
300
|
-
continue;
|
|
301
|
-
}
|
|
302
|
-
|
|
303
|
-
if (parsed.usage) {
|
|
304
|
-
rawUsage = parsed.usage;
|
|
305
|
-
}
|
|
306
|
-
|
|
307
|
-
const choice = parsed.choices?.[0];
|
|
308
|
-
if (!choice) continue;
|
|
309
|
-
|
|
310
|
-
const delta = choice.delta;
|
|
311
|
-
if (delta) {
|
|
312
|
-
// 1. Text chunk
|
|
313
|
-
if (delta.content) {
|
|
314
|
-
content += delta.content;
|
|
315
|
-
if (options.onChunk) {
|
|
316
|
-
options.onChunk(delta.content);
|
|
317
|
-
}
|
|
318
|
-
}
|
|
319
|
-
|
|
320
|
-
// 2. Reasoning chunk
|
|
321
|
-
const reasoning = delta.reasoning || delta.reasoning_content;
|
|
322
|
-
if (reasoning) {
|
|
323
|
-
reasoningContent += reasoning;
|
|
324
|
-
if (options.onReasoningChunk) {
|
|
325
|
-
options.onReasoningChunk(reasoning);
|
|
326
|
-
}
|
|
327
|
-
}
|
|
328
|
-
|
|
329
|
-
// 3. Tool calls assembly
|
|
330
|
-
if (Array.isArray(delta.tool_calls)) {
|
|
331
|
-
for (const tc of delta.tool_calls) {
|
|
332
|
-
const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
|
|
333
|
-
let existing = toolCallsMap.get(idx);
|
|
334
|
-
if (!existing) {
|
|
335
|
-
existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
|
|
336
|
-
toolCallsMap.set(idx, existing);
|
|
337
|
-
}
|
|
338
|
-
if (tc.id) existing.id = tc.id;
|
|
339
|
-
if (tc.function?.name) existing.name += tc.function.name;
|
|
340
|
-
if (tc.function?.arguments) existing.arguments += tc.function.arguments;
|
|
341
|
-
}
|
|
342
|
-
}
|
|
343
|
-
}
|
|
344
|
-
}
|
|
396
|
+
processLine(line);
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
buffer += decoder.decode();
|
|
400
|
+
if (buffer.trim()) {
|
|
401
|
+
for (const line of buffer.split('\n')) {
|
|
402
|
+
processLine(line);
|
|
345
403
|
}
|
|
346
404
|
}
|
|
347
405
|
} finally {
|
|
@@ -349,11 +407,13 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
349
407
|
}
|
|
350
408
|
|
|
351
409
|
const toolCalls: ChatResponseToolCall[] = [];
|
|
352
|
-
|
|
410
|
+
const sortedItems = [...toolCallsMap.entries()].sort((a, b) => a[0] - b[0]);
|
|
411
|
+
for (const [idx, item] of sortedItems) {
|
|
353
412
|
if (item.name) {
|
|
354
413
|
const cleanName = normalizeToolName(item.name);
|
|
414
|
+
if (!cleanName) continue;
|
|
355
415
|
toolCalls.push({
|
|
356
|
-
id: item.id,
|
|
416
|
+
id: sanitizeProviderToolId(item.id, 'call_openrouter', idx),
|
|
357
417
|
type: 'function',
|
|
358
418
|
function: {
|
|
359
419
|
name: cleanName,
|
|
@@ -364,9 +424,10 @@ export class OpenRouterProvider extends LLMProvider {
|
|
|
364
424
|
}
|
|
365
425
|
|
|
366
426
|
if (toolCalls.length === 0 && content) {
|
|
367
|
-
const extracted = extractTextToolCalls(content, '
|
|
427
|
+
const extracted = extractTextToolCalls(content, 'call_openrouter_text', freeFormPaths);
|
|
368
428
|
if (extracted.length > 0) {
|
|
369
429
|
toolCalls.push(...extracted);
|
|
430
|
+
content = stripToolCallMarkup(content).trim();
|
|
370
431
|
}
|
|
371
432
|
}
|
|
372
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 = '';
|