@prestyj/core 5.32.2 → 5.34.0

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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getAppPaths
3
- } from "./chunk-W4NHU4UL.js";
3
+ } from "./chunk-DVWS2KEW.js";
4
4
 
5
5
  // src/oauth/kimi.ts
6
6
  import { execFileSync } from "child_process";
@@ -230,9 +230,9 @@ async function refreshKimiToken(refreshToken) {
230
230
  }
231
231
 
232
232
  // src/auth-storage.ts
233
- import fs4 from "fs/promises";
234
- import { readFileSync as readFileSync3 } from "fs";
235
- import crypto5 from "crypto";
233
+ import fs5 from "fs/promises";
234
+ import { readFileSync as readFileSync2 } from "fs";
235
+ import crypto6 from "crypto";
236
236
 
237
237
  // src/oauth/anthropic.ts
238
238
  import crypto2 from "crypto";
@@ -256,347 +256,11 @@ async function generatePKCE() {
256
256
  }
257
257
 
258
258
  // src/claude-code-version.ts
259
- import fs2 from "fs/promises";
260
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
261
- import path3 from "path";
262
-
263
- // src/logger.ts
264
- import fs from "fs";
265
- import path2 from "path";
266
- import { randomBytes } from "crypto";
267
- import { environmentSecrets, redactText, redactValue } from "@prestyj/ai";
268
- var MAX_BYTES = 10 * 1024 * 1024;
269
- var MIN_HEADROOM_BYTES = 64 * 1024;
270
- var fd = null;
271
- var logPath = null;
272
- var fileBytes = 0;
273
- var processBytes = 0;
274
- var rotationFailed = false;
275
- var capped = false;
276
- var sessionId = "";
277
- var appName = "app";
278
- var cleanups = [];
279
- var exactSecrets = [];
280
- function rotateIfNeeded(filePath, force = false) {
281
- try {
282
- const st = fs.statSync(filePath);
283
- if (!force && st.size <= MAX_BYTES - MIN_HEADROOM_BYTES) return;
284
- const rotated = `${filePath}.1`;
285
- try {
286
- fs.unlinkSync(rotated);
287
- } catch {
288
- }
289
- fs.renameSync(filePath, rotated);
290
- } catch {
291
- }
292
- }
293
- function rotateOpenLog() {
294
- if (fd === null || logPath === null) return false;
295
- const sizeBefore = fileBytes;
296
- try {
297
- fs.closeSync(fd);
298
- } catch {
299
- }
300
- fd = null;
301
- rotateIfNeeded(logPath, true);
302
- try {
303
- fd = fs.openSync(logPath, "a");
304
- fileBytes = fs.fstatSync(fd).size;
305
- } catch {
306
- if (fd !== null) {
307
- try {
308
- fs.closeSync(fd);
309
- } catch {
310
- }
311
- }
312
- fd = null;
313
- capped = true;
314
- return false;
315
- }
316
- if (fileBytes >= sizeBefore) rotationFailed = true;
317
- return true;
318
- }
319
- function openLog(filePath, name) {
320
- if (fd !== null || capped) return false;
321
- appName = name;
322
- exactSecrets = environmentSecrets(process.env);
323
- try {
324
- fs.mkdirSync(path2.dirname(filePath), { recursive: true, mode: 448 });
325
- } catch {
326
- }
327
- rotateIfNeeded(filePath);
328
- try {
329
- fd = fs.openSync(filePath, "a");
330
- } catch {
331
- fd = null;
332
- fileBytes = 0;
333
- return false;
334
- }
335
- try {
336
- fileBytes = fs.fstatSync(fd).size;
337
- } catch {
338
- try {
339
- fs.closeSync(fd);
340
- } catch {
341
- }
342
- fd = null;
343
- fileBytes = 0;
344
- return false;
345
- }
346
- logPath = filePath;
347
- processBytes = 0;
348
- rotationFailed = false;
349
- sessionId = randomBytes(4).toString("hex");
350
- try {
351
- if (fileBytes < MAX_BYTES) {
352
- const written = fs.writeSync(fd, "\n");
353
- fileBytes += written;
354
- processBytes += written;
355
- }
356
- } catch {
357
- }
358
- return true;
359
- }
360
- function getSessionId() {
361
- return sessionId;
362
- }
363
- function isLoggerOpen() {
364
- return fd !== null;
365
- }
366
- function log(level, category, message, data) {
367
- if (fd === null) return;
368
- const ts = (/* @__PURE__ */ new Date()).toISOString();
369
- const safeMessage = redactText(message, { secrets: exactSecrets });
370
- let line = `[${ts}] [sid=${sessionId}] [${level}] [${category}] ${safeMessage}`;
371
- if (data) {
372
- const safeData = redactValue(data, { secrets: exactSecrets });
373
- const pairs = Object.entries(safeData).map(([k, v]) => {
374
- if (typeof v === "string") return `${k}=${v}`;
375
- if (typeof v === "bigint") return `${k}=${String(v)}`;
376
- return `${k}=${JSON.stringify(v)}`;
377
- }).join(" ");
378
- if (pairs) line += ` ${pairs}`;
379
- }
380
- line += "\n";
381
- const lineBytes = Buffer.byteLength(line);
382
- if (processBytes + lineBytes > MAX_BYTES) {
383
- const capLine = `[${ts}] [sid=${sessionId}] [WARN] [logger] Log cap reached; file logging disabled until restart
384
- `;
385
- try {
386
- if (fileBytes + Buffer.byteLength(capLine) <= MAX_BYTES) {
387
- fileBytes += fs.writeSync(fd, capLine);
388
- }
389
- fs.closeSync(fd);
390
- } catch {
391
- }
392
- fd = null;
393
- capped = true;
394
- return;
395
- }
396
- if (fileBytes + lineBytes > MAX_BYTES && !rotationFailed && !rotateOpenLog()) return;
397
- if (fd === null) return;
398
- try {
399
- const written = fs.writeSync(fd, line);
400
- fileBytes += written;
401
- processBytes += written;
402
- } catch {
403
- }
404
- }
405
- function registerLogCleanup(fn) {
406
- cleanups.push(fn);
407
- }
408
- function closeLogger(opts) {
409
- if (fd !== null) {
410
- if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName} shutting down`);
411
- try {
412
- if (fd !== null) fs.closeSync(fd);
413
- } catch {
414
- }
415
- }
416
- fd = null;
417
- logPath = null;
418
- fileBytes = 0;
419
- processBytes = 0;
420
- rotationFailed = false;
421
- capped = false;
422
- exactSecrets = [];
423
- for (const unsub of cleanups) unsub();
424
- cleanups = [];
425
- }
426
-
427
- // src/claude-code-version.ts
428
- var NPM_LATEST_URL = "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";
429
- var CACHE_FRESH_MS = 60 * 60 * 1e3;
430
- var CACHE_HARD_MS = 24 * 60 * 60 * 1e3;
431
- var FETCH_TIMEOUT_MS = 3e3;
432
- var FALLBACK_VERSION = "2.1.280";
433
- var memoryCache = null;
434
- var inflight = null;
435
- var backgroundRefresh = null;
436
- var versionFloor = null;
437
- function cachePath() {
438
- return path3.join(getAppPaths().agentDir, "claude-code-version.json");
439
- }
440
- function compareClaudeCodeVersions(a, b) {
441
- const parse = (v) => v.split(".").map((part) => Number.parseInt(part, 10)).map((n) => Number.isFinite(n) ? n : 0);
442
- const left = parse(a);
443
- const right = parse(b);
444
- for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
445
- const diff = (left[i] ?? 0) - (right[i] ?? 0);
446
- if (diff !== 0) return diff;
447
- }
448
- return 0;
449
- }
450
- function applyFloor(version) {
451
- if (!versionFloor) return version;
452
- return compareClaudeCodeVersions(versionFloor, version) > 0 ? versionFloor : version;
453
- }
454
- async function readDiskCache() {
455
- try {
456
- const raw = await fs2.readFile(cachePath(), "utf-8");
457
- const parsed = JSON.parse(raw);
458
- if (typeof parsed.version === "string" && typeof parsed.fetchedAt === "number") {
459
- if (typeof parsed.minVersion === "string") {
460
- if (!versionFloor || compareClaudeCodeVersions(parsed.minVersion, versionFloor) > 0) {
461
- versionFloor = parsed.minVersion;
462
- }
463
- }
464
- return parsed;
465
- }
466
- return null;
467
- } catch {
468
- return null;
469
- }
470
- }
471
- async function writeDiskCache(data) {
472
- try {
473
- await fs2.mkdir(getAppPaths().agentDir, { recursive: true, mode: 448 });
474
- await fs2.writeFile(
475
- cachePath(),
476
- JSON.stringify({ ...data, ...versionFloor ? { minVersion: versionFloor } : {} }),
477
- { mode: 384 }
478
- );
479
- } catch (err) {
480
- log(
481
- "WARN",
482
- "claude-code-version",
483
- `Failed to write cache: ${err instanceof Error ? err.message : String(err)}`
484
- );
485
- }
486
- }
487
- async function fetchLatest() {
488
- const controller = new AbortController();
489
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
490
- try {
491
- const response = await fetch(NPM_LATEST_URL, { signal: controller.signal });
492
- if (!response.ok) return null;
493
- const data = await response.json();
494
- if (typeof data.version === "string" && /^\d/.test(data.version)) {
495
- return data.version;
496
- }
497
- return null;
498
- } catch {
499
- return null;
500
- } finally {
501
- clearTimeout(timer);
502
- }
503
- }
504
- function refreshInBackground() {
505
- if (backgroundRefresh) return;
506
- backgroundRefresh = (async () => {
507
- const fetched = await fetchLatest();
508
- if (fetched) {
509
- await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
510
- memoryCache = { version: applyFloor(fetched), expiresAt: Date.now() + CACHE_FRESH_MS };
511
- }
512
- })().catch(() => {
513
- }).finally(() => {
514
- backgroundRefresh = null;
515
- });
516
- }
517
- async function getClaudeCodeVersion() {
518
- if (memoryCache && Date.now() < memoryCache.expiresAt) {
519
- return memoryCache.version;
520
- }
521
- if (inflight) return inflight;
522
- inflight = (async () => {
523
- const disk = await readDiskCache();
524
- const age = disk ? Date.now() - disk.fetchedAt : Infinity;
525
- if (disk && age < CACHE_FRESH_MS) {
526
- const version = applyFloor(disk.version);
527
- memoryCache = { version, expiresAt: Date.now() + CACHE_FRESH_MS };
528
- return version;
529
- }
530
- if (disk && age < CACHE_HARD_MS) {
531
- const version = applyFloor(disk.version);
532
- memoryCache = { version, expiresAt: Date.now() + 5 * 60 * 1e3 };
533
- refreshInBackground();
534
- return version;
535
- }
536
- const fetched = await fetchLatest();
537
- if (fetched) {
538
- await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
539
- const version = applyFloor(fetched);
540
- memoryCache = { version, expiresAt: Date.now() + CACHE_FRESH_MS };
541
- return version;
542
- }
543
- const resolved = applyFloor(disk?.version ?? FALLBACK_VERSION);
544
- memoryCache = { version: resolved, expiresAt: Date.now() + 5 * 60 * 1e3 };
545
- log(
546
- "WARN",
547
- "claude-code-version",
548
- `Failed to fetch latest Claude Code version; using ${resolved}`
549
- );
550
- return resolved;
551
- })();
552
- try {
553
- return await inflight;
554
- } finally {
555
- inflight = null;
556
- }
557
- }
558
- var REQUIRED_VERSION_PATTERN = /version\s+(\d+(?:\.\d+)+)\s+or\s+newer\s+is\s+required/i;
559
- function recordRequiredClaudeCodeVersion(message) {
560
- const required = REQUIRED_VERSION_PATTERN.exec(message ?? "")?.[1];
561
- if (!required) return null;
562
- if (versionFloor && compareClaudeCodeVersions(required, versionFloor) <= 0) return versionFloor;
563
- versionFloor = required;
564
- memoryCache = null;
565
- log(
566
- "WARN",
567
- "claude-code-version",
568
- `Provider requires Claude Code >= ${required}; pinning User-Agent floor`
569
- );
570
- try {
571
- const dir = getAppPaths().agentDir;
572
- mkdirSync2(dir, { recursive: true, mode: 448 });
573
- let existing = {};
574
- try {
575
- existing = JSON.parse(readFileSync2(cachePath(), "utf-8"));
576
- } catch {
577
- }
578
- writeFileSync2(
579
- cachePath(),
580
- JSON.stringify({
581
- version: existing.version ?? required,
582
- fetchedAt: existing.fetchedAt ?? 0,
583
- minVersion: required
584
- }),
585
- { mode: 384 }
586
- );
587
- } catch (err) {
588
- log(
589
- "WARN",
590
- "claude-code-version",
591
- `Failed to persist required version: ${err instanceof Error ? err.message : String(err)}`
592
- );
593
- }
594
- return required;
595
- }
596
- async function getClaudeCliUserAgent() {
597
- const version = await getClaudeCodeVersion();
598
- return `claude-cli/${version} (external, cli)`;
599
- }
259
+ import {
260
+ getClaudeCodeVersion,
261
+ getClaudeCliUserAgent,
262
+ pendingClaudeCodeVersionRefresh
263
+ } from "@prestyj/ai";
600
264
 
601
265
  // src/oauth/anthropic.ts
602
266
  var CLIENT_ID2 = atob("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
@@ -1463,81 +1127,872 @@ async function loginXai(callbacks) {
1463
1127
  interval += 5;
1464
1128
  }
1465
1129
  }
1466
- throw new Error("Grok login timed out. Please run login again.");
1130
+ throw new Error("Grok login timed out. Please run login again.");
1131
+ }
1132
+ async function refreshXaiToken(refreshToken) {
1133
+ const { status, data } = await postForm2("/oauth2/token", {
1134
+ client_id: clientId(),
1135
+ grant_type: "refresh_token",
1136
+ refresh_token: refreshToken
1137
+ });
1138
+ if (status === 200 && typeof data.access_token === "string") {
1139
+ return credsFromTokenResponse2(data, { fallbackRefreshToken: refreshToken });
1140
+ }
1141
+ const errorCode = typeof data.error === "string" ? data.error : "";
1142
+ throw new Error(`Grok token refresh failed (${status}): ${errorCode || errorDetail2(data)}`);
1143
+ }
1144
+
1145
+ // src/file-lock.ts
1146
+ import fs from "fs/promises";
1147
+ import { setTimeout as setTimeout2 } from "timers/promises";
1148
+ var STALE_TIMEOUT_MS = 1e4;
1149
+ var RETRY_INTERVAL_MS = 50;
1150
+ var MAX_WAIT_MS = 5e3;
1151
+ var PENDING_DELETE_CODES = /* @__PURE__ */ new Set(["EACCES", "EBUSY", "EPERM"]);
1152
+ async function withFileLock(filePath, fn) {
1153
+ const lockPath = filePath + ".lock";
1154
+ await acquireLock(lockPath);
1155
+ try {
1156
+ return await fn();
1157
+ } finally {
1158
+ await releaseLock(lockPath);
1159
+ }
1160
+ }
1161
+ async function acquireLock(lockPath) {
1162
+ const startTime = Date.now();
1163
+ let refusedWithoutLock = 0;
1164
+ while (true) {
1165
+ try {
1166
+ const info = { pid: process.pid, timestamp: Date.now() };
1167
+ await fs.writeFile(lockPath, JSON.stringify(info), { flag: "wx" });
1168
+ return;
1169
+ } catch (err) {
1170
+ const code = err.code;
1171
+ if (code !== "EEXIST") {
1172
+ if (process.platform !== "win32" || !code || !PENDING_DELETE_CODES.has(code)) throw err;
1173
+ const lockPresent = await lockFileExists(lockPath);
1174
+ if (!lockPresent && ++refusedWithoutLock > 3) throw err;
1175
+ if (Date.now() - startTime > MAX_WAIT_MS) throw err;
1176
+ await setTimeout2(RETRY_INTERVAL_MS);
1177
+ continue;
1178
+ }
1179
+ try {
1180
+ const content = await fs.readFile(lockPath, "utf-8");
1181
+ const info = JSON.parse(content);
1182
+ const isProcessAlive = isAlive(info.pid);
1183
+ const isStale = Date.now() - info.timestamp > STALE_TIMEOUT_MS;
1184
+ if (!isProcessAlive || isStale) {
1185
+ await fs.unlink(lockPath).catch(() => {
1186
+ });
1187
+ continue;
1188
+ }
1189
+ } catch {
1190
+ const stat = await fs.stat(lockPath).catch(() => null);
1191
+ if (!stat) continue;
1192
+ if (Date.now() - stat.mtimeMs > STALE_TIMEOUT_MS) {
1193
+ await fs.unlink(lockPath).catch(() => {
1194
+ });
1195
+ continue;
1196
+ }
1197
+ }
1198
+ if (Date.now() - startTime > MAX_WAIT_MS) {
1199
+ await fs.unlink(lockPath).catch(() => {
1200
+ });
1201
+ continue;
1202
+ }
1203
+ await setTimeout2(RETRY_INTERVAL_MS);
1204
+ }
1205
+ }
1206
+ }
1207
+ async function lockFileExists(lockPath) {
1208
+ try {
1209
+ await fs.stat(lockPath);
1210
+ return true;
1211
+ } catch (err) {
1212
+ return err.code !== "ENOENT";
1213
+ }
1214
+ }
1215
+ async function releaseLock(lockPath) {
1216
+ await fs.unlink(lockPath).catch(() => {
1217
+ });
1218
+ }
1219
+ function isAlive(pid) {
1220
+ try {
1221
+ process.kill(pid, 0);
1222
+ return true;
1223
+ } catch (err) {
1224
+ if (err.code === "EPERM") return true;
1225
+ return false;
1226
+ }
1227
+ }
1228
+
1229
+ // src/logger.ts
1230
+ import fs2 from "fs";
1231
+ import path2 from "path";
1232
+ import { randomBytes } from "crypto";
1233
+ import { environmentSecrets, redactText, redactValue } from "@prestyj/ai";
1234
+ var MAX_BYTES = 10 * 1024 * 1024;
1235
+ var ROTATED_GENERATIONS = 3;
1236
+ var MIN_HEADROOM_BYTES = 64 * 1024;
1237
+ var fd = null;
1238
+ var logPath = null;
1239
+ var fileBytes = 0;
1240
+ var processBytes = 0;
1241
+ var rotationFailed = false;
1242
+ var capped = false;
1243
+ var sessionId = "";
1244
+ var appName = "app";
1245
+ var cleanups = [];
1246
+ var exactSecrets = [];
1247
+ function rotateIfNeeded(filePath, force = false) {
1248
+ try {
1249
+ const st = fs2.statSync(filePath);
1250
+ if (!force && st.size <= MAX_BYTES - MIN_HEADROOM_BYTES) return;
1251
+ const rotated = `${filePath}.1`;
1252
+ for (let generation = ROTATED_GENERATIONS - 1; generation >= 1; generation--) {
1253
+ const older = `${filePath}.${generation + 1}`;
1254
+ try {
1255
+ fs2.unlinkSync(older);
1256
+ } catch {
1257
+ }
1258
+ try {
1259
+ fs2.renameSync(`${filePath}.${generation}`, older);
1260
+ } catch {
1261
+ }
1262
+ }
1263
+ try {
1264
+ fs2.unlinkSync(rotated);
1265
+ } catch {
1266
+ }
1267
+ fs2.renameSync(filePath, rotated);
1268
+ } catch {
1269
+ }
1270
+ }
1271
+ function rotateOpenLog() {
1272
+ if (fd === null || logPath === null) return false;
1273
+ const sizeBefore = fileBytes;
1274
+ try {
1275
+ fs2.closeSync(fd);
1276
+ } catch {
1277
+ }
1278
+ fd = null;
1279
+ rotateIfNeeded(logPath, true);
1280
+ try {
1281
+ fd = fs2.openSync(logPath, "a");
1282
+ fileBytes = fs2.fstatSync(fd).size;
1283
+ } catch {
1284
+ if (fd !== null) {
1285
+ try {
1286
+ fs2.closeSync(fd);
1287
+ } catch {
1288
+ }
1289
+ }
1290
+ fd = null;
1291
+ capped = true;
1292
+ return false;
1293
+ }
1294
+ if (fileBytes >= sizeBefore) rotationFailed = true;
1295
+ return true;
1296
+ }
1297
+ function openLog(filePath, name) {
1298
+ if (fd !== null || capped) return false;
1299
+ appName = name;
1300
+ exactSecrets = environmentSecrets(process.env);
1301
+ try {
1302
+ fs2.mkdirSync(path2.dirname(filePath), { recursive: true, mode: 448 });
1303
+ } catch {
1304
+ }
1305
+ rotateIfNeeded(filePath);
1306
+ try {
1307
+ fd = fs2.openSync(filePath, "a");
1308
+ } catch {
1309
+ fd = null;
1310
+ fileBytes = 0;
1311
+ return false;
1312
+ }
1313
+ try {
1314
+ fileBytes = fs2.fstatSync(fd).size;
1315
+ } catch {
1316
+ try {
1317
+ fs2.closeSync(fd);
1318
+ } catch {
1319
+ }
1320
+ fd = null;
1321
+ fileBytes = 0;
1322
+ return false;
1323
+ }
1324
+ logPath = filePath;
1325
+ processBytes = 0;
1326
+ rotationFailed = false;
1327
+ sessionId = randomBytes(4).toString("hex");
1328
+ try {
1329
+ if (fileBytes < MAX_BYTES) {
1330
+ const written = fs2.writeSync(fd, "\n");
1331
+ fileBytes += written;
1332
+ processBytes += written;
1333
+ }
1334
+ } catch {
1335
+ }
1336
+ return true;
1337
+ }
1338
+ function getSessionId() {
1339
+ return sessionId;
1340
+ }
1341
+ function isLoggerOpen() {
1342
+ return fd !== null;
1343
+ }
1344
+ function log(level, category, message, data) {
1345
+ if (fd === null) return;
1346
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
1347
+ const safeMessage = redactText(message, { secrets: exactSecrets });
1348
+ let line = `[${ts}] [sid=${sessionId}] [${level}] [${category}] ${safeMessage}`;
1349
+ if (data) {
1350
+ const safeData = redactValue(data, { secrets: exactSecrets });
1351
+ const pairs = Object.entries(safeData).map(([k, v]) => {
1352
+ if (typeof v === "string") return `${k}=${v}`;
1353
+ if (typeof v === "bigint") return `${k}=${String(v)}`;
1354
+ return `${k}=${JSON.stringify(v)}`;
1355
+ }).join(" ");
1356
+ if (pairs) line += ` ${pairs}`;
1357
+ }
1358
+ line += "\n";
1359
+ const lineBytes = Buffer.byteLength(line);
1360
+ if (processBytes + lineBytes > MAX_BYTES) {
1361
+ const capLine = `[${ts}] [sid=${sessionId}] [WARN] [logger] Log cap reached; file logging disabled until restart
1362
+ `;
1363
+ try {
1364
+ if (fileBytes + Buffer.byteLength(capLine) <= MAX_BYTES) {
1365
+ fileBytes += fs2.writeSync(fd, capLine);
1366
+ }
1367
+ fs2.closeSync(fd);
1368
+ } catch {
1369
+ }
1370
+ fd = null;
1371
+ capped = true;
1372
+ return;
1373
+ }
1374
+ if (fileBytes + lineBytes > MAX_BYTES && !rotationFailed && !rotateOpenLog()) return;
1375
+ if (fd === null) return;
1376
+ try {
1377
+ const written = fs2.writeSync(fd, line);
1378
+ fileBytes += written;
1379
+ processBytes += written;
1380
+ } catch {
1381
+ }
1382
+ }
1383
+ function registerLogCleanup(fn) {
1384
+ cleanups.push(fn);
1385
+ }
1386
+ function closeLogger(opts) {
1387
+ if (fd !== null) {
1388
+ if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName} shutting down`);
1389
+ try {
1390
+ if (fd !== null) fs2.closeSync(fd);
1391
+ } catch {
1392
+ }
1393
+ }
1394
+ fd = null;
1395
+ logPath = null;
1396
+ fileBytes = 0;
1397
+ processBytes = 0;
1398
+ rotationFailed = false;
1399
+ capped = false;
1400
+ exactSecrets = [];
1401
+ for (const unsub of cleanups) unsub();
1402
+ cleanups = [];
1403
+ }
1404
+
1405
+ // src/hidden-providers.ts
1406
+ var HIDDEN_PROVIDERS = ["gemini"];
1407
+ function isHiddenProvider(provider) {
1408
+ return HIDDEN_PROVIDERS.includes(provider);
1409
+ }
1410
+
1411
+ // src/claude-code/runtime.ts
1412
+ import { spawn } from "child_process";
1413
+ import crypto5 from "crypto";
1414
+ import fs4 from "fs";
1415
+ import fsp2 from "fs/promises";
1416
+ import path3 from "path";
1417
+
1418
+ // src/claude-code/tar.ts
1419
+ import fs3 from "fs";
1420
+ import fsp from "fs/promises";
1421
+ import zlib from "zlib";
1422
+ var BLOCK = 512;
1423
+ function readString(buf, offset, length) {
1424
+ const end = buf.indexOf(0, offset);
1425
+ return buf.toString("utf8", offset, end === -1 || end > offset + length ? offset + length : end);
1426
+ }
1427
+ function readSize(buf, offset) {
1428
+ if (buf[offset] & 128) {
1429
+ let value = buf[offset] & 127;
1430
+ for (let i = 1; i < 12; i++) value = value * 256 + buf[offset + i];
1431
+ return value;
1432
+ }
1433
+ const text = readString(buf, offset, 12).trim();
1434
+ return text ? parseInt(text, 8) : 0;
1435
+ }
1436
+ function paxPath(data) {
1437
+ let pos = 0;
1438
+ while (pos < data.length) {
1439
+ const space = data.indexOf(32, pos);
1440
+ if (space === -1) break;
1441
+ const len = parseInt(data.toString("utf8", pos, space), 10);
1442
+ if (!Number.isFinite(len) || len <= 0) break;
1443
+ const record = data.toString("utf8", space + 1, pos + len - 1);
1444
+ const eq = record.indexOf("=");
1445
+ if (eq !== -1 && record.slice(0, eq) === "path") return record.slice(eq + 1);
1446
+ pos += len;
1447
+ }
1448
+ return void 0;
1449
+ }
1450
+ async function extractFileFromTarGz(tgzPath, entryName, destPath) {
1451
+ const input = fs3.createReadStream(tgzPath).pipe(zlib.createGunzip());
1452
+ let pending = Buffer.alloc(0);
1453
+ let remaining = 0;
1454
+ let padding = 0;
1455
+ let kind = "skip";
1456
+ let meta = [];
1457
+ let overridePath;
1458
+ let out;
1459
+ let found = false;
1460
+ try {
1461
+ for await (const chunk of input) {
1462
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
1463
+ let pos = 0;
1464
+ while (pos < pending.length) {
1465
+ if (remaining > 0) {
1466
+ const take = Math.min(remaining, pending.length - pos);
1467
+ const slice = pending.subarray(pos, pos + take);
1468
+ if (kind === "target") await out.write(slice);
1469
+ else if (kind === "pax" || kind === "longname") meta.push(Buffer.from(slice));
1470
+ pos += take;
1471
+ remaining -= take;
1472
+ if (remaining === 0) {
1473
+ if (kind === "target") {
1474
+ await out.close();
1475
+ out = void 0;
1476
+ found = true;
1477
+ } else if (kind === "pax") {
1478
+ overridePath = paxPath(Buffer.concat(meta)) ?? overridePath;
1479
+ } else if (kind === "longname") {
1480
+ overridePath = readString(Buffer.concat(meta), 0, Number.MAX_SAFE_INTEGER);
1481
+ }
1482
+ }
1483
+ continue;
1484
+ }
1485
+ if (padding > 0) {
1486
+ const skip = Math.min(padding, pending.length - pos);
1487
+ pos += skip;
1488
+ padding -= skip;
1489
+ continue;
1490
+ }
1491
+ if (found) break;
1492
+ if (pending.length - pos < BLOCK) break;
1493
+ const header = pending.subarray(pos, pos + BLOCK);
1494
+ pos += BLOCK;
1495
+ if (header.every((b) => b === 0)) continue;
1496
+ const size = readSize(header, 124);
1497
+ const type2 = String.fromCharCode(header[156] || 48);
1498
+ let name = readString(header, 0, 100);
1499
+ if (readString(header, 257, 6) === "ustar") {
1500
+ const prefix = readString(header, 345, 155);
1501
+ if (prefix) name = `${prefix}/${name}`;
1502
+ }
1503
+ remaining = size;
1504
+ padding = (BLOCK - size % BLOCK) % BLOCK;
1505
+ meta = [];
1506
+ if (type2 === "x") kind = "pax";
1507
+ else if (type2 === "L") kind = "longname";
1508
+ else {
1509
+ const path4 = overridePath ?? name;
1510
+ overridePath = void 0;
1511
+ if ((type2 === "0" || type2 === "\0" || type2 === "7") && path4 === entryName) {
1512
+ kind = "target";
1513
+ out = await fsp.open(destPath, "w", 493);
1514
+ if (size === 0) {
1515
+ await out.close();
1516
+ out = void 0;
1517
+ found = true;
1518
+ }
1519
+ } else {
1520
+ kind = "skip";
1521
+ }
1522
+ }
1523
+ }
1524
+ pending = pos < pending.length ? Buffer.from(pending.subarray(pos)) : Buffer.alloc(0);
1525
+ if (found) break;
1526
+ }
1527
+ if (!found && out) throw new Error(`Archive ended inside ${entryName}`);
1528
+ return found;
1529
+ } finally {
1530
+ if (out) await out.close().catch(() => {
1531
+ });
1532
+ input.destroy();
1533
+ }
1534
+ }
1535
+
1536
+ // src/claude-code/manifest.json
1537
+ var manifest_default = {
1538
+ sdkVersion: "0.3.318",
1539
+ claudeCodeVersion: "2.1.318",
1540
+ platforms: {
1541
+ "darwin-arm64": {
1542
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.318.tgz",
1543
+ integrity: "sha512-AWoXeDXzAMD3RaA21lWuHvCrKd8xmbTTmKjovninn4j07jheoVSMzFbCFjpp4kk5TdhT36JtWPkAxvjNMbcO8w==",
1544
+ bin: "claude"
1545
+ },
1546
+ "darwin-x64": {
1547
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.318.tgz",
1548
+ integrity: "sha512-6CkZ5PCdebSY/LePp16sf/HYRtM6zVuxtn8qYICFS5KUZFsjccJJ9swVsOdHXNHi4SWZcSmIFTwoUbfFCzisRw==",
1549
+ bin: "claude"
1550
+ },
1551
+ "linux-arm64": {
1552
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.318.tgz",
1553
+ integrity: "sha512-mBm4su17aMitLBBCQj3bHdejyUDY6z/ormGih+HG24N689RSbdKECjGjkT87tDBIR/4jyoqmuSeHqM1DI8TJlg==",
1554
+ bin: "claude"
1555
+ },
1556
+ "linux-arm64-musl": {
1557
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.318.tgz",
1558
+ integrity: "sha512-l4LSYFOrvlYCrUImGfxMTQ0wg+T3s9CBhrBvPF/0oJGKZg+QnxHHU8jUVm9e9/xYmDRTtqFIrr4id/5AfH4XGw==",
1559
+ bin: "claude"
1560
+ },
1561
+ "linux-x64": {
1562
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.318.tgz",
1563
+ integrity: "sha512-+mE+ueBD3oRFdaG16rd0h+LMjdeivGxL0pr/+FZK7JeLWVu+yPSw/f/X02b9oK36/DWykiFTu2G6HnJ9/+YO6w==",
1564
+ bin: "claude"
1565
+ },
1566
+ "linux-x64-musl": {
1567
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.318.tgz",
1568
+ integrity: "sha512-SAF3lj/2OzTU84p+OOA13QEKA9+5fYAw0M9E7AJjdnRmVFGqQfbV7Do1i1f9Sj0mIubB3rLTRphGRw8O4HZjgA==",
1569
+ bin: "claude"
1570
+ },
1571
+ "win32-arm64": {
1572
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.318.tgz",
1573
+ integrity: "sha512-19iVSZ4379QbZU1XnGUtfFvhKS1WzS8H1sbU/DbrzqbJ5Kq1eB1drj+obB1fCxTh6m26tRPj0zMJmdeu/jk3Gw==",
1574
+ bin: "claude.exe"
1575
+ },
1576
+ "win32-x64": {
1577
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.318.tgz",
1578
+ integrity: "sha512-ZdKVWpyVNVt0cXrOf8sUBaxcxLEAP+oGMdQDLBWr/BqOxTWLy7TBWOj1kzw+wVg/9WIkjkgQWeJzGXPWulR1sA==",
1579
+ bin: "claude.exe"
1580
+ }
1581
+ }
1582
+ };
1583
+
1584
+ // src/claude-code/runtime.ts
1585
+ var CLAUDE_CODE_MANIFEST = manifest_default;
1586
+ var CLAUDE_CODE_AUTH_KEY = "anthropic-claude-code";
1587
+ var CLAUDE_CODE_AUTH_MARKER = { via: "claude-code" };
1588
+ function isClaudeCodeAuthMarker(value) {
1589
+ return value?.via === CLAUDE_CODE_AUTH_MARKER.via;
1590
+ }
1591
+ function isLegacyClaudeOAuth(value) {
1592
+ const token = value?.accessToken;
1593
+ return typeof token === "string" && token.startsWith("sk-ant-oat");
1594
+ }
1595
+ function isMusl() {
1596
+ if (process.platform !== "linux") return false;
1597
+ const report = typeof process.report?.getReport === "function" ? process.report.getReport() : null;
1598
+ return report != null && report.header?.glibcVersionRuntime === void 0;
1599
+ }
1600
+ function claudeCodePlatformKey(info = { platform: process.platform, arch: process.arch, musl: isMusl() }) {
1601
+ const arch2 = info.arch === "arm64" || info.arch === "x64" ? info.arch : null;
1602
+ if (!arch2) return null;
1603
+ if (info.platform === "darwin" || info.platform === "win32") return `${info.platform}-${arch2}`;
1604
+ if (info.platform === "linux") return `linux-${arch2}${info.musl ? "-musl" : ""}`;
1605
+ return null;
1606
+ }
1607
+ function resolveAsset(opts) {
1608
+ const manifest = opts.manifest ?? CLAUDE_CODE_MANIFEST;
1609
+ const key = opts.platformKey ?? claudeCodePlatformKey();
1610
+ const asset = key ? manifest.platforms[key] : void 0;
1611
+ if (!asset) {
1612
+ throw new Error(
1613
+ `Claude Code isn't available for ${process.platform}-${process.arch}. Use an Anthropic API key instead.`
1614
+ );
1615
+ }
1616
+ return { manifest, asset };
1617
+ }
1618
+ function claudeCodeHome(opts = {}) {
1619
+ return opts.home ?? getAppPaths().claudeCodeDir;
1620
+ }
1621
+ function claudeCodeConfigDir(opts = {}) {
1622
+ return opts.home ? path3.join(opts.home, "config") : getAppPaths().claudeCodeConfigDir;
1623
+ }
1624
+ function claudeCodeBinaryPath(opts = {}) {
1625
+ const { manifest, asset } = resolveAsset(opts);
1626
+ return path3.join(claudeCodeHome(opts), manifest.claudeCodeVersion, asset.bin);
1627
+ }
1628
+ function resolveClaudeCodeBinary(opts = {}) {
1629
+ let binary;
1630
+ try {
1631
+ binary = claudeCodeBinaryPath(opts);
1632
+ } catch {
1633
+ return null;
1634
+ }
1635
+ try {
1636
+ return fs4.statSync(binary).isFile() ? binary : null;
1637
+ } catch {
1638
+ return null;
1639
+ }
1640
+ }
1641
+ var installs = /* @__PURE__ */ new Map();
1642
+ async function ensureClaudeCodeBinary(opts = {}) {
1643
+ const existing = resolveClaudeCodeBinary(opts);
1644
+ if (existing) return existing;
1645
+ const target = claudeCodeBinaryPath(opts);
1646
+ let install = installs.get(target);
1647
+ if (!install) {
1648
+ install = installClaudeCode(opts).finally(() => installs.delete(target));
1649
+ installs.set(target, install);
1650
+ }
1651
+ return install;
1652
+ }
1653
+ async function installClaudeCode(opts) {
1654
+ const { manifest, asset } = resolveAsset(opts);
1655
+ const home = claudeCodeHome(opts);
1656
+ const versionDir = path3.join(home, manifest.claudeCodeVersion);
1657
+ const binary = path3.join(versionDir, asset.bin);
1658
+ await fsp2.mkdir(home, { recursive: true });
1659
+ const tag = `${process.pid}-${crypto5.randomBytes(4).toString("hex")}`;
1660
+ const tarball = path3.join(home, `.download-${tag}.tgz`);
1661
+ const staging = path3.join(home, `.staging-${tag}`);
1662
+ try {
1663
+ await download(asset, tarball, opts);
1664
+ opts.onProgress?.({ phase: "extract" });
1665
+ await fsp2.mkdir(staging, { recursive: true });
1666
+ const found = await extractFileFromTarGz(
1667
+ tarball,
1668
+ `package/${asset.bin}`,
1669
+ path3.join(staging, asset.bin)
1670
+ );
1671
+ if (!found) throw new Error(`The Claude Code download has no ${asset.bin} binary.`);
1672
+ await fsp2.chmod(path3.join(staging, asset.bin), 493);
1673
+ try {
1674
+ await fsp2.rename(staging, versionDir);
1675
+ } catch (err) {
1676
+ if (!fs4.existsSync(binary)) throw err;
1677
+ }
1678
+ await removeOldVersions(home, manifest.claudeCodeVersion);
1679
+ return binary;
1680
+ } finally {
1681
+ await fsp2.rm(tarball, { force: true }).catch(() => {
1682
+ });
1683
+ await fsp2.rm(staging, { recursive: true, force: true }).catch(() => {
1684
+ });
1685
+ }
1686
+ }
1687
+ async function download(asset, dest, opts) {
1688
+ const doFetch = opts.fetch ?? fetch;
1689
+ const res = await doFetch(asset.url, { signal: opts.signal });
1690
+ if (!res.ok || !res.body) {
1691
+ throw new Error(`Claude Code download failed (HTTP ${res.status}).`);
1692
+ }
1693
+ const totalBytes = Number(res.headers.get("content-length")) || void 0;
1694
+ const hash = crypto5.createHash("sha512");
1695
+ const out = await fsp2.open(dest, "w");
1696
+ let receivedBytes = 0;
1697
+ let lastReported = -1;
1698
+ try {
1699
+ opts.onProgress?.({ phase: "download", receivedBytes, totalBytes });
1700
+ for await (const chunk of res.body) {
1701
+ if (opts.signal?.aborted) throw opts.signal.reason ?? new Error("Download cancelled.");
1702
+ hash.update(chunk);
1703
+ await out.write(chunk);
1704
+ receivedBytes += chunk.byteLength;
1705
+ const step = totalBytes ? Math.floor(receivedBytes / totalBytes * 100) : Math.floor(receivedBytes / 4194304);
1706
+ if (step !== lastReported) {
1707
+ lastReported = step;
1708
+ opts.onProgress?.({ phase: "download", receivedBytes, totalBytes });
1709
+ }
1710
+ }
1711
+ } finally {
1712
+ await out.close();
1713
+ }
1714
+ opts.onProgress?.({ phase: "verify" });
1715
+ const expected = asset.integrity.replace(/^sha512-/, "");
1716
+ if (hash.digest("base64") !== expected) {
1717
+ throw new Error(
1718
+ "The Claude Code download didn't match its pinned checksum, so it was discarded."
1719
+ );
1720
+ }
1721
+ }
1722
+ async function removeOldVersions(home, keep) {
1723
+ let entries;
1724
+ try {
1725
+ entries = await fsp2.readdir(home, { withFileTypes: true });
1726
+ } catch {
1727
+ return;
1728
+ }
1729
+ for (const entry of entries) {
1730
+ if (!entry.isDirectory() || entry.name === keep || entry.name === "config") continue;
1731
+ if (!/^\d+\.\d+\.\d+/.test(entry.name)) continue;
1732
+ await fsp2.rm(path3.join(home, entry.name), { recursive: true, force: true }).catch(() => {
1733
+ });
1734
+ }
1467
1735
  }
1468
- async function refreshXaiToken(refreshToken) {
1469
- const { status, data } = await postForm2("/oauth2/token", {
1470
- client_id: clientId(),
1471
- grant_type: "refresh_token",
1472
- refresh_token: refreshToken
1736
+ function formatClaudeCodeInstallProgress(progress) {
1737
+ if (progress.phase === "verify") return "Checking the Claude Code download\u2026";
1738
+ if (progress.phase === "extract") return "Unpacking Claude Code\u2026";
1739
+ const mb = (bytes) => Math.round(bytes / 1048576);
1740
+ if (!progress.totalBytes) return `Downloading Claude Code\u2026 ${mb(progress.receivedBytes)} MB`;
1741
+ const pct = Math.floor(progress.receivedBytes / progress.totalBytes * 100);
1742
+ return `Downloading Claude Code\u2026 ${pct}% (${mb(progress.receivedBytes)} of ${mb(progress.totalBytes)} MB)`;
1743
+ }
1744
+ var STRIPPED_ENV = [
1745
+ "ANTHROPIC_API_KEY",
1746
+ "ANTHROPIC_AUTH_TOKEN",
1747
+ "ANTHROPIC_BASE_URL",
1748
+ "CLAUDE_CODE_OAUTH_TOKEN",
1749
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
1750
+ "CLAUDE_CODE_USE_BEDROCK",
1751
+ "CLAUDE_CODE_USE_VERTEX",
1752
+ "CLAUDE_CODE_USE_FOUNDRY",
1753
+ "NODE_OPTIONS"
1754
+ ];
1755
+ function claudeCodeEnv(opts = {}, base = process.env) {
1756
+ const env = {};
1757
+ for (const [key, value] of Object.entries(base)) {
1758
+ if (value !== void 0 && !STRIPPED_ENV.includes(key)) env[key] = value;
1759
+ }
1760
+ env.CLAUDE_CONFIG_DIR = claudeCodeConfigDir(opts);
1761
+ env.DISABLE_AUTOUPDATER = "1";
1762
+ return env;
1763
+ }
1764
+ function runCommand(opts) {
1765
+ if (opts.binary) return { command: opts.binary, prefix: opts.binaryArgs ?? [] };
1766
+ const binary = resolveClaudeCodeBinary(opts);
1767
+ if (!binary) throw new Error("Claude Code isn't installed yet. Sign in with Claude first.");
1768
+ return { command: binary, prefix: [] };
1769
+ }
1770
+ function runClaude(args, opts) {
1771
+ const { command, prefix } = runCommand(opts);
1772
+ return new Promise((resolve, reject) => {
1773
+ const child = spawn(command, [...prefix, ...args], {
1774
+ env: claudeCodeEnv(opts),
1775
+ stdio: ["ignore", "pipe", "pipe"],
1776
+ windowsHide: true,
1777
+ signal: opts.signal
1778
+ });
1779
+ let stdout = "";
1780
+ let stderr = "";
1781
+ child.stdout.on("data", (d) => stdout += d.toString());
1782
+ child.stderr.on("data", (d) => stderr += d.toString());
1783
+ child.on("error", reject);
1784
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
1473
1785
  });
1474
- if (status === 200 && typeof data.access_token === "string") {
1475
- return credsFromTokenResponse2(data, { fallbackRefreshToken: refreshToken });
1786
+ }
1787
+ async function claudeCodeAuthStatus(opts = {}) {
1788
+ if (!opts.binary && !resolveClaudeCodeBinary(opts)) return { loggedIn: false };
1789
+ const { stdout } = await runClaude(["auth", "status", "--json"], opts);
1790
+ try {
1791
+ const parsed = JSON.parse(stdout);
1792
+ return {
1793
+ loggedIn: parsed.loggedIn === true,
1794
+ ...typeof parsed.authMethod === "string" ? { authMethod: parsed.authMethod } : {},
1795
+ ...typeof parsed.email === "string" ? { email: parsed.email } : {},
1796
+ ...typeof parsed.subscriptionType === "string" ? { subscriptionType: parsed.subscriptionType } : {}
1797
+ };
1798
+ } catch {
1799
+ return { loggedIn: false };
1476
1800
  }
1477
- const errorCode = typeof data.error === "string" ? data.error : "";
1478
- throw new Error(`Grok token refresh failed (${status}): ${errorCode || errorDetail2(data)}`);
1479
1801
  }
1480
-
1481
- // src/file-lock.ts
1482
- import fs3 from "fs/promises";
1483
- import { setTimeout as setTimeout2 } from "timers/promises";
1484
- var STALE_TIMEOUT_MS = 1e4;
1485
- var RETRY_INTERVAL_MS = 50;
1486
- var MAX_WAIT_MS = 5e3;
1487
- async function withFileLock(filePath, fn) {
1488
- const lockPath = filePath + ".lock";
1489
- await acquireLock(lockPath);
1802
+ async function logoutClaudeCode(opts = {}) {
1803
+ if (!opts.binary && !resolveClaudeCodeBinary(opts)) return;
1804
+ const { code, stderr } = await runClaude(["auth", "logout"], opts);
1805
+ if (code !== 0) throw new Error(stderr.trim() || `claude auth logout exited with ${code}`);
1806
+ }
1807
+ var OPEN_URL_HOOK = `const arg = String(process.argv[1] || "");
1808
+ const file = process.env.EZ_CLAUDE_CODE_URL_FILE;
1809
+ if (file && /https?:/.test(arg)) {
1810
+ require("node:fs").appendFileSync(file, arg + "\\n");
1811
+ process.exit(0);
1812
+ }
1813
+ `;
1814
+ var CAPTURE_WAIT_MS = 3e3;
1815
+ function stripAnsi(text) {
1816
+ return text.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[A-Za-z]/g, "");
1817
+ }
1818
+ function claudeCodeCallbackUrl(manualUrl, captured) {
1819
+ const port = /localhost(?::|%3A)(\d{2,5})(?:\/|%2F)callback/i.exec(captured)?.[1];
1820
+ if (!port) return null;
1490
1821
  try {
1491
- return await fn();
1822
+ const url = new URL(manualUrl);
1823
+ url.searchParams.set("redirect_uri", `http://localhost:${port}/callback`);
1824
+ return url.toString();
1825
+ } catch {
1826
+ return null;
1827
+ }
1828
+ }
1829
+ async function loginClaudeCode(callbacks, opts = {}) {
1830
+ const { command, prefix } = runCommand(opts);
1831
+ const home = claudeCodeHome(opts);
1832
+ await fsp2.mkdir(claudeCodeConfigDir(opts), { recursive: true });
1833
+ const tag = `${process.pid}-${crypto5.randomBytes(4).toString("hex")}`;
1834
+ const hookFile = path3.join(home, `.open-url-${tag}.cjs`);
1835
+ const urlFile = path3.join(home, `.open-url-${tag}.txt`);
1836
+ await fsp2.writeFile(hookFile, OPEN_URL_HOOK);
1837
+ const env = {
1838
+ ...claudeCodeEnv(opts),
1839
+ BROWSER: process.execPath,
1840
+ NODE_OPTIONS: `--require ${JSON.stringify(hookFile)}`,
1841
+ EZ_CLAUDE_CODE_URL_FILE: urlFile
1842
+ };
1843
+ const promptAbort = new AbortController();
1844
+ let timer;
1845
+ try {
1846
+ await new Promise((resolve, reject) => {
1847
+ const child = spawn(command, [...prefix, "auth", "login", "--claudeai"], {
1848
+ env,
1849
+ stdio: ["pipe", "pipe", "pipe"],
1850
+ windowsHide: true
1851
+ });
1852
+ let stdout = "";
1853
+ let stderr = "";
1854
+ let manualUrl = null;
1855
+ let opened = false;
1856
+ const onAbort = () => child.kill();
1857
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
1858
+ const open = (url, needsCode) => {
1859
+ if (opened) return;
1860
+ opened = true;
1861
+ clearInterval(timer);
1862
+ callbacks.onOpenUrl(url);
1863
+ callbacks.onStatus("Finish signing in to Claude in your browser\u2026");
1864
+ if (!needsCode) return;
1865
+ void callbacks.onPromptCode("Paste the code shown after signing in to Claude:", promptAbort.signal).then((code) => {
1866
+ const trimmed = code.trim();
1867
+ if (trimmed && !child.stdin.destroyed) child.stdin.write(`${trimmed}
1868
+ `);
1869
+ }).catch(() => {
1870
+ });
1871
+ };
1872
+ child.stdout.on("data", (d) => {
1873
+ stdout += d.toString();
1874
+ if (manualUrl) return;
1875
+ const match = /visit:\s*(https:\/\/\S+)/.exec(stripAnsi(stdout));
1876
+ if (!match) return;
1877
+ manualUrl = match[1];
1878
+ const started = Date.now();
1879
+ timer = setInterval(() => {
1880
+ let captured = "";
1881
+ try {
1882
+ captured = fs4.readFileSync(urlFile, "utf8");
1883
+ } catch {
1884
+ }
1885
+ const callbackUrl = captured ? claudeCodeCallbackUrl(manualUrl, captured) : null;
1886
+ if (callbackUrl) open(callbackUrl, false);
1887
+ else if (Date.now() - started > (opts.browserWaitMs ?? CAPTURE_WAIT_MS))
1888
+ open(manualUrl, true);
1889
+ }, 100);
1890
+ });
1891
+ child.stderr.on("data", (d) => stderr += d.toString());
1892
+ child.on("error", reject);
1893
+ child.on("close", (code) => {
1894
+ opts.signal?.removeEventListener("abort", onAbort);
1895
+ if (opts.signal?.aborted) reject(new Error("Sign-in cancelled."));
1896
+ else if (code === 0) resolve();
1897
+ else {
1898
+ const detail = stripAnsi(stderr).trim().split("\n").pop()?.trim();
1899
+ reject(new Error(detail || `Claude sign-in failed (exit ${code}).`));
1900
+ }
1901
+ });
1902
+ });
1492
1903
  } finally {
1493
- await releaseLock(lockPath);
1904
+ clearInterval(timer);
1905
+ promptAbort.abort();
1906
+ await fsp2.rm(hookFile, { force: true }).catch(() => {
1907
+ });
1908
+ await fsp2.rm(urlFile, { force: true }).catch(() => {
1909
+ });
1494
1910
  }
1495
1911
  }
1496
- async function acquireLock(lockPath) {
1497
- const startTime = Date.now();
1498
- while (true) {
1912
+
1913
+ // src/auth-storage.ts
1914
+ import { LOCAL_NO_API_KEY } from "@prestyj/ai";
1915
+
1916
+ // src/minimax-region.ts
1917
+ var MINIMAX_GLOBAL_BASE_URL = "https://api.minimax.io/anthropic";
1918
+ var MINIMAX_CN_BASE_URL = "https://api.minimax.cn/anthropic";
1919
+ var REGION_HOSTS = [
1920
+ { host: "https://api.minimax.io", baseUrl: MINIMAX_GLOBAL_BASE_URL },
1921
+ { host: "https://api.minimax.cn", baseUrl: MINIMAX_CN_BASE_URL }
1922
+ ];
1923
+ var KEY_KNOWN_CODES = /* @__PURE__ */ new Set([0, 2062]);
1924
+ var KEY_REJECTED_CODES = /* @__PURE__ */ new Set([1004, 2049]);
1925
+ async function probeRegion(host, apiKey, fetchImpl, timeoutMs) {
1926
+ const url = apiKey.startsWith("sk-api-") ? `${host}/account/query_balance` : `${host}/v1/token_plan/remains`;
1927
+ let sawRejection = false;
1928
+ const authHeaders = [
1929
+ { Authorization: `Bearer ${apiKey}` },
1930
+ { "x-api-key": apiKey }
1931
+ ];
1932
+ for (const auth of authHeaders) {
1933
+ let res;
1499
1934
  try {
1500
- const info = { pid: process.pid, timestamp: Date.now() };
1501
- await fs3.writeFile(lockPath, JSON.stringify(info), { flag: "wx" });
1502
- return;
1503
- } catch (err) {
1504
- if (err.code !== "EEXIST") throw err;
1505
- try {
1506
- const content = await fs3.readFile(lockPath, "utf-8");
1507
- const info = JSON.parse(content);
1508
- const isProcessAlive = isAlive(info.pid);
1509
- const isStale = Date.now() - info.timestamp > STALE_TIMEOUT_MS;
1510
- if (!isProcessAlive || isStale) {
1511
- await fs3.unlink(lockPath).catch(() => {
1512
- });
1513
- continue;
1514
- }
1515
- } catch {
1516
- await fs3.unlink(lockPath).catch(() => {
1517
- });
1518
- continue;
1519
- }
1520
- if (Date.now() - startTime > MAX_WAIT_MS) {
1521
- await fs3.unlink(lockPath).catch(() => {
1522
- });
1523
- continue;
1524
- }
1525
- await setTimeout2(RETRY_INTERVAL_MS);
1935
+ res = await fetchImpl(url, {
1936
+ headers: { ...auth, "Content-Type": "application/json" },
1937
+ signal: AbortSignal.timeout(timeoutMs)
1938
+ });
1939
+ } catch {
1940
+ return "inconclusive";
1941
+ }
1942
+ if (res.status === 401 || res.status === 403) {
1943
+ sawRejection = true;
1944
+ continue;
1945
+ }
1946
+ if (!res.ok) return "inconclusive";
1947
+ let code;
1948
+ try {
1949
+ code = (await res.json()).base_resp?.status_code;
1950
+ } catch {
1951
+ return "inconclusive";
1952
+ }
1953
+ if (typeof code === "number" && KEY_KNOWN_CODES.has(code)) return "authorized";
1954
+ if (typeof code === "number" && KEY_REJECTED_CODES.has(code)) {
1955
+ sawRejection = true;
1956
+ continue;
1526
1957
  }
1958
+ return "inconclusive";
1527
1959
  }
1960
+ return sawRejection ? "unauthorized" : "inconclusive";
1528
1961
  }
1529
- async function releaseLock(lockPath) {
1530
- await fs3.unlink(lockPath).catch(() => {
1531
- });
1962
+ async function detectMiniMaxBaseUrl(apiKey, options = {}) {
1963
+ const fetchImpl = options.fetch ?? fetch;
1964
+ const timeoutMs = options.timeoutMs ?? 5e3;
1965
+ const results = await Promise.all(
1966
+ REGION_HOSTS.map((r) => probeRegion(r.host, apiKey, fetchImpl, timeoutMs))
1967
+ );
1968
+ const index = results.indexOf("authorized");
1969
+ return index === -1 ? void 0 : REGION_HOSTS[index].baseUrl;
1532
1970
  }
1533
- function isAlive(pid) {
1534
- try {
1535
- process.kill(pid, 0);
1536
- return true;
1537
- } catch (err) {
1538
- if (err.code === "EPERM") return true;
1539
- return false;
1540
- }
1971
+
1972
+ // src/xiaomi-region.ts
1973
+ var XIAOMI_TOKEN_PLAN_BASE_URLS = [
1974
+ "https://token-plan-sgp.xiaomimimo.com/v1",
1975
+ "https://token-plan-ams.xiaomimimo.com/v1",
1976
+ "https://token-plan-cn.xiaomimimo.com/v1"
1977
+ ];
1978
+ async function detectXiaomiTokenPlanBaseUrl(apiKey, options = {}) {
1979
+ const fetchImpl = options.fetch ?? fetch;
1980
+ const timeoutMs = options.timeoutMs ?? 5e3;
1981
+ const accepted = await Promise.all(
1982
+ XIAOMI_TOKEN_PLAN_BASE_URLS.map(async (baseUrl) => {
1983
+ try {
1984
+ const res = await fetchImpl(`${baseUrl}/models`, {
1985
+ headers: { Authorization: `Bearer ${apiKey}` },
1986
+ signal: AbortSignal.timeout(timeoutMs)
1987
+ });
1988
+ return res.ok;
1989
+ } catch {
1990
+ return false;
1991
+ }
1992
+ })
1993
+ );
1994
+ const index = accepted.indexOf(true);
1995
+ return index === -1 ? void 0 : XIAOMI_TOKEN_PLAN_BASE_URLS[index];
1541
1996
  }
1542
1997
 
1543
1998
  // src/auth-storage.ts
@@ -1590,9 +2045,18 @@ function activeBaseUrlEntry(data, provider) {
1590
2045
  }
1591
2046
  return data[provider];
1592
2047
  }
2048
+ var MINIMAX_REGION_RETRY_MS = 5 * 60 * 1e3;
2049
+ var miniMaxRegionProbes = /* @__PURE__ */ new Map();
2050
+ function cachedMiniMaxRegion(apiKey) {
2051
+ const cached = miniMaxRegionProbes.get(apiKey);
2052
+ if (cached && Date.now() - cached.at < MINIMAX_REGION_RETRY_MS) return cached.result;
2053
+ const result = detectMiniMaxBaseUrl(apiKey).catch(() => void 0);
2054
+ miniMaxRegionProbes.set(apiKey, { at: Date.now(), result });
2055
+ return result;
2056
+ }
1593
2057
  function readStoredBaseUrlSync(authFile, provider) {
1594
2058
  try {
1595
- const data = JSON.parse(readFileSync3(authFile, "utf-8"));
2059
+ const data = JSON.parse(readFileSync2(authFile, "utf-8"));
1596
2060
  return activeBaseUrlEntry(data, provider)?.baseUrl;
1597
2061
  } catch {
1598
2062
  return void 0;
@@ -1636,8 +2100,12 @@ var AuthStorage = class {
1636
2100
  snapshotIno = 0;
1637
2101
  /** Per-provider lock to serialize concurrent refresh calls. */
1638
2102
  refreshLocks = /* @__PURE__ */ new Map();
1639
- constructor(filePath) {
2103
+ detectMiniMaxRegion;
2104
+ detectXiaomiCluster;
2105
+ constructor(filePath, options) {
1640
2106
  this.filePath = filePath ?? getAppPaths().authFile;
2107
+ this.detectMiniMaxRegion = options?.detectMiniMaxBaseUrl ?? cachedMiniMaxRegion;
2108
+ this.detectXiaomiCluster = options?.detectXiaomiTokenPlanBaseUrl ?? detectXiaomiTokenPlanBaseUrl;
1641
2109
  }
1642
2110
  /** Path to the on-disk auth file. Useful for status output. */
1643
2111
  get path() {
@@ -1670,6 +2138,7 @@ var AuthStorage = class {
1670
2138
  * satisfies it.
1671
2139
  */
1672
2140
  async hasProviderAuth(provider) {
2141
+ if (isHiddenProvider(provider)) return false;
1673
2142
  await this.ensureFresh();
1674
2143
  const dual = dualAuthProvider(provider);
1675
2144
  if (dual) {
@@ -1681,11 +2150,28 @@ var AuthStorage = class {
1681
2150
  if (provider === "gemini") {
1682
2151
  return Boolean(this.data["gemini"] || this.data[GEMINI_API_KEY]);
1683
2152
  }
2153
+ if (provider === "anthropic" && isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY])) {
2154
+ return true;
2155
+ }
1684
2156
  if (provider === "local") {
1685
2157
  return Object.keys(this.data).some((key) => key.startsWith(LOCAL_AUTH_KEY_PREFIX));
1686
2158
  }
1687
2159
  return Boolean(this.data[provider]);
1688
2160
  }
2161
+ /** True when the user signed in with Claude through Claude Code (marker only, no token). */
2162
+ async hasClaudeCodeLogin() {
2163
+ await this.ensureFresh();
2164
+ return isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY]);
2165
+ }
2166
+ /** Record a Claude Code sign-in. Claude Code keeps the token; auth.json gets only the marker. */
2167
+ async setClaudeCodeLogin() {
2168
+ await this.mutateLatest((latest) => {
2169
+ latest[CLAUDE_CODE_AUTH_KEY] = { ...CLAUDE_CODE_AUTH_MARKER };
2170
+ });
2171
+ }
2172
+ async clearClaudeCodeLogin() {
2173
+ await this.clearCredentials(CLAUDE_CODE_AUTH_KEY);
2174
+ }
1689
2175
  /** Endpoint ids that currently have a `local:<id>` credential stored. */
1690
2176
  async listLocalEndpointIds() {
1691
2177
  await this.ensureLoaded();
@@ -1698,7 +2184,7 @@ var AuthStorage = class {
1698
2184
  */
1699
2185
  async setLocalEndpoint(endpointId, baseUrl, apiKey) {
1700
2186
  await this.setCredentials(`${LOCAL_AUTH_KEY_PREFIX}${endpointId}`, {
1701
- accessToken: apiKey && apiKey.length > 0 ? apiKey : "local",
2187
+ accessToken: apiKey && apiKey.length > 0 ? apiKey : LOCAL_NO_API_KEY,
1702
2188
  refreshToken: "",
1703
2189
  expiresAt: Date.now() + LOCAL_CREDENTIAL_LIFETIME_MS,
1704
2190
  baseUrl
@@ -1739,7 +2225,7 @@ var AuthStorage = class {
1739
2225
  const first = !this.loaded;
1740
2226
  await withFileLock(this.filePath, async () => {
1741
2227
  try {
1742
- const content = await fs4.readFile(this.filePath, "utf-8");
2228
+ const content = await fs5.readFile(this.filePath, "utf-8");
1743
2229
  this.data = JSON.parse(content);
1744
2230
  if (first) {
1745
2231
  log("INFO", "auth", `Loaded credentials from ${this.filePath}`, {
@@ -1794,7 +2280,7 @@ var AuthStorage = class {
1794
2280
  }
1795
2281
  let changed;
1796
2282
  try {
1797
- const stat = await fs4.stat(this.filePath);
2283
+ const stat = await fs5.stat(this.filePath);
1798
2284
  changed = stat.ino !== this.snapshotIno || stat.mtimeMs !== this.snapshotMtimeMs || stat.size !== this.snapshotSize;
1799
2285
  } catch {
1800
2286
  changed = this.snapshotSize !== -1;
@@ -1804,7 +2290,7 @@ var AuthStorage = class {
1804
2290
  /** Record the file identity behind the current snapshot. */
1805
2291
  async rememberSnapshot() {
1806
2292
  try {
1807
- const stat = await fs4.stat(this.filePath);
2293
+ const stat = await fs5.stat(this.filePath);
1808
2294
  this.snapshotMtimeMs = stat.mtimeMs;
1809
2295
  this.snapshotSize = stat.size;
1810
2296
  this.snapshotIno = stat.ino;
@@ -1841,11 +2327,54 @@ var AuthStorage = class {
1841
2327
  await this.ensureFresh();
1842
2328
  return this.data[provider];
1843
2329
  }
2330
+ /**
2331
+ * A MiniMax key saved without an endpoint (every key, until its first use)
2332
+ * gets the endpoint of the region that issued it, saved so the check runs
2333
+ * once. Without this a Mainland China key went to the Global API, got a 401,
2334
+ * and was deleted as invalid.
2335
+ */
2336
+ async withMiniMaxRegion(creds) {
2337
+ const baseUrl = await this.detectMiniMaxRegion(creds.accessToken);
2338
+ if (!baseUrl) return creds;
2339
+ log("INFO", "auth", `MiniMax key belongs to ${baseUrl} \u2014 saved for future requests`);
2340
+ await this.mutateLatest((latest) => {
2341
+ const current = latest["minimax"];
2342
+ if (current?.accessToken === creds.accessToken && !current.baseUrl) {
2343
+ current.baseUrl = baseUrl;
2344
+ }
2345
+ });
2346
+ return { ...creds, baseUrl };
2347
+ }
1844
2348
  async setCredentials(provider, creds) {
1845
2349
  await this.mutateLatest((latest) => {
1846
2350
  latest[provider] = creds;
1847
2351
  });
1848
2352
  }
2353
+ /**
2354
+ * After a 401, move a regional key to the cluster that issued it instead of
2355
+ * treating it as invalid. Only the Xiaomi Token Plan is regional: every key
2356
+ * used to go to Singapore, so Europe and China keys were rejected and deleted.
2357
+ * Returns the new base URL, or undefined when no other cluster accepts the key.
2358
+ */
2359
+ async relocateRegionalApiKey(storageKeys) {
2360
+ const key = await this.pickStorageKey(storageKeys);
2361
+ const creds = key === "xiaomi" ? this.data[key] : void 0;
2362
+ if (!creds) return void 0;
2363
+ const baseUrl = await this.detectXiaomiCluster(creds.accessToken);
2364
+ if (!baseUrl || baseUrl === creds.baseUrl) return void 0;
2365
+ await this.mutateLatest((latest) => {
2366
+ const current = latest["xiaomi"];
2367
+ if (current?.accessToken === creds.accessToken) current.baseUrl = baseUrl;
2368
+ });
2369
+ log("INFO", "auth", `Xiaomi Token Plan key belongs to ${baseUrl} \u2014 saved for future requests`);
2370
+ return baseUrl;
2371
+ }
2372
+ // Keeps local-endpoint keys: they're the user's own config, and a 401 there is often a busy gateway.
2373
+ async clearRejectedApiKey(storageKey) {
2374
+ if (storageKey.startsWith(LOCAL_AUTH_KEY_PREFIX)) return false;
2375
+ await this.clearCredentials(storageKey);
2376
+ return true;
2377
+ }
1849
2378
  async clearCredentials(provider) {
1850
2379
  await this.mutateLatest((latest) => {
1851
2380
  delete latest[provider];
@@ -1925,6 +2454,9 @@ var AuthStorage = class {
1925
2454
  }
1926
2455
  throw new NotLoggedInError(provider);
1927
2456
  }
2457
+ if (provider === "anthropic" && !this.data.anthropic && isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY])) {
2458
+ return { accessToken: "", refreshToken: "", expiresAt: Number.MAX_SAFE_INTEGER };
2459
+ }
1928
2460
  const dual = dualAuthProvider(provider);
1929
2461
  const dualOAuthCreds = dual ? this.data[dual.oauthKey] : void 0;
1930
2462
  if (dual && dualOAuthCreds) {
@@ -1959,6 +2491,7 @@ var AuthStorage = class {
1959
2491
  throw new NotLoggedInError(provider);
1960
2492
  }
1961
2493
  if (STATIC_API_KEY_PROVIDERS.has(provider)) {
2494
+ if (provider === "minimax" && !creds.baseUrl) return await this.withMiniMaxRegion(creds);
1962
2495
  return creds;
1963
2496
  }
1964
2497
  if (!opts?.forceRefresh && Date.now() < creds.expiresAt - refreshThresholdMs(creds)) {
@@ -2045,7 +2578,7 @@ var AuthStorage = class {
2045
2578
  };
2046
2579
  async function readAuthData(filePath) {
2047
2580
  try {
2048
- const content = await fs4.readFile(filePath, "utf-8");
2581
+ const content = await fs5.readFile(filePath, "utf-8");
2049
2582
  return JSON.parse(content);
2050
2583
  } catch (error) {
2051
2584
  if (error.code === "ENOENT") return {};
@@ -2053,12 +2586,12 @@ async function readAuthData(filePath) {
2053
2586
  }
2054
2587
  }
2055
2588
  async function atomicWriteFile(filePath, content) {
2056
- const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto5.randomUUID().slice(0, 8)}.tmp`;
2589
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto6.randomUUID().slice(0, 8)}.tmp`;
2057
2590
  try {
2058
- await fs4.writeFile(tmpPath, content, { encoding: "utf-8", mode: 384 });
2059
- await fs4.rename(tmpPath, filePath);
2591
+ await fs5.writeFile(tmpPath, content, { encoding: "utf-8", mode: 384 });
2592
+ await fs5.rename(tmpPath, filePath);
2060
2593
  } catch (err) {
2061
- await fs4.unlink(tmpPath).catch(() => {
2594
+ await fs5.unlink(tmpPath).catch(() => {
2062
2595
  });
2063
2596
  throw err;
2064
2597
  }
@@ -2079,6 +2612,12 @@ var CLAUDE_FAST_BILLING = {
2079
2612
  paid: true,
2080
2613
  standardModel: "claude-opus-5-5"
2081
2614
  };
2615
+ var CLAUDE_FABLE_FAST_BILLING = {
2616
+ label: "bills usage credits",
2617
+ detail: "Fast mode bills your Claude usage credits ($16 in / $80 out per million tokens) from the first token, never your plan's included usage.",
2618
+ paid: true,
2619
+ standardModel: "claude-fable-5-2"
2620
+ };
2082
2621
  var XIAOMI_ULTRASPEED_BILLING = {
2083
2622
  label: "bills API Credits",
2084
2623
  detail: "UltraSpeed runs only on your Xiaomi API Credits, billed per token at a higher rate than MiMo-V2.6-Pro, never on the Token Plan.",
@@ -2093,18 +2632,18 @@ var CODEX_FAST_BILLING = {
2093
2632
  var GEMINI_AUTH_KEYS = [GEMINI_API_KEY, "gemini"];
2094
2633
  var MODELS = [
2095
2634
  // ── Anthropic ──────────────────────────────────────────
2096
- // NOTE: Claude Mythos 5.1 (`claude-mythos-5-1`, 2026-09-01) is kept commented
2097
- // out — it's a Project Glasswing model, still "Active (invite only)" in
2098
- // Anthropic's docs and unavailable to most users. Re-enable once it's
2099
- // generally available.
2635
+ // NOTE: Claude Mythos 5.2 (`claude-mythos-5-2`, 2026-11-09) is kept commented
2636
+ // out — it's only for organizations verified through Anthropic's verification
2637
+ // programs and unavailable to most users. Re-enable once it's generally
2638
+ // available.
2100
2639
  {
2101
- // Released 2026-09-01 — replaces Fable 5 at the same $10/$50 MTok (cache
2102
- // reads drop to $0.25). Always-on adaptive thinking steered by effort;
2103
- // forced tool use is rejected with a 400, which @prestyj/ai never sends on the
2104
- // Anthropic path. Fable 5 is retired here — a session that still has it
2105
- // saved falls back to the provider default on next start.
2106
- id: "claude-fable-5-1",
2107
- name: "Claude Fable 5.1",
2640
+ // Released 2026-11-09 — replaces Fable 5.1 at $8/$40 MTok (down from
2641
+ // $10/$50; cache reads $0.20). Same API surface as 5.1: always-on adaptive
2642
+ // thinking steered by effort, forced tool use rejected with a 400 (@prestyj/ai
2643
+ // never sends it on the Anthropic path). Fable 5.1 is retired here — a
2644
+ // session that still has it saved falls back to the provider default.
2645
+ id: "claude-fable-5-2",
2646
+ name: "Claude Fable 5.2",
2108
2647
  provider: "anthropic",
2109
2648
  contextWindow: 1e6,
2110
2649
  maxOutputTokens: 128e3,
@@ -2114,12 +2653,28 @@ var MODELS = [
2114
2653
  costTier: "high",
2115
2654
  maxThinkingLevel: "max"
2116
2655
  },
2656
+ {
2657
+ // Fable 5.2 in fast mode: the same model at up to 2.5x output tokens/sec,
2658
+ // $16/$80 MTok. Sent as `claude-fable-5-2` + `speed: "fast"`; on a Claude
2659
+ // subscription it bills usage credits only, like Opus 5.5 Fast.
2660
+ id: "claude-fable-5-2-fast",
2661
+ name: "Claude Fable 5.2 Fast",
2662
+ provider: "anthropic",
2663
+ contextWindow: 1e6,
2664
+ maxOutputTokens: 128e3,
2665
+ supportsThinking: true,
2666
+ supportsImages: true,
2667
+ supportsVideo: false,
2668
+ costTier: "high",
2669
+ maxThinkingLevel: "max",
2670
+ billing: CLAUDE_FABLE_FAST_BILLING
2671
+ },
2117
2672
  // {
2118
2673
  // // Mythos-class model offered through Project Glasswing (limited
2119
- // // availability, invitation-only). Same underlying model as Fable 5.1 with
2120
- // // some safeguards lifted; kept here so approved accounts can select it.
2121
- // id: "claude-mythos-5-1",
2122
- // name: "Claude Mythos 5.1",
2674
+ // // availability, verified organizations only). Same specs and pricing as
2675
+ // // Fable 5.2; kept here so approved accounts can select it.
2676
+ // id: "claude-mythos-5-2",
2677
+ // name: "Claude Mythos 5.2",
2123
2678
  // provider: "anthropic",
2124
2679
  // contextWindow: 1_000_000,
2125
2680
  // maxOutputTokens: 128_000,
@@ -2218,18 +2773,13 @@ var MODELS = [
2218
2773
  },
2219
2774
  // ── OpenAI (Codex) ─────────────────────────────────────
2220
2775
  {
2221
- // GPT-6 Astra — "Our most capable model for complex, demanding work."
2222
- // (Codex catalog priority 2, listed for every ChatGPT plan, requires a
2223
- // Codex client >= 0.153.0 — see CODEX_CLIENT_VERSION). Same split as 5.6:
2224
- // 1.05M on the public Responses API, 272K on the ChatGPT OAuth route
2225
- // (openai/codex models.json, `gpt-6-astra`). Reasoning ladder low → medium
2226
- // → high → xhigh → max → ultra; `ultra` is the Codex orchestration preset
2227
- // (multi_agent v2) and is Codex-only — the public API tops out at `max`.
2228
- // Note: through a plain API key OpenAI requires the Responses API for tool
2229
- // calling on Astra, so the Chat Completions path is text-only; the OAuth
2230
- // Codex route is the supported way to use it as an agent.
2231
- id: "gpt-6-astra",
2232
- name: "GPT-6 Astra",
2776
+ // GPT-6.2 Astra — released 2026-11-17, "Our most capable model for your
2777
+ // hardest projects." (Codex catalog priority 2, default low, client >=
2778
+ // 0.166.0). $8/$40 MTok, cached input $0.40. 1.05M on the public Responses
2779
+ // API, 272K on the Codex route; 128K output, text+image input. Same ladder
2780
+ // and Ultra preset as GPT-6 Astra, which it retires; the API rejects reasoning effort `none`.
2781
+ id: "gpt-6.2-astra",
2782
+ name: "GPT-6.2 Astra",
2233
2783
  provider: "openai",
2234
2784
  contextWindow: 105e4,
2235
2785
  codexContextWindow: 272e3,
@@ -2242,12 +2792,12 @@ var MODELS = [
2242
2792
  maxThinkingLevel: "ultra"
2243
2793
  },
2244
2794
  {
2245
- // Codex Fast mode for Astra (catalog `service_tiers: priority`, "2x speed,
2246
- // increased usage"). @prestyj/ai's `stream()` sends it as `gpt-6-astra` +
2247
- // `service_tier: "priority"`, exactly what the Codex CLI sends. On a
2248
- // ChatGPT plan it draws included limits at 2.5x the standard rate.
2249
- id: "gpt-6-astra-fast",
2250
- name: "GPT-6 Astra Fast",
2795
+ // Codex Fast mode for 6.2 Astra ("2x speed, increased usage"). @prestyj/ai's
2796
+ // `stream()` sends it as `gpt-6.2-astra` + `service_tier: "priority"`,
2797
+ // exactly what the Codex CLI sends. On a ChatGPT plan it draws included
2798
+ // limits at 2.5x the standard rate.
2799
+ id: "gpt-6.2-astra-fast",
2800
+ name: "GPT-6.2 Astra Fast",
2251
2801
  provider: "openai",
2252
2802
  contextWindow: 105e4,
2253
2803
  codexContextWindow: 272e3,
@@ -2261,25 +2811,26 @@ var MODELS = [
2261
2811
  billing: CODEX_FAST_BILLING
2262
2812
  },
2263
2813
  // GPT-6 Sol + Luna — released 2026-09-22 below Astra, replacing the whole
2264
- // GPT-5.6 family (Sol/Terra/Luna; there is no GPT-6 Terra — OpenAI's Codex
2265
- // catalog upgrades 5.6 Terra to 6 Sol). GPT-6.1 Sol (2026-09-29) then replaced
2266
- // GPT-6 Sol. Same window split as Astra: 1.05M on the public Responses API,
2267
- // 272K on the Codex route; 128K output, text+image input, freeform
2268
- // apply_patch, responses-lite transport. The GPT-5.6 ids and `gpt-6-sol` are
2269
- // retired — a saved session on one falls back to the provider default on
2270
- // next start.
2814
+ // GPT-5.6 family (Sol/Terra/Luna; there was no GPT-6 Terra — OpenAI's Codex
2815
+ // catalog upgrades 5.6 Terra to 6 Sol). GPT-6.1 Sol (2026-09-29) replaced
2816
+ // GPT-6 Sol, GPT-6.1 Terra (2026-10-26) sits between Sol and Luna, and
2817
+ // GPT-6.2 Sol (2026-11-17) replaced GPT-6.1 Sol. 1.05M on the public
2818
+ // Responses API; 128K output, text+image input, freeform apply_patch,
2819
+ // responses-lite transport. The GPT-5.6 ids, `gpt-6-sol` and `gpt-6.1-sol`
2820
+ // are retired — a saved session on one falls back to the provider default
2821
+ // on next start.
2271
2822
  {
2272
- // GPT-6.1 Sol — "Latest workhorse model for coding and everyday work."
2273
- // (Codex priority 1, default low). The catalog says Codex client >= 0.153.0,
2274
- // but the ChatGPT backend only serves it from 0.159.0 (see
2275
- // CODEX_CLIENT_VERSION). $2/$10 MTok, cached input $0.10. Ladder low →
2823
+ // GPT-6.2 Sol — "Our go-to model for everyday work, from coding to
2824
+ // powering agents at scale." (Codex priority 1, default low, client >=
2825
+ // 0.166.0). $2/$10 MTok, cached input $0.10. Like Terra, the Codex route
2826
+ // gets a 500K window (catalog `context_window`). Ladder low →
2276
2827
  // medium → high → xhigh → max → ultra; ultra is the Codex orchestration
2277
2828
  // preset (xhigh effort on the wire + proactive local subagent delegation).
2278
- id: "gpt-6.1-sol",
2279
- name: "GPT-6.1 Sol",
2829
+ id: "gpt-6.2-sol",
2830
+ name: "GPT-6.2 Sol",
2280
2831
  provider: "openai",
2281
2832
  contextWindow: 105e4,
2282
- codexContextWindow: 272e3,
2833
+ codexContextWindow: 5e5,
2283
2834
  maxOutputTokens: 128e3,
2284
2835
  supportsThinking: true,
2285
2836
  defaultThinkingLevel: "low",
@@ -2289,13 +2840,47 @@ var MODELS = [
2289
2840
  maxThinkingLevel: "ultra"
2290
2841
  },
2291
2842
  {
2292
- // Codex Fast mode for 6.1 Sol ("2x speed, increased usage") — see
2293
- // `gpt-6-astra-fast` for the wire mapping and billing.
2294
- id: "gpt-6.1-sol-fast",
2295
- name: "GPT-6.1 Sol Fast",
2843
+ // Codex Fast mode for 6.2 Sol ("2x speed, increased usage") — see
2844
+ // `gpt-6.2-astra-fast` for the wire mapping and billing.
2845
+ id: "gpt-6.2-sol-fast",
2846
+ name: "GPT-6.2 Sol Fast",
2296
2847
  provider: "openai",
2297
2848
  contextWindow: 105e4,
2298
- codexContextWindow: 272e3,
2849
+ codexContextWindow: 5e5,
2850
+ maxOutputTokens: 128e3,
2851
+ supportsThinking: true,
2852
+ defaultThinkingLevel: "low",
2853
+ supportsImages: true,
2854
+ supportsVideo: false,
2855
+ costTier: "medium",
2856
+ maxThinkingLevel: "ultra",
2857
+ billing: CODEX_FAST_BILLING
2858
+ },
2859
+ {
2860
+ // GPT-6.1 Terra (Codex priority 7, default low, client >= 0.153.0). $1/$5
2861
+ // MTok, cached input $0.05. Unlike Sol/Astra the Codex route gets a 500K
2862
+ // window (catalog `context_window`). Same ladder and Ultra preset as Sol.
2863
+ id: "gpt-6.1-terra",
2864
+ name: "GPT-6.1 Terra",
2865
+ provider: "openai",
2866
+ contextWindow: 105e4,
2867
+ codexContextWindow: 5e5,
2868
+ maxOutputTokens: 128e3,
2869
+ supportsThinking: true,
2870
+ defaultThinkingLevel: "low",
2871
+ supportsImages: true,
2872
+ supportsVideo: false,
2873
+ costTier: "medium",
2874
+ maxThinkingLevel: "ultra"
2875
+ },
2876
+ {
2877
+ // Codex Fast mode for 6.1 Terra ("1.5x speed") — see `gpt-6.2-astra-fast`
2878
+ // for the wire mapping and billing.
2879
+ id: "gpt-6.1-terra-fast",
2880
+ name: "GPT-6.1 Terra Fast",
2881
+ provider: "openai",
2882
+ contextWindow: 105e4,
2883
+ codexContextWindow: 5e5,
2299
2884
  maxOutputTokens: 128e3,
2300
2885
  supportsThinking: true,
2301
2886
  defaultThinkingLevel: "low",
@@ -2323,7 +2908,7 @@ var MODELS = [
2323
2908
  maxThinkingLevel: "max"
2324
2909
  },
2325
2910
  {
2326
- // Codex Fast mode for Luna ("1.5x speed") — see `gpt-6-astra-fast` for the
2911
+ // Codex Fast mode for Luna ("1.5x speed") — see `gpt-6.2-astra-fast` for the
2327
2912
  // wire mapping and billing. Listed after Luna so compaction summaries
2328
2913
  // (first `low` OpenAI model) stay on standard-speed Luna.
2329
2914
  id: "gpt-6-luna-fast",
@@ -2609,6 +3194,23 @@ var MODELS = [
2609
3194
  maxThinkingLevel: "max"
2610
3195
  },
2611
3196
  // ── MiniMax ────────────────────────────────────────────
3197
+ {
3198
+ // The only text model M Plan / Token Plan keys cover; MiniMax-M3 on those
3199
+ // keys fails with "insufficient balance (1008)". Pay-as-you-go serves both.
3200
+ // Always thinks (`thinking: disabled` 400s; omitted = on) with a real
3201
+ // low→max effort ladder on output_config.effort, API default max.
3202
+ id: "MiniMax-M3.1-Flash",
3203
+ name: "MiniMax M3.1 Flash",
3204
+ provider: "minimax",
3205
+ contextWindow: 1e6,
3206
+ maxOutputTokens: 131072,
3207
+ supportsThinking: true,
3208
+ supportsImages: true,
3209
+ supportsVideo: true,
3210
+ maxVideoBytes: 50 * 1024 * 1024,
3211
+ costTier: "low",
3212
+ maxThinkingLevel: "max"
3213
+ },
2612
3214
  {
2613
3215
  id: "MiniMax-M3",
2614
3216
  name: "MiniMax M3",
@@ -2754,6 +3356,93 @@ var MODELS = [
2754
3356
  costTier: "medium",
2755
3357
  maxThinkingLevel: "high"
2756
3358
  },
3359
+ // ── OpenCode Console (Go subscription, then pay-as-you-go) ────────
3360
+ // One Console API key reaches many labs' models through opencode.ai. Ids
3361
+ // carry the plan prefix (`opencode-go/kimi-k3`) because the gateway reuses
3362
+ // the vendors' own ids; @prestyj/ai strips it at the wire. These rows are only the
3363
+ // offline fallback: the desktop app replaces them with each plan's live,
3364
+ // public model list (core/opencode-catalog-store.ts). Limits, image input
3365
+ // and effort ladders are from GET /inference[/go]/v1/models (2026-11-11);
3366
+ // all three speak Chat Completions natively.
3367
+ {
3368
+ // Go declares `max` as K3's only effort; pay-as-you-go adds low and high.
3369
+ id: "opencode-go/kimi-k3",
3370
+ name: "Kimi K3",
3371
+ provider: "opencode-go",
3372
+ contextWindow: 1048576,
3373
+ maxOutputTokens: 131072,
3374
+ supportsThinking: true,
3375
+ supportsImages: true,
3376
+ supportsVideo: false,
3377
+ costTier: "high",
3378
+ maxThinkingLevel: "max",
3379
+ thinkingLevels: ["max"]
3380
+ },
3381
+ {
3382
+ id: "opencode-go/glm-5.3",
3383
+ name: "GLM-5.3",
3384
+ provider: "opencode-go",
3385
+ contextWindow: 1e6,
3386
+ maxOutputTokens: 131072,
3387
+ supportsThinking: true,
3388
+ supportsImages: false,
3389
+ supportsVideo: false,
3390
+ costTier: "medium",
3391
+ maxThinkingLevel: "max",
3392
+ thinkingLevels: ["low", "high", "max"]
3393
+ },
3394
+ {
3395
+ id: "opencode-go/glm-5.3-flash",
3396
+ name: "GLM-5.3-Flash",
3397
+ provider: "opencode-go",
3398
+ contextWindow: 1e6,
3399
+ maxOutputTokens: 131072,
3400
+ supportsThinking: true,
3401
+ supportsImages: true,
3402
+ supportsVideo: false,
3403
+ costTier: "low",
3404
+ maxThinkingLevel: "max",
3405
+ thinkingLevels: ["low", "high", "max"]
3406
+ },
3407
+ {
3408
+ id: "opencode/kimi-k3",
3409
+ name: "Kimi K3",
3410
+ provider: "opencode",
3411
+ contextWindow: 1048576,
3412
+ maxOutputTokens: 131072,
3413
+ supportsThinking: true,
3414
+ supportsImages: true,
3415
+ supportsVideo: false,
3416
+ costTier: "high",
3417
+ maxThinkingLevel: "max",
3418
+ thinkingLevels: ["low", "high", "max"]
3419
+ },
3420
+ {
3421
+ id: "opencode/glm-5.3",
3422
+ name: "GLM-5.3",
3423
+ provider: "opencode",
3424
+ contextWindow: 1e6,
3425
+ maxOutputTokens: 131072,
3426
+ supportsThinking: true,
3427
+ supportsImages: false,
3428
+ supportsVideo: false,
3429
+ costTier: "medium",
3430
+ maxThinkingLevel: "max",
3431
+ thinkingLevels: ["low", "high", "max"]
3432
+ },
3433
+ {
3434
+ id: "opencode/glm-5.3-flash",
3435
+ name: "GLM-5.3-Flash",
3436
+ provider: "opencode",
3437
+ contextWindow: 1e6,
3438
+ maxOutputTokens: 131072,
3439
+ supportsThinking: true,
3440
+ supportsImages: true,
3441
+ supportsVideo: false,
3442
+ costTier: "low",
3443
+ maxThinkingLevel: "max",
3444
+ thinkingLevels: ["low", "high", "max"]
3445
+ },
2757
3446
  // ── Hugging Face (Inference Providers router) ────────
2758
3447
  // One HF token (hf.co/settings/tokens, "Make calls to Inference Providers"
2759
3448
  // permission) routes to whichever hosted backend serves each open model;
@@ -2831,15 +3520,51 @@ function clearRuntimeModels(predicate) {
2831
3520
  if (predicate(model)) runtimeModels.delete(id);
2832
3521
  }
2833
3522
  }
3523
+ var providerCatalogs = /* @__PURE__ */ new Map();
3524
+ function setProviderCatalog(provider, models) {
3525
+ if (!models) {
3526
+ providerCatalogs.delete(provider);
3527
+ return [];
3528
+ }
3529
+ const installed = /* @__PURE__ */ new Map();
3530
+ for (const model of models) {
3531
+ if (model.provider !== provider) continue;
3532
+ if (MODELS.some((m) => m.id === model.id && m.provider !== provider)) continue;
3533
+ installed.set(model.id, model);
3534
+ }
3535
+ providerCatalogs.set(provider, installed);
3536
+ return [...installed.values()];
3537
+ }
3538
+ function getProviderCatalog(provider) {
3539
+ const catalog = providerCatalogs.get(provider);
3540
+ return catalog ? [...catalog.values()] : void 0;
3541
+ }
2834
3542
  function getAllModels() {
2835
- return [...MODELS, ...runtimeModels.values()];
3543
+ const synced = [...providerCatalogs.values()].flatMap((c) => [...c.values()]);
3544
+ return [
3545
+ ...MODELS.filter((m) => !providerCatalogs.has(m.provider)),
3546
+ ...synced,
3547
+ ...runtimeModels.values()
3548
+ ];
2836
3549
  }
2837
3550
  function getModel(id) {
2838
- return MODELS.find((m) => m.id === id) ?? runtimeModels.get(id);
3551
+ const fixed = MODELS.find((m) => m.id === id);
3552
+ if (fixed && !providerCatalogs.has(fixed.provider)) return fixed;
3553
+ return findSynced(id) ?? fixed ?? runtimeModels.get(id);
3554
+ }
3555
+ function findSynced(id) {
3556
+ for (const catalog of providerCatalogs.values()) {
3557
+ const hit = catalog.get(id);
3558
+ if (hit) return hit;
3559
+ }
3560
+ return void 0;
2839
3561
  }
2840
3562
  function getModelsForProvider(provider) {
2841
3563
  return getAllModels().filter((m) => m.provider === provider);
2842
3564
  }
3565
+ function getListedModels() {
3566
+ return getAllModels().filter((m) => !isHiddenProvider(m.provider));
3567
+ }
2843
3568
  function isPaidModel(modelId) {
2844
3569
  return getModel(modelId)?.billing?.paid === true;
2845
3570
  }
@@ -2868,13 +3593,15 @@ function getVideoByteLimit(modelId) {
2868
3593
  }
2869
3594
  var DEFAULT_MODEL_IDS = {
2870
3595
  xiaomi: "mimo-v2.6-pro",
2871
- openai: "gpt-6.1-sol",
3596
+ openai: "gpt-6.2-sol",
2872
3597
  gemini: "gemini-3.1-flash-lite",
2873
3598
  glm: "glm-5.3",
2874
3599
  moonshot: "kimi-k3",
2875
- minimax: "MiniMax-M3",
3600
+ minimax: "MiniMax-M3.1-Flash",
2876
3601
  deepseek: "deepseek-v4-pro",
2877
3602
  huggingface: "moonshotai/Kimi-K2.7-Code",
3603
+ opencode: "opencode/kimi-k3",
3604
+ "opencode-go": "opencode-go/kimi-k3",
2878
3605
  openrouter: "qwen/qwen3.8-max",
2879
3606
  sakana: "fugu",
2880
3607
  xai: "grok-4.7"
@@ -2945,16 +3672,9 @@ export {
2945
3672
  loginKimi,
2946
3673
  refreshKimiToken,
2947
3674
  generatePKCE,
2948
- openLog,
2949
- getSessionId,
2950
- isLoggerOpen,
2951
- log,
2952
- registerLogCleanup,
2953
- closeLogger,
2954
- compareClaudeCodeVersions,
2955
3675
  getClaudeCodeVersion,
2956
- recordRequiredClaudeCodeVersion,
2957
3676
  getClaudeCliUserAgent,
3677
+ pendingClaudeCodeVersionRefresh,
2958
3678
  loginAnthropic,
2959
3679
  refreshAnthropicToken,
2960
3680
  loginOpenAI,
@@ -2967,6 +3687,36 @@ export {
2967
3687
  loginXai,
2968
3688
  refreshXaiToken,
2969
3689
  withFileLock,
3690
+ openLog,
3691
+ getSessionId,
3692
+ isLoggerOpen,
3693
+ log,
3694
+ registerLogCleanup,
3695
+ closeLogger,
3696
+ HIDDEN_PROVIDERS,
3697
+ isHiddenProvider,
3698
+ CLAUDE_CODE_MANIFEST,
3699
+ CLAUDE_CODE_AUTH_KEY,
3700
+ CLAUDE_CODE_AUTH_MARKER,
3701
+ isClaudeCodeAuthMarker,
3702
+ isLegacyClaudeOAuth,
3703
+ claudeCodePlatformKey,
3704
+ claudeCodeHome,
3705
+ claudeCodeConfigDir,
3706
+ claudeCodeBinaryPath,
3707
+ resolveClaudeCodeBinary,
3708
+ ensureClaudeCodeBinary,
3709
+ formatClaudeCodeInstallProgress,
3710
+ claudeCodeEnv,
3711
+ claudeCodeAuthStatus,
3712
+ logoutClaudeCode,
3713
+ claudeCodeCallbackUrl,
3714
+ loginClaudeCode,
3715
+ MINIMAX_GLOBAL_BASE_URL,
3716
+ MINIMAX_CN_BASE_URL,
3717
+ detectMiniMaxBaseUrl,
3718
+ XIAOMI_TOKEN_PLAN_BASE_URLS,
3719
+ detectXiaomiTokenPlanBaseUrl,
2970
3720
  MOONSHOT_OAUTH_KEY,
2971
3721
  XAI_OAUTH_KEY,
2972
3722
  dualAuthProvider,
@@ -2983,9 +3733,12 @@ export {
2983
3733
  MODELS,
2984
3734
  registerRuntimeModels,
2985
3735
  clearRuntimeModels,
3736
+ setProviderCatalog,
3737
+ getProviderCatalog,
2986
3738
  getAllModels,
2987
3739
  getModel,
2988
3740
  getModelsForProvider,
3741
+ getListedModels,
2989
3742
  isPaidModel,
2990
3743
  withoutPaidTier,
2991
3744
  getAuthStorageKeys,
@@ -3000,4 +3753,4 @@ export {
3000
3753
  getDefaultThinkingLevel,
3001
3754
  getSummaryModel
3002
3755
  };
3003
- //# sourceMappingURL=chunk-6I3APHDP.js.map
3756
+ //# sourceMappingURL=chunk-7IHCMEIY.js.map