@prestyj/core 5.32.2 → 5.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,19 +1,36 @@
1
1
  import {
2
2
  AuthStorage,
3
+ CLAUDE_CODE_AUTH_KEY,
4
+ CLAUDE_CODE_AUTH_MARKER,
5
+ CLAUDE_CODE_MANIFEST,
3
6
  DEFAULT_MAX_VIDEO_BYTES,
4
7
  GEMINI_API_KEY,
5
8
  GEMINI_API_KEY_BASE_URL,
9
+ HIDDEN_PROVIDERS,
6
10
  LOCAL_AUTH_KEY_PREFIX,
11
+ MINIMAX_CN_BASE_URL,
12
+ MINIMAX_GLOBAL_BASE_URL,
7
13
  MODELS,
8
14
  MOONSHOT_OAUTH_KEY,
9
15
  NotLoggedInError,
10
16
  XAI_OAUTH_KEY,
11
17
  XIAOMI_CREDITS_KEY,
18
+ XIAOMI_TOKEN_PLAN_BASE_URLS,
19
+ claudeCodeAuthStatus,
20
+ claudeCodeBinaryPath,
21
+ claudeCodeCallbackUrl,
22
+ claudeCodeConfigDir,
23
+ claudeCodeEnv,
24
+ claudeCodeHome,
25
+ claudeCodePlatformKey,
12
26
  clearRuntimeModels,
13
27
  closeLogger,
14
- compareClaudeCodeVersions,
28
+ detectMiniMaxBaseUrl,
29
+ detectXiaomiTokenPlanBaseUrl,
15
30
  dualAuthProvider,
16
31
  dualAuthProviderByOAuthKey,
32
+ ensureClaudeCodeBinary,
33
+ formatClaudeCodeInstallProgress,
17
34
  generatePKCE,
18
35
  getAllModels,
19
36
  getAuthStorageKey,
@@ -23,32 +40,39 @@ import {
23
40
  getContextWindow,
24
41
  getDefaultModel,
25
42
  getDefaultThinkingLevel,
43
+ getListedModels,
26
44
  getMaxThinkingLevel,
27
45
  getModel,
28
46
  getModelsForProvider,
47
+ getProviderCatalog,
29
48
  getSessionId,
30
49
  getSummaryModel,
31
50
  getToolResultCharLimit,
32
51
  getVideoByteLimit,
33
52
  grokCliBaseUrl,
34
53
  grokCliHeaders,
54
+ isClaudeCodeAuthMarker,
35
55
  isGrokCliEndpoint,
56
+ isHiddenProvider,
36
57
  isKimiCodingEndpoint,
58
+ isLegacyClaudeOAuth,
37
59
  isLoggerOpen,
38
60
  isPaidModel,
39
61
  kimiCodeBaseUrl,
40
62
  kimiCodingHeaders,
41
63
  log,
42
64
  loginAnthropic,
65
+ loginClaudeCode,
43
66
  loginGemini,
44
67
  loginKimi,
45
68
  loginOpenAI,
46
69
  loginXai,
70
+ logoutClaudeCode,
47
71
  oauthStorageKey,
48
72
  openLog,
73
+ pendingClaudeCodeVersionRefresh,
49
74
  providerStorageKeys,
50
75
  readStoredBaseUrlSync,
51
- recordRequiredClaudeCodeVersion,
52
76
  refreshAnthropicToken,
53
77
  refreshGeminiToken,
54
78
  refreshKimiToken,
@@ -56,13 +80,132 @@ import {
56
80
  refreshXaiToken,
57
81
  registerLogCleanup,
58
82
  registerRuntimeModels,
83
+ resolveClaudeCodeBinary,
84
+ setProviderCatalog,
59
85
  usesOpenAICodexTransport,
60
86
  withFileLock,
61
87
  withoutPaidTier
62
- } from "./chunk-6I3APHDP.js";
88
+ } from "./chunk-7IHCMEIY.js";
63
89
  import {
64
90
  getAppPaths
65
- } from "./chunk-W4NHU4UL.js";
91
+ } from "./chunk-DVWS2KEW.js";
92
+
93
+ // src/openrouter-catalog.ts
94
+ var OPENROUTER_DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
95
+ var EFFORT_LADDER = ["low", "medium", "high", "xhigh", "max"];
96
+ function positiveInt(value) {
97
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
98
+ }
99
+ function strings(value) {
100
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
101
+ }
102
+ function costTier(prompt) {
103
+ const perToken = typeof prompt === "string" ? Number(prompt) : NaN;
104
+ if (!Number.isFinite(perToken) || perToken < 5e-7) return "low";
105
+ return perToken < 3e-6 ? "medium" : "high";
106
+ }
107
+ function parseOpenRouterCatalog(body) {
108
+ const data = body?.data;
109
+ if (!Array.isArray(data)) return { models: [], skipped: 0 };
110
+ const models = [];
111
+ let skipped = 0;
112
+ const seen = /* @__PURE__ */ new Set();
113
+ for (const raw of data) {
114
+ const id = typeof raw?.id === "string" ? raw.id.trim() : "";
115
+ const params = strings(raw?.supported_parameters);
116
+ const contextWindow = positiveInt(raw?.top_provider?.context_length) ?? positiveInt(raw?.context_length);
117
+ if (!id || seen.has(id) || !params.includes("tools") || !contextWindow) {
118
+ skipped++;
119
+ continue;
120
+ }
121
+ seen.add(id);
122
+ const efforts = strings(raw.reasoning?.supported_efforts);
123
+ const ladder = EFFORT_LADDER.filter((rung) => efforts.includes(rung));
124
+ const supportsThinking = ladder.length > 0 || params.includes("reasoning") || params.includes("reasoning_effort");
125
+ const defaultEffort = raw.reasoning?.default_effort;
126
+ const maxOutput = positiveInt(raw.top_provider?.max_completion_tokens) ?? Math.min(contextWindow, 16384);
127
+ models.push({
128
+ id,
129
+ name: typeof raw.name === "string" && raw.name.trim() ? raw.name.trim() : id,
130
+ provider: "openrouter",
131
+ contextWindow,
132
+ maxOutputTokens: Math.min(maxOutput, contextWindow),
133
+ supportsThinking,
134
+ supportsImages: strings(raw.architecture?.input_modalities).includes("image"),
135
+ // Video needs a per-transport payload cap the catalog doesn't publish.
136
+ supportsVideo: false,
137
+ costTier: costTier(raw.pricing?.prompt),
138
+ maxThinkingLevel: ladder[ladder.length - 1] ?? "high",
139
+ ...ladder.length > 0 ? { thinkingLevels: ladder } : {},
140
+ ...typeof defaultEffort === "string" && ladder.includes(defaultEffort) ? { defaultThinkingLevel: defaultEffort } : {}
141
+ });
142
+ }
143
+ return { models, skipped };
144
+ }
145
+
146
+ // src/opencode-catalog.ts
147
+ var OPENCODE_PROVIDERS = ["opencode-go", "opencode"];
148
+ var OPENCODE_CATALOG_URLS = {
149
+ opencode: "https://opencode.ai/inference/v1/models",
150
+ "opencode-go": "https://opencode.ai/inference/go/v1/models"
151
+ };
152
+ var EFFORT_LADDER2 = ["low", "medium", "high", "xhigh", "max"];
153
+ function positiveInt2(value) {
154
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
155
+ }
156
+ function strings2(value) {
157
+ return Array.isArray(value) ? value.filter((v) => typeof v === "string") : [];
158
+ }
159
+ function costTier2(price) {
160
+ if (typeof price !== "number" || !Number.isFinite(price) || price < 0.5) return "low";
161
+ return price < 3 ? "medium" : "high";
162
+ }
163
+ function formatOpenCodeModelId(provider, rawId) {
164
+ return `${provider}/${rawId}`;
165
+ }
166
+ function parseOpenCodeCatalog(provider, body) {
167
+ const data = body?.data;
168
+ if (!Array.isArray(data)) return { models: [], skipped: 0 };
169
+ const models = [];
170
+ let skipped = 0;
171
+ const seen = /* @__PURE__ */ new Set();
172
+ for (const raw of data) {
173
+ const rawId = typeof raw?.id === "string" ? raw.id.trim() : "";
174
+ const contextWindow = positiveInt2(raw?.limit?.context);
175
+ const price = raw?.cost?.text?.input?.price;
176
+ if (!/^[\w.:-]+$/.test(rawId) || seen.has(rawId) || raw.type !== "chat" || !raw.api?.["chat-completions"] || raw.capabilities?.tools?.supported !== true || !contextWindow || provider === "opencode" && price === 0) {
177
+ skipped++;
178
+ continue;
179
+ }
180
+ seen.add(rawId);
181
+ const reasoning = raw.capabilities.reasoning;
182
+ const efforts = strings2(reasoning?.effort);
183
+ const ladder = EFFORT_LADDER2.filter((rung) => efforts.includes(rung));
184
+ const defaultEffort = reasoning?.default?.type === "effort" ? reasoning.default.value : null;
185
+ const maxOutput = Math.min(
186
+ positiveInt2(raw.limit?.output) ?? 16384,
187
+ Math.floor(contextWindow / 2)
188
+ );
189
+ models.push({
190
+ id: formatOpenCodeModelId(provider, rawId),
191
+ name: typeof raw.name === "string" && raw.name.trim() ? raw.name.trim() : rawId,
192
+ provider,
193
+ contextWindow,
194
+ maxOutputTokens: Math.max(1, maxOutput),
195
+ // Only a declared effort ladder counts: a model without one is never sent
196
+ // a reasoning_effort it might reject.
197
+ supportsThinking: ladder.length > 0,
198
+ supportsImages: strings2(raw.modalities?.input).some((m) => m.startsWith("image")),
199
+ // Video needs a per-transport payload cap the catalog doesn't publish.
200
+ supportsVideo: false,
201
+ costTier: costTier2(price),
202
+ maxThinkingLevel: ladder[ladder.length - 1] ?? "low",
203
+ ...ladder.length > 0 ? { thinkingLevels: ladder } : {},
204
+ ...typeof defaultEffort === "string" && ladder.includes(defaultEffort) ? { defaultThinkingLevel: defaultEffort } : {}
205
+ });
206
+ }
207
+ return { models, skipped };
208
+ }
66
209
 
67
210
  // src/thinking-level.ts
68
211
  var OPENAI_GPT_THINKING_LEVELS = ["medium", "high", "xhigh"];
@@ -92,6 +235,13 @@ var ANTHROPIC_ADAPTIVE_THINKING_LEVELS = [
92
235
  ];
93
236
  var MOONSHOT_K3_THINKING_LEVELS = ["low", "high", "max"];
94
237
  var GLM_THINKING_LEVELS = ["low", "medium", "high", "xhigh", "max"];
238
+ var MINIMAX_EFFORT_THINKING_LEVELS = [
239
+ "low",
240
+ "medium",
241
+ "high",
242
+ "xhigh",
243
+ "max"
244
+ ];
95
245
  var LOCAL_THINKING_LEVELS = ["low", "medium", "high", "max"];
96
246
  function isOpenAIGptModel(provider, model) {
97
247
  return provider === "openai" && model.startsWith("gpt-");
@@ -108,8 +258,11 @@ function isMoonshotK3Model(provider, model) {
108
258
  function isGlmModel(provider) {
109
259
  return provider === "glm";
110
260
  }
261
+ function isMiniMaxEffortModel(provider, model) {
262
+ return provider === "minimax" && model.startsWith("MiniMax-M3.1");
263
+ }
111
264
  function isAnthropicXhighModel(provider, model) {
112
- return provider === "anthropic" && /opus-5|opus-4[-.]8|opus-4[-.]7|sonnet-5[-.]5|haiku-5[-.]5/.test(model);
265
+ return provider === "anthropic" && /fable-5|mythos-5|opus-5|opus-4-8|opus-4-7|sonnet-5[-.]5|haiku-5[-.]5/.test(model);
113
266
  }
114
267
  function isAnthropicAdaptiveModel(provider, model) {
115
268
  return provider === "anthropic" && /opus-5|opus-4[-.]8|opus-4[-.]7|opus-4[-.]6|sonnet-5|haiku-5|fable-5|mythos-5/.test(model);
@@ -121,6 +274,8 @@ function getSupportedThinkingLevels(provider, model) {
121
274
  const maxIndex2 = LOCAL_THINKING_LEVELS.indexOf(info.maxThinkingLevel);
122
275
  return maxIndex2 === -1 ? LOCAL_THINKING_LEVELS.slice(0, 3) : LOCAL_THINKING_LEVELS.slice(0, maxIndex2 + 1);
123
276
  }
277
+ const declared = getModel(model)?.thinkingLevels;
278
+ if (declared && declared.length > 0) return declared;
124
279
  const maxLevel = getMaxThinkingLevel(model);
125
280
  if (isAnthropicAdaptiveModel(provider, model)) {
126
281
  const levels2 = isAnthropicXhighModel(provider, model) ? ANTHROPIC_XHIGH_THINKING_LEVELS : ANTHROPIC_ADAPTIVE_THINKING_LEVELS;
@@ -140,6 +295,7 @@ function getSupportedThinkingLevels(provider, model) {
140
295
  }
141
296
  if (isMoonshotK3Model(provider, model)) return MOONSHOT_K3_THINKING_LEVELS;
142
297
  if (provider === "deepseek") return DEEPSEEK_THINKING_LEVELS;
298
+ if (isMiniMaxEffortModel(provider, model)) return MINIMAX_EFFORT_THINKING_LEVELS;
143
299
  if (isGlmModel(provider)) {
144
300
  const maxIndex2 = GLM_THINKING_LEVELS.indexOf(maxLevel);
145
301
  if (maxIndex2 === -1) return GLM_THINKING_LEVELS;
@@ -160,7 +316,7 @@ function isThinkingLevelSupported(provider, model, level) {
160
316
  }
161
317
  function getNextThinkingLevel(provider, model, current) {
162
318
  const supportedLevels = getSupportedThinkingLevels(provider, model);
163
- 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
319
+ 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
164
320
  // low/medium/high on `reasoning_effort` (verified against 0.32) and the
165
321
  // other OpenAI-compatible servers use the same three. A model that can't
166
322
  // reason at all already has no supported levels, so it never gets here.
@@ -188,11 +344,12 @@ function clampThinkingForPlanMode(level) {
188
344
  }
189
345
 
190
346
  // src/local-models.ts
347
+ import { LOCAL_NO_API_KEY, localBearerKey } from "@prestyj/ai";
191
348
  var DEFAULT_LOCAL_ENDPOINTS = [
192
349
  { id: "ollama", label: "Ollama", baseUrl: "http://127.0.0.1:11434/v1", kind: "ollama" }
193
350
  ];
194
351
  var FALLBACK_CONTEXT_WINDOW = 4096;
195
- var LOCAL_API_KEY_PLACEHOLDER = "local";
352
+ var LOCAL_API_KEY_PLACEHOLDER = LOCAL_NO_API_KEY;
196
353
  var DEFAULT_PROBE_TIMEOUT_MS = 1200;
197
354
  var ENRICH_CONCURRENCY = 6;
198
355
  var CACHE_TTL_MS = 3e4;
@@ -208,6 +365,9 @@ function parseLocalModelId(id) {
208
365
  if (slash <= 0 || slash === rest.length - 1) return void 0;
209
366
  return { endpointId: rest.slice(0, slash), rawId: rest.slice(slash + 1) };
210
367
  }
368
+ function localModelShortName(rawId) {
369
+ return rawId.slice(rawId.lastIndexOf("/") + 1) || rawId;
370
+ }
211
371
  function isLocalModelId(id) {
212
372
  return parseLocalModelId(id) !== void 0;
213
373
  }
@@ -218,8 +378,9 @@ function endpointRoot(baseUrl) {
218
378
  return baseUrl.replace(/\/+$/, "").replace(/\/v1$/, "");
219
379
  }
220
380
  function authHeaders(endpoint) {
381
+ const key = localBearerKey(endpoint.apiKey);
221
382
  return {
222
- Authorization: `Bearer ${endpoint.apiKey ?? LOCAL_API_KEY_PLACEHOLDER}`,
383
+ ...key ? { Authorization: `Bearer ${key}` } : {},
223
384
  Accept: "application/json"
224
385
  };
225
386
  }
@@ -270,7 +431,14 @@ async function probeEndpoint(endpoint, { timeoutMs = DEFAULT_PROBE_TIMEOUT_MS, s
270
431
  const entries = (list.data ?? []).filter(
271
432
  (entry) => typeof entry.id === "string" && entry.id.length > 0 && !NON_CHAT_ID_PATTERN.test(entry.id)
272
433
  );
273
- const models = await enrich(endpoint, entries, { timeoutMs, signal });
434
+ const enriched = await enrich(endpoint, entries, { timeoutMs, signal });
435
+ const pinned = contextLength(endpoint.contextLength);
436
+ const images = typeof endpoint.supportsImages === "boolean" ? endpoint.supportsImages : void 0;
437
+ const models = enriched.map((m) => ({
438
+ ...m,
439
+ ...pinned === void 0 ? {} : { contextWindow: pinned, contextWindowKnown: true },
440
+ ...images === void 0 ? {} : { supportsImages: images }
441
+ }));
274
442
  log("INFO", "local-models", `Probed ${endpoint.label}`, {
275
443
  baseUrl: endpoint.baseUrl,
276
444
  models: String(models.length)
@@ -281,10 +449,22 @@ async function enrich(endpoint, entries, options) {
281
449
  if (endpoint.kind === "lmstudio") return enrichLmStudio(endpoint, entries, options);
282
450
  if (endpoint.kind === "ollama") return enrichOllama(endpoint, entries, options);
283
451
  if (endpoint.kind === "llamacpp") return enrichLlamaCpp(endpoint, entries, options);
452
+ if (endpoint.kind === "custom") return enrichCustom(endpoint, entries, options);
284
453
  return entries.map((entry) => genericModel(endpoint, entry));
285
454
  }
455
+ async function enrichCustom(endpoint, entries, options) {
456
+ const generic = entries.map((entry) => genericModel(endpoint, entry));
457
+ if (generic.every((model) => model.contextWindowKnown)) return generic;
458
+ const root = endpointRoot(endpoint.baseUrl);
459
+ const props = await fetchJson(`${root}/props`, endpoint, options);
460
+ const nCtx = contextLength(props?.default_generation_settings?.n_ctx);
461
+ if (nCtx !== void 0) return llamaCppModels(endpoint, entries, nCtx, props);
462
+ const lmStudio = await fetchJson(`${root}/api/v1/models`, endpoint, options);
463
+ if (Array.isArray(lmStudio?.models)) return enrichLmStudio(endpoint, entries, options, lmStudio);
464
+ return generic;
465
+ }
286
466
  function genericModel(endpoint, entry) {
287
- const declared = contextLength(entry.max_model_len);
467
+ const declared = contextLength(entry.max_model_len) ?? contextLength(entry.context_length) ?? contextLength(entry.meta?.n_ctx);
288
468
  return {
289
469
  rawId: entry.id,
290
470
  endpointId: endpoint.id,
@@ -311,9 +491,7 @@ async function enrichOllama(endpoint, entries, options) {
311
491
  });
312
492
  const caps = Array.isArray(show?.capabilities) ? show.capabilities : [];
313
493
  if (caps.includes("embedding") && !caps.includes("completion")) return void 0;
314
- const ctx = contextLength(
315
- runningModels.find((model) => model?.name === entry.id || model?.model === entry.id)?.context_length
316
- );
494
+ const ctx = runningContext(runningModels, entry.id) ?? modelfileNumCtx(show?.parameters);
317
495
  return {
318
496
  rawId: entry.id,
319
497
  endpointId: endpoint.id,
@@ -328,12 +506,41 @@ async function enrichOllama(endpoint, entries, options) {
328
506
  });
329
507
  return enriched.filter((model) => model !== void 0);
330
508
  }
509
+ function runningContext(models, rawId) {
510
+ return contextLength(
511
+ models.find((model) => model?.name === rawId || model?.model === rawId)?.context_length
512
+ );
513
+ }
514
+ function modelfileNumCtx(parameters) {
515
+ const match = /^num_ctx\s+(\d+)\s*$/m.exec(parameters ?? "");
516
+ return match ? contextLength(Number(match[1])) : void 0;
517
+ }
518
+ async function ollamaServedContext(endpoint, rawId, {
519
+ load = false,
520
+ timeoutMs = 12e4,
521
+ signal
522
+ } = {}) {
523
+ const root = endpointRoot(endpoint.baseUrl);
524
+ if (load) {
525
+ await fetchJson(`${root}/api/generate`, endpoint, {
526
+ timeoutMs,
527
+ signal,
528
+ method: "POST",
529
+ body: { model: rawId }
530
+ });
531
+ }
532
+ const running = await fetchJson(`${root}/api/ps`, endpoint, {
533
+ timeoutMs: DEFAULT_PROBE_TIMEOUT_MS,
534
+ signal
535
+ });
536
+ return runningContext(Array.isArray(running?.models) ? running.models : [], rawId);
537
+ }
331
538
  function contextLength(value) {
332
539
  return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : void 0;
333
540
  }
334
- async function enrichLmStudio(endpoint, entries, options) {
541
+ async function enrichLmStudio(endpoint, entries, options, fetched) {
335
542
  const root = endpointRoot(endpoint.baseUrl);
336
- const detail = await fetchJson(`${root}/api/v1/models`, endpoint, options);
543
+ const detail = fetched ?? await fetchJson(`${root}/api/v1/models`, endpoint, options);
337
544
  const byId = /* @__PURE__ */ new Map();
338
545
  if (Array.isArray(detail?.models)) {
339
546
  for (const model of detail.models) {
@@ -391,12 +598,19 @@ async function enrichLlamaCpp(endpoint, entries, options) {
391
598
  endpoint,
392
599
  options
393
600
  );
394
- const nCtx = contextLength(props?.default_generation_settings?.n_ctx);
395
- const known = nCtx !== void 0;
601
+ return llamaCppModels(
602
+ endpoint,
603
+ entries,
604
+ contextLength(props?.default_generation_settings?.n_ctx),
605
+ props
606
+ );
607
+ }
608
+ function llamaCppModels(endpoint, entries, nCtx, props) {
396
609
  return entries.map((entry) => ({
397
610
  ...genericModel(endpoint, entry),
398
- contextWindow: known ? nCtx : FALLBACK_CONTEXT_WINDOW,
399
- contextWindowKnown: known
611
+ contextWindow: nCtx ?? FALLBACK_CONTEXT_WINDOW,
612
+ contextWindowKnown: nCtx !== void 0,
613
+ supportsImages: props?.modalities?.vision === true
400
614
  }));
401
615
  }
402
616
  async function mapLimited(items, limit, fn) {
@@ -432,7 +646,7 @@ function toModelInfo(model, endpoint) {
432
646
  }
433
647
  var cache;
434
648
  function cacheKey(endpoints) {
435
- return endpoints.map((e) => `${e.id}@${e.baseUrl}`).join("|");
649
+ return endpoints.map((e) => `${e.id}@${e.baseUrl}#${e.contextLength ?? ""}#${e.supportsImages ?? ""}`).join("|");
436
650
  }
437
651
  async function discoverLocalModels(endpoints = DEFAULT_LOCAL_ENDPOINTS, options = {}) {
438
652
  const key = cacheKey(endpoints);
@@ -461,18 +675,131 @@ function findProbedModel(probes, modelId) {
461
675
  return void 0;
462
676
  }
463
677
 
678
+ // src/point-scale.ts
679
+ var NORM1000_PATTERN = /qwen3[-_.]?vl|qwen3[._]?[56](?![\d])/i;
680
+ function pointScale(modelId) {
681
+ return NORM1000_PATTERN.test(modelId) ? "norm1000" : "pixels";
682
+ }
683
+
684
+ // src/claude-code/usage.ts
685
+ import fsp from "fs/promises";
686
+ import path from "path";
687
+ var USAGE_FILE = "usage.json";
688
+ var WINDOWS = {
689
+ five_hour: { kind: "current", label: "5-hour" },
690
+ seven_day: { kind: "weekly", label: "Weekly" }
691
+ };
692
+ function finite(value) {
693
+ return typeof value === "number" && Number.isFinite(value) ? value : void 0;
694
+ }
695
+ function toWindow(key, raw) {
696
+ const shape = WINDOWS[key];
697
+ const fraction = finite(raw?.utilization);
698
+ if (!shape || fraction === void 0) return null;
699
+ const resetsAt = finite(raw?.resetsAt);
700
+ return {
701
+ ...shape,
702
+ usedPercent: Math.min(100, Math.max(0, fraction * 100)),
703
+ ...resetsAt !== void 0 ? { resetsAt: resetsAt * 1e3 } : {}
704
+ };
705
+ }
706
+ function mergeClaudeCodeRateLimit(info, previous, now = Date.now()) {
707
+ const reported = info.unifiedWindows ? Object.entries(info.unifiedWindows).map(([key, raw]) => toWindow(key, raw)) : info.rateLimitType ? [toWindow(info.rateLimitType, info)] : [];
708
+ const byKind = new Map(previous?.windows.map((w) => [w.kind, w]) ?? []);
709
+ for (const window of reported) if (window) byKind.set(window.kind, window);
710
+ const windows = [...byKind.values()].sort(
711
+ (a, b) => a.kind === b.kind ? 0 : a.kind === "current" ? -1 : 1
712
+ );
713
+ return { provider: "anthropic", displayName: "Anthropic", windows, fetchedAt: now };
714
+ }
715
+ function usagePath(opts) {
716
+ return path.join(claudeCodeHome(opts), USAGE_FILE);
717
+ }
718
+ async function readClaudeCodeUsage(opts = {}) {
719
+ let parsed;
720
+ try {
721
+ parsed = JSON.parse(await fsp.readFile(usagePath(opts), "utf8"));
722
+ } catch {
723
+ return null;
724
+ }
725
+ if (!Array.isArray(parsed?.windows) || typeof parsed.fetchedAt !== "number") return null;
726
+ const now = opts.now ?? Date.now();
727
+ const windows = parsed.windows.filter(
728
+ (w) => (w.kind === "current" || w.kind === "weekly") && typeof w.usedPercent === "number" && (w.resetsAt === void 0 || w.resetsAt > now)
729
+ );
730
+ return { provider: "anthropic", displayName: "Anthropic", windows, fetchedAt: parsed.fetchedAt };
731
+ }
732
+ var writeQueue = Promise.resolve();
733
+ function recordClaudeCodeRateLimit(info, opts = {}) {
734
+ const write = async () => {
735
+ const now = opts.now ?? Date.now();
736
+ const next = mergeClaudeCodeRateLimit(info, await readClaudeCodeUsage({ ...opts, now }), now);
737
+ if (next.windows.length === 0) return;
738
+ const file = usagePath(opts);
739
+ await fsp.mkdir(path.dirname(file), { recursive: true });
740
+ await fsp.writeFile(file, JSON.stringify(next), "utf8");
741
+ };
742
+ writeQueue = writeQueue.then(write).catch(() => {
743
+ });
744
+ return writeQueue;
745
+ }
746
+ async function clearClaudeCodeUsage(opts = {}) {
747
+ await writeQueue;
748
+ await fsp.rm(usagePath(opts), { force: true }).catch(() => {
749
+ });
750
+ }
751
+
752
+ // src/claude-code/sign-in.ts
753
+ async function signInWithClaudeCode(auth, callbacks, opts = {}) {
754
+ if (!opts.binary && !resolveClaudeCodeBinary(opts)) {
755
+ callbacks.onStatus("Downloading Claude Code (one time)\u2026");
756
+ await ensureClaudeCodeBinary({
757
+ ...opts,
758
+ onProgress: (progress) => {
759
+ callbacks.onStatus(formatClaudeCodeInstallProgress(progress));
760
+ opts.onProgress?.(progress);
761
+ }
762
+ });
763
+ }
764
+ let status = await claudeCodeAuthStatus(opts);
765
+ if (!status.loggedIn) {
766
+ callbacks.onStatus("Opening Claude sign-in\u2026");
767
+ await loginClaudeCode(callbacks, opts);
768
+ status = await claudeCodeAuthStatus(opts);
769
+ }
770
+ if (!status.loggedIn) throw new Error("Claude sign-in didn't finish. Try again.");
771
+ await auth.setClaudeCodeLogin();
772
+ return status;
773
+ }
774
+ async function signOutOfClaudeCode(auth, opts = {}) {
775
+ await auth.clearClaudeCodeLogin();
776
+ await clearClaudeCodeUsage(opts);
777
+ try {
778
+ await logoutClaudeCode(opts);
779
+ } catch (err) {
780
+ log(
781
+ "WARN",
782
+ "auth",
783
+ `claude auth logout failed: ${err instanceof Error ? err.message : String(err)}`
784
+ );
785
+ }
786
+ }
787
+
464
788
  // src/auth-providers.ts
465
- var AUTH_PROVIDERS = [
789
+ function apiKeyDetails(label, billing, when = "") {
790
+ return { apikey: { method: "apikey", label, billing, when } };
791
+ }
792
+ var ALL_AUTH_PROVIDERS = [
466
793
  {
467
794
  value: "anthropic",
468
795
  label: "Anthropic",
469
- description: "Claude Fable 5.1, Opus 5.5, Opus 5.5 Fast, Sonnet 5.5, Haiku 5.5",
796
+ description: "Claude Fable 5.2, Fable 5.2 Fast, Opus 5.5, Opus 5.5 Fast, Sonnet 5.5, Haiku 5.5",
470
797
  methods: ["oauth"]
471
798
  },
472
799
  {
473
800
  value: "openai",
474
801
  label: "OpenAI",
475
- description: "GPT-6 Astra, GPT-6 Astra Fast, GPT-6.1 Sol, GPT-6.1 Sol Fast, GPT-6 Luna, GPT-6 Luna Fast",
802
+ description: "GPT-6.2 Astra, GPT-6.2 Astra Fast, GPT-6.2 Sol, GPT-6.2 Sol Fast, GPT-6.1 Terra, GPT-6.1 Terra Fast, GPT-6 Luna, GPT-6 Luna Fast",
476
803
  methods: ["oauth"]
477
804
  },
478
805
  {
@@ -553,7 +880,7 @@ var AUTH_PROVIDERS = [
553
880
  {
554
881
  value: "minimax",
555
882
  label: "MiniMax",
556
- description: "MiniMax M3",
883
+ description: "MiniMax M3.1 Flash, M3",
557
884
  methods: ["apikey"],
558
885
  apiKeyLabel: "MiniMax"
559
886
  },
@@ -591,6 +918,30 @@ var AUTH_PROVIDERS = [
591
918
  methods: ["apikey"],
592
919
  apiKeyLabel: "Sakana"
593
920
  },
921
+ {
922
+ value: "opencode-go",
923
+ label: "OpenCode Go",
924
+ description: "Kimi K3, GLM-5.3, GLM-5.3-Flash and more Go models",
925
+ methods: ["apikey"],
926
+ apiKeyLabel: "OpenCode",
927
+ methodDetails: apiKeyDetails(
928
+ "OpenCode API key",
929
+ "Uses your OpenCode Go subscription.",
930
+ "Create a personal API key in the OpenCode Console, in a workspace subscribed to Go."
931
+ )
932
+ },
933
+ {
934
+ value: "opencode",
935
+ label: "OpenCode",
936
+ description: "Kimi K3, GLM-5.3, GLM-5.3-Flash and more paid Console models",
937
+ methods: ["apikey"],
938
+ apiKeyLabel: "OpenCode",
939
+ methodDetails: apiKeyDetails(
940
+ "OpenCode API key",
941
+ "Pay-per-token from your OpenCode Console credits.",
942
+ "Free-tier models only run inside OpenCode, so they are not listed here."
943
+ )
944
+ },
594
945
  {
595
946
  value: "openrouter",
596
947
  label: "OpenRouter",
@@ -606,6 +957,9 @@ var AUTH_PROVIDERS = [
606
957
  apiKeyLabel: "Hugging Face"
607
958
  }
608
959
  ];
960
+ var AUTH_PROVIDERS = ALL_AUTH_PROVIDERS.filter(
961
+ (p) => !isHiddenProvider(p.value)
962
+ );
609
963
  function getAuthProvider(value) {
610
964
  return AUTH_PROVIDERS.find((p) => p.value === value);
611
965
  }
@@ -1206,7 +1560,7 @@ async function transcribeVoice(fileUrl) {
1206
1560
  // src/auto-update.ts
1207
1561
  import { spawn } from "child_process";
1208
1562
  import fs from "fs";
1209
- import path from "path";
1563
+ import path2 from "path";
1210
1564
  var CHECK_INTERVAL_MS = 60 * 60 * 1e3;
1211
1565
  var FETCH_TIMEOUT_MS = 1e4;
1212
1566
  function compareVersions(a, b) {
@@ -1248,7 +1602,7 @@ function createAutoUpdater(config) {
1248
1602
  function writeState(state) {
1249
1603
  try {
1250
1604
  const filePath = stateFilePath();
1251
- fs.mkdirSync(path.dirname(filePath), { recursive: true, mode: 448 });
1605
+ fs.mkdirSync(path2.dirname(filePath), { recursive: true, mode: 448 });
1252
1606
  fs.writeFileSync(filePath, JSON.stringify(state));
1253
1607
  } catch {
1254
1608
  }
@@ -1374,38 +1728,60 @@ function createAutoUpdater(config) {
1374
1728
  export {
1375
1729
  AUTH_PROVIDERS,
1376
1730
  AuthStorage,
1731
+ CLAUDE_CODE_AUTH_KEY,
1732
+ CLAUDE_CODE_AUTH_MARKER,
1733
+ CLAUDE_CODE_MANIFEST,
1377
1734
  DEFAULT_LOCAL_ENDPOINTS,
1378
1735
  DEFAULT_MAX_VIDEO_BYTES,
1379
1736
  FALLBACK_CONTEXT_WINDOW,
1380
1737
  GEMINI_API_KEY,
1381
1738
  GEMINI_API_KEY_BASE_URL,
1739
+ HIDDEN_PROVIDERS,
1382
1740
  LOCAL_API_KEY_PLACEHOLDER,
1383
1741
  LOCAL_AUTH_KEY_PREFIX,
1742
+ MINIMAX_CN_BASE_URL,
1743
+ MINIMAX_GLOBAL_BASE_URL,
1384
1744
  MODELS,
1385
1745
  MOONSHOT_OAUTH_KEY,
1386
1746
  NotLoggedInError,
1747
+ OPENCODE_CATALOG_URLS,
1748
+ OPENCODE_PROVIDERS,
1749
+ OPENROUTER_DEFAULT_BASE_URL,
1387
1750
  PLAN_MODE_THINKING_CAP,
1388
1751
  SubscriptionUsageError,
1389
1752
  TelegramBot,
1390
1753
  XAI_OAUTH_KEY,
1391
1754
  XIAOMI_CREDITS_KEY,
1755
+ XIAOMI_TOKEN_PLAN_BASE_URLS,
1392
1756
  authPriorityNote,
1393
1757
  clampThinkingForPlanMode,
1758
+ claudeCodeAuthStatus,
1759
+ claudeCodeBinaryPath,
1760
+ claudeCodeCallbackUrl,
1761
+ claudeCodeConfigDir,
1762
+ claudeCodeEnv,
1763
+ claudeCodeHome,
1764
+ claudeCodePlatformKey,
1765
+ clearClaudeCodeUsage,
1394
1766
  clearLocalDiscoveryCache,
1395
1767
  clearRuntimeModels,
1396
1768
  closeLogger,
1397
- compareClaudeCodeVersions,
1398
1769
  createAutoUpdater,
1399
1770
  decodeOggOpus,
1400
1771
  describeAuthMethods,
1772
+ detectMiniMaxBaseUrl,
1773
+ detectXiaomiTokenPlanBaseUrl,
1401
1774
  discoverLocalModels,
1402
1775
  downmixToMono,
1403
1776
  dualAuthProvider,
1404
1777
  dualAuthProviderByOAuthKey,
1405
1778
  endpointRoot,
1779
+ ensureClaudeCodeBinary,
1406
1780
  fetchSubscriptionUsage,
1407
1781
  findProbedModel,
1782
+ formatClaudeCodeInstallProgress,
1408
1783
  formatLocalModelId,
1784
+ formatOpenCodeModelId,
1409
1785
  generatePKCE,
1410
1786
  getAllModels,
1411
1787
  getAppPaths,
@@ -1417,11 +1793,13 @@ export {
1417
1793
  getContextWindow,
1418
1794
  getDefaultModel,
1419
1795
  getDefaultThinkingLevel,
1796
+ getListedModels,
1420
1797
  getLowestThinkingLevel,
1421
1798
  getMaxThinkingLevel,
1422
1799
  getModel,
1423
1800
  getModelsForProvider,
1424
1801
  getNextThinkingLevel,
1802
+ getProviderCatalog,
1425
1803
  getSessionId,
1426
1804
  getSummaryModel,
1427
1805
  getSupportedThinkingLevels,
@@ -1429,8 +1807,11 @@ export {
1429
1807
  getVideoByteLimit,
1430
1808
  grokCliBaseUrl,
1431
1809
  grokCliHeaders,
1810
+ isClaudeCodeAuthMarker,
1432
1811
  isGrokCliEndpoint,
1812
+ isHiddenProvider,
1433
1813
  isKimiCodingEndpoint,
1814
+ isLegacyClaudeOAuth,
1434
1815
  isLocalModelId,
1435
1816
  isLoggerOpen,
1436
1817
  isModelLoaded,
@@ -1439,19 +1820,29 @@ export {
1439
1820
  kimiCodeBaseUrl,
1440
1821
  kimiCodingHeaders,
1441
1822
  localAuthStorageKey,
1823
+ localModelShortName,
1442
1824
  log,
1443
1825
  loginAnthropic,
1826
+ loginClaudeCode,
1444
1827
  loginGemini,
1445
1828
  loginKimi,
1446
1829
  loginOpenAI,
1447
1830
  loginXai,
1831
+ logoutClaudeCode,
1832
+ mergeClaudeCodeRateLimit,
1448
1833
  oauthStorageKey,
1834
+ ollamaServedContext,
1449
1835
  openLog,
1450
1836
  parseLocalModelId,
1837
+ parseOpenCodeCatalog,
1838
+ parseOpenRouterCatalog,
1839
+ pendingClaudeCodeVersionRefresh,
1840
+ pointScale,
1451
1841
  probeEndpoint,
1452
1842
  providerStorageKeys,
1843
+ readClaudeCodeUsage,
1453
1844
  readStoredBaseUrlSync,
1454
- recordRequiredClaudeCodeVersion,
1845
+ recordClaudeCodeRateLimit,
1455
1846
  refreshAnthropicToken,
1456
1847
  refreshGeminiToken,
1457
1848
  refreshKimiToken,
@@ -1460,7 +1851,11 @@ export {
1460
1851
  registerLogCleanup,
1461
1852
  registerRuntimeModels,
1462
1853
  resample,
1854
+ resolveClaudeCodeBinary,
1463
1855
  setProgressCallback,
1856
+ setProviderCatalog,
1857
+ signInWithClaudeCode,
1858
+ signOutOfClaudeCode,
1464
1859
  toModelInfo,
1465
1860
  transcribeVoice,
1466
1861
  usesOpenAICodexTransport,