@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.
@@ -1,6 +1,6 @@
1
1
  import {
2
2
  getAppPaths
3
- } from "./chunk-W4NHU4UL.js";
3
+ } from "./chunk-DVWS2KEW.js";
4
4
 
5
5
  // src/oauth/kimi.ts
6
6
  import { execFileSync } from "child_process";
@@ -230,9 +230,9 @@ async function refreshKimiToken(refreshToken) {
230
230
  }
231
231
 
232
232
  // src/auth-storage.ts
233
- import fs4 from "fs/promises";
234
- import { readFileSync as readFileSync3 } from "fs";
235
- import crypto5 from "crypto";
233
+ import fs5 from "fs/promises";
234
+ import { readFileSync as readFileSync2 } from "fs";
235
+ import crypto6 from "crypto";
236
236
 
237
237
  // src/oauth/anthropic.ts
238
238
  import crypto2 from "crypto";
@@ -256,347 +256,11 @@ async function generatePKCE() {
256
256
  }
257
257
 
258
258
  // src/claude-code-version.ts
259
- import fs2 from "fs/promises";
260
- import { mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
261
- import path3 from "path";
262
-
263
- // src/logger.ts
264
- import fs from "fs";
265
- import path2 from "path";
266
- import { randomBytes } from "crypto";
267
- import { environmentSecrets, redactText, redactValue } from "@prestyj/ai";
268
- var MAX_BYTES = 10 * 1024 * 1024;
269
- var MIN_HEADROOM_BYTES = 64 * 1024;
270
- var fd = null;
271
- var logPath = null;
272
- var fileBytes = 0;
273
- var processBytes = 0;
274
- var rotationFailed = false;
275
- var capped = false;
276
- var sessionId = "";
277
- var appName = "app";
278
- var cleanups = [];
279
- var exactSecrets = [];
280
- function rotateIfNeeded(filePath, force = false) {
281
- try {
282
- const st = fs.statSync(filePath);
283
- if (!force && st.size <= MAX_BYTES - MIN_HEADROOM_BYTES) return;
284
- const rotated = `${filePath}.1`;
285
- try {
286
- fs.unlinkSync(rotated);
287
- } catch {
288
- }
289
- fs.renameSync(filePath, rotated);
290
- } catch {
291
- }
292
- }
293
- function rotateOpenLog() {
294
- if (fd === null || logPath === null) return false;
295
- const sizeBefore = fileBytes;
296
- try {
297
- fs.closeSync(fd);
298
- } catch {
299
- }
300
- fd = null;
301
- rotateIfNeeded(logPath, true);
302
- try {
303
- fd = fs.openSync(logPath, "a");
304
- fileBytes = fs.fstatSync(fd).size;
305
- } catch {
306
- if (fd !== null) {
307
- try {
308
- fs.closeSync(fd);
309
- } catch {
310
- }
311
- }
312
- fd = null;
313
- capped = true;
314
- return false;
315
- }
316
- if (fileBytes >= sizeBefore) rotationFailed = true;
317
- return true;
318
- }
319
- function openLog(filePath, name) {
320
- if (fd !== null || capped) return false;
321
- appName = name;
322
- exactSecrets = environmentSecrets(process.env);
323
- try {
324
- fs.mkdirSync(path2.dirname(filePath), { recursive: true, mode: 448 });
325
- } catch {
326
- }
327
- rotateIfNeeded(filePath);
328
- try {
329
- fd = fs.openSync(filePath, "a");
330
- } catch {
331
- fd = null;
332
- fileBytes = 0;
333
- return false;
334
- }
335
- try {
336
- fileBytes = fs.fstatSync(fd).size;
337
- } catch {
338
- try {
339
- fs.closeSync(fd);
340
- } catch {
341
- }
342
- fd = null;
343
- fileBytes = 0;
344
- return false;
345
- }
346
- logPath = filePath;
347
- processBytes = 0;
348
- rotationFailed = false;
349
- sessionId = randomBytes(4).toString("hex");
350
- try {
351
- if (fileBytes < MAX_BYTES) {
352
- const written = fs.writeSync(fd, "\n");
353
- fileBytes += written;
354
- processBytes += written;
355
- }
356
- } catch {
357
- }
358
- return true;
359
- }
360
- function getSessionId() {
361
- return sessionId;
362
- }
363
- function isLoggerOpen() {
364
- return fd !== null;
365
- }
366
- function log(level, category, message, data) {
367
- if (fd === null) return;
368
- const ts = (/* @__PURE__ */ new Date()).toISOString();
369
- const safeMessage = redactText(message, { secrets: exactSecrets });
370
- let line = `[${ts}] [sid=${sessionId}] [${level}] [${category}] ${safeMessage}`;
371
- if (data) {
372
- const safeData = redactValue(data, { secrets: exactSecrets });
373
- const pairs = Object.entries(safeData).map(([k, v]) => {
374
- if (typeof v === "string") return `${k}=${v}`;
375
- if (typeof v === "bigint") return `${k}=${String(v)}`;
376
- return `${k}=${JSON.stringify(v)}`;
377
- }).join(" ");
378
- if (pairs) line += ` ${pairs}`;
379
- }
380
- line += "\n";
381
- const lineBytes = Buffer.byteLength(line);
382
- if (processBytes + lineBytes > MAX_BYTES) {
383
- const capLine = `[${ts}] [sid=${sessionId}] [WARN] [logger] Log cap reached; file logging disabled until restart
384
- `;
385
- try {
386
- if (fileBytes + Buffer.byteLength(capLine) <= MAX_BYTES) {
387
- fileBytes += fs.writeSync(fd, capLine);
388
- }
389
- fs.closeSync(fd);
390
- } catch {
391
- }
392
- fd = null;
393
- capped = true;
394
- return;
395
- }
396
- if (fileBytes + lineBytes > MAX_BYTES && !rotationFailed && !rotateOpenLog()) return;
397
- if (fd === null) return;
398
- try {
399
- const written = fs.writeSync(fd, line);
400
- fileBytes += written;
401
- processBytes += written;
402
- } catch {
403
- }
404
- }
405
- function registerLogCleanup(fn) {
406
- cleanups.push(fn);
407
- }
408
- function closeLogger(opts) {
409
- if (fd !== null) {
410
- if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName} shutting down`);
411
- try {
412
- if (fd !== null) fs.closeSync(fd);
413
- } catch {
414
- }
415
- }
416
- fd = null;
417
- logPath = null;
418
- fileBytes = 0;
419
- processBytes = 0;
420
- rotationFailed = false;
421
- capped = false;
422
- exactSecrets = [];
423
- for (const unsub of cleanups) unsub();
424
- cleanups = [];
425
- }
426
-
427
- // src/claude-code-version.ts
428
- var NPM_LATEST_URL = "https://registry.npmjs.org/@anthropic-ai/claude-code/latest";
429
- var CACHE_FRESH_MS = 60 * 60 * 1e3;
430
- var CACHE_HARD_MS = 24 * 60 * 60 * 1e3;
431
- var FETCH_TIMEOUT_MS = 3e3;
432
- var FALLBACK_VERSION = "2.1.280";
433
- var memoryCache = null;
434
- var inflight = null;
435
- var backgroundRefresh = null;
436
- var versionFloor = null;
437
- function cachePath() {
438
- return path3.join(getAppPaths().agentDir, "claude-code-version.json");
439
- }
440
- function compareClaudeCodeVersions(a, b) {
441
- const parse = (v) => v.split(".").map((part) => Number.parseInt(part, 10)).map((n) => Number.isFinite(n) ? n : 0);
442
- const left = parse(a);
443
- const right = parse(b);
444
- for (let i = 0; i < Math.max(left.length, right.length); i += 1) {
445
- const diff = (left[i] ?? 0) - (right[i] ?? 0);
446
- if (diff !== 0) return diff;
447
- }
448
- return 0;
449
- }
450
- function applyFloor(version) {
451
- if (!versionFloor) return version;
452
- return compareClaudeCodeVersions(versionFloor, version) > 0 ? versionFloor : version;
453
- }
454
- async function readDiskCache() {
455
- try {
456
- const raw = await fs2.readFile(cachePath(), "utf-8");
457
- const parsed = JSON.parse(raw);
458
- if (typeof parsed.version === "string" && typeof parsed.fetchedAt === "number") {
459
- if (typeof parsed.minVersion === "string") {
460
- if (!versionFloor || compareClaudeCodeVersions(parsed.minVersion, versionFloor) > 0) {
461
- versionFloor = parsed.minVersion;
462
- }
463
- }
464
- return parsed;
465
- }
466
- return null;
467
- } catch {
468
- return null;
469
- }
470
- }
471
- async function writeDiskCache(data) {
472
- try {
473
- await fs2.mkdir(getAppPaths().agentDir, { recursive: true, mode: 448 });
474
- await fs2.writeFile(
475
- cachePath(),
476
- JSON.stringify({ ...data, ...versionFloor ? { minVersion: versionFloor } : {} }),
477
- { mode: 384 }
478
- );
479
- } catch (err) {
480
- log(
481
- "WARN",
482
- "claude-code-version",
483
- `Failed to write cache: ${err instanceof Error ? err.message : String(err)}`
484
- );
485
- }
486
- }
487
- async function fetchLatest() {
488
- const controller = new AbortController();
489
- const timer = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);
490
- try {
491
- const response = await fetch(NPM_LATEST_URL, { signal: controller.signal });
492
- if (!response.ok) return null;
493
- const data = await response.json();
494
- if (typeof data.version === "string" && /^\d/.test(data.version)) {
495
- return data.version;
496
- }
497
- return null;
498
- } catch {
499
- return null;
500
- } finally {
501
- clearTimeout(timer);
502
- }
503
- }
504
- function refreshInBackground() {
505
- if (backgroundRefresh) return;
506
- backgroundRefresh = (async () => {
507
- const fetched = await fetchLatest();
508
- if (fetched) {
509
- await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
510
- memoryCache = { version: applyFloor(fetched), expiresAt: Date.now() + CACHE_FRESH_MS };
511
- }
512
- })().catch(() => {
513
- }).finally(() => {
514
- backgroundRefresh = null;
515
- });
516
- }
517
- async function getClaudeCodeVersion() {
518
- if (memoryCache && Date.now() < memoryCache.expiresAt) {
519
- return memoryCache.version;
520
- }
521
- if (inflight) return inflight;
522
- inflight = (async () => {
523
- const disk = await readDiskCache();
524
- const age = disk ? Date.now() - disk.fetchedAt : Infinity;
525
- if (disk && age < CACHE_FRESH_MS) {
526
- const version = applyFloor(disk.version);
527
- memoryCache = { version, expiresAt: Date.now() + CACHE_FRESH_MS };
528
- return version;
529
- }
530
- if (disk && age < CACHE_HARD_MS) {
531
- const version = applyFloor(disk.version);
532
- memoryCache = { version, expiresAt: Date.now() + 5 * 60 * 1e3 };
533
- refreshInBackground();
534
- return version;
535
- }
536
- const fetched = await fetchLatest();
537
- if (fetched) {
538
- await writeDiskCache({ version: fetched, fetchedAt: Date.now() });
539
- const version = applyFloor(fetched);
540
- memoryCache = { version, expiresAt: Date.now() + CACHE_FRESH_MS };
541
- return version;
542
- }
543
- const resolved = applyFloor(disk?.version ?? FALLBACK_VERSION);
544
- memoryCache = { version: resolved, expiresAt: Date.now() + 5 * 60 * 1e3 };
545
- log(
546
- "WARN",
547
- "claude-code-version",
548
- `Failed to fetch latest Claude Code version; using ${resolved}`
549
- );
550
- return resolved;
551
- })();
552
- try {
553
- return await inflight;
554
- } finally {
555
- inflight = null;
556
- }
557
- }
558
- var REQUIRED_VERSION_PATTERN = /version\s+(\d+(?:\.\d+)+)\s+or\s+newer\s+is\s+required/i;
559
- function recordRequiredClaudeCodeVersion(message) {
560
- const required = REQUIRED_VERSION_PATTERN.exec(message ?? "")?.[1];
561
- if (!required) return null;
562
- if (versionFloor && compareClaudeCodeVersions(required, versionFloor) <= 0) return versionFloor;
563
- versionFloor = required;
564
- memoryCache = null;
565
- log(
566
- "WARN",
567
- "claude-code-version",
568
- `Provider requires Claude Code >= ${required}; pinning User-Agent floor`
569
- );
570
- try {
571
- const dir = getAppPaths().agentDir;
572
- mkdirSync2(dir, { recursive: true, mode: 448 });
573
- let existing = {};
574
- try {
575
- existing = JSON.parse(readFileSync2(cachePath(), "utf-8"));
576
- } catch {
577
- }
578
- writeFileSync2(
579
- cachePath(),
580
- JSON.stringify({
581
- version: existing.version ?? required,
582
- fetchedAt: existing.fetchedAt ?? 0,
583
- minVersion: required
584
- }),
585
- { mode: 384 }
586
- );
587
- } catch (err) {
588
- log(
589
- "WARN",
590
- "claude-code-version",
591
- `Failed to persist required version: ${err instanceof Error ? err.message : String(err)}`
592
- );
593
- }
594
- return required;
595
- }
596
- async function getClaudeCliUserAgent() {
597
- const version = await getClaudeCodeVersion();
598
- return `claude-cli/${version} (external, cli)`;
599
- }
259
+ import {
260
+ getClaudeCodeVersion,
261
+ getClaudeCliUserAgent,
262
+ pendingClaudeCodeVersionRefresh
263
+ } from "@prestyj/ai";
600
264
 
601
265
  // src/oauth/anthropic.ts
602
266
  var CLIENT_ID2 = atob("OWQxYzI1MGEtZTYxYi00NGQ5LTg4ZWQtNTk0NGQxOTYyZjVl");
@@ -1284,7 +948,7 @@ var DEFAULT_CLIENT_ID2 = "b1a00492-073a-47ea-816f-4c329264a828";
1284
948
  var DEFAULT_ISSUER = "https://auth.x.ai";
1285
949
  var DEFAULT_CLI_BASE_URL = "https://cli-chat-proxy.grok.com/v1";
1286
950
  var OAUTH_SCOPE = "openid profile email offline_access grok-cli:access api:access";
1287
- var DEFAULT_GROK_CLI_VERSION = "0.2.101";
951
+ var DEFAULT_GROK_CLI_VERSION = "1.0.67";
1288
952
  var DEVICE_TIMEOUT_FALLBACK_MS = 10 * 60 * 1e3;
1289
953
  var DEFAULT_TOKEN_LIFETIME_SECONDS = 3600;
1290
954
  function issuer() {
@@ -1408,136 +1072,915 @@ async function requestDeviceAuthorization2() {
1408
1072
  expiresInMs: (Number(data.expires_in) || 0) > 0 ? Number(data.expires_in) * 1e3 : DEVICE_TIMEOUT_FALLBACK_MS
1409
1073
  };
1410
1074
  }
1411
- async function pollDeviceToken2(deviceCode) {
1412
- const { status, data } = await postForm2("/oauth2/token", {
1413
- client_id: clientId(),
1414
- device_code: deviceCode,
1415
- grant_type: "urn:ietf:params:oauth:grant-type:device_code"
1416
- });
1417
- if (status === 200 && typeof data.access_token === "string") {
1418
- return { kind: "success", creds: credsFromTokenResponse2(data) };
1075
+ async function pollDeviceToken2(deviceCode) {
1076
+ const { status, data } = await postForm2("/oauth2/token", {
1077
+ client_id: clientId(),
1078
+ device_code: deviceCode,
1079
+ grant_type: "urn:ietf:params:oauth:grant-type:device_code"
1080
+ });
1081
+ if (status === 200 && typeof data.access_token === "string") {
1082
+ return { kind: "success", creds: credsFromTokenResponse2(data) };
1083
+ }
1084
+ if (status >= 500) {
1085
+ throw new Error(`Grok token polling server error (${status}): ${errorDetail2(data)}`);
1086
+ }
1087
+ const errorCode = typeof data.error === "string" ? data.error : "unknown_error";
1088
+ switch (errorCode) {
1089
+ case "authorization_pending":
1090
+ return { kind: "pending" };
1091
+ case "slow_down":
1092
+ return { kind: "slow_down" };
1093
+ case "expired_token":
1094
+ return { kind: "expired" };
1095
+ case "access_denied":
1096
+ return { kind: "denied" };
1097
+ default:
1098
+ throw new Error(`Grok token polling failed (${status}): ${errorDetail2(data)}`);
1099
+ }
1100
+ }
1101
+ function sleep2(ms) {
1102
+ return new Promise((resolve) => {
1103
+ setTimeout(resolve, ms);
1104
+ });
1105
+ }
1106
+ async function loginXai(callbacks) {
1107
+ const auth = await requestDeviceAuthorization2();
1108
+ callbacks.onStatus(
1109
+ `Visit ${auth.verificationUri || auth.verificationUriComplete} and enter code: ${auth.userCode}`
1110
+ );
1111
+ callbacks.onOpenUrl(auth.verificationUriComplete || auth.verificationUri);
1112
+ callbacks.onStatus("Waiting for you to authorize in the browser...");
1113
+ const deadline = Date.now() + auth.expiresInMs;
1114
+ let interval = Math.max(auth.interval, 1);
1115
+ while (Date.now() < deadline) {
1116
+ const remaining = deadline - Date.now();
1117
+ await sleep2(Math.min(interval * 1e3, remaining));
1118
+ const result = await pollDeviceToken2(auth.deviceCode);
1119
+ if (result.kind === "success") return result.creds;
1120
+ if (result.kind === "denied") {
1121
+ throw new Error("Grok authorization was denied.");
1122
+ }
1123
+ if (result.kind === "expired") {
1124
+ throw new Error("Grok device code expired. Please run login again.");
1125
+ }
1126
+ if (result.kind === "slow_down") {
1127
+ interval += 5;
1128
+ }
1129
+ }
1130
+ throw new Error("Grok login timed out. Please run login again.");
1131
+ }
1132
+ async function refreshXaiToken(refreshToken) {
1133
+ const { status, data } = await postForm2("/oauth2/token", {
1134
+ client_id: clientId(),
1135
+ grant_type: "refresh_token",
1136
+ refresh_token: refreshToken
1137
+ });
1138
+ if (status === 200 && typeof data.access_token === "string") {
1139
+ return credsFromTokenResponse2(data, { fallbackRefreshToken: refreshToken });
1140
+ }
1141
+ const errorCode = typeof data.error === "string" ? data.error : "";
1142
+ throw new Error(`Grok token refresh failed (${status}): ${errorCode || errorDetail2(data)}`);
1143
+ }
1144
+
1145
+ // src/file-lock.ts
1146
+ import fs from "fs/promises";
1147
+ import { setTimeout as setTimeout2 } from "timers/promises";
1148
+ var STALE_TIMEOUT_MS = 1e4;
1149
+ var RETRY_INTERVAL_MS = 50;
1150
+ var MAX_WAIT_MS = 5e3;
1151
+ var PENDING_DELETE_CODES = /* @__PURE__ */ new Set(["EACCES", "EBUSY", "EPERM"]);
1152
+ async function withFileLock(filePath, fn) {
1153
+ const lockPath = filePath + ".lock";
1154
+ await acquireLock(lockPath);
1155
+ try {
1156
+ return await fn();
1157
+ } finally {
1158
+ await releaseLock(lockPath);
1159
+ }
1160
+ }
1161
+ async function acquireLock(lockPath) {
1162
+ const startTime = Date.now();
1163
+ let refusedWithoutLock = 0;
1164
+ while (true) {
1165
+ try {
1166
+ const info = { pid: process.pid, timestamp: Date.now() };
1167
+ await fs.writeFile(lockPath, JSON.stringify(info), { flag: "wx" });
1168
+ return;
1169
+ } catch (err) {
1170
+ const code = err.code;
1171
+ if (code !== "EEXIST") {
1172
+ if (process.platform !== "win32" || !code || !PENDING_DELETE_CODES.has(code)) throw err;
1173
+ const lockPresent = await lockFileExists(lockPath);
1174
+ if (!lockPresent && ++refusedWithoutLock > 3) throw err;
1175
+ if (Date.now() - startTime > MAX_WAIT_MS) throw err;
1176
+ await setTimeout2(RETRY_INTERVAL_MS);
1177
+ continue;
1178
+ }
1179
+ try {
1180
+ const content = await fs.readFile(lockPath, "utf-8");
1181
+ const info = JSON.parse(content);
1182
+ const isProcessAlive = isAlive(info.pid);
1183
+ const isStale = Date.now() - info.timestamp > STALE_TIMEOUT_MS;
1184
+ if (!isProcessAlive || isStale) {
1185
+ await fs.unlink(lockPath).catch(() => {
1186
+ });
1187
+ continue;
1188
+ }
1189
+ } catch {
1190
+ const stat = await fs.stat(lockPath).catch(() => null);
1191
+ if (!stat) continue;
1192
+ if (Date.now() - stat.mtimeMs > STALE_TIMEOUT_MS) {
1193
+ await fs.unlink(lockPath).catch(() => {
1194
+ });
1195
+ continue;
1196
+ }
1197
+ }
1198
+ if (Date.now() - startTime > MAX_WAIT_MS) {
1199
+ await fs.unlink(lockPath).catch(() => {
1200
+ });
1201
+ continue;
1202
+ }
1203
+ await setTimeout2(RETRY_INTERVAL_MS);
1204
+ }
1205
+ }
1206
+ }
1207
+ async function lockFileExists(lockPath) {
1208
+ try {
1209
+ await fs.stat(lockPath);
1210
+ return true;
1211
+ } catch (err) {
1212
+ return err.code !== "ENOENT";
1213
+ }
1214
+ }
1215
+ async function releaseLock(lockPath) {
1216
+ await fs.unlink(lockPath).catch(() => {
1217
+ });
1218
+ }
1219
+ function isAlive(pid) {
1220
+ try {
1221
+ process.kill(pid, 0);
1222
+ return true;
1223
+ } catch (err) {
1224
+ if (err.code === "EPERM") return true;
1225
+ return false;
1226
+ }
1227
+ }
1228
+
1229
+ // src/logger.ts
1230
+ import fs2 from "fs";
1231
+ import path2 from "path";
1232
+ import { randomBytes } from "crypto";
1233
+ import { environmentSecrets, redactText, redactValue } from "@prestyj/ai";
1234
+ var MAX_BYTES = 10 * 1024 * 1024;
1235
+ var MIN_HEADROOM_BYTES = 64 * 1024;
1236
+ var fd = null;
1237
+ var logPath = null;
1238
+ var fileBytes = 0;
1239
+ var processBytes = 0;
1240
+ var rotationFailed = false;
1241
+ var capped = false;
1242
+ var sessionId = "";
1243
+ var appName = "app";
1244
+ var cleanups = [];
1245
+ var exactSecrets = [];
1246
+ function rotateIfNeeded(filePath, force = false) {
1247
+ try {
1248
+ const st = fs2.statSync(filePath);
1249
+ if (!force && st.size <= MAX_BYTES - MIN_HEADROOM_BYTES) return;
1250
+ const rotated = `${filePath}.1`;
1251
+ try {
1252
+ fs2.unlinkSync(rotated);
1253
+ } catch {
1254
+ }
1255
+ fs2.renameSync(filePath, rotated);
1256
+ } catch {
1257
+ }
1258
+ }
1259
+ function rotateOpenLog() {
1260
+ if (fd === null || logPath === null) return false;
1261
+ const sizeBefore = fileBytes;
1262
+ try {
1263
+ fs2.closeSync(fd);
1264
+ } catch {
1265
+ }
1266
+ fd = null;
1267
+ rotateIfNeeded(logPath, true);
1268
+ try {
1269
+ fd = fs2.openSync(logPath, "a");
1270
+ fileBytes = fs2.fstatSync(fd).size;
1271
+ } catch {
1272
+ if (fd !== null) {
1273
+ try {
1274
+ fs2.closeSync(fd);
1275
+ } catch {
1276
+ }
1277
+ }
1278
+ fd = null;
1279
+ capped = true;
1280
+ return false;
1281
+ }
1282
+ if (fileBytes >= sizeBefore) rotationFailed = true;
1283
+ return true;
1284
+ }
1285
+ function openLog(filePath, name) {
1286
+ if (fd !== null || capped) return false;
1287
+ appName = name;
1288
+ exactSecrets = environmentSecrets(process.env);
1289
+ try {
1290
+ fs2.mkdirSync(path2.dirname(filePath), { recursive: true, mode: 448 });
1291
+ } catch {
1292
+ }
1293
+ rotateIfNeeded(filePath);
1294
+ try {
1295
+ fd = fs2.openSync(filePath, "a");
1296
+ } catch {
1297
+ fd = null;
1298
+ fileBytes = 0;
1299
+ return false;
1300
+ }
1301
+ try {
1302
+ fileBytes = fs2.fstatSync(fd).size;
1303
+ } catch {
1304
+ try {
1305
+ fs2.closeSync(fd);
1306
+ } catch {
1307
+ }
1308
+ fd = null;
1309
+ fileBytes = 0;
1310
+ return false;
1311
+ }
1312
+ logPath = filePath;
1313
+ processBytes = 0;
1314
+ rotationFailed = false;
1315
+ sessionId = randomBytes(4).toString("hex");
1316
+ try {
1317
+ if (fileBytes < MAX_BYTES) {
1318
+ const written = fs2.writeSync(fd, "\n");
1319
+ fileBytes += written;
1320
+ processBytes += written;
1321
+ }
1322
+ } catch {
1323
+ }
1324
+ return true;
1325
+ }
1326
+ function getSessionId() {
1327
+ return sessionId;
1328
+ }
1329
+ function isLoggerOpen() {
1330
+ return fd !== null;
1331
+ }
1332
+ function log(level, category, message, data) {
1333
+ if (fd === null) return;
1334
+ const ts = (/* @__PURE__ */ new Date()).toISOString();
1335
+ const safeMessage = redactText(message, { secrets: exactSecrets });
1336
+ let line = `[${ts}] [sid=${sessionId}] [${level}] [${category}] ${safeMessage}`;
1337
+ if (data) {
1338
+ const safeData = redactValue(data, { secrets: exactSecrets });
1339
+ const pairs = Object.entries(safeData).map(([k, v]) => {
1340
+ if (typeof v === "string") return `${k}=${v}`;
1341
+ if (typeof v === "bigint") return `${k}=${String(v)}`;
1342
+ return `${k}=${JSON.stringify(v)}`;
1343
+ }).join(" ");
1344
+ if (pairs) line += ` ${pairs}`;
1345
+ }
1346
+ line += "\n";
1347
+ const lineBytes = Buffer.byteLength(line);
1348
+ if (processBytes + lineBytes > MAX_BYTES) {
1349
+ const capLine = `[${ts}] [sid=${sessionId}] [WARN] [logger] Log cap reached; file logging disabled until restart
1350
+ `;
1351
+ try {
1352
+ if (fileBytes + Buffer.byteLength(capLine) <= MAX_BYTES) {
1353
+ fileBytes += fs2.writeSync(fd, capLine);
1354
+ }
1355
+ fs2.closeSync(fd);
1356
+ } catch {
1357
+ }
1358
+ fd = null;
1359
+ capped = true;
1360
+ return;
1361
+ }
1362
+ if (fileBytes + lineBytes > MAX_BYTES && !rotationFailed && !rotateOpenLog()) return;
1363
+ if (fd === null) return;
1364
+ try {
1365
+ const written = fs2.writeSync(fd, line);
1366
+ fileBytes += written;
1367
+ processBytes += written;
1368
+ } catch {
1369
+ }
1370
+ }
1371
+ function registerLogCleanup(fn) {
1372
+ cleanups.push(fn);
1373
+ }
1374
+ function closeLogger(opts) {
1375
+ if (fd !== null) {
1376
+ if (opts?.shutdownLine !== false) log("INFO", "shutdown", `${appName} shutting down`);
1377
+ try {
1378
+ if (fd !== null) fs2.closeSync(fd);
1379
+ } catch {
1380
+ }
1381
+ }
1382
+ fd = null;
1383
+ logPath = null;
1384
+ fileBytes = 0;
1385
+ processBytes = 0;
1386
+ rotationFailed = false;
1387
+ capped = false;
1388
+ exactSecrets = [];
1389
+ for (const unsub of cleanups) unsub();
1390
+ cleanups = [];
1391
+ }
1392
+
1393
+ // src/hidden-providers.ts
1394
+ var HIDDEN_PROVIDERS = ["gemini"];
1395
+ function isHiddenProvider(provider) {
1396
+ return HIDDEN_PROVIDERS.includes(provider);
1397
+ }
1398
+
1399
+ // src/claude-code/runtime.ts
1400
+ import { spawn } from "child_process";
1401
+ import crypto5 from "crypto";
1402
+ import fs4 from "fs";
1403
+ import fsp2 from "fs/promises";
1404
+ import path3 from "path";
1405
+
1406
+ // src/claude-code/tar.ts
1407
+ import fs3 from "fs";
1408
+ import fsp from "fs/promises";
1409
+ import zlib from "zlib";
1410
+ var BLOCK = 512;
1411
+ function readString(buf, offset, length) {
1412
+ const end = buf.indexOf(0, offset);
1413
+ return buf.toString("utf8", offset, end === -1 || end > offset + length ? offset + length : end);
1414
+ }
1415
+ function readSize(buf, offset) {
1416
+ if (buf[offset] & 128) {
1417
+ let value = buf[offset] & 127;
1418
+ for (let i = 1; i < 12; i++) value = value * 256 + buf[offset + i];
1419
+ return value;
1420
+ }
1421
+ const text = readString(buf, offset, 12).trim();
1422
+ return text ? parseInt(text, 8) : 0;
1423
+ }
1424
+ function paxPath(data) {
1425
+ let pos = 0;
1426
+ while (pos < data.length) {
1427
+ const space = data.indexOf(32, pos);
1428
+ if (space === -1) break;
1429
+ const len = parseInt(data.toString("utf8", pos, space), 10);
1430
+ if (!Number.isFinite(len) || len <= 0) break;
1431
+ const record = data.toString("utf8", space + 1, pos + len - 1);
1432
+ const eq = record.indexOf("=");
1433
+ if (eq !== -1 && record.slice(0, eq) === "path") return record.slice(eq + 1);
1434
+ pos += len;
1435
+ }
1436
+ return void 0;
1437
+ }
1438
+ async function extractFileFromTarGz(tgzPath, entryName, destPath) {
1439
+ const input = fs3.createReadStream(tgzPath).pipe(zlib.createGunzip());
1440
+ let pending = Buffer.alloc(0);
1441
+ let remaining = 0;
1442
+ let padding = 0;
1443
+ let kind = "skip";
1444
+ let meta = [];
1445
+ let overridePath;
1446
+ let out;
1447
+ let found = false;
1448
+ try {
1449
+ for await (const chunk of input) {
1450
+ pending = pending.length ? Buffer.concat([pending, chunk]) : chunk;
1451
+ let pos = 0;
1452
+ while (pos < pending.length) {
1453
+ if (remaining > 0) {
1454
+ const take = Math.min(remaining, pending.length - pos);
1455
+ const slice = pending.subarray(pos, pos + take);
1456
+ if (kind === "target") await out.write(slice);
1457
+ else if (kind === "pax" || kind === "longname") meta.push(Buffer.from(slice));
1458
+ pos += take;
1459
+ remaining -= take;
1460
+ if (remaining === 0) {
1461
+ if (kind === "target") {
1462
+ await out.close();
1463
+ out = void 0;
1464
+ found = true;
1465
+ } else if (kind === "pax") {
1466
+ overridePath = paxPath(Buffer.concat(meta)) ?? overridePath;
1467
+ } else if (kind === "longname") {
1468
+ overridePath = readString(Buffer.concat(meta), 0, Number.MAX_SAFE_INTEGER);
1469
+ }
1470
+ }
1471
+ continue;
1472
+ }
1473
+ if (padding > 0) {
1474
+ const skip = Math.min(padding, pending.length - pos);
1475
+ pos += skip;
1476
+ padding -= skip;
1477
+ continue;
1478
+ }
1479
+ if (found) break;
1480
+ if (pending.length - pos < BLOCK) break;
1481
+ const header = pending.subarray(pos, pos + BLOCK);
1482
+ pos += BLOCK;
1483
+ if (header.every((b) => b === 0)) continue;
1484
+ const size = readSize(header, 124);
1485
+ const type2 = String.fromCharCode(header[156] || 48);
1486
+ let name = readString(header, 0, 100);
1487
+ if (readString(header, 257, 6) === "ustar") {
1488
+ const prefix = readString(header, 345, 155);
1489
+ if (prefix) name = `${prefix}/${name}`;
1490
+ }
1491
+ remaining = size;
1492
+ padding = (BLOCK - size % BLOCK) % BLOCK;
1493
+ meta = [];
1494
+ if (type2 === "x") kind = "pax";
1495
+ else if (type2 === "L") kind = "longname";
1496
+ else {
1497
+ const path4 = overridePath ?? name;
1498
+ overridePath = void 0;
1499
+ if ((type2 === "0" || type2 === "\0" || type2 === "7") && path4 === entryName) {
1500
+ kind = "target";
1501
+ out = await fsp.open(destPath, "w", 493);
1502
+ if (size === 0) {
1503
+ await out.close();
1504
+ out = void 0;
1505
+ found = true;
1506
+ }
1507
+ } else {
1508
+ kind = "skip";
1509
+ }
1510
+ }
1511
+ }
1512
+ pending = pos < pending.length ? Buffer.from(pending.subarray(pos)) : Buffer.alloc(0);
1513
+ if (found) break;
1514
+ }
1515
+ if (!found && out) throw new Error(`Archive ended inside ${entryName}`);
1516
+ return found;
1517
+ } finally {
1518
+ if (out) await out.close().catch(() => {
1519
+ });
1520
+ input.destroy();
1521
+ }
1522
+ }
1523
+
1524
+ // src/claude-code/manifest.json
1525
+ var manifest_default = {
1526
+ sdkVersion: "0.3.318",
1527
+ claudeCodeVersion: "2.1.318",
1528
+ platforms: {
1529
+ "darwin-arm64": {
1530
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-arm64/-/claude-agent-sdk-darwin-arm64-0.3.318.tgz",
1531
+ integrity: "sha512-AWoXeDXzAMD3RaA21lWuHvCrKd8xmbTTmKjovninn4j07jheoVSMzFbCFjpp4kk5TdhT36JtWPkAxvjNMbcO8w==",
1532
+ bin: "claude"
1533
+ },
1534
+ "darwin-x64": {
1535
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-darwin-x64/-/claude-agent-sdk-darwin-x64-0.3.318.tgz",
1536
+ integrity: "sha512-6CkZ5PCdebSY/LePp16sf/HYRtM6zVuxtn8qYICFS5KUZFsjccJJ9swVsOdHXNHi4SWZcSmIFTwoUbfFCzisRw==",
1537
+ bin: "claude"
1538
+ },
1539
+ "linux-arm64": {
1540
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64/-/claude-agent-sdk-linux-arm64-0.3.318.tgz",
1541
+ integrity: "sha512-mBm4su17aMitLBBCQj3bHdejyUDY6z/ormGih+HG24N689RSbdKECjGjkT87tDBIR/4jyoqmuSeHqM1DI8TJlg==",
1542
+ bin: "claude"
1543
+ },
1544
+ "linux-arm64-musl": {
1545
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-arm64-musl/-/claude-agent-sdk-linux-arm64-musl-0.3.318.tgz",
1546
+ integrity: "sha512-l4LSYFOrvlYCrUImGfxMTQ0wg+T3s9CBhrBvPF/0oJGKZg+QnxHHU8jUVm9e9/xYmDRTtqFIrr4id/5AfH4XGw==",
1547
+ bin: "claude"
1548
+ },
1549
+ "linux-x64": {
1550
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64/-/claude-agent-sdk-linux-x64-0.3.318.tgz",
1551
+ integrity: "sha512-+mE+ueBD3oRFdaG16rd0h+LMjdeivGxL0pr/+FZK7JeLWVu+yPSw/f/X02b9oK36/DWykiFTu2G6HnJ9/+YO6w==",
1552
+ bin: "claude"
1553
+ },
1554
+ "linux-x64-musl": {
1555
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-linux-x64-musl/-/claude-agent-sdk-linux-x64-musl-0.3.318.tgz",
1556
+ integrity: "sha512-SAF3lj/2OzTU84p+OOA13QEKA9+5fYAw0M9E7AJjdnRmVFGqQfbV7Do1i1f9Sj0mIubB3rLTRphGRw8O4HZjgA==",
1557
+ bin: "claude"
1558
+ },
1559
+ "win32-arm64": {
1560
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-arm64/-/claude-agent-sdk-win32-arm64-0.3.318.tgz",
1561
+ integrity: "sha512-19iVSZ4379QbZU1XnGUtfFvhKS1WzS8H1sbU/DbrzqbJ5Kq1eB1drj+obB1fCxTh6m26tRPj0zMJmdeu/jk3Gw==",
1562
+ bin: "claude.exe"
1563
+ },
1564
+ "win32-x64": {
1565
+ url: "https://registry.npmjs.org/@anthropic-ai/claude-agent-sdk-win32-x64/-/claude-agent-sdk-win32-x64-0.3.318.tgz",
1566
+ integrity: "sha512-ZdKVWpyVNVt0cXrOf8sUBaxcxLEAP+oGMdQDLBWr/BqOxTWLy7TBWOj1kzw+wVg/9WIkjkgQWeJzGXPWulR1sA==",
1567
+ bin: "claude.exe"
1568
+ }
1569
+ }
1570
+ };
1571
+
1572
+ // src/claude-code/runtime.ts
1573
+ var CLAUDE_CODE_MANIFEST = manifest_default;
1574
+ var CLAUDE_CODE_AUTH_KEY = "anthropic-claude-code";
1575
+ var CLAUDE_CODE_AUTH_MARKER = { via: "claude-code" };
1576
+ function isClaudeCodeAuthMarker(value) {
1577
+ return value?.via === CLAUDE_CODE_AUTH_MARKER.via;
1578
+ }
1579
+ function isLegacyClaudeOAuth(value) {
1580
+ const token = value?.accessToken;
1581
+ return typeof token === "string" && token.startsWith("sk-ant-oat");
1582
+ }
1583
+ function isMusl() {
1584
+ if (process.platform !== "linux") return false;
1585
+ const report = typeof process.report?.getReport === "function" ? process.report.getReport() : null;
1586
+ return report != null && report.header?.glibcVersionRuntime === void 0;
1587
+ }
1588
+ function claudeCodePlatformKey(info = { platform: process.platform, arch: process.arch, musl: isMusl() }) {
1589
+ const arch2 = info.arch === "arm64" || info.arch === "x64" ? info.arch : null;
1590
+ if (!arch2) return null;
1591
+ if (info.platform === "darwin" || info.platform === "win32") return `${info.platform}-${arch2}`;
1592
+ if (info.platform === "linux") return `linux-${arch2}${info.musl ? "-musl" : ""}`;
1593
+ return null;
1594
+ }
1595
+ function resolveAsset(opts) {
1596
+ const manifest = opts.manifest ?? CLAUDE_CODE_MANIFEST;
1597
+ const key = opts.platformKey ?? claudeCodePlatformKey();
1598
+ const asset = key ? manifest.platforms[key] : void 0;
1599
+ if (!asset) {
1600
+ throw new Error(
1601
+ `Claude Code isn't available for ${process.platform}-${process.arch}. Use an Anthropic API key instead.`
1602
+ );
1603
+ }
1604
+ return { manifest, asset };
1605
+ }
1606
+ function claudeCodeHome(opts = {}) {
1607
+ return opts.home ?? getAppPaths().claudeCodeDir;
1608
+ }
1609
+ function claudeCodeConfigDir(opts = {}) {
1610
+ return opts.home ? path3.join(opts.home, "config") : getAppPaths().claudeCodeConfigDir;
1611
+ }
1612
+ function claudeCodeBinaryPath(opts = {}) {
1613
+ const { manifest, asset } = resolveAsset(opts);
1614
+ return path3.join(claudeCodeHome(opts), manifest.claudeCodeVersion, asset.bin);
1615
+ }
1616
+ function resolveClaudeCodeBinary(opts = {}) {
1617
+ let binary;
1618
+ try {
1619
+ binary = claudeCodeBinaryPath(opts);
1620
+ } catch {
1621
+ return null;
1622
+ }
1623
+ try {
1624
+ return fs4.statSync(binary).isFile() ? binary : null;
1625
+ } catch {
1626
+ return null;
1627
+ }
1628
+ }
1629
+ var installs = /* @__PURE__ */ new Map();
1630
+ async function ensureClaudeCodeBinary(opts = {}) {
1631
+ const existing = resolveClaudeCodeBinary(opts);
1632
+ if (existing) return existing;
1633
+ const target = claudeCodeBinaryPath(opts);
1634
+ let install = installs.get(target);
1635
+ if (!install) {
1636
+ install = installClaudeCode(opts).finally(() => installs.delete(target));
1637
+ installs.set(target, install);
1638
+ }
1639
+ return install;
1640
+ }
1641
+ async function installClaudeCode(opts) {
1642
+ const { manifest, asset } = resolveAsset(opts);
1643
+ const home = claudeCodeHome(opts);
1644
+ const versionDir = path3.join(home, manifest.claudeCodeVersion);
1645
+ const binary = path3.join(versionDir, asset.bin);
1646
+ await fsp2.mkdir(home, { recursive: true });
1647
+ const tag = `${process.pid}-${crypto5.randomBytes(4).toString("hex")}`;
1648
+ const tarball = path3.join(home, `.download-${tag}.tgz`);
1649
+ const staging = path3.join(home, `.staging-${tag}`);
1650
+ try {
1651
+ await download(asset, tarball, opts);
1652
+ opts.onProgress?.({ phase: "extract" });
1653
+ await fsp2.mkdir(staging, { recursive: true });
1654
+ const found = await extractFileFromTarGz(
1655
+ tarball,
1656
+ `package/${asset.bin}`,
1657
+ path3.join(staging, asset.bin)
1658
+ );
1659
+ if (!found) throw new Error(`The Claude Code download has no ${asset.bin} binary.`);
1660
+ await fsp2.chmod(path3.join(staging, asset.bin), 493);
1661
+ try {
1662
+ await fsp2.rename(staging, versionDir);
1663
+ } catch (err) {
1664
+ if (!fs4.existsSync(binary)) throw err;
1665
+ }
1666
+ await removeOldVersions(home, manifest.claudeCodeVersion);
1667
+ return binary;
1668
+ } finally {
1669
+ await fsp2.rm(tarball, { force: true }).catch(() => {
1670
+ });
1671
+ await fsp2.rm(staging, { recursive: true, force: true }).catch(() => {
1672
+ });
1673
+ }
1674
+ }
1675
+ async function download(asset, dest, opts) {
1676
+ const doFetch = opts.fetch ?? fetch;
1677
+ const res = await doFetch(asset.url, { signal: opts.signal });
1678
+ if (!res.ok || !res.body) {
1679
+ throw new Error(`Claude Code download failed (HTTP ${res.status}).`);
1419
1680
  }
1420
- if (status >= 500) {
1421
- throw new Error(`Grok token polling server error (${status}): ${errorDetail2(data)}`);
1681
+ const totalBytes = Number(res.headers.get("content-length")) || void 0;
1682
+ const hash = crypto5.createHash("sha512");
1683
+ const out = await fsp2.open(dest, "w");
1684
+ let receivedBytes = 0;
1685
+ let lastReported = -1;
1686
+ try {
1687
+ opts.onProgress?.({ phase: "download", receivedBytes, totalBytes });
1688
+ for await (const chunk of res.body) {
1689
+ if (opts.signal?.aborted) throw opts.signal.reason ?? new Error("Download cancelled.");
1690
+ hash.update(chunk);
1691
+ await out.write(chunk);
1692
+ receivedBytes += chunk.byteLength;
1693
+ const step = totalBytes ? Math.floor(receivedBytes / totalBytes * 100) : Math.floor(receivedBytes / 4194304);
1694
+ if (step !== lastReported) {
1695
+ lastReported = step;
1696
+ opts.onProgress?.({ phase: "download", receivedBytes, totalBytes });
1697
+ }
1698
+ }
1699
+ } finally {
1700
+ await out.close();
1422
1701
  }
1423
- const errorCode = typeof data.error === "string" ? data.error : "unknown_error";
1424
- switch (errorCode) {
1425
- case "authorization_pending":
1426
- return { kind: "pending" };
1427
- case "slow_down":
1428
- return { kind: "slow_down" };
1429
- case "expired_token":
1430
- return { kind: "expired" };
1431
- case "access_denied":
1432
- return { kind: "denied" };
1433
- default:
1434
- throw new Error(`Grok token polling failed (${status}): ${errorDetail2(data)}`);
1702
+ opts.onProgress?.({ phase: "verify" });
1703
+ const expected = asset.integrity.replace(/^sha512-/, "");
1704
+ if (hash.digest("base64") !== expected) {
1705
+ throw new Error(
1706
+ "The Claude Code download didn't match its pinned checksum, so it was discarded."
1707
+ );
1435
1708
  }
1436
1709
  }
1437
- function sleep2(ms) {
1438
- return new Promise((resolve) => {
1439
- setTimeout(resolve, ms);
1710
+ async function removeOldVersions(home, keep) {
1711
+ let entries;
1712
+ try {
1713
+ entries = await fsp2.readdir(home, { withFileTypes: true });
1714
+ } catch {
1715
+ return;
1716
+ }
1717
+ for (const entry of entries) {
1718
+ if (!entry.isDirectory() || entry.name === keep || entry.name === "config") continue;
1719
+ if (!/^\d+\.\d+\.\d+/.test(entry.name)) continue;
1720
+ await fsp2.rm(path3.join(home, entry.name), { recursive: true, force: true }).catch(() => {
1721
+ });
1722
+ }
1723
+ }
1724
+ function formatClaudeCodeInstallProgress(progress) {
1725
+ if (progress.phase === "verify") return "Checking the Claude Code download\u2026";
1726
+ if (progress.phase === "extract") return "Unpacking Claude Code\u2026";
1727
+ const mb = (bytes) => Math.round(bytes / 1048576);
1728
+ if (!progress.totalBytes) return `Downloading Claude Code\u2026 ${mb(progress.receivedBytes)} MB`;
1729
+ const pct = Math.floor(progress.receivedBytes / progress.totalBytes * 100);
1730
+ return `Downloading Claude Code\u2026 ${pct}% (${mb(progress.receivedBytes)} of ${mb(progress.totalBytes)} MB)`;
1731
+ }
1732
+ var STRIPPED_ENV = [
1733
+ "ANTHROPIC_API_KEY",
1734
+ "ANTHROPIC_AUTH_TOKEN",
1735
+ "ANTHROPIC_BASE_URL",
1736
+ "CLAUDE_CODE_OAUTH_TOKEN",
1737
+ "CLAUDE_CODE_OAUTH_REFRESH_TOKEN",
1738
+ "CLAUDE_CODE_USE_BEDROCK",
1739
+ "CLAUDE_CODE_USE_VERTEX",
1740
+ "CLAUDE_CODE_USE_FOUNDRY",
1741
+ "NODE_OPTIONS"
1742
+ ];
1743
+ function claudeCodeEnv(opts = {}, base = process.env) {
1744
+ const env = {};
1745
+ for (const [key, value] of Object.entries(base)) {
1746
+ if (value !== void 0 && !STRIPPED_ENV.includes(key)) env[key] = value;
1747
+ }
1748
+ env.CLAUDE_CONFIG_DIR = claudeCodeConfigDir(opts);
1749
+ env.DISABLE_AUTOUPDATER = "1";
1750
+ return env;
1751
+ }
1752
+ function runCommand(opts) {
1753
+ if (opts.binary) return { command: opts.binary, prefix: opts.binaryArgs ?? [] };
1754
+ const binary = resolveClaudeCodeBinary(opts);
1755
+ if (!binary) throw new Error("Claude Code isn't installed yet. Sign in with Claude first.");
1756
+ return { command: binary, prefix: [] };
1757
+ }
1758
+ function runClaude(args, opts) {
1759
+ const { command, prefix } = runCommand(opts);
1760
+ return new Promise((resolve, reject) => {
1761
+ const child = spawn(command, [...prefix, ...args], {
1762
+ env: claudeCodeEnv(opts),
1763
+ stdio: ["ignore", "pipe", "pipe"],
1764
+ windowsHide: true,
1765
+ signal: opts.signal
1766
+ });
1767
+ let stdout = "";
1768
+ let stderr = "";
1769
+ child.stdout.on("data", (d) => stdout += d.toString());
1770
+ child.stderr.on("data", (d) => stderr += d.toString());
1771
+ child.on("error", reject);
1772
+ child.on("close", (code) => resolve({ code, stdout, stderr }));
1440
1773
  });
1441
1774
  }
1442
- async function loginXai(callbacks) {
1443
- const auth = await requestDeviceAuthorization2();
1444
- callbacks.onStatus(
1445
- `Visit ${auth.verificationUri || auth.verificationUriComplete} and enter code: ${auth.userCode}`
1446
- );
1447
- callbacks.onOpenUrl(auth.verificationUriComplete || auth.verificationUri);
1448
- callbacks.onStatus("Waiting for you to authorize in the browser...");
1449
- const deadline = Date.now() + auth.expiresInMs;
1450
- let interval = Math.max(auth.interval, 1);
1451
- while (Date.now() < deadline) {
1452
- const remaining = deadline - Date.now();
1453
- await sleep2(Math.min(interval * 1e3, remaining));
1454
- const result = await pollDeviceToken2(auth.deviceCode);
1455
- if (result.kind === "success") return result.creds;
1456
- if (result.kind === "denied") {
1457
- throw new Error("Grok authorization was denied.");
1458
- }
1459
- if (result.kind === "expired") {
1460
- throw new Error("Grok device code expired. Please run login again.");
1461
- }
1462
- if (result.kind === "slow_down") {
1463
- interval += 5;
1464
- }
1775
+ async function claudeCodeAuthStatus(opts = {}) {
1776
+ if (!opts.binary && !resolveClaudeCodeBinary(opts)) return { loggedIn: false };
1777
+ const { stdout } = await runClaude(["auth", "status", "--json"], opts);
1778
+ try {
1779
+ const parsed = JSON.parse(stdout);
1780
+ return {
1781
+ loggedIn: parsed.loggedIn === true,
1782
+ ...typeof parsed.authMethod === "string" ? { authMethod: parsed.authMethod } : {},
1783
+ ...typeof parsed.email === "string" ? { email: parsed.email } : {},
1784
+ ...typeof parsed.subscriptionType === "string" ? { subscriptionType: parsed.subscriptionType } : {}
1785
+ };
1786
+ } catch {
1787
+ return { loggedIn: false };
1465
1788
  }
1466
- throw new Error("Grok login timed out. Please run login again.");
1467
1789
  }
1468
- async function refreshXaiToken(refreshToken) {
1469
- const { status, data } = await postForm2("/oauth2/token", {
1470
- client_id: clientId(),
1471
- grant_type: "refresh_token",
1472
- refresh_token: refreshToken
1473
- });
1474
- if (status === 200 && typeof data.access_token === "string") {
1475
- return credsFromTokenResponse2(data, { fallbackRefreshToken: refreshToken });
1790
+ async function logoutClaudeCode(opts = {}) {
1791
+ if (!opts.binary && !resolveClaudeCodeBinary(opts)) return;
1792
+ const { code, stderr } = await runClaude(["auth", "logout"], opts);
1793
+ if (code !== 0) throw new Error(stderr.trim() || `claude auth logout exited with ${code}`);
1794
+ }
1795
+ var OPEN_URL_HOOK = `const arg = String(process.argv[1] || "");
1796
+ const file = process.env.EZ_CLAUDE_CODE_URL_FILE;
1797
+ if (file && /https?:/.test(arg)) {
1798
+ require("node:fs").appendFileSync(file, arg + "\\n");
1799
+ process.exit(0);
1800
+ }
1801
+ `;
1802
+ var CAPTURE_WAIT_MS = 3e3;
1803
+ function stripAnsi(text) {
1804
+ return text.replace(/\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)|\x1b\[[0-9;?]*[A-Za-z]/g, "");
1805
+ }
1806
+ function claudeCodeCallbackUrl(manualUrl, captured) {
1807
+ const port = /localhost(?::|%3A)(\d{2,5})(?:\/|%2F)callback/i.exec(captured)?.[1];
1808
+ if (!port) return null;
1809
+ try {
1810
+ const url = new URL(manualUrl);
1811
+ url.searchParams.set("redirect_uri", `http://localhost:${port}/callback`);
1812
+ return url.toString();
1813
+ } catch {
1814
+ return null;
1476
1815
  }
1477
- const errorCode = typeof data.error === "string" ? data.error : "";
1478
- throw new Error(`Grok token refresh failed (${status}): ${errorCode || errorDetail2(data)}`);
1479
1816
  }
1480
-
1481
- // src/file-lock.ts
1482
- import fs3 from "fs/promises";
1483
- import { setTimeout as setTimeout2 } from "timers/promises";
1484
- var STALE_TIMEOUT_MS = 1e4;
1485
- var RETRY_INTERVAL_MS = 50;
1486
- var MAX_WAIT_MS = 5e3;
1487
- async function withFileLock(filePath, fn) {
1488
- const lockPath = filePath + ".lock";
1489
- await acquireLock(lockPath);
1817
+ async function loginClaudeCode(callbacks, opts = {}) {
1818
+ const { command, prefix } = runCommand(opts);
1819
+ const home = claudeCodeHome(opts);
1820
+ await fsp2.mkdir(claudeCodeConfigDir(opts), { recursive: true });
1821
+ const tag = `${process.pid}-${crypto5.randomBytes(4).toString("hex")}`;
1822
+ const hookFile = path3.join(home, `.open-url-${tag}.cjs`);
1823
+ const urlFile = path3.join(home, `.open-url-${tag}.txt`);
1824
+ await fsp2.writeFile(hookFile, OPEN_URL_HOOK);
1825
+ const env = {
1826
+ ...claudeCodeEnv(opts),
1827
+ BROWSER: process.execPath,
1828
+ NODE_OPTIONS: `--require ${JSON.stringify(hookFile)}`,
1829
+ EZ_CLAUDE_CODE_URL_FILE: urlFile
1830
+ };
1831
+ const promptAbort = new AbortController();
1832
+ let timer;
1490
1833
  try {
1491
- return await fn();
1834
+ await new Promise((resolve, reject) => {
1835
+ const child = spawn(command, [...prefix, "auth", "login", "--claudeai"], {
1836
+ env,
1837
+ stdio: ["pipe", "pipe", "pipe"],
1838
+ windowsHide: true
1839
+ });
1840
+ let stdout = "";
1841
+ let stderr = "";
1842
+ let manualUrl = null;
1843
+ let opened = false;
1844
+ const onAbort = () => child.kill();
1845
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
1846
+ const open = (url, needsCode) => {
1847
+ if (opened) return;
1848
+ opened = true;
1849
+ clearInterval(timer);
1850
+ callbacks.onOpenUrl(url);
1851
+ callbacks.onStatus("Finish signing in to Claude in your browser\u2026");
1852
+ if (!needsCode) return;
1853
+ void callbacks.onPromptCode("Paste the code shown after signing in to Claude:", promptAbort.signal).then((code) => {
1854
+ const trimmed = code.trim();
1855
+ if (trimmed && !child.stdin.destroyed) child.stdin.write(`${trimmed}
1856
+ `);
1857
+ }).catch(() => {
1858
+ });
1859
+ };
1860
+ child.stdout.on("data", (d) => {
1861
+ stdout += d.toString();
1862
+ if (manualUrl) return;
1863
+ const match = /visit:\s*(https:\/\/\S+)/.exec(stripAnsi(stdout));
1864
+ if (!match) return;
1865
+ manualUrl = match[1];
1866
+ const started = Date.now();
1867
+ timer = setInterval(() => {
1868
+ let captured = "";
1869
+ try {
1870
+ captured = fs4.readFileSync(urlFile, "utf8");
1871
+ } catch {
1872
+ }
1873
+ const callbackUrl = captured ? claudeCodeCallbackUrl(manualUrl, captured) : null;
1874
+ if (callbackUrl) open(callbackUrl, false);
1875
+ else if (Date.now() - started > (opts.browserWaitMs ?? CAPTURE_WAIT_MS))
1876
+ open(manualUrl, true);
1877
+ }, 100);
1878
+ });
1879
+ child.stderr.on("data", (d) => stderr += d.toString());
1880
+ child.on("error", reject);
1881
+ child.on("close", (code) => {
1882
+ opts.signal?.removeEventListener("abort", onAbort);
1883
+ if (opts.signal?.aborted) reject(new Error("Sign-in cancelled."));
1884
+ else if (code === 0) resolve();
1885
+ else {
1886
+ const detail = stripAnsi(stderr).trim().split("\n").pop()?.trim();
1887
+ reject(new Error(detail || `Claude sign-in failed (exit ${code}).`));
1888
+ }
1889
+ });
1890
+ });
1492
1891
  } finally {
1493
- await releaseLock(lockPath);
1892
+ clearInterval(timer);
1893
+ promptAbort.abort();
1894
+ await fsp2.rm(hookFile, { force: true }).catch(() => {
1895
+ });
1896
+ await fsp2.rm(urlFile, { force: true }).catch(() => {
1897
+ });
1494
1898
  }
1495
1899
  }
1496
- async function acquireLock(lockPath) {
1497
- const startTime = Date.now();
1498
- while (true) {
1900
+
1901
+ // src/auth-storage.ts
1902
+ import { LOCAL_NO_API_KEY } from "@prestyj/ai";
1903
+
1904
+ // src/minimax-region.ts
1905
+ var MINIMAX_GLOBAL_BASE_URL = "https://api.minimax.io/anthropic";
1906
+ var MINIMAX_CN_BASE_URL = "https://api.minimax.cn/anthropic";
1907
+ var REGION_HOSTS = [
1908
+ { host: "https://api.minimax.io", baseUrl: MINIMAX_GLOBAL_BASE_URL },
1909
+ { host: "https://api.minimax.cn", baseUrl: MINIMAX_CN_BASE_URL }
1910
+ ];
1911
+ var KEY_KNOWN_CODES = /* @__PURE__ */ new Set([0, 2062]);
1912
+ var KEY_REJECTED_CODES = /* @__PURE__ */ new Set([1004, 2049]);
1913
+ async function probeRegion(host, apiKey, fetchImpl, timeoutMs) {
1914
+ const url = apiKey.startsWith("sk-api-") ? `${host}/account/query_balance` : `${host}/v1/token_plan/remains`;
1915
+ let sawRejection = false;
1916
+ const authHeaders = [
1917
+ { Authorization: `Bearer ${apiKey}` },
1918
+ { "x-api-key": apiKey }
1919
+ ];
1920
+ for (const auth of authHeaders) {
1921
+ let res;
1499
1922
  try {
1500
- const info = { pid: process.pid, timestamp: Date.now() };
1501
- await fs3.writeFile(lockPath, JSON.stringify(info), { flag: "wx" });
1502
- return;
1503
- } catch (err) {
1504
- if (err.code !== "EEXIST") throw err;
1505
- try {
1506
- const content = await fs3.readFile(lockPath, "utf-8");
1507
- const info = JSON.parse(content);
1508
- const isProcessAlive = isAlive(info.pid);
1509
- const isStale = Date.now() - info.timestamp > STALE_TIMEOUT_MS;
1510
- if (!isProcessAlive || isStale) {
1511
- await fs3.unlink(lockPath).catch(() => {
1512
- });
1513
- continue;
1514
- }
1515
- } catch {
1516
- await fs3.unlink(lockPath).catch(() => {
1517
- });
1518
- continue;
1519
- }
1520
- if (Date.now() - startTime > MAX_WAIT_MS) {
1521
- await fs3.unlink(lockPath).catch(() => {
1522
- });
1523
- continue;
1524
- }
1525
- await setTimeout2(RETRY_INTERVAL_MS);
1923
+ res = await fetchImpl(url, {
1924
+ headers: { ...auth, "Content-Type": "application/json" },
1925
+ signal: AbortSignal.timeout(timeoutMs)
1926
+ });
1927
+ } catch {
1928
+ return "inconclusive";
1929
+ }
1930
+ if (res.status === 401 || res.status === 403) {
1931
+ sawRejection = true;
1932
+ continue;
1933
+ }
1934
+ if (!res.ok) return "inconclusive";
1935
+ let code;
1936
+ try {
1937
+ code = (await res.json()).base_resp?.status_code;
1938
+ } catch {
1939
+ return "inconclusive";
1526
1940
  }
1941
+ if (typeof code === "number" && KEY_KNOWN_CODES.has(code)) return "authorized";
1942
+ if (typeof code === "number" && KEY_REJECTED_CODES.has(code)) {
1943
+ sawRejection = true;
1944
+ continue;
1945
+ }
1946
+ return "inconclusive";
1527
1947
  }
1948
+ return sawRejection ? "unauthorized" : "inconclusive";
1528
1949
  }
1529
- async function releaseLock(lockPath) {
1530
- await fs3.unlink(lockPath).catch(() => {
1531
- });
1950
+ async function detectMiniMaxBaseUrl(apiKey, options = {}) {
1951
+ const fetchImpl = options.fetch ?? fetch;
1952
+ const timeoutMs = options.timeoutMs ?? 5e3;
1953
+ const results = await Promise.all(
1954
+ REGION_HOSTS.map((r) => probeRegion(r.host, apiKey, fetchImpl, timeoutMs))
1955
+ );
1956
+ const index = results.indexOf("authorized");
1957
+ return index === -1 ? void 0 : REGION_HOSTS[index].baseUrl;
1532
1958
  }
1533
- function isAlive(pid) {
1534
- try {
1535
- process.kill(pid, 0);
1536
- return true;
1537
- } catch (err) {
1538
- if (err.code === "EPERM") return true;
1539
- return false;
1540
- }
1959
+
1960
+ // src/xiaomi-region.ts
1961
+ var XIAOMI_TOKEN_PLAN_BASE_URLS = [
1962
+ "https://token-plan-sgp.xiaomimimo.com/v1",
1963
+ "https://token-plan-ams.xiaomimimo.com/v1",
1964
+ "https://token-plan-cn.xiaomimimo.com/v1"
1965
+ ];
1966
+ async function detectXiaomiTokenPlanBaseUrl(apiKey, options = {}) {
1967
+ const fetchImpl = options.fetch ?? fetch;
1968
+ const timeoutMs = options.timeoutMs ?? 5e3;
1969
+ const accepted = await Promise.all(
1970
+ XIAOMI_TOKEN_PLAN_BASE_URLS.map(async (baseUrl) => {
1971
+ try {
1972
+ const res = await fetchImpl(`${baseUrl}/models`, {
1973
+ headers: { Authorization: `Bearer ${apiKey}` },
1974
+ signal: AbortSignal.timeout(timeoutMs)
1975
+ });
1976
+ return res.ok;
1977
+ } catch {
1978
+ return false;
1979
+ }
1980
+ })
1981
+ );
1982
+ const index = accepted.indexOf(true);
1983
+ return index === -1 ? void 0 : XIAOMI_TOKEN_PLAN_BASE_URLS[index];
1541
1984
  }
1542
1985
 
1543
1986
  // src/auth-storage.ts
@@ -1590,9 +2033,18 @@ function activeBaseUrlEntry(data, provider) {
1590
2033
  }
1591
2034
  return data[provider];
1592
2035
  }
2036
+ var MINIMAX_REGION_RETRY_MS = 5 * 60 * 1e3;
2037
+ var miniMaxRegionProbes = /* @__PURE__ */ new Map();
2038
+ function cachedMiniMaxRegion(apiKey) {
2039
+ const cached = miniMaxRegionProbes.get(apiKey);
2040
+ if (cached && Date.now() - cached.at < MINIMAX_REGION_RETRY_MS) return cached.result;
2041
+ const result = detectMiniMaxBaseUrl(apiKey).catch(() => void 0);
2042
+ miniMaxRegionProbes.set(apiKey, { at: Date.now(), result });
2043
+ return result;
2044
+ }
1593
2045
  function readStoredBaseUrlSync(authFile, provider) {
1594
2046
  try {
1595
- const data = JSON.parse(readFileSync3(authFile, "utf-8"));
2047
+ const data = JSON.parse(readFileSync2(authFile, "utf-8"));
1596
2048
  return activeBaseUrlEntry(data, provider)?.baseUrl;
1597
2049
  } catch {
1598
2050
  return void 0;
@@ -1636,8 +2088,12 @@ var AuthStorage = class {
1636
2088
  snapshotIno = 0;
1637
2089
  /** Per-provider lock to serialize concurrent refresh calls. */
1638
2090
  refreshLocks = /* @__PURE__ */ new Map();
1639
- constructor(filePath) {
2091
+ detectMiniMaxRegion;
2092
+ detectXiaomiCluster;
2093
+ constructor(filePath, options) {
1640
2094
  this.filePath = filePath ?? getAppPaths().authFile;
2095
+ this.detectMiniMaxRegion = options?.detectMiniMaxBaseUrl ?? cachedMiniMaxRegion;
2096
+ this.detectXiaomiCluster = options?.detectXiaomiTokenPlanBaseUrl ?? detectXiaomiTokenPlanBaseUrl;
1641
2097
  }
1642
2098
  /** Path to the on-disk auth file. Useful for status output. */
1643
2099
  get path() {
@@ -1670,6 +2126,7 @@ var AuthStorage = class {
1670
2126
  * satisfies it.
1671
2127
  */
1672
2128
  async hasProviderAuth(provider) {
2129
+ if (isHiddenProvider(provider)) return false;
1673
2130
  await this.ensureFresh();
1674
2131
  const dual = dualAuthProvider(provider);
1675
2132
  if (dual) {
@@ -1681,11 +2138,28 @@ var AuthStorage = class {
1681
2138
  if (provider === "gemini") {
1682
2139
  return Boolean(this.data["gemini"] || this.data[GEMINI_API_KEY]);
1683
2140
  }
2141
+ if (provider === "anthropic" && isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY])) {
2142
+ return true;
2143
+ }
1684
2144
  if (provider === "local") {
1685
2145
  return Object.keys(this.data).some((key) => key.startsWith(LOCAL_AUTH_KEY_PREFIX));
1686
2146
  }
1687
2147
  return Boolean(this.data[provider]);
1688
2148
  }
2149
+ /** True when the user signed in with Claude through Claude Code (marker only, no token). */
2150
+ async hasClaudeCodeLogin() {
2151
+ await this.ensureFresh();
2152
+ return isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY]);
2153
+ }
2154
+ /** Record a Claude Code sign-in. Claude Code keeps the token; auth.json gets only the marker. */
2155
+ async setClaudeCodeLogin() {
2156
+ await this.mutateLatest((latest) => {
2157
+ latest[CLAUDE_CODE_AUTH_KEY] = { ...CLAUDE_CODE_AUTH_MARKER };
2158
+ });
2159
+ }
2160
+ async clearClaudeCodeLogin() {
2161
+ await this.clearCredentials(CLAUDE_CODE_AUTH_KEY);
2162
+ }
1689
2163
  /** Endpoint ids that currently have a `local:<id>` credential stored. */
1690
2164
  async listLocalEndpointIds() {
1691
2165
  await this.ensureLoaded();
@@ -1698,7 +2172,7 @@ var AuthStorage = class {
1698
2172
  */
1699
2173
  async setLocalEndpoint(endpointId, baseUrl, apiKey) {
1700
2174
  await this.setCredentials(`${LOCAL_AUTH_KEY_PREFIX}${endpointId}`, {
1701
- accessToken: apiKey && apiKey.length > 0 ? apiKey : "local",
2175
+ accessToken: apiKey && apiKey.length > 0 ? apiKey : LOCAL_NO_API_KEY,
1702
2176
  refreshToken: "",
1703
2177
  expiresAt: Date.now() + LOCAL_CREDENTIAL_LIFETIME_MS,
1704
2178
  baseUrl
@@ -1739,7 +2213,7 @@ var AuthStorage = class {
1739
2213
  const first = !this.loaded;
1740
2214
  await withFileLock(this.filePath, async () => {
1741
2215
  try {
1742
- const content = await fs4.readFile(this.filePath, "utf-8");
2216
+ const content = await fs5.readFile(this.filePath, "utf-8");
1743
2217
  this.data = JSON.parse(content);
1744
2218
  if (first) {
1745
2219
  log("INFO", "auth", `Loaded credentials from ${this.filePath}`, {
@@ -1794,7 +2268,7 @@ var AuthStorage = class {
1794
2268
  }
1795
2269
  let changed;
1796
2270
  try {
1797
- const stat = await fs4.stat(this.filePath);
2271
+ const stat = await fs5.stat(this.filePath);
1798
2272
  changed = stat.ino !== this.snapshotIno || stat.mtimeMs !== this.snapshotMtimeMs || stat.size !== this.snapshotSize;
1799
2273
  } catch {
1800
2274
  changed = this.snapshotSize !== -1;
@@ -1804,7 +2278,7 @@ var AuthStorage = class {
1804
2278
  /** Record the file identity behind the current snapshot. */
1805
2279
  async rememberSnapshot() {
1806
2280
  try {
1807
- const stat = await fs4.stat(this.filePath);
2281
+ const stat = await fs5.stat(this.filePath);
1808
2282
  this.snapshotMtimeMs = stat.mtimeMs;
1809
2283
  this.snapshotSize = stat.size;
1810
2284
  this.snapshotIno = stat.ino;
@@ -1841,11 +2315,54 @@ var AuthStorage = class {
1841
2315
  await this.ensureFresh();
1842
2316
  return this.data[provider];
1843
2317
  }
2318
+ /**
2319
+ * A MiniMax key saved without an endpoint (every key, until its first use)
2320
+ * gets the endpoint of the region that issued it, saved so the check runs
2321
+ * once. Without this a Mainland China key went to the Global API, got a 401,
2322
+ * and was deleted as invalid.
2323
+ */
2324
+ async withMiniMaxRegion(creds) {
2325
+ const baseUrl = await this.detectMiniMaxRegion(creds.accessToken);
2326
+ if (!baseUrl) return creds;
2327
+ log("INFO", "auth", `MiniMax key belongs to ${baseUrl} \u2014 saved for future requests`);
2328
+ await this.mutateLatest((latest) => {
2329
+ const current = latest["minimax"];
2330
+ if (current?.accessToken === creds.accessToken && !current.baseUrl) {
2331
+ current.baseUrl = baseUrl;
2332
+ }
2333
+ });
2334
+ return { ...creds, baseUrl };
2335
+ }
1844
2336
  async setCredentials(provider, creds) {
1845
2337
  await this.mutateLatest((latest) => {
1846
2338
  latest[provider] = creds;
1847
2339
  });
1848
2340
  }
2341
+ /**
2342
+ * After a 401, move a regional key to the cluster that issued it instead of
2343
+ * treating it as invalid. Only the Xiaomi Token Plan is regional: every key
2344
+ * used to go to Singapore, so Europe and China keys were rejected and deleted.
2345
+ * Returns the new base URL, or undefined when no other cluster accepts the key.
2346
+ */
2347
+ async relocateRegionalApiKey(storageKeys) {
2348
+ const key = await this.pickStorageKey(storageKeys);
2349
+ const creds = key === "xiaomi" ? this.data[key] : void 0;
2350
+ if (!creds) return void 0;
2351
+ const baseUrl = await this.detectXiaomiCluster(creds.accessToken);
2352
+ if (!baseUrl || baseUrl === creds.baseUrl) return void 0;
2353
+ await this.mutateLatest((latest) => {
2354
+ const current = latest["xiaomi"];
2355
+ if (current?.accessToken === creds.accessToken) current.baseUrl = baseUrl;
2356
+ });
2357
+ log("INFO", "auth", `Xiaomi Token Plan key belongs to ${baseUrl} \u2014 saved for future requests`);
2358
+ return baseUrl;
2359
+ }
2360
+ // Keeps local-endpoint keys: they're the user's own config, and a 401 there is often a busy gateway.
2361
+ async clearRejectedApiKey(storageKey) {
2362
+ if (storageKey.startsWith(LOCAL_AUTH_KEY_PREFIX)) return false;
2363
+ await this.clearCredentials(storageKey);
2364
+ return true;
2365
+ }
1849
2366
  async clearCredentials(provider) {
1850
2367
  await this.mutateLatest((latest) => {
1851
2368
  delete latest[provider];
@@ -1925,6 +2442,9 @@ var AuthStorage = class {
1925
2442
  }
1926
2443
  throw new NotLoggedInError(provider);
1927
2444
  }
2445
+ if (provider === "anthropic" && !this.data.anthropic && isClaudeCodeAuthMarker(this.data[CLAUDE_CODE_AUTH_KEY])) {
2446
+ return { accessToken: "", refreshToken: "", expiresAt: Number.MAX_SAFE_INTEGER };
2447
+ }
1928
2448
  const dual = dualAuthProvider(provider);
1929
2449
  const dualOAuthCreds = dual ? this.data[dual.oauthKey] : void 0;
1930
2450
  if (dual && dualOAuthCreds) {
@@ -1959,6 +2479,7 @@ var AuthStorage = class {
1959
2479
  throw new NotLoggedInError(provider);
1960
2480
  }
1961
2481
  if (STATIC_API_KEY_PROVIDERS.has(provider)) {
2482
+ if (provider === "minimax" && !creds.baseUrl) return await this.withMiniMaxRegion(creds);
1962
2483
  return creds;
1963
2484
  }
1964
2485
  if (!opts?.forceRefresh && Date.now() < creds.expiresAt - refreshThresholdMs(creds)) {
@@ -2045,7 +2566,7 @@ var AuthStorage = class {
2045
2566
  };
2046
2567
  async function readAuthData(filePath) {
2047
2568
  try {
2048
- const content = await fs4.readFile(filePath, "utf-8");
2569
+ const content = await fs5.readFile(filePath, "utf-8");
2049
2570
  return JSON.parse(content);
2050
2571
  } catch (error) {
2051
2572
  if (error.code === "ENOENT") return {};
@@ -2053,12 +2574,12 @@ async function readAuthData(filePath) {
2053
2574
  }
2054
2575
  }
2055
2576
  async function atomicWriteFile(filePath, content) {
2056
- const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto5.randomUUID().slice(0, 8)}.tmp`;
2577
+ const tmpPath = `${filePath}.${process.pid}.${Date.now()}.${crypto6.randomUUID().slice(0, 8)}.tmp`;
2057
2578
  try {
2058
- await fs4.writeFile(tmpPath, content, { encoding: "utf-8", mode: 384 });
2059
- await fs4.rename(tmpPath, filePath);
2579
+ await fs5.writeFile(tmpPath, content, { encoding: "utf-8", mode: 384 });
2580
+ await fs5.rename(tmpPath, filePath);
2060
2581
  } catch (err) {
2061
- await fs4.unlink(tmpPath).catch(() => {
2582
+ await fs5.unlink(tmpPath).catch(() => {
2062
2583
  });
2063
2584
  throw err;
2064
2585
  }
@@ -2079,6 +2600,12 @@ var CLAUDE_FAST_BILLING = {
2079
2600
  paid: true,
2080
2601
  standardModel: "claude-opus-5-5"
2081
2602
  };
2603
+ var CLAUDE_FABLE_FAST_BILLING = {
2604
+ label: "bills usage credits",
2605
+ 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.",
2606
+ paid: true,
2607
+ standardModel: "claude-fable-5-2"
2608
+ };
2082
2609
  var XIAOMI_ULTRASPEED_BILLING = {
2083
2610
  label: "bills API Credits",
2084
2611
  detail: "UltraSpeed runs only on your Xiaomi API Credits, billed per token at a higher rate than MiMo-V2.6-Pro, never on the Token Plan.",
@@ -2093,18 +2620,18 @@ var CODEX_FAST_BILLING = {
2093
2620
  var GEMINI_AUTH_KEYS = [GEMINI_API_KEY, "gemini"];
2094
2621
  var MODELS = [
2095
2622
  // ── Anthropic ──────────────────────────────────────────
2096
- // NOTE: Claude Mythos 5.1 (`claude-mythos-5-1`, 2026-09-01) is kept commented
2097
- // out — it's a Project Glasswing model, still "Active (invite only)" in
2098
- // Anthropic's docs and unavailable to most users. Re-enable once it's
2099
- // generally available.
2623
+ // NOTE: Claude Mythos 5.2 (`claude-mythos-5-2`, 2026-11-09) is kept commented
2624
+ // out — it's only for organizations verified through Anthropic's verification
2625
+ // programs and unavailable to most users. Re-enable once it's generally
2626
+ // available.
2100
2627
  {
2101
- // Released 2026-09-01 — replaces Fable 5 at the same $10/$50 MTok (cache
2102
- // reads drop to $0.25). Always-on adaptive thinking steered by effort;
2103
- // forced tool use is rejected with a 400, which @prestyj/ai never sends on the
2104
- // Anthropic path. Fable 5 is retired here — a session that still has it
2105
- // saved falls back to the provider default on next start.
2106
- id: "claude-fable-5-1",
2107
- name: "Claude Fable 5.1",
2628
+ // Released 2026-11-09 — replaces Fable 5.1 at $8/$40 MTok (down from
2629
+ // $10/$50; cache reads $0.20). Same API surface as 5.1: always-on adaptive
2630
+ // thinking steered by effort, forced tool use rejected with a 400 (@prestyj/ai
2631
+ // never sends it on the Anthropic path). Fable 5.1 is retired here — a
2632
+ // session that still has it saved falls back to the provider default.
2633
+ id: "claude-fable-5-2",
2634
+ name: "Claude Fable 5.2",
2108
2635
  provider: "anthropic",
2109
2636
  contextWindow: 1e6,
2110
2637
  maxOutputTokens: 128e3,
@@ -2114,12 +2641,28 @@ var MODELS = [
2114
2641
  costTier: "high",
2115
2642
  maxThinkingLevel: "max"
2116
2643
  },
2644
+ {
2645
+ // Fable 5.2 in fast mode: the same model at up to 2.5x output tokens/sec,
2646
+ // $16/$80 MTok. Sent as `claude-fable-5-2` + `speed: "fast"`; on a Claude
2647
+ // subscription it bills usage credits only, like Opus 5.5 Fast.
2648
+ id: "claude-fable-5-2-fast",
2649
+ name: "Claude Fable 5.2 Fast",
2650
+ provider: "anthropic",
2651
+ contextWindow: 1e6,
2652
+ maxOutputTokens: 128e3,
2653
+ supportsThinking: true,
2654
+ supportsImages: true,
2655
+ supportsVideo: false,
2656
+ costTier: "high",
2657
+ maxThinkingLevel: "max",
2658
+ billing: CLAUDE_FABLE_FAST_BILLING
2659
+ },
2117
2660
  // {
2118
2661
  // // Mythos-class model offered through Project Glasswing (limited
2119
- // // availability, invitation-only). Same underlying model as Fable 5.1 with
2120
- // // some safeguards lifted; kept here so approved accounts can select it.
2121
- // id: "claude-mythos-5-1",
2122
- // name: "Claude Mythos 5.1",
2662
+ // // availability, verified organizations only). Same specs and pricing as
2663
+ // // Fable 5.2; kept here so approved accounts can select it.
2664
+ // id: "claude-mythos-5-2",
2665
+ // name: "Claude Mythos 5.2",
2123
2666
  // provider: "anthropic",
2124
2667
  // contextWindow: 1_000_000,
2125
2668
  // maxOutputTokens: 128_000,
@@ -2261,9 +2804,9 @@ var MODELS = [
2261
2804
  billing: CODEX_FAST_BILLING
2262
2805
  },
2263
2806
  // GPT-6 Sol + Luna — released 2026-09-22 below Astra, replacing the whole
2264
- // GPT-5.6 family (Sol/Terra/Luna; there is no GPT-6 Terra — OpenAI's Codex
2807
+ // GPT-5.6 family (Sol/Terra/Luna; there was no GPT-6 Terra — OpenAI's Codex
2265
2808
  // catalog upgrades 5.6 Terra to 6 Sol). GPT-6.1 Sol (2026-09-29) then replaced
2266
- // GPT-6 Sol. Same window split as Astra: 1.05M on the public Responses API,
2809
+ // 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,
2267
2810
  // 272K on the Codex route; 128K output, text+image input, freeform
2268
2811
  // apply_patch, responses-lite transport. The GPT-5.6 ids and `gpt-6-sol` are
2269
2812
  // retired — a saved session on one falls back to the provider default on
@@ -2305,6 +2848,40 @@ var MODELS = [
2305
2848
  maxThinkingLevel: "ultra",
2306
2849
  billing: CODEX_FAST_BILLING
2307
2850
  },
2851
+ {
2852
+ // GPT-6.1 Terra (Codex priority 7, default low, client >= 0.153.0). $1/$5
2853
+ // MTok, cached input $0.05. Unlike Sol/Astra the Codex route gets a 500K
2854
+ // window (catalog `context_window`). Same ladder and Ultra preset as Sol.
2855
+ id: "gpt-6.1-terra",
2856
+ name: "GPT-6.1 Terra",
2857
+ provider: "openai",
2858
+ contextWindow: 105e4,
2859
+ codexContextWindow: 5e5,
2860
+ maxOutputTokens: 128e3,
2861
+ supportsThinking: true,
2862
+ defaultThinkingLevel: "low",
2863
+ supportsImages: true,
2864
+ supportsVideo: false,
2865
+ costTier: "medium",
2866
+ maxThinkingLevel: "ultra"
2867
+ },
2868
+ {
2869
+ // Codex Fast mode for 6.1 Terra ("1.5x speed") — see `gpt-6-astra-fast`
2870
+ // for the wire mapping and billing.
2871
+ id: "gpt-6.1-terra-fast",
2872
+ name: "GPT-6.1 Terra Fast",
2873
+ provider: "openai",
2874
+ contextWindow: 105e4,
2875
+ codexContextWindow: 5e5,
2876
+ maxOutputTokens: 128e3,
2877
+ supportsThinking: true,
2878
+ defaultThinkingLevel: "low",
2879
+ supportsImages: true,
2880
+ supportsVideo: false,
2881
+ costTier: "medium",
2882
+ maxThinkingLevel: "ultra",
2883
+ billing: CODEX_FAST_BILLING
2884
+ },
2308
2885
  {
2309
2886
  // Luna — "Fast and affordable model for easier tasks." (Codex priority 4,
2310
2887
  // default medium, needs a Codex client >= 0.155.0). $0.10/$0.50 MTok.
@@ -2609,6 +3186,23 @@ var MODELS = [
2609
3186
  maxThinkingLevel: "max"
2610
3187
  },
2611
3188
  // ── MiniMax ────────────────────────────────────────────
3189
+ {
3190
+ // The only text model M Plan / Token Plan keys cover; MiniMax-M3 on those
3191
+ // keys fails with "insufficient balance (1008)". Pay-as-you-go serves both.
3192
+ // Always thinks (`thinking: disabled` 400s; omitted = on) with a real
3193
+ // low→max effort ladder on output_config.effort, API default max.
3194
+ id: "MiniMax-M3.1-Flash",
3195
+ name: "MiniMax M3.1 Flash",
3196
+ provider: "minimax",
3197
+ contextWindow: 1e6,
3198
+ maxOutputTokens: 131072,
3199
+ supportsThinking: true,
3200
+ supportsImages: true,
3201
+ supportsVideo: true,
3202
+ maxVideoBytes: 50 * 1024 * 1024,
3203
+ costTier: "low",
3204
+ maxThinkingLevel: "max"
3205
+ },
2612
3206
  {
2613
3207
  id: "MiniMax-M3",
2614
3208
  name: "MiniMax M3",
@@ -2831,15 +3425,51 @@ function clearRuntimeModels(predicate) {
2831
3425
  if (predicate(model)) runtimeModels.delete(id);
2832
3426
  }
2833
3427
  }
3428
+ var providerCatalogs = /* @__PURE__ */ new Map();
3429
+ function setProviderCatalog(provider, models) {
3430
+ if (!models) {
3431
+ providerCatalogs.delete(provider);
3432
+ return [];
3433
+ }
3434
+ const installed = /* @__PURE__ */ new Map();
3435
+ for (const model of models) {
3436
+ if (model.provider !== provider) continue;
3437
+ if (MODELS.some((m) => m.id === model.id && m.provider !== provider)) continue;
3438
+ installed.set(model.id, model);
3439
+ }
3440
+ providerCatalogs.set(provider, installed);
3441
+ return [...installed.values()];
3442
+ }
3443
+ function getProviderCatalog(provider) {
3444
+ const catalog = providerCatalogs.get(provider);
3445
+ return catalog ? [...catalog.values()] : void 0;
3446
+ }
2834
3447
  function getAllModels() {
2835
- return [...MODELS, ...runtimeModels.values()];
3448
+ const synced = [...providerCatalogs.values()].flatMap((c) => [...c.values()]);
3449
+ return [
3450
+ ...MODELS.filter((m) => !providerCatalogs.has(m.provider)),
3451
+ ...synced,
3452
+ ...runtimeModels.values()
3453
+ ];
2836
3454
  }
2837
3455
  function getModel(id) {
2838
- return MODELS.find((m) => m.id === id) ?? runtimeModels.get(id);
3456
+ const fixed = MODELS.find((m) => m.id === id);
3457
+ if (fixed && !providerCatalogs.has(fixed.provider)) return fixed;
3458
+ return findSynced(id) ?? fixed ?? runtimeModels.get(id);
3459
+ }
3460
+ function findSynced(id) {
3461
+ for (const catalog of providerCatalogs.values()) {
3462
+ const hit = catalog.get(id);
3463
+ if (hit) return hit;
3464
+ }
3465
+ return void 0;
2839
3466
  }
2840
3467
  function getModelsForProvider(provider) {
2841
3468
  return getAllModels().filter((m) => m.provider === provider);
2842
3469
  }
3470
+ function getListedModels() {
3471
+ return getAllModels().filter((m) => !isHiddenProvider(m.provider));
3472
+ }
2843
3473
  function isPaidModel(modelId) {
2844
3474
  return getModel(modelId)?.billing?.paid === true;
2845
3475
  }
@@ -2872,7 +3502,7 @@ var DEFAULT_MODEL_IDS = {
2872
3502
  gemini: "gemini-3.1-flash-lite",
2873
3503
  glm: "glm-5.3",
2874
3504
  moonshot: "kimi-k3",
2875
- minimax: "MiniMax-M3",
3505
+ minimax: "MiniMax-M3.1-Flash",
2876
3506
  deepseek: "deepseek-v4-pro",
2877
3507
  huggingface: "moonshotai/Kimi-K2.7-Code",
2878
3508
  openrouter: "qwen/qwen3.8-max",
@@ -2945,16 +3575,9 @@ export {
2945
3575
  loginKimi,
2946
3576
  refreshKimiToken,
2947
3577
  generatePKCE,
2948
- openLog,
2949
- getSessionId,
2950
- isLoggerOpen,
2951
- log,
2952
- registerLogCleanup,
2953
- closeLogger,
2954
- compareClaudeCodeVersions,
2955
3578
  getClaudeCodeVersion,
2956
- recordRequiredClaudeCodeVersion,
2957
3579
  getClaudeCliUserAgent,
3580
+ pendingClaudeCodeVersionRefresh,
2958
3581
  loginAnthropic,
2959
3582
  refreshAnthropicToken,
2960
3583
  loginOpenAI,
@@ -2967,6 +3590,36 @@ export {
2967
3590
  loginXai,
2968
3591
  refreshXaiToken,
2969
3592
  withFileLock,
3593
+ openLog,
3594
+ getSessionId,
3595
+ isLoggerOpen,
3596
+ log,
3597
+ registerLogCleanup,
3598
+ closeLogger,
3599
+ HIDDEN_PROVIDERS,
3600
+ isHiddenProvider,
3601
+ CLAUDE_CODE_MANIFEST,
3602
+ CLAUDE_CODE_AUTH_KEY,
3603
+ CLAUDE_CODE_AUTH_MARKER,
3604
+ isClaudeCodeAuthMarker,
3605
+ isLegacyClaudeOAuth,
3606
+ claudeCodePlatformKey,
3607
+ claudeCodeHome,
3608
+ claudeCodeConfigDir,
3609
+ claudeCodeBinaryPath,
3610
+ resolveClaudeCodeBinary,
3611
+ ensureClaudeCodeBinary,
3612
+ formatClaudeCodeInstallProgress,
3613
+ claudeCodeEnv,
3614
+ claudeCodeAuthStatus,
3615
+ logoutClaudeCode,
3616
+ claudeCodeCallbackUrl,
3617
+ loginClaudeCode,
3618
+ MINIMAX_GLOBAL_BASE_URL,
3619
+ MINIMAX_CN_BASE_URL,
3620
+ detectMiniMaxBaseUrl,
3621
+ XIAOMI_TOKEN_PLAN_BASE_URLS,
3622
+ detectXiaomiTokenPlanBaseUrl,
2970
3623
  MOONSHOT_OAUTH_KEY,
2971
3624
  XAI_OAUTH_KEY,
2972
3625
  dualAuthProvider,
@@ -2983,9 +3636,12 @@ export {
2983
3636
  MODELS,
2984
3637
  registerRuntimeModels,
2985
3638
  clearRuntimeModels,
3639
+ setProviderCatalog,
3640
+ getProviderCatalog,
2986
3641
  getAllModels,
2987
3642
  getModel,
2988
3643
  getModelsForProvider,
3644
+ getListedModels,
2989
3645
  isPaidModel,
2990
3646
  withoutPaidTier,
2991
3647
  getAuthStorageKeys,
@@ -3000,4 +3656,4 @@ export {
3000
3656
  getDefaultThinkingLevel,
3001
3657
  getSummaryModel
3002
3658
  };
3003
- //# sourceMappingURL=chunk-XPXWXKRZ.js.map
3659
+ //# sourceMappingURL=chunk-G3ZS4V2K.js.map