@causyne/agent 1.20.71 → 1.20.73

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/src/commands.js CHANGED
@@ -1633,8 +1633,31 @@ export const COMMANDS = [
1633
1633
  }
1634
1634
 
1635
1635
  if (sub === 'disconnect') {
1636
- disconnectOpenRouter();
1637
- return ok('OpenRouter account disconnected and API key removed from local vault.');
1636
+ const updatedConfig = disconnectOpenRouter();
1637
+ if (ctx.loop) {
1638
+ ctx.loop.config = updatedConfig;
1639
+ if (typeof ctx.loop.updateTierLimits === 'function') {
1640
+ ctx.loop.updateTierLimits();
1641
+ }
1642
+ }
1643
+ if (ctx.prompt) {
1644
+ if (typeof ctx.prompt.updateModel === 'function') {
1645
+ ctx.prompt.updateModel(
1646
+ updatedConfig.provider || 'antigravity',
1647
+ updatedConfig.model || 'Gemini 3.8 Flash (Low)'
1648
+ );
1649
+ } else if (ctx.prompt.renderer?.status) {
1650
+ ctx.prompt.renderer.status.setSession({
1651
+ provider: updatedConfig.provider || 'antigravity',
1652
+ model: updatedConfig.model || 'Gemini 3.8 Flash (Low)'
1653
+ });
1654
+ if (typeof ctx.prompt.scheduleDraw === 'function') ctx.prompt.scheduleDraw();
1655
+ }
1656
+ }
1657
+ return ok(
1658
+ `OpenRouter account disconnected and API key removed from local vault.\n` +
1659
+ `Active model reverted to ${updatedConfig.provider || 'antigravity'} / ${updatedConfig.model || 'Gemini 3.8 Flash (Low)'}.`
1660
+ );
1638
1661
  }
1639
1662
 
1640
1663
  if (sub === 'privacy' || sub === 'data-collection') {
@@ -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);
@@ -10,6 +10,23 @@ const originalConsole = {
10
10
  const originalStderrWrite = process.stderr?.write
11
11
  ? process.stderr.write.bind(process.stderr)
12
12
  : null;
13
+ const originalStdoutWrite = process.stdout?.write
14
+ ? process.stdout.write.bind(process.stdout)
15
+ : null;
16
+ let stageInternalWriting = false;
17
+ /**
18
+ * Run a write operation with permission to write to stdout during Stage sessions.
19
+ */
20
+ export function runWithStageWrite(fn) {
21
+ const prev = stageInternalWriting;
22
+ stageInternalWriting = true;
23
+ try {
24
+ return fn();
25
+ }
26
+ finally {
27
+ stageInternalWriting = prev;
28
+ }
29
+ }
13
30
  export function isAnyStageReservedOnStdout() {
14
31
  if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
15
32
  return true;
@@ -50,6 +67,22 @@ function ensureConsoleGuardInstalled() {
50
67
  return originalStderrWrite(chunk, encodingOrCb, cb);
51
68
  });
52
69
  }
70
+ if (originalStdoutWrite && process.stdout) {
71
+ process.stdout.write = ((chunk, encodingOrCb, cb) => {
72
+ if (isAnyStageReservedOnStdout() && !stageInternalWriting) {
73
+ // Prevent rogue unmanaged writes from emitting bare newlines that scroll the stage
74
+ const text = String(chunk ?? '');
75
+ if (text.includes('\n')) {
76
+ if (typeof encodingOrCb === 'function')
77
+ encodingOrCb();
78
+ else if (typeof cb === 'function')
79
+ cb();
80
+ return true;
81
+ }
82
+ }
83
+ return originalStdoutWrite(chunk, encodingOrCb, cb);
84
+ });
85
+ }
53
86
  }
54
87
  /**
55
88
  * Track TUI Stage open/close lifecycle so raw console writes cannot corrupt the composer box.
@@ -23,6 +23,25 @@ const originalStderrWrite = process.stderr?.write
23
23
  ? process.stderr.write.bind(process.stderr)
24
24
  : null;
25
25
 
26
+ const originalStdoutWrite = process.stdout?.write
27
+ ? process.stdout.write.bind(process.stdout)
28
+ : null;
29
+
30
+ let stageInternalWriting = false;
31
+
32
+ /**
33
+ * Run a write operation with permission to write to stdout during Stage sessions.
34
+ */
35
+ export function runWithStageWrite<T>(fn: () => T): T {
36
+ const prev = stageInternalWriting;
37
+ stageInternalWriting = true;
38
+ try {
39
+ return fn();
40
+ } finally {
41
+ stageInternalWriting = prev;
42
+ }
43
+ }
44
+
26
45
  export function isAnyStageReservedOnStdout(): boolean {
27
46
  if (stageMouseSessionDepth > 0 && process.stdout?.isTTY) {
28
47
  return true;
@@ -64,6 +83,21 @@ function ensureConsoleGuardInstalled(): void {
64
83
  return (originalStderrWrite as (...a: unknown[]) => boolean)(chunk, encodingOrCb, cb);
65
84
  }) as typeof process.stderr.write;
66
85
  }
86
+
87
+ if (originalStdoutWrite && process.stdout) {
88
+ process.stdout.write = ((chunk: unknown, encodingOrCb?: unknown, cb?: unknown): boolean => {
89
+ if (isAnyStageReservedOnStdout() && !stageInternalWriting) {
90
+ // Prevent rogue unmanaged writes from emitting bare newlines that scroll the stage
91
+ const text = String(chunk ?? '');
92
+ if (text.includes('\n')) {
93
+ if (typeof encodingOrCb === 'function') (encodingOrCb as () => void)();
94
+ else if (typeof cb === 'function') (cb as () => void)();
95
+ return true;
96
+ }
97
+ }
98
+ return (originalStdoutWrite as (...a: unknown[]) => boolean)(chunk, encodingOrCb, cb);
99
+ }) as typeof process.stdout.write;
100
+ }
67
101
  }
68
102
 
69
103
  /**
@@ -9,18 +9,20 @@ 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 } from '../auth/openrouterAuth.js';
12
+ import { startLoopbackAuth, saveOpenRouterKey, disconnectOpenRouter } from '../auth/openrouterAuth.js';
13
+ import { setTransientNotice } from './consoleGuard.js';
13
14
  import { getAvailableProvidersOverview, resolveAvailableProvidersOverview, resolveAvailableModels } from '../dynamicCatalogue.js';
14
- async function showConfiguringAnimation(providerLabel) {
15
- if (!process.stdout.isTTY)
15
+ async function showConfiguringAnimation(providerLabel, promptHost) {
16
+ if (promptHost && typeof promptHost.scheduleDraw === 'function') {
17
+ promptHost.notice = `Configuring ${providerLabel} in secure local vault…`;
18
+ promptHost.scheduleDraw();
19
+ await new Promise(r => setTimeout(r, 120));
20
+ promptHost.notice = `✓ ${providerLabel} credentials saved.`;
21
+ promptHost.scheduleDraw();
16
22
  return;
17
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
18
- const text = `Configuring ${providerLabel} in secure local vault…`;
19
- for (let i = 0; i < 5; i++) {
20
- const f = frames[i % frames.length];
21
- process.stdout.write(`\r \x1b[36m${f}\x1b[0m ${text}`);
22
- await new Promise(r => setTimeout(r, 60));
23
23
  }
24
+ if (!process.stdout.isTTY)
25
+ return;
24
26
  process.stdout.write(`\r\x1b[K \x1b[32m✓\x1b[0m ${providerLabel} credentials saved.\n`);
25
27
  }
26
28
  /**
@@ -172,36 +174,50 @@ export function buildModelPickerItems(config, overview, options = {}) {
172
174
  }
173
175
  // 3. Free Cloud Models (OpenRouter Free)
174
176
  if (tab === 'all' || tab === 'free') {
175
- const openrouterPeer = overview.byok.find(p => p.id === 'openrouter');
176
177
  const isConfigured = Boolean((config.provider === 'openrouter' && config.apiKey) ||
177
178
  config.providerKeys?.openrouter ||
178
179
  process.env.OPENROUTER_API_KEY);
179
180
  const isCurrentProvider = activeProvider === 'openrouter';
180
- const models = openrouterPeer?.models && openrouterPeer.models.length > 0
181
- ? openrouterPeer.models
182
- : ['openrouter/free'];
183
181
  const catTitle = isConfigured
184
182
  ? 'Free Cloud · OpenRouter (ready)'
185
183
  : 'Free Cloud · OpenRouter (connect account)';
186
- for (const m of models) {
187
- const isCurrent = isCurrentProvider && activeModel === m;
188
- const desc = isCurrent
189
- ? '● active (free)'
190
- : (isConfigured ? 'free inference' : 'connect OpenRouter · free');
184
+ const isCurrent = isCurrentProvider && (activeModel === 'openrouter/free' || !activeModel);
185
+ const desc = isCurrent
186
+ ? '● active (free)'
187
+ : (isConfigured ? 'free inference' : 'connect OpenRouter · free');
188
+ // Canonical auto-routing free model (OpenRouter automatically routes free inference)
189
+ items.push({
190
+ id: 'openrouter/openrouter/free',
191
+ label: 'openrouter/free',
192
+ category: catTitle,
193
+ description: desc,
194
+ value: {
195
+ type: 'free',
196
+ providerId: 'openrouter',
197
+ modelId: 'openrouter/free',
198
+ providerLabel: 'OpenRouter Free',
199
+ installed: true,
200
+ isCurrent,
201
+ isConfigured,
202
+ envVar: 'OPENROUTER_API_KEY'
203
+ }
204
+ });
205
+ // Provide first-class in-place Disconnect / Unlink action when configured
206
+ if (isConfigured) {
191
207
  items.push({
192
- id: `openrouter/${m}`,
193
- label: m,
208
+ id: 'openrouter:disconnect',
209
+ label: 'Disconnect OpenRouter (unlink account)',
194
210
  category: catTitle,
195
- description: desc,
211
+ description: 'unlink & remove key',
196
212
  value: {
197
- type: 'free',
213
+ type: 'action',
198
214
  providerId: 'openrouter',
199
- modelId: m,
215
+ modelId: 'disconnect',
200
216
  providerLabel: 'OpenRouter Free',
201
217
  installed: true,
202
- isCurrent,
203
- isConfigured,
204
- envVar: 'OPENROUTER_API_KEY'
218
+ isCurrent: false,
219
+ isConfigured: true,
220
+ action: 'disconnect'
205
221
  }
206
222
  });
207
223
  }
@@ -457,7 +473,20 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
457
473
  notifyPrompt(target.providerId, target.modelId);
458
474
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
459
475
  }
460
- // Case 2: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
476
+ // Case 2: Disconnect / Unlink action (e.g. Disconnect OpenRouter)
477
+ if (target.action === 'disconnect' || target.modelId === 'disconnect') {
478
+ const updatedConfig = disconnectOpenRouter(store);
479
+ if (options.loop) {
480
+ options.loop.config = updatedConfig;
481
+ if (typeof options.loop.updateTierLimits === 'function') {
482
+ options.loop.updateTierLimits();
483
+ }
484
+ }
485
+ notifyPrompt(updatedConfig.provider || 'antigravity', updatedConfig.model || 'Gemini 3.8 Flash (Low)');
486
+ return (`✓ Disconnected OpenRouter. Account and API credentials have been unlinked from Causyne Agent.\n` +
487
+ `Active model reverted to ${updatedConfig.provider || 'antigravity'} / ${updatedConfig.model || 'Gemini 3.8 Flash (Low)'}.`);
488
+ }
489
+ // Case 3: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
461
490
  if (target.providerId === 'openrouter') {
462
491
  let existingKey = '';
463
492
  const providerKeys = config['providerKeys'] && typeof config['providerKeys'] === 'object' ? config['providerKeys'] : {};
@@ -509,10 +538,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
509
538
  if (!cleanInput) {
510
539
  // User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
511
540
  try {
512
- if (process.stdout.isTTY) {
513
- process.stdout.write('\r \x1b[36m●\x1b[0m Opening browser for OpenRouter OAuth authorization…\n');
514
- process.stdout.write(' \x1b[90mWaiting for authorization on 127.0.0.1 (timeout: 120s)…\x1b[0m\n');
515
- }
541
+ setTransientNotice(prompt, '● Opening browser for OpenRouter OAuth authorization… (Waiting on 127.0.0.1)', 120_000);
516
542
  const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
517
543
  saveOpenRouterKey(apiKey, { setAsActive: true, store });
518
544
  const updatedConfig = store.loadConfig();
@@ -523,9 +549,17 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
523
549
  }
524
550
  }
525
551
  notifyPrompt('openrouter', target.modelId);
552
+ setTransientNotice(prompt, `✓ Connected to OpenRouter successfully! Using OpenRouter Free / ${target.modelId}.`, 5000);
553
+ if (prompt.surface?.stage) {
554
+ prompt.surface.stage.invalidate();
555
+ }
556
+ if (typeof prompt.scheduleDraw === 'function') {
557
+ prompt.scheduleDraw();
558
+ }
526
559
  return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
527
560
  }
528
561
  catch (err) {
562
+ setTransientNotice(prompt, `✕ OpenRouter authorization failed: ${err?.message || err}`, 6000);
529
563
  return (`✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
530
564
  `Solutions:\n` +
531
565
  `1. Check that your browser can open local URLs (http://127.0.0.1).\n` +
@@ -535,7 +569,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
535
569
  }
536
570
  }
537
571
  // User pasted an API key
538
- await showConfiguringAnimation('OpenRouter');
572
+ await showConfiguringAnimation('OpenRouter', prompt);
539
573
  saveOpenRouterKey(cleanInput, { setAsActive: true, store });
540
574
  const updatedConfig = store.loadConfig();
541
575
  if (options.loop) {
@@ -601,7 +635,7 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
601
635
  return `Cancelled. An API key is required to use ${target.providerLabel} / ${target.modelId}. Model was not changed.`;
602
636
  }
603
637
  const cleanKey = enteredKey.trim();
604
- await showConfiguringAnimation(target.providerLabel);
638
+ await showConfiguringAnimation(target.providerLabel, prompt);
605
639
  config['provider'] = target.providerId;
606
640
  config['model'] = target.modelId;
607
641
  config['apiKey'] = cleanKey;
@@ -10,7 +10,8 @@ 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
+ import { startLoopbackAuth, saveOpenRouterKey, disconnectOpenRouter } from '../auth/openrouterAuth.js';
14
+ import { setTransientNotice } from './consoleGuard.js';
14
15
  import {
15
16
  getAvailableProvidersOverview,
16
17
  resolveAvailableProvidersOverview,
@@ -19,7 +20,7 @@ import {
19
20
  } from '../dynamicCatalogue.js';
20
21
 
21
22
  export interface ModelPickerItemValue {
22
- type: 'acp' | 'byok' | 'free' | 'toggle';
23
+ type: 'acp' | 'byok' | 'free' | 'action' | 'toggle';
23
24
  providerId: string;
24
25
  modelId: string;
25
26
  providerLabel: string;
@@ -29,7 +30,7 @@ export interface ModelPickerItemValue {
29
30
  envVar?: string | undefined;
30
31
  setupInstruction?: string | undefined;
31
32
  isToggle?: boolean | undefined;
32
- action?: 'expand' | 'collapse' | undefined;
33
+ action?: 'expand' | 'collapse' | 'disconnect' | undefined;
33
34
  peerKey?: string | undefined;
34
35
  }
35
36
 
@@ -66,15 +67,16 @@ export interface BuildModelPickerOptions {
66
67
  maxAcpPerPeer?: number | undefined;
67
68
  }
68
69
 
69
- async function showConfiguringAnimation(providerLabel: string): Promise<void> {
70
- if (!process.stdout.isTTY) return;
71
- const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
72
- const text = `Configuring ${providerLabel} in secure local vault…`;
73
- for (let i = 0; i < 5; i++) {
74
- const f = frames[i % frames.length];
75
- process.stdout.write(`\r \x1b[36m${f}\x1b[0m ${text}`);
76
- await new Promise(r => setTimeout(r, 60));
70
+ async function showConfiguringAnimation(providerLabel: string, promptHost?: any): Promise<void> {
71
+ if (promptHost && typeof promptHost.scheduleDraw === 'function') {
72
+ promptHost.notice = `Configuring ${providerLabel} in secure local vault…`;
73
+ promptHost.scheduleDraw();
74
+ await new Promise(r => setTimeout(r, 120));
75
+ promptHost.notice = `✓ ${providerLabel} credentials saved.`;
76
+ promptHost.scheduleDraw();
77
+ return;
77
78
  }
79
+ if (!process.stdout.isTTY) return;
78
80
  process.stdout.write(`\r\x1b[K \x1b[32m✓\x1b[0m ${providerLabel} credentials saved.\n`);
79
81
  }
80
82
 
@@ -236,40 +238,56 @@ export function buildModelPickerItems(
236
238
 
237
239
  // 3. Free Cloud Models (OpenRouter Free)
238
240
  if (tab === 'all' || tab === 'free') {
239
- const openrouterPeer = overview.byok.find(p => p.id === 'openrouter');
240
241
  const isConfigured = Boolean(
241
242
  (config.provider === 'openrouter' && config.apiKey) ||
242
243
  config.providerKeys?.openrouter ||
243
244
  process.env.OPENROUTER_API_KEY
244
245
  );
245
246
  const isCurrentProvider = activeProvider === 'openrouter';
246
- const models = openrouterPeer?.models && openrouterPeer.models.length > 0
247
- ? openrouterPeer.models
248
- : ['openrouter/free'];
249
247
 
250
248
  const catTitle = isConfigured
251
249
  ? 'Free Cloud · OpenRouter (ready)'
252
250
  : 'Free Cloud · OpenRouter (connect account)';
253
251
 
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');
252
+ const isCurrent = isCurrentProvider && (activeModel === 'openrouter/free' || !activeModel);
253
+ const desc = isCurrent
254
+ ? '● active (free)'
255
+ : (isConfigured ? 'free inference' : 'connect OpenRouter · free');
256
+
257
+ // Canonical auto-routing free model (OpenRouter automatically routes free inference)
258
+ items.push({
259
+ id: 'openrouter/openrouter/free',
260
+ label: 'openrouter/free',
261
+ category: catTitle,
262
+ description: desc,
263
+ value: {
264
+ type: 'free',
265
+ providerId: 'openrouter',
266
+ modelId: 'openrouter/free',
267
+ providerLabel: 'OpenRouter Free',
268
+ installed: true,
269
+ isCurrent,
270
+ isConfigured,
271
+ envVar: 'OPENROUTER_API_KEY'
272
+ }
273
+ });
274
+
275
+ // Provide first-class in-place Disconnect / Unlink action when configured
276
+ if (isConfigured) {
259
277
  items.push({
260
- id: `openrouter/${m}`,
261
- label: m,
278
+ id: 'openrouter:disconnect',
279
+ label: 'Disconnect OpenRouter (unlink account)',
262
280
  category: catTitle,
263
- description: desc,
281
+ description: 'unlink & remove key',
264
282
  value: {
265
- type: 'free',
283
+ type: 'action',
266
284
  providerId: 'openrouter',
267
- modelId: m,
285
+ modelId: 'disconnect',
268
286
  providerLabel: 'OpenRouter Free',
269
287
  installed: true,
270
- isCurrent,
271
- isConfigured,
272
- envVar: 'OPENROUTER_API_KEY'
288
+ isCurrent: false,
289
+ isConfigured: true,
290
+ action: 'disconnect'
273
291
  }
274
292
  });
275
293
  }
@@ -558,7 +576,23 @@ export async function runInteractiveModelPicker(
558
576
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
559
577
  }
560
578
 
561
- // Case 2: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
579
+ // Case 2: Disconnect / Unlink action (e.g. Disconnect OpenRouter)
580
+ if (target.action === 'disconnect' || target.modelId === 'disconnect') {
581
+ const updatedConfig = disconnectOpenRouter(store);
582
+ if (options.loop) {
583
+ options.loop.config = updatedConfig;
584
+ if (typeof options.loop.updateTierLimits === 'function') {
585
+ options.loop.updateTierLimits();
586
+ }
587
+ }
588
+ notifyPrompt(updatedConfig.provider || 'antigravity', updatedConfig.model || 'Gemini 3.8 Flash (Low)');
589
+ return (
590
+ `✓ Disconnected OpenRouter. Account and API credentials have been unlinked from Causyne Agent.\n` +
591
+ `Active model reverted to ${updatedConfig.provider || 'antigravity'} / ${updatedConfig.model || 'Gemini 3.8 Flash (Low)'}.`
592
+ );
593
+ }
594
+
595
+ // Case 3: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
562
596
  if (target.providerId === 'openrouter') {
563
597
  let existingKey = '';
564
598
  const providerKeys: Record<string, string> =
@@ -615,10 +649,7 @@ export async function runInteractiveModelPicker(
615
649
  if (!cleanInput) {
616
650
  // User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
617
651
  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
- }
652
+ setTransientNotice(prompt as any, '● Opening browser for OpenRouter OAuth authorization… (Waiting on 127.0.0.1)', 120_000);
622
653
  const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
623
654
  saveOpenRouterKey(apiKey, { setAsActive: true, store });
624
655
 
@@ -630,8 +661,16 @@ export async function runInteractiveModelPicker(
630
661
  }
631
662
  }
632
663
  notifyPrompt('openrouter', target.modelId);
664
+ setTransientNotice(prompt as any, `✓ Connected to OpenRouter successfully! Using OpenRouter Free / ${target.modelId}.`, 5000);
665
+ if ((prompt as any).surface?.stage) {
666
+ (prompt as any).surface.stage.invalidate();
667
+ }
668
+ if (typeof (prompt as any).scheduleDraw === 'function') {
669
+ (prompt as any).scheduleDraw();
670
+ }
633
671
  return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
634
672
  } catch (err: any) {
673
+ setTransientNotice(prompt as any, `✕ OpenRouter authorization failed: ${err?.message || err}`, 6000);
635
674
  return (
636
675
  `✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
637
676
  `Solutions:\n` +
@@ -644,7 +683,7 @@ export async function runInteractiveModelPicker(
644
683
  }
645
684
 
646
685
  // User pasted an API key
647
- await showConfiguringAnimation('OpenRouter');
686
+ await showConfiguringAnimation('OpenRouter', prompt);
648
687
  saveOpenRouterKey(cleanInput, { setAsActive: true, store });
649
688
  const updatedConfig = store.loadConfig();
650
689
  if (options.loop) {
@@ -715,7 +754,7 @@ export async function runInteractiveModelPicker(
715
754
  }
716
755
 
717
756
  const cleanKey = enteredKey.trim();
718
- await showConfiguringAnimation(target.providerLabel);
757
+ await showConfiguringAnimation(target.providerLabel, prompt);
719
758
 
720
759
  config['provider'] = target.providerId;
721
760
  config['model'] = target.modelId;
package/src/tui/stage.js CHANGED
@@ -33,6 +33,7 @@
33
33
  // Pure Node: no dependency, no shell.
34
34
 
35
35
  import { visibleWidth, truncate } from './text.js';
36
+ import { runWithStageWrite } from './consoleGuard.js';
36
37
 
37
38
  // Below this the band cannot hold a viewport plus an input box plus a footer,
38
39
  // and a cramped stage is worse than honest scrollback. The fallback is not a
@@ -133,7 +134,11 @@ export class Stage {
133
134
  write(text) {
134
135
  if (!text) return;
135
136
  this.stats.bytes += text.length;
136
- this.out.write(text);
137
+ if (typeof runWithStageWrite === 'function') {
138
+ runWithStageWrite(() => this.out.write(text));
139
+ } else {
140
+ this.out.write(text);
141
+ }
137
142
  }
138
143
 
139
144
  /**