@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.d.ts CHANGED
@@ -1,8 +1,47 @@
1
1
  import { ModelInfo } from './model-registry.js';
2
- export { ContextWindowOptions, DEFAULT_MAX_VIDEO_BYTES, MODELS, ModelBilling, clearRuntimeModels, getAllModels, getAuthStorageKey, getAuthStorageKeys, getContextWindow, getDefaultModel, getDefaultThinkingLevel, getMaxThinkingLevel, getModel, getModelsForProvider, getSummaryModel, getToolResultCharLimit, getVideoByteLimit, isPaidModel, registerRuntimeModels, usesOpenAICodexTransport, withoutPaidTier } from './model-registry.js';
2
+ export { ContextWindowOptions, DEFAULT_MAX_VIDEO_BYTES, HIDDEN_PROVIDERS, MODELS, ModelBilling, clearRuntimeModels, getAllModels, getAuthStorageKey, getAuthStorageKeys, getContextWindow, getDefaultModel, getDefaultThinkingLevel, getListedModels, getMaxThinkingLevel, getModel, getModelsForProvider, getProviderCatalog, getSummaryModel, getToolResultCharLimit, getVideoByteLimit, isHiddenProvider, isPaidModel, registerRuntimeModels, setProviderCatalog, usesOpenAICodexTransport, withoutPaidTier } from './model-registry.js';
3
3
  import { ThinkingLevel, Provider } from '@prestyj/ai';
4
+ export { getClaudeCliUserAgent, getClaudeCodeVersion, pendingClaudeCodeVersionRefresh } from '@prestyj/ai';
4
5
  export { AppPaths, getAppPaths } from './paths.js';
5
6
 
7
+ /** @prestyj/ai's OPENROUTER_BASE_URL — where the openrouter transport goes with no override. */
8
+ declare const OPENROUTER_DEFAULT_BASE_URL = "https://openrouter.ai/api/v1";
9
+ interface ParsedOpenRouterCatalog {
10
+ models: ModelInfo[];
11
+ /** Rows dropped because they can't call tools (the agent needs tools) or are malformed. */
12
+ skipped: number;
13
+ }
14
+ /**
15
+ * Turn an OpenRouter-style `/models` body into registry rows. Field mapping is
16
+ * the live schema: tools from `supported_parameters`, image input from
17
+ * `architecture.input_modalities`, the effort ladder from
18
+ * `reasoning.supported_efforts`, output cap from `top_provider`.
19
+ */
20
+ declare function parseOpenRouterCatalog(body: unknown): ParsedOpenRouterCatalog;
21
+
22
+ /** The two OpenCode Console plans, each with its own endpoint and model list. */
23
+ type OpenCodeProvider = "opencode" | "opencode-go";
24
+ declare const OPENCODE_PROVIDERS: readonly OpenCodeProvider[];
25
+ /** Where each plan publishes its model list. Public: the list needs no key. */
26
+ declare const OPENCODE_CATALOG_URLS: Record<OpenCodeProvider, string>;
27
+ interface ParsedOpenCodeCatalog {
28
+ models: ModelInfo[];
29
+ /** Rows dropped: not served on Chat Completions, no tool calling, free tier, or malformed. */
30
+ skipped: number;
31
+ }
32
+ /** The registry id of a Console model: the plan's provider id, then the gateway's id. */
33
+ declare function formatOpenCodeModelId(provider: OpenCodeProvider, rawId: string): string;
34
+ /**
35
+ * Turn a Console `/v1/models` body into registry rows for one plan. Only models
36
+ * the gateway serves on Chat Completions are listed, since that is the one API
37
+ * @prestyj/ai sends OpenCode requests to: a Responses, Messages or Gemini model
38
+ * called there has failed for other clients (HTTP 500, "Model does not support
39
+ * this protocol"). Pay-as-you-go also drops the free tier: the gateway answers
40
+ * HTTP 403 for those models from any client but OpenCode itself. Go keeps its
41
+ * free models, which the subscription covers.
42
+ */
43
+ declare function parseOpenCodeCatalog(provider: OpenCodeProvider, body: unknown): ParsedOpenCodeCatalog;
44
+
6
45
  declare function getSupportedThinkingLevels(provider: Provider, model: string): readonly ThinkingLevel[];
7
46
  /**
8
47
  * The lowest effort `model` accepts — the first rung of its ladder, never
@@ -26,23 +65,6 @@ declare const PLAN_MODE_THINKING_CAP: ThinkingLevel;
26
65
  * `undefined` (thinking off) and already-low levels. */
27
66
  declare function clampThinkingForPlanMode(level: ThinkingLevel | undefined): ThinkingLevel | undefined;
28
67
 
29
- /**
30
- * Local model discovery — Ollama, LM Studio, llama.cpp (`llama-server`), vLLM,
31
- * and any other OpenAI-compatible server the user points us at.
32
- *
33
- * Everything rides the OpenAI-compatible `/v1` transport (see the `local`
34
- * provider in @prestyj/ai's stream.ts); the only per-server difference is where the
35
- * *capabilities* come from, because `GET /v1/models` reports nothing useful:
36
- *
37
- * - Ollama → `/api/show` + `/api/ps` → capabilities + running context
38
- * - LM Studio → `/api/v1/models` (v0 fallback) → capabilities + loaded context
39
- * - llama.cpp → `GET /props` → `default_generation_settings.n_ctx`
40
- * - vLLM/other → nothing; `max_model_len` sometimes rides the model object.
41
- *
42
- * Probing never throws: an unreachable server is a normal state (the user just
43
- * doesn't have it running), not an error to surface.
44
- */
45
-
46
68
  /** Which capability API a local endpoint speaks, beyond plain `/v1/models`. */
47
69
  type LocalEndpointKind = "ollama" | "lmstudio" | "llamacpp" | "vllm" | "custom";
48
70
  interface LocalEndpoint {
@@ -56,6 +78,10 @@ interface LocalEndpoint {
56
78
  apiKey?: string;
57
79
  /** True for endpoints the user added by hand (removable). */
58
80
  custom?: boolean;
81
+ /** User-pinned context window; wins over whatever the server reports. */
82
+ contextLength?: number;
83
+ /** User-pinned image support (vLLM and most gateways never report it); wins over the server. */
84
+ supportsImages?: boolean;
59
85
  }
60
86
  /** One model as reported (and enriched) by a local server. */
61
87
  interface LocalModel {
@@ -90,7 +116,7 @@ declare const DEFAULT_LOCAL_ENDPOINTS: readonly LocalEndpoint[];
90
116
  * auto-compaction already sailed past, while under-guessing only compacts early.
91
117
  */
92
118
  declare const FALLBACK_CONTEXT_WINDOW = 4096;
93
- /** Placeholder token for endpoints with no key — these servers ignore it. */
119
+ /** Token stored for endpoints with no key; never sent on the wire. */
94
120
  declare const LOCAL_API_KEY_PLACEHOLDER = "local";
95
121
  /**
96
122
  * `local/<endpointId>/<rawModelId>`. The raw id can itself contain slashes
@@ -101,6 +127,11 @@ declare function parseLocalModelId(id: string): {
101
127
  endpointId: string;
102
128
  rawId: string;
103
129
  } | undefined;
130
+ /**
131
+ * The model's own name, for a UI that shows the endpoint separately: the last
132
+ * segment of the raw id, so `minimax/minimax-m2:free` reads `minimax-m2:free`.
133
+ */
134
+ declare function localModelShortName(rawId: string): string;
104
135
  declare function isLocalModelId(id: string): boolean;
105
136
  /** Auth-storage key holding the credential (and baseUrl) for one local endpoint. */
106
137
  declare function localAuthStorageKey(endpointId: string): string;
@@ -116,6 +147,17 @@ interface ProbeOptions {
116
147
  * error toast.
117
148
  */
118
149
  declare function probeEndpoint(endpoint: LocalEndpoint, { timeoutMs, signal }?: ProbeOptions): Promise<LocalEndpointProbe>;
150
+ /**
151
+ * The context Ollama serves `rawId` with, read from `/api/ps`. With `load`, first
152
+ * loads the model the way a chat request would (default options), since an
153
+ * unloaded model's size is only decided at load time: the OpenAI endpoint
154
+ * ignores `num_ctx`, so this is the window the agent will really get.
155
+ */
156
+ declare function ollamaServedContext(endpoint: LocalEndpoint, rawId: string, { load, timeoutMs, signal, }?: {
157
+ load?: boolean;
158
+ timeoutMs?: number;
159
+ signal?: AbortSignal;
160
+ }): Promise<number | undefined>;
119
161
  /** Convert a probed local model into the registry shape the whole app speaks. */
120
162
  declare function toModelInfo(model: LocalModel, endpoint: LocalEndpoint): ModelInfo;
121
163
  interface DiscoveryResult {
@@ -141,6 +183,14 @@ declare function findProbedModel(probes: readonly LocalEndpointProbe[], modelId:
141
183
  endpoint: LocalEndpoint;
142
184
  } | undefined;
143
185
 
186
+ /** How a vision model writes screen coordinates when asked to point at something. */
187
+ type PointScale = "pixels" | "norm1000";
188
+ /**
189
+ * The coordinate scale a model answers in, from its id. Works on bare ids (`qwen3-vl:8b`),
190
+ * local ids (`local/lmstudio/qwen/qwen3.5-27b`) and OpenRouter ids (`qwen/qwen3-vl-32b-instruct`).
191
+ */
192
+ declare function pointScale(modelId: string): PointScale;
193
+
144
194
  type LogLevel = "INFO" | "ERROR" | "WARN" | "DEBUG";
145
195
  /**
146
196
  * Open the debug log in append mode, tagging this process with a session id and
@@ -176,42 +226,6 @@ declare function closeLogger(opts?: {
176
226
  */
177
227
  declare function withFileLock<T>(filePath: string, fn: () => Promise<T>): Promise<T>;
178
228
 
179
- /**
180
- * Compare two dotted version strings numerically.
181
- *
182
- * Returns >0 when `a` is newer, <0 when older, 0 when equal. Segment-wise
183
- * numeric comparison matters here: Claude Code is deep into 2.1.x, where a
184
- * lexical compare puts "2.1.9" above "2.1.280" and would happily serve a UA
185
- * that Anthropic rejects.
186
- */
187
- declare function compareClaudeCodeVersions(a: string, b: string): number;
188
- /**
189
- * Resolve the current Claude Code release version for spoofing the claude-cli
190
- * User-Agent on OAuth and inference requests.
191
- *
192
- * A cached value under an hour old is served straight away. An older one is
193
- * still served immediately — the hot path never waits on npm — but triggers a
194
- * background refresh, so a client-version gate on a newly released model costs
195
- * at most one request instead of a full day of lockout. Past 24h the cache is
196
- * refreshed synchronously, and only falls back to the stale value (then the
197
- * bundled constant) if npm cannot be reached at all.
198
- */
199
- declare function getClaudeCodeVersion(): Promise<string>;
200
- /**
201
- * Learn the minimum client version from a provider rejection.
202
- *
203
- * Anthropic gates newly released models on a minimum Claude Code version and
204
- * names it in the error ("version 2.1.280 or newer is required"). That message
205
- * is authoritative — more current than the npm registry can be at launch — so
206
- * we pin it as a floor, persist it, and drop the memoised value. The next
207
- * request builds its User-Agent from the floor and succeeds.
208
- *
209
- * Returns the newly applied floor, or null when the error is unrelated.
210
- */
211
- declare function recordRequiredClaudeCodeVersion(message: string): string | null;
212
- /** Build the User-Agent string Anthropic's OAuth + inference edges expect. */
213
- declare function getClaudeCliUserAgent(): Promise<string>;
214
-
215
229
  interface OAuthCredentials {
216
230
  accessToken: string;
217
231
  refreshToken: string;
@@ -244,6 +258,99 @@ interface OAuthLoginCallbacks {
244
258
  onStatus: (message: string) => void;
245
259
  }
246
260
 
261
+ interface ClaudeCodePlatformAsset {
262
+ url: string;
263
+ /** npm `dist.integrity`: "sha512-<base64>". */
264
+ integrity: string;
265
+ bin: string;
266
+ }
267
+ interface ClaudeCodeManifest {
268
+ sdkVersion: string;
269
+ claudeCodeVersion: string;
270
+ platforms: Record<string, ClaudeCodePlatformAsset>;
271
+ }
272
+ declare const CLAUDE_CODE_MANIFEST: ClaudeCodeManifest;
273
+ /** auth.json key for "signed in with Claude through Claude Code". Holds only the marker. */
274
+ declare const CLAUDE_CODE_AUTH_KEY = "anthropic-claude-code";
275
+ declare const CLAUDE_CODE_AUTH_MARKER: {
276
+ readonly via: "claude-code";
277
+ };
278
+ declare function isClaudeCodeAuthMarker(value: unknown): boolean;
279
+ /** An old EZ Coder Claude sign-in token (`sk-ant-oat…`). It no longer works; the user must sign in again. */
280
+ declare function isLegacyClaudeOAuth(value: unknown): boolean;
281
+ type ClaudeCodeInstallProgress = {
282
+ phase: "download";
283
+ receivedBytes: number;
284
+ totalBytes?: number;
285
+ } | {
286
+ phase: "verify";
287
+ } | {
288
+ phase: "extract";
289
+ };
290
+ interface ClaudeCodeRuntimeOptions {
291
+ /** Defaults to `~/.ezcoder/claude-code`. */
292
+ home?: string;
293
+ manifest?: ClaudeCodeManifest;
294
+ /** Platform key in the manifest; detected from the running process by default. */
295
+ platformKey?: string;
296
+ }
297
+ interface EnsureClaudeCodeOptions extends ClaudeCodeRuntimeOptions {
298
+ onProgress?: (progress: ClaudeCodeInstallProgress) => void;
299
+ signal?: AbortSignal;
300
+ fetch?: typeof fetch;
301
+ }
302
+ interface ClaudeCodeRunOptions extends ClaudeCodeRuntimeOptions {
303
+ /** Executable to run instead of the installed binary (tests). */
304
+ binary?: string;
305
+ /** Arguments placed before the `auth …` arguments (tests run a script via node). */
306
+ binaryArgs?: string[];
307
+ signal?: AbortSignal;
308
+ /** How long sign-in waits for the browser URL before falling back to the paste-code page. */
309
+ browserWaitMs?: number;
310
+ }
311
+ interface ClaudeCodeAuthStatus {
312
+ loggedIn: boolean;
313
+ /** "claude.ai" for a Claude subscription. */
314
+ authMethod?: string;
315
+ email?: string;
316
+ subscriptionType?: string;
317
+ }
318
+ interface PlatformInfo {
319
+ platform: NodeJS.Platform;
320
+ arch: string;
321
+ musl: boolean;
322
+ }
323
+ /** Manifest key for a platform, or null where Claude Code has no build. */
324
+ declare function claudeCodePlatformKey(info?: PlatformInfo): string | null;
325
+ declare function claudeCodeHome(opts?: ClaudeCodeRuntimeOptions): string;
326
+ declare function claudeCodeConfigDir(opts?: ClaudeCodeRuntimeOptions): string;
327
+ /** Where the pinned binary lives once installed (it may not exist yet). */
328
+ declare function claudeCodeBinaryPath(opts?: ClaudeCodeRuntimeOptions): string;
329
+ /** The installed binary for the pinned version, or null when it still needs downloading. */
330
+ declare function resolveClaudeCodeBinary(opts?: ClaudeCodeRuntimeOptions): string | null;
331
+ /**
332
+ * Download, verify and unpack the pinned Claude Code binary if it isn't
333
+ * installed yet. Concurrent callers in this process share one download;
334
+ * other processes race safely because each unpacks into its own staging dir
335
+ * and only one rename wins.
336
+ */
337
+ declare function ensureClaudeCodeBinary(opts?: EnsureClaudeCodeOptions): Promise<string>;
338
+ /** Plain-language status line for an install progress event. */
339
+ declare function formatClaudeCodeInstallProgress(progress: ClaudeCodeInstallProgress): string;
340
+ /** Environment for every Claude Code process EZ Coder starts: our own login, no stray keys. */
341
+ declare function claudeCodeEnv(opts?: ClaudeCodeRuntimeOptions, base?: NodeJS.ProcessEnv): Record<string, string>;
342
+ /** `claude auth status` for EZ Coder's own login. Logged out when the binary is missing. */
343
+ declare function claudeCodeAuthStatus(opts?: ClaudeCodeRunOptions): Promise<ClaudeCodeAuthStatus>;
344
+ declare function logoutClaudeCode(opts?: ClaudeCodeRunOptions): Promise<void>;
345
+ /** The browser sign-in URL with Claude Code's localhost callback instead of the paste-code page. */
346
+ declare function claudeCodeCallbackUrl(manualUrl: string, captured: string): string | null;
347
+ /**
348
+ * Run `claude auth login` for EZ Coder's own Claude login. The browser URL goes
349
+ * to `onOpenUrl`; Claude Code's localhost callback finishes sign-in, and a
350
+ * pasted code (from the fallback page) is accepted too.
351
+ */
352
+ declare function loginClaudeCode(callbacks: OAuthLoginCallbacks, opts?: ClaudeCodeRunOptions): Promise<void>;
353
+
247
354
  /**
248
355
  * Storage key for Kimi Code OAuth credentials. Kept distinct from the
249
356
  * `moonshot` API-key entry so a user can configure BOTH and we always
@@ -340,7 +447,12 @@ declare class AuthStorage {
340
447
  private snapshotIno;
341
448
  /** Per-provider lock to serialize concurrent refresh calls. */
342
449
  private refreshLocks;
343
- constructor(filePath?: string);
450
+ private readonly detectMiniMaxRegion;
451
+ private readonly detectXiaomiCluster;
452
+ constructor(filePath?: string, options?: {
453
+ detectMiniMaxBaseUrl?: (apiKey: string) => Promise<string | undefined>;
454
+ detectXiaomiTokenPlanBaseUrl?: (apiKey: string) => Promise<string | undefined>;
455
+ });
344
456
  /** Path to the on-disk auth file. Useful for status output. */
345
457
  get path(): string;
346
458
  /** List provider keys with stored credentials. */
@@ -361,6 +473,11 @@ declare class AuthStorage {
361
473
  * satisfies it.
362
474
  */
363
475
  hasProviderAuth(provider: string): Promise<boolean>;
476
+ /** True when the user signed in with Claude through Claude Code (marker only, no token). */
477
+ hasClaudeCodeLogin(): Promise<boolean>;
478
+ /** Record a Claude Code sign-in. Claude Code keeps the token; auth.json gets only the marker. */
479
+ setClaudeCodeLogin(): Promise<void>;
480
+ clearClaudeCodeLogin(): Promise<void>;
364
481
  /** Endpoint ids that currently have a `local:<id>` credential stored. */
365
482
  listLocalEndpointIds(): Promise<string[]>;
366
483
  /**
@@ -418,7 +535,22 @@ declare class AuthStorage {
418
535
  private mutateLatest;
419
536
  private reloadLatest;
420
537
  getCredentials(provider: string): Promise<OAuthCredentials | undefined>;
538
+ /**
539
+ * A MiniMax key saved without an endpoint (every key, until its first use)
540
+ * gets the endpoint of the region that issued it, saved so the check runs
541
+ * once. Without this a Mainland China key went to the Global API, got a 401,
542
+ * and was deleted as invalid.
543
+ */
544
+ private withMiniMaxRegion;
421
545
  setCredentials(provider: string, creds: OAuthCredentials): Promise<void>;
546
+ /**
547
+ * After a 401, move a regional key to the cluster that issued it instead of
548
+ * treating it as invalid. Only the Xiaomi Token Plan is regional: every key
549
+ * used to go to Singapore, so Europe and China keys were rejected and deleted.
550
+ * Returns the new base URL, or undefined when no other cluster accepts the key.
551
+ */
552
+ relocateRegionalApiKey(storageKeys: string[]): Promise<string | undefined>;
553
+ clearRejectedApiKey(storageKey: string): Promise<boolean>;
422
554
  clearCredentials(provider: string): Promise<void>;
423
555
  /**
424
556
  * Mark the credential stored under `storageKey` as usage-exhausted until
@@ -468,6 +600,117 @@ declare class NotLoggedInError extends Error {
468
600
  constructor(provider: string);
469
601
  }
470
602
 
603
+ type ClaudeCodeSignInOptions = EnsureClaudeCodeOptions & ClaudeCodeRunOptions;
604
+ /**
605
+ * "Sign in with Claude": download Claude Code if it is missing, run its browser
606
+ * sign-in, confirm it with `claude auth status`, then record the marker.
607
+ */
608
+ declare function signInWithClaudeCode(auth: Pick<AuthStorage, "setClaudeCodeLogin">, callbacks: OAuthLoginCallbacks, opts?: ClaudeCodeSignInOptions): Promise<ClaudeCodeAuthStatus>;
609
+ /** Sign out of Claude Code and drop the marker. The marker goes even if `claude auth logout` fails. */
610
+ declare function signOutOfClaudeCode(auth: Pick<AuthStorage, "clearClaudeCodeLogin">, opts?: ClaudeCodeRunOptions): Promise<void>;
611
+
612
+ type SubscriptionUsageProvider = "anthropic" | "openai" | "moonshot";
613
+ /** Providers whose usage endpoint we call with a token. Claude reports its own (claude-code/usage.ts). */
614
+ type FetchedSubscriptionUsageProvider = Exclude<SubscriptionUsageProvider, "anthropic">;
615
+ interface SubscriptionUsageWindow {
616
+ kind: "current" | "weekly";
617
+ label: string;
618
+ usedPercent: number;
619
+ /** Unix epoch milliseconds. */
620
+ resetsAt?: number;
621
+ }
622
+ interface SubscriptionUsageSnapshot {
623
+ provider: SubscriptionUsageProvider;
624
+ displayName: string;
625
+ windows: SubscriptionUsageWindow[];
626
+ fetchedAt: number;
627
+ }
628
+ declare class SubscriptionUsageError extends Error {
629
+ readonly status?: number | undefined;
630
+ readonly retryAfterMs?: number | undefined;
631
+ constructor(message: string, status?: number | undefined, retryAfterMs?: number | undefined);
632
+ }
633
+ type FetchFn = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
634
+ interface FetchSubscriptionUsageOptions {
635
+ fetchFn?: FetchFn;
636
+ timeoutMs?: number;
637
+ now?: () => number;
638
+ }
639
+ /**
640
+ * Fetch subscription quota windows with an already-resolved OAuth credential.
641
+ * Tokens stay server-side: callers expose only the normalized percentages and
642
+ * reset timestamps to their UI.
643
+ */
644
+ declare function fetchSubscriptionUsage(provider: SubscriptionUsageProvider, credentials: Pick<OAuthCredentials, "accessToken" | "accountId">, options?: FetchSubscriptionUsageOptions): Promise<SubscriptionUsageSnapshot>;
645
+
646
+ /** The parts of the SDK's `rate_limit_event.rate_limit_info` the usage meter reads. */
647
+ interface ClaudeCodeRateLimitInfo {
648
+ rateLimitType?: string;
649
+ /** Fraction of the window used, 0–1. */
650
+ utilization?: number;
651
+ /** Unix epoch seconds. */
652
+ resetsAt?: number;
653
+ /** Not in the SDK types yet; carries every window the response reported. */
654
+ unifiedWindows?: Record<string, {
655
+ utilization?: number;
656
+ resetsAt?: number;
657
+ } | undefined>;
658
+ }
659
+ /**
660
+ * Fold one SDK rate-limit report into the last snapshot. A report can carry a
661
+ * single window, so windows it doesn't mention keep their previous values.
662
+ */
663
+ declare function mergeClaudeCodeRateLimit(info: ClaudeCodeRateLimitInfo, previous: SubscriptionUsageSnapshot | null, now?: number): SubscriptionUsageSnapshot;
664
+ /**
665
+ * The latest Claude subscription usage Claude Code reported, from any GG
666
+ * process on this machine. Windows whose reset time has passed are dropped:
667
+ * their old percentage no longer holds and the new one isn't known yet.
668
+ */
669
+ declare function readClaudeCodeUsage(opts?: ClaudeCodeRuntimeOptions & {
670
+ now?: number;
671
+ }): Promise<SubscriptionUsageSnapshot | null>;
672
+ /** Save an SDK rate-limit report so the usage meter (app or CLI) can show it. */
673
+ declare function recordClaudeCodeRateLimit(info: ClaudeCodeRateLimitInfo, opts?: ClaudeCodeRuntimeOptions & {
674
+ now?: number;
675
+ }): Promise<void>;
676
+ /** Forget saved usage, e.g. on sign-out, so another account never inherits it. */
677
+ declare function clearClaudeCodeUsage(opts?: ClaudeCodeRuntimeOptions): Promise<void>;
678
+
679
+ /**
680
+ * MiniMax runs two separate platforms, and a key only works on the one that
681
+ * issued it: Global (platform.minimax.io) or Mainland China
682
+ * (platform.minimaxi.com). The user's location doesn't matter. Sending a key to
683
+ * the other region's API is rejected as an invalid key.
684
+ */
685
+ declare const MINIMAX_GLOBAL_BASE_URL = "https://api.minimax.io/anthropic";
686
+ declare const MINIMAX_CN_BASE_URL = "https://api.minimax.cn/anthropic";
687
+ /**
688
+ * The Anthropic-compatible base URL for the region that issued `apiKey`, found
689
+ * by asking both regions about the key. Undefined when neither region gives a
690
+ * clear answer (offline, timeouts) — callers then keep the Global default and
691
+ * may ask again later.
692
+ */
693
+ declare function detectMiniMaxBaseUrl(apiKey: string, options?: {
694
+ fetch?: typeof fetch;
695
+ timeoutMs?: number;
696
+ }): Promise<string | undefined>;
697
+
698
+ /**
699
+ * Xiaomi MiMo Token Plan runs separate clusters, and a `tp-` key only works on
700
+ * the cluster that issued it (shown on the user's Token Plan page). Any other
701
+ * cluster answers 401 "Invalid API Key". Pay-as-you-go (API Credits) keys use
702
+ * the single global host and are unaffected.
703
+ */
704
+ declare const XIAOMI_TOKEN_PLAN_BASE_URLS: readonly ["https://token-plan-sgp.xiaomimimo.com/v1", "https://token-plan-ams.xiaomimimo.com/v1", "https://token-plan-cn.xiaomimimo.com/v1"];
705
+ /**
706
+ * The Token Plan base URL whose cluster accepts `apiKey`, found by listing
707
+ * models (free, auth-only) on every cluster. Undefined when none accepts it.
708
+ */
709
+ declare function detectXiaomiTokenPlanBaseUrl(apiKey: string, options?: {
710
+ fetch?: typeof fetch;
711
+ timeoutMs?: number;
712
+ }): Promise<string | undefined>;
713
+
471
714
  type AuthMethod = "oauth" | "apikey";
472
715
  /**
473
716
  * One API-key option for a provider that splits auth across multiple distinct
@@ -525,12 +768,7 @@ interface AuthMethodMeta {
525
768
  /** Prerequisite the user must already have, if any. */
526
769
  requires?: string;
527
770
  }
528
- /**
529
- * Every provider a user can connect, in login-screen order. `description`
530
- * lists that provider's models and feeds both the CLI login screen and the
531
- * app's provider list, so `auth-providers.test.ts` pins each one to the model
532
- * registry — a registry change that isn't reflected here fails the suite.
533
- */
771
+ /** Every provider a user can connect right now, in login-screen order. */
534
772
  declare const AUTH_PROVIDERS: AuthProviderMeta[];
535
773
  declare function getAuthProvider(value: string): AuthProviderMeta | undefined;
536
774
  /**
@@ -549,38 +787,6 @@ declare function describeAuthMethods(provider: string): AuthMethodMeta[];
549
787
  */
550
788
  declare function authPriorityNote(provider: string): string | undefined;
551
789
 
552
- type SubscriptionUsageProvider = "anthropic" | "openai" | "moonshot";
553
- interface SubscriptionUsageWindow {
554
- kind: "current" | "weekly";
555
- label: string;
556
- usedPercent: number;
557
- /** Unix epoch milliseconds. */
558
- resetsAt?: number;
559
- }
560
- interface SubscriptionUsageSnapshot {
561
- provider: SubscriptionUsageProvider;
562
- displayName: string;
563
- windows: SubscriptionUsageWindow[];
564
- fetchedAt: number;
565
- }
566
- declare class SubscriptionUsageError extends Error {
567
- readonly status?: number | undefined;
568
- readonly retryAfterMs?: number | undefined;
569
- constructor(message: string, status?: number | undefined, retryAfterMs?: number | undefined);
570
- }
571
- type FetchFn = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
572
- interface FetchSubscriptionUsageOptions {
573
- fetchFn?: FetchFn;
574
- timeoutMs?: number;
575
- now?: () => number;
576
- }
577
- /**
578
- * Fetch subscription quota windows with an already-resolved OAuth credential.
579
- * Tokens stay server-side: callers expose only the normalized percentages and
580
- * reset timestamps to their UI.
581
- */
582
- declare function fetchSubscriptionUsage(provider: SubscriptionUsageProvider, credentials: Pick<OAuthCredentials, "accessToken" | "accountId">, options?: FetchSubscriptionUsageOptions): Promise<SubscriptionUsageSnapshot>;
583
-
584
790
  declare function generatePKCE(): Promise<{
585
791
  verifier: string;
586
792
  challenge: string;
@@ -879,4 +1085,4 @@ interface AutoUpdater {
879
1085
  }
880
1086
  declare function createAutoUpdater(config: AutoUpdateConfig): AutoUpdater;
881
1087
 
882
- export { AUTH_PROVIDERS, type ApiKeyVariant, type AuthMethod, type AuthMethodMeta, type AuthProviderMeta, AuthStorage, type AutoUpdateConfig, type AutoUpdater, DEFAULT_LOCAL_ENDPOINTS, type DiscoverOptions, type DiscoveryResult, type DualAuthProvider, FALLBACK_CONTEXT_WINDOW, GEMINI_API_KEY, GEMINI_API_KEY_BASE_URL, type InlineButton, LOCAL_API_KEY_PLACEHOLDER, LOCAL_AUTH_KEY_PREFIX, type LocalEndpoint, type LocalEndpointKind, type LocalEndpointProbe, type LocalModel, type LogLevel, MOONSHOT_OAUTH_KEY, ModelInfo, NotLoggedInError, type OAuthCredentials, type OAuthLoginCallbacks, PLAN_MODE_THINKING_CAP, type ProbeOptions, type ProgressCallback, SubscriptionUsageError, type SubscriptionUsageProvider, type SubscriptionUsageSnapshot, type SubscriptionUsageWindow, TelegramBot, type TelegramConfig, type TelegramMessage, type TelegramUpdate, type TelegramVoiceMessage, XAI_OAUTH_KEY, XIAOMI_CREDITS_KEY, authPriorityNote, clampThinkingForPlanMode, clearLocalDiscoveryCache, closeLogger, compareClaudeCodeVersions, createAutoUpdater, decodeOggOpus, describeAuthMethods, discoverLocalModels, downmixToMono, dualAuthProvider, dualAuthProviderByOAuthKey, endpointRoot, fetchSubscriptionUsage, findProbedModel, formatLocalModelId, generatePKCE, getAuthProvider, getClaudeCliUserAgent, getClaudeCodeVersion, getLowestThinkingLevel, getNextThinkingLevel, getSessionId, getSupportedThinkingLevels, grokCliBaseUrl, grokCliHeaders, isGrokCliEndpoint, isKimiCodingEndpoint, isLocalModelId, isLoggerOpen, isModelLoaded, isThinkingLevelSupported, kimiCodeBaseUrl, kimiCodingHeaders, localAuthStorageKey, log, loginAnthropic, loginGemini, loginKimi, loginOpenAI, loginXai, oauthStorageKey, openLog, parseLocalModelId, probeEndpoint, providerStorageKeys, readStoredBaseUrlSync, recordRequiredClaudeCodeVersion, refreshAnthropicToken, refreshGeminiToken, refreshKimiToken, refreshOpenAIToken, refreshXaiToken, registerLogCleanup, resample, setProgressCallback, toModelInfo, transcribeVoice, withFileLock };
1088
+ export { AUTH_PROVIDERS, type ApiKeyVariant, type AuthMethod, type AuthMethodMeta, type AuthProviderMeta, AuthStorage, type AutoUpdateConfig, type AutoUpdater, CLAUDE_CODE_AUTH_KEY, CLAUDE_CODE_AUTH_MARKER, CLAUDE_CODE_MANIFEST, type ClaudeCodeAuthStatus, type ClaudeCodeInstallProgress, type ClaudeCodeManifest, type ClaudeCodePlatformAsset, type ClaudeCodeRateLimitInfo, type ClaudeCodeRunOptions, type ClaudeCodeRuntimeOptions, type ClaudeCodeSignInOptions, DEFAULT_LOCAL_ENDPOINTS, type DiscoverOptions, type DiscoveryResult, type DualAuthProvider, type EnsureClaudeCodeOptions, FALLBACK_CONTEXT_WINDOW, type FetchedSubscriptionUsageProvider, GEMINI_API_KEY, GEMINI_API_KEY_BASE_URL, type InlineButton, LOCAL_API_KEY_PLACEHOLDER, LOCAL_AUTH_KEY_PREFIX, type LocalEndpoint, type LocalEndpointKind, type LocalEndpointProbe, type LocalModel, type LogLevel, MINIMAX_CN_BASE_URL, MINIMAX_GLOBAL_BASE_URL, MOONSHOT_OAUTH_KEY, ModelInfo, NotLoggedInError, type OAuthCredentials, type OAuthLoginCallbacks, OPENCODE_CATALOG_URLS, OPENCODE_PROVIDERS, OPENROUTER_DEFAULT_BASE_URL, type OpenCodeProvider, PLAN_MODE_THINKING_CAP, type ParsedOpenCodeCatalog, type ParsedOpenRouterCatalog, type PointScale, type ProbeOptions, type ProgressCallback, SubscriptionUsageError, type SubscriptionUsageProvider, type SubscriptionUsageSnapshot, type SubscriptionUsageWindow, TelegramBot, type TelegramConfig, type TelegramMessage, type TelegramUpdate, type TelegramVoiceMessage, XAI_OAUTH_KEY, XIAOMI_CREDITS_KEY, XIAOMI_TOKEN_PLAN_BASE_URLS, authPriorityNote, clampThinkingForPlanMode, claudeCodeAuthStatus, claudeCodeBinaryPath, claudeCodeCallbackUrl, claudeCodeConfigDir, claudeCodeEnv, claudeCodeHome, claudeCodePlatformKey, clearClaudeCodeUsage, clearLocalDiscoveryCache, closeLogger, createAutoUpdater, decodeOggOpus, describeAuthMethods, detectMiniMaxBaseUrl, detectXiaomiTokenPlanBaseUrl, discoverLocalModels, downmixToMono, dualAuthProvider, dualAuthProviderByOAuthKey, endpointRoot, ensureClaudeCodeBinary, fetchSubscriptionUsage, findProbedModel, formatClaudeCodeInstallProgress, formatLocalModelId, formatOpenCodeModelId, generatePKCE, getAuthProvider, getLowestThinkingLevel, getNextThinkingLevel, getSessionId, getSupportedThinkingLevels, grokCliBaseUrl, grokCliHeaders, isClaudeCodeAuthMarker, isGrokCliEndpoint, isKimiCodingEndpoint, isLegacyClaudeOAuth, isLocalModelId, isLoggerOpen, isModelLoaded, isThinkingLevelSupported, kimiCodeBaseUrl, kimiCodingHeaders, localAuthStorageKey, localModelShortName, log, loginAnthropic, loginClaudeCode, loginGemini, loginKimi, loginOpenAI, loginXai, logoutClaudeCode, mergeClaudeCodeRateLimit, oauthStorageKey, ollamaServedContext, openLog, parseLocalModelId, parseOpenCodeCatalog, parseOpenRouterCatalog, pointScale, probeEndpoint, providerStorageKeys, readClaudeCodeUsage, readStoredBaseUrlSync, recordClaudeCodeRateLimit, refreshAnthropicToken, refreshGeminiToken, refreshKimiToken, refreshOpenAIToken, refreshXaiToken, registerLogCleanup, resample, resolveClaudeCodeBinary, setProgressCallback, signInWithClaudeCode, signOutOfClaudeCode, toModelInfo, transcribeVoice, withFileLock };