@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.
@@ -0,0 +1,378 @@
1
+ /**
2
+ * Causyne Agent — OpenRouter Free Authentication & OAuth PKCE Flow
3
+ *
4
+ * Implements the official OpenRouter OAuth PKCE authorization with S256,
5
+ * loopback callback server on ephemeral 127.0.0.1 port, headless/manual fallback,
6
+ * and secure credential storage in Causyne's encrypted configuration vault.
7
+ */
8
+
9
+ import http from 'node:http';
10
+ import crypto from 'node:crypto';
11
+ import { URL } from 'node:url';
12
+ import { loadConfig, saveConfig } from '../config.js';
13
+ import { openWithNativeOS } from '../tools/desktopOpen.js';
14
+
15
+ export const OPENROUTER_AUTH_URL = 'https://openrouter.ai/auth';
16
+ export const OPENROUTER_TOKEN_EXCHANGE_URL = 'https://openrouter.ai/api/v1/auth/keys';
17
+ export const OPENROUTER_FREE_MODEL = 'openrouter/free';
18
+
19
+ export interface PkceCodes {
20
+ codeVerifier: string;
21
+ codeChallenge: string;
22
+ codeChallengeMethod: 'S256';
23
+ state: string;
24
+ }
25
+
26
+ export interface OpenRouterStatus {
27
+ connected: boolean;
28
+ active: boolean;
29
+ model: string;
30
+ dataCollection: 'deny' | 'allow';
31
+ maskedKey?: string | undefined;
32
+ keySource?: 'vault' | 'environment' | undefined;
33
+ }
34
+
35
+ export class OpenRouterAuthError extends Error {
36
+ constructor(message: string) {
37
+ super(message);
38
+ this.name = 'OpenRouterAuthError';
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Generate cryptographically secure PKCE verifier, S256 challenge, and CSRF state token.
44
+ */
45
+ export function generatePkceCodes(): PkceCodes {
46
+ // 32 random bytes as base64url string yields 43 characters (RFC 7636 compliant: 43-128 chars)
47
+ const codeVerifier = crypto.randomBytes(32).toString('base64url');
48
+ const codeChallenge = crypto
49
+ .createHash('sha256')
50
+ .update(codeVerifier)
51
+ .digest('base64url');
52
+ const state = crypto.randomBytes(16).toString('hex');
53
+
54
+ return {
55
+ codeVerifier,
56
+ codeChallenge,
57
+ codeChallengeMethod: 'S256',
58
+ state
59
+ };
60
+ }
61
+
62
+ /**
63
+ * Build the official OpenRouter OAuth authorization URL.
64
+ */
65
+ export function buildAuthorizationUrl(callbackUrl: string, codeChallenge: string, state: string): string {
66
+ const url = new URL(OPENROUTER_AUTH_URL);
67
+ url.searchParams.set('callback_url', callbackUrl);
68
+ url.searchParams.set('code_challenge', codeChallenge);
69
+ url.searchParams.set('code_challenge_method', 'S256');
70
+ url.searchParams.set('state', state);
71
+ return url.toString();
72
+ }
73
+
74
+ /**
75
+ * Exchange the authorization code for an OpenRouter API key using PKCE verifier.
76
+ */
77
+ export async function exchangeCodeForApiKey(
78
+ code: string,
79
+ codeVerifier: string,
80
+ fetchFn: typeof fetch = fetch
81
+ ): Promise<string> {
82
+ const cleanCode = (code || '').trim();
83
+ const cleanVerifier = (codeVerifier || '').trim();
84
+
85
+ if (!cleanCode) {
86
+ throw new OpenRouterAuthError('Authorization code cannot be empty.');
87
+ }
88
+ if (!cleanVerifier) {
89
+ throw new OpenRouterAuthError('PKCE code verifier cannot be empty.');
90
+ }
91
+
92
+ const payload = {
93
+ code: cleanCode,
94
+ code_verifier: cleanVerifier,
95
+ code_challenge_method: 'S256'
96
+ };
97
+
98
+ let response: Response;
99
+ try {
100
+ response = await fetchFn(OPENROUTER_TOKEN_EXCHANGE_URL, {
101
+ method: 'POST',
102
+ headers: {
103
+ 'Content-Type': 'application/json',
104
+ 'HTTP-Referer': 'https://causyne.com',
105
+ 'X-Title': 'Causyne Agent'
106
+ },
107
+ body: JSON.stringify(payload)
108
+ });
109
+ } catch (err: any) {
110
+ throw new OpenRouterAuthError(`Failed to reach OpenRouter token exchange: ${err?.message || err}`);
111
+ }
112
+
113
+ if (!response.ok) {
114
+ const errorBody = await response.text().catch(() => '');
115
+ throw new OpenRouterAuthError(
116
+ `OpenRouter token exchange failed (HTTP ${response.status}): ${errorBody || 'Invalid code or verifier'}`
117
+ );
118
+ }
119
+
120
+ const data = (await response.json().catch(() => null)) as { key?: string } | null;
121
+ const apiKey = data?.key?.trim();
122
+ if (!apiKey) {
123
+ throw new OpenRouterAuthError('OpenRouter response did not contain an API key.');
124
+ }
125
+
126
+ return apiKey;
127
+ }
128
+
129
+ /**
130
+ * Start loopback HTTP server on 127.0.0.1 to receive the OAuth redirect code.
131
+ */
132
+ export async function startLoopbackAuth(options: {
133
+ timeoutMs?: number;
134
+ openBrowser?: boolean;
135
+ fetchFn?: typeof fetch;
136
+ onUrlReady?: (url: string) => void;
137
+ } = {}): Promise<{ apiKey: string }> {
138
+ const timeoutMs = options.timeoutMs ?? 120_000;
139
+ const openBrowser = options.openBrowser ?? true;
140
+ const fetchFn = options.fetchFn ?? fetch;
141
+
142
+ const pkce = generatePkceCodes();
143
+
144
+ return new Promise<{ apiKey: string }>((resolve, reject) => {
145
+ let resolved = false;
146
+ let timeoutTimer: NodeJS.Timeout | null = null;
147
+
148
+ const cleanup = () => {
149
+ if (timeoutTimer) {
150
+ clearTimeout(timeoutTimer);
151
+ timeoutTimer = null;
152
+ }
153
+ try {
154
+ server.close();
155
+ } catch {
156
+ // Ignore close errors
157
+ }
158
+ };
159
+
160
+ const server = http.createServer(async (req, res) => {
161
+ try {
162
+ const reqUrl = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
163
+ if (reqUrl.pathname !== '/callback') {
164
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
165
+ res.end('Not Found');
166
+ return;
167
+ }
168
+
169
+ const code = reqUrl.searchParams.get('code');
170
+ const state = reqUrl.searchParams.get('state');
171
+
172
+ if (!state || state !== pkce.state) {
173
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
174
+ res.end(
175
+ '<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
176
+ '<h2 style="color:#ef4444;">Authorization Error: State Mismatch</h2>' +
177
+ '<p>The received CSRF verification state did not match the session. Please try again.</p>' +
178
+ '</body></html>'
179
+ );
180
+ if (!resolved) {
181
+ resolved = true;
182
+ cleanup();
183
+ reject(new OpenRouterAuthError('State mismatch detected during OpenRouter callback.'));
184
+ }
185
+ return;
186
+ }
187
+
188
+ if (!code) {
189
+ res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
190
+ res.end(
191
+ '<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
192
+ '<h2 style="color:#ef4444;">Authorization Failed</h2>' +
193
+ '<p>No authorization code was returned by OpenRouter.</p>' +
194
+ '</body></html>'
195
+ );
196
+ if (!resolved) {
197
+ resolved = true;
198
+ cleanup();
199
+ reject(new OpenRouterAuthError('No authorization code returned from callback.'));
200
+ }
201
+ return;
202
+ }
203
+
204
+ // Send friendly HTML response to user's browser
205
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
206
+ res.end(
207
+ '<html><body style="font-family:sans-serif;padding:40px;background:#0d1117;color:#c9d1d9;text-align:center;">' +
208
+ '<h2 style="color:#2ea043;margin-bottom:12px;">Causyne Agent Connected Successfully</h2>' +
209
+ '<p style="font-size:16px;color:#8b949e;">Your OpenRouter account has been authorized. You can close this window and return to your terminal.</p>' +
210
+ '</body></html>'
211
+ );
212
+
213
+ // Perform token exchange
214
+ const apiKey = await exchangeCodeForApiKey(code, pkce.codeVerifier, fetchFn);
215
+
216
+ if (!resolved) {
217
+ resolved = true;
218
+ cleanup();
219
+ resolve({ apiKey });
220
+ }
221
+ } catch (err: any) {
222
+ if (!resolved) {
223
+ resolved = true;
224
+ cleanup();
225
+ reject(err);
226
+ }
227
+ }
228
+ });
229
+
230
+ server.on('error', (err) => {
231
+ if (!resolved) {
232
+ resolved = true;
233
+ cleanup();
234
+ reject(new OpenRouterAuthError(`Loopback server failed to bind: ${err.message}`));
235
+ }
236
+ });
237
+
238
+ server.listen(0, '127.0.0.1', () => {
239
+ const addr = server.address();
240
+ if (!addr || typeof addr === 'string') {
241
+ cleanup();
242
+ reject(new OpenRouterAuthError('Failed to retrieve loopback server port.'));
243
+ return;
244
+ }
245
+
246
+ const callbackUrl = `http://127.0.0.1:${addr.port}/callback`;
247
+ const authUrl = buildAuthorizationUrl(callbackUrl, pkce.codeChallenge, pkce.state);
248
+
249
+ if (options.onUrlReady) {
250
+ options.onUrlReady(authUrl);
251
+ }
252
+
253
+ if (openBrowser) {
254
+ openWithNativeOS(authUrl).catch(() => {
255
+ // If browser opening fails, user can copy URL manually
256
+ });
257
+ }
258
+
259
+ timeoutTimer = setTimeout(() => {
260
+ if (!resolved) {
261
+ resolved = true;
262
+ cleanup();
263
+ reject(new OpenRouterAuthError(`Authorization timed out after ${Math.round(timeoutMs / 1000)} seconds.`));
264
+ }
265
+ }, timeoutMs);
266
+ });
267
+ });
268
+ }
269
+
270
+ /**
271
+ * Mask an API key for safe display in logs and status screens.
272
+ */
273
+ export function maskApiKey(key: string): string {
274
+ const clean = (key || '').trim();
275
+ if (!clean) return 'none';
276
+ if (clean.length <= 8) return '********';
277
+ return `${clean.slice(0, 7)}...${clean.slice(-4)}`;
278
+ }
279
+
280
+ /**
281
+ * Save user OpenRouter key into local encrypted configuration vault.
282
+ */
283
+ export function saveOpenRouterKey(
284
+ apiKey: string,
285
+ options: {
286
+ dataCollection?: 'deny' | 'allow';
287
+ setAsActive?: boolean;
288
+ store?: { loadConfig(): any; saveConfig(cfg: any): void };
289
+ } = {}
290
+ ): Record<string, any> {
291
+ const cleanKey = (apiKey || '').trim();
292
+ if (!cleanKey) {
293
+ throw new OpenRouterAuthError('Cannot save an empty OpenRouter API key.');
294
+ }
295
+
296
+ const store = options.store || { loadConfig, saveConfig };
297
+ const currentConfig = store.loadConfig() || {};
298
+ const providerKeys = {
299
+ ...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
300
+ };
301
+
302
+ providerKeys['openrouter'] = cleanKey;
303
+ currentConfig.providerKeys = providerKeys;
304
+
305
+ if (options.dataCollection) {
306
+ currentConfig.openrouterDataCollection = options.dataCollection;
307
+ } else if (!currentConfig.openrouterDataCollection) {
308
+ currentConfig.openrouterDataCollection = 'deny';
309
+ }
310
+
311
+ if (options.setAsActive) {
312
+ currentConfig.provider = 'openrouter';
313
+ currentConfig.model = OPENROUTER_FREE_MODEL;
314
+ currentConfig.apiKey = cleanKey;
315
+ }
316
+
317
+ store.saveConfig(currentConfig);
318
+ return currentConfig;
319
+ }
320
+
321
+ /**
322
+ * Disconnect OpenRouter credentials from local vault.
323
+ */
324
+ export function disconnectOpenRouter(store: { loadConfig(): any; saveConfig(cfg: any): void } = { loadConfig, saveConfig }): Record<string, any> {
325
+ const currentConfig = store.loadConfig() || {};
326
+ const providerKeys = {
327
+ ...(currentConfig.providerKeys && typeof currentConfig.providerKeys === 'object' ? currentConfig.providerKeys : {})
328
+ };
329
+
330
+ delete providerKeys['openrouter'];
331
+ currentConfig.providerKeys = providerKeys;
332
+
333
+ if (currentConfig.provider === 'openrouter') {
334
+ currentConfig.provider = 'deepseek';
335
+ currentConfig.model = 'deepseek-chat';
336
+ currentConfig.apiKey = providerKeys['deepseek'] || '';
337
+ }
338
+
339
+ store.saveConfig(currentConfig);
340
+ return currentConfig;
341
+ }
342
+
343
+ /**
344
+ * Retrieve live OpenRouter connection and privacy status.
345
+ */
346
+ export function getOpenRouterStatus(cfg?: Record<string, any>): OpenRouterStatus {
347
+ const config = cfg || loadConfig() || {};
348
+ const vaultKey = config.providerKeys?.openrouter || (config.provider === 'openrouter' ? config.apiKey : '');
349
+ const envKey = process.env.OPENROUTER_API_KEY;
350
+
351
+ const connectedKey = vaultKey || envKey || '';
352
+ const isConnected = Boolean(connectedKey);
353
+ const isActive = config.provider === 'openrouter';
354
+ const currentModel = isActive ? (config.model || OPENROUTER_FREE_MODEL) : OPENROUTER_FREE_MODEL;
355
+ const dataCollection: 'deny' | 'allow' = config.openrouterDataCollection === 'allow' ? 'allow' : 'deny';
356
+
357
+ return {
358
+ connected: isConnected,
359
+ active: isActive,
360
+ model: currentModel,
361
+ dataCollection,
362
+ maskedKey: isConnected ? maskApiKey(connectedKey) : undefined,
363
+ keySource: vaultKey ? 'vault' : (envKey ? 'environment' : undefined)
364
+ };
365
+ }
366
+
367
+ /**
368
+ * Update user's OpenRouter data collection preference.
369
+ */
370
+ export function setOpenRouterDataCollection(
371
+ preference: 'deny' | 'allow',
372
+ store: { loadConfig(): any; saveConfig(cfg: any): void } = { loadConfig, saveConfig }
373
+ ): Record<string, any> {
374
+ const config = store.loadConfig() || {};
375
+ config.openrouterDataCollection = preference;
376
+ store.saveConfig(config);
377
+ return config;
378
+ }
package/src/cliMode.js CHANGED
@@ -637,16 +637,19 @@ export async function chatMode({ home = false } = {}) {
637
637
  paint('muted', ' Run /setup or select setup from the home menu to configure your provider.\n'));
638
638
  continue;
639
639
  }
640
- await loop.run();
640
+ try {
641
+ await loop.run();
642
+ } finally {
643
+ conn.stopSpinner();
644
+ // Active skill remains persistent across turns until explicitly cleared via /skill clear or another skill is selected.
645
+ if (surface) surface.setSessionInfo({ activeSkill: loop.activeSkill });
646
+ conn.renderer.turnFooter(Date.now() - startedAt);
647
+ }
641
648
  } finally {
642
649
  // Must be released on the error path too, or one failed turn leaves the
643
650
  // prompt permanently queueing and the chat looks hung.
644
651
  if (prompt) prompt.setBusy(false);
645
652
  }
