@causyne/agent 1.20.68 → 1.20.70
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/agentLoop.js +26 -11
- package/src/agentLoop.ts +26 -11
- package/src/auth/openrouterAuth.js +296 -0
- package/src/auth/openrouterAuth.ts +378 -0
- package/src/cliMode.js +8 -5
- package/src/commands.js +116 -0
- package/src/dynamicCatalogue.js +47 -0
- package/src/dynamicCatalogue.ts +47 -0
- package/src/modelCatalogue.js +5 -2
- package/src/providers/antigravity.js +52 -12
- package/src/providers/antigravity.ts +47 -16
- package/src/providers/base.d.ts +2 -0
- package/src/providers/factory.js +2 -0
- package/src/providers/openrouter.js +316 -0
- package/src/providers/openrouter.ts +361 -0
- package/src/tui/consoleGuard.js +15 -0
- package/src/tui/consoleGuard.ts +15 -0
- package/src/tui/home.js +1 -0
- package/src/tui/modelPicker.js +12 -2
- package/src/tui/modelPicker.ts +12 -2
- package/src/tui/prompt.js +3 -0
- package/src/tui/stage.js +4 -2
- package/src/tui/stageSurface.js +35 -1
- package/src/tui/text.js +25 -2
- package/src/tui/text.ts +24 -2
package/src/modelCatalogue.js
CHANGED
|
@@ -137,7 +137,8 @@ export const MODEL_CATALOGUE = {
|
|
|
137
137
|
'Pi (Local Peer)': ['default'],
|
|
138
138
|
'ACP (Peer Agents)': ['opencode', 'claude', 'codex', 'gemini', 'cursor', 'hermes', 'qwen', 'copilot', 'kimi', 'goose'],
|
|
139
139
|
'OpenCode (ACP)': PEER_MODEL_CATALOGUE.opencode,
|
|
140
|
-
'Claude Code (ACP)': PEER_MODEL_CATALOGUE.claude
|
|
140
|
+
'Claude Code (ACP)': PEER_MODEL_CATALOGUE.claude,
|
|
141
|
+
'OpenRouter (Free)': ['openrouter/free']
|
|
141
142
|
};
|
|
142
143
|
|
|
143
144
|
/** Provider labels in picker order. */
|
|
@@ -168,6 +169,7 @@ export const DEFAULT_MODEL_BY_PROVIDER = {
|
|
|
168
169
|
'acp/goose': 'goose',
|
|
169
170
|
'acp/hermes': 'hermes',
|
|
170
171
|
antigravity: 'Gemini 3.8 Flash (Low)',
|
|
172
|
+
openrouter: 'openrouter/free',
|
|
171
173
|
pi: 'default',
|
|
172
174
|
'openai-compatible': ''
|
|
173
175
|
};
|
|
@@ -207,7 +209,8 @@ export const UTILITY_MODEL_BY_PROVIDER = {
|
|
|
207
209
|
'dashscope-byok': 'qwen3.6-flash',
|
|
208
210
|
anthropic: 'claude-haiku-4-5', // $1/$5 against opus's $5/$25
|
|
209
211
|
openai: 'gpt-5.4-mini', // $0.75/$4.50 against sol's $5/$30
|
|
210
|
-
gemini: 'gemini-3.1-flash-lite'
|
|
212
|
+
gemini: 'gemini-3.1-flash-lite', // $0.25/$1.50 against flash's $1.50/$9
|
|
213
|
+
openrouter: 'openrouter/free'
|
|
211
214
|
};
|
|
212
215
|
|
|
213
216
|
export function allCatalogueModels() {
|
|
@@ -353,9 +353,13 @@ function nativeInspectionTarget(name, parameters) {
|
|
|
353
353
|
const normName = name.toLowerCase().replace(/[_\s-]/g, '');
|
|
354
354
|
if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(normName)) {
|
|
355
355
|
if (/^(readfile|viewfile)$/.test(normName)) {
|
|
356
|
-
const p = String(parameters.AbsolutePath ?? parameters.filePath ?? parameters.path ?? parameters.file ?? '');
|
|
357
|
-
if (p)
|
|
358
|
-
return
|
|
356
|
+
const p = String(parameters.AbsolutePath ?? parameters.Path ?? parameters.filePath ?? parameters.path ?? parameters.file ?? '').trim().toLowerCase();
|
|
357
|
+
if (!p)
|
|
358
|
+
return null;
|
|
359
|
+
const start = parameters.StartLine ?? parameters.startLine ?? parameters.offset ?? parameters.line ?? '';
|
|
360
|
+
const end = parameters.EndLine ?? parameters.endLine ?? parameters.limit ?? '';
|
|
361
|
+
const byteOffset = parameters.ByteOffset ?? parameters.byteOffset ?? '';
|
|
362
|
+
return `${p}:${start}-${end}:${byteOffset}`;
|
|
359
363
|
}
|
|
360
364
|
return null;
|
|
361
365
|
}
|
|
@@ -390,6 +394,23 @@ function nativeInspectionTarget(name, parameters) {
|
|
|
390
394
|
}
|
|
391
395
|
return null;
|
|
392
396
|
}
|
|
397
|
+
export function isRepeatableNativeTool(name, parameters = {}) {
|
|
398
|
+
if (!name || typeof name !== 'string')
|
|
399
|
+
return false;
|
|
400
|
+
const action = name.toLowerCase().replace(/[_\s-]/g, '');
|
|
401
|
+
if (/^(?:managetask|managesubagents|sendmessage|invokesubagent|definesubagent|schedule|tasksummary|todowrite|updateplan|askquestion|processlist|sysrunpoll|procterm|waitfortask|checkstatus)$/.test(action)) {
|
|
402
|
+
return true;
|
|
403
|
+
}
|
|
404
|
+
if (/(?:poll|status|getresult|wait)$/.test(action)) {
|
|
405
|
+
return true;
|
|
406
|
+
}
|
|
407
|
+
if (/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action)) {
|
|
408
|
+
const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
|
|
409
|
+
if (/^(?:ps\s+aux|pgrep|lsof|netstat|ss\s+-)\b/i.test(command))
|
|
410
|
+
return true;
|
|
411
|
+
}
|
|
412
|
+
return false;
|
|
413
|
+
}
|
|
393
414
|
export function isNativeMutation(name, parameters = {}) {
|
|
394
415
|
if (!name || typeof name !== 'string')
|
|
395
416
|
return false;
|
|
@@ -405,7 +426,7 @@ export function isNativeMutation(name, parameters = {}) {
|
|
|
405
426
|
return /\b(?:save_as_mainfile|save_mainfile|write_text|write_bytes|tee)\b/.test(command)
|
|
406
427
|
|| /(?:^|[;&|]\s*)(?:cp|mv|rm|install|patch|touch|mkdir|chmod|sed)\s/.test(command)
|
|
407
428
|
|| /(?:>|>>)/.test(command)
|
|
408
|
-
|| /\b(?:npm|yarn|pnpm|cargo|gradle|gradlew|mvn|dotnet|pip|pip3|pytest|vitest|jest|tsc|make|docker|git\s+(?:add|commit|checkout|merge|rebase|stash|pull|push))\b/i.test(command);
|
|
429
|
+
|| /\b(?:npm|npx|yarn|pnpm|bun|deno|cargo|gradle|gradlew|mvn|dotnet|pip|pip3|pytest|vitest|jest|tsc|make|cmake|ninja|docker|apktool|jadx|jarsigner|apksigner|zipalign|keytool|adb|kotlinc|javac|go|rustc|swift|xcodebuild|codesign|unzip|tar|brew|git\s+(?:add|commit|checkout|merge|rebase|stash|pull|push|restore|reset|clean|rm|mv|apply|cherry-pick|revert|tag|branch|init|clone))\b/i.test(command);
|
|
409
430
|
}
|
|
410
431
|
export function nativeToolSignature(name, parameters = {}) {
|
|
411
432
|
const normName = name.toLowerCase().replace(/[_\s-]/g, '');
|
|
@@ -1007,6 +1028,7 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1007
1028
|
let lastToolSignature = '';
|
|
1008
1029
|
const recentSignatures = [];
|
|
1009
1030
|
const seenNativeActionSteps = new Set();
|
|
1031
|
+
const seenLoopCheckSteps = new Set();
|
|
1010
1032
|
const mediaInspectionCounts = new Map();
|
|
1011
1033
|
const pendingMediaMutations = new Set();
|
|
1012
1034
|
// Antigravity's result usage is cumulative across the conversation, but
|
|
@@ -1187,14 +1209,39 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1187
1209
|
(stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
|
|
1188
1210
|
(toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
|
|
1189
1211
|
{};
|
|
1190
|
-
|
|
1212
|
+
const hasParams = Boolean(rawParams && typeof rawParams === 'object' && Object.keys(rawParams).length > 0);
|
|
1213
|
+
const readyForLoopCheck = state === 'DONE'
|
|
1214
|
+
|| (state === 'ACTIVE' && (hasParams || isNativeMutation(name || '', rawParams) || isRepeatableNativeTool(name || '', rawParams)));
|
|
1215
|
+
const shouldCheckLoop = Boolean(name) && readyForLoopCheck
|
|
1216
|
+
&& (!Number.isFinite(stepIndex) || !seenLoopCheckSteps.has(stepIndex));
|
|
1217
|
+
if (name && state === 'DONE' && !toolInfo?.error && isNativeMutation(name, rawParams)) {
|
|
1218
|
+
if (Number.isFinite(stepIndex))
|
|
1219
|
+
seenLoopCheckSteps.add(stepIndex);
|
|
1220
|
+
lastMutationActionIndex = nativeActionStarts + 1;
|
|
1221
|
+
progressiveActionsCount++;
|
|
1222
|
+
consecutiveIdenticalCount = 0;
|
|
1223
|
+
consecutiveInspections = 0;
|
|
1224
|
+
lastToolSignature = '';
|
|
1225
|
+
recentSignatures.length = 0;
|
|
1226
|
+
}
|
|
1227
|
+
else if (name && shouldCheckLoop) {
|
|
1228
|
+
if (Number.isFinite(stepIndex))
|
|
1229
|
+
seenLoopCheckSteps.add(stepIndex);
|
|
1191
1230
|
const mutating = isNativeMutation(name, rawParams);
|
|
1231
|
+
const repeatable = isRepeatableNativeTool(name, rawParams);
|
|
1192
1232
|
if (mutating) {
|
|
1193
1233
|
lastMutationActionIndex = nativeActionStarts + 1;
|
|
1194
1234
|
progressiveActionsCount++;
|
|
1195
1235
|
consecutiveIdenticalCount = 0;
|
|
1196
1236
|
consecutiveInspections = 0;
|
|
1197
1237
|
lastToolSignature = '';
|
|
1238
|
+
recentSignatures.length = 0;
|
|
1239
|
+
}
|
|
1240
|
+
else if (repeatable) {
|
|
1241
|
+
// Task/subagent polling, plan updates, and user questions are legitimate
|
|
1242
|
+
// coordination steps and must not count as aimless read-only loops.
|
|
1243
|
+
consecutiveIdenticalCount = 0;
|
|
1244
|
+
lastToolSignature = '';
|
|
1198
1245
|
}
|
|
1199
1246
|
else if (!desktopTask && options.taskArchetype !== 'media_3d_generation') {
|
|
1200
1247
|
consecutiveInspections++;
|
|
@@ -1224,13 +1271,6 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1224
1271
|
terminateChild();
|
|
1225
1272
|
return;
|
|
1226
1273
|
}
|
|
1227
|
-
// 3. Stagnant read-only inspection runaway without mutations on an editing task
|
|
1228
|
-
if (consecutiveInspections >= 30 && options.taskArchetype !== 'web_research_only') {
|
|
1229
|
-
const error = Object.assign(new Error(`Antigravity performed ${consecutiveInspections} consecutive read-only inspections without writing or modifying code. Halting exploration loop.`), { code: 'AGY_EXPLORATION_LOOP', inspectionCount: consecutiveInspections });
|
|
1230
|
-
safeReject(error);
|
|
1231
|
-
terminateChild();
|
|
1232
|
-
return;
|
|
1233
|
-
}
|
|
1234
1274
|
}
|
|
1235
1275
|
}
|
|
1236
1276
|
if (newNativeAction) {
|
|
@@ -357,8 +357,12 @@ function nativeInspectionTarget(name: string, parameters: Record<string, unknown
|
|
|
357
357
|
const normName = name.toLowerCase().replace(/[_\s-]/g, '');
|
|
358
358
|
if (!/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(normName)) {
|
|
359
359
|
if (/^(readfile|viewfile)$/.test(normName)) {
|
|
360
|
-
const p = String(parameters.AbsolutePath ?? parameters.filePath ?? parameters.path ?? parameters.file ?? '');
|
|
361
|
-
if (p) return
|
|
360
|
+
const p = String(parameters.AbsolutePath ?? parameters.Path ?? parameters.filePath ?? parameters.path ?? parameters.file ?? '').trim().toLowerCase();
|
|
361
|
+
if (!p) return null;
|
|
362
|
+
const start = parameters.StartLine ?? parameters.startLine ?? parameters.offset ?? parameters.line ?? '';
|
|
363
|
+
const end = parameters.EndLine ?? parameters.endLine ?? parameters.limit ?? '';
|
|
364
|
+
const byteOffset = parameters.ByteOffset ?? parameters.byteOffset ?? '';
|
|
365
|
+
return `${p}:${start}-${end}:${byteOffset}`;
|
|
362
366
|
}
|
|
363
367
|
return null;
|
|
364
368
|
}
|
|
@@ -396,6 +400,22 @@ function nativeInspectionTarget(name: string, parameters: Record<string, unknown
|
|
|
396
400
|
return null;
|
|
397
401
|
}
|
|
398
402
|
|
|
403
|
+
export function isRepeatableNativeTool(name: string, parameters: Record<string, unknown> = {}): boolean {
|
|
404
|
+
if (!name || typeof name !== 'string') return false;
|
|
405
|
+
const action = name.toLowerCase().replace(/[_\s-]/g, '');
|
|
406
|
+
if (/^(?:managetask|managesubagents|sendmessage|invokesubagent|definesubagent|schedule|tasksummary|todowrite|updateplan|askquestion|processlist|sysrunpoll|procterm|waitfortask|checkstatus)$/.test(action)) {
|
|
407
|
+
return true;
|
|
408
|
+
}
|
|
409
|
+
if (/(?:poll|status|getresult|wait)$/.test(action)) {
|
|
410
|
+
return true;
|
|
411
|
+
}
|
|
412
|
+
if (/^(runcommand|command|sysrun|terminal|bash|shell)$/.test(action)) {
|
|
413
|
+
const command = cleanCommandString(parameters.CommandLine ?? parameters.command ?? parameters.cmd ?? '');
|
|
414
|
+
if (/^(?:ps\s+aux|pgrep|lsof|netstat|ss\s+-)\b/i.test(command)) return true;
|
|
415
|
+
}
|
|
416
|
+
return false;
|
|
417
|
+
}
|
|
418
|
+
|
|
399
419
|
export function isNativeMutation(name: string, parameters: Record<string, unknown> = {}): boolean {
|
|
400
420
|
if (!name || typeof name !== 'string') return false;
|
|
401
421
|
const action = name.toLowerCase().replace(/[_\s-]/g, '');
|
|
@@ -408,7 +428,7 @@ export function isNativeMutation(name: string, parameters: Record<string, unknow
|
|
|
408
428
|
return /\b(?:save_as_mainfile|save_mainfile|write_text|write_bytes|tee)\b/.test(command)
|
|
409
429
|
|| /(?:^|[;&|]\s*)(?:cp|mv|rm|install|patch|touch|mkdir|chmod|sed)\s/.test(command)
|
|
410
430
|
|| /(?:>|>>)/.test(command)
|
|
411
|
-
|| /\b(?:npm|yarn|pnpm|cargo|gradle|gradlew|mvn|dotnet|pip|pip3|pytest|vitest|jest|tsc|make|docker|git\s+(?:add|commit|checkout|merge|rebase|stash|pull|push))\b/i.test(command);
|
|
431
|
+
|| /\b(?:npm|npx|yarn|pnpm|bun|deno|cargo|gradle|gradlew|mvn|dotnet|pip|pip3|pytest|vitest|jest|tsc|make|cmake|ninja|docker|apktool|jadx|jarsigner|apksigner|zipalign|keytool|adb|kotlinc|javac|go|rustc|swift|xcodebuild|codesign|unzip|tar|brew|git\s+(?:add|commit|checkout|merge|rebase|stash|pull|push|restore|reset|clean|rm|mv|apply|cherry-pick|revert|tag|branch|init|clone))\b/i.test(command);
|
|
412
432
|
}
|
|
413
433
|
|
|
414
434
|
export function nativeToolSignature(name: string, parameters: Record<string, unknown> = {}): string {
|
|
@@ -1049,6 +1069,7 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1049
1069
|
let lastToolSignature = '';
|
|
1050
1070
|
const recentSignatures: string[] = [];
|
|
1051
1071
|
const seenNativeActionSteps = new Set<number>();
|
|
1072
|
+
const seenLoopCheckSteps = new Set<number>();
|
|
1052
1073
|
const mediaInspectionCounts = new Map<string, number>();
|
|
1053
1074
|
const pendingMediaMutations = new Set<number>();
|
|
1054
1075
|
// Antigravity's result usage is cumulative across the conversation, but
|
|
@@ -1231,15 +1252,36 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1231
1252
|
(stepUpdate && typeof stepUpdate === 'object' && stepUpdate.parameters) ||
|
|
1232
1253
|
(toolInfo && typeof toolInfo === 'object' && toolInfo.input) ||
|
|
1233
1254
|
{};
|
|
1234
|
-
|
|
1235
|
-
|
|
1255
|
+
const hasParams = Boolean(rawParams && typeof rawParams === 'object' && Object.keys(rawParams).length > 0);
|
|
1256
|
+
const readyForLoopCheck = state === 'DONE'
|
|
1257
|
+
|| (state === 'ACTIVE' && (hasParams || isNativeMutation(name || '', rawParams) || isRepeatableNativeTool(name || '', rawParams)));
|
|
1258
|
+
const shouldCheckLoop = Boolean(name) && readyForLoopCheck
|
|
1259
|
+
&& (!Number.isFinite(stepIndex) || !seenLoopCheckSteps.has(stepIndex));
|
|
1260
|
+
|
|
1261
|
+
if (name && state === 'DONE' && !toolInfo?.error && isNativeMutation(name, rawParams)) {
|
|
1262
|
+
if (Number.isFinite(stepIndex)) seenLoopCheckSteps.add(stepIndex);
|
|
1263
|
+
lastMutationActionIndex = nativeActionStarts + 1;
|
|
1264
|
+
progressiveActionsCount++;
|
|
1265
|
+
consecutiveIdenticalCount = 0;
|
|
1266
|
+
consecutiveInspections = 0;
|
|
1267
|
+
lastToolSignature = '';
|
|
1268
|
+
recentSignatures.length = 0;
|
|
1269
|
+
} else if (name && shouldCheckLoop) {
|
|
1270
|
+
if (Number.isFinite(stepIndex)) seenLoopCheckSteps.add(stepIndex);
|
|
1236
1271
|
const mutating = isNativeMutation(name, rawParams);
|
|
1272
|
+
const repeatable = isRepeatableNativeTool(name, rawParams);
|
|
1237
1273
|
if (mutating) {
|
|
1238
1274
|
lastMutationActionIndex = nativeActionStarts + 1;
|
|
1239
1275
|
progressiveActionsCount++;
|
|
1240
1276
|
consecutiveIdenticalCount = 0;
|
|
1241
1277
|
consecutiveInspections = 0;
|
|
1242
1278
|
lastToolSignature = '';
|
|
1279
|
+
recentSignatures.length = 0;
|
|
1280
|
+
} else if (repeatable) {
|
|
1281
|
+
// Task/subagent polling, plan updates, and user questions are legitimate
|
|
1282
|
+
// coordination steps and must not count as aimless read-only loops.
|
|
1283
|
+
consecutiveIdenticalCount = 0;
|
|
1284
|
+
lastToolSignature = '';
|
|
1243
1285
|
} else if (!desktopTask && (options as any).taskArchetype !== 'media_3d_generation') {
|
|
1244
1286
|
consecutiveInspections++;
|
|
1245
1287
|
const sig = nativeToolSignature(name, rawParams);
|
|
@@ -1274,17 +1316,6 @@ export class AntigravityProvider extends LLMProvider {
|
|
|
1274
1316
|
terminateChild();
|
|
1275
1317
|
return;
|
|
1276
1318
|
}
|
|
1277
|
-
|
|
1278
|
-
// 3. Stagnant read-only inspection runaway without mutations on an editing task
|
|
1279
|
-
if (consecutiveInspections >= 30 && (options as any).taskArchetype !== 'web_research_only') {
|
|
1280
|
-
const error = Object.assign(
|
|
1281
|
-
new Error(`Antigravity performed ${consecutiveInspections} consecutive read-only inspections without writing or modifying code. Halting exploration loop.`),
|
|
1282
|
-
{ code: 'AGY_EXPLORATION_LOOP', inspectionCount: consecutiveInspections }
|
|
1283
|
-
);
|
|
1284
|
-
safeReject(error);
|
|
1285
|
-
terminateChild();
|
|
1286
|
-
return;
|
|
1287
|
-
}
|
|
1288
1319
|
}
|
|
1289
1320
|
}
|
|
1290
1321
|
|
package/src/providers/base.d.ts
CHANGED
|
@@ -84,6 +84,8 @@ export class LLMProvider {
|
|
|
84
84
|
get supportsVision(): boolean;
|
|
85
85
|
get supportsAudio(): boolean;
|
|
86
86
|
supportsToolSearch?(): boolean;
|
|
87
|
+
prepareMessages(messages: any[]): any[];
|
|
88
|
+
normalizeUsage(rawUsage: any): ChatResponseUsage;
|
|
87
89
|
chat(messages: any[], options?: ChatOptions): Promise<ChatResponse>;
|
|
88
90
|
}
|
|
89
91
|
|
package/src/providers/factory.js
CHANGED
|
@@ -19,6 +19,7 @@ import { MuseProvider } from './muse.js';
|
|
|
19
19
|
import { AcpProvider, isAcpProvider } from './acp.js';
|
|
20
20
|
import { PiProvider, isPiProvider } from './pi.js';
|
|
21
21
|
import { AntigravityProvider, isAntigravityProvider } from './antigravity.js';
|
|
22
|
+
import { OpenRouterProvider } from './openrouter.js';
|
|
22
23
|
|
|
23
24
|
export function createProvider(config) {
|
|
24
25
|
const p = config.provider?.toLowerCase();
|
|
@@ -35,6 +36,7 @@ export function createProvider(config) {
|
|
|
35
36
|
// Meta Model API. 'meta' and 'muse' both reach it: the vendor is Meta, the
|
|
36
37
|
// model family is Muse, and users say either.
|
|
37
38
|
if (p === 'muse' || p === 'meta') return new MuseProvider(config);
|
|
39
|
+
if (p === 'openrouter' || p === 'openrouter-free') return new OpenRouterProvider(config);
|
|
38
40
|
if (isAcpProvider(p)) return new AcpProvider(config);
|
|
39
41
|
if (isPiProvider(p)) return new PiProvider(config);
|
|
40
42
|
if (isAntigravityProvider(p)) return new AntigravityProvider(config);
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Causyne Agent — OpenRouter Free Provider
|
|
3
|
+
*
|
|
4
|
+
* Implements genuine zero-cost hosted model inference via the official
|
|
5
|
+
* OpenRouter Free router (`openrouter/free`) and verified zero-cost models.
|
|
6
|
+
* Enforces strict zero-cost boundaries, default data_collection: "deny",
|
|
7
|
+
* streaming SSE, and safe tool-call parsing without paid model fallbacks.
|
|
8
|
+
*/
|
|
9
|
+
import { LLMProvider } from './base.js';
|
|
10
|
+
import { canonicalModelId } from '../modelIds.js';
|
|
11
|
+
import { scanAndAdaptToolsForProvider } from '../tools/toolScanner.js';
|
|
12
|
+
export const OPENROUTER_API_BASE = 'https://openrouter.ai/api/v1';
|
|
13
|
+
export const OPENROUTER_CHAT_ENDPOINT = 'https://openrouter.ai/api/v1/chat/completions';
|
|
14
|
+
export const OPENROUTER_DEFAULT_FREE_MODEL = 'openrouter/free';
|
|
15
|
+
export class FreeModeCostGuardError extends Error {
|
|
16
|
+
constructor(message) {
|
|
17
|
+
super(message);
|
|
18
|
+
this.name = 'FreeModeCostGuardError';
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
export class OpenRouterRateLimitError extends Error {
|
|
22
|
+
constructor(message) {
|
|
23
|
+
super(message);
|
|
24
|
+
this.name = 'OpenRouterRateLimitError';
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
export class OpenRouterPrivacyConstraintError extends Error {
|
|
28
|
+
constructor(message) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = 'OpenRouterPrivacyConstraintError';
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
export class OpenRouterProvider extends LLMProvider {
|
|
34
|
+
dataCollection;
|
|
35
|
+
freeOnly;
|
|
36
|
+
constructor(config = {}) {
|
|
37
|
+
super(config);
|
|
38
|
+
this.baseUrl = config['baseUrl'] || OPENROUTER_CHAT_ENDPOINT;
|
|
39
|
+
this.model = canonicalModelId(String(config['model'] || OPENROUTER_DEFAULT_FREE_MODEL));
|
|
40
|
+
this.dataCollection = config['openrouterDataCollection'] === 'allow' ? 'allow' : 'deny';
|
|
41
|
+
this.freeOnly = config['freeOnly'] !== false; // Default: free mode enforced
|
|
42
|
+
// Verify model cost constraint upon instantiation
|
|
43
|
+
if (this.freeOnly) {
|
|
44
|
+
this.assertFreeModel(this.model);
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Determine whether a model identifier represents a zero-cost free route.
|
|
49
|
+
*/
|
|
50
|
+
isFreeModel(modelId) {
|
|
51
|
+
const clean = (modelId || '').trim().toLowerCase();
|
|
52
|
+
if (clean === 'openrouter/free' || clean === 'free')
|
|
53
|
+
return true;
|
|
54
|
+
if (clean.endsWith(':free'))
|
|
55
|
+
return true;
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
/**
|
|
59
|
+
* Enforce that the requested model is strictly zero-cost.
|
|
60
|
+
*/
|
|
61
|
+
assertFreeModel(modelId) {
|
|
62
|
+
if (!this.isFreeModel(modelId)) {
|
|
63
|
+
throw new FreeModeCostGuardError(`Model '${modelId}' is not an authorized free model. Free mode strictly forbids paid models to prevent unintended charges.`);
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
/**
|
|
67
|
+
* Execute chat completion with OpenRouter, supporting streaming, tools, and privacy tags.
|
|
68
|
+
*/
|
|
69
|
+
async chat(messages, options = {}) {
|
|
70
|
+
if (this.freeOnly) {
|
|
71
|
+
this.assertFreeModel(this.model);
|
|
72
|
+
}
|
|
73
|
+
const apiKey = this.apiKey || process.env.OPENROUTER_API_KEY;
|
|
74
|
+
if (!apiKey) {
|
|
75
|
+
throw new Error('OpenRouter API key is required. Run /openrouter connect or /setup to connect your OpenRouter account.');
|
|
76
|
+
}
|
|
77
|
+
const preparedMessages = this.prepareMessages(messages);
|
|
78
|
+
const shouldStream = typeof options.onChunk === 'function';
|
|
79
|
+
const payload = {
|
|
80
|
+
model: this.model,
|
|
81
|
+
messages: preparedMessages,
|
|
82
|
+
temperature: options.temperature ?? 0.1,
|
|
83
|
+
stream: shouldStream,
|
|
84
|
+
provider: {
|
|
85
|
+
data_collection: this.dataCollection
|
|
86
|
+
}
|
|
87
|
+
};
|
|
88
|
+
if (options['jsonMode']) {
|
|
89
|
+
payload['response_format'] = { type: 'json_object' };
|
|
90
|
+
}
|
|
91
|
+
if (options.tools && Array.isArray(options.tools) && options.tools.length > 0) {
|
|
92
|
+
const scanReport = scanAndAdaptToolsForProvider(options.tools, 'openai');
|
|
93
|
+
payload['tools'] = scanReport.adaptedTools;
|
|
94
|
+
payload['tool_choice'] = 'auto';
|
|
95
|
+
}
|
|
96
|
+
const headers = {
|
|
97
|
+
'Content-Type': 'application/json',
|
|
98
|
+
'Authorization': `Bearer ${apiKey}`,
|
|
99
|
+
'HTTP-Referer': 'https://causyne.com',
|
|
100
|
+
'X-Title': 'Causyne Agent'
|
|
101
|
+
};
|
|
102
|
+
let response;
|
|
103
|
+
const endpoint = this.baseUrl || OPENROUTER_CHAT_ENDPOINT;
|
|
104
|
+
const fetchInit = {
|
|
105
|
+
method: 'POST',
|
|
106
|
+
headers,
|
|
107
|
+
body: JSON.stringify(payload)
|
|
108
|
+
};
|
|
109
|
+
if (options.signal) {
|
|
110
|
+
fetchInit.signal = options.signal;
|
|
111
|
+
}
|
|
112
|
+
try {
|
|
113
|
+
response = await fetch(endpoint, fetchInit);
|
|
114
|
+
}
|
|
115
|
+
catch (err) {
|
|
116
|
+
if (err?.name === 'AbortError' || options.signal?.aborted) {
|
|
117
|
+
throw err;
|
|
118
|
+
}
|
|
119
|
+
throw new Error(`OpenRouter network connection error: ${err?.message || err}`);
|
|
120
|
+
}
|
|
121
|
+
if (!response.ok) {
|
|
122
|
+
const errorText = await response.text().catch(() => '');
|
|
123
|
+
this.handleHttpErrors(response.status, errorText);
|
|
124
|
+
}
|
|
125
|
+
if (shouldStream && response.body) {
|
|
126
|
+
return this.handleStreamingResponse(response, options);
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
return this.handleJsonResponse(response);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
/**
|
|
133
|
+
* Map HTTP error codes into user-friendly and security-preserving exceptions.
|
|
134
|
+
*/
|
|
135
|
+
handleHttpErrors(status, errorText) {
|
|
136
|
+
if (status === 429) {
|
|
137
|
+
throw new OpenRouterRateLimitError('OpenRouter Free rate limit or quota exceeded. Free models have community concurrency limits. Please wait a moment or try again later.');
|
|
138
|
+
}
|
|
139
|
+
const lowered = (errorText || '').toLowerCase();
|
|
140
|
+
if (status === 400 || status === 404) {
|
|
141
|
+
if (lowered.includes('data_collection') || lowered.includes('no provider available') || lowered.includes('data policy')) {
|
|
142
|
+
throw new OpenRouterPrivacyConstraintError(`No free provider is currently available matching the privacy policy (data_collection='${this.dataCollection}'). ` +
|
|
143
|
+
`You can retry shortly, or inspect your preference with /openrouter status.`);
|
|
144
|
+
}
|
|
145
|
+
if (lowered.includes('rate limit') || lowered.includes('free model quota')) {
|
|
146
|
+
throw new OpenRouterRateLimitError('OpenRouter Free usage limit reached for this free model. Please wait a moment or select another free model with /model.');
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
throw new Error(`OpenRouter API Error (${status}): ${errorText}`);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* Process a non-streaming JSON response from OpenRouter.
|
|
153
|
+
*/
|
|
154
|
+
async handleJsonResponse(response) {
|
|
155
|
+
const data = (await response.json());
|
|
156
|
+
let content = '';
|
|
157
|
+
let toolCalls = [];
|
|
158
|
+
let reasoningContent = '';
|
|
159
|
+
if (data.choices && Array.isArray(data.choices) && data.choices[0]?.message) {
|
|
160
|
+
const message = data.choices[0].message;
|
|
161
|
+
content = message.content || '';
|
|
162
|
+
toolCalls = this.normalizeToolCalls(message.tool_calls);
|
|
163
|
+
reasoningContent = message.reasoning || message.reasoning_content || '';
|
|
164
|
+
}
|
|
165
|
+
const rawUsage = data.usage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 };
|
|
166
|
+
const usage = this.normalizeUsage(rawUsage);
|
|
167
|
+
return {
|
|
168
|
+
content,
|
|
169
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
170
|
+
reasoningContent: reasoningContent || undefined,
|
|
171
|
+
usage
|
|
172
|
+
};
|
|
173
|
+
}
|
|
174
|
+
/**
|
|
175
|
+
* Process a streaming SSE response from OpenRouter.
|
|
176
|
+
*/
|
|
177
|
+
async handleStreamingResponse(response, options) {
|
|
178
|
+
const reader = response.body.getReader();
|
|
179
|
+
const decoder = new TextDecoder('utf-8');
|
|
180
|
+
let content = '';
|
|
181
|
+
let reasoningContent = '';
|
|
182
|
+
let buffer = '';
|
|
183
|
+
const toolCallsMap = new Map();
|
|
184
|
+
let rawUsage = null;
|
|
185
|
+
try {
|
|
186
|
+
while (true) {
|
|
187
|
+
if (options.signal?.aborted) {
|
|
188
|
+
await reader.cancel().catch(() => { });
|
|
189
|
+
break;
|
|
190
|
+
}
|
|
191
|
+
const { done, value } = await reader.read();
|
|
192
|
+
if (done)
|
|
193
|
+
break;
|
|
194
|
+
buffer += decoder.decode(value, { stream: true });
|
|
195
|
+
const lines = buffer.split('\n');
|
|
196
|
+
buffer = lines.pop() || '';
|
|
197
|
+
for (const line of lines) {
|
|
198
|
+
const trimmed = line.trim();
|
|
199
|
+
if (!trimmed || trimmed.startsWith(':'))
|
|
200
|
+
continue; // Skip comments/keepalive
|
|
201
|
+
if (trimmed === 'data: [DONE]')
|
|
202
|
+
continue;
|
|
203
|
+
if (trimmed.startsWith('data: ')) {
|
|
204
|
+
const jsonStr = trimmed.slice(6);
|
|
205
|
+
let parsed;
|
|
206
|
+
try {
|
|
207
|
+
parsed = JSON.parse(jsonStr);
|
|
208
|
+
}
|
|
209
|
+
catch {
|
|
210
|
+
continue;
|
|
211
|
+
}
|
|
212
|
+
if (parsed.usage) {
|
|
213
|
+
rawUsage = parsed.usage;
|
|
214
|
+
}
|
|
215
|
+
const choice = parsed.choices?.[0];
|
|
216
|
+
if (!choice)
|
|
217
|
+
continue;
|
|
218
|
+
const delta = choice.delta;
|
|
219
|
+
if (delta) {
|
|
220
|
+
// 1. Text chunk
|
|
221
|
+
if (delta.content) {
|
|
222
|
+
content += delta.content;
|
|
223
|
+
if (options.onChunk) {
|
|
224
|
+
options.onChunk(delta.content);
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
// 2. Reasoning chunk
|
|
228
|
+
const reasoning = delta.reasoning || delta.reasoning_content;
|
|
229
|
+
if (reasoning) {
|
|
230
|
+
reasoningContent += reasoning;
|
|
231
|
+
if (options.onReasoningChunk) {
|
|
232
|
+
options.onReasoningChunk(reasoning);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
// 3. Tool calls assembly
|
|
236
|
+
if (Array.isArray(delta.tool_calls)) {
|
|
237
|
+
for (const tc of delta.tool_calls) {
|
|
238
|
+
const idx = typeof tc.index === 'number' ? tc.index : toolCallsMap.size;
|
|
239
|
+
let existing = toolCallsMap.get(idx);
|
|
240
|
+
if (!existing) {
|
|
241
|
+
existing = { id: tc.id || `call_${idx}_${Date.now()}`, name: '', arguments: '' };
|
|
242
|
+
toolCallsMap.set(idx, existing);
|
|
243
|
+
}
|
|
244
|
+
if (tc.id)
|
|
245
|
+
existing.id = tc.id;
|
|
246
|
+
if (tc.function?.name)
|
|
247
|
+
existing.name += tc.function.name;
|
|
248
|
+
if (tc.function?.arguments)
|
|
249
|
+
existing.arguments += tc.function.arguments;
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
reader.releaseLock();
|
|
259
|
+
}
|
|
260
|
+
const toolCalls = [];
|
|
261
|
+
for (const item of toolCallsMap.values()) {
|
|
262
|
+
if (item.name) {
|
|
263
|
+
toolCalls.push({
|
|
264
|
+
id: item.id,
|
|
265
|
+
type: 'function',
|
|
266
|
+
function: {
|
|
267
|
+
name: item.name,
|
|
268
|
+
arguments: item.arguments || '{}'
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
const usage = this.normalizeUsage(rawUsage || { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 });
|
|
274
|
+
return {
|
|
275
|
+
content,
|
|
276
|
+
toolCalls: toolCalls.length > 0 ? toolCalls : undefined,
|
|
277
|
+
reasoningContent: reasoningContent || undefined,
|
|
278
|
+
usage
|
|
279
|
+
};
|
|
280
|
+
}
|
|
281
|
+
/**
|
|
282
|
+
* Safely normalize tool calls from provider message.
|
|
283
|
+
*/
|
|
284
|
+
normalizeToolCalls(rawCalls) {
|
|
285
|
+
if (!Array.isArray(rawCalls))
|
|
286
|
+
return [];
|
|
287
|
+
const normalized = [];
|
|
288
|
+
for (let i = 0; i < rawCalls.length; i++) {
|
|
289
|
+
const tc = rawCalls[i];
|
|
290
|
+
if (!tc || typeof tc !== 'object')
|
|
291
|
+
continue;
|
|
292
|
+
const id = typeof tc.id === 'string' && tc.id ? tc.id : `call_${i}_${Date.now()}`;
|
|
293
|
+
const name = tc.function?.name || tc.name || '';
|
|
294
|
+
if (!name || typeof name !== 'string')
|
|
295
|
+
continue;
|
|
296
|
+
let args = tc.function?.arguments;
|
|
297
|
+
if (typeof args !== 'string') {
|
|
298
|
+
try {
|
|
299
|
+
args = JSON.stringify(args || {});
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
args = '{}';
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
normalized.push({
|
|
306
|
+
id,
|
|
307
|
+
type: 'function',
|
|
308
|
+
function: {
|
|
309
|
+
name,
|
|
310
|
+
arguments: args
|
|
311
|
+
}
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
return normalized;
|
|
315
|
+
}
|
|
316
|
+
}
|