@prestyj/core 5.32.1 → 5.33.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.
package/dist/index.cjs CHANGED
@@ -32,37 +32,56 @@ var index_exports = {};
32
32
  __export(index_exports, {
33
33
  AUTH_PROVIDERS: () => AUTH_PROVIDERS,
34
34
  AuthStorage: () => AuthStorage,
35
+ CLAUDE_CODE_AUTH_KEY: () => CLAUDE_CODE_AUTH_KEY,
36
+ CLAUDE_CODE_AUTH_MARKER: () => CLAUDE_CODE_AUTH_MARKER,
37
+ CLAUDE_CODE_MANIFEST: () => CLAUDE_CODE_MANIFEST,
35
38
  DEFAULT_LOCAL_ENDPOINTS: () => DEFAULT_LOCAL_ENDPOINTS,
36
39
  DEFAULT_MAX_VIDEO_BYTES: () => DEFAULT_MAX_VIDEO_BYTES,
37
40
  FALLBACK_CONTEXT_WINDOW: () => FALLBACK_CONTEXT_WINDOW,
38
41
  GEMINI_API_KEY: () => GEMINI_API_KEY,
39
42
  GEMINI_API_KEY_BASE_URL: () => GEMINI_API_KEY_BASE_URL,
43
+ HIDDEN_PROVIDERS: () => HIDDEN_PROVIDERS,
40
44
  LOCAL_API_KEY_PLACEHOLDER: () => LOCAL_API_KEY_PLACEHOLDER,
41
45
  LOCAL_AUTH_KEY_PREFIX: () => LOCAL_AUTH_KEY_PREFIX,
46
+ MINIMAX_CN_BASE_URL: () => MINIMAX_CN_BASE_URL,
47
+ MINIMAX_GLOBAL_BASE_URL: () => MINIMAX_GLOBAL_BASE_URL,
42
48
  MODELS: () => MODELS,
43
49
  MOONSHOT_OAUTH_KEY: () => MOONSHOT_OAUTH_KEY,
44
50
  NotLoggedInError: () => NotLoggedInError,
51
+ OPENROUTER_DEFAULT_BASE_URL: () => OPENROUTER_DEFAULT_BASE_URL,
45
52
  PLAN_MODE_THINKING_CAP: () => PLAN_MODE_THINKING_CAP,
46
53
  SubscriptionUsageError: () => SubscriptionUsageError,
47
54
  TelegramBot: () => TelegramBot,
48
55
  XAI_OAUTH_KEY: () => XAI_OAUTH_KEY,
49
56
  XIAOMI_CREDITS_KEY: () => XIAOMI_CREDITS_KEY,
57
+ XIAOMI_TOKEN_PLAN_BASE_URLS: () => XIAOMI_TOKEN_PLAN_BASE_URLS,
50
58
  authPriorityNote: () => authPriorityNote,
51
59
  clampThinkingForPlanMode: () => clampThinkingForPlanMode,
60
+ claudeCodeAuthStatus: () => claudeCodeAuthStatus,
61
+ claudeCodeBinaryPath: () => claudeCodeBinaryPath,
62
+ claudeCodeCallbackUrl: () => claudeCodeCallbackUrl,
63
+ claudeCodeConfigDir: () => claudeCodeConfigDir,
64
+ claudeCodeEnv: () => claudeCodeEnv,
65
+ claudeCodeHome: () => claudeCodeHome,
66
+ claudeCodePlatformKey: () => claudeCodePlatformKey,
67
+ clearClaudeCodeUsage: () => clearClaudeCodeUsage,
52
68
  clearLocalDiscoveryCache: () => clearLocalDiscoveryCache,
53
69
  clearRuntimeModels: () => clearRuntimeModels,
54
70
  closeLogger: () => closeLogger,
55
- compareClaudeCodeVersions: () => compareClaudeCodeVersions,
56
71
  createAutoUpdater: () => createAutoUpdater,
57
72
  decodeOggOpus: () => decodeOggOpus,
58
73
  describeAuthMethods: () => describeAuthMethods,
74
+ detectMiniMaxBaseUrl: () => detectMiniMaxBaseUrl,
75
+ detectXiaomiTokenPlanBaseUrl: () => detectXiaomiTokenPlanBaseUrl,
59
76
  discoverLocalModels: () => discoverLocalModels,
60
77
  downmixToMono: () => downmixToMono,
61
78
  dualAuthProvider: () => dualAuthProvider,
62
79
  dualAuthProviderByOAuthKey: () => dualAuthProviderByOAuthKey,
63
80
  endpointRoot: () => endpointRoot,
81
+ ensureClaudeCodeBinary: () => ensureClaudeCodeBinary,
64
82
  fetchSubscriptionUsage: () => fetchSubscriptionUsage,
65
83
  findProbedModel: () => findProbedModel,
84
+ formatClaudeCodeInstallProgress: () => formatClaudeCodeInstallProgress,
66
85
  formatLocalModelId: () => formatLocalModelId,
67
86
  generatePKCE: () => generatePKCE,
68
87
  getAllModels: () => getAllModels,
@@ -70,16 +89,18 @@ __export(index_exports, {
70
89
  getAuthProvider: () => getAuthProvider,
71
90
  getAuthStorageKey: () => getAuthStorageKey,
72
91
  getAuthStorageKeys: () => getAuthStorageKeys,
73
- getClaudeCliUserAgent: () => getClaudeCliUserAgent,
74
- getClaudeCodeVersion: () => getClaudeCodeVersion,
92
+ getClaudeCliUserAgent: () => import_ai.getClaudeCliUserAgent,
93
+ getClaudeCodeVersion: () => import_ai.getClaudeCodeVersion,
75
94
  getContextWindow: () => getContextWindow,
76
95
  getDefaultModel: () => getDefaultModel,
77
96
  getDefaultThinkingLevel: () => getDefaultThinkingLevel,
97
+ getListedModels: () => getListedModels,
78
98
  getLowestThinkingLevel: () => getLowestThinkingLevel,
79
99
  getMaxThinkingLevel: () => getMaxThinkingLevel,
80
100
  getModel: () => getModel,
81
101
  getModelsForProvider: () => getModelsForProvider,
82
102
  getNextThinkingLevel: () => getNextThinkingLevel,
103
+ getProviderCatalog: () => getProviderCatalog,
83
104
  getSessionId: () => getSessionId,
84
105
  getSummaryModel: () => getSummaryModel,
85
106
  getSupportedThinkingLevels: () => getSupportedThinkingLevels,
@@ -87,8 +108,11 @@ __export(index_exports, {
87
108
  getVideoByteLimit: () => getVideoByteLimit,
88
109
  grokCliBaseUrl: () => grokCliBaseUrl,
89
110
  grokCliHeaders: () => grokCliHeaders,
111
+ isClaudeCodeAuthMarker: () => isClaudeCodeAuthMarker,
90
112
  isGrokCliEndpoint: () => isGrokCliEndpoint,
113
+ isHiddenProvider: () => isHiddenProvider,
91
114
  isKimiCodingEndpoint: () => isKimiCodingEndpoint,
115
+ isLegacyClaudeOAuth: () => isLegacyClaudeOAuth,
92
116
  isLocalModelId: () => isLocalModelId,
93
117
  isLoggerOpen: () => isLoggerOpen,
94
118
  isModelLoaded: () => isModelLoaded,
@@ -97,19 +121,27 @@ __export(index_exports, {
97
121
  kimiCodeBaseUrl: () => kimiCodeBaseUrl,
98
122
  kimiCodingHeaders: () => kimiCodingHeaders,
99
123
  localAuthStorageKey: () => localAuthStorageKey,
124
+ localModelShortName: () => localModelShortName,
100
125
  log: () => log,
101
126
  loginAnthropic: () => loginAnthropic,
127
+ loginClaudeCode: () => loginClaudeCode,
102
128
  loginGemini: () => loginGemini,
103
129
  loginKimi: () => loginKimi,
104
130
  loginOpenAI: () => loginOpenAI,
105
131
  loginXai: () => loginXai,
132
+ logoutClaudeCode: () => logoutClaudeCode,
133
+ mergeClaudeCodeRateLimit: () => mergeClaudeCodeRateLimit,
106
134
  oauthStorageKey: () => oauthStorageKey,
135
+ ollamaServedContext: () => ollamaServedContext,
107
136
  openLog: () => openLog,
108
137
  parseLocalModelId: () => parseLocalModelId,
138
+ parseOpenRouterCatalog: () => parseOpenRouterCatalog,
139
+ pendingClaudeCodeVersionRefresh: () => import_ai.pendingClaudeCodeVersionRefresh,
109
140
  probeEndpoint: () => probeEndpoint,
110
141
  providerStorageKeys: () => providerStorageKeys,
142
+ readClaudeCodeUsage: () => readClaudeCodeUsage,
111
143
  readStoredBaseUrlSync: () => readStoredBaseUrlSync,
112
- recordRequiredClaudeCodeVersion: () => recordRequiredClaudeCodeVersion,
144
+ recordClaudeCodeRateLimit: () => recordClaudeCodeRateLimit,
113
145
  refreshAnthropicToken: () => refreshAnthropicToken,
114
146
  refreshGeminiToken: () => refreshGeminiToken,
115
147
  refreshKimiToken: () => refreshKimiToken,
@@ -118,7 +150,11 @@ __export(index_exports, {
118
150
  registerLogCleanup: () => registerLogCleanup,
119
151
  registerRuntimeModels: () => registerRuntimeModels,
120
152
  resample: () => resample,
153
+ resolveClaudeCodeBinary: () => resolveClaudeCodeBinary,
121
154
  setProgressCallback: () => setProgressCallback,
155
+ setProviderCatalog: () => setProviderCatalog,
156
+ signInWithClaudeCode: () => signInWithClaudeCode,
157
+ signOutOfClaudeCode: () => signOutOfClaudeCode,
122
158
  toModelInfo: () => toModelInfo,
123
159
  transcribeVoice: () => transcribeVoice,
124
160
  usesOpenAICodexTransport: () => usesOpenAICodexTransport,
@@ -157,7 +193,9 @@ function getAppPaths() {
157
193
  agentsDir: import_node_path.default.join(agentDir, "agents"),
158
194
  progressFile: import_node_path.default.join(agentDir, "progress.json"),
159
195
  progressBackupFile: import_node_path.default.join(agentDir, "progress.backup.json"),
160
- trophiesFile: import_node_path.default.join(agentDir, "trophies.json")
196
+ trophiesFile: import_node_path.default.join(agentDir, "trophies.json"),
197
+ claudeCodeDir: import_node_path.default.join(agentDir, "claude-code"),
198
+ claudeCodeConfigDir: import_node_path.default.join(agentDir, "claude-code", "config")
161
199
  };
162
200
  }
163
201
 
@@ -382,12 +420,12 @@ async function refreshKimiToken(refreshToken) {
382
420
  }
383
421
 
384
422
  // src/auth-storage.ts
385
- var import_promises4 = __toESM(require("fs/promises"), 1);
386
- var import_node_fs4 = require("fs");
387
- var import_node_crypto6 = __toESM(require("crypto"), 1);
423
+ var import_promises5 = __toESM(require("fs/promises"), 1);
424
+ var import_node_fs5 = require("fs");
425
+ var import_node_crypto7 = __toESM(require("crypto"), 1);
388
426
 
389
427
  // src/oauth/anthropic.ts
390
- var import_node_crypto3 = __toESM(require("crypto"), 1);
428
+ var import_node_crypto2 = __toESM(require("crypto"), 1);
391
429
 
392
430
  // src/oauth/pkce.ts
393
431
  function base64urlEncode(bytes) {
@@ -408,347 +446,7 @@ async function generatePKCE() {
408
446
  }
409
447
 
410
448
  // src/claude-code-version.ts
411
- var import_promises = __toESM(require("fs/promises"), 1);
412
- var import_node_fs3 = require("fs");
413
- var import_node_path4 = __toESM(require("path"), 1);
414
-
415
- // src/logger.ts
416
- var import_node_fs2 = __toESM(require("fs"), 1);
417
- var import_node_path3 = __toESM(require("path"), 1);
418
- var import_node_crypto2 = require("crypto");
419
449
  var import_ai = require("@prestyj/ai");
420
- var MAX_BYTES = 10 * 1024 * 1024;
421
- var MIN_HEADROOM_BYTES = 64 * 1024;
422
- var fd = null;
423
- var logPath = null;
424
- var fileBytes = 0;
425
- var processBytes = 0;
426
- var rotationFailed = false;
427
- var capped = false;
428
- var sessionId = "";
429
- var appName = "app";
430
- var cleanups = [];
431
- var exactSecrets = [];
432
- function rotateIfNeeded(filePath, force = false) {
433
- try {
434
- const st = import_node_fs2.default.statSync(filePath);
435
- if (!force && st.size <= MAX_BYTES - MIN_HEADROOM_BYTES) return;
436
- const rotated = `${filePath}.1`;
437
- try {
438
- import_node_fs2.default.unlinkSync(rotated);
439
- } catch {
440
- }
441
- import_node_fs2.default.renameSync(filePath, rotated);
442
- } catch {
443
- }
444
- }
445
- function rotateOpenLog() {
446
- if (fd === null || logPath === null) return false;
447
- const sizeBefore = fileBytes;
448
- try {
449
- import_node_fs2.default.closeSync(fd);
450
- } catch {
451
- }
452
- fd = null;
453
- rotateIfNeeded(logPath, true);
454
- try {
455
- fd = import_node_fs2.default.openSync(logPath, "a");
456
- fileBytes = import_node_fs2.default.fstatSync(fd).size;
457
- } catch {
458
- if (fd !== null) {
459
- try {
460
- import_node_fs2.default.closeSync(fd);
461
- } catch {
462
- }
463
- }
464
- fd = null;
465
- capped = true;
466
- return false;
467
- }
468
- if (fileBytes >= sizeBefore) rotationFailed = true;
469
- return true;
470
- }
471
- function openLog(filePath, name) {
472
- if (fd !== null || capped) return false;
473
- appName = name;
474
- exactSecrets = (0, import_ai.environmentSecrets)(process.env);
475
- try {
476
- import_node_fs2.default.mkdirSync(import_node_path3.default.dirname(filePath), { recursive: true, mode: 448 });
477
- } catch {
478
- }
479
- rotateIfNeeded(filePath);
480
- try {
481
- fd = import_node_fs2.default.openSync(filePath, "a");
482
- } catch {
483
- fd = null;
484
- fileBytes = 0;
485
- return false;
486
- }
487
- try {
488
- fileBytes = import_node_fs2.default.fstatSync(fd).size;
489
- } catch {
490
- try {
491
- import_node_fs2.default.closeSync(fd);
492
- } catch {
493
- }
494
- fd = null;
495
- fileBytes = 0;
496
- return false;
497
- }
498
- logPath = filePath;
499
- processBytes = 0;
500
- rotationFailed = false;
501
- sessionId = (0, import_node_crypto2.randomBytes)(4).toString("hex");
502
- try {
503
- if (fileBytes < MAX_BYTES) {
504
- const written = import_node_fs2.default.writeSync(fd, "\n");
505
- fileBytes += written;
506
- processBytes += written;
507
- }
508
- } catch {
509
- }
510
- return true;
511
- }
512
- function getSessionId() {
513
- return sessionId;
514
- }
515
- function isLoggerOpen() {
516
- return fd !== null;
517
- }
518
- function log(level, category, message, data) {
519
- if (fd === null) return;
520
- const ts = (/* @__PURE__ */ new Date()).toISOString();
521
- const safeMessage = (0, import_ai.redactText)(message, { secrets: exactSecrets });
522
- let line = `[${ts}] [sid=${sessionId}] [${level}] [${category}] ${safeMessage}`;
523
- if (data) {
524
- const safeData = (0, import_ai.redactValue)(data, { secrets: exactSecrets });
525
- const pairs = Object.entries(safeData).map(([k, v]) => {
526
- if (typeof v === "string") return `${k}=${v}`;
527
- if (typeof v === "bigint") return `${k}=${String(v)}`;
528
- return `${k}=${JSON.stringify(v)}`;
529
- }).join(" ");
530
- if (pairs) line += ` ${pairs}`;
531
- }
532
- line += "\n";
533
- const lineBytes = Buffer.byteLength(line);
534
- if (processBytes + lineBytes > MAX_BYTES) {
535
- const capLine = `[${ts}] [sid=${sessionId}] [WARN] [logger] Log cap reached; file logging disabled until restart
536
- `;
537
- try {
538
- if (fileBytes + Buffer.byteLength(capLine) <= MAX_BYTES) {
539
- fileBytes += import_node_fs2.default.writeSync(fd, capLine);
540
- }
541
- import_node_fs2.default.closeSync(fd);
542
- } catch {
543
- }
544
- fd = null;
545
- capped = true;
546
- return;
547
- }
548
- if (fileBytes + lineBytes > MAX_BYTES && !rotationFailed && !rotateOpenLog()) return;
549
- if (fd === null) return;
550
- try {
551
- const written = import_node_fs2.default.writeSync(fd, line);
552
- fileBytes += written;
553
- processBytes += written;
554
- } catch {
555
- }
556
- }
557
- function registerLogCleanup(fn) {
558
- cleanups.push(fn);
559
- }
560
- function closeLogger(opts) {
561
- if (fd !== null) {
562
- if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName} shutting down`);
563
- try {
564
- if (fd !== null) import_node_fs2.default.closeSync(fd);
565
- } catch {
566
- }
567
- }
568
- fd = null;
569
- logPath = null;
570
- fileBytes = 0;
571
- processBytes = 0;
572
- rotationFailed = false;
573
- capped = false;
574
- exactSecrets = [];
575
- for (const unsub of cleanups) unsub();
576
- cleanups = [];
577
- }
578
-
579
- // src/claude-code-version.ts
580
- var NPM_LATEST_URL = "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";
581
- var CACHE_FRESH_MS = 60 * 60 * 1e3;
582
- var CACHE_HARD_MS = 24 * 60 * 60 * 1e3;
583
- var FETCH_TIMEOUT_MS = 3e3;
584
- var FALLBACK_VERSION = "2.1.280";
585
- var memoryCache = null;
586
- var inflight = null;
587
- var backgroundRefresh = null;
588
- var versionFloor = null;
589
- function cachePath() {
590
- return import_node_path4.default.join(getAppPaths().agentDir, "claude-code-version.json");
591
- }
592
- function compareClaudeCodeVersions(a, b) {
593
- const parse = (v) => v.split(".").map((part) => Number.parseInt(part, 10)).map((n) => Number.isFinite(n) ? n : 0);
594
- const left = parse(a);
595
- const right = parse(b);
596
- for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
597
- const diff = (left[i] ?? 0) - (right[i] ?? 0);
598
- if (diff !== 0) return diff;
599
- }
600
- return 0;
601
- }
602
- function applyFloor(version) {
603
- if (!versionFloor) return version;
604
- return compareClaudeCodeVersions(versionFloor, version) > 0 ? versionFloor : version;
605
- }
606
- async function readDiskCache() {
607
- try {
608
- const raw = await import_promises.default.readFile(cachePath(), "utf-8");
609
- const parsed = JSON.parse(raw);
610
- if (typeof parsed.version === "string" && typeof parsed.fetchedAt === "number") {
611
- if (typeof parsed.minVersion === "string") {
612
- if (!versionFloor || compareClaudeCodeVersions(parsed.minVersion, versionFloor) > 0) {
613
- versionFloor = parsed.minVersion;
614
- }
615
- }
616
- return parsed;
617
- }
618
- return null;
619
- } catch {
620
- return null;
621
- }
622
- }
623
- async function writeDiskCache(data) {
624
- try {
625
- await import_promises.default.mkdir(getAppPaths().agentDir, { recursive: true, mode: 448 });
626
- await import_promises.default.writeFile(
627
- cachePath(),
628
- JSON.stringify({ ...data, ...versionFloor ? { minVersion: versionFloor } : {} }),
629
- { mode: 384 }
630
- );
631
- } catch (err) {
632
- log(
633
- "WARN",
634
- "claude-code-version",
635
- `Failed to write cache: ${err instanceof Error ? err.message : String(err)}`
636
- );
637
- }
638
- }
639
- async function fetchLatest() {
640
- const controller = new AbortController();
641
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
642
- try {
643
- const response = await fetch(NPM_LATEST_URL, { signal: controller.signal });
644
- if (!response.ok) return null;
645
- const data = await response.json();
646
- if (typeof data.version === "string" && /^\d/.test(data.version)) {
647
- return data.version;
648
- }
649
- return null;
650
- } catch {
651
- return null;
652
- } finally {
653
- clearTimeout(timer);
654
- }
655
- }
656
- function refreshInBackground() {
657
- if (backgroundRefresh) return;
658
- backgroundRefresh = (async () => {
659
- const fetched = await fetchLatest();
660
- if (fetched) {
661
- await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
662
- memoryCache = { version: applyFloor(fetched), expiresAt: Date.now() + CACHE_FRESH_MS };
663
- }
664
- })().catch(() => {
665
- }).finally(() => {
666
- backgroundRefresh = null;
667
- });
668
- }
669
- async function getClaudeCodeVersion() {
670
- if (memoryCache && Date.now() < memoryCache.expiresAt) {
671
- return memoryCache.version;
672
- }
673
- if (inflight) return inflight;
674
- inflight = (async () => {
675
- const disk = await readDiskCache();
676
- const age = disk ? Date.now() - disk.fetchedAt : Infinity;
677
- if (disk && age < CACHE_FRESH_MS) {
678
- const version = applyFloor(disk.version);
679
- memoryCache = { version, expiresAt: Date.now() + CACHE_FRESH_MS };
680
- return version;
681
- }
682
- if (disk && age < CACHE_HARD_MS) {
683
- const version = applyFloor(disk.version);
684
- memoryCache = { version, expiresAt: Date.now() + 5 * 60 * 1e3 };
685
- refreshInBackground();
686
- return version;
687
- }
688
- const fetched = await fetchLatest();
689
- if (fetched) {
690
- await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
691
- const version = applyFloor(fetched);
692
- memoryCache = { version, expiresAt: Date.now() + CACHE_FRESH_MS };
693
- return version;
694
- }
695
- const resolved = applyFloor(disk?.version ?? FALLBACK_VERSION);
696
- memoryCache = { version: resolved, expiresAt: Date.now() + 5 * 60 * 1e3 };
697
- log(
698
- "WARN",
699
- "claude-code-version",
700
- `Failed to fetch latest Claude Code version; using ${resolved}`
701
- );
702
- return resolved;
703
- })();
704
- try {
705
- return await inflight;
706
- } finally {
707
- inflight = null;
708
- }
709
- }
710
- var REQUIRED_VERSION_PATTERN = /version\s+(\d+(?:\.\d+)+)\s+or\s+newer\s+is\s+required/i;
711
- function recordRequiredClaudeCodeVersion(message) {
712
- const required = REQUIRED_VERSION_PATTERN.exec(message ?? "")?.[1];
713
- if (!required) return null;
714
- if (versionFloor && compareClaudeCodeVersions(required, versionFloor) <= 0) return versionFloor;
715
- versionFloor = required;
716
- memoryCache = null;
717
- log(
718
- "WARN",
719
- "claude-code-version",
720
- `Provider requires Claude Code >= ${required}; pinning User-Agent floor`
721
- );
722
- try {
723
- const dir = getAppPaths().agentDir;
724
- (0, import_node_fs3.mkdirSync)(dir, { recursive: true, mode: 448 });
725
- let existing = {};
726
- try {
727
- existing = JSON.parse((0, import_node_fs3.readFileSync)(cachePath(), "utf-8"));
728
- } catch {
729
- }
730
- (0, import_node_fs3.writeFileSync)(
731
- cachePath(),
732
- JSON.stringify({
733
- version: existing.version ?? required,
734
- fetchedAt: existing.fetchedAt ?? 0,
735
- minVersion: required
736
- }),
737
- { mode: 384 }
738
- );
739
- } catch (err) {
740
- log(
741
- "WARN",
742
- "claude-code-version",
743
- `Failed to persist required version: ${err instanceof Error ? err.message : String(err)}`
744
- );
745
- }
746
- return required;
747
- }
748
- async function getClaudeCliUserAgent() {
749
- const version = await getClaudeCodeVersion();
750
- return `claude-cli/${version} (external, cli)`;
751
- }
752
450
 
753
451
  // src/oauth/anthropic.ts
754
452
  var CLIENT_ID2 = atob("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
@@ -763,7 +461,7 @@ async function postTokenRequest(body, label) {
763
461
  const encoded = JSON.stringify(body);
764
462
  const headers = {
765
463
  "Content-Type": "application/json",
766
- "User-Agent": await getClaudeCliUserAgent(),
464
+ "User-Agent": await (0, import_ai.getClaudeCliUserAgent)(),
767
465
  "anthropic-beta": "oauth-2025-04-20"
768
466
  };
769
467
  let lastError = null;
@@ -800,7 +498,7 @@ function toCredentials(data) {
800
498
  }
801
499
  async function loginAnthropic(callbacks) {
802
500
  const { verifier, challenge } = await generatePKCE();
803
- const state = import_node_crypto3.default.randomBytes(16).toString("hex");
501
+ const state = import_node_crypto2.default.randomBytes(16).toString("hex");
804
502
  const params = new URLSearchParams({
805
503
  code: "true",
806
504
  client_id: CLIENT_ID2,
@@ -848,7 +546,7 @@ async function refreshAnthropicToken(refreshToken) {
848
546
 
849
547
  // src/oauth/openai.ts
850
548
  var import_node_http = __toESM(require("http"), 1);
851
- var import_node_crypto4 = __toESM(require("crypto"), 1);
549
+ var import_node_crypto3 = __toESM(require("crypto"), 1);
852
550
  var CLIENT_ID3 = "app_EMoamEEZ73f0CkXaXp7hrann";
853
551
  var AUTHORIZE_URL2 = "https://auth.openai.com/oauth/authorize";
854
552
  var TOKEN_URL = "https://auth.openai.com/oauth/token";
@@ -860,7 +558,7 @@ var MAX_PASTE_ATTEMPTS = 3;
860
558
  var MIN_RAW_CODE_LENGTH = 10;
861
559
  async function loginOpenAI(callbacks) {
862
560
  const { verifier, challenge } = await generatePKCE();
863
- const state = import_node_crypto4.default.randomBytes(16).toString("hex");
561
+ const state = import_node_crypto3.default.randomBytes(16).toString("hex");
864
562
  const url = new URL(AUTHORIZE_URL2);
865
563
  url.searchParams.set("response_type", "code");
866
564
  url.searchParams.set("client_id", CLIENT_ID3);
@@ -1068,7 +766,7 @@ async function refreshOpenAIToken(refreshToken) {
1068
766
 
1069
767
  // src/oauth/gemini.ts
1070
768
  var import_node_http2 = __toESM(require("http"), 1);
1071
- var import_node_crypto5 = __toESM(require("crypto"), 1);
769
+ var import_node_crypto4 = __toESM(require("crypto"), 1);
1072
770
  var CLIENT_ID_ENV = "EZCODER_GEMINI_OAUTH_CLIENT_ID";
1073
771
  var CLIENT_SECRET_ENV = "EZCODER_GEMINI_OAUTH_CLIENT_SECRET";
1074
772
  var DEFAULT_CLIENT_ID = "681255809395-oo8ft2oprdrnp9e3aqf6av3hmdib135j.apps.googleusercontent.com";
@@ -1102,7 +800,7 @@ var CodeAssistHttpError = class extends Error {
1102
800
  async function loginGemini(callbacks) {
1103
801
  const { clientId: clientId2, clientSecret } = getGeminiOAuthClientCredentials();
1104
802
  const { verifier, challenge } = await generatePKCE();
1105
- const state = import_node_crypto5.default.randomBytes(32).toString("hex");
803
+ const state = import_node_crypto4.default.randomBytes(32).toString("hex");
1106
804
  const redirectUri = await getLoopbackRedirectUri();
1107
805
  const url = new URL(AUTHORIZE_URL3);
1108
806
  url.searchParams.set("response_type", "code");
@@ -1436,7 +1134,7 @@ var DEFAULT_CLIENT_ID2 = "b1a00492-073a-47ea-816f-4c329264a828";
1436
1134
  var DEFAULT_ISSUER = "https://auth.x.ai";
1437
1135
  var DEFAULT_CLI_BASE_URL = "https://cli-chat-proxy.grok.com/v1";
1438
1136
  var OAUTH_SCOPE = "openid profile email offline_access grok-cli:access api:access";
1439
- var DEFAULT_GROK_CLI_VERSION = "0.2.101";
1137
+ var DEFAULT_GROK_CLI_VERSION = "1.0.67";
1440
1138
  var DEVICE_TIMEOUT_FALLBACK_MS = 10 * 60 * 1e3;
1441
1139
  var DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;
1442
1140
  function issuer() {
@@ -1615,81 +1313,860 @@ async function loginXai(callbacks) {
1615
1313
  interval += 5;
1616
1314
  }
1617
1315
  }
1618
- throw new Error("Grok login timed out. Please run login again.");
1316
+ throw new Error("Grok login timed out. Please run login again.");
1317
+ }
1318
+ async function refreshXaiToken(refreshToken) {
1319
+ const { status, data } = await postForm2("/oauth2/token", {
1320
+ client_id: clientId(),
1321
+ grant_type: "refresh_token",
1322
+ refresh_token: refreshToken
1323
+ });
1324
+ if (status === 200 && typeof data.access_token === "string") {
1325
+ return credsFromTokenResponse2(data, { fallbackRefreshToken: refreshToken });
1326
+ }
1327
+ const errorCode = typeof data.error === "string" ? data.error : "";
1328
+ throw new Error(`Grok token refresh failed (${status}): ${errorCode || errorDetail2(data)}`);
1329
+ }
1330
+
1331
+ // src/file-lock.ts
1332
+ var import_promises = __toESM(require("fs/promises"), 1);
1333
+ var import_promises2 = require("timers/promises");
1334
+ var STALE_TIMEOUT_MS = 1e4;
1335
+ var RETRY_INTERVAL_MS = 50;
1336
+ var MAX_WAIT_MS = 5e3;
1337
+ var PENDING_DELETE_CODES = /* @__PURE__ */ new Set(["EACCES", "EBUSY", "EPERM"]);
1338
+ async function withFileLock(filePath, fn) {
1339
+ const lockPath = filePath + ".lock";
1340
+ await acquireLock(lockPath);
1341
+ try {
1342
+ return await fn();
1343
+ } finally {
1344
+ await releaseLock(lockPath);
1345
+ }
1346
+ }
1347
+ async function acquireLock(lockPath) {
1348
+ const startTime = Date.now();
1349
+ let refusedWithoutLock = 0;
1350
+ while (true) {
1351
+ try {
1352
+ const info = { pid: process.pid, timestamp: Date.now() };
1353
+ await import_promises.default.writeFile(lockPath, JSON.stringify(info), { flag: "wx" });
1354
+ return;
1355
+ } catch (err) {
1356
+ const code = err.code;
1357
+ if (code !== "EEXIST") {
1358
+ if (process.platform !== "win32" || !code || !PENDING_DELETE_CODES.has(code)) throw err;
1359
+ const lockPresent = await lockFileExists(lockPath);
1360
+ if (!lockPresent && ++refusedWithoutLock > 3) throw err;
1361
+ if (Date.now() - startTime > MAX_WAIT_MS) throw err;
1362
+ await (0, import_promises2.setTimeout)(RETRY_INTERVAL_MS);
1363
+ continue;
1364
+ }
1365
+ try {
1366
+ const content = await import_promises.default.readFile(lockPath, "utf-8");
1367
+ const info = JSON.parse(content);
1368
+ const isProcessAlive = isAlive(info.pid);
1369
+ const isStale = Date.now() - info.timestamp > STALE_TIMEOUT_MS;
1370
+ if (!isProcessAlive || isStale) {
1371
+ await import_promises.default.unlink(lockPath).catch(() => {
1372
+ });
1373
+ continue;
1374
+ }
1375
+ } catch {
1376
+ const stat = await import_promises.default.stat(lockPath).catch(() => null);
1377
+ if (!stat) continue;
1378
+ if (Date.now() - stat.mtimeMs > STALE_TIMEOUT_MS) {
1379
+ await import_promises.default.unlink(lockPath).catch(() => {
1380
+ });
1381
+ continue;
1382
+ }
1383
+ }
1384
+ if (Date.now() - startTime > MAX_WAIT_MS) {
1385
+ await import_promises.default.unlink(lockPath).catch(() => {
1386
+ });
1387
+ continue;
1388
+ }
1389
+ await (0, import_promises2.setTimeout)(RETRY_INTERVAL_MS);
1390
+ }
1391
+ }
1392
+ }
1393
+ async function lockFileExists(lockPath) {
1394
+ try {
1395
+ await import_promises.default.stat(lockPath);
1396
+ return true;
1397
+ } catch (err) {
1398
+ return err.code !== "ENOENT";
1399
+ }
1400
+ }
1401
+ async function releaseLock(lockPath) {
1402
+ await import_promises.default.unlink(lockPath).catch(() => {
1403
+ });
1404
+ }
1405
+ function isAlive(pid) {
1406
+ try {
1407
+ process.kill(pid, 0);
1408
+ return true;
1409
+ } catch (err) {
1410
+ if (err.code === "EPERM") return true;
1411
+ return false;
1412
+ }
1413
+ }
1414
+
1415
+ // src/logger.ts
1416
+ var import_node_fs2 = __toESM(require("fs"), 1);
1417
+ var import_node_path3 = __toESM(require("path"), 1);
1418
+ var import_node_crypto5 = require("crypto");
1419
+ var import_ai2 = require("@prestyj/ai");
1420
+ var MAX_BYTES = 10 * 1024 * 1024;
1421
+ var MIN_HEADROOM_BYTES = 64 * 1024;
1422
+ var fd = null;
1423
+ var logPath = null;
1424
+ var fileBytes = 0;
1425
+ var processBytes = 0;
1426
+ var rotationFailed = false;
1427
+ var capped = false;
1428
+ var sessionId = "";
1429
+ var appName = "app";
1430
+ var cleanups = [];
1431
+ var exactSecrets = [];
1432
+ function rotateIfNeeded(filePath, force = false) {
1433
+ try {
1434
+ const st = import_node_fs2.default.statSync(filePath);
1435
+ if (!force && st.size <= MAX_BYTES - MIN_HEADROOM_BYTES) return;
1436
+ const rotated = `${filePath}.1`;
1437
+ try {
1438
+ import_node_fs2.default.unlinkSync(rotated);
1439
+ } catch {
1440
+ }
1441
+ import_node_fs2.default.renameSync(filePath, rotated);
1442
+ } catch {
1443
+ }
1444
+ }
1445
+ function rotateOpenLog() {
1446
+ if (fd === null || logPath === null) return false;
1447
+ const sizeBefore = fileBytes;
1448
+ try {
1449
+ import_node_fs2.default.closeSync(fd);
1450
+ } catch {
1451
+ }
1452
+ fd = null;
1453
+ rotateIfNeeded(logPath, true);
1454
+ try {
1455
+ fd = import_node_fs2.default.openSync(logPath, "a");
1456
+ fileBytes = import_node_fs2.default.fstatSync(fd).size;
1457
+ } catch {
1458
+ if (fd !== null) {
1459
+ try {
1460
+ import_node_fs2.default.closeSync(fd);
1461
+ } catch {
1462
+ }
1463
+ }
1464
+ fd = null;
1465
+ capped = true;
1466
+ return false;
1467
+ }
1468
+ if (fileBytes >= sizeBefore) rotationFailed = true;
1469
+ return true;
1470
+ }
1471
+ function openLog(filePath, name) {
1472
+ if (fd !== null || capped) return false;
1473
+ appName = name;
1474
+ exactSecrets = (0, import_ai2.environmentSecrets)(process.env);
1475
+ try {
1476
+ import_node_fs2.default.mkdirSync(import_node_path3.default.dirname(filePath), { recursive: true, mode: 448 });
1477
+ } catch {
1478
+ }
1479
+ rotateIfNeeded(filePath);
1480
+ try {
1481
+ fd = import_node_fs2.default.openSync(filePath, "a");
1482
+ } catch {
1483
+ fd = null;
1484
+ fileBytes = 0;
1485
+ return false;
1486
+ }
1487
+ try {
1488
+ fileBytes = import_node_fs2.default.fstatSync(fd).size;
1489
+ } catch {
1490
+ try {
1491
+ import_node_fs2.default.closeSync(fd);
1492
+ } catch {
1493
+ }
1494
+ fd = null;
1495
+ fileBytes = 0;
1496
+ return false;
1497
+ }
1498
+ logPath = filePath;
1499
+ processBytes = 0;
1500
+ rotationFailed = false;
1501
+ sessionId = (0, import_node_crypto5.randomBytes)(4).toString("hex");
1502
+ try {
1503
+ if (fileBytes < MAX_BYTES) {
1504
+ const written = import_node_fs2.default.writeSync(fd, "\n");
1505
+ fileBytes += written;
1506
+ processBytes += written;
1507
+ }
1508
+ } catch {
1509
+ }
1510
+ return true;
1511
+ }
1512
+ function getSessionId() {
1513
+ return sessionId;
1514
+ }
1515
+ function isLoggerOpen() {
1516
+ return fd !== null;
1517
+ }
1518
+ function log(level, category, message, data) {
1519
+ if (fd === null) return;
1520
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
1521
+ const safeMessage = (0, import_ai2.redactText)(message, { secrets: exactSecrets });
1522
+ let line = `[${ts}] [sid=${sessionId}] [${level}] [${category}] ${safeMessage}`;
1523
+ if (data) {
1524
+ const safeData = (0, import_ai2.redactValue)(data, { secrets: exactSecrets });
1525
+ const pairs = Object.entries(safeData).map(([k, v]) => {
1526
+ if (typeof v === "string") return `${k}=${v}`;
1527
+ if (typeof v === "bigint") return `${k}=${String(v)}`;
1528
+ return `${k}=${JSON.stringify(v)}`;
1529
+ }).join(" ");
1530
+ if (pairs) line += ` ${pairs}`;
1531
+ }
1532
+ line += "\n";
1533
+ const lineBytes = Buffer.byteLength(line);
1534
+ if (processBytes + lineBytes > MAX_BYTES) {
1535
+ const capLine = `[${ts}] [sid=${sessionId}] [WARN] [logger] Log cap reached; file logging disabled until restart
1536
+ `;
1537
+ try {
1538
+ if (fileBytes + Buffer.byteLength(capLine) <= MAX_BYTES) {
1539
+ fileBytes += import_node_fs2.default.writeSync(fd, capLine);
1540
+ }
1541
+ import_node_fs2.default.closeSync(fd);
1542
+ } catch {
1543
+ }
1544
+ fd = null;
1545
+ capped = true;
1546
+ return;
1547
+ }
1548
+ if (fileBytes + lineBytes > MAX_BYTES && !rotationFailed && !rotateOpenLog()) return;
1549
+ if (fd === null) return;
1550
+ try {
1551
+ const written = import_node_fs2.default.writeSync(fd, line);
1552
+ fileBytes += written;
1553
+ processBytes += written;
1554
+ } catch {
1555
+ }
1556
+ }
1557
+ function registerLogCleanup(fn) {
1558
+ cleanups.push(fn);
1559
+ }
1560
+ function closeLogger(opts) {
1561
+ if (fd !== null) {
1562
+ if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName} shutting down`);
1563
+ try {
1564
+ if (fd !== null) import_node_fs2.default.closeSync(fd);
1565
+ } catch {
1566
+ }
1567
+ }
1568
+ fd = null;
1569
+ logPath = null;
1570
+ fileBytes = 0;
1571
+ processBytes = 0;
1572
+ rotationFailed = false;
1573
+ capped = false;
1574
+ exactSecrets = [];
1575
+ for (const unsub of cleanups) unsub();
1576
+ cleanups = [];
1577
+ }
1578
+
1579
+ // src/hidden-providers.ts
1580
+ var HIDDEN_PROVIDERS = ["gemini"];
1581
+ function isHiddenProvider(provider) {
1582
+ return HIDDEN_PROVIDERS.includes(provider);
1583
+ }
1584
+
1585
+ // src/claude-code/runtime.ts
1586
+ var import_node_child_process2 = require("child_process");
1587
+ var import_node_crypto6 = __toESM(require("crypto"), 1);
1588
+ var import_node_fs4 = __toESM(require("fs"), 1);
1589
+ var import_promises4 = __toESM(require("fs/promises"), 1);
1590
+ var import_node_path4 = __toESM(require("path"), 1);
1591
+
1592
+ // src/claude-code/tar.ts
1593
+ var import_node_fs3 = __toESM(require("fs"), 1);
1594
+ var import_promises3 = __toESM(require("fs/promises"), 1);
1595
+ var import_node_zlib = __toESM(require("zlib"), 1);
1596
+ var BLOCK = 512;
1597
+ function readString(buf, offset, length) {
1598
+ const end = buf.indexOf(0, offset);
1599
+ return buf.toString("utf8", offset, end === -1 || end > offset + length ? offset + length : end);
1600
+ }
1601
+ function readSize(buf, offset) {
1602
+ if (buf[offset] & 128) {
1603
+ let value = buf[offset] & 127;
1604
+ for (let i = 1; i < 12; i++) value = value * 256 + buf[offset + i];
1605
+ return value;
1606
+ }
1607
+ const text = readString(buf, offset, 12).trim();
1608
+ return text ? parseInt(text, 8) : 0;
1609
+ }
1610
+ function paxPath(data) {
1611
+ let pos = 0;
1612
+ while (pos < data.length) {
1613
+ const space = data.indexOf(32, pos);
1614
+ if (space === -1) break;
1615
+ const len = parseInt(data.toString("utf8", pos, space), 10);
1616
+ if (!Number.isFinite(len) || len <= 0) break;
1617
+ const record = data.toString("utf8", space + 1, pos + len - 1);
1618
+ const eq = record.indexOf("=");
1619
+ if (eq !== -1 && record.slice(0, eq) === "path") return record.slice(eq + 1);
1620
+ pos += len;
1621
+ }
1622
+ return void 0;
1623
+ }
1624
+ async function extractFileFromTarGz(tgzPath, entryName, destPath) {
1625
+ const input = import_node_fs3.default.createReadStream(tgzPath).pipe(import_node_zlib.default.createGunzip());
1626
+ let pending = Buffer.alloc(0);
1627
+ let remaining = 0;
1628
+ let padding = 0;
1629
+ let kind = "skip";
1630
+ let meta = [];
1631
+ let overridePath;
1632
+ let out;
1633
+ let found = false;
1634
+ try {
1635
+ for await (const chunk of input) {
1636
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
1637
+ let pos = 0;
1638
+ while (pos < pending.length) {
1639
+ if (remaining > 0) {
1640
+ const take = Math.min(remaining, pending.length - pos);
1641
+ const slice = pending.subarray(pos, pos + take);
1642
+ if (kind === "target") await out.write(slice);
1643
+ else if (kind === "pax" || kind === "longname") meta.push(Buffer.from(slice));
1644
+ pos += take;
1645
+ remaining -= take;
1646
+ if (remaining === 0) {
1647
+ if (kind === "target") {
1648
+ await out.close();
1649
+ out = void 0;
1650
+ found = true;
1651
+ } else if (kind === "pax") {
1652
+ overridePath = paxPath(Buffer.concat(meta)) ?? overridePath;
1653
+ } else if (kind === "longname") {
1654
+ overridePath = readString(Buffer.concat(meta), 0, Number.MAX_SAFE_INTEGER);
1655
+ }
1656
+ }
1657
+ continue;
1658
+ }
1659
+ if (padding > 0) {
1660
+ const skip = Math.min(padding, pending.length - pos);
1661
+ pos += skip;
1662
+ padding -= skip;
1663
+ continue;
1664
+ }
1665
+ if (found) break;
1666
+ if (pending.length - pos < BLOCK) break;
1667
+ const header = pending.subarray(pos, pos + BLOCK);
1668
+ pos += BLOCK;
1669
+ if (header.every((b) => b === 0)) continue;
1670
+ const size = readSize(header, 124);
1671
+ const type2 = String.fromCharCode(header[156] || 48);
1672
+ let name = readString(header, 0, 100);
1673
+ if (readString(header, 257, 6) === "ustar") {
1674
+ const prefix = readString(header, 345, 155);
1675
+ if (prefix) name = `${prefix}/${name}`;
1676
+ }
1677
+ remaining = size;
1678
+ padding = (BLOCK - size % BLOCK) % BLOCK;
1679
+ meta = [];
1680
+ if (type2 === "x") kind = "pax";
1681
+ else if (type2 === "L") kind = "longname";
1682
+ else {
1683
+ const path7 = overridePath ?? name;
1684
+ overridePath = void 0;
1685
+ if ((type2 === "0" || type2 === "\0" || type2 === "7") && path7 === entryName) {
1686
+ kind = "target";
1687
+ out = await import_promises3.default.open(destPath, "w", 493);
1688
+ if (size === 0) {
1689
+ await out.close();
1690
+ out = void 0;
1691
+ found = true;
1692
+ }
1693
+ } else {
1694
+ kind = "skip";
1695
+ }
1696
+ }
1697
+ }
1698
+ pending = pos < pending.length ? Buffer.from(pending.subarray(pos)) : Buffer.alloc(0);
1699
+ if (found) break;
1700
+ }
1701
+ if (!found && out) throw new Error(`Archive ended inside ${entryName}`);
1702
+ return found;
1703
+ } finally {
1704
+ if (out) await out.close().catch(() => {
1705
+ });
1706
+ input.destroy();
1707
+ }
1708
+ }
1709
+
1710
+ // src/claude-code/manifest.json
1711
+ var manifest_default = {
1712
+ sdkVersion: "0.3.318",
1713
+ claudeCodeVersion: "2.1.318",
1714
+ platforms: {
1715
+ "darwin-arm64": {
1716
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.318.tgz",
1717
+ integrity: "sha512-AWoXeDXzAMD3RaA21lWuHvCrKd8xmbTTmKjovninn4j07jheoVSMzFbCFjpp4kk5TdhT36JtWPkAxvjNMbcO8w==",
1718
+ bin: "claude"
1719
+ },
1720
+ "darwin-x64": {
1721
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.318.tgz",
1722
+ integrity: "sha512-6CkZ5PCdebSY/LePp16sf/HYRtM6zVuxtn8qYICFS5KUZFsjccJJ9swVsOdHXNHi4SWZcSmIFTwoUbfFCzisRw==",
1723
+ bin: "claude"
1724
+ },
1725
+ "linux-arm64": {
1726
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.318.tgz",
1727
+ integrity: "sha512-mBm4su17aMitLBBCQj3bHdejyUDY6z/ormGih+HG24N689RSbdKECjGjkT87tDBIR/4jyoqmuSeHqM1DI8TJlg==",
1728
+ bin: "claude"
1729
+ },
1730
+ "linux-arm64-musl": {
1731
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.318.tgz",
1732
+ integrity: "sha512-l4LSYFOrvlYCrUImGfxMTQ0wg+T3s9CBhrBvPF/0oJGKZg+QnxHHU8jUVm9e9/xYmDRTtqFIrr4id/5AfH4XGw==",
1733
+ bin: "claude"
1734
+ },
1735
+ "linux-x64": {
1736
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.318.tgz",
1737
+ integrity: "sha512-+mE+ueBD3oRFdaG16rd0h+LMjdeivGxL0pr/+FZK7JeLWVu+yPSw/f/X02b9oK36/DWykiFTu2G6HnJ9/+YO6w==",
1738
+ bin: "claude"
1739
+ },
1740
+ "linux-x64-musl": {
1741
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.318.tgz",
1742
+ integrity: "sha512-SAF3lj/2OzTU84p+OOA13QEKA9+5fYAw0M9E7AJjdnRmVFGqQfbV7Do1i1f9Sj0mIubB3rLTRphGRw8O4HZjgA==",
1743
+ bin: "claude"
1744
+ },
1745
+ "win32-arm64": {
1746
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.318.tgz",
1747
+ integrity: "sha512-19iVSZ4379QbZU1XnGUtfFvhKS1WzS8H1sbU/DbrzqbJ5Kq1eB1drj+obB1fCxTh6m26tRPj0zMJmdeu/jk3Gw==",
1748
+ bin: "claude.exe"
1749
+ },
1750
+ "win32-x64": {
1751
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.318.tgz",
1752
+ integrity: "sha512-ZdKVWpyVNVt0cXrOf8sUBaxcxLEAP+oGMdQDLBWr/BqOxTWLy7TBWOj1kzw+wVg/9WIkjkgQWeJzGXPWulR1sA==",
1753
+ bin: "claude.exe"
1754
+ }
1755
+ }
1756
+ };
1757
+
1758
+ // src/claude-code/runtime.ts
1759
+ var CLAUDE_CODE_MANIFEST = manifest_default;
1760
+ var CLAUDE_CODE_AUTH_KEY = "anthropic-claude-code";
1761
+ var CLAUDE_CODE_AUTH_MARKER = { via: "claude-code" };
1762
+ function isClaudeCodeAuthMarker(value) {
1763
+ return value?.via === CLAUDE_CODE_AUTH_MARKER.via;
1764
+ }
1765
+ function isLegacyClaudeOAuth(value) {
1766
+ const token = value?.accessToken;
1767
+ return typeof token === "string" && token.startsWith("sk-ant-oat");
1768
+ }
1769
+ function isMusl() {
1770
+ if (process.platform !== "linux") return false;
1771
+ const report = typeof process.report?.getReport === "function" ? process.report.getReport() : null;
1772
+ return report != null && report.header?.glibcVersionRuntime === void 0;
1773
+ }
1774
+ function claudeCodePlatformKey(info = { platform: process.platform, arch: process.arch, musl: isMusl() }) {
1775
+ const arch2 = info.arch === "arm64" || info.arch === "x64" ? info.arch : null;
1776
+ if (!arch2) return null;
1777
+ if (info.platform === "darwin" || info.platform === "win32") return `${info.platform}-${arch2}`;
1778
+ if (info.platform === "linux") return `linux-${arch2}${info.musl ? "-musl" : ""}`;
1779
+ return null;
1780
+ }
1781
+ function resolveAsset(opts) {
1782
+ const manifest = opts.manifest ?? CLAUDE_CODE_MANIFEST;
1783
+ const key = opts.platformKey ?? claudeCodePlatformKey();
1784
+ const asset = key ? manifest.platforms[key] : void 0;
1785
+ if (!asset) {
1786
+ throw new Error(
1787
+ `Claude Code isn't available for ${process.platform}-${process.arch}. Use an Anthropic API key instead.`
1788
+ );
1789
+ }
1790
+ return { manifest, asset };
1791
+ }
1792
+ function claudeCodeHome(opts = {}) {
1793
+ return opts.home ?? getAppPaths().claudeCodeDir;
1794
+ }
1795
+ function claudeCodeConfigDir(opts = {}) {
1796
+ return opts.home ? import_node_path4.default.join(opts.home, "config") : getAppPaths().claudeCodeConfigDir;
1797
+ }
1798
+ function claudeCodeBinaryPath(opts = {}) {
1799
+ const { manifest, asset } = resolveAsset(opts);
1800
+ return import_node_path4.default.join(claudeCodeHome(opts), manifest.claudeCodeVersion, asset.bin);
1801
+ }
1802
+ function resolveClaudeCodeBinary(opts = {}) {
1803
+ let binary;
1804
+ try {
1805
+ binary = claudeCodeBinaryPath(opts);
1806
+ } catch {
1807
+ return null;
1808
+ }
1809
+ try {
1810
+ return import_node_fs4.default.statSync(binary).isFile() ? binary : null;
1811
+ } catch {
1812
+ return null;
1813
+ }
1814
+ }
1815
+ var installs = /* @__PURE__ */ new Map();
1816
+ async function ensureClaudeCodeBinary(opts = {}) {
1817
+ const existing = resolveClaudeCodeBinary(opts);
1818
+ if (existing) return existing;
1819
+ const target = claudeCodeBinaryPath(opts);
1820
+ let install = installs.get(target);
1821
+ if (!install) {
1822
+ install = installClaudeCode(opts).finally(() => installs.delete(target));
1823
+ installs.set(target, install);
1824
+ }
1825
+ return install;
1826
+ }
1827
+ async function installClaudeCode(opts) {
1828
+ const { manifest, asset } = resolveAsset(opts);
1829
+ const home = claudeCodeHome(opts);
1830
+ const versionDir = import_node_path4.default.join(home, manifest.claudeCodeVersion);
1831
+ const binary = import_node_path4.default.join(versionDir, asset.bin);
1832
+ await import_promises4.default.mkdir(home, { recursive: true });
1833
+ const tag = `${process.pid}-${import_node_crypto6.default.randomBytes(4).toString("hex")}`;
1834
+ const tarball = import_node_path4.default.join(home, `.download-${tag}.tgz`);
1835
+ const staging = import_node_path4.default.join(home, `.staging-${tag}`);
1836
+ try {
1837
+ await download(asset, tarball, opts);
1838
+ opts.onProgress?.({ phase: "extract" });
1839
+ await import_promises4.default.mkdir(staging, { recursive: true });
1840
+ const found = await extractFileFromTarGz(
1841
+ tarball,
1842
+ `package/${asset.bin}`,
1843
+ import_node_path4.default.join(staging, asset.bin)
1844
+ );
1845
+ if (!found) throw new Error(`The Claude Code download has no ${asset.bin} binary.`);
1846
+ await import_promises4.default.chmod(import_node_path4.default.join(staging, asset.bin), 493);
1847
+ try {
1848
+ await import_promises4.default.rename(staging, versionDir);
1849
+ } catch (err) {
1850
+ if (!import_node_fs4.default.existsSync(binary)) throw err;
1851
+ }
1852
+ await removeOldVersions(home, manifest.claudeCodeVersion);
1853
+ return binary;
1854
+ } finally {
1855
+ await import_promises4.default.rm(tarball, { force: true }).catch(() => {
1856
+ });
1857
+ await import_promises4.default.rm(staging, { recursive: true, force: true }).catch(() => {
1858
+ });
1859
+ }
1860
+ }
1861
+ async function download(asset, dest, opts) {
1862
+ const doFetch = opts.fetch ?? fetch;
1863
+ const res = await doFetch(asset.url, { signal: opts.signal });
1864
+ if (!res.ok || !res.body) {
1865
+ throw new Error(`Claude Code download failed (HTTP ${res.status}).`);
1866
+ }
1867
+ const totalBytes = Number(res.headers.get("content-length")) || void 0;
1868
+ const hash = import_node_crypto6.default.createHash("sha512");
1869
+ const out = await import_promises4.default.open(dest, "w");
1870
+ let receivedBytes = 0;
1871
+ let lastReported = -1;
1872
+ try {
1873
+ opts.onProgress?.({ phase: "download", receivedBytes, totalBytes });
1874
+ for await (const chunk of res.body) {
1875
+ if (opts.signal?.aborted) throw opts.signal.reason ?? new Error("Download cancelled.");
1876
+ hash.update(chunk);
1877
+ await out.write(chunk);
1878
+ receivedBytes += chunk.byteLength;
1879
+ const step = totalBytes ? Math.floor(receivedBytes / totalBytes * 100) : Math.floor(receivedBytes / 4194304);
1880
+ if (step !== lastReported) {
1881
+ lastReported = step;
1882
+ opts.onProgress?.({ phase: "download", receivedBytes, totalBytes });
1883
+ }
1884
+ }
1885
+ } finally {
1886
+ await out.close();
1887
+ }
1888
+ opts.onProgress?.({ phase: "verify" });
1889
+ const expected = asset.integrity.replace(/^sha512-/, "");
1890
+ if (hash.digest("base64") !== expected) {
1891
+ throw new Error(
1892
+ "The Claude Code download didn't match its pinned checksum, so it was discarded."
1893
+ );
1894
+ }
1895
+ }
1896
+ async function removeOldVersions(home, keep) {
1897
+ let entries;
1898
+ try {
1899
+ entries = await import_promises4.default.readdir(home, { withFileTypes: true });
1900
+ } catch {
1901
+ return;
1902
+ }
1903
+ for (const entry of entries) {
1904
+ if (!entry.isDirectory() || entry.name === keep || entry.name === "config") continue;
1905
+ if (!/^\d+\.\d+\.\d+/.test(entry.name)) continue;
1906
+ await import_promises4.default.rm(import_node_path4.default.join(home, entry.name), { recursive: true, force: true }).catch(() => {
1907
+ });
1908
+ }
1619
1909
  }
1620
- async function refreshXaiToken(refreshToken) {
1621
- const { status, data } = await postForm2("/oauth2/token", {
1622
- client_id: clientId(),
1623
- grant_type: "refresh_token",
1624
- refresh_token: refreshToken
1910
+ function formatClaudeCodeInstallProgress(progress) {
1911
+ if (progress.phase === "verify") return "Checking the Claude Code download\u2026";
1912
+ if (progress.phase === "extract") return "Unpacking Claude Code\u2026";
1913
+ const mb = (bytes) => Math.round(bytes / 1048576);
1914
+ if (!progress.totalBytes) return `Downloading Claude Code\u2026 ${mb(progress.receivedBytes)} MB`;
1915
+ const pct = Math.floor(progress.receivedBytes / progress.totalBytes * 100);
1916
+ return `Downloading Claude Code\u2026 ${pct}% (${mb(progress.receivedBytes)} of ${mb(progress.totalBytes)} MB)`;
1917
+ }
1918
+ var STRIPPED_ENV = [
1919
+ "ANTHROPIC_API_KEY",
1920
+ "ANTHROPIC_AUTH_TOKEN",
1921
+ "ANTHROPIC_BASE_URL",
1922
+ "CLAUDE_CODE_OAUTH_TOKEN",
1923
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
1924
+ "CLAUDE_CODE_USE_BEDROCK",
1925
+ "CLAUDE_CODE_USE_VERTEX",
1926
+ "CLAUDE_CODE_USE_FOUNDRY",
1927
+ "NODE_OPTIONS"
1928
+ ];
1929
+ function claudeCodeEnv(opts = {}, base = process.env) {
1930
+ const env = {};
1931
+ for (const [key, value] of Object.entries(base)) {
1932
+ if (value !== void 0 && !STRIPPED_ENV.includes(key)) env[key] = value;
1933
+ }
1934
+ env.CLAUDE_CONFIG_DIR = claudeCodeConfigDir(opts);
1935
+ env.DISABLE_AUTOUPDATER = "1";
1936
+ return env;
1937
+ }
1938
+ function runCommand(opts) {
1939
+ if (opts.binary) return { command: opts.binary, prefix: opts.binaryArgs ?? [] };
1940
+ const binary = resolveClaudeCodeBinary(opts);
1941
+ if (!binary) throw new Error("Claude Code isn't installed yet. Sign in with Claude first.");
1942
+ return { command: binary, prefix: [] };
1943
+ }
1944
+ function runClaude(args, opts) {
1945
+ const { command, prefix } = runCommand(opts);
1946
+ return new Promise((resolve, reject) => {
1947
+ const child = (0, import_node_child_process2.spawn)(command, [...prefix, ...args], {
1948
+ env: claudeCodeEnv(opts),
1949
+ stdio: ["ignore", "pipe", "pipe"],
1950
+ windowsHide: true,
1951
+ signal: opts.signal
1952
+ });
1953
+ let stdout = "";
1954
+ let stderr = "";
1955
+ child.stdout.on("data", (d) => stdout += d.toString());
1956
+ child.stderr.on("data", (d) => stderr += d.toString());
1957
+ child.on("error", reject);
1958
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
1625
1959
  });
1626
- if (status === 200 && typeof data.access_token === "string") {
1627
- return credsFromTokenResponse2(data, { fallbackRefreshToken: refreshToken });
1960
+ }
1961
+ async function claudeCodeAuthStatus(opts = {}) {
1962
+ if (!opts.binary && !resolveClaudeCodeBinary(opts)) return { loggedIn: false };
1963
+ const { stdout } = await runClaude(["auth", "status", "--json"], opts);
1964
+ try {
1965
+ const parsed = JSON.parse(stdout);
1966
+ return {
1967
+ loggedIn: parsed.loggedIn === true,
1968
+ ...typeof parsed.authMethod === "string" ? { authMethod: parsed.authMethod } : {},
1969
+ ...typeof parsed.email === "string" ? { email: parsed.email } : {},
1970
+ ...typeof parsed.subscriptionType === "string" ? { subscriptionType: parsed.subscriptionType } : {}
1971
+ };
1972
+ } catch {
1973
+ return { loggedIn: false };
1628
1974
  }
1629
- const errorCode = typeof data.error === "string" ? data.error : "";
1630
- throw new Error(`Grok token refresh failed (${status}): ${errorCode || errorDetail2(data)}`);
1631
1975
  }
1632
-
1633
- // src/file-lock.ts
1634
- var import_promises2 = __toESM(require("fs/promises"), 1);
1635
- var import_promises3 = require("timers/promises");
1636
- var STALE_TIMEOUT_MS = 1e4;
1637
- var RETRY_INTERVAL_MS = 50;
1638
- var MAX_WAIT_MS = 5e3;
1639
- async function withFileLock(filePath, fn) {
1640
- const lockPath = filePath + ".lock";
1641
- await acquireLock(lockPath);
1976
+ async function logoutClaudeCode(opts = {}) {
1977
+ if (!opts.binary && !resolveClaudeCodeBinary(opts)) return;
1978
+ const { code, stderr } = await runClaude(["auth", "logout"], opts);
1979
+ if (code !== 0) throw new Error(stderr.trim() || `claude auth logout exited with ${code}`);
1980
+ }
1981
+ var OPEN_URL_HOOK = `const arg = String(process.argv[1] || "");
1982
+ const file = process.env.EZ_CLAUDE_CODE_URL_FILE;
1983
+ if (file && /https?:/.test(arg)) {
1984
+ require("node:fs").appendFileSync(file, arg + "\\n");
1985
+ process.exit(0);
1986
+ }
1987
+ `;
1988
+ var CAPTURE_WAIT_MS = 3e3;
1989
+ function stripAnsi(text) {
1990
+ return text.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[A-Za-z]/g, "");
1991
+ }
1992
+ function claudeCodeCallbackUrl(manualUrl, captured) {
1993
+ const port = /localhost(?::|%3A)(\d{2,5})(?:\/|%2F)callback/i.exec(captured)?.[1];
1994
+ if (!port) return null;
1642
1995
  try {
1643
- return await fn();
1996
+ const url = new URL(manualUrl);
1997
+ url.searchParams.set("redirect_uri", `http://localhost:${port}/callback`);
1998
+ return url.toString();
1999
+ } catch {
2000
+ return null;
2001
+ }
2002
+ }
2003
+ async function loginClaudeCode(callbacks, opts = {}) {
2004
+ const { command, prefix } = runCommand(opts);
2005
+ const home = claudeCodeHome(opts);
2006
+ await import_promises4.default.mkdir(claudeCodeConfigDir(opts), { recursive: true });
2007
+ const tag = `${process.pid}-${import_node_crypto6.default.randomBytes(4).toString("hex")}`;
2008
+ const hookFile = import_node_path4.default.join(home, `.open-url-${tag}.cjs`);
2009
+ const urlFile = import_node_path4.default.join(home, `.open-url-${tag}.txt`);
2010
+ await import_promises4.default.writeFile(hookFile, OPEN_URL_HOOK);
2011
+ const env = {
2012
+ ...claudeCodeEnv(opts),
2013
+ BROWSER: process.execPath,
2014
+ NODE_OPTIONS: `--require ${JSON.stringify(hookFile)}`,
2015
+ EZ_CLAUDE_CODE_URL_FILE: urlFile
2016
+ };
2017
+ const promptAbort = new AbortController();
2018
+ let timer;
2019
+ try {
2020
+ await new Promise((resolve, reject) => {
2021
+ const child = (0, import_node_child_process2.spawn)(command, [...prefix, "auth", "login", "--claudeai"], {
2022
+ env,
2023
+ stdio: ["pipe", "pipe", "pipe"],
2024
+ windowsHide: true
2025
+ });
2026
+ let stdout = "";
2027
+ let stderr = "";
2028
+ let manualUrl = null;
2029
+ let opened = false;
2030
+ const onAbort = () => child.kill();
2031
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
2032
+ const open = (url, needsCode) => {
2033
+ if (opened) return;
2034
+ opened = true;
2035
+ clearInterval(timer);
2036
+ callbacks.onOpenUrl(url);
2037
+ callbacks.onStatus("Finish signing in to Claude in your browser\u2026");
2038
+ if (!needsCode) return;
2039
+ void callbacks.onPromptCode("Paste the code shown after signing in to Claude:", promptAbort.signal).then((code) => {
2040
+ const trimmed = code.trim();
2041
+ if (trimmed && !child.stdin.destroyed) child.stdin.write(`${trimmed}
2042
+ `);
2043
+ }).catch(() => {
2044
+ });
2045
+ };
2046
+ child.stdout.on("data", (d) => {
2047
+ stdout += d.toString();
2048
+ if (manualUrl) return;
2049
+ const match = /visit:\s*(https:\/\/\S+)/.exec(stripAnsi(stdout));
2050
+ if (!match) return;
2051
+ manualUrl = match[1];
2052
+ const started = Date.now();
2053
+ timer = setInterval(() => {
2054
+ let captured = "";
2055
+ try {
2056
+ captured = import_node_fs4.default.readFileSync(urlFile, "utf8");
2057
+ } catch {
2058
+ }
2059
+ const callbackUrl = captured ? claudeCodeCallbackUrl(manualUrl, captured) : null;
2060
+ if (callbackUrl) open(callbackUrl, false);
2061
+ else if (Date.now() - started > (opts.browserWaitMs ?? CAPTURE_WAIT_MS))
2062
+ open(manualUrl, true);
2063
+ }, 100);
2064
+ });
2065
+ child.stderr.on("data", (d) => stderr += d.toString());
2066
+ child.on("error", reject);
2067
+ child.on("close", (code) => {
2068
+ opts.signal?.removeEventListener("abort", onAbort);
2069
+ if (opts.signal?.aborted) reject(new Error("Sign-in cancelled."));
2070
+ else if (code === 0) resolve();
2071
+ else {
2072
+ const detail = stripAnsi(stderr).trim().split("\n").pop()?.trim();
2073
+ reject(new Error(detail || `Claude sign-in failed (exit ${code}).`));
2074
+ }
2075
+ });
2076
+ });
1644
2077
  } finally {
1645
- await releaseLock(lockPath);
2078
+ clearInterval(timer);
2079
+ promptAbort.abort();
2080
+ await import_promises4.default.rm(hookFile, { force: true }).catch(() => {
2081
+ });
2082
+ await import_promises4.default.rm(urlFile, { force: true }).catch(() => {
2083
+ });
1646
2084
  }
1647
2085
  }
1648
- async function acquireLock(lockPath) {
1649
- const startTime = Date.now();
1650
- while (true) {
2086
+
2087
+ // src/auth-storage.ts
2088
+ var import_ai3 = require("@prestyj/ai");
2089
+
2090
+ // src/minimax-region.ts
2091
+ var MINIMAX_GLOBAL_BASE_URL = "https://api.minimax.io/anthropic";
2092
+ var MINIMAX_CN_BASE_URL = "https://api.minimax.cn/anthropic";
2093
+ var REGION_HOSTS = [
2094
+ { host: "https://api.minimax.io", baseUrl: MINIMAX_GLOBAL_BASE_URL },
2095
+ { host: "https://api.minimax.cn", baseUrl: MINIMAX_CN_BASE_URL }
2096
+ ];
2097
+ var KEY_KNOWN_CODES = /* @__PURE__ */ new Set([0, 2062]);
2098
+ var KEY_REJECTED_CODES = /* @__PURE__ */ new Set([1004, 2049]);
2099
+ async function probeRegion(host, apiKey, fetchImpl, timeoutMs) {
2100
+ const url = apiKey.startsWith("sk-api-") ? `${host}/account/query_balance` : `${host}/v1/token_plan/remains`;
2101
+ let sawRejection = false;
2102
+ const authHeaders2 = [
2103
+ { Authorization: `Bearer ${apiKey}` },
2104
+ { "x-api-key": apiKey }
2105
+ ];
2106
+ for (const auth of authHeaders2) {
2107
+ let res;
1651
2108
  try {
1652
- const info = { pid: process.pid, timestamp: Date.now() };
1653
- await import_promises2.default.writeFile(lockPath, JSON.stringify(info), { flag: "wx" });
1654
- return;
1655
- } catch (err) {
1656
- if (err.code !== "EEXIST") throw err;
1657
- try {
1658
- const content = await import_promises2.default.readFile(lockPath, "utf-8");
1659
- const info = JSON.parse(content);
1660
- const isProcessAlive = isAlive(info.pid);
1661
- const isStale = Date.now() - info.timestamp > STALE_TIMEOUT_MS;
1662
- if (!isProcessAlive || isStale) {
1663
- await import_promises2.default.unlink(lockPath).catch(() => {
1664
- });
1665
- continue;
1666
- }
1667
- } catch {
1668
- await import_promises2.default.unlink(lockPath).catch(() => {
1669
- });
1670
- continue;
1671
- }
1672
- if (Date.now() - startTime > MAX_WAIT_MS) {
1673
- await import_promises2.default.unlink(lockPath).catch(() => {
1674
- });
1675
- continue;
1676
- }
1677
- await (0, import_promises3.setTimeout)(RETRY_INTERVAL_MS);
2109
+ res = await fetchImpl(url, {
2110
+ headers: { ...auth, "Content-Type": "application/json" },
2111
+ signal: AbortSignal.timeout(timeoutMs)
2112
+ });
2113
+ } catch {
2114
+ return "inconclusive";
2115
+ }
2116
+ if (res.status === 401 || res.status === 403) {
2117
+ sawRejection = true;
2118
+ continue;
2119
+ }
2120
+ if (!res.ok) return "inconclusive";
2121
+ let code;
2122
+ try {
2123
+ code = (await res.json()).base_resp?.status_code;
2124
+ } catch {
2125
+ return "inconclusive";
1678
2126
  }
2127
+ if (typeof code === "number" && KEY_KNOWN_CODES.has(code)) return "authorized";
2128
+ if (typeof code === "number" && KEY_REJECTED_CODES.has(code)) {
2129
+ sawRejection = true;
2130
+ continue;
2131
+ }
2132
+ return "inconclusive";
1679
2133
  }
2134
+ return sawRejection ? "unauthorized" : "inconclusive";
1680
2135
  }
1681
- async function releaseLock(lockPath) {
1682
- await import_promises2.default.unlink(lockPath).catch(() => {
1683
- });
2136
+ async function detectMiniMaxBaseUrl(apiKey, options = {}) {
2137
+ const fetchImpl = options.fetch ?? fetch;
2138
+ const timeoutMs = options.timeoutMs ?? 5e3;
2139
+ const results = await Promise.all(
2140
+ REGION_HOSTS.map((r) => probeRegion(r.host, apiKey, fetchImpl, timeoutMs))
2141
+ );
2142
+ const index = results.indexOf("authorized");
2143
+ return index === -1 ? void 0 : REGION_HOSTS[index].baseUrl;
1684
2144
  }
1685
- function isAlive(pid) {
1686
- try {
1687
- process.kill(pid, 0);
1688
- return true;
1689
- } catch (err) {
1690
- if (err.code === "EPERM") return true;
1691
- return false;
1692
- }
2145
+
2146
+ // src/xiaomi-region.ts
2147
+ var XIAOMI_TOKEN_PLAN_BASE_URLS = [
2148
+ "https://token-plan-sgp.xiaomimimo.com/v1",
2149
+ "https://token-plan-ams.xiaomimimo.com/v1",
2150
+ "https://token-plan-cn.xiaomimimo.com/v1"
2151
+ ];
2152
+ async function detectXiaomiTokenPlanBaseUrl(apiKey, options = {}) {
2153
+ const fetchImpl = options.fetch ?? fetch;
2154
+ const timeoutMs = options.timeoutMs ?? 5e3;
2155
+ const accepted = await Promise.all(
2156
+ XIAOMI_TOKEN_PLAN_BASE_URLS.map(async (baseUrl) => {
2157
+ try {
2158
+ const res = await fetchImpl(`${baseUrl}/models`, {
2159
+ headers: { Authorization: `Bearer ${apiKey}` },
2160
+ signal: AbortSignal.timeout(timeoutMs)
2161
+ });
2162
+ return res.ok;
2163
+ } catch {
2164
+ return false;
2165
+ }
2166
+ })
2167
+ );
2168
+ const index = accepted.indexOf(true);
2169
+ return index === -1 ? void 0 : XIAOMI_TOKEN_PLAN_BASE_URLS[index];
1693
2170
  }
1694
2171
 
1695
2172
  // src/auth-storage.ts
@@ -1742,9 +2219,18 @@ function activeBaseUrlEntry(data, provider) {
1742
2219
  }
1743
2220
  return data[provider];
1744
2221
  }
2222
+ var MINIMAX_REGION_RETRY_MS = 5 * 60 * 1e3;
2223
+ var miniMaxRegionProbes = /* @__PURE__ */ new Map();
2224
+ function cachedMiniMaxRegion(apiKey) {
2225
+ const cached = miniMaxRegionProbes.get(apiKey);
2226
+ if (cached && Date.now() - cached.at < MINIMAX_REGION_RETRY_MS) return cached.result;
2227
+ const result = detectMiniMaxBaseUrl(apiKey).catch(() => void 0);
2228
+ miniMaxRegionProbes.set(apiKey, { at: Date.now(), result });
2229
+ return result;
2230
+ }
1745
2231
  function readStoredBaseUrlSync(authFile, provider) {
1746
2232
  try {
1747
- const data = JSON.parse((0, import_node_fs4.readFileSync)(authFile, "utf-8"));
2233
+ const data = JSON.parse((0, import_node_fs5.readFileSync)(authFile, "utf-8"));
1748
2234
  return activeBaseUrlEntry(data, provider)?.baseUrl;
1749
2235
  } catch {
1750
2236
  return void 0;
@@ -1788,8 +2274,12 @@ var AuthStorage = class {
1788
2274
  snapshotIno = 0;
1789
2275
  /** Per-provider lock to serialize concurrent refresh calls. */
1790
2276
  refreshLocks = /* @__PURE__ */ new Map();
1791
- constructor(filePath) {
2277
+ detectMiniMaxRegion;
2278
+ detectXiaomiCluster;
2279
+ constructor(filePath, options) {
1792
2280
  this.filePath = filePath ?? getAppPaths().authFile;
2281
+ this.detectMiniMaxRegion = options?.detectMiniMaxBaseUrl ?? cachedMiniMaxRegion;
2282
+ this.detectXiaomiCluster = options?.detectXiaomiTokenPlanBaseUrl ?? detectXiaomiTokenPlanBaseUrl;
1793
2283
  }
1794
2284
  /** Path to the on-disk auth file. Useful for status output. */
1795
2285
  get path() {
@@ -1822,6 +2312,7 @@ var AuthStorage = class {
1822
2312
  * satisfies it.
1823
2313
  */
1824
2314
  async hasProviderAuth(provider) {
2315
+ if (isHiddenProvider(provider)) return false;
1825
2316
  await this.ensureFresh();
1826
2317
  const dual = dualAuthProvider(provider);
1827
2318
  if (dual) {
@@ -1833,11 +2324,28 @@ var AuthStorage = class {
1833
2324
  if (provider === "gemini") {
1834
2325
  return Boolean(this.data["gemini"] || this.data[GEMINI_API_KEY]);
1835
2326
  }
2327
+ if (provider === "anthropic" && isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY])) {
2328
+ return true;
2329
+ }
1836
2330
  if (provider === "local") {
1837
2331
  return Object.keys(this.data).some((key) => key.startsWith(LOCAL_AUTH_KEY_PREFIX));
1838
2332
  }
1839
2333
  return Boolean(this.data[provider]);
1840
2334
  }
2335
+ /** True when the user signed in with Claude through Claude Code (marker only, no token). */
2336
+ async hasClaudeCodeLogin() {
2337
+ await this.ensureFresh();
2338
+ return isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY]);
2339
+ }
2340
+ /** Record a Claude Code sign-in. Claude Code keeps the token; auth.json gets only the marker. */
2341
+ async setClaudeCodeLogin() {
2342
+ await this.mutateLatest((latest) => {
2343
+ latest[CLAUDE_CODE_AUTH_KEY] = { ...CLAUDE_CODE_AUTH_MARKER };
2344
+ });
2345
+ }
2346
+ async clearClaudeCodeLogin() {
2347
+ await this.clearCredentials(CLAUDE_CODE_AUTH_KEY);
2348
+ }
1841
2349
  /** Endpoint ids that currently have a `local:<id>` credential stored. */
1842
2350
  async listLocalEndpointIds() {
1843
2351
  await this.ensureLoaded();
@@ -1850,7 +2358,7 @@ var AuthStorage = class {
1850
2358
  */
1851
2359
  async setLocalEndpoint(endpointId, baseUrl, apiKey) {
1852
2360
  await this.setCredentials(`${LOCAL_AUTH_KEY_PREFIX}${endpointId}`, {
1853
- accessToken: apiKey && apiKey.length > 0 ? apiKey : "local",
2361
+ accessToken: apiKey && apiKey.length > 0 ? apiKey : import_ai3.LOCAL_NO_API_KEY,
1854
2362
  refreshToken: "",
1855
2363
  expiresAt: Date.now() + LOCAL_CREDENTIAL_LIFETIME_MS,
1856
2364
  baseUrl
@@ -1891,7 +2399,7 @@ var AuthStorage = class {
1891
2399
  const first = !this.loaded;
1892
2400
  await withFileLock(this.filePath, async () => {
1893
2401
  try {
1894
- const content = await import_promises4.default.readFile(this.filePath, "utf-8");
2402
+ const content = await import_promises5.default.readFile(this.filePath, "utf-8");
1895
2403
  this.data = JSON.parse(content);
1896
2404
  if (first) {
1897
2405
  log("INFO", "auth", `Loaded credentials from ${this.filePath}`, {
@@ -1946,7 +2454,7 @@ var AuthStorage = class {
1946
2454
  }
1947
2455
  let changed;
1948
2456
  try {
1949
- const stat = await import_promises4.default.stat(this.filePath);
2457
+ const stat = await import_promises5.default.stat(this.filePath);
1950
2458
  changed = stat.ino !== this.snapshotIno || stat.mtimeMs !== this.snapshotMtimeMs || stat.size !== this.snapshotSize;
1951
2459
  } catch {
1952
2460
  changed = this.snapshotSize !== -1;
@@ -1956,7 +2464,7 @@ var AuthStorage = class {
1956
2464
  /** Record the file identity behind the current snapshot. */
1957
2465
  async rememberSnapshot() {
1958
2466
  try {
1959
- const stat = await import_promises4.default.stat(this.filePath);
2467
+ const stat = await import_promises5.default.stat(this.filePath);
1960
2468
  this.snapshotMtimeMs = stat.mtimeMs;
1961
2469
  this.snapshotSize = stat.size;
1962
2470
  this.snapshotIno = stat.ino;
@@ -1993,11 +2501,54 @@ var AuthStorage = class {
1993
2501
  await this.ensureFresh();
1994
2502
  return this.data[provider];
1995
2503
  }
2504
+ /**
2505
+ * A MiniMax key saved without an endpoint (every key, until its first use)
2506
+ * gets the endpoint of the region that issued it, saved so the check runs
2507
+ * once. Without this a Mainland China key went to the Global API, got a 401,
2508
+ * and was deleted as invalid.
2509
+ */
2510
+ async withMiniMaxRegion(creds) {
2511
+ const baseUrl = await this.detectMiniMaxRegion(creds.accessToken);
2512
+ if (!baseUrl) return creds;
2513
+ log("INFO", "auth", `MiniMax key belongs to ${baseUrl} \u2014 saved for future requests`);
2514
+ await this.mutateLatest((latest) => {
2515
+ const current = latest["minimax"];
2516
+ if (current?.accessToken === creds.accessToken && !current.baseUrl) {
2517
+ current.baseUrl = baseUrl;
2518
+ }
2519
+ });
2520
+ return { ...creds, baseUrl };
2521
+ }
1996
2522
  async setCredentials(provider, creds) {
1997
2523
  await this.mutateLatest((latest) => {
1998
2524
  latest[provider] = creds;
1999
2525
  });
2000
2526
  }
2527
+ /**
2528
+ * After a 401, move a regional key to the cluster that issued it instead of
2529
+ * treating it as invalid. Only the Xiaomi Token Plan is regional: every key
2530
+ * used to go to Singapore, so Europe and China keys were rejected and deleted.
2531
+ * Returns the new base URL, or undefined when no other cluster accepts the key.
2532
+ */
2533
+ async relocateRegionalApiKey(storageKeys) {
2534
+ const key = await this.pickStorageKey(storageKeys);
2535
+ const creds = key === "xiaomi" ? this.data[key] : void 0;
2536
+ if (!creds) return void 0;
2537
+ const baseUrl = await this.detectXiaomiCluster(creds.accessToken);
2538
+ if (!baseUrl || baseUrl === creds.baseUrl) return void 0;
2539
+ await this.mutateLatest((latest) => {
2540
+ const current = latest["xiaomi"];
2541
+ if (current?.accessToken === creds.accessToken) current.baseUrl = baseUrl;
2542
+ });
2543
+ log("INFO", "auth", `Xiaomi Token Plan key belongs to ${baseUrl} \u2014 saved for future requests`);
2544
+ return baseUrl;
2545
+ }
2546
+ // Keeps local-endpoint keys: they're the user's own config, and a 401 there is often a busy gateway.
2547
+ async clearRejectedApiKey(storageKey) {
2548
+ if (storageKey.startsWith(LOCAL_AUTH_KEY_PREFIX)) return false;
2549
+ await this.clearCredentials(storageKey);
2550
+ return true;
2551
+ }
2001
2552
  async clearCredentials(provider) {
2002
2553
  await this.mutateLatest((latest) => {
2003
2554
  delete latest[provider];
@@ -2077,6 +2628,9 @@ var AuthStorage = class {
2077
2628
  }
2078
2629
  throw new NotLoggedInError(provider);
2079
2630
  }
2631
+ if (provider === "anthropic" && !this.data.anthropic && isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY])) {
2632
+ return { accessToken: "", refreshToken: "", expiresAt: Number.MAX_SAFE_INTEGER };
2633
+ }
2080
2634
  const dual = dualAuthProvider(provider);
2081
2635
  const dualOAuthCreds = dual ? this.data[dual.oauthKey] : void 0;
2082
2636
  if (dual && dualOAuthCreds) {
@@ -2111,6 +2665,7 @@ var AuthStorage = class {
2111
2665
  throw new NotLoggedInError(provider);
2112
2666
  }
2113
2667
  if (STATIC_API_KEY_PROVIDERS.has(provider)) {
2668
+ if (provider === "minimax" && !creds.baseUrl) return await this.withMiniMaxRegion(creds);
2114
2669
  return creds;
2115
2670
  }
2116
2671
  if (!opts?.forceRefresh && Date.now() < creds.expiresAt - refreshThresholdMs(creds)) {
@@ -2197,7 +2752,7 @@ var AuthStorage = class {
2197
2752
  };
2198
2753
  async function readAuthData(filePath) {
2199
2754
  try {
2200
- const content = await import_promises4.default.readFile(filePath, "utf-8");
2755
+ const content = await import_promises5.default.readFile(filePath, "utf-8");
2201
2756
  return JSON.parse(content);
2202
2757
  } catch (error) {
2203
2758
  if (error.code === "ENOENT") return {};
@@ -2205,12 +2760,12 @@ async function readAuthData(filePath) {
2205
2760
  }
2206
2761
  }
2207
2762
  async function atomicWriteFile(filePath, content) {
2208
- const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_node_crypto6.default.randomUUID().slice(0, 8)}.tmp`;
2763
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${import_node_crypto7.default.randomUUID().slice(0, 8)}.tmp`;
2209
2764
  try {
2210
- await import_promises4.default.writeFile(tmpPath, content, { encoding: "utf-8", mode: 384 });
2211
- await import_promises4.default.rename(tmpPath, filePath);
2765
+ await import_promises5.default.writeFile(tmpPath, content, { encoding: "utf-8", mode: 384 });
2766
+ await import_promises5.default.rename(tmpPath, filePath);
2212
2767
  } catch (err) {
2213
- await import_promises4.default.unlink(tmpPath).catch(() => {
2768
+ await import_promises5.default.unlink(tmpPath).catch(() => {
2214
2769
  });
2215
2770
  throw err;
2216
2771
  }
@@ -2231,6 +2786,12 @@ var CLAUDE_FAST_BILLING = {
2231
2786
  paid: true,
2232
2787
  standardModel: "claude-opus-5-5"
2233
2788
  };
2789
+ var CLAUDE_FABLE_FAST_BILLING = {
2790
+ label: "bills usage credits",
2791
+ 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.",
2792
+ paid: true,
2793
+ standardModel: "claude-fable-5-2"
2794
+ };
2234
2795
  var XIAOMI_ULTRASPEED_BILLING = {
2235
2796
  label: "bills API Credits",
2236
2797
  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.",
@@ -2245,18 +2806,18 @@ var CODEX_FAST_BILLING = {
2245
2806
  var GEMINI_AUTH_KEYS = [GEMINI_API_KEY, "gemini"];
2246
2807
  var MODELS = [
2247
2808
  // ── Anthropic ──────────────────────────────────────────
2248
- // NOTE: Claude Mythos 5.1 (`claude-mythos-5-1`, 2026-09-01) is kept commented
2249
- // out — it's a Project Glasswing model, still "Active (invite only)" in
2250
- // Anthropic's docs and unavailable to most users. Re-enable once it's
2251
- // generally available.
2809
+ // NOTE: Claude Mythos 5.2 (`claude-mythos-5-2`, 2026-11-09) is kept commented
2810
+ // out — it's only for organizations verified through Anthropic's verification
2811
+ // programs and unavailable to most users. Re-enable once it's generally
2812
+ // available.
2252
2813
  {
2253
- // Released 2026-09-01 — replaces Fable 5 at the same $10/$50 MTok (cache
2254
- // reads drop to $0.25). Always-on adaptive thinking steered by effort;
2255
- // forced tool use is rejected with a 400, which @prestyj/ai never sends on the
2256
- // Anthropic path. Fable 5 is retired here — a session that still has it
2257
- // saved falls back to the provider default on next start.
2258
- id: "claude-fable-5-1",
2259
- name: "Claude Fable 5.1",
2814
+ // Released 2026-11-09 — replaces Fable 5.1 at $8/$40 MTok (down from
2815
+ // $10/$50; cache reads $0.20). Same API surface as 5.1: always-on adaptive
2816
+ // thinking steered by effort, forced tool use rejected with a 400 (@prestyj/ai
2817
+ // never sends it on the Anthropic path). Fable 5.1 is retired here — a
2818
+ // session that still has it saved falls back to the provider default.
2819
+ id: "claude-fable-5-2",
2820
+ name: "Claude Fable 5.2",
2260
2821
  provider: "anthropic",
2261
2822
  contextWindow: 1e6,
2262
2823
  maxOutputTokens: 128e3,
@@ -2266,12 +2827,28 @@ var MODELS = [
2266
2827
  costTier: "high",
2267
2828
  maxThinkingLevel: "max"
2268
2829
  },
2830
+ {
2831
+ // Fable 5.2 in fast mode: the same model at up to 2.5x output tokens/sec,
2832
+ // $16/$80 MTok. Sent as `claude-fable-5-2` + `speed: "fast"`; on a Claude
2833
+ // subscription it bills usage credits only, like Opus 5.5 Fast.
2834
+ id: "claude-fable-5-2-fast",
2835
+ name: "Claude Fable 5.2 Fast",
2836
+ provider: "anthropic",
2837
+ contextWindow: 1e6,
2838
+ maxOutputTokens: 128e3,
2839
+ supportsThinking: true,
2840
+ supportsImages: true,
2841
+ supportsVideo: false,
2842
+ costTier: "high",
2843
+ maxThinkingLevel: "max",
2844
+ billing: CLAUDE_FABLE_FAST_BILLING
2845
+ },
2269
2846
  // {
2270
2847
  // // Mythos-class model offered through Project Glasswing (limited
2271
- // // availability, invitation-only). Same underlying model as Fable 5.1 with
2272
- // // some safeguards lifted; kept here so approved accounts can select it.
2273
- // id: "claude-mythos-5-1",
2274
- // name: "Claude Mythos 5.1",
2848
+ // // availability, verified organizations only). Same specs and pricing as
2849
+ // // Fable 5.2; kept here so approved accounts can select it.
2850
+ // id: "claude-mythos-5-2",
2851
+ // name: "Claude Mythos 5.2",
2275
2852
  // provider: "anthropic",
2276
2853
  // contextWindow: 1_000_000,
2277
2854
  // maxOutputTokens: 128_000,
@@ -2413,9 +2990,9 @@ var MODELS = [
2413
2990
  billing: CODEX_FAST_BILLING
2414
2991
  },
2415
2992
  // GPT-6 Sol + Luna — released 2026-09-22 below Astra, replacing the whole
2416
- // GPT-5.6 family (Sol/Terra/Luna; there is no GPT-6 Terra — OpenAI's Codex
2993
+ // GPT-5.6 family (Sol/Terra/Luna; there was no GPT-6 Terra — OpenAI's Codex
2417
2994
  // catalog upgrades 5.6 Terra to 6 Sol). GPT-6.1 Sol (2026-09-29) then replaced
2418
- // GPT-6 Sol. Same window split as Astra: 1.05M on the public Responses API,
2995
+ // GPT-6 Sol, and GPT-6.1 Terra (2026-10-26) sits between Sol and Luna. Same window split as Astra: 1.05M on the public Responses API,
2419
2996
  // 272K on the Codex route; 128K output, text+image input, freeform
2420
2997
  // apply_patch, responses-lite transport. The GPT-5.6 ids and `gpt-6-sol` are
2421
2998
  // retired — a saved session on one falls back to the provider default on
@@ -2457,6 +3034,40 @@ var MODELS = [
2457
3034
  maxThinkingLevel: "ultra",
2458
3035
  billing: CODEX_FAST_BILLING
2459
3036
  },
3037
+ {
3038
+ // GPT-6.1 Terra (Codex priority 7, default low, client >= 0.153.0). $1/$5
3039
+ // MTok, cached input $0.05. Unlike Sol/Astra the Codex route gets a 500K
3040
+ // window (catalog `context_window`). Same ladder and Ultra preset as Sol.
3041
+ id: "gpt-6.1-terra",
3042
+ name: "GPT-6.1 Terra",
3043
+ provider: "openai",
3044
+ contextWindow: 105e4,
3045
+ codexContextWindow: 5e5,
3046
+ maxOutputTokens: 128e3,
3047
+ supportsThinking: true,
3048
+ defaultThinkingLevel: "low",
3049
+ supportsImages: true,
3050
+ supportsVideo: false,
3051
+ costTier: "medium",
3052
+ maxThinkingLevel: "ultra"
3053
+ },
3054
+ {
3055
+ // Codex Fast mode for 6.1 Terra ("1.5x speed") — see `gpt-6-astra-fast`
3056
+ // for the wire mapping and billing.
3057
+ id: "gpt-6.1-terra-fast",
3058
+ name: "GPT-6.1 Terra Fast",
3059
+ provider: "openai",
3060
+ contextWindow: 105e4,
3061
+ codexContextWindow: 5e5,
3062
+ maxOutputTokens: 128e3,
3063
+ supportsThinking: true,
3064
+ defaultThinkingLevel: "low",
3065
+ supportsImages: true,
3066
+ supportsVideo: false,
3067
+ costTier: "medium",
3068
+ maxThinkingLevel: "ultra",
3069
+ billing: CODEX_FAST_BILLING
3070
+ },
2460
3071
  {
2461
3072
  // Luna — "Fast and affordable model for easier tasks." (Codex priority 4,
2462
3073
  // default medium, needs a Codex client >= 0.155.0). $0.10/$0.50 MTok.
@@ -2761,6 +3372,23 @@ var MODELS = [
2761
3372
  maxThinkingLevel: "max"
2762
3373
  },
2763
3374
  // ── MiniMax ────────────────────────────────────────────
3375
+ {
3376
+ // The only text model M Plan / Token Plan keys cover; MiniMax-M3 on those
3377
+ // keys fails with "insufficient balance (1008)". Pay-as-you-go serves both.
3378
+ // Always thinks (`thinking: disabled` 400s; omitted = on) with a real
3379
+ // low→max effort ladder on output_config.effort, API default max.
3380
+ id: "MiniMax-M3.1-Flash",
3381
+ name: "MiniMax M3.1 Flash",
3382
+ provider: "minimax",
3383
+ contextWindow: 1e6,
3384
+ maxOutputTokens: 131072,
3385
+ supportsThinking: true,
3386
+ supportsImages: true,
3387
+ supportsVideo: true,
3388
+ maxVideoBytes: 50 * 1024 * 1024,
3389
+ costTier: "low",
3390
+ maxThinkingLevel: "max"
3391
+ },
2764
3392
  {
2765
3393
  id: "MiniMax-M3",
2766
3394
  name: "MiniMax M3",
@@ -2983,15 +3611,51 @@ function clearRuntimeModels(predicate) {
2983
3611
  if (predicate(model)) runtimeModels.delete(id);
2984
3612
  }
2985
3613
  }
3614
+ var providerCatalogs = /* @__PURE__ */ new Map();
3615
+ function setProviderCatalog(provider, models) {
3616
+ if (!models) {
3617
+ providerCatalogs.delete(provider);
3618
+ return [];
3619
+ }
3620
+ const installed = /* @__PURE__ */ new Map();
3621
+ for (const model of models) {
3622
+ if (model.provider !== provider) continue;
3623
+ if (MODELS.some((m) => m.id === model.id && m.provider !== provider)) continue;
3624
+ installed.set(model.id, model);
3625
+ }
3626
+ providerCatalogs.set(provider, installed);
3627
+ return [...installed.values()];
3628
+ }
3629
+ function getProviderCatalog(provider) {
3630
+ const catalog = providerCatalogs.get(provider);
3631
+ return catalog ? [...catalog.values()] : void 0;
3632
+ }
2986
3633
  function getAllModels() {
2987
- return [...MODELS, ...runtimeModels.values()];
3634
+ const synced = [...providerCatalogs.values()].flatMap((c) => [...c.values()]);
3635
+ return [
3636
+ ...MODELS.filter((m) => !providerCatalogs.has(m.provider)),
3637
+ ...synced,
3638
+ ...runtimeModels.values()
3639
+ ];
2988
3640
  }
2989
3641
  function getModel(id) {
2990
- return MODELS.find((m) => m.id === id) ?? runtimeModels.get(id);
3642
+ const fixed = MODELS.find((m) => m.id === id);
3643
+ if (fixed && !providerCatalogs.has(fixed.provider)) return fixed;
3644
+ return findSynced(id) ?? fixed ?? runtimeModels.get(id);
3645
+ }
3646
+ function findSynced(id) {
3647
+ for (const catalog of providerCatalogs.values()) {
3648
+ const hit = catalog.get(id);
3649
+ if (hit) return hit;
3650
+ }
3651
+ return void 0;
2991
3652
  }
2992
3653
  function getModelsForProvider(provider) {
2993
3654
  return getAllModels().filter((m) => m.provider === provider);
2994
3655
  }
3656
+ function getListedModels() {
3657
+ return getAllModels().filter((m) => !isHiddenProvider(m.provider));
3658
+ }
2995
3659
  function isPaidModel(modelId) {
2996
3660
  return getModel(modelId)?.billing?.paid === true;
2997
3661
  }
@@ -3024,7 +3688,7 @@ var DEFAULT_MODEL_IDS = {
3024
3688
  gemini: "gemini-3.1-flash-lite",
3025
3689
  glm: "glm-5.3",
3026
3690
  moonshot: "kimi-k3",
3027
- minimax: "MiniMax-M3",
3691
+ minimax: "MiniMax-M3.1-Flash",
3028
3692
  deepseek: "deepseek-v4-pro",
3029
3693
  huggingface: "moonshotai/Kimi-K2.7-Code",
3030
3694
  openrouter: "qwen/qwen3.8-max",
@@ -3090,6 +3754,59 @@ function getSummaryModel(provider, currentModelId) {
3090
3754
  return tagged ?? getModel(currentModelId) ?? getDefaultModel(provider);
3091
3755
  }
3092
3756
 
3757
+ // src/openrouter-catalog.ts
3758
+ var OPENROUTER_DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
3759
+ var EFFORT_LADDER = ["low", "medium", "high", "xhigh", "max"];
3760
+ function positiveInt(value) {
3761
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
3762
+ }
3763
+ function strings(value) {
3764
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
3765
+ }
3766
+ function costTier(prompt) {
3767
+ const perToken = typeof prompt === "string" ? Number(prompt) : NaN;
3768
+ if (!Number.isFinite(perToken) || perToken < 5e-7) return "low";
3769
+ return perToken < 3e-6 ? "medium" : "high";
3770
+ }
3771
+ function parseOpenRouterCatalog(body) {
3772
+ const data = body?.data;
3773
+ if (!Array.isArray(data)) return { models: [], skipped: 0 };
3774
+ const models = [];
3775
+ let skipped = 0;
3776
+ const seen = /* @__PURE__ */ new Set();
3777
+ for (const raw of data) {
3778
+ const id = typeof raw?.id === "string" ? raw.id.trim() : "";
3779
+ const params = strings(raw?.supported_parameters);
3780
+ const contextWindow = positiveInt(raw?.top_provider?.context_length) ?? positiveInt(raw?.context_length);
3781
+ if (!id || seen.has(id) || !params.includes("tools") || !contextWindow) {
3782
+ skipped++;
3783
+ continue;
3784
+ }
3785
+ seen.add(id);
3786
+ const efforts = strings(raw.reasoning?.supported_efforts);
3787
+ const ladder = EFFORT_LADDER.filter((rung) => efforts.includes(rung));
3788
+ const supportsThinking = ladder.length > 0 || params.includes("reasoning") || params.includes("reasoning_effort");
3789
+ const defaultEffort = raw.reasoning?.default_effort;
3790
+ const maxOutput = positiveInt(raw.top_provider?.max_completion_tokens) ?? Math.min(contextWindow, 16384);
3791
+ models.push({
3792
+ id,
3793
+ name: typeof raw.name === "string" && raw.name.trim() ? raw.name.trim() : id,
3794
+ provider: "openrouter",
3795
+ contextWindow,
3796
+ maxOutputTokens: Math.min(maxOutput, contextWindow),
3797
+ supportsThinking,
3798
+ supportsImages: strings(raw.architecture?.input_modalities).includes("image"),
3799
+ // Video needs a per-transport payload cap the catalog doesn't publish.
3800
+ supportsVideo: false,
3801
+ costTier: costTier(raw.pricing?.prompt),
3802
+ maxThinkingLevel: ladder[ladder.length - 1] ?? "high",
3803
+ ...ladder.length > 0 ? { thinkingLevels: ladder } : {},
3804
+ ...typeof defaultEffort === "string" && ladder.includes(defaultEffort) ? { defaultThinkingLevel: defaultEffort } : {}
3805
+ });
3806
+ }
3807
+ return { models, skipped };
3808
+ }
3809
+
3093
3810
  // src/thinking-level.ts
3094
3811
  var OPENAI_GPT_THINKING_LEVELS = ["medium", "high", "xhigh"];
3095
3812
  var OPENAI_GPT_56_THINKING_LEVELS = [
@@ -3118,6 +3835,13 @@ var ANTHROPIC_ADAPTIVE_THINKING_LEVELS = [
3118
3835
  ];
3119
3836
  var MOONSHOT_K3_THINKING_LEVELS = ["low", "high", "max"];
3120
3837
  var GLM_THINKING_LEVELS = ["low", "medium", "high", "xhigh", "max"];
3838
+ var MINIMAX_EFFORT_THINKING_LEVELS = [
3839
+ "low",
3840
+ "medium",
3841
+ "high",
3842
+ "xhigh",
3843
+ "max"
3844
+ ];
3121
3845
  var LOCAL_THINKING_LEVELS = ["low", "medium", "high", "max"];
3122
3846
  function isOpenAIGptModel(provider, model) {
3123
3847
  return provider === "openai" && model.startsWith("gpt-");
@@ -3134,8 +3858,11 @@ function isMoonshotK3Model(provider, model) {
3134
3858
  function isGlmModel(provider) {
3135
3859
  return provider === "glm";
3136
3860
  }
3861
+ function isMiniMaxEffortModel(provider, model) {
3862
+ return provider === "minimax" && model.startsWith("MiniMax-M3.1");
3863
+ }
3137
3864
  function isAnthropicXhighModel(provider, model) {
3138
- return provider === "anthropic" && /opus-5|opus-4[-.]8|opus-4[-.]7|sonnet-5[-.]5|haiku-5[-.]5/.test(model);
3865
+ return provider === "anthropic" && /fable-5|mythos-5|opus-5|opus-4-8|opus-4-7|sonnet-5[-.]5|haiku-5[-.]5/.test(model);
3139
3866
  }
3140
3867
  function isAnthropicAdaptiveModel(provider, model) {
3141
3868
  return provider === "anthropic" && /opus-5|opus-4[-.]8|opus-4[-.]7|opus-4[-.]6|sonnet-5|haiku-5|fable-5|mythos-5/.test(model);
@@ -3147,6 +3874,8 @@ function getSupportedThinkingLevels(provider, model) {
3147
3874
  const maxIndex2 = LOCAL_THINKING_LEVELS.indexOf(info.maxThinkingLevel);
3148
3875
  return maxIndex2 === -1 ? LOCAL_THINKING_LEVELS.slice(0, 3) : LOCAL_THINKING_LEVELS.slice(0, maxIndex2 + 1);
3149
3876
  }
3877
+ const declared = getModel(model)?.thinkingLevels;
3878
+ if (declared && declared.length > 0) return declared;
3150
3879
  const maxLevel = getMaxThinkingLevel(model);
3151
3880
  if (isAnthropicAdaptiveModel(provider, model)) {
3152
3881
  const levels2 = isAnthropicXhighModel(provider, model) ? ANTHROPIC_XHIGH_THINKING_LEVELS : ANTHROPIC_ADAPTIVE_THINKING_LEVELS;
@@ -3166,6 +3895,7 @@ function getSupportedThinkingLevels(provider, model) {
3166
3895
  }
3167
3896
  if (isMoonshotK3Model(provider, model)) return MOONSHOT_K3_THINKING_LEVELS;
3168
3897
  if (provider === "deepseek") return DEEPSEEK_THINKING_LEVELS;
3898
+ if (isMiniMaxEffortModel(provider, model)) return MINIMAX_EFFORT_THINKING_LEVELS;
3169
3899
  if (isGlmModel(provider)) {
3170
3900
  const maxIndex2 = GLM_THINKING_LEVELS.indexOf(maxLevel);
3171
3901
  if (maxIndex2 === -1) return GLM_THINKING_LEVELS;
@@ -3186,7 +3916,7 @@ function isThinkingLevelSupported(provider, model, level) {
3186
3916
  }
3187
3917
  function getNextThinkingLevel(provider, model, current) {
3188
3918
  const supportedLevels = getSupportedThinkingLevels(provider, model);
3189
- const shouldCycleLevels = isOpenAIGptModel(provider, model) || isAnthropicAdaptiveModel(provider, model) || isSakanaModel(provider) || isXaiModel(provider) || isMoonshotK3Model(provider, model) || isGlmModel(provider) || provider === "deepseek" || // Local servers take a real effort level, not just on/off: Ollama accepts
3919
+ const shouldCycleLevels = isOpenAIGptModel(provider, model) || isAnthropicAdaptiveModel(provider, model) || isSakanaModel(provider) || isXaiModel(provider) || isMoonshotK3Model(provider, model) || isGlmModel(provider) || isMiniMaxEffortModel(provider, model) || provider === "deepseek" || // Local servers take a real effort level, not just on/off: Ollama accepts
3190
3920
  // low/medium/high on `reasoning_effort` (verified against 0.32) and the
3191
3921
  // other OpenAI-compatible servers use the same three. A model that can't
3192
3922
  // reason at all already has no supported levels, so it never gets here.
@@ -3214,11 +3944,12 @@ function clampThinkingForPlanMode(level) {
3214
3944
  }
3215
3945
 
3216
3946
  // src/local-models.ts
3947
+ var import_ai4 = require("@prestyj/ai");
3217
3948
  var DEFAULT_LOCAL_ENDPOINTS = [
3218
3949
  { id: "ollama", label: "Ollama", baseUrl: "http://127.0.0.1:11434/v1", kind: "ollama" }
3219
3950
  ];
3220
3951
  var FALLBACK_CONTEXT_WINDOW = 4096;
3221
- var LOCAL_API_KEY_PLACEHOLDER = "local";
3952
+ var LOCAL_API_KEY_PLACEHOLDER = import_ai4.LOCAL_NO_API_KEY;
3222
3953
  var DEFAULT_PROBE_TIMEOUT_MS = 1200;
3223
3954
  var ENRICH_CONCURRENCY = 6;
3224
3955
  var CACHE_TTL_MS = 3e4;
@@ -3234,6 +3965,9 @@ function parseLocalModelId(id) {
3234
3965
  if (slash <= 0 || slash === rest.length - 1) return void 0;
3235
3966
  return { endpointId: rest.slice(0, slash), rawId: rest.slice(slash + 1) };
3236
3967
  }
3968
+ function localModelShortName(rawId) {
3969
+ return rawId.slice(rawId.lastIndexOf("/") + 1) || rawId;
3970
+ }
3237
3971
  function isLocalModelId(id) {
3238
3972
  return parseLocalModelId(id) !== void 0;
3239
3973
  }
@@ -3244,8 +3978,9 @@ function endpointRoot(baseUrl) {
3244
3978
  return baseUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
3245
3979
  }
3246
3980
  function authHeaders(endpoint) {
3981
+ const key = (0, import_ai4.localBearerKey)(endpoint.apiKey);
3247
3982
  return {
3248
- Authorization: `Bearer ${endpoint.apiKey ?? LOCAL_API_KEY_PLACEHOLDER}`,
3983
+ ...key ? { Authorization: `Bearer ${key}` } : {},
3249
3984
  Accept: "application/json"
3250
3985
  };
3251
3986
  }
@@ -3296,7 +4031,9 @@ async function probeEndpoint(endpoint, { timeoutMs = DEFAULT_PROBE_TIMEOUT_MS, s
3296
4031
  const entries = (list.data ?? []).filter(
3297
4032
  (entry) => typeof entry.id === "string" && entry.id.length > 0 && !NON_CHAT_ID_PATTERN.test(entry.id)
3298
4033
  );
3299
- const models = await enrich(endpoint, entries, { timeoutMs, signal });
4034
+ const enriched = await enrich(endpoint, entries, { timeoutMs, signal });
4035
+ const pinned = contextLength(endpoint.contextLength);
4036
+ const models = pinned === void 0 ? enriched : enriched.map((m) => ({ ...m, contextWindow: pinned, contextWindowKnown: true }));
3300
4037
  log("INFO", "local-models", `Probed ${endpoint.label}`, {
3301
4038
  baseUrl: endpoint.baseUrl,
3302
4039
  models: String(models.length)
@@ -3307,10 +4044,22 @@ async function enrich(endpoint, entries, options) {
3307
4044
  if (endpoint.kind === "lmstudio") return enrichLmStudio(endpoint, entries, options);
3308
4045
  if (endpoint.kind === "ollama") return enrichOllama(endpoint, entries, options);
3309
4046
  if (endpoint.kind === "llamacpp") return enrichLlamaCpp(endpoint, entries, options);
4047
+ if (endpoint.kind === "custom") return enrichCustom(endpoint, entries, options);
3310
4048
  return entries.map((entry) => genericModel(endpoint, entry));
3311
4049
  }
4050
+ async function enrichCustom(endpoint, entries, options) {
4051
+ const generic = entries.map((entry) => genericModel(endpoint, entry));
4052
+ if (generic.every((model) => model.contextWindowKnown)) return generic;
4053
+ const root = endpointRoot(endpoint.baseUrl);
4054
+ const props = await fetchJson(`${root}/props`, endpoint, options);
4055
+ const nCtx = contextLength(props?.default_generation_settings?.n_ctx);
4056
+ if (nCtx !== void 0) return llamaCppModels(endpoint, entries, nCtx);
4057
+ const lmStudio = await fetchJson(`${root}/api/v1/models`, endpoint, options);
4058
+ if (Array.isArray(lmStudio?.models)) return enrichLmStudio(endpoint, entries, options, lmStudio);
4059
+ return generic;
4060
+ }
3312
4061
  function genericModel(endpoint, entry) {
3313
- const declared = contextLength(entry.max_model_len);
4062
+ const declared = contextLength(entry.max_model_len) ?? contextLength(entry.context_length) ?? contextLength(entry.meta?.n_ctx);
3314
4063
  return {
3315
4064
  rawId: entry.id,
3316
4065
  endpointId: endpoint.id,
@@ -3337,9 +4086,7 @@ async function enrichOllama(endpoint, entries, options) {
3337
4086
  });
3338
4087
  const caps = Array.isArray(show?.capabilities) ? show.capabilities : [];
3339
4088
  if (caps.includes("embedding") && !caps.includes("completion")) return void 0;
3340
- const ctx = contextLength(
3341
- runningModels.find((model) => model?.name === entry.id || model?.model === entry.id)?.context_length
3342
- );
4089
+ const ctx = runningContext(runningModels, entry.id) ?? modelfileNumCtx(show?.parameters);
3343
4090
  return {
3344
4091
  rawId: entry.id,
3345
4092
  endpointId: endpoint.id,
@@ -3354,12 +4101,41 @@ async function enrichOllama(endpoint, entries, options) {
3354
4101
  });
3355
4102
  return enriched.filter((model) => model !== void 0);
3356
4103
  }
4104
+ function runningContext(models, rawId) {
4105
+ return contextLength(
4106
+ models.find((model) => model?.name === rawId || model?.model === rawId)?.context_length
4107
+ );
4108
+ }
4109
+ function modelfileNumCtx(parameters) {
4110
+ const match = /^num_ctx\s+(\d+)\s*$/m.exec(parameters ?? "");
4111
+ return match ? contextLength(Number(match[1])) : void 0;
4112
+ }
4113
+ async function ollamaServedContext(endpoint, rawId, {
4114
+ load = false,
4115
+ timeoutMs = 12e4,
4116
+ signal
4117
+ } = {}) {
4118
+ const root = endpointRoot(endpoint.baseUrl);
4119
+ if (load) {
4120
+ await fetchJson(`${root}/api/generate`, endpoint, {
4121
+ timeoutMs,
4122
+ signal,
4123
+ method: "POST",
4124
+ body: { model: rawId }
4125
+ });
4126
+ }
4127
+ const running = await fetchJson(`${root}/api/ps`, endpoint, {
4128
+ timeoutMs: DEFAULT_PROBE_TIMEOUT_MS,
4129
+ signal
4130
+ });
4131
+ return runningContext(Array.isArray(running?.models) ? running.models : [], rawId);
4132
+ }
3357
4133
  function contextLength(value) {
3358
4134
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
3359
4135
  }
3360
- async function enrichLmStudio(endpoint, entries, options) {
4136
+ async function enrichLmStudio(endpoint, entries, options, fetched) {
3361
4137
  const root = endpointRoot(endpoint.baseUrl);
3362
- const detail = await fetchJson(`${root}/api/v1/models`, endpoint, options);
4138
+ const detail = fetched ?? await fetchJson(`${root}/api/v1/models`, endpoint, options);
3363
4139
  const byId = /* @__PURE__ */ new Map();
3364
4140
  if (Array.isArray(detail?.models)) {
3365
4141
  for (const model of detail.models) {
@@ -3417,12 +4193,17 @@ async function enrichLlamaCpp(endpoint, entries, options) {
3417
4193
  endpoint,
3418
4194
  options
3419
4195
  );
3420
- const nCtx = contextLength(props?.default_generation_settings?.n_ctx);
3421
- const known = nCtx !== void 0;
4196
+ return llamaCppModels(
4197
+ endpoint,
4198
+ entries,
4199
+ contextLength(props?.default_generation_settings?.n_ctx)
4200
+ );
4201
+ }
4202
+ function llamaCppModels(endpoint, entries, nCtx) {
3422
4203
  return entries.map((entry) => ({
3423
4204
  ...genericModel(endpoint, entry),
3424
- contextWindow: known ? nCtx : FALLBACK_CONTEXT_WINDOW,
3425
- contextWindowKnown: known
4205
+ contextWindow: nCtx ?? FALLBACK_CONTEXT_WINDOW,
4206
+ contextWindowKnown: nCtx !== void 0
3426
4207
  }));
3427
4208
  }
3428
4209
  async function mapLimited(items, limit, fn) {
@@ -3458,7 +4239,7 @@ function toModelInfo(model, endpoint) {
3458
4239
  }
3459
4240
  var cache;
3460
4241
  function cacheKey(endpoints) {
3461
- return endpoints.map((e) => `${e.id}@${e.baseUrl}`).join("|");
4242
+ return endpoints.map((e) => `${e.id}@${e.baseUrl}#${e.contextLength ?? ""}`).join("|");
3462
4243
  }
3463
4244
  async function discoverLocalModels(endpoints = DEFAULT_LOCAL_ENDPOINTS, options = {}) {
3464
4245
  const key = cacheKey(endpoints);
@@ -3487,18 +4268,122 @@ function findProbedModel(probes, modelId) {
3487
4268
  return void 0;
3488
4269
  }
3489
4270
 
4271
+ // src/claude-code/usage.ts
4272
+ var import_promises6 = __toESM(require("fs/promises"), 1);
4273
+ var import_node_path5 = __toESM(require("path"), 1);
4274
+ var USAGE_FILE = "usage.json";
4275
+ var WINDOWS = {
4276
+ five_hour: { kind: "current", label: "5-hour" },
4277
+ seven_day: { kind: "weekly", label: "Weekly" }
4278
+ };
4279
+ function finite(value) {
4280
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
4281
+ }
4282
+ function toWindow(key, raw) {
4283
+ const shape = WINDOWS[key];
4284
+ const fraction = finite(raw?.utilization);
4285
+ if (!shape || fraction === void 0) return null;
4286
+ const resetsAt = finite(raw?.resetsAt);
4287
+ return {
4288
+ ...shape,
4289
+ usedPercent: Math.min(100, Math.max(0, fraction * 100)),
4290
+ ...resetsAt !== void 0 ? { resetsAt: resetsAt * 1e3 } : {}
4291
+ };
4292
+ }
4293
+ function mergeClaudeCodeRateLimit(info, previous, now = Date.now()) {
4294
+ const reported = info.unifiedWindows ? Object.entries(info.unifiedWindows).map(([key, raw]) => toWindow(key, raw)) : info.rateLimitType ? [toWindow(info.rateLimitType, info)] : [];
4295
+ const byKind = new Map(previous?.windows.map((w) => [w.kind, w]) ?? []);
4296
+ for (const window of reported) if (window) byKind.set(window.kind, window);
4297
+ const windows = [...byKind.values()].sort(
4298
+ (a, b) => a.kind === b.kind ? 0 : a.kind === "current" ? -1 : 1
4299
+ );
4300
+ return { provider: "anthropic", displayName: "Anthropic", windows, fetchedAt: now };
4301
+ }
4302
+ function usagePath(opts) {
4303
+ return import_node_path5.default.join(claudeCodeHome(opts), USAGE_FILE);
4304
+ }
4305
+ async function readClaudeCodeUsage(opts = {}) {
4306
+ let parsed;
4307
+ try {
4308
+ parsed = JSON.parse(await import_promises6.default.readFile(usagePath(opts), "utf8"));
4309
+ } catch {
4310
+ return null;
4311
+ }
4312
+ if (!Array.isArray(parsed?.windows) || typeof parsed.fetchedAt !== "number") return null;
4313
+ const now = opts.now ?? Date.now();
4314
+ const windows = parsed.windows.filter(
4315
+ (w) => (w.kind === "current" || w.kind === "weekly") && typeof w.usedPercent === "number" && (w.resetsAt === void 0 || w.resetsAt > now)
4316
+ );
4317
+ return { provider: "anthropic", displayName: "Anthropic", windows, fetchedAt: parsed.fetchedAt };
4318
+ }
4319
+ var writeQueue = Promise.resolve();
4320
+ function recordClaudeCodeRateLimit(info, opts = {}) {
4321
+ const write = async () => {
4322
+ const now = opts.now ?? Date.now();
4323
+ const next = mergeClaudeCodeRateLimit(info, await readClaudeCodeUsage({ ...opts, now }), now);
4324
+ if (next.windows.length === 0) return;
4325
+ const file = usagePath(opts);
4326
+ await import_promises6.default.mkdir(import_node_path5.default.dirname(file), { recursive: true });
4327
+ await import_promises6.default.writeFile(file, JSON.stringify(next), "utf8");
4328
+ };
4329
+ writeQueue = writeQueue.then(write).catch(() => {
4330
+ });
4331
+ return writeQueue;
4332
+ }
4333
+ async function clearClaudeCodeUsage(opts = {}) {
4334
+ await writeQueue;
4335
+ await import_promises6.default.rm(usagePath(opts), { force: true }).catch(() => {
4336
+ });
4337
+ }
4338
+
4339
+ // src/claude-code/sign-in.ts
4340
+ async function signInWithClaudeCode(auth, callbacks, opts = {}) {
4341
+ if (!opts.binary && !resolveClaudeCodeBinary(opts)) {
4342
+ callbacks.onStatus("Downloading Claude Code (one time)\u2026");
4343
+ await ensureClaudeCodeBinary({
4344
+ ...opts,
4345
+ onProgress: (progress) => {
4346
+ callbacks.onStatus(formatClaudeCodeInstallProgress(progress));
4347
+ opts.onProgress?.(progress);
4348
+ }
4349
+ });
4350
+ }
4351
+ let status = await claudeCodeAuthStatus(opts);
4352
+ if (!status.loggedIn) {
4353
+ callbacks.onStatus("Opening Claude sign-in\u2026");
4354
+ await loginClaudeCode(callbacks, opts);
4355
+ status = await claudeCodeAuthStatus(opts);
4356
+ }
4357
+ if (!status.loggedIn) throw new Error("Claude sign-in didn't finish. Try again.");
4358
+ await auth.setClaudeCodeLogin();
4359
+ return status;
4360
+ }
4361
+ async function signOutOfClaudeCode(auth, opts = {}) {
4362
+ await auth.clearClaudeCodeLogin();
4363
+ await clearClaudeCodeUsage(opts);
4364
+ try {
4365
+ await logoutClaudeCode(opts);
4366
+ } catch (err) {
4367
+ log(
4368
+ "WARN",
4369
+ "auth",
4370
+ `claude auth logout failed: ${err instanceof Error ? err.message : String(err)}`
4371
+ );
4372
+ }
4373
+ }
4374
+
3490
4375
  // src/auth-providers.ts
3491
- var AUTH_PROVIDERS = [
4376
+ var ALL_AUTH_PROVIDERS = [
3492
4377
  {
3493
4378
  value: "anthropic",
3494
4379
  label: "Anthropic",
3495
- description: "Claude Fable 5.1, Opus 5.5, Opus 5.5 Fast, Sonnet 5.5, Haiku 5.5",
4380
+ description: "Claude Fable 5.2, Fable 5.2 Fast, Opus 5.5, Opus 5.5 Fast, Sonnet 5.5, Haiku 5.5",
3496
4381
  methods: ["oauth"]
3497
4382
  },
3498
4383
  {
3499
4384
  value: "openai",
3500
4385
  label: "OpenAI",
3501
- description: "GPT-6 Astra, GPT-6 Astra Fast, GPT-6.1 Sol, GPT-6.1 Sol Fast, GPT-6 Luna, GPT-6 Luna Fast",
4386
+ description: "GPT-6 Astra, GPT-6 Astra Fast, GPT-6.1 Sol, GPT-6.1 Sol Fast, GPT-6.1 Terra, GPT-6.1 Terra Fast, GPT-6 Luna, GPT-6 Luna Fast",
3502
4387
  methods: ["oauth"]
3503
4388
  },
3504
4389
  {
@@ -3579,7 +4464,7 @@ var AUTH_PROVIDERS = [
3579
4464
  {
3580
4465
  value: "minimax",
3581
4466
  label: "MiniMax",
3582
- description: "MiniMax M3",
4467
+ description: "MiniMax M3.1 Flash, M3",
3583
4468
  methods: ["apikey"],
3584
4469
  apiKeyLabel: "MiniMax"
3585
4470
  },
@@ -3632,6 +4517,9 @@ var AUTH_PROVIDERS = [
3632
4517
  apiKeyLabel: "Hugging Face"
3633
4518
  }
3634
4519
  ];
4520
+ var AUTH_PROVIDERS = ALL_AUTH_PROVIDERS.filter(
4521
+ (p) => !isHiddenProvider(p.value)
4522
+ );
3635
4523
  function getAuthProvider(value) {
3636
4524
  return AUTH_PROVIDERS.find((p) => p.value === value);
3637
4525
  }
@@ -4230,11 +5118,11 @@ async function transcribeVoice(fileUrl) {
4230
5118
  }
4231
5119
 
4232
5120
  // src/auto-update.ts
4233
- var import_node_child_process2 = require("child_process");
4234
- var import_node_fs5 = __toESM(require("fs"), 1);
4235
- var import_node_path5 = __toESM(require("path"), 1);
5121
+ var import_node_child_process3 = require("child_process");
5122
+ var import_node_fs6 = __toESM(require("fs"), 1);
5123
+ var import_node_path6 = __toESM(require("path"), 1);
4236
5124
  var CHECK_INTERVAL_MS = 60 * 60 * 1e3;
4237
- var FETCH_TIMEOUT_MS2 = 1e4;
5125
+ var FETCH_TIMEOUT_MS = 1e4;
4238
5126
  function compareVersions(a, b) {
4239
5127
  const pa = a.split(".").map(Number);
4240
5128
  const pb = b.split(".").map(Number);
@@ -4247,7 +5135,7 @@ function compareVersions(a, b) {
4247
5135
  function performUpdateInBackground(command) {
4248
5136
  try {
4249
5137
  const parts = command.split(" ");
4250
- const child = (0, import_node_child_process2.spawn)(parts[0], parts.slice(1), {
5138
+ const child = (0, import_node_child_process3.spawn)(parts[0], parts.slice(1), {
4251
5139
  detached: true,
4252
5140
  stdio: "ignore",
4253
5141
  env: { ...process.env, npm_config_loglevel: "silent" }
@@ -4265,7 +5153,7 @@ function createAutoUpdater(config) {
4265
5153
  }
4266
5154
  function readState() {
4267
5155
  try {
4268
- const raw = import_node_fs5.default.readFileSync(stateFilePath(), "utf-8");
5156
+ const raw = import_node_fs6.default.readFileSync(stateFilePath(), "utf-8");
4269
5157
  return JSON.parse(raw);
4270
5158
  } catch {
4271
5159
  return null;
@@ -4274,8 +5162,8 @@ function createAutoUpdater(config) {
4274
5162
  function writeState(state) {
4275
5163
  try {
4276
5164
  const filePath = stateFilePath();
4277
- import_node_fs5.default.mkdirSync(import_node_path5.default.dirname(filePath), { recursive: true, mode: 448 });
4278
- import_node_fs5.default.writeFileSync(filePath, JSON.stringify(state));
5165
+ import_node_fs6.default.mkdirSync(import_node_path6.default.dirname(filePath), { recursive: true, mode: 448 });
5166
+ import_node_fs6.default.writeFileSync(filePath, JSON.stringify(state));
4279
5167
  } catch {
4280
5168
  }
4281
5169
  }
@@ -4304,7 +5192,7 @@ function createAutoUpdater(config) {
4304
5192
  async function fetchLatestVersion() {
4305
5193
  try {
4306
5194
  const controller = new AbortController();
4307
- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS2);
5195
+ const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
4308
5196
  const response = await fetch(REGISTRY_URL, { signal: controller.signal });
4309
5197
  clearTimeout(timeout);
4310
5198
  const data = await response.json();
@@ -4401,37 +5289,56 @@ function createAutoUpdater(config) {
4401
5289
  0 && (module.exports = {
4402
5290
  AUTH_PROVIDERS,
4403
5291
  AuthStorage,
5292
+ CLAUDE_CODE_AUTH_KEY,
5293
+ CLAUDE_CODE_AUTH_MARKER,
5294
+ CLAUDE_CODE_MANIFEST,
4404
5295
  DEFAULT_LOCAL_ENDPOINTS,
4405
5296
  DEFAULT_MAX_VIDEO_BYTES,
4406
5297
  FALLBACK_CONTEXT_WINDOW,
4407
5298
  GEMINI_API_KEY,
4408
5299
  GEMINI_API_KEY_BASE_URL,
5300
+ HIDDEN_PROVIDERS,
4409
5301
  LOCAL_API_KEY_PLACEHOLDER,
4410
5302
  LOCAL_AUTH_KEY_PREFIX,
5303
+ MINIMAX_CN_BASE_URL,
5304
+ MINIMAX_GLOBAL_BASE_URL,
4411
5305
  MODELS,
4412
5306
  MOONSHOT_OAUTH_KEY,
4413
5307
  NotLoggedInError,
5308
+ OPENROUTER_DEFAULT_BASE_URL,
4414
5309
  PLAN_MODE_THINKING_CAP,
4415
5310
  SubscriptionUsageError,
4416
5311
  TelegramBot,
4417
5312
  XAI_OAUTH_KEY,
4418
5313
  XIAOMI_CREDITS_KEY,
5314
+ XIAOMI_TOKEN_PLAN_BASE_URLS,
4419
5315
  authPriorityNote,
4420
5316
  clampThinkingForPlanMode,
5317
+ claudeCodeAuthStatus,
5318
+ claudeCodeBinaryPath,
5319
+ claudeCodeCallbackUrl,
5320
+ claudeCodeConfigDir,
5321
+ claudeCodeEnv,
5322
+ claudeCodeHome,
5323
+ claudeCodePlatformKey,
5324
+ clearClaudeCodeUsage,
4421
5325
  clearLocalDiscoveryCache,
4422
5326
  clearRuntimeModels,
4423
5327
  closeLogger,
4424
- compareClaudeCodeVersions,
4425
5328
  createAutoUpdater,
4426
5329
  decodeOggOpus,
4427
5330
  describeAuthMethods,
5331
+ detectMiniMaxBaseUrl,
5332
+ detectXiaomiTokenPlanBaseUrl,
4428
5333
  discoverLocalModels,
4429
5334
  downmixToMono,
4430
5335
  dualAuthProvider,
4431
5336
  dualAuthProviderByOAuthKey,
4432
5337
  endpointRoot,
5338
+ ensureClaudeCodeBinary,
4433
5339
  fetchSubscriptionUsage,
4434
5340
  findProbedModel,
5341
+ formatClaudeCodeInstallProgress,
4435
5342
  formatLocalModelId,
4436
5343
  generatePKCE,
4437
5344
  getAllModels,
@@ -4444,11 +5351,13 @@ function createAutoUpdater(config) {
4444
5351
  getContextWindow,
4445
5352
  getDefaultModel,
4446
5353
  getDefaultThinkingLevel,
5354
+ getListedModels,
4447
5355
  getLowestThinkingLevel,
4448
5356
  getMaxThinkingLevel,
4449
5357
  getModel,
4450
5358
  getModelsForProvider,
4451
5359
  getNextThinkingLevel,
5360
+ getProviderCatalog,
4452
5361
  getSessionId,
4453
5362
  getSummaryModel,
4454
5363
  getSupportedThinkingLevels,
@@ -4456,8 +5365,11 @@ function createAutoUpdater(config) {
4456
5365
  getVideoByteLimit,
4457
5366
  grokCliBaseUrl,
4458
5367
  grokCliHeaders,
5368
+ isClaudeCodeAuthMarker,
4459
5369
  isGrokCliEndpoint,
5370
+ isHiddenProvider,
4460
5371
  isKimiCodingEndpoint,
5372
+ isLegacyClaudeOAuth,
4461
5373
  isLocalModelId,
4462
5374
  isLoggerOpen,
4463
5375
  isModelLoaded,
@@ -4466,19 +5378,27 @@ function createAutoUpdater(config) {
4466
5378
  kimiCodeBaseUrl,
4467
5379
  kimiCodingHeaders,
4468
5380
  localAuthStorageKey,
5381
+ localModelShortName,
4469
5382
  log,
4470
5383
  loginAnthropic,
5384
+ loginClaudeCode,
4471
5385
  loginGemini,
4472
5386
  loginKimi,
4473
5387
  loginOpenAI,
4474
5388
  loginXai,
5389
+ logoutClaudeCode,
5390
+ mergeClaudeCodeRateLimit,
4475
5391
  oauthStorageKey,
5392
+ ollamaServedContext,
4476
5393
  openLog,
4477
5394
  parseLocalModelId,
5395
+ parseOpenRouterCatalog,
5396
+ pendingClaudeCodeVersionRefresh,
4478
5397
  probeEndpoint,
4479
5398
  providerStorageKeys,
5399
+ readClaudeCodeUsage,
4480
5400
  readStoredBaseUrlSync,
4481
- recordRequiredClaudeCodeVersion,
5401
+ recordClaudeCodeRateLimit,
4482
5402
  refreshAnthropicToken,
4483
5403
  refreshGeminiToken,
4484
5404
  refreshKimiToken,
@@ -4487,7 +5407,11 @@ function createAutoUpdater(config) {
4487
5407
  registerLogCleanup,
4488
5408
  registerRuntimeModels,
4489
5409
  resample,
5410
+ resolveClaudeCodeBinary,
4490
5411
  setProgressCallback,
5412
+ setProviderCatalog,
5413
+ signInWithClaudeCode,
5414
+ signOutOfClaudeCode,
4491
5415
  toModelInfo,
4492
5416
  transcribeVoice,
4493
5417
  usesOpenAICodexTransport,