@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.
@@ -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, disconnectOpenRouter } 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' | 'action' | 'toggle';
22
23
  providerId: string;
23
24
  modelId: string;
24
25
  providerLabel: string;
@@ -28,7 +29,7 @@ export interface ModelPickerItemValue {
28
29
  envVar?: string | undefined;
29
30
  setupInstruction?: string | undefined;
30
31
  isToggle?: boolean | undefined;
31
- action?: 'expand' | 'collapse' | undefined;
32
+ action?: 'expand' | 'collapse' | 'disconnect' | undefined;
32
33
  peerKey?: string | undefined;
33
34
  }
34
35
 
@@ -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,28 +193,27 @@ 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}`
201
- : p.id === 'openrouter'
202
- ? `Free Cloud · ${p.label} ${p.isConfigured ? '(ready)' : '(connect account)'}`
203
- : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
205
+ : `BYOK · ${p.label} ${p.isConfigured ? '(configured)' : '(needs key)'}`;
204
206
 
205
207
  const models = Array.isArray(p.models) && p.models.length > 0 ? p.models : [p.defaultModel];
206
208
  for (const m of models) {
207
209
  const isCurrent = isCurrentProvider && activeModel === m;
208
210
  const desc = isCurrent
209
- ? (p.id === 'openrouter' ? '● active (free)' : '● active')
211
+ ? '● active'
210
212
  : p.id === 'ollama'
211
213
  ? 'local'
212
- : p.id === 'openrouter'
213
- ? (p.isConfigured ? 'free inference' : 'connect OpenRouter')
214
- : p.isConfigured
215
- ? 'configured'
216
- : 'needs API key';
214
+ : p.isConfigured
215
+ ? 'configured'
216
+ : 'needs API key';
217
217
  items.push({
218
218
  id: `${p.id}/${m}`,
219
219
  label: m,
@@ -234,15 +234,72 @@ export function buildModelPickerItems(
234
234
  }
235
235
  }
236
236
 
237
+ // 3. Free Cloud Models (OpenRouter Free)
238
+ if (tab === 'all' || tab === 'free') {
239
+ const isConfigured = Boolean(
240
+ (config.provider === 'openrouter' && config.apiKey) ||
241
+ config.providerKeys?.openrouter ||
242
+ process.env.OPENROUTER_API_KEY
243
+ );
244
+ const isCurrentProvider = activeProvider === 'openrouter';
245
+
246
+ const catTitle = isConfigured
247
+ ? 'Free Cloud · OpenRouter (ready)'
248
+ : 'Free Cloud · OpenRouter (connect account)';
249
+
250
+ const isCurrent = isCurrentProvider && (activeModel === 'openrouter/free' || !activeModel);
251
+ const desc = isCurrent
252
+ ? '● active (free)'
253
+ : (isConfigured ? 'free inference' : 'connect OpenRouter · free');
254
+
255
+ // Canonical auto-routing free model (OpenRouter automatically routes free inference)
256
+ items.push({
257
+ id: 'openrouter/openrouter/free',
258
+ label: 'openrouter/free',
259
+ category: catTitle,
260
+ description: desc,
261
+ value: {
262
+ type: 'free',
263
+ providerId: 'openrouter',
264
+ modelId: 'openrouter/free',
265
+ providerLabel: 'OpenRouter Free',
266
+ installed: true,
267
+ isCurrent,
268
+ isConfigured,
269
+ envVar: 'OPENROUTER_API_KEY'
270
+ }
271
+ });
272
+
273
+ // Provide first-class in-place Disconnect / Unlink action when configured
274
+ if (isConfigured) {
275
+ items.push({
276
+ id: 'openrouter:disconnect',
277
+ label: 'Disconnect OpenRouter (unlink account)',
278
+ category: catTitle,
279
+ description: 'unlink & remove key',
280
+ value: {
281
+ type: 'action',
282
+ providerId: 'openrouter',
283
+ modelId: 'disconnect',
284
+ providerLabel: 'OpenRouter Free',
285
+ installed: true,
286
+ isCurrent: false,
287
+ isConfigured: true,
288
+ action: 'disconnect'
289
+ }
290
+ });
291
+ }
292
+ }
293
+
237
294
  return items;
238
295
  }
239
296
 
240
297
  /**
241
- * Sovereign Model Picker Layer with dual-tab support (| ACP | BYOK |)
298
+ * Sovereign Model Picker Layer with tri-tab support (| ACP | BYOK | FREE |)
242
299
  * and interactive 10-model pagination.
243
300
  */
244
301
  export class ModelPickerLayer extends SelectLayer {
245
- public activeTab: 'acp' | 'byok';
302
+ public activeTab: 'acp' | 'byok' | 'free';
246
303
  public config: Record<string, any>;
247
304
  public overview: ProviderOverview;
248
305
  public expandedPeers: Set<string>;
@@ -261,20 +318,22 @@ export class ModelPickerLayer extends SelectLayer {
261
318
  onPick: (item: ModelPickerItem | null) => void;
262
319
  }) {
263
320
  const activeProvider = (options.config.provider || '').toLowerCase().trim();
264
- const initialTab: 'acp' | 'byok' =
265
- activeProvider === 'antigravity' ||
266
- activeProvider === 'agy' ||
267
- activeProvider === 'acp' ||
268
- activeProvider.startsWith('acp/')
269
- ? 'acp'
270
- : 'byok';
321
+ const initialTab: 'acp' | 'byok' | 'free' =
322
+ activeProvider === 'openrouter'
323
+ ? 'free'
324
+ : (activeProvider === 'antigravity' ||
325
+ activeProvider === 'agy' ||
326
+ activeProvider === 'acp' ||
327
+ activeProvider.startsWith('acp/')
328
+ ? 'acp'
329
+ : 'byok');
271
330
 
272
331
  const expandedPeers = new Set<string>();
273
332
  const allItems = buildModelPickerItems(options.config, options.overview, { tab: 'all', maxAcpPerPeer: Infinity });
274
333
 
275
334
  super({
276
335
  title: 'Select Model',
277
- placeholder: 'type to filter (e.g. gemini, sonnet, opencode)…',
336
+ placeholder: 'type to filter (e.g. gemini, sonnet, openrouter)…',
278
337
  emptyText: 'No models matched your search in this tab',
279
338
  items: allItems,
280
339
  width: 78,
@@ -319,7 +378,7 @@ export class ModelPickerLayer extends SelectLayer {
319
378
  }
320
379
  }
321
380
 
322
- switchTab(tab: 'acp' | 'byok'): void {
381
+ switchTab(tab: 'acp' | 'byok' | 'free'): void {
323
382
  if (this.activeTab === tab) return;
324
383
  this.activeTab = tab;
325
384
  this.list.refilter();
@@ -355,7 +414,8 @@ export class ModelPickerLayer extends SelectLayer {
355
414
  body(width: number, height: number): string[] {
356
415
  const tabACP = this.activeTab === 'acp' ? paint('accent', bold('● ACP')) : dim('ACP');
357
416
  const tabBYOK = this.activeTab === 'byok' ? paint('accent', bold('● BYOK')) : dim('BYOK');
358
- const tabBar = ` | ${tabACP} | ${tabBYOK} | ${dim('(Tab / ← → switch tab)')}`;
417
+ const tabFREE = this.activeTab === 'free' ? paint('accent', bold('● FREE')) : dim('FREE');
418
+ const tabBar = ` | ${tabACP} | ${tabBYOK} | ${tabFREE} | ${dim('(Tab / ← → switch tab)')}`;
359
419
  const separator = paint('rule', GLYPHS.hLine.repeat(Math.max(4, width)));
360
420
 
361
421
  const listHeight = Math.max(1, height - 2);
@@ -370,29 +430,43 @@ export class ModelPickerLayer extends SelectLayer {
370
430
 
371
431
  // 1. Tab switching via Tab, Left/Right arrows, or PgLeft/PgRight mappings
372
432
  if (event.name === 'tab') {
373
- this.switchTab(this.activeTab === 'acp' ? 'byok' : 'acp');
433
+ if (this.activeTab === 'acp') this.switchTab('byok');
434
+ else if (this.activeTab === 'byok') this.switchTab('free');
435
+ else this.switchTab('acp');
374
436
  return 'handled';
375
437
  }
376
438
 
377
- if (event.name === 'left' && this.activeTab === 'byok') {
439
+ if (event.name === 'left') {
378
440
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
379
- this.switchTab('acp');
380
- return 'handled';
441
+ if (this.activeTab === 'free') {
442
+ this.switchTab('byok');
443
+ return 'handled';
444
+ } else if (this.activeTab === 'byok') {
445
+ this.switchTab('acp');
446
+ return 'handled';
447
+ }
381
448
  }
382
449
  }
383
- if (event.name === 'right' && this.activeTab === 'acp') {
450
+ if (event.name === 'right') {
384
451
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
385
- this.switchTab('byok');
386
- return 'handled';
452
+ if (this.activeTab === 'acp') {
453
+ this.switchTab('byok');
454
+ return 'handled';
455
+ } else if (this.activeTab === 'byok') {
456
+ this.switchTab('free');
457
+ return 'handled';
458
+ }
387
459
  }
388
460
  }
389
461
 
390
462
  if (event.name === '[' || (event.name === 'pageup' && (event.shift || event.alt || event.ctrl))) {
391
- this.switchTab('acp');
463
+ if (this.activeTab === 'free') this.switchTab('byok');
464
+ else if (this.activeTab === 'byok') this.switchTab('acp');
392
465
  return 'handled';
393
466
  }
394
467
  if (event.name === ']' || (event.name === 'pagedown' && (event.shift || event.alt || event.ctrl))) {
395
- this.switchTab('byok');
468
+ if (this.activeTab === 'acp') this.switchTab('byok');
469
+ else if (this.activeTab === 'byok') this.switchTab('free');
396
470
  return 'handled';
397
471
  }
398
472
 
@@ -500,7 +574,122 @@ export async function runInteractiveModelPicker(
500
574
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
501
575
  }
502
576
 
503
- // Case 2: BYOK Provider (Cloud or Local API)
577
+ // Case 2: Disconnect / Unlink action (e.g. Disconnect OpenRouter)
578
+ if (target.action === 'disconnect' || target.modelId === 'disconnect') {
579
+ const updatedConfig = disconnectOpenRouter(store);
580
+ if (options.loop) {
581
+ options.loop.config = updatedConfig;
582
+ if (typeof options.loop.updateTierLimits === 'function') {
583
+ options.loop.updateTierLimits();
584
+ }
585
+ }
586
+ notifyPrompt(updatedConfig.provider || 'antigravity', updatedConfig.model || 'Gemini 3.8 Flash (Low)');
587
+ return (
588
+ `✓ Disconnected OpenRouter. Account and API credentials have been unlinked from Causyne Agent.\n` +
589
+ `Active model reverted to ${updatedConfig.provider || 'antigravity'} / ${updatedConfig.model || 'Gemini 3.8 Flash (Low)'}.`
590
+ );
591
+ }
592
+
593
+ // Case 3: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
594
+ if (target.providerId === 'openrouter') {
595
+ let existingKey = '';
596
+ const providerKeys: Record<string, string> =
597
+ config['providerKeys'] && typeof config['providerKeys'] === 'object' ? config['providerKeys'] : {};
598
+ if (config['provider'] === 'openrouter' && typeof config['apiKey'] === 'string' && config['apiKey']) {
599
+ existingKey = config['apiKey'];
600
+ } else if (providerKeys['openrouter']) {
601
+ existingKey = providerKeys['openrouter'];
602
+ } else if (process.env.OPENROUTER_API_KEY) {
603
+ existingKey = process.env.OPENROUTER_API_KEY;
604
+ }
605
+
606
+ if (existingKey) {
607
+ config['provider'] = 'openrouter';
608
+ config['model'] = target.modelId;
609
+ config['apiKey'] = existingKey;
610
+ config['providerKeys'] = providerKeys;
611
+ config['providerKeys']['openrouter'] = existingKey;
612
+ store.saveConfig(config);
613
+
614
+ void resolveAvailableModels('openrouter', { ...config, apiKey: existingKey }, true).catch(() => {});
615
+
616
+ if (options.loop) {
617
+ options.loop.config = config;
618
+ if (typeof options.loop.updateTierLimits === 'function') {
619
+ options.loop.updateTierLimits();
620
+ }
621
+ }
622
+ notifyPrompt('openrouter', target.modelId);
623
+ return `Now using OpenRouter Free / ${target.modelId}.`;
624
+ }
625
+
626
+ // Unconfigured OpenRouter: prompt where pressing Enter once immediately starts OAuth redirect
627
+ const entered = await new Promise<string | null>((resolve) => {
628
+ const layer = new InputLayer({
629
+ title: 'Connect OpenRouter · Free Cloud Inference',
630
+ lines: [
631
+ 'Press [Enter] to open your browser and authorize with OpenRouter.',
632
+ 'Or paste an existing OpenRouter API key (Esc to cancel).'
633
+ ],
634
+ mask: false,
635
+ placeholder: 'Press Enter to authorize in browser, or paste API key',
636
+ onSubmit: resolve,
637
+ onCancel: () => resolve(null)
638
+ });
639
+ prompt.openLayer(layer);
640
+ });
641
+
642
+ if (entered === null) {
643
+ return 'Cancelled. OpenRouter connection was not completed. Model was not changed.';
644
+ }
645
+
646
+ const cleanInput = entered.trim();
647
+ if (!cleanInput) {
648
+ // User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
649
+ try {
650
+ if (process.stdout.isTTY) {
651
+ process.stdout.write('\r \x1b[36m●\x1b[0m Opening browser for OpenRouter OAuth authorization…\n');
652
+ process.stdout.write(' \x1b[90mWaiting for authorization on 127.0.0.1 (timeout: 120s)…\x1b[0m\n');
653
+ }
654
+ const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
655
+ saveOpenRouterKey(apiKey, { setAsActive: true, store });
656
+
657
+ const updatedConfig = store.loadConfig();
658
+ if (options.loop) {
659
+ options.loop.config = updatedConfig;
660
+ if (typeof options.loop.updateTierLimits === 'function') {
661
+ options.loop.updateTierLimits();
662
+ }
663
+ }
664
+ notifyPrompt('openrouter', target.modelId);
665
+ return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
666
+ } catch (err: any) {
667
+ return (
668
+ `✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
669
+ `Solutions:\n` +
670
+ `1. Check that your browser can open local URLs (http://127.0.0.1).\n` +
671
+ `2. For headless or SSH environments, create a free API key at:\n` +
672
+ ` https://openrouter.ai/keys\n` +
673
+ ` and run: /openrouter connect <your-api-key>`
674
+ );
675
+ }
676
+ }
677
+
678
+ // User pasted an API key
679
+ await showConfiguringAnimation('OpenRouter');
680
+ saveOpenRouterKey(cleanInput, { setAsActive: true, store });
681
+ const updatedConfig = store.loadConfig();
682
+ if (options.loop) {
683
+ options.loop.config = updatedConfig;
684
+ if (typeof options.loop.updateTierLimits === 'function') {
685
+ options.loop.updateTierLimits();
686
+ }
687
+ }
688
+ notifyPrompt('openrouter', target.modelId);
689
+ return `✓ Saved API key. Now using OpenRouter Free / ${target.modelId}.`;
690
+ }
691
+
692
+ // Case 3: BYOK Provider (Cloud or Local API)
504
693
  let existingKey = '';
505
694
  const providerKeys: Record<string, string> = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
506
695
  if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {