@causyne/agent 1.20.70 → 1.20.72

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.
@@ -80,6 +80,8 @@ export function getCuratedModels(provider) {
80
80
  const norm = normalizeProviderKey(provider);
81
81
  if (norm === 'antigravity')
82
82
  return Object.keys(BASELINE_ANTIGRAVITY_MODELS);
83
+ if (norm === 'openrouter')
84
+ return ['openrouter/free'];
83
85
  if (norm === 'pi')
84
86
  return [...(MODEL_CATALOGUE['Pi (Local Peer)'] || ['default'])];
85
87
  const peer = peerIdFromProviderKey(norm);
@@ -1009,41 +1011,10 @@ export async function fetchLiveModels(provider, config = {}) {
1009
1011
  }
1010
1012
  }
1011
1013
  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
- }
1014
+ // OpenRouter automatically routes free inference server-side via openrouter/free.
1015
+ // Auto-detection of transient individual :free endpoints is disabled specifically
1016
+ // for OpenRouter to prevent routing failures and privacy mismatches, while
1017
+ // keeping ACP and local peer dynamic auto-detection fully active.
1047
1018
  return ['openrouter/free'];
1048
1019
  }
1049
1020
  if (norm === 'openai-compatible') {
@@ -1106,6 +1077,9 @@ function resolveEffectiveApiKey(norm, config = {}) {
1106
1077
  */
1107
1078
  export async function resolveAvailableModels(provider, config = {}, forceRefresh = false) {
1108
1079
  const norm = normalizeProviderKey(provider);
1080
+ if (norm === 'openrouter') {
1081
+ return { models: ['openrouter/free'], source: 'catalogue' };
1082
+ }
1109
1083
  const curated = getCuratedModels(norm);
1110
1084
  const localAgent = isLocalOrAcpProvider(norm);
1111
1085
  const effectiveKey = resolveEffectiveApiKey(norm, config);
@@ -101,6 +101,7 @@ export function peerIdFromProviderKey(provider: string): string | null {
101
101
  export function getCuratedModels(provider: string): string[] {
102
102
  const norm = normalizeProviderKey(provider);
103
103
  if (norm === 'antigravity') return Object.keys(BASELINE_ANTIGRAVITY_MODELS);
104
+ if (norm === 'openrouter') return ['openrouter/free'];
104
105
  if (norm === 'pi') return [...(MODEL_CATALOGUE['Pi (Local Peer)'] || ['default'])];
105
106
  const peer = peerIdFromProviderKey(norm);
106
107
  if (peer) return [...(PEER_MODEL_CATALOGUE[peer] ?? [])];
@@ -1075,41 +1076,10 @@ export async function fetchLiveModels(
1075
1076
  }
1076
1077
 
1077
1078
  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
- }
1079
+ // OpenRouter automatically routes free inference server-side via openrouter/free.
1080
+ // Auto-detection of transient individual :free endpoints is disabled specifically
1081
+ // for OpenRouter to prevent routing failures and privacy mismatches, while
1082
+ // keeping ACP and local peer dynamic auto-detection fully active.
1113
1083
  return ['openrouter/free'];
1114
1084
  }
1115
1085
 
@@ -1179,6 +1149,9 @@ export async function resolveAvailableModels(
1179
1149
  forceRefresh = false
1180
1150
  ): Promise<ModelResolutionResult> {
1181
1151
  const norm = normalizeProviderKey(provider);
1152
+ if (norm === 'openrouter') {
1153
+ return { models: ['openrouter/free'], source: 'catalogue' };
1154
+ }
1182
1155
  const curated = getCuratedModels(norm);
1183
1156
  const localAgent = isLocalOrAcpProvider(norm);
1184
1157
  const effectiveKey = resolveEffectiveApiKey(norm, config);
@@ -9,6 +9,7 @@ import { paint, bold, dim, GLYPHS } from './theme.js';
9
9
  // @ts-expect-error untyped local TUI selectList
10
10
  import { fuzzyFilter } from './selectList.js';
11
11
  import { loadConfig, saveConfig } from '../config.js';
12
+ import { startLoopbackAuth, saveOpenRouterKey, disconnectOpenRouter } from '../auth/openrouterAuth.js';
12
13
  import { getAvailableProvidersOverview, resolveAvailableProvidersOverview, resolveAvailableModels } from '../dynamicCatalogue.js';
13
14
  async function showConfiguringAnimation(providerLabel) {
14
15
  if (!process.stdout.isTTY)
@@ -130,27 +131,26 @@ export function buildModelPickerItems(config, overview, options = {}) {
130
131
  }
131
132
  }
132
133
  }
133
- // 2. BYOK Providers (Cloud & Local APIs)
134
+ // 2. BYOK Providers (Cloud & Local APIs) — excluding OpenRouter in BYOK tab
134
135
  if (tab === 'all' || tab === 'byok') {
135
136
  for (const p of overview.byok) {
137
+ if (p.id === 'openrouter') {
138
+ continue;
139
+ }
136
140
  const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
137
141
  const catTitle = p.id === 'ollama'
138
142
  ? `BYOK · ${p.label}`
139
- : p.id === 'openrouter'
140
- ? `Free Cloud · ${p.label} ${p.isConfigured ? '(ready)' : '(connect account)'}`
141
- : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
143
+ : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
142
144
  const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
143
145
  for (const m of models) {
144
146
  const isCurrent = isCurrentProvider && activeModel === m;
145
147
  const desc = isCurrent
146
- ? (p.id === 'openrouter' ? '● active (free)' : '● active')
148
+ ? '● active'
147
149
  : p.id === 'ollama'
148
150
  ? 'local'
149
- : p.id === 'openrouter'
150
- ? (p.isConfigured ? 'free inference' : 'connect OpenRouter')
151
- : p.isConfigured
152
- ? 'configured'
153
- : 'needs API key';
151
+ : p.isConfigured
152
+ ? 'configured'
153
+ : 'needs API key';
154
154
  items.push({
155
155
  id: `${p.id}/${m}`,
156
156
  label: m,
@@ -170,10 +170,60 @@ export function buildModelPickerItems(config, overview, options = {}) {
170
170
  }
171
171
  }
172
172
  }
173
+ // 3. Free Cloud Models (OpenRouter Free)
174
+ if (tab === 'all' || tab === 'free') {
175
+ const isConfigured = Boolean((config.provider === 'openrouter' && config.apiKey) ||
176
+ config.providerKeys?.openrouter ||
177
+ process.env.OPENROUTER_API_KEY);
178
+ const isCurrentProvider = activeProvider === 'openrouter';
179
+ const catTitle = isConfigured
180
+ ? 'Free Cloud · OpenRouter (ready)'
181
+ : 'Free Cloud · OpenRouter (connect account)';
182
+ const isCurrent = isCurrentProvider && (activeModel === 'openrouter/free' || !activeModel);
183
+ const desc = isCurrent
184
+ ? '● active (free)'
185
+ : (isConfigured ? 'free inference' : 'connect OpenRouter · free');
186
+ // Canonical auto-routing free model (OpenRouter automatically routes free inference)
187
+ items.push({
188
+ id: 'openrouter/openrouter/free',
189
+ label: 'openrouter/free',
190
+ category: catTitle,
191
+ description: desc,
192
+ value: {
193
+ type: 'free',
194
+ providerId: 'openrouter',
195
+ modelId: 'openrouter/free',
196
+ providerLabel: 'OpenRouter Free',
197
+ installed: true,
198
+ isCurrent,
199
+ isConfigured,
200
+ envVar: 'OPENROUTER_API_KEY'
201
+ }
202
+ });
203
+ // Provide first-class in-place Disconnect / Unlink action when configured
204
+ if (isConfigured) {
205
+ items.push({
206
+ id: 'openrouter:disconnect',
207
+ label: 'Disconnect OpenRouter (unlink account)',
208
+ category: catTitle,
209
+ description: 'unlink & remove key',
210
+ value: {
211
+ type: 'action',
212
+ providerId: 'openrouter',
213
+ modelId: 'disconnect',
214
+ providerLabel: 'OpenRouter Free',
215
+ installed: true,
216
+ isCurrent: false,
217
+ isConfigured: true,
218
+ action: 'disconnect'
219
+ }
220
+ });
221
+ }
222
+ }
173
223
  return items;
174
224
  }
175
225
  /**
176
- * Sovereign Model Picker Layer with dual-tab support (| ACP | BYOK |)
226
+ * Sovereign Model Picker Layer with tri-tab support (| ACP | BYOK | FREE |)
177
227
  * and interactive 10-model pagination.
178
228
  */
179
229
  export class ModelPickerLayer extends SelectLayer {
@@ -185,17 +235,19 @@ export class ModelPickerLayer extends SelectLayer {
185
235
  allItems;
186
236
  constructor(options) {
187
237
  const activeProvider = (options.config.provider || '').toLowerCase().trim();
188
- const initialTab = activeProvider === 'antigravity' ||
189
- activeProvider === 'agy' ||
190
- activeProvider === 'acp' ||
191
- activeProvider.startsWith('acp/')
192
- ? 'acp'
193
- : 'byok';
238
+ const initialTab = activeProvider === 'openrouter'
239
+ ? 'free'
240
+ : (activeProvider === 'antigravity' ||
241
+ activeProvider === 'agy' ||
242
+ activeProvider === 'acp' ||
243
+ activeProvider.startsWith('acp/')
244
+ ? 'acp'
245
+ : 'byok');
194
246
  const expandedPeers = new Set();
195
247
  const allItems = buildModelPickerItems(options.config, options.overview, { tab: 'all', maxAcpPerPeer: Infinity });
196
248
  super({
197
249
  title: 'Select Model',
198
- placeholder: 'type to filter (e.g. gemini, sonnet, opencode)…',
250
+ placeholder: 'type to filter (e.g. gemini, sonnet, openrouter)…',
199
251
  emptyText: 'No models matched your search in this tab',
200
252
  items: allItems,
201
253
  width: 78,
@@ -271,7 +323,8 @@ export class ModelPickerLayer extends SelectLayer {
271
323
  body(width, height) {
272
324
  const tabACP = this.activeTab === 'acp' ? paint('accent', bold('● ACP')) : dim('ACP');
273
325
  const tabBYOK = this.activeTab === 'byok' ? paint('accent', bold('● BYOK')) : dim('BYOK');
274
- const tabBar = ` | ${tabACP} | ${tabBYOK} | ${dim('(Tab / ← → switch tab)')}`;
326
+ const tabFREE = this.activeTab === 'free' ? paint('accent', bold('● FREE')) : dim('FREE');
327
+ const tabBar = ` | ${tabACP} | ${tabBYOK} | ${tabFREE} | ${dim('(Tab / ← → switch tab)')}`;
275
328
  const separator = paint('rule', GLYPHS.hLine.repeat(Math.max(4, width)));
276
329
  const listHeight = Math.max(1, height - 2);
277
330
  const { rows } = this.list.render(width, listHeight);
@@ -283,27 +336,50 @@ export class ModelPickerLayer extends SelectLayer {
283
336
  return null;
284
337
  // 1. Tab switching via Tab, Left/Right arrows, or PgLeft/PgRight mappings
285
338
  if (event.name === 'tab') {
286
- this.switchTab(this.activeTab === 'acp' ? 'byok' : 'acp');
339
+ if (this.activeTab === 'acp')
340
+ this.switchTab('byok');
341
+ else if (this.activeTab === 'byok')
342
+ this.switchTab('free');
343
+ else
344
+ this.switchTab('acp');
287
345
  return 'handled';
288
346
  }
289
- if (event.name === 'left' && this.activeTab === 'byok') {
347
+ if (event.name === 'left') {
290
348
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
291
- this.switchTab('acp');
292
- return 'handled';
349
+ if (this.activeTab === 'free') {
350
+ this.switchTab('byok');
351
+ return 'handled';
352
+ }
353
+ else if (this.activeTab === 'byok') {
354
+ this.switchTab('acp');
355
+ return 'handled';
356
+ }
293
357
  }
294
358
  }
295
- if (event.name === 'right' && this.activeTab === 'acp') {
359
+ if (event.name === 'right') {
296
360
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
297
- this.switchTab('byok');
298
- return 'handled';
361
+ if (this.activeTab === 'acp') {
362
+ this.switchTab('byok');
363
+ return 'handled';
364
+ }
365
+ else if (this.activeTab === 'byok') {
366
+ this.switchTab('free');
367
+ return 'handled';
368
+ }
299
369
  }
300
370
  }
301
371
  if (event.name === '[' || (event.name === 'pageup' && (event.shift || event.alt || event.ctrl))) {
302
- this.switchTab('acp');
372
+ if (this.activeTab === 'free')
373
+ this.switchTab('byok');
374
+ else if (this.activeTab === 'byok')
375
+ this.switchTab('acp');
303
376
  return 'handled';
304
377
  }
305
378
  if (event.name === ']' || (event.name === 'pagedown' && (event.shift || event.alt || event.ctrl))) {
306
- this.switchTab('byok');
379
+ if (this.activeTab === 'acp')
380
+ this.switchTab('byok');
381
+ else if (this.activeTab === 'byok')
382
+ this.switchTab('free');
307
383
  return 'handled';
308
384
  }
309
385
  // 2. Delegate to SelectList for navigation / query typing
@@ -395,7 +471,110 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
395
471
  notifyPrompt(target.providerId, target.modelId);
396
472
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
397
473
  }
398
- // Case 2: BYOK Provider (Cloud or Local API)
474
+ // Case 2: Disconnect / Unlink action (e.g. Disconnect OpenRouter)
475
+ if (target.action === 'disconnect' || target.modelId === 'disconnect') {
476
+ const updatedConfig = disconnectOpenRouter(store);
477
+ if (options.loop) {
478
+ options.loop.config = updatedConfig;
479
+ if (typeof options.loop.updateTierLimits === 'function') {
480
+ options.loop.updateTierLimits();
481
+ }
482
+ }
483
+ notifyPrompt(updatedConfig.provider || 'antigravity', updatedConfig.model || 'Gemini 3.8 Flash (Low)');
484
+ return (`✓ Disconnected OpenRouter. Account and API credentials have been unlinked from Causyne Agent.\n` +
485
+ `Active model reverted to ${updatedConfig.provider || 'antigravity'} / ${updatedConfig.model || 'Gemini 3.8 Flash (Low)'}.`);
486
+ }
487
+ // Case 3: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
488
+ if (target.providerId === 'openrouter') {
489
+ let existingKey = '';
490
+ const providerKeys = config['providerKeys'] && typeof config['providerKeys'] === 'object' ? config['providerKeys'] : {};
491
+ if (config['provider'] === 'openrouter' && typeof config['apiKey'] === 'string' && config['apiKey']) {
492
+ existingKey = config['apiKey'];
493
+ }
494
+ else if (providerKeys['openrouter']) {
495
+ existingKey = providerKeys['openrouter'];
496
+ }
497
+ else if (process.env.OPENROUTER_API_KEY) {
498
+ existingKey = process.env.OPENROUTER_API_KEY;
499
+ }
500
+ if (existingKey) {
501
+ config['provider'] = 'openrouter';
502
+ config['model'] = target.modelId;
503
+ config['apiKey'] = existingKey;
504
+ config['providerKeys'] = providerKeys;
505
+ config['providerKeys']['openrouter'] = existingKey;
506
+ store.saveConfig(config);
507
+ void resolveAvailableModels('openrouter', { ...config, apiKey: existingKey }, true).catch(() => { });
508
+ if (options.loop) {
509
+ options.loop.config = config;
510
+ if (typeof options.loop.updateTierLimits === 'function') {
511
+ options.loop.updateTierLimits();
512
+ }
513
+ }
514
+ notifyPrompt('openrouter', target.modelId);
515
+ return `Now using OpenRouter Free / ${target.modelId}.`;
516
+ }
517
+ // Unconfigured OpenRouter: prompt where pressing Enter once immediately starts OAuth redirect
518
+ const entered = await new Promise((resolve) => {
519
+ const layer = new InputLayer({
520
+ title: 'Connect OpenRouter · Free Cloud Inference',
521
+ lines: [
522
+ 'Press [Enter] to open your browser and authorize with OpenRouter.',
523
+ 'Or paste an existing OpenRouter API key (Esc to cancel).'
524
+ ],
525
+ mask: false,
526
+ placeholder: 'Press Enter to authorize in browser, or paste API key',
527
+ onSubmit: resolve,
528
+ onCancel: () => resolve(null)
529
+ });
530
+ prompt.openLayer(layer);
531
+ });
532
+ if (entered === null) {
533
+ return 'Cancelled. OpenRouter connection was not completed. Model was not changed.';
534
+ }
535
+ const cleanInput = entered.trim();
536
+ if (!cleanInput) {
537
+ // User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
538
+ try {
539
+ if (process.stdout.isTTY) {
540
+ process.stdout.write('\r \x1b[36m●\x1b[0m Opening browser for OpenRouter OAuth authorization…\n');
541
+ process.stdout.write(' \x1b[90mWaiting for authorization on 127.0.0.1 (timeout: 120s)…\x1b[0m\n');
542
+ }
543
+ const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
544
+ saveOpenRouterKey(apiKey, { setAsActive: true, store });
545
+ const updatedConfig = store.loadConfig();
546
+ if (options.loop) {
547
+ options.loop.config = updatedConfig;
548
+ if (typeof options.loop.updateTierLimits === 'function') {
549
+ options.loop.updateTierLimits();
550
+ }
551
+ }
552
+ notifyPrompt('openrouter', target.modelId);
553
+ return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
554
+ }
555
+ catch (err) {
556
+ return (`✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
557
+ `Solutions:\n` +
558
+ `1. Check that your browser can open local URLs (http://127.0.0.1).\n` +
559
+ `2. For headless or SSH environments, create a free API key at:\n` +
560
+ ` https://openrouter.ai/keys\n` +
561
+ ` and run: /openrouter connect <your-api-key>`);
562
+ }
563
+ }
564
+ // User pasted an API key
565
+ await showConfiguringAnimation('OpenRouter');
566
+ saveOpenRouterKey(cleanInput, { setAsActive: true, store });
567
+ const updatedConfig = store.loadConfig();
568
+ if (options.loop) {
569
+ options.loop.config = updatedConfig;
570
+ if (typeof options.loop.updateTierLimits === 'function') {
571
+ options.loop.updateTierLimits();
572
+ }
573
+ }
574
+ notifyPrompt('openrouter', target.modelId);
575
+ return `✓ Saved API key. Now using OpenRouter Free / ${target.modelId}.`;
576
+ }
577
+ // Case 3: BYOK Provider (Cloud or Local API)
399
578
  let existingKey = '';
400
579
  const providerKeys = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
401
580
  if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {