@causyne/agent 1.20.69 → 1.20.71

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.
@@ -10,6 +10,7 @@ import { paint, bold, dim, GLYPHS } from './theme.js';
10
10
  // @ts-expect-error untyped local TUI selectList
11
11
  import { fuzzyFilter } from './selectList.js';
12
12
  import { loadConfig, saveConfig } from '../config.js';
13
+ import { startLoopbackAuth, saveOpenRouterKey } from '../auth/openrouterAuth.js';
13
14
  import {
14
15
  getAvailableProvidersOverview,
15
16
  resolveAvailableProvidersOverview,
@@ -18,7 +19,7 @@ import {
18
19
  } from '../dynamicCatalogue.js';
19
20
 
20
21
  export interface ModelPickerItemValue {
21
- type: 'acp' | 'byok' | 'toggle';
22
+ type: 'acp' | 'byok' | 'free' | 'toggle';
22
23
  providerId: string;
23
24
  modelId: string;
24
25
  providerLabel: string;
@@ -60,7 +61,7 @@ export interface InteractiveModelPickerOptions {
60
61
  }
61
62
 
62
63
  export interface BuildModelPickerOptions {
63
- tab?: 'acp' | 'byok' | 'all' | undefined;
64
+ tab?: 'acp' | 'byok' | 'free' | 'all' | undefined;
64
65
  expandedPeers?: Set<string> | undefined;
65
66
  maxAcpPerPeer?: number | undefined;
66
67
  }
@@ -192,9 +193,12 @@ export function buildModelPickerItems(
192
193
  }
193
194
  }
194
195
 
195
- // 2. BYOK Providers (Cloud & Local APIs)
196
+ // 2. BYOK Providers (Cloud & Local APIs) — excluding OpenRouter in BYOK tab
196
197
  if (tab === 'all' || tab === 'byok') {
197
198
  for (const p of overview.byok) {
199
+ if (p.id === 'openrouter') {
200
+ continue;
201
+ }
198
202
  const isCurrentProvider = activeProvider === p.id || (p.id === 'qwen' && activeProvider === 'dashscope-byok');
199
203
  const catTitle = p.id === 'ollama'
200
204
  ? `BYOK · ${p.label}`
@@ -203,7 +207,13 @@ export function buildModelPickerItems(
203
207
  const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
204
208
  for (const m of models) {
205
209
  const isCurrent = isCurrentProvider && activeModel === m;
206
- const desc = isCurrent ? '● active' : (p.id === 'ollama' ? 'local' : (p.isConfigured ? 'configured' : 'needs API key'));
210
+ const desc = isCurrent
211
+ ? '● active'
212
+ : p.id === 'ollama'
213
+ ? 'local'
214
+ : p.isConfigured
215
+ ? 'configured'
216
+ : 'needs API key';
207
217
  items.push({
208
218
  id: `${p.id}/${m}`,
209
219
  label: m,
@@ -224,15 +234,56 @@ export function buildModelPickerItems(
224
234
  }
225
235
  }
226
236
 
237
+ // 3. Free Cloud Models (OpenRouter Free)
238
+ if (tab === 'all' || tab === 'free') {
239
+ const openrouterPeer = overview.byok.find(p => p.id === 'openrouter');
240
+ const isConfigured = Boolean(
241
+ (config.provider === 'openrouter' && config.apiKey) ||
242
+ config.providerKeys?.openrouter ||
243
+ process.env.OPENROUTER_API_KEY
244
+ );
245
+ const isCurrentProvider = activeProvider === 'openrouter';
246
+ const models = openrouterPeer?.models && openrouterPeer.models.length > 0
247
+ ? openrouterPeer.models
248
+ : ['openrouter/free'];
249
+
250
+ const catTitle = isConfigured
251
+ ? 'Free Cloud · OpenRouter (ready)'
252
+ : 'Free Cloud · OpenRouter (connect account)';
253
+
254
+ for (const m of models) {
255
+ const isCurrent = isCurrentProvider && activeModel === m;
256
+ const desc = isCurrent
257
+ ? '● active (free)'
258
+ : (isConfigured ? 'free inference' : 'connect OpenRouter · free');
259
+ items.push({
260
+ id: `openrouter/${m}`,
261
+ label: m,
262
+ category: catTitle,
263
+ description: desc,
264
+ value: {
265
+ type: 'free',
266
+ providerId: 'openrouter',
267
+ modelId: m,
268
+ providerLabel: 'OpenRouter Free',
269
+ installed: true,
270
+ isCurrent,
271
+ isConfigured,
272
+ envVar: 'OPENROUTER_API_KEY'
273
+ }
274
+ });
275
+ }
276
+ }
277
+
227
278
  return items;
228
279
  }
229
280
 
230
281
  /**
231
- * Sovereign Model Picker Layer with dual-tab support (| ACP | BYOK |)
282
+ * Sovereign Model Picker Layer with tri-tab support (| ACP | BYOK | FREE |)
232
283
  * and interactive 10-model pagination.
233
284
  */
234
285
  export class ModelPickerLayer extends SelectLayer {
235
- public activeTab: 'acp' | 'byok';
286
+ public activeTab: 'acp' | 'byok' | 'free';
236
287
  public config: Record<string, any>;
237
288
  public overview: ProviderOverview;
238
289
  public expandedPeers: Set<string>;
@@ -251,20 +302,22 @@ export class ModelPickerLayer extends SelectLayer {
251
302
  onPick: (item: ModelPickerItem | null) => void;
252
303
  }) {
253
304
  const activeProvider = (options.config.provider || '').toLowerCase().trim();
254
- const initialTab: 'acp' | 'byok' =
255
- activeProvider === 'antigravity' ||
256
- activeProvider === 'agy' ||
257
- activeProvider === 'acp' ||
258
- activeProvider.startsWith('acp/')
259
- ? 'acp'
260
- : 'byok';
305
+ const initialTab: 'acp' | 'byok' | 'free' =
306
+ activeProvider === 'openrouter'
307
+ ? 'free'
308
+ : (activeProvider === 'antigravity' ||
309
+ activeProvider === 'agy' ||
310
+ activeProvider === 'acp' ||
311
+ activeProvider.startsWith('acp/')
312
+ ? 'acp'
313
+ : 'byok');
261
314
 
262
315
  const expandedPeers = new Set<string>();
263
316
  const allItems = buildModelPickerItems(options.config, options.overview, { tab: 'all', maxAcpPerPeer: Infinity });
264
317
 
265
318
  super({
266
319
  title: 'Select Model',
267
- placeholder: 'type to filter (e.g. gemini, sonnet, opencode)…',
320
+ placeholder: 'type to filter (e.g. gemini, sonnet, openrouter)…',
268
321
  emptyText: 'No models matched your search in this tab',
269
322
  items: allItems,
270
323
  width: 78,
@@ -309,7 +362,7 @@ export class ModelPickerLayer extends SelectLayer {
309
362
  }
310
363
  }
311
364
 
312
- switchTab(tab: 'acp' | 'byok'): void {
365
+ switchTab(tab: 'acp' | 'byok' | 'free'): void {
313
366
  if (this.activeTab === tab) return;
314
367
  this.activeTab = tab;
315
368
  this.list.refilter();
@@ -345,7 +398,8 @@ export class ModelPickerLayer extends SelectLayer {
345
398
  body(width: number, height: number): string[] {
346
399
  const tabACP = this.activeTab === 'acp' ? paint('accent', bold('● ACP')) : dim('ACP');
347
400
  const tabBYOK = this.activeTab === 'byok' ? paint('accent', bold('● BYOK')) : dim('BYOK');
348
- const tabBar = ` | ${tabACP} | ${tabBYOK} | ${dim('(Tab / ← → switch tab)')}`;
401
+ const tabFREE = this.activeTab === 'free' ? paint('accent', bold('● FREE')) : dim('FREE');
402
+ const tabBar = ` | ${tabACP} | ${tabBYOK} | ${tabFREE} | ${dim('(Tab / ← → switch tab)')}`;
349
403
  const separator = paint('rule', GLYPHS.hLine.repeat(Math.max(4, width)));
350
404
 
351
405
  const listHeight = Math.max(1, height - 2);
@@ -360,29 +414,43 @@ export class ModelPickerLayer extends SelectLayer {
360
414
 
361
415
  // 1. Tab switching via Tab, Left/Right arrows, or PgLeft/PgRight mappings
362
416
  if (event.name === 'tab') {
363
- this.switchTab(this.activeTab === 'acp' ? 'byok' : 'acp');
417
+ if (this.activeTab === 'acp') this.switchTab('byok');
418
+ else if (this.activeTab === 'byok') this.switchTab('free');
419
+ else this.switchTab('acp');
364
420
  return 'handled';
365
421
  }
366
422
 
367
- if (event.name === 'left' && this.activeTab === 'byok') {
423
+ if (event.name === 'left') {
368
424
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
369
- this.switchTab('acp');
370
- return 'handled';
425
+ if (this.activeTab === 'free') {
426
+ this.switchTab('byok');
427
+ return 'handled';
428
+ } else if (this.activeTab === 'byok') {
429
+ this.switchTab('acp');
430
+ return 'handled';
431
+ }
371
432
  }
372
433
  }
373
- if (event.name === 'right' && this.activeTab === 'acp') {
434
+ if (event.name === 'right') {
374
435
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
375
- this.switchTab('byok');
376
- return 'handled';
436
+ if (this.activeTab === 'acp') {
437
+ this.switchTab('byok');
438
+ return 'handled';
439
+ } else if (this.activeTab === 'byok') {
440
+ this.switchTab('free');
441
+ return 'handled';
442
+ }
377
443
  }
378
444
  }
379
445
 
380
446
  if (event.name === '[' || (event.name === 'pageup' && (event.shift || event.alt || event.ctrl))) {
381
- this.switchTab('acp');
447
+ if (this.activeTab === 'free') this.switchTab('byok');
448
+ else if (this.activeTab === 'byok') this.switchTab('acp');
382
449
  return 'handled';
383
450
  }
384
451
  if (event.name === ']' || (event.name === 'pagedown' && (event.shift || event.alt || event.ctrl))) {
385
- this.switchTab('byok');
452
+ if (this.activeTab === 'acp') this.switchTab('byok');
453
+ else if (this.activeTab === 'byok') this.switchTab('free');
386
454
  return 'handled';
387
455
  }
388
456
 
@@ -490,7 +558,106 @@ export async function runInteractiveModelPicker(
490
558
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
491
559
  }
492
560
 
493
- // Case 2: BYOK Provider (Cloud or Local API)
561
+ // Case 2: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
562
+ if (target.providerId === 'openrouter') {
563
+ let existingKey = '';
564
+ const providerKeys: Record<string, string> =
565
+ config['providerKeys'] && typeof config['providerKeys'] === 'object' ? config['providerKeys'] : {};
566
+ if (config['provider'] === 'openrouter' && typeof config['apiKey'] === 'string' && config['apiKey']) {
567
+ existingKey = config['apiKey'];
568
+ } else if (providerKeys['openrouter']) {
569
+ existingKey = providerKeys['openrouter'];
570
+ } else if (process.env.OPENROUTER_API_KEY) {
571
+ existingKey = process.env.OPENROUTER_API_KEY;
572
+ }
573
+
574
+ if (existingKey) {
575
+ config['provider'] = 'openrouter';
576
+ config['model'] = target.modelId;
577
+ config['apiKey'] = existingKey;
578
+ config['providerKeys'] = providerKeys;
579
+ config['providerKeys']['openrouter'] = existingKey;
580
+ store.saveConfig(config);
581
+
582
+ void resolveAvailableModels('openrouter', { ...config, apiKey: existingKey }, true).catch(() => {});
583
+
584
+ if (options.loop) {
585
+ options.loop.config = config;
586
+ if (typeof options.loop.updateTierLimits === 'function') {
587
+ options.loop.updateTierLimits();
588
+ }
589
+ }
590
+ notifyPrompt('openrouter', target.modelId);
591
+ return `Now using OpenRouter Free / ${target.modelId}.`;
592
+ }
593
+
594
+ // Unconfigured OpenRouter: prompt where pressing Enter once immediately starts OAuth redirect
595
+ const entered = await new Promise<string | null>((resolve) => {
596
+ const layer = new InputLayer({
597
+ title: 'Connect OpenRouter · Free Cloud Inference',
598
+ lines: [
599
+ 'Press [Enter] to open your browser and authorize with OpenRouter.',
600
+ 'Or paste an existing OpenRouter API key (Esc to cancel).'
601
+ ],
602
+ mask: false,
603
+ placeholder: 'Press Enter to authorize in browser, or paste API key',
604
+ onSubmit: resolve,
605
+ onCancel: () => resolve(null)
606
+ });
607
+ prompt.openLayer(layer);
608
+ });
609
+
610
+ if (entered === null) {
611
+ return 'Cancelled. OpenRouter connection was not completed. Model was not changed.';
612
+ }
613
+
614
+ const cleanInput = entered.trim();
615
+ if (!cleanInput) {
616
+ // User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
617
+ try {
618
+ if (process.stdout.isTTY) {
619
+ process.stdout.write('\r \x1b[36m●\x1b[0m Opening browser for OpenRouter OAuth authorization…\n');
620
+ process.stdout.write(' \x1b[90mWaiting for authorization on 127.0.0.1 (timeout: 120s)…\x1b[0m\n');
621
+ }
622
+ const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
623
+ saveOpenRouterKey(apiKey, { setAsActive: true, store });
624
+
625
+ const updatedConfig = store.loadConfig();
626
+ if (options.loop) {
627
+ options.loop.config = updatedConfig;
628
+ if (typeof options.loop.updateTierLimits === 'function') {
629
+ options.loop.updateTierLimits();
630
+ }
631
+ }
632
+ notifyPrompt('openrouter', target.modelId);
633
+ return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
634
+ } catch (err: any) {
635
+ return (
636
+ `✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
637
+ `Solutions:\n` +
638
+ `1. Check that your browser can open local URLs (http://127.0.0.1).\n` +
639
+ `2. For headless or SSH environments, create a free API key at:\n` +
640
+ ` https://openrouter.ai/keys\n` +
641
+ ` and run: /openrouter connect <your-api-key>`
642
+ );
643
+ }
644
+ }
645
+
646
+ // User pasted an API key
647
+ await showConfiguringAnimation('OpenRouter');
648
+ saveOpenRouterKey(cleanInput, { setAsActive: true, store });
649
+ const updatedConfig = store.loadConfig();
650
+ if (options.loop) {
651
+ options.loop.config = updatedConfig;
652
+ if (typeof options.loop.updateTierLimits === 'function') {
653
+ options.loop.updateTierLimits();
654
+ }
655
+ }
656
+ notifyPrompt('openrouter', target.modelId);
657
+ return `✓ Saved API key. Now using OpenRouter Free / ${target.modelId}.`;
658
+ }
659
+
660
+ // Case 3: BYOK Provider (Cloud or Local API)
494
661
  let existingKey = '';
495
662
  const providerKeys: Record<string, string> = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
496
663
  if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {