@causyne/agent 1.20.70 → 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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@causyne/agent",
3
- "version": "1.20.70",
3
+ "version": "1.20.71",
4
4
  "description": "Agentic AI for software, tools, and computer workflows",
5
5
  "main": "bin/causyne.js",
6
6
  "type": "module",
Binary file
@@ -7,7 +7,9 @@
7
7
  */
8
8
  import http from 'node:http';
9
9
  import crypto from 'node:crypto';
10
- import { URL } from 'node:url';
10
+ import fs from 'node:fs';
11
+ import path from 'node:path';
12
+ import { fileURLToPath, URL } from 'node:url';
11
13
  import { loadConfig, saveConfig } from '../config.js';
12
14
  import { openWithNativeOS } from '../tools/desktopOpen.js';
13
15
  export const OPENROUTER_AUTH_URL = 'https://openrouter.ai/auth';
@@ -91,6 +93,180 @@ export async function exchangeCodeForApiKey(code, codeVerifier, fetchFn = fetch)
91
93
  }
92
94
  return apiKey;
93
95
  }
96
+ /**
97
+ * Retrieve the Causyne Agent emblem logo as a binary buffer if available.
98
+ */
99
+ export function getLogoBuffer() {
100
+ try {
101
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
102
+ const assetPath = path.resolve(currentDir, '../assets/logo.png');
103
+ if (fs.existsSync(assetPath)) {
104
+ return fs.readFileSync(assetPath);
105
+ }
106
+ }
107
+ catch {
108
+ // Ignore read errors
109
+ }
110
+ return null;
111
+ }
112
+ /**
113
+ * Retrieve the Causyne Agent emblem logo encoded as Base64.
114
+ */
115
+ export function getLogoBase64() {
116
+ const buf = getLogoBuffer();
117
+ return buf ? buf.toString('base64') : '';
118
+ }
119
+ /**
120
+ * Render a professional branded HTML response page for OpenRouter OAuth callbacks.
121
+ */
122
+ export function renderAuthPage(options) {
123
+ const isSuccess = options.status === 'success';
124
+ const base64Logo = getLogoBase64();
125
+ const logoSrc = base64Logo ? `data:image/png;base64,${base64Logo}` : '/logo.png';
126
+ const badgeHtml = isSuccess
127
+ ? '<div style="display:inline-flex;align-items:center;gap:8px;' +
128
+ 'background:rgba(46,160,67,0.15);border:1px solid #2ea043;color:#3fb950;' +
129
+ 'padding:6px 18px;border-radius:24px;font-size:13px;font-weight:600;margin-bottom:20px;">' +
130
+ '✓ Connected Successfully</div>'
131
+ : '<div style="display:inline-flex;align-items:center;gap:8px;' +
132
+ 'background:rgba(239,68,68,0.15);border:1px solid #ef4444;color:#f87171;' +
133
+ 'padding:6px 18px;border-radius:24px;font-size:13px;font-weight:600;margin-bottom:20px;">' +
134
+ '✕ Authorization Failed</div>';
135
+ const title = options.title || (isSuccess ? 'OpenRouter Account Authorized' : 'Authorization Error');
136
+ const defaultMsg = isSuccess
137
+ ? 'Your OpenRouter account has been connected to Causyne Agent. You can now close this tab and return to your terminal.'
138
+ : 'The authorization flow could not be completed.';
139
+ const message = options.message || defaultMsg;
140
+ const contentBox = isSuccess
141
+ ? '<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);' +
142
+ 'border-radius:10px;padding:14px 18px;margin-bottom:28px;text-align:left;font-family:monospace;' +
143
+ 'font-size:13px;color:#cbd5e1;">' +
144
+ '<div style="display:flex;justify-content:space-between;margin-bottom:8px;">' +
145
+ '<span style="color:#64748b;">Active Model</span>' +
146
+ `<span style="color:#9df028;font-weight:600;">${options.model || OPENROUTER_FREE_MODEL}</span>` +
147
+ '</div>' +
148
+ '<div style="display:flex;justify-content:space-between;">' +
149
+ '<span style="color:#64748b;">Privacy Guard</span>' +
150
+ '<span style="color:#38bdf8;">provider.data_collection = &quot;deny&quot;</span>' +
151
+ '</div>' +
152
+ '</div>'
153
+ : '<div style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.25);' +
154
+ 'border-radius:10px;padding:14px;color:#fca5a5;font-size:13px;line-height:1.5;margin-bottom:20px;' +
155
+ `text-align:left;">${options.errorDetail || 'An unexpected error occurred during authorization.'}</div>` +
156
+ '<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);' +
157
+ 'border-radius:10px;padding:16px;margin-bottom:24px;text-align:left;">' +
158
+ '<div style="color:#ffffff;font-size:13px;font-weight:600;margin-bottom:8px;">Recommended Solutions:</div>' +
159
+ '<ol style="color:#94a3b8;font-size:13px;line-height:1.6;margin:0;padding-left:18px;">' +
160
+ '<li>Return to your terminal and select OpenRouter in the FREE tab again to retry.</li>' +
161
+ '<li>Or create a free API key at <a href="https://openrouter.ai/keys" target="_blank" ' +
162
+ 'style="color:#38bdf8;text-decoration:none;">openrouter.ai/keys</a> and configure it via:</li>' +
163
+ '</ol>' +
164
+ '<pre style="background:#05070a;color:#9df028;padding:10px 14px;border-radius:6px;font-family:monospace;' +
165
+ 'font-size:12px;margin-top:10px;overflow-x:auto;">causyne config set providerKeys.openrouter &lt;your-key&gt;</pre>' +
166
+ '</div>';
167
+ const actionButton = isSuccess
168
+ ? '<button onclick="window.close()" style="background:#9df028;color:#080b11;border:none;' +
169
+ 'padding:12px 28px;border-radius:8px;font-size:14px;font-weight:700;cursor:pointer;font-family:inherit;">' +
170
+ 'Return to Terminal</button>' +
171
+ '<div style="font-size:12px;color:#64748b;margin-top:14px;">You can safely close this browser window.</div>'
172
+ : '<button onclick="window.close()" style="background:#334155;color:#f8fafc;border:none;' +
173
+ 'padding:10px 24px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;">' +
174
+ 'Close Window</button>';
175
+ return `<!DOCTYPE html>
176
+ <html lang="en">
177
+ <head>
178
+ <meta charset="utf-8">
179
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
180
+ <title>Causyne Agent Connected Successfully</title>
181
+ <style>
182
+ * { box-sizing: border-box; margin: 0; padding: 0; }
183
+ body {
184
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
185
+ background: #080b11 radial-gradient(circle at 50% 20%, #152238 0%, #080b11 75%);
186
+ color: #c9d1d9;
187
+ min-height: 100vh;
188
+ display: flex;
189
+ align-items: center;
190
+ justify-content: center;
191
+ padding: 24px;
192
+ }
193
+ .container {
194
+ max-width: 540px;
195
+ width: 100%;
196
+ text-align: center;
197
+ }
198
+ .header {
199
+ display: flex;
200
+ align-items: center;
201
+ justify-content: center;
202
+ gap: 16px;
203
+ margin-bottom: 28px;
204
+ }
205
+ .logo {
206
+ width: 52px;
207
+ height: 52px;
208
+ object-fit: contain;
209
+ border-radius: 12px;
210
+ filter: drop-shadow(0 4px 16px rgba(157, 240, 40, 0.3));
211
+ }
212
+ .brand-title {
213
+ font-family: "JetBrains Mono", SFMono-Regular, Menlo, Consolas, monospace;
214
+ font-size: 24px;
215
+ font-weight: 800;
216
+ letter-spacing: 1.5px;
217
+ color: #ffffff;
218
+ line-height: 1.2;
219
+ }
220
+ .brand-subtitle {
221
+ font-size: 11px;
222
+ color: #8a99a8;
223
+ letter-spacing: 1px;
224
+ text-transform: uppercase;
225
+ margin-top: 2px;
226
+ text-align: left;
227
+ }
228
+ .card {
229
+ background: rgba(18, 25, 38, 0.95);
230
+ border: 1px solid rgba(157, 240, 40, 0.22);
231
+ border-radius: 16px;
232
+ padding: 36px 32px;
233
+ box-shadow: 0 24px 48px rgba(0, 0, 0, 0.6);
234
+ backdrop-filter: blur(16px);
235
+ }
236
+ h1 {
237
+ color: #ffffff;
238
+ font-size: 21px;
239
+ font-weight: 700;
240
+ margin-bottom: 12px;
241
+ }
242
+ p {
243
+ color: #94a3b8;
244
+ font-size: 14px;
245
+ line-height: 1.6;
246
+ margin-bottom: 24px;
247
+ }
248
+ </style>
249
+ </head>
250
+ <body>
251
+ <div class="container">
252
+ <div class="header">
253
+ <img src="${logoSrc}" alt="Causyne Agent Logo" class="logo" />
254
+ <div>
255
+ <div class="brand-title">CAUSYNE <span style="color:#9df028;">AGENT</span></div>
256
+ <div class="brand-subtitle">Autonomous AI Harness</div>
257
+ </div>
258
+ </div>
259
+ <div class="card">
260
+ ${badgeHtml}
261
+ <h1>${title}</h1>
262
+ <p>${message}</p>
263
+ ${contentBox}
264
+ ${actionButton}
265
+ </div>
266
+ </div>
267
+ </body>
268
+ </html>`;
269
+ }
94
270
  /**
95
271
  * Start loopback HTTP server on 127.0.0.1 to receive the OAuth redirect code.
96
272
  */