646
- conn.stopSpinner();
647
- // Active skill remains persistent across turns until explicitly cleared via /skill clear or another skill is selected.
648
- if (surface) surface.setSessionInfo({ activeSkill: loop.activeSkill });
649
- conn.renderer.turnFooter(Date.now() - startedAt);
650
653
  }
651
654
 
652
655
  process.exit(0);
package/src/commands.js CHANGED
@@ -52,6 +52,15 @@ import { getPackageVersion } from './version.js';
52
52
  import { listGroups } from './checkpoints.js';
53
53
  import { renameSession, getSession } from './sessionStore.js';
54
54
  import { listPlugins } from './plugins/pluginManager.js';
55
+ import {
56
+ getOpenRouterStatus,
57
+ startLoopbackAuth,
58
+ saveOpenRouterKey,
59
+ disconnectOpenRouter,
60
+ setOpenRouterDataCollection,
61
+ buildAuthorizationUrl,
62
+ generatePkceCodes
63
+ } from './auth/openrouterAuth.js';
55
64
 
56
65
  export const SCOPES = ['local'];
57
66
 
@@ -1588,6 +1597,113 @@ export const COMMANDS = [
1588
1597
  }
1589
1598
  },
1590
1599
 
1600
+ {
1601
+ name: 'openrouter',
1602
+ aliases: ['free'],
1603
+ scope: 'local',
1604
+ usage: '/openrouter [status | connect | disconnect | privacy <deny|allow>]',
1605
+ description: 'Connect OpenRouter account for free cloud AI models (openrouter/free)',
1606
+ dialogTitle: 'OpenRouter Free',
1607
+ complete: () => [
1608
+ { value: 'status', label: 'status', description: 'view connection and data collection status' },
1609
+ { value: 'connect', label: 'connect', description: 'connect your OpenRouter account via OAuth PKCE' },
1610
+ { value: 'privacy deny', label: 'privacy deny', description: 'strict privacy (default): restrict provider data collection' },
1611
+ { value: 'privacy allow', label: 'privacy allow', description: 'permit routing to training-eligible providers' },
1612
+ { value: 'disconnect', label: 'disconnect', description: 'disconnect OpenRouter account' }
1613
+ ],
1614
+ run: async (argv, ctx = {}) => {
1615
+ const sub = (argv[0] || 'status').toLowerCase();
1616
+
1617
+ if (sub === 'status') {
1618
+ const status = getOpenRouterStatus();
1619
+ const lines = [
1620
+ 'OpenRouter Free Models — Connection Status',
1621
+ '',
1622
+ ` • Connected : ${status.connected ? 'YES' : 'NO'}`,
1623
+ ` • Active Provider : ${status.active ? 'YES (OpenRouter is active)' : 'NO (using ' + (loadConfig().provider || 'none') + ')'}`,
1624
+ ` • Default Model : ${status.model}`,
1625
+ ` • Privacy Policy : provider.data_collection = "${status.dataCollection}"`,
1626
+ ` • Stored Key : ${status.maskedKey || 'none'} (${status.keySource || 'unconfigured'})`,
1627
+ '',
1628
+ status.connected
1629
+ ? 'OpenRouter Free is ready. Run "/model openrouter/free" to select it.'
1630
+ : 'To connect your account, run "/openrouter connect".'
1631
+ ];
1632
+ return ok(lines.join('\n'));
1633
+ }
1634
+
1635
+ if (sub === 'disconnect') {
1636
+ disconnectOpenRouter();
1637
+ return ok('OpenRouter account disconnected and API key removed from local vault.');
1638
+ }
1639
+
1640
+ if (sub === 'privacy' || sub === 'data-collection') {
1641
+ const val = (argv[1] || '').toLowerCase();
1642
+ if (val !== 'deny' && val !== 'allow') {
1643
+ return fail('Usage: /openrouter privacy <deny | allow>');
1644
+ }
1645
+ setOpenRouterDataCollection(val);
1646
+ const disclosure = val === 'allow'
1647
+ ? '\nNotice: Setting data_collection to "allow" means training-eligible providers are eligible for routing. It does not by itself establish user consent to model training or guarantee training occurs.'
1648
+ : '\nNotice: Strict privacy active. Provider data collection for model training is strictly denied.';
1649
+ return ok(`OpenRouter data_collection policy set to "${val}".${disclosure}`);
1650
+ }
1651
+
1652
+ if (sub === 'connect') {
1653
+ const candidateKey = argv[1];
1654
+ if (candidateKey && candidateKey.trim()) {
1655
+ saveOpenRouterKey(candidateKey.trim(), { setAsActive: true });
1656
+ return ok('Saved OpenRouter API key and switched active model to openrouter/free.');
1657
+ }
1658
+
1659
+ const isSsh = Boolean(process.env.SSH_CLIENT || process.env.SSH_TTY || process.env.SSH_CONNECTION);
1660
+ if (isSsh) {
1661
+ const pkce = generatePkceCodes();
1662
+ const authUrl = buildAuthorizationUrl('urn:ietf:wg:oauth:2.0:oob', pkce.codeChallenge, pkce.state);
1663
+ const lines = [
1664
+ 'SSH / Headless environment detected.',
1665
+ 'Please open the following authorization URL in your browser:',
1666
+ '',
1667
+ ` ${authUrl}`,
1668
+ '',
1669
+ 'After authorizing, configure your key using:',
1670
+ ' /openrouter connect <your-api-key>'
1671
+ ];
1672
+ return ok(lines.join('\n'));
1673
+ }
1674
+
1675
+ try {
1676
+ const resultPromise = startLoopbackAuth({
1677
+ timeoutMs: 120_000,
1678
+ openBrowser: true
1679
+ });
1680
+
1681
+ if (ctx.prompt && typeof ctx.prompt.scheduleDraw === 'function') {
1682
+ ctx.prompt.scheduleDraw();
1683
+ }
1684
+
1685
+ const { apiKey } = await resultPromise;
1686
+ saveOpenRouterKey(apiKey, { setAsActive: true });
1687
+
1688
+ if (ctx.loop) {
1689
+ ctx.loop.config = loadConfig();
1690
+ }
1691
+ if (ctx.prompt) {
1692
+ if (typeof ctx.prompt.updateModel === 'function') {
1693
+ ctx.prompt.updateModel('openrouter', 'openrouter/free');
1694
+ }
1695
+ }
1696
+
1697
+ return ok('Successfully authenticated with OpenRouter! Now using openrouter/free.');
1698
+ } catch (err) {
1699
+ return fail(`OpenRouter connection error: ${err.message || err}\nFallback: run "/openrouter connect <api-key>" with an API key from https://openrouter.ai/keys`);
1700
+ }
1701
+ }
1702
+
1703
+ return fail('Usage: /openrouter [status | connect | disconnect | privacy <deny|allow>]');
1704
+ }
1705
+ },
1706
+
1591
1707
  {
1592
1708
  name: 'mcp',
1593
1709
  scope: 'local',
@@ -46,6 +46,8 @@ export function normalizeProviderKey(provider) {
46
46
  return 'moonshot';
47
47
  if (p === 'muse' || p === 'meta')
48
48
  return 'muse';
49
+ if (p === 'openrouter' || p === 'openrouter-free' || p === 'openrouter/free')
50
+ return 'openrouter';
49
51
  if (p === 'openai-compatible' || p === 'custom')
50
52
  return 'openai-compatible';
51
53
  if (p === 'antigravity' || p === 'agy')
@@ -253,6 +255,13 @@ export function getAvailableProvidersOverview(config = {}) {
253
255
  defaultModel: DEFAULT_MODEL_BY_PROVIDER['ollama'] || 'llama3.3',
254
256
  models: MODEL_CATALOGUE['Ollama (Local)'] ? [...MODEL_CATALOGUE['Ollama (Local)']] : []
255
257
  },
258
+ {
259
+ id: 'openrouter',
260
+ label: 'OpenRouter (Free Models)',
261
+ envVar: 'OPENROUTER_API_KEY',
262
+ defaultModel: DEFAULT_MODEL_BY_PROVIDER['openrouter'] || 'openrouter/free',
263
+ models: MODEL_CATALOGUE['OpenRouter (Free)'] ? [...MODEL_CATALOGUE['OpenRouter (Free)']] : ['openrouter/free']
264
+ },
256
265
  {
257
266
  id: 'xai',
258
267
  label: 'xAI (Grok)',
@@ -999,6 +1008,44 @@ export async function fetchLiveModels(provider, config = {}) {
999
1008
  return data.data.map((m) => m.id || '').filter((id) => /^(qwen)/i.test(id)).sort();
1000
1009
  }
1001
1010
  }
1011
+ if (norm === 'openrouter') {
1012
+ const host = (baseUrl || 'https://openrouter.ai/api/v1').replace(/\/+$/, '');
1013
+ const headers = {
1014
+ 'HTTP-Referer': 'https://causyne.com',
1015
+ 'X-Title': 'Causyne Agent'
1016
+ };
1017
+ if (apiKey)
1018
+ headers['Authorization'] = `Bearer ${apiKey}`;
1019
+ const res = await fetch(`${host}/models`, {
1020
+ headers,
1021
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1022
+ });
1023
+ if (!res.ok)
1024
+ return ['openrouter/free'];
1025
+ const data = (await res.json());
1026
+ if (Array.isArray(data.data)) {
1027
+ const freeModels = data.data
1028
+ .filter((m) => {
1029
+ if (!m.id)
1030
+ return false;
1031
+ if (m.id === 'openrouter/free')
1032
+ return true;
1033
+ if (m.id.endsWith(':free'))
1034
+ return true;
1035
+ const promptZero = m.pricing?.prompt === '0' || m.pricing?.prompt === 0;
1036
+ const complZero = m.pricing?.completion === '0' || m.pricing?.completion === 0;
1037
+ return promptZero && complZero;
1038
+ })
1039
+ .map((m) => m.id || '')
1040
+ .filter(Boolean)
1041
+ .sort();
1042
+ if (!freeModels.includes('openrouter/free')) {
1043
+ freeModels.unshift('openrouter/free');
1044
+ }
1045
+ return freeModels;
1046
+ }
1047
+ return ['openrouter/free'];
1048
+ }
1002
1049
  if (norm === 'openai-compatible') {
1003
1050
  if (!baseUrl)
1004
1051
  return [];
@@ -71,6 +71,7 @@ export function normalizeProviderKey(provider: string): string {
71
71
  if (p === 'xai' || p === 'grok') return 'xai';
72
72
  if (p === 'moonshot' || p === 'kimi') return 'moonshot';
73
73
  if (p === 'muse' || p === 'meta') return 'muse';
74
+ if (p === 'openrouter' || p === 'openrouter-free' || p === 'openrouter/free') return 'openrouter';
74
75
  if (p === 'openai-compatible' || p === 'custom') return 'openai-compatible';
75
76
  if (p === 'antigravity' || p === 'agy') return 'antigravity';
76
77
  if (p === 'acp') return 'acp';
@@ -316,6 +317,13 @@ export function getAvailableProvidersOverview(
316
317
  defaultModel: DEFAULT_MODEL_BY_PROVIDER['ollama'] || 'llama3.3',
317
318
  models: MODEL_CATALOGUE['Ollama (Local)'] ? [...MODEL_CATALOGUE['Ollama (Local)']] : []
318
319
  },
320
+ {
321
+ id: 'openrouter',
322
+ label: 'OpenRouter (Free Models)',
323
+ envVar: 'OPENROUTER_API_KEY',
324
+ defaultModel: DEFAULT_MODEL_BY_PROVIDER['openrouter'] || 'openrouter/free',
325
+ models: MODEL_CATALOGUE['OpenRouter (Free)'] ? [...MODEL_CATALOGUE['OpenRouter (Free)']] : ['openrouter/free']
326
+ },
319
327
  {
320
328
  id: 'xai',
321
329
  label: 'xAI (Grok)',
@@ -1066,6 +1074,45 @@ export async function fetchLiveModels(
1066
1074
  }
1067
1075
  }
1068
1076
 
1077
+ if (norm === 'openrouter') {
1078
+ const host = (baseUrl || 'https://openrouter.ai/api/v1').replace(/\/+$/, '');
1079
+ const headers: Record<string, string> = {
1080
+ 'HTTP-Referer': 'https://causyne.com',
1081
+ 'X-Title': 'Causyne Agent'
1082
+ };
1083
+ if (apiKey) headers['Authorization'] = `Bearer ${apiKey}`;
1084
+ const res = await fetch(`${host}/models`, {
1085
+ headers,
1086
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS)
1087
+ });
1088
+ if (!res.ok) return ['openrouter/free'];
1089
+ const data = (await res.json()) as {
1090
+ data?: Array<{
1091
+ id?: string;
1092
+ pricing?: { prompt?: string | number; completion?: string | number };
1093
+ }>;
1094
+ };
1095
+ if (Array.isArray(data.data)) {
1096
+ const freeModels = data.data
1097
+ .filter((m) => {
1098
+ if (!m.id) return false;
1099
+ if (m.id === 'openrouter/free') return true;
1100
+ if (m.id.endsWith(':free')) return true;
1101
+ const promptZero = m.pricing?.prompt === '0' || m.pricing?.prompt === 0;
1102
+ const complZero = m.pricing?.completion === '0' || m.pricing?.completion === 0;
1103
+ return promptZero && complZero;
1104
+ })
1105
+ .map((m) => m.id || '')
1106
+ .filter(Boolean)
1107
+ .sort();
1108
+ if (!freeModels.includes('openrouter/free')) {
1109
+ freeModels.unshift('openrouter/free');
1110
+ }
1111
+ return freeModels;
1112
+ }
1113
+ return ['openrouter/free'];
1114
+ }
1115
+
1069
1116
  if (norm === 'openai-compatible') {
1070
1117
  if (!baseUrl) return [];
1071
1118
  const host = baseUrl.replace(/\/+$/, '');