@@ -117,6 +293,21 @@ export async function startLoopbackAuth(options = {}) {
117
293
  const server = http.createServer(async (req, res) => {
118
294
  try {
119
295
  const reqUrl = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
296
+ if (reqUrl.pathname === '/logo.png') {
297
+ const logoBuf = getLogoBuffer();
298
+ if (logoBuf) {
299
+ res.writeHead(200, {
300
+ 'Content-Type': 'image/png',
301
+ 'Content-Length': logoBuf.length,
302
+ 'Cache-Control': 'public, max-age=3600'
303
+ });
304
+ res.end(logoBuf);
305
+ return;
306
+ }
307
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
308
+ res.end('Not Found');
309
+ return;
310
+ }
120
311
  if (reqUrl.pathname !== '/callback') {
121
312
  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
122
313
  res.end('Not Found');
@@ -126,10 +317,11 @@ export async function startLoopbackAuth(options = {}) {
126
317
  const state = reqUrl.searchParams.get('state');
127
318
  if (!state || state !== pkce.state) {
128
319
  res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
129
- res.end('<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
130
- '<h2 style="color:#ef4444;">Authorization Error: State Mismatch</h2>' +
131
- '<p>The received CSRF verification state did not match the session. Please try again.</p>' +
132
- '</body></html>');
320
+ res.end(renderAuthPage({
321
+ status: 'error',
322
+ title: 'Authorization Error: State Mismatch',
323
+ errorDetail: 'The received CSRF verification state did not match the active session. This can happen if the authorization request timed out or was tampered with.'
324
+ }));
133
325
  if (!resolved) {
134
326
  resolved = true;
135
327
  cleanup();
@@ -139,10 +331,11 @@ export async function startLoopbackAuth(options = {}) {
139
331
  }
140
332
  if (!code) {
141
333
  res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
142
- res.end('<html><body style="font-family:sans-serif;padding:32px;background:#111;color:#eee;">' +
143
- '<h2 style="color:#ef4444;">Authorization Failed</h2>' +
144
- '<p>No authorization code was returned by OpenRouter.</p>' +
145
- '</body></html>');
334
+ res.end(renderAuthPage({
335
+ status: 'error',
336
+ title: 'Authorization Failed',
337
+ errorDetail: 'No authorization code was returned by OpenRouter.'
338
+ }));
146
339
  if (!resolved) {
147
340
  resolved = true;
148
341
  cleanup();
@@ -152,15 +345,15 @@ export async function startLoopbackAuth(options = {}) {
152
345
  }
153
346
  // Send friendly HTML response to user's browser
154
347
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
155
- res.end('<html><body style="font-family:sans-serif;padding:40px;background:#0d1117;color:#c9d1d9;text-align:center;">' +
156
- '<h2 style="color:#2ea043;margin-bottom:12px;">Causyne Agent Connected Successfully</h2>' +
157
- '<p style="font-size:16px;color:#8b949e;">Your OpenRouter account has been authorized. You can close this window and return to your terminal.</p>' +
158
- '</body></html>');
348
+ res.end(renderAuthPage({
349
+ status: 'success',
350
+ model: OPENROUTER_FREE_MODEL
351
+ }));
159
352
  // Perform token exchange
160
353
  const apiKey = await exchangeCodeForApiKey(code, pkce.codeVerifier, fetchFn);
161
354
  if (!resolved) {
162
355
  resolved = true;
163
- cleanup();
356
+ setTimeout(cleanup, 1200);
164
357
  resolve({ apiKey });
165
358
  }
166
359
  }
@@ -8,7 +8,9 @@
8
8
 
9
9
  import http from 'node:http';
10
10
  import crypto from 'node:crypto';
11
- import { URL } from 'node:url';
11
+ import fs from 'node:fs';
12
+ import path from 'node:path';
13
+ import { fileURLToPath, URL } from 'node:url';
12
14
  import { loadConfig, saveConfig } from '../config.js';
13
15
  import { openWithNativeOS } from '../tools/desktopOpen.js';
14
16
 
@@ -126,6 +128,195 @@ export async function exchangeCodeForApiKey(
126
128
  return apiKey;
127
129
  }
128
130
 
131
+ /**
132
+ * Retrieve the Causyne Agent emblem logo as a binary buffer if available.
133
+ */
134
+ export function getLogoBuffer(): Buffer | null {
135
+ try {
136
+ const currentDir = path.dirname(fileURLToPath(import.meta.url));
137
+ const assetPath = path.resolve(currentDir, '../assets/logo.png');
138
+ if (fs.existsSync(assetPath)) {
139
+ return fs.readFileSync(assetPath);
140
+ }
141
+ } catch {
142
+ // Ignore read errors
143
+ }
144
+ return null;
145
+ }
146
+
147
+ /**
148
+ * Retrieve the Causyne Agent emblem logo encoded as Base64.
149
+ */
150
+ export function getLogoBase64(): string {
151
+ const buf = getLogoBuffer();
152
+ return buf ? buf.toString('base64') : '';
153
+ }
154
+
155
+ export interface RenderAuthPageOptions {
156
+ status: 'success' | 'error';
157
+ title?: string | undefined;
158
+ message?: string | undefined;
159
+ errorDetail?: string | undefined;
160
+ model?: string | undefined;
161
+ }
162
+
163
+ /**
164
+ * Render a professional branded HTML response page for OpenRouter OAuth callbacks.
165
+ */
166
+ export function renderAuthPage(options: RenderAuthPageOptions): string {
167
+ const isSuccess = options.status === 'success';
168
+ const base64Logo = getLogoBase64();
169
+ const logoSrc = base64Logo ? `data:image/png;base64,${base64Logo}` : '/logo.png';
170
+
171
+ const badgeHtml = isSuccess
172
+ ? '<div style="display:inline-flex;align-items:center;gap:8px;' +
173
+ 'background:rgba(46,160,67,0.15);border:1px solid #2ea043;color:#3fb950;' +
174
+ 'padding:6px 18px;border-radius:24px;font-size:13px;font-weight:600;margin-bottom:20px;">' +
175
+ '✓ Connected Successfully</div>'
176
+ : '<div style="display:inline-flex;align-items:center;gap:8px;' +
177
+ 'background:rgba(239,68,68,0.15);border:1px solid #ef4444;color:#f87171;' +
178
+ 'padding:6px 18px;border-radius:24px;font-size:13px;font-weight:600;margin-bottom:20px;">' +
179
+ '✕ Authorization Failed</div>';
180
+
181
+ const title = options.title || (isSuccess ? 'OpenRouter Account Authorized' : 'Authorization Error');
182
+ const defaultMsg = isSuccess
183
+ ? 'Your OpenRouter account has been connected to Causyne Agent. You can now close this tab and return to your terminal.'
184
+ : 'The authorization flow could not be completed.';
185
+ const message = options.message || defaultMsg;
186
+
187
+ const contentBox = isSuccess
188
+ ? '<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);' +
189
+ 'border-radius:10px;padding:14px 18px;margin-bottom:28px;text-align:left;font-family:monospace;' +
190
+ 'font-size:13px;color:#cbd5e1;">' +
191
+ '<div style="display:flex;justify-content:space-between;margin-bottom:8px;">' +
192
+ '<span style="color:#64748b;">Active Model</span>' +
193
+ `<span style="color:#9df028;font-weight:600;">${options.model || OPENROUTER_FREE_MODEL}</span>` +
194
+ '</div>' +
195
+ '<div style="display:flex;justify-content:space-between;">' +
196
+ '<span style="color:#64748b;">Privacy Guard</span>' +
197
+ '<span style="color:#38bdf8;">provider.data_collection = &quot;deny&quot;</span>' +
198
+ '</div>' +
199
+ '</div>'
200
+ : '<div style="background:rgba(239,68,68,0.08);border:1px solid rgba(239,68,68,0.25);' +
201
+ 'border-radius:10px;padding:14px;color:#fca5a5;font-size:13px;line-height:1.5;margin-bottom:20px;' +
202
+ `text-align:left;">${options.errorDetail || 'An unexpected error occurred during authorization.'}</div>` +
203
+ '<div style="background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);' +
204
+ 'border-radius:10px;padding:16px;margin-bottom:24px;text-align:left;">' +
205
+ '<div style="color:#ffffff;font-size:13px;font-weight:600;margin-bottom:8px;">Recommended Solutions:</div>' +
206
+ '<ol style="color:#94a3b8;font-size:13px;line-height:1.6;margin:0;padding-left:18px;">' +
207
+ '<li>Return to your terminal and select OpenRouter in the FREE tab again to retry.</li>' +
208
+ '<li>Or create a free API key at <a href="https://openrouter.ai/keys" target="_blank" ' +
209
+ 'style="color:#38bdf8;text-decoration:none;">openrouter.ai/keys</a> and configure it via:</li>' +
210
+ '</ol>' +
211
+ '<pre style="background:#05070a;color:#9df028;padding:10px 14px;border-radius:6px;font-family:monospace;' +
212
+ 'font-size:12px;margin-top:10px;overflow-x:auto;">causyne config set providerKeys.openrouter &lt;your-key&gt;</pre>' +
213
+ '</div>';
214
+
215
+ const actionButton = isSuccess
216
+ ? '<button onclick="window.close()" style="background:#9df028;color:#080b11;border:none;' +
217
+ 'padding:12px 28px;border-radius:8px;font-size:14px;font-weight:700;cursor:pointer;font-family:inherit;">' +
218
+ 'Return to Terminal</button>' +
219
+ '<div style="font-size:12px;color:#64748b;margin-top:14px;">You can safely close this browser window.</div>'
220
+ : '<button onclick="window.close()" style="background:#334155;color:#f8fafc;border:none;' +
221
+ 'padding:10px 24px;border-radius:8px;font-size:13px;font-weight:600;cursor:pointer;font-family:inherit;">' +
222
+ 'Close Window</button>';
223
+
224
+ return `<!DOCTYPE html>
225
+ <html lang="en">
226
+ <head>
227
+ <meta charset="utf-8">
228
+ <meta name="viewport" content="width=device-width, initial-scale=1.0">
229
+ <title>Causyne Agent Connected Successfully</title>
230
+ <style>
231
+ * { box-sizing: border-box; margin: 0; padding: 0; }
232
+ body {
233
+ font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
234
+ background: #080b11 radial-gradient(circle at 50% 20%, #152238 0%, #080b11 75%);
235
+ color: #c9d1d9;
236
+ min-height: 100vh;
237
+ display: flex;
238
+ align-items: center;
239
+ justify-content: center;
240
+ padding: 24px;
241
+ }
242
+ .container {
243
+ max-width: 540px;
244
+ width: 100%;
245
+ text-align: center;
246
+ }
247
+ .header {
248
+ display: flex;
249
+ align-items: center;
250
+ justify-content: center;
251
+ gap: 16px;
252
+ margin-bottom: 28px;
253
+ }
254
+ .logo {
255
+ width: 52px;
256
+ height: 52px;
257
+ object-fit: contain;
258
+ border-radius: 12px;
259
+ filter: drop-shadow(0 4px 16px rgba(157, 240, 40, 0.3));
260
+ }
261
+ .brand-title {
262
+ font-family: "JetBrains Mono", SFMono-Regular, Menlo, Consolas, monospace;
263
+ font-size: 24px;
264
+ font-weight: 800;
265
+ letter-spacing: 1.5px;
266
+ color: #ffffff;
267
+ line-height: 1.2;
268
+ }
269
+ .brand-subtitle {
270
+ font-size: 11px;
271
+ color: #8a99a8;
272
+ letter-spacing: 1px;
273
+ text-transform: uppercase;
274
+ margin-top: 2px;
275
+ text-align: left;
276
+ }
277
+ .card {
278
+ background: rgba(18, 25, 38, 0.95);
279
+ border: 1px solid rgba(157, 240, 40, 0.22);
280
+ border-radius: 16px;
281
+ padding: 36px 32px;
282
+ box-shadow: 0 24px 48px rgba(0, 0, 0, 0.6);
283
+ backdrop-filter: blur(16px);
284
+ }
285
+ h1 {
286
+ color: #ffffff;
287
+ font-size: 21px;
288
+ font-weight: 700;
289
+ margin-bottom: 12px;
290
+ }
291
+ p {
292
+ color: #94a3b8;
293
+ font-size: 14px;
294
+ line-height: 1.6;
295
+ margin-bottom: 24px;
296
+ }
297
+ </style>
298
+ </head>
299
+ <body>
300
+ <div class="container">
301
+ <div class="header">
302
+ <img src="${logoSrc}" alt="Causyne Agent Logo" class="logo" />
303
+ <div>
304
+ <div class="brand-title">CAUSYNE <span style="color:#9df028;">AGENT</span></div>
305
+ <div class="brand-subtitle">Autonomous AI Harness</div>
306
+ </div>
307
+ </div>
308
+ <div class="card">
309
+ ${badgeHtml}
310
+ <h1>${title}</h1>
311
+ <p>${message}</p>
312
+ ${contentBox}
313
+ ${actionButton}
314
+ </div>
315
+ </div>
316
+ </body>
317
+ </html>`;
318
+ }
319
+
129
320
  /**
130
321
  * Start loopback HTTP server on 127.0.0.1 to receive the OAuth redirect code.
131
322
  */
@@ -160,6 +351,23 @@ export async function startLoopbackAuth(options: {
160
351
  const server = http.createServer(async (req, res) => {
161
352
  try {
162
353
  const reqUrl = new URL(req.url || '/', `http://${req.headers.host || '127.0.0.1'}`);
354
+
355
+ if (reqUrl.pathname === '/logo.png') {
356
+ const logoBuf = getLogoBuffer();
357
+ if (logoBuf) {
358
+ res.writeHead(200, {
359
+ 'Content-Type': 'image/png',
360
+ 'Content-Length': logoBuf.length,
361
+ 'Cache-Control': 'public, max-age=3600'
362
+ });
363
+ res.end(logoBuf);
364
+ return;
365
+ }
366
+ res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
367
+ res.end('Not Found');
368
+ return;
369
+ }
370
+
163
371
  if (reqUrl.pathname !== '/callback') {
164
372
  res.writeHead(404, { 'Content-Type': 'text/plain; charset=utf-8' });
165
373
  res.end('Not Found');
@@ -172,10 +380,11 @@ export async function startLoopbackAuth(options: {
172
380
  if (!state || state !== pkce.state) {
173
381
  res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
174
382
  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>'
383
+ renderAuthPage({
384
+ status: 'error',
385
+ title: 'Authorization Error: State Mismatch',
386
+ errorDetail: 'The received CSRF verification state did not match the active session. This can happen if the authorization request timed out or was tampered with.'
387
+ })
179
388
  );
180
389
  if (!resolved) {
181
390
  resolved = true;
@@ -188,10 +397,11 @@ export async function startLoopbackAuth(options: {
188
397
  if (!code) {
189
398
  res.writeHead(400, { 'Content-Type': 'text/html; charset=utf-8' });
190
399
  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>'
400
+ renderAuthPage({
401
+ status: 'error',
402
+ title: 'Authorization Failed',
403
+ errorDetail: 'No authorization code was returned by OpenRouter.'
404
+ })
195
405
  );
196
406
  if (!resolved) {
197
407
  resolved = true;
@@ -204,10 +414,10 @@ export async function startLoopbackAuth(options: {
204
414
  // Send friendly HTML response to user's browser
205
415
  res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
206
416
  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>'
417
+ renderAuthPage({
418
+ status: 'success',
419
+ model: OPENROUTER_FREE_MODEL
420
+ })
211
421
  );
212
422
 
213
423
  // Perform token exchange
@@ -215,7 +425,7 @@ export async function startLoopbackAuth(options: {
215
425
 
216
426
  if (!resolved) {
217
427
  resolved = true;
218
- cleanup();
428
+ setTimeout(cleanup, 1200);
219
429
  resolve({ apiKey });
220
430
  }
221
431
  } catch (err: any) {
@@ -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 } 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,46 @@ 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 openrouterPeer = overview.byok.find(p => p.id === 'openrouter');
176
+ const isConfigured = Boolean((config.provider === 'openrouter' && config.apiKey) ||
177
+ config.providerKeys?.openrouter ||
178
+ process.env.OPENROUTER_API_KEY);
179
+ const isCurrentProvider = activeProvider === 'openrouter';
180
+ const models = openrouterPeer?.models && openrouterPeer.models.length > 0
181
+ ? openrouterPeer.models
182
+ : ['openrouter/free'];
183
+ const catTitle = isConfigured
184
+ ? 'Free Cloud · OpenRouter (ready)'
185
+ : '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');
191
+ items.push({
192
+ id: `openrouter/${m}`,
193
+ label: m,
194
+ category: catTitle,
195
+ description: desc,
196
+ value: {
197
+ type: 'free',
198
+ providerId: 'openrouter',
199
+ modelId: m,
200
+ providerLabel: 'OpenRouter Free',
201
+ installed: true,
202
+ isCurrent,
203
+ isConfigured,
204
+ envVar: 'OPENROUTER_API_KEY'
205
+ }
206
+ });
207
+ }
208
+ }
173
209
  return items;
174
210
  }
175
211
  /**
176
- * Sovereign Model Picker Layer with dual-tab support (| ACP | BYOK |)
212
+ * Sovereign Model Picker Layer with tri-tab support (| ACP | BYOK | FREE |)
177
213
  * and interactive 10-model pagination.
178
214
  */
179
215
  export class ModelPickerLayer extends SelectLayer {
@@ -185,17 +221,19 @@ export class ModelPickerLayer extends SelectLayer {
185
221
  allItems;
186
222
  constructor(options) {
187
223
  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';
224
+ const initialTab = activeProvider === 'openrouter'
225
+ ? 'free'
226
+ : (activeProvider === 'antigravity' ||
227
+ activeProvider === 'agy' ||
228
+ activeProvider === 'acp' ||
229
+ activeProvider.startsWith('acp/')
230
+ ? 'acp'
231
+ : 'byok');
194
232
  const expandedPeers = new Set();
195
233
  const allItems = buildModelPickerItems(options.config, options.overview, { tab: 'all', maxAcpPerPeer: Infinity });
196
234
  super({
197
235
  title: 'Select Model',
198
- placeholder: 'type to filter (e.g. gemini, sonnet, opencode)…',
236
+ placeholder: 'type to filter (e.g. gemini, sonnet, openrouter)…',
199
237
  emptyText: 'No models matched your search in this tab',
200
238
  items: allItems,
201
239
  width: 78,
@@ -271,7 +309,8 @@ export class ModelPickerLayer extends SelectLayer {
271
309
  body(width, height) {
272
310
  const tabACP = this.activeTab === 'acp' ? paint('accent', bold('● ACP')) : dim('ACP');
273
311
  const tabBYOK = this.activeTab === 'byok' ? paint('accent', bold('● BYOK')) : dim('BYOK');
274
- const tabBar = ` | ${tabACP} | ${tabBYOK} | ${dim('(Tab / ← → switch tab)')}`;
312
+ const tabFREE = this.activeTab === 'free' ? paint('accent', bold('● FREE')) : dim('FREE');
313
+ const tabBar = ` | ${tabACP} | ${tabBYOK} | ${tabFREE} | ${dim('(Tab / ← → switch tab)')}`;
275
314
  const separator = paint('rule', GLYPHS.hLine.repeat(Math.max(4, width)));
276
315
  const listHeight = Math.max(1, height - 2);
277
316
  const { rows } = this.list.render(width, listHeight);
@@ -283,27 +322,50 @@ export class ModelPickerLayer extends SelectLayer {
283
322
  return null;
284
323
  // 1. Tab switching via Tab, Left/Right arrows, or PgLeft/PgRight mappings
285
324
  if (event.name === 'tab') {
286
- this.switchTab(this.activeTab === 'acp' ? 'byok' : 'acp');
325
+ if (this.activeTab === 'acp')
326
+ this.switchTab('byok');
327
+ else if (this.activeTab === 'byok')
328
+ this.switchTab('free');
329
+ else
330
+ this.switchTab('acp');
287
331
  return 'handled';
288
332
  }
289
- if (event.name === 'left' && this.activeTab === 'byok') {
333
+ if (event.name === 'left') {
290
334
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
291
- this.switchTab('acp');
292
- return 'handled';
335
+ if (this.activeTab === 'free') {
336
+ this.switchTab('byok');
337
+ return 'handled';
338
+ }
339
+ else if (this.activeTab === 'byok') {
340
+ this.switchTab('acp');
341
+ return 'handled';
342
+ }
293
343
  }
294
344
  }
295
- if (event.name === 'right' && this.activeTab === 'acp') {
345
+ if (event.name === 'right') {
296
346
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
297
- this.switchTab('byok');
298
- return 'handled';
347
+ if (this.activeTab === 'acp') {
348
+ this.switchTab('byok');
349
+ return 'handled';
350
+ }
351
+ else if (this.activeTab === 'byok') {
352
+ this.switchTab('free');
353
+ return 'handled';
354
+ }
299
355
  }
300
356
  }
301
357
  if (event.name === '[' || (event.name === 'pageup' && (event.shift || event.alt || event.ctrl))) {
302
- this.switchTab('acp');
358
+ if (this.activeTab === 'free')
359
+ this.switchTab('byok');
360
+ else if (this.activeTab === 'byok')
361
+ this.switchTab('acp');
303
362
  return 'handled';
304
363
  }
305
364
  if (event.name === ']' || (event.name === 'pagedown' && (event.shift || event.alt || event.ctrl))) {
306
- this.switchTab('byok');
365
+ if (this.activeTab === 'acp')
366
+ this.switchTab('byok');
367
+ else if (this.activeTab === 'byok')
368
+ this.switchTab('free');
307
369
  return 'handled';
308
370
  }
309
371
  // 2. Delegate to SelectList for navigation / query typing
@@ -395,7 +457,97 @@ export async function runInteractiveModelPicker(prompt, store = { loadConfig, sa
395
457
  notifyPrompt(target.providerId, target.modelId);
396
458
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
397
459
  }
398
- // Case 2: BYOK Provider (Cloud or Local API)
460
+ // Case 2: OpenRouter Free Models with instant 1-Enter OAuth PKCE flow
461
+ if (target.providerId === 'openrouter') {
462
+ let existingKey = '';
463
+ const providerKeys = config['providerKeys'] && typeof config['providerKeys'] === 'object' ? config['providerKeys'] : {};
464
+ if (config['provider'] === 'openrouter' && typeof config['apiKey'] === 'string' && config['apiKey']) {
465
+ existingKey = config['apiKey'];
466
+ }
467
+ else if (providerKeys['openrouter']) {
468
+ existingKey = providerKeys['openrouter'];
469
+ }
470
+ else if (process.env.OPENROUTER_API_KEY) {
471
+ existingKey = process.env.OPENROUTER_API_KEY;
472
+ }
473
+ if (existingKey) {
474
+ config['provider'] = 'openrouter';
475
+ config['model'] = target.modelId;
476
+ config['apiKey'] = existingKey;
477
+ config['providerKeys'] = providerKeys;
478
+ config['providerKeys']['openrouter'] = existingKey;
479
+ store.saveConfig(config);
480
+ void resolveAvailableModels('openrouter', { ...config, apiKey: existingKey }, true).catch(() => { });
481
+ if (options.loop) {
482
+ options.loop.config = config;
483
+ if (typeof options.loop.updateTierLimits === 'function') {
484
+ options.loop.updateTierLimits();
485
+ }
486
+ }
487
+ notifyPrompt('openrouter', target.modelId);
488
+ return `Now using OpenRouter Free / ${target.modelId}.`;
489
+ }
490
+ // Unconfigured OpenRouter: prompt where pressing Enter once immediately starts OAuth redirect
491
+ const entered = await new Promise((resolve) => {
492
+ const layer = new InputLayer({
493
+ title: 'Connect OpenRouter · Free Cloud Inference',
494
+ lines: [
495
+ 'Press [Enter] to open your browser and authorize with OpenRouter.',
496
+ 'Or paste an existing OpenRouter API key (Esc to cancel).'
497
+ ],
498
+ mask: false,
499
+ placeholder: 'Press Enter to authorize in browser, or paste API key',
500
+ onSubmit: resolve,
501
+ onCancel: () => resolve(null)
502
+ });
503
+ prompt.openLayer(layer);
504
+ });
505
+ if (entered === null) {
506
+ return 'Cancelled. OpenRouter connection was not completed. Model was not changed.';
507
+ }
508
+ const cleanInput = entered.trim();
509
+ if (!cleanInput) {
510
+ // User pressed Enter on empty placeholder: run OAuth PKCE loopback flow!
511
+ 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
+ }
516
+ const { apiKey } = await startLoopbackAuth({ timeoutMs: 120_000, openBrowser: true });
517
+ saveOpenRouterKey(apiKey, { setAsActive: true, store });
518
+ const updatedConfig = store.loadConfig();
519
+ if (options.loop) {
520
+ options.loop.config = updatedConfig;
521
+ if (typeof options.loop.updateTierLimits === 'function') {
522
+ options.loop.updateTierLimits();
523
+ }
524
+ }
525
+ notifyPrompt('openrouter', target.modelId);
526
+ return `✓ Connected to OpenRouter successfully! Now using OpenRouter Free / ${target.modelId}.`;
527
+ }
528
+ catch (err) {
529
+ return (`✕ OpenRouter authorization failed: ${err?.message || err}\n\n` +
530
+ `Solutions:\n` +
531
+ `1. Check that your browser can open local URLs (http://127.0.0.1).\n` +
532
+ `2. For headless or SSH environments, create a free API key at:\n` +
533
+ ` https://openrouter.ai/keys\n` +
534
+ ` and run: /openrouter connect <your-api-key>`);
535
+ }
536
+ }
537
+ // User pasted an API key
538
+ await showConfiguringAnimation('OpenRouter');
539
+ saveOpenRouterKey(cleanInput, { setAsActive: true, store });
540
+ const updatedConfig = store.loadConfig();
541
+ if (options.loop) {
542
+ options.loop.config = updatedConfig;
543
+ if (typeof options.loop.updateTierLimits === 'function') {
544
+ options.loop.updateTierLimits();
545
+ }
546
+ }
547
+ notifyPrompt('openrouter', target.modelId);
548
+ return `✓ Saved API key. Now using OpenRouter Free / ${target.modelId}.`;
549
+ }
550
+ // Case 3: BYOK Provider (Cloud or Local API)
399
551
  let existingKey = '';
400
552
  const providerKeys = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
401
553
  if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {
@@ -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,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,56 @@ export function buildModelPickerItems(
234
234
  }
235
235
  }
236
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
+
237
278
  return items;
238
279
  }
239
280
 
240
281
  /**
241
- * Sovereign Model Picker Layer with dual-tab support (| ACP | BYOK |)
282
+ * Sovereign Model Picker Layer with tri-tab support (| ACP | BYOK | FREE |)
242
283
  * and interactive 10-model pagination.
243
284
  */
244
285
  export class ModelPickerLayer extends SelectLayer {
245
- public activeTab: 'acp' | 'byok';
286
+ public activeTab: 'acp' | 'byok' | 'free';
246
287
  public config: Record<string, any>;
247
288
  public overview: ProviderOverview;
248
289
  public expandedPeers: Set<string>;
@@ -261,20 +302,22 @@ export class ModelPickerLayer extends SelectLayer {
261
302
  onPick: (item: ModelPickerItem | null) => void;
262
303
  }) {
263
304
  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';
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');
271
314
 
272
315
  const expandedPeers = new Set<string>();
273
316
  const allItems = buildModelPickerItems(options.config, options.overview, { tab: 'all', maxAcpPerPeer: Infinity });
274
317
 
275
318
  super({
276
319
  title: 'Select Model',
277
- placeholder: 'type to filter (e.g. gemini, sonnet, opencode)…',
320
+ placeholder: 'type to filter (e.g. gemini, sonnet, openrouter)…',
278
321
  emptyText: 'No models matched your search in this tab',
279
322
  items: allItems,
280
323
  width: 78,
@@ -319,7 +362,7 @@ export class ModelPickerLayer extends SelectLayer {
319
362
  }
320
363
  }
321
364
 
322
- switchTab(tab: 'acp' | 'byok'): void {
365
+ switchTab(tab: 'acp' | 'byok' | 'free'): void {
323
366
  if (this.activeTab === tab) return;
324
367
  this.activeTab = tab;
325
368
  this.list.refilter();
@@ -355,7 +398,8 @@ export class ModelPickerLayer extends SelectLayer {
355
398
  body(width: number, height: number): string[] {
356
399
  const tabACP = this.activeTab === 'acp' ? paint('accent', bold('● ACP')) : dim('ACP');
357
400
  const tabBYOK = this.activeTab === 'byok' ? paint('accent', bold('● BYOK')) : dim('BYOK');
358
- 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)')}`;
359
403
  const separator = paint('rule', GLYPHS.hLine.repeat(Math.max(4, width)));
360
404
 
361
405
  const listHeight = Math.max(1, height - 2);
@@ -370,29 +414,43 @@ export class ModelPickerLayer extends SelectLayer {
370
414
 
371
415
  // 1. Tab switching via Tab, Left/Right arrows, or PgLeft/PgRight mappings
372
416
  if (event.name === 'tab') {
373
- 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');
374
420
  return 'handled';
375
421
  }
376
422
 
377
- if (event.name === 'left' && this.activeTab === 'byok') {
423
+ if (event.name === 'left') {
378
424
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
379
- this.switchTab('acp');
380
- 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
+ }
381
432
  }
382
433
  }
383
- if (event.name === 'right' && this.activeTab === 'acp') {
434
+ if (event.name === 'right') {
384
435
  if (!this.list.query || event.alt || event.ctrl || event.meta) {
385
- this.switchTab('byok');
386
- 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
+ }
387
443
  }
388
444
  }
389
445
 
390
446
  if (event.name === '[' || (event.name === 'pageup' && (event.shift || event.alt || event.ctrl))) {
391
- this.switchTab('acp');
447
+ if (this.activeTab === 'free') this.switchTab('byok');
448
+ else if (this.activeTab === 'byok') this.switchTab('acp');
392
449
  return 'handled';
393
450
  }
394
451
  if (event.name === ']' || (event.name === 'pagedown' && (event.shift || event.alt || event.ctrl))) {
395
- this.switchTab('byok');
452
+ if (this.activeTab === 'acp') this.switchTab('byok');
453
+ else if (this.activeTab === 'byok') this.switchTab('free');
396
454
  return 'handled';
397
455
  }
398
456
 
@@ -500,7 +558,106 @@ export async function runInteractiveModelPicker(
500
558
  return `Now using ${target.providerLabel} / ${target.modelId}.`;
501
559
  }
502
560
 
503
- // 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)
504
661
  let existingKey = '';
505
662
  const providerKeys: Record<string, string> = (config['providerKeys'] && typeof config['providerKeys'] === 'object') ? config['providerKeys'] : {};
506
663
  if (config['provider'] === target.providerId && typeof config['apiKey'] === 'string' && config['apiKey']) {