@hk_net/pi-usage-bars 0.5.0 → 0.7.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,1274 +1,1629 @@
1
- import * as fs from "node:fs";
2
- import * as os from "node:os";
3
- import * as path from "node:path";
4
-
5
- export type ProviderKey =
6
- | "codex"
7
- | "claude"
8
- | "zai"
9
- | "zai-cn"
10
- | "kimi"
11
- | "minimax"
12
- | "minimax-cn"
13
- | "openrouter"
14
- | "deepseek"
15
- | "moonshot"
16
- | "moonshot-cn";
17
- export type PiProviderId =
18
- | "openai-codex"
19
- | "anthropic"
20
- | "zai"
21
- | "zai-coding-cn"
22
- | "kimi-coding"
23
- | "minimax"
24
- | "minimax-cn"
25
- | "openrouter"
26
- | "deepseek"
27
- | "moonshotai"
28
- | "moonshotai-cn";
29
-
30
- export interface AccountBalance {
31
- amount: number;
32
- unit: string;
33
- label: string;
34
- }
35
-
36
- export interface AccountSpend {
37
- unit: string;
38
- daily?: number;
39
- weekly?: number;
40
- monthly?: number;
41
- lifetime?: number;
42
- }
43
-
44
- export interface UsageData {
45
- session: number;
46
- weekly: number;
47
- quotaHidden?: boolean;
48
- accountBalance?: AccountBalance;
49
- accountBalanceDetails?: AccountBalance[];
50
- accountSpend?: AccountSpend;
51
- sessionResetsIn?: string;
52
- weeklyResetsIn?: string;
53
- sessionResetsAt?: string;
54
- weeklyResetsAt?: string;
55
- extraSpend?: number;
56
- extraLimit?: number;
57
- sessionLabel?: string;
58
- weeklyLabel?: string;
59
- sessionHidden?: boolean;
60
- weeklyHidden?: boolean;
61
- notice?: string;
62
- warning?: string;
63
- stale?: boolean;
64
- fetchedAt?: number;
65
- error?: string;
66
- }
67
-
68
- export type UsageByProvider = Record<ProviderKey, UsageData | null>;
69
- export type UsageTokens = Partial<Record<ProviderKey, string>>;
70
-
71
- export interface UsageEndpoints {
72
- zai: string;
73
- zaiCn: string;
74
- kimi: string;
75
- minimax: string;
76
- minimaxLegacy: string;
77
- minimaxCn: string;
78
- minimaxCnLegacy: string;
79
- openRouterCredits: string;
80
- openRouterKey: string;
81
- deepSeekBalance: string;
82
- moonshotBalance: string;
83
- moonshotCnBalance: string;
84
- }
85
-
86
- export interface HeadersLike {
87
- get(name: string): string | null;
88
- }
89
-
90
- export interface FetchResponseLike {
91
- ok: boolean;
92
- status: number;
93
- headers?: HeadersLike;
94
- json(): Promise<unknown>;
95
- }
96
-
97
- export type FetchLike = (input: string, init?: RequestInit) => Promise<FetchResponseLike>;
98
-
99
- export interface RequestConfig {
100
- fetchFn?: FetchLike;
101
- timeoutMs?: number;
102
- signal?: AbortSignal;
103
- }
104
-
105
- export interface FetchConfig extends RequestConfig {
106
- endpoints?: UsageEndpoints;
107
- env?: NodeJS.ProcessEnv;
108
- }
109
-
110
- export interface FetchAllUsagesConfig extends FetchConfig {
111
- cacheFile?: string;
112
- nowMs?: number;
113
- }
114
-
115
- export interface ClaudeUsageFetchConfig extends RequestConfig {
116
- cacheFile?: string;
117
- nowMs?: number;
118
- }
119
-
120
- interface JsonRequestSuccess {
121
- ok: true;
122
- data: unknown;
123
- status: number;
124
- headers?: HeadersLike;
125
- }
126
-
127
- interface JsonRequestError {
128
- ok: false;
129
- error: string;
130
- status: number | null;
131
- headers?: HeadersLike;
132
- }
133
-
134
- type JsonRequestResult = JsonRequestSuccess | JsonRequestError;
135
-
136
- interface ClaudeUsageAttemptResult {
137
- usage: UsageData;
138
- status: number | null;
139
- retryAfterMs: number | null;
140
- }
141
-
142
- interface ClaudeUsageCacheState {
143
- lastSuccess?: UsageData;
144
- lastSuccessAt?: number;
145
- cooldownUntil?: number;
146
- consecutive429s?: number;
147
- lastError?: string;
148
- }
149
-
150
- interface UsageBarsCacheFile {
151
- version: 1;
152
- claude?: ClaudeUsageCacheState;
153
- }
154
-
155
- const DEFAULT_FETCH_TIMEOUT_MS = 12_000;
156
- const CLAUDE_SHARED_FRESH_TTL_MS = 2 * 60 * 1000;
157
- const CLAUDE_BASE_BACKOFF_MS = 2 * 60 * 1000;
158
- const CLAUDE_MAX_BACKOFF_MS = 30 * 60 * 1000;
159
- const CLAUDE_LOCK_WAIT_MS = 4_000;
160
- const CLAUDE_LOCK_POLL_MS = 125;
161
- const CLAUDE_LOCK_STALE_MS = 20_000;
162
-
163
- export const DEFAULT_USAGE_CACHE_FILE = path.join(os.tmpdir(), "pi", "usage-bars-cache.json");
164
- export const DEFAULT_ZAI_USAGE_ENDPOINT = "https://api.z.ai/api/monitor/usage/quota/limit";
165
- export const DEFAULT_ZAI_CN_USAGE_ENDPOINT = "https://open.bigmodel.cn/api/monitor/usage/quota/limit";
166
- export const DEFAULT_KIMI_USAGE_ENDPOINT = "https://api.kimi.com/coding/v1/usages";
167
- export const DEFAULT_MINIMAX_USAGE_ENDPOINT = "https://api.minimax.io/v1/token_plan/remains";
168
- export const DEFAULT_MINIMAX_LEGACY_USAGE_ENDPOINT = "https://api.minimax.io/v1/api/openplatform/coding_plan/remains";
169
- export const DEFAULT_MINIMAX_CN_USAGE_ENDPOINT = "https://api.minimaxi.com/v1/token_plan/remains";
170
- export const DEFAULT_MINIMAX_CN_LEGACY_USAGE_ENDPOINT = "https://api.minimaxi.com/v1/api/openplatform/coding_plan/remains";
171
- export const DEFAULT_OPENROUTER_CREDITS_ENDPOINT = "https://openrouter.ai/api/v1/credits";
172
- export const DEFAULT_OPENROUTER_KEY_ENDPOINT = "https://openrouter.ai/api/v1/key";
173
- export const DEFAULT_DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
174
- export const DEFAULT_MOONSHOT_BALANCE_ENDPOINT = "https://api.moonshot.ai/v1/users/me/balance";
175
- export const DEFAULT_MOONSHOT_CN_BALANCE_ENDPOINT = "https://api.moonshot.cn/v1/users/me/balance";
176
-
177
- export function resolveUsageEndpoints(env: NodeJS.ProcessEnv = process.env): UsageEndpoints {
178
- const configured = (value: string | undefined, fallback: string) => {
179
- const trimmed = value?.trim();
180
- return trimmed || fallback;
181
- };
182
-
183
- return {
184
- zai: configured(env.PI_ZAI_USAGE_ENDPOINT, DEFAULT_ZAI_USAGE_ENDPOINT),
185
- zaiCn: configured(env.PI_ZAI_CODING_CN_USAGE_ENDPOINT, DEFAULT_ZAI_CN_USAGE_ENDPOINT),
186
- kimi: configured(env.PI_KIMI_USAGE_ENDPOINT, DEFAULT_KIMI_USAGE_ENDPOINT),
187
- minimax: configured(env.PI_MINIMAX_USAGE_ENDPOINT, DEFAULT_MINIMAX_USAGE_ENDPOINT),
188
- minimaxLegacy: configured(env.PI_MINIMAX_LEGACY_USAGE_ENDPOINT, DEFAULT_MINIMAX_LEGACY_USAGE_ENDPOINT),
189
- minimaxCn: configured(env.PI_MINIMAX_CN_USAGE_ENDPOINT, DEFAULT_MINIMAX_CN_USAGE_ENDPOINT),
190
- minimaxCnLegacy: configured(env.PI_MINIMAX_CN_LEGACY_USAGE_ENDPOINT, DEFAULT_MINIMAX_CN_LEGACY_USAGE_ENDPOINT),
191
- openRouterCredits: configured(env.PI_OPENROUTER_CREDITS_ENDPOINT, DEFAULT_OPENROUTER_CREDITS_ENDPOINT),
192
- openRouterKey: configured(env.PI_OPENROUTER_KEY_ENDPOINT, DEFAULT_OPENROUTER_KEY_ENDPOINT),
193
- deepSeekBalance: configured(env.PI_DEEPSEEK_BALANCE_ENDPOINT, DEFAULT_DEEPSEEK_BALANCE_ENDPOINT),
194
- moonshotBalance: configured(env.PI_MOONSHOT_BALANCE_ENDPOINT, DEFAULT_MOONSHOT_BALANCE_ENDPOINT),
195
- moonshotCnBalance: configured(env.PI_MOONSHOT_CN_BALANCE_ENDPOINT, DEFAULT_MOONSHOT_CN_BALANCE_ENDPOINT),
196
- };
197
- }
198
-
199
- function toErrorMessage(error: unknown, externalSignal?: AbortSignal): string {
200
- if (error instanceof Error) {
201
- if (error.name === "AbortError") {
202
- return externalSignal?.aborted ? "request cancelled" : "request timeout";
203
- }
204
- return error.message || String(error);
205
- }
206
- return String(error);
207
- }
208
-
209
- function asObject(value: unknown): Record<string, unknown> | null {
210
- if (!value || typeof value !== "object") return null;
211
- return value as Record<string, unknown>;
212
- }
213
-
214
- function normalizeUsagePair(session: number, weekly: number): { session: number; weekly: number } {
215
- const clean = (value: number) => Number.isFinite(value) ? Number(value.toFixed(2)) : 0;
216
- return { session: clean(session), weekly: clean(weekly) };
217
- }
218
-
219
- function getHeader(headers: HeadersLike | undefined, name: string): string | null {
220
- if (!headers) return null;
221
- try {
222
- return headers.get(name);
223
- } catch {
224
- return null;
225
- }
226
- }
227
-
228
- function combineSignals(timeoutSignal: AbortSignal | undefined, externalSignal: AbortSignal | undefined): AbortSignal | undefined {
229
- if (timeoutSignal && externalSignal) return AbortSignal.any([timeoutSignal, externalSignal]);
230
- return timeoutSignal ?? externalSignal;
231
- }
232
-
233
- async function requestJson(url: string, init: RequestInit, config: RequestConfig = {}): Promise<JsonRequestResult> {
234
- const fetchFn = config.fetchFn ?? (fetch as unknown as FetchLike);
235
- const timeoutMs = config.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
236
- const timeoutController = timeoutMs > 0 ? new AbortController() : undefined;
237
- const timeout = timeoutController
238
- ? setTimeout(() => timeoutController.abort(), timeoutMs)
239
- : undefined;
240
- const signal = combineSignals(timeoutController?.signal, config.signal);
241
-
242
- try {
243
- if (config.signal?.aborted) {
244
- return { ok: false, error: "request cancelled", status: null };
245
- }
246
-
247
- const response = await fetchFn(url, { ...init, signal });
248
- if (!response.ok) {
249
- return { ok: false, error: `HTTP ${response.status}`, status: response.status, headers: response.headers };
250
- }
251
-
252
- try {
253
- return { ok: true, data: await response.json(), status: response.status, headers: response.headers };
254
- } catch {
255
- return { ok: false, error: "invalid JSON response", status: response.status, headers: response.headers };
256
- }
257
- } catch (error) {
258
- return { ok: false, error: toErrorMessage(error, config.signal), status: null };
259
- } finally {
260
- if (timeout !== undefined) clearTimeout(timeout);
261
- }
262
- }
263
-
264
- export function formatDuration(seconds: number): string {
265
- if (!Number.isFinite(seconds) || seconds <= 0) return "now";
266
- const days = Math.floor(seconds / 86400);
267
- const hours = Math.floor((seconds % 86400) / 3600);
268
- const minutes = Math.floor((seconds % 3600) / 60);
269
- if (days > 0 && hours > 0) return `${days}d ${hours}h`;
270
- if (days > 0) return `${days}d`;
271
- if (hours > 0 && minutes > 0) return `${hours}h ${minutes}m`;
272
- if (hours > 0) return `${hours}h`;
273
- if (minutes > 0) return `${minutes}m`;
274
- return "<1m";
275
- }
276
-
277
- export function formatResetsAt(isoDate: string, nowMs = Date.now()): string {
278
- const resetTime = new Date(isoDate).getTime();
279
- if (!Number.isFinite(resetTime)) return "";
280
- return formatDuration(Math.max(0, resetTime - nowMs) / 1000);
281
- }
282
-
283
- export function parseRetryAfterMs(value: string | null | undefined, nowMs = Date.now()): number | null {
284
- if (!value) return null;
285
- const numeric = Number(value);
286
- if (Number.isFinite(numeric) && numeric >= 0) return numeric * 1000;
287
- const dateMs = new Date(value).getTime();
288
- return Number.isFinite(dateMs) ? Math.max(0, dateMs - nowMs) : null;
289
- }
290
-
291
- function readUsageCache(cacheFile = DEFAULT_USAGE_CACHE_FILE): UsageBarsCacheFile {
292
- try {
293
- const parsed = JSON.parse(fs.readFileSync(cacheFile, "utf-8"));
294
- if (parsed?.version === 1 && typeof parsed === "object") return parsed as UsageBarsCacheFile;
295
- } catch {
296
- // Invalid or missing caches are treated as empty.
297
- }
298
- return { version: 1 };
299
- }
300
-
301
- function writeUsageCache(cache: UsageBarsCacheFile, cacheFile = DEFAULT_USAGE_CACHE_FILE): boolean {
302
- try {
303
- const directory = path.dirname(cacheFile);
304
- if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
305
- const temporaryPath = `${cacheFile}.tmp-${process.pid}-${Date.now()}`;
306
- fs.writeFileSync(temporaryPath, JSON.stringify(cache, null, 2), { mode: 0o600 });
307
- fs.renameSync(temporaryPath, cacheFile);
308
- return true;
309
- } catch {
310
- return false;
311
- }
312
- }
313
-
314
- function sleep(ms: number, signal?: AbortSignal): Promise<void> {
315
- if (signal?.aborted) return Promise.reject(new DOMException("Aborted", "AbortError"));
316
- return new Promise((resolve, reject) => {
317
- const timer = setTimeout(resolve, ms);
318
- signal?.addEventListener("abort", () => {
319
- clearTimeout(timer);
320
- reject(new DOMException("Aborted", "AbortError"));
321
- }, { once: true });
322
- });
323
- }
324
-
325
- function ensureParentDir(filePath: string): void {
326
- const directory = path.dirname(filePath);
327
- if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
328
- }
329
-
330
- function safeUnlink(filePath: string): void {
331
- try {
332
- fs.unlinkSync(filePath);
333
- } catch {
334
- // Ignore cleanup races.
335
- }
336
- }
337
-
338
- async function acquireFileLock(lockFile: string, signal?: AbortSignal): Promise<(() => void) | null> {
339
- ensureParentDir(lockFile);
340
- const startedAt = Date.now();
341
-
342
- while (Date.now() - startedAt <= CLAUDE_LOCK_WAIT_MS) {
343
- if (signal?.aborted) return null;
344
- try {
345
- const fd = fs.openSync(lockFile, "wx", 0o600);
346
- fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, createdAt: Date.now() }));
347
- fs.closeSync(fd);
348
- return () => safeUnlink(lockFile);
349
- } catch (error: unknown) {
350
- if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") return null;
351
- try {
352
- const stat = fs.statSync(lockFile);
353
- if (Date.now() - stat.mtimeMs >= CLAUDE_LOCK_STALE_MS) {
354
- safeUnlink(lockFile);
355
- continue;
356
- }
357
- } catch {
358
- continue;
359
- }
360
- try {
361
- await sleep(CLAUDE_LOCK_POLL_MS, signal);
362
- } catch {
363
- return null;
364
- }
365
- }
366
- }
367
-
368
- return null;
369
- }
370
-
371
- export function readPercentCandidate(value: unknown): number | null {
372
- if (typeof value !== "number" || !Number.isFinite(value)) return null;
373
- if (value >= 0 && value <= 1) return Number.isInteger(value) ? value : value * 100;
374
- return value >= 0 && value <= 100 ? value : null;
375
- }
376
-
377
- export function readLimitPercent(limit: unknown): number | null {
378
- const value = asObject(limit);
379
- const direct = [
380
- value?.percentage,
381
- value?.utilization,
382
- value?.used_percent,
383
- value?.usedPercent,
384
- value?.usagePercent,
385
- value?.usage_percent,
386
- ].map(readPercentCandidate).find((candidate) => candidate !== null);
387
- if (direct !== undefined) return direct;
388
-
389
- const current = typeof value?.currentValue === "number" ? value.currentValue : null;
390
- const remaining = typeof value?.remaining === "number" ? value.remaining : null;
391
- if (current !== null && remaining !== null && current + remaining > 0) {
392
- return (current / (current + remaining)) * 100;
393
- }
394
- return null;
395
- }
396
-
397
- export function extractUsageFromPayload(payload: unknown): { session: number; weekly: number } | null {
398
- const data = payload as any;
399
- const limitArrays = [data?.data?.limits, data?.limits, data?.quota?.limits, data?.data?.quota?.limits];
400
- const limits = limitArrays.find(Array.isArray) as unknown[] | undefined;
401
-
402
- if (limits) {
403
- const byType = (types: string[]) => limits.find((entry) => {
404
- const type = String((entry as any)?.type || "").toUpperCase();
405
- return types.includes(type);
406
- });
407
- const session = readLimitPercent(byType(["TIME_LIMIT", "SESSION_LIMIT", "REQUEST_LIMIT", "RPM_LIMIT", "RPD_LIMIT"]));
408
- const weekly = readLimitPercent(byType(["TOKENS_LIMIT", "TOKEN_LIMIT", "WEEK_LIMIT", "WEEKLY_LIMIT", "TPM_LIMIT", "DAILY_LIMIT"]));
409
- if (session !== null && weekly !== null) return normalizeUsagePair(session, weekly);
410
- }
411
-
412
- const sessionCandidates = [
413
- data?.session,
414
- data?.sessionPercent,
415
- data?.session_percent,
416
- data?.five_hour?.utilization,
417
- data?.rate_limit?.primary_window?.used_percent,
418
- data?.limits?.session?.utilization,
419
- data?.usage?.session,
420
- data?.data?.session,
421
- data?.data?.sessionPercent,
422
- data?.data?.session_percent,
423
- data?.data?.usage?.session,
424
- data?.quota?.session?.percentage,
425
- data?.data?.quota?.session?.percentage,
426
- ];
427
- const weeklyCandidates = [
428
- data?.weekly,
429
- data?.weeklyPercent,
430
- data?.weekly_percent,
431
- data?.seven_day?.utilization,
432
- data?.rate_limit?.secondary_window?.used_percent,
433
- data?.limits?.weekly?.utilization,
434
- data?.usage?.weekly,
435
- data?.data?.weekly,
436
- data?.data?.weeklyPercent,
437
- data?.data?.weekly_percent,
438
- data?.data?.usage?.weekly,
439
- data?.quota?.weekly?.percentage,
440
- data?.data?.quota?.weekly?.percentage,
441
- data?.quota?.daily?.percentage,
442
- data?.data?.quota?.daily?.percentage,
443
- ];
444
-
445
- const session = sessionCandidates.map(readPercentCandidate).find((candidate) => candidate !== null);
446
- const weekly = weeklyCandidates.map(readPercentCandidate).find((candidate) => candidate !== null);
447
- return session === undefined || weekly === undefined ? null : normalizeUsagePair(session, weekly);
448
- }
449
-
450
- function hydrateUsageResets(usage: UsageData, nowMs = Date.now()): UsageData {
451
- return {
452
- ...usage,
453
- sessionResetsIn: usage.sessionResetsAt ? formatResetsAt(usage.sessionResetsAt, nowMs) : usage.sessionResetsIn,
454
- weeklyResetsIn: usage.weeklyResetsAt ? formatResetsAt(usage.weeklyResetsAt, nowMs) : usage.weeklyResetsIn,
455
- };
456
- }
457
-
458
- function snapshotUsage(usage: UsageData, nowMs = Date.now()): UsageData {
459
- return {
460
- session: usage.session,
461
- weekly: usage.weekly,
462
- quotaHidden: usage.quotaHidden,
463
- accountBalance: usage.accountBalance,
464
- accountBalanceDetails: usage.accountBalanceDetails,
465
- accountSpend: usage.accountSpend,
466
- sessionResetsAt: usage.sessionResetsAt,
467
- weeklyResetsAt: usage.weeklyResetsAt,
468
- sessionResetsIn: usage.sessionResetsIn,
469
- weeklyResetsIn: usage.weeklyResetsIn,
470
- extraSpend: usage.extraSpend,
471
- extraLimit: usage.extraLimit,
472
- sessionLabel: usage.sessionLabel,
473
- weeklyLabel: usage.weeklyLabel,
474
- sessionHidden: usage.sessionHidden,
475
- weeklyHidden: usage.weeklyHidden,
476
- notice: usage.notice,
477
- fetchedAt: usage.fetchedAt ?? nowMs,
478
- };
479
- }
480
-
481
- function staleCachedUsage(cached: UsageData, warning: string, nowMs = Date.now()): UsageData {
482
- return { ...hydrateUsageResets(snapshotUsage(cached, nowMs), nowMs), stale: true, warning };
483
- }
484
-
485
- function readClaudeCacheState(cacheFile = DEFAULT_USAGE_CACHE_FILE): ClaudeUsageCacheState {
486
- return readUsageCache(cacheFile).claude ?? {};
487
- }
488
-
489
- function writeClaudeCacheState(state: ClaudeUsageCacheState, cacheFile = DEFAULT_USAGE_CACHE_FILE): boolean {
490
- const cache = readUsageCache(cacheFile);
491
- cache.claude = state;
492
- return writeUsageCache(cache, cacheFile);
493
- }
494
-
495
- function clearClaudeCooldown(state: ClaudeUsageCacheState): ClaudeUsageCacheState {
496
- return { ...state, cooldownUntil: undefined, consecutive429s: 0, lastError: undefined };
497
- }
498
-
499
- function computeClaudeBackoffMs(state: ClaudeUsageCacheState, retryAfterMs: number | null): number {
500
- if (retryAfterMs !== null && retryAfterMs > 0) {
501
- return Math.min(CLAUDE_MAX_BACKOFF_MS, Math.max(CLAUDE_BASE_BACKOFF_MS, retryAfterMs));
502
- }
503
- const count = Math.max(1, state.consecutive429s ?? 0);
504
- return Math.min(CLAUDE_MAX_BACKOFF_MS, CLAUDE_BASE_BACKOFF_MS * 2 ** Math.max(0, count - 1));
505
- }
506
-
507
- function cooldownMessage(untilMs: number, nowMs = Date.now()): string {
508
- return `rate limited; retry in ${formatDuration(Math.max(0, untilMs - nowMs) / 1000)}`;
509
- }
510
-
511
- function readClaudeCacheOutcome(cacheFile = DEFAULT_USAGE_CACHE_FILE, nowMs = Date.now()): UsageData | null {
512
- const state = readClaudeCacheState(cacheFile);
513
- if (state.cooldownUntil && state.cooldownUntil > nowMs) {
514
- const warning = cooldownMessage(state.cooldownUntil, nowMs);
515
- return state.lastSuccess
516
- ? staleCachedUsage(state.lastSuccess, warning, nowMs)
517
- : { session: 0, weekly: 0, error: warning };
518
- }
519
- if (state.lastSuccess && state.lastSuccessAt && nowMs - state.lastSuccessAt <= CLAUDE_SHARED_FRESH_TTL_MS) {
520
- return hydrateUsageResets(snapshotUsage(state.lastSuccess, state.lastSuccessAt), nowMs);
521
- }
522
- return null;
523
- }
524
-
525
- export function parseCodexRateLimit(data: any): UsageData {
526
- const rateLimit = data?.rate_limit ?? data?.rate_limits;
527
- const primary = rateLimit?.primary_window ?? rateLimit?.primary ?? rateLimit?.five_hour;
528
- const secondary = rateLimit?.secondary_window ?? rateLimit?.secondary ?? rateLimit?.weekly;
529
-
530
- let sessionWindow: any = null;
531
- let weeklyWindow: any = null;
532
- for (const [position, window] of [["primary", primary], ["secondary", secondary]] as const) {
533
- if (!window || typeof window !== "object") continue;
534
- const duration = window.limit_window_seconds;
535
- if (typeof duration === "number" && Number.isFinite(duration)) {
536
- // Some Codex accounts return their seven-day quota as primary_window
537
- // and omit secondary_window, so position alone does not identify it.
538
- if (duration >= 2 * 24 * 60 * 60) weeklyWindow ??= window;
539
- else sessionWindow ??= window;
540
- } else if (position === "primary") {
541
- sessionWindow ??= window;
542
- } else {
543
- weeklyWindow ??= window;
544
- }
545
- }
546
-
547
- const reset = (window: any) =>
548
- typeof window?.reset_after_seconds === "number" ? formatDuration(window.reset_after_seconds) : undefined;
549
-
550
- return {
551
- session: readPercentCandidate(sessionWindow?.used_percent) ?? 0,
552
- weekly: readPercentCandidate(weeklyWindow?.used_percent) ?? 0,
553
- ...(!sessionWindow ? { sessionHidden: true } : {}),
554
- ...(!weeklyWindow ? { weeklyHidden: true } : {}),
555
- sessionResetsIn: reset(sessionWindow),
556
- weeklyResetsIn: reset(weeklyWindow),
557
- };
558
- }
559
-
560
- export async function fetchCodexUsage(token: string, config: RequestConfig = {}): Promise<UsageData> {
561
- const result = await requestJson(
562
- "https://chatgpt.com/backend-api/wham/usage",
563
- { headers: { Authorization: `Bearer ${token}` } },
564
- config,
565
- );
566
- if (!result.ok) return { session: 0, weekly: 0, error: result.error };
567
- return parseCodexRateLimit(result.data);
568
- }
569
-
570
- async function fetchClaudeUsageAttempt(
571
- token: string,
572
- config: RequestConfig = {},
573
- nowMs = Date.now(),
574
- ): Promise<ClaudeUsageAttemptResult> {
575
- const result = await requestJson(
576
- "https://api.anthropic.com/api/oauth/usage",
577
- {
578
- headers: {
579
- Authorization: `Bearer ${token}`,
580
- "anthropic-beta": "oauth-2025-04-20",
581
- },
582
- },
583
- config,
584
- );
585
- const retryAfterMs = parseRetryAfterMs(getHeader(result.headers, "retry-after"), nowMs);
586
- if (!result.ok) {
587
- return { usage: { session: 0, weekly: 0, error: result.error }, status: result.status, retryAfterMs };
588
- }
589
-
590
- const data = result.data as any;
591
- const usage: UsageData = hydrateUsageResets({
592
- session: readPercentCandidate(data?.five_hour?.utilization) ?? 0,
593
- weekly: readPercentCandidate(data?.seven_day?.utilization) ?? 0,
594
- sessionResetsAt: typeof data?.five_hour?.resets_at === "string" ? data.five_hour.resets_at : undefined,
595
- weeklyResetsAt: typeof data?.seven_day?.resets_at === "string" ? data.seven_day.resets_at : undefined,
596
- fetchedAt: nowMs,
597
- }, nowMs);
598
-
599
- if (data?.extra_usage?.is_enabled) {
600
- usage.extraSpend = typeof data.extra_usage.used_credits === "number" ? data.extra_usage.used_credits : undefined;
601
- usage.extraLimit = typeof data.extra_usage.monthly_limit === "number" ? data.extra_usage.monthly_limit : undefined;
602
- }
603
- return { usage, status: result.status, retryAfterMs };
604
- }
605
-
606
- export async function fetchClaudeUsage(token: string, config: RequestConfig = {}): Promise<UsageData> {
607
- return (await fetchClaudeUsageAttempt(token, config)).usage;
608
- }
609
-
610
- export async function fetchClaudeUsageWithFallback(
611
- token: string,
612
- config: ClaudeUsageFetchConfig = {},
613
- ): Promise<UsageData> {
614
- const cacheFile = config.cacheFile ?? DEFAULT_USAGE_CACHE_FILE;
615
- const nowMs = config.nowMs ?? Date.now();
616
- const cachedOutcome = readClaudeCacheOutcome(cacheFile, nowMs);
617
- if (cachedOutcome) return cachedOutcome;
618
- if (config.signal?.aborted) return { session: 0, weekly: 0, error: "request cancelled" };
619
-
620
- const lockFile = `${cacheFile}.claude.lock`;
621
- const releaseLock = await acquireFileLock(lockFile, config.signal);
622
- if (!releaseLock) {
623
- const waitedOutcome = readClaudeCacheOutcome(cacheFile, nowMs);
624
- if (waitedOutcome) return waitedOutcome;
625
- if (config.signal?.aborted) return { session: 0, weekly: 0, error: "request cancelled" };
626
- }
627
-
628
- try {
629
- const lockOutcome = readClaudeCacheOutcome(cacheFile, nowMs);
630
- if (lockOutcome) return lockOutcome;
631
-
632
- let state = readClaudeCacheState(cacheFile);
633
- const attempt = await fetchClaudeUsageAttempt(token, config, nowMs);
634
- if (!attempt.usage.error) {
635
- state = clearClaudeCooldown(state);
636
- state.lastSuccess = snapshotUsage(attempt.usage, nowMs);
637
- state.lastSuccessAt = nowMs;
638
- writeClaudeCacheState(state, cacheFile);
639
- return attempt.usage;
640
- }
641
-
642
- if (attempt.status === 429) {
643
- const consecutive429s = Math.max(1, (state.consecutive429s ?? 0) + 1);
644
- const cooldownUntil = nowMs + computeClaudeBackoffMs({ ...state, consecutive429s }, attempt.retryAfterMs);
645
- state = { ...state, cooldownUntil, consecutive429s, lastError: attempt.usage.error };
646
- writeClaudeCacheState(state, cacheFile);
647
- return state.lastSuccess
648
- ? staleCachedUsage(state.lastSuccess, cooldownMessage(cooldownUntil, nowMs), nowMs)
649
- : { session: 0, weekly: 0, error: `${attempt.usage.error}; ${cooldownMessage(cooldownUntil, nowMs)}` };
650
- }
651
-
652
- return attempt.usage;
653
- } finally {
654
- releaseLock?.();
655
- }
656
- }
657
-
658
- function readNumber(value: unknown): number | null {
659
- if (typeof value === "number" && Number.isFinite(value)) return value;
660
- if (typeof value === "string" && value.trim()) {
661
- const parsed = Number(value);
662
- if (Number.isFinite(parsed)) return parsed;
663
- }
664
- return null;
665
- }
666
-
667
- function usedPercentFromCounts(
668
- value: Record<string, unknown> | null | undefined,
669
- options: { remainingPercent?: string; used?: string; total?: string; remaining?: string } = {},
670
- ): number | null {
671
- if (!value) return null;
672
- const remainingPercent = readNumber(value[options.remainingPercent ?? "remaining_percent"]);
673
- if (remainingPercent !== null) return Math.max(0, Math.min(100, 100 - remainingPercent));
674
-
675
- const total = readNumber(value[options.total ?? "limit"]);
676
- const used = readNumber(value[options.used ?? "used"]);
677
- const remaining = readNumber(value[options.remaining ?? "remaining"]);
678
- if (total === null || total <= 0) return null;
679
- if (used !== null) return Math.max(0, Math.min(100, used / total * 100));
680
- if (remaining !== null) return Math.max(0, Math.min(100, (total - remaining) / total * 100));
681
- return null;
682
- }
683
-
684
- function normalizeIsoDate(value: unknown): string | undefined {
685
- if (typeof value !== "string" || !value.trim()) return undefined;
686
- const normalized = value.trim().replace(/(\.\d{3})\d+(?=Z|[+-]\d\d:\d\d$)/, "$1");
687
- return Number.isFinite(new Date(normalized).getTime()) ? normalized : undefined;
688
- }
689
-
690
- function isoFromEpoch(value: unknown): string | undefined {
691
- const raw = readNumber(value);
692
- if (raw === null || raw <= 0) return undefined;
693
- const milliseconds = raw > 1_000_000_000_000 ? raw : raw * 1000;
694
- const date = new Date(milliseconds);
695
- return Number.isFinite(date.getTime()) ? date.toISOString() : undefined;
696
- }
697
-
698
- function resetFromRemains(value: unknown, nowMs: number): string | undefined {
699
- const raw = readNumber(value);
700
- if (raw === null || raw <= 0) return undefined;
701
- const milliseconds = raw > 1_000_000 ? raw : raw * 1000;
702
- return new Date(nowMs + milliseconds).toISOString();
703
- }
704
-
705
- export function extractKimiUsageFromPayload(payload: unknown, nowMs = Date.now()): UsageData | null {
706
- const root = asObject(payload);
707
- if (!root) return null;
708
- const webUsages = Array.isArray(root.usages) ? root.usages : undefined;
709
- const codingUsage = webUsages?.map(asObject).find((entry) =>
710
- String(entry?.scope ?? "").toUpperCase() === "FEATURE_CODING") ?? root;
711
- const dataRows = Array.isArray(codingUsage.data) ? codingUsage.data.map(asObject).filter(Boolean) : [];
712
- const usage = asObject(codingUsage.usage) ?? asObject(codingUsage.detail) ??
713
- dataRows.find((entry) => String(entry?.model_name ?? entry?.modelName ?? "").toLowerCase() === "all");
714
- const limits = Array.isArray(codingUsage.limits)
715
- ? codingUsage.limits
716
- : dataRows.filter((entry) => entry !== usage);
717
- const sessionLimit = limits.map(asObject).find((entry) => {
718
- const window = asObject(entry?.window);
719
- const duration = readNumber(window?.duration);
720
- const unit = String(window?.timeUnit ?? window?.time_unit ?? "").toUpperCase();
721
- return duration === 300 && unit.includes("MINUTE");
722
- }) ?? limits.map(asObject).find((entry) => entry !== null);
723
- const sessionDetail = asObject(sessionLimit?.detail) ?? sessionLimit;
724
-
725
- const session = usedPercentFromCounts(sessionDetail);
726
- const weekly = usedPercentFromCounts(usage);
727
- if (session === null || weekly === null) return null;
728
-
729
- const sessionReset = normalizeIsoDate(sessionDetail?.resetTime ?? sessionDetail?.reset_at ?? sessionDetail?.reset_time);
730
- const weeklyReset = normalizeIsoDate(usage?.resetTime ?? usage?.reset_at ?? usage?.reset_time);
731
- return hydrateUsageResets({
732
- ...normalizeUsagePair(session, weekly),
733
- sessionLabel: "5-hour",
734
- weeklyLabel: "Weekly",
735
- sessionResetsAt: sessionReset,
736
- weeklyResetsAt: weeklyReset,
737
- }, nowMs);
738
- }
739
-
740
- export async function fetchKimiUsage(token: string, config: FetchConfig = {}): Promise<UsageData> {
741
- const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
742
- const result = await requestJson(endpoints.kimi, {
743
- headers: {
744
- Authorization: `Bearer ${token}`,
745
- "User-Agent": "KimiCLI/1.5",
746
- },
747
- }, config);
748
- if (!result.ok) return { session: 0, weekly: 0, error: result.error };
749
- return extractKimiUsageFromPayload(result.data) ?? {
750
- session: 0,
751
- weekly: 0,
752
- error: "unrecognized response shape",
753
- };
754
- }
755
-
756
- interface MiniMaxWindow {
757
- percent: number;
758
- resetsAt?: string;
759
- }
760
-
761
- function pickHighestWindow(windows: MiniMaxWindow[]): MiniMaxWindow | undefined {
762
- return windows.reduce<MiniMaxWindow | undefined>((highest, window) =>
763
- !highest || window.percent > highest.percent ? window : highest, undefined);
764
- }
765
-
766
- function miniMaxResetAt(value: Record<string, unknown>, prefix: "current" | "weekly", nowMs: number): string | undefined {
767
- const end = prefix === "current"
768
- ? value.end_time ?? value.endTime
769
- : value.weekly_end_time ?? value.weeklyEndTime;
770
- const remains = prefix === "current"
771
- ? value.remains_time ?? value.remainsTime
772
- : value.weekly_remains_time ?? value.weeklyRemainsTime;
773
- const resetsAt = prefix === "current"
774
- ? value.current_resets_at ?? value.currentResetsAt
775
- : value.weekly_resets_at ?? value.weeklyResetsAt;
776
- return normalizeIsoDate(resetsAt) ?? isoFromEpoch(end) ?? resetFromRemains(remains, nowMs);
777
- }
778
-
779
- function extractMiniMaxCreditBalance(payload: unknown): AccountBalance | undefined {
780
- const root = asObject(payload);
781
- const data = asObject(root?.data) ?? root;
782
- if (!data) return undefined;
783
- const amount = readNumber(
784
- data.points_balance ?? data.pointsBalance ??
785
- data.point_balance ?? data.pointBalance ??
786
- data.credits_balance ?? data.creditsBalance ??
787
- data.credit_balance ?? data.creditBalance,
788
- );
789
- return amount === null ? undefined : { amount, unit: "credits", label: "Credit balance" };
790
- }
791
-
792
- export function extractMiniMaxUsageFromPayload(payload: unknown, nowMs = Date.now()): UsageData | null {
793
- const root = asObject(payload);
794
- const data = asObject(root?.data) ?? root;
795
- if (!data) return null;
796
- const accountBalance = extractMiniMaxCreditBalance(payload);
797
-
798
- const intervalWindows: MiniMaxWindow[] = [];
799
- const weeklyWindows: MiniMaxWindow[] = [];
800
- if (Array.isArray(data.services)) {
801
- for (const rawService of data.services) {
802
- const service = asObject(rawService);
803
- if (!service) continue;
804
- const directPercent = readPercentCandidate(readNumber(service.percent));
805
- const percent = directPercent ?? usedPercentFromCounts(service, { total: "limit", used: "usage" });
806
- if (percent === null) continue;
807
- const windowType = String(service.window_type ?? service.windowType ?? "").toLowerCase();
808
- const resetsAt = normalizeIsoDate(service.resets_at ?? service.reset_time ?? service.end_time);
809
- (windowType.includes("week") ? weeklyWindows : intervalWindows).push({ percent, resetsAt });
810
- }
811
- }
812
-
813
- if (Array.isArray(data.model_remains ?? data.modelRemains)) {
814
- for (const rawModel of (data.model_remains ?? data.modelRemains) as unknown[]) {
815
- const raw = asObject(rawModel);
816
- if (!raw) continue;
817
- const model: Record<string, unknown> = {
818
- ...raw,
819
- current_interval_remaining_percent:
820
- raw.current_interval_remaining_percent ?? raw.currentIntervalRemainingPercent,
821
- current_interval_total_count: raw.current_interval_total_count ?? raw.currentIntervalTotalCount,
822
- current_interval_usage_count: raw.current_interval_usage_count ?? raw.currentIntervalUsageCount,
823
- current_interval_status: raw.current_interval_status ?? raw.currentIntervalStatus,
824
- current_weekly_remaining_percent:
825
- raw.current_weekly_remaining_percent ?? raw.currentWeeklyRemainingPercent,
826
- current_weekly_total_count: raw.current_weekly_total_count ?? raw.currentWeeklyTotalCount,
827
- current_weekly_usage_count: raw.current_weekly_usage_count ?? raw.currentWeeklyUsageCount,
828
- current_weekly_status: raw.current_weekly_status ?? raw.currentWeeklyStatus,
829
- };
830
- const unavailable = (prefix: "interval" | "weekly") =>
831
- readNumber(model[`current_${prefix}_status`]) === 3 &&
832
- (readNumber(model[`current_${prefix}_remaining_percent`]) ?? 0) >= 100 &&
833
- (readNumber(model[`current_${prefix}_total_count`]) ?? 0) === 0 &&
834
- (readNumber(model[`current_${prefix}_usage_count`]) ?? 0) === 0;
835
- const interval = unavailable("interval") ? null : usedPercentFromCounts(model, {
836
- remainingPercent: "current_interval_remaining_percent",
837
- total: "current_interval_total_count",
838
- remaining: "current_interval_usage_count",
839
- });
840
- if (interval !== null) {
841
- intervalWindows.push({ percent: interval, resetsAt: miniMaxResetAt(model, "current", nowMs) });
842
- }
843
- const weekly = unavailable("weekly") ? null : usedPercentFromCounts(model, {
844
- remainingPercent: "current_weekly_remaining_percent",
845
- total: "current_weekly_total_count",
846
- remaining: "current_weekly_usage_count",
847
- });
848
- if (weekly !== null) {
849
- weeklyWindows.push({ percent: weekly, resetsAt: miniMaxResetAt(model, "weekly", nowMs) });
850
- }
851
- }
852
- }
853
-
854
- const session = pickHighestWindow(intervalWindows);
855
- const weekly = pickHighestWindow(weeklyWindows);
856
- if (!session) {
857
- return accountBalance
858
- ? { session: 0, weekly: 0, quotaHidden: true, accountBalance }
859
- : null;
860
- }
861
- return hydrateUsageResets({
862
- session: Number(session.percent.toFixed(2)),
863
- accountBalance,
864
- weekly: Number((weekly?.percent ?? 0).toFixed(2)),
865
- sessionLabel: "Interval",
866
- weeklyLabel: "Weekly",
867
- weeklyHidden: !weekly,
868
- sessionResetsAt: session.resetsAt,
869
- weeklyResetsAt: weekly?.resetsAt,
870
- }, nowMs);
871
- }
872
-
873
- function miniMaxPayloadStatus(payload: unknown): number | null {
874
- const root = asObject(payload);
875
- const data = asObject(root?.data);
876
- const baseResponse = asObject(data?.base_resp ?? data?.baseResp ?? root?.base_resp ?? root?.baseResp);
877
- return readNumber(baseResponse?.status_code ?? baseResponse?.statusCode);
878
- }
879
-
880
- function miniMaxPayloadError(payload: unknown): string | null {
881
- const root = asObject(payload);
882
- const data = asObject(root?.data);
883
- const baseResponse = asObject(data?.base_resp ?? data?.baseResp ?? root?.base_resp ?? root?.baseResp);
884
- const status = miniMaxPayloadStatus(payload);
885
- if (status === null || status === 0) return null;
886
- const message = baseResponse?.status_msg ?? baseResponse?.statusMessage;
887
- return typeof message === "string" && message.trim()
888
- ? `API ${status}: ${message.trim()}`
889
- : `API ${status}`;
890
- }
891
-
892
- export async function fetchMiniMaxUsage(
893
- token: string,
894
- provider: "minimax" | "minimax-cn" = "minimax",
895
- config: FetchConfig = {},
896
- ): Promise<UsageData> {
897
- const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
898
- const candidates = provider === "minimax-cn"
899
- ? [endpoints.minimaxCn, endpoints.minimaxCnLegacy]
900
- : [endpoints.minimax, endpoints.minimaxLegacy];
901
- let lastError = "usage request failed";
902
- let credentialError: string | undefined;
903
- let noActiveTokenPlan = false;
904
-
905
- for (const endpoint of [...new Set(candidates)]) {
906
- const result = await requestJson(endpoint, {
907
- headers: {
908
- Authorization: `Bearer ${token}`,
909
- Accept: "application/json",
910
- },
911
- }, config);
912
- if (!result.ok) {
913
- lastError = result.error;
914
- if (result.status === 401 || result.status === 403) credentialError ??= result.error;
915
- if (config.signal?.aborted) break;
916
- continue;
917
- }
918
- const payloadStatus = miniMaxPayloadStatus(result.data);
919
- const payloadError = miniMaxPayloadError(result.data);
920
- const usage = extractMiniMaxUsageFromPayload(result.data);
921
- if (usage && (!payloadError || usage.quotaHidden)) return usage;
922
- if (payloadStatus === 2062) {
923
- noActiveTokenPlan = true;
924
- continue;
925
- }
926
- if (payloadError) {
927
- lastError = payloadError;
928
- continue;
929
- }
930
- lastError = "unrecognized response shape";
931
- }
932
-
933
- if (noActiveTokenPlan) {
934
- return {
935
- session: 0,
936
- weekly: 0,
937
- quotaHidden: true,
938
- notice: "No active Token Plan · check Credit balance in the MiniMax console",
939
- };
940
- }
941
- return { session: 0, weekly: 0, error: credentialError ?? lastError };
942
- }
943
-
944
- export function extractOpenRouterUsageFromPayloads(
945
- creditsPayload: unknown,
946
- keyPayload: unknown,
947
- ): UsageData | null {
948
- const credits = asObject(asObject(creditsPayload)?.data) ?? asObject(creditsPayload);
949
- const key = asObject(asObject(keyPayload)?.data) ?? asObject(keyPayload);
950
-
951
- const totalCredits = readNumber(credits?.total_credits ?? credits?.totalCredits);
952
- const totalUsage = readNumber(credits?.total_usage ?? credits?.totalUsage);
953
- const accountBalance = totalCredits !== null && totalUsage !== null
954
- ? {
955
- amount: Number((totalCredits - totalUsage).toFixed(6)),
956
- unit: "USD",
957
- label: "Balance",
958
- }
959
- : undefined;
960
-
961
- const spendValues = {
962
- daily: readNumber(key?.usage_daily ?? key?.usageDaily),
963
- weekly: readNumber(key?.usage_weekly ?? key?.usageWeekly),
964
- monthly: readNumber(key?.usage_monthly ?? key?.usageMonthly),
965
- lifetime: readNumber(key?.usage),
966
- };
967
- const accountSpend = Object.values(spendValues).some((value) => value !== null)
968
- ? {
969
- unit: "USD",
970
- daily: spendValues.daily ?? undefined,
971
- weekly: spendValues.weekly ?? undefined,
972
- monthly: spendValues.monthly ?? undefined,
973
- lifetime: spendValues.lifetime ?? undefined,
974
- }
975
- : undefined;
976
-
977
- const limit = readNumber(key?.limit);
978
- const remaining = readNumber(key?.limit_remaining ?? key?.limitRemaining);
979
- const limitUsed = limit !== null && limit > 0 && remaining !== null
980
- ? Math.max(0, Math.min(limit, limit - remaining))
981
- : null;
982
- const limitPercent = limitUsed !== null && limit !== null ? limitUsed / limit * 100 : null;
983
- if (!accountBalance && !accountSpend && limitPercent === null) return null;
984
-
985
- return {
986
- session: limitPercent === null ? 0 : Number(limitPercent.toFixed(2)),
987
- weekly: 0,
988
- quotaHidden: limitPercent === null,
989
- weeklyHidden: true,
990
- sessionLabel: "Key limit",
991
- accountBalance,
992
- accountSpend,
993
- };
994
- }
995
-
996
- export async function fetchOpenRouterUsage(token: string, config: FetchConfig = {}): Promise<UsageData> {
997
- const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
998
- const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
999
- const [creditsResult, keyResult] = await Promise.all([
1000
- requestJson(endpoints.openRouterCredits, { headers }, config),
1001
- requestJson(endpoints.openRouterKey, { headers }, config),
1002
- ]);
1003
- const usage = extractOpenRouterUsageFromPayloads(
1004
- creditsResult.ok ? creditsResult.data : undefined,
1005
- keyResult.ok ? keyResult.data : undefined,
1006
- );
1007
- if (usage) return usage;
1008
-
1009
- const errors = [
1010
- creditsResult.ok ? undefined : `credits: ${creditsResult.error}`,
1011
- keyResult.ok ? undefined : `key: ${keyResult.error}`,
1012
- ].filter((value): value is string => Boolean(value));
1013
- return {
1014
- session: 0,
1015
- weekly: 0,
1016
- error: errors.length > 0 ? errors.join("; ") : "unrecognized response shape",
1017
- };
1018
- }
1019
-
1020
- export function extractDeepSeekBalanceFromPayload(payload: unknown): UsageData | null {
1021
- const root = asObject(payload);
1022
- const rawBalances = Array.isArray(root?.balance_infos) ? root.balance_infos : [];
1023
- const balances = rawBalances.map(asObject).filter((value): value is Record<string, unknown> => value !== null);
1024
- if (balances.length === 0) return null;
1025
-
1026
- const parsed = balances.flatMap((balance) => {
1027
- const unit = typeof balance.currency === "string" ? balance.currency.toUpperCase() : "USD";
1028
- const total = readNumber(balance.total_balance ?? balance.totalBalance);
1029
- if (total === null) return [];
1030
- return [{
1031
- total: { amount: total, unit, label: "Total balance" } satisfies AccountBalance,
1032
- toppedUp: readNumber(balance.topped_up_balance ?? balance.toppedUpBalance),
1033
- granted: readNumber(balance.granted_balance ?? balance.grantedBalance),
1034
- }];
1035
- });
1036
- const primary = parsed[0];
1037
- if (!primary) return null;
1038
-
1039
- const details: AccountBalance[] = [];
1040
- if (primary.toppedUp !== null) {
1041
- details.push({ amount: primary.toppedUp, unit: primary.total.unit, label: "Topped up" });
1042
- }
1043
- if (primary.granted !== null) {
1044
- details.push({ amount: primary.granted, unit: primary.total.unit, label: "Granted" });
1045
- }
1046
- for (const additional of parsed.slice(1)) details.push(additional.total);
1047
-
1048
- return {
1049
- session: 0,
1050
- weekly: 0,
1051
- quotaHidden: true,
1052
- accountBalance: primary.total,
1053
- accountBalanceDetails: details,
1054
- warning: root?.is_available === false ? "Balance is not currently available for API use" : undefined,
1055
- };
1056
- }
1057
-
1058
- export async function fetchDeepSeekBalance(token: string, config: FetchConfig = {}): Promise<UsageData> {
1059
- const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1060
- const result = await requestJson(endpoints.deepSeekBalance, {
1061
- headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
1062
- }, config);
1063
- if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1064
- return extractDeepSeekBalanceFromPayload(result.data) ?? {
1065
- session: 0,
1066
- weekly: 0,
1067
- error: "unrecognized response shape",
1068
- };
1069
- }
1070
-
1071
- export function extractMoonshotBalanceFromPayload(
1072
- payload: unknown,
1073
- provider: "moonshot" | "moonshot-cn" = "moonshot",
1074
- ): UsageData | null {
1075
- const root = asObject(payload);
1076
- const data = asObject(root?.data) ?? root;
1077
- if (!data) return null;
1078
- const available = readNumber(data.available_balance ?? data.availableBalance);
1079
- if (available === null) return null;
1080
- const cash = readNumber(data.cash_balance ?? data.cashBalance);
1081
- const voucher = readNumber(data.voucher_balance ?? data.voucherBalance);
1082
- const unit = provider === "moonshot-cn" ? "CNY" : "USD";
1083
- const details: AccountBalance[] = [];
1084
- if (cash !== null) details.push({ amount: cash, unit, label: "Cash" });
1085
- if (voucher !== null) details.push({ amount: voucher, unit, label: "Voucher" });
1086
-
1087
- return {
1088
- session: 0,
1089
- weekly: 0,
1090
- quotaHidden: true,
1091
- accountBalance: { amount: available, unit, label: "Available balance" },
1092
- accountBalanceDetails: details,
1093
- warning: available <= 0 ? "Balance exhausted; inference requests may be rejected" : undefined,
1094
- };
1095
- }
1096
-
1097
- export async function fetchMoonshotBalance(
1098
- token: string,
1099
- provider: "moonshot" | "moonshot-cn" = "moonshot",
1100
- config: FetchConfig = {},
1101
- ): Promise<UsageData> {
1102
- const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1103
- const endpoint = provider === "moonshot-cn" ? endpoints.moonshotCnBalance : endpoints.moonshotBalance;
1104
- const result = await requestJson(endpoint, {
1105
- headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
1106
- }, config);
1107
- if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1108
- return extractMoonshotBalanceFromPayload(result.data, provider) ?? {
1109
- session: 0,
1110
- weekly: 0,
1111
- error: "unrecognized response shape",
1112
- };
1113
- }
1114
-
1115
- /** Parse ZAI limits where unit 3 is the five-hour window and unit 6 the weekly window. */
1116
- export function extractZaiUsageFromPayload(payload: unknown, nowMs = Date.now()): UsageData | null {
1117
- const data = payload as any;
1118
- const arrays = [data?.data?.limits, data?.limits, data?.quota?.limits, data?.data?.quota?.limits];
1119
- const limits = arrays.find(Array.isArray) as any[] | undefined;
1120
- if (!limits?.length) return null;
1121
-
1122
- // CREDIT_LIMIT (GLM Coding Plan "lite"/credit-based tiers) reports the same
1123
- // unit/percentage/nextResetTime shape as TOKENS_LIMIT, so treat both as the
1124
- // quota windows for session (unit 3) and weekly (unit 6).
1125
- const tokenLimits = limits.filter((entry) => {
1126
- const type = String(entry?.type || "").toUpperCase();
1127
- return type === "TOKENS_LIMIT" || type === "CREDIT_LIMIT";
1128
- });
1129
- const sessionEntry = tokenLimits.find((entry) => entry?.unit === 3);
1130
- const weeklyEntry = tokenLimits.find((entry) => entry?.unit === 6);
1131
- if (!sessionEntry || !weeklyEntry) return null;
1132
-
1133
- const session = readPercentCandidate(sessionEntry.percentage);
1134
- const weekly = readPercentCandidate(weeklyEntry.percentage);
1135
- if (session === null || weekly === null) return null;
1136
- const normalized = normalizeUsagePair(session, weekly);
1137
-
1138
- return {
1139
- ...normalized,
1140
- sessionResetsIn: typeof sessionEntry.nextResetTime === "number" && sessionEntry.nextResetTime > 0
1141
- ? formatDuration(Math.max(0, sessionEntry.nextResetTime - nowMs) / 1000)
1142
- : undefined,
1143
- weeklyResetsIn: typeof weeklyEntry.nextResetTime === "number" && weeklyEntry.nextResetTime > 0
1144
- ? formatDuration(Math.max(0, weeklyEntry.nextResetTime - nowMs) / 1000)
1145
- : undefined,
1146
- };
1147
- }
1148
-
1149
- export async function fetchZaiUsage(
1150
- token: string,
1151
- provider: "zai" | "zai-cn" = "zai",
1152
- config: FetchConfig = {},
1153
- ): Promise<UsageData> {
1154
- const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1155
- const endpoint = provider === "zai-cn" ? endpoints.zaiCn : endpoints.zai;
1156
- const result = await requestJson(endpoint, { headers: { Authorization: `Bearer ${token}` } }, config);
1157
- if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1158
-
1159
- const zaiUsage = extractZaiUsageFromPayload(result.data);
1160
- if (zaiUsage) return zaiUsage;
1161
- return extractUsageFromPayload(result.data) ?? { session: 0, weekly: 0, error: "unrecognized response shape" };
1162
- }
1163
-
1164
- export function detectProvider(
1165
- model: { provider?: string } | string | undefined | null,
1166
- ): ProviderKey | null {
1167
- if (!model || typeof model === "string") return null;
1168
- switch ((model.provider || "").toLowerCase()) {
1169
- case "openai-codex": return "codex";
1170
- case "anthropic": return "claude";
1171
- case "zai": return "zai";
1172
- case "zai-coding-cn": return "zai-cn";
1173
- case "kimi-coding": return "kimi";
1174
- case "minimax": return "minimax";
1175
- case "minimax-cn": return "minimax-cn";
1176
- case "openrouter": return "openrouter";
1177
- case "deepseek": return "deepseek";
1178
- case "moonshotai": return "moonshot";
1179
- case "moonshotai-cn": return "moonshot-cn";
1180
- default: return null;
1181
- }
1182
- }
1183
-
1184
- export function providerToPiProviderId(provider: ProviderKey): PiProviderId {
1185
- switch (provider) {
1186
- case "codex": return "openai-codex";
1187
- case "claude": return "anthropic";
1188
- case "zai": return "zai";
1189
- case "zai-cn": return "zai-coding-cn";
1190
- case "kimi": return "kimi-coding";
1191
- case "minimax": return "minimax";
1192
- case "minimax-cn": return "minimax-cn";
1193
- case "openrouter": return "openrouter";
1194
- case "deepseek": return "deepseek";
1195
- case "moonshot": return "moonshotai";
1196
- case "moonshot-cn": return "moonshotai-cn";
1197
- }
1198
- }
1199
-
1200
- export function clampPercent(value: number): number {
1201
- if (!Number.isFinite(value)) return 0;
1202
- return Math.max(0, Math.min(100, Math.round(value)));
1203
- }
1204
-
1205
- export function colorForPercent(value: number): "success" | "warning" | "error" {
1206
- if (value >= 90) return "error";
1207
- if (value >= 70) return "warning";
1208
- return "success";
1209
- }
1210
-
1211
- export async function fetchAllUsages(
1212
- tokens: UsageTokens,
1213
- config: FetchAllUsagesConfig = {},
1214
- ): Promise<UsageByProvider> {
1215
- const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1216
- const results: UsageByProvider = {
1217
- codex: null,
1218
- claude: null,
1219
- zai: null,
1220
- "zai-cn": null,
1221
- kimi: null,
1222
- minimax: null,
1223
- "minimax-cn": null,
1224
- openrouter: null,
1225
- deepseek: null,
1226
- moonshot: null,
1227
- "moonshot-cn": null,
1228
- };
1229
- const tasks: Promise<void>[] = [];
1230
-
1231
- const assign = (provider: ProviderKey, request: Promise<UsageData>) => {
1232
- tasks.push(request.then((usage) => {
1233
- results[provider] = usage;
1234
- }).catch((error) => {
1235
- results[provider] = { session: 0, weekly: 0, error: toErrorMessage(error, config.signal) };
1236
- }));
1237
- };
1238
-
1239
- if (tokens.codex) assign("codex", fetchCodexUsage(tokens.codex, config));
1240
- if (tokens.claude) {
1241
- assign("claude", fetchClaudeUsageWithFallback(tokens.claude, {
1242
- ...config,
1243
- cacheFile: config.cacheFile,
1244
- nowMs: config.nowMs,
1245
- }));
1246
- }
1247
- if (tokens.zai) assign("zai", fetchZaiUsage(tokens.zai, "zai", { ...config, endpoints }));
1248
- if (tokens["zai-cn"]) assign("zai-cn", fetchZaiUsage(tokens["zai-cn"], "zai-cn", { ...config, endpoints }));
1249
- if (tokens.kimi) assign("kimi", fetchKimiUsage(tokens.kimi, { ...config, endpoints }));
1250
- if (tokens.minimax) assign("minimax", fetchMiniMaxUsage(tokens.minimax, "minimax", { ...config, endpoints }));
1251
- if (tokens["minimax-cn"]) {
1252
- assign("minimax-cn", fetchMiniMaxUsage(tokens["minimax-cn"], "minimax-cn", { ...config, endpoints }));
1253
- }
1254
- if (tokens.openrouter) assign("openrouter", fetchOpenRouterUsage(tokens.openrouter, { ...config, endpoints }));
1255
- if (tokens.deepseek) assign("deepseek", fetchDeepSeekBalance(tokens.deepseek, { ...config, endpoints }));
1256
- if (tokens.moonshot) assign("moonshot", fetchMoonshotBalance(tokens.moonshot, "moonshot", { ...config, endpoints }));
1257
- if (tokens["moonshot-cn"]) {
1258
- assign("moonshot-cn", fetchMoonshotBalance(tokens["moonshot-cn"], "moonshot-cn", { ...config, endpoints }));
1259
- }
1260
-
1261
- await Promise.all(tasks);
1262
-
1263
- // Pi intentionally uses MOONSHOT_API_KEY for both regional providers. When one
1264
- // key works in only one region, hide the expected regional auth failure from
1265
- // the all-provider view while preserving active-provider polling behavior.
1266
- if (tokens.moonshot && tokens.moonshot === tokens["moonshot-cn"]) {
1267
- if (results.moonshot && !results.moonshot.error && results["moonshot-cn"]?.error) {
1268
- results["moonshot-cn"] = null;
1269
- } else if (results["moonshot-cn"] && !results["moonshot-cn"].error && results.moonshot?.error) {
1270
- results.moonshot = null;
1271
- }
1272
- }
1273
- return results;
1274
- }
1
+ import * as fs from "node:fs";
2
+ import * as os from "node:os";
3
+ import * as path from "node:path";
4
+
5
+ export type ProviderKey =
6
+ | "codex"
7
+ | "claude"
8
+ | "zai"
9
+ | "zai-cn"
10
+ | "kimi"
11
+ | "minimax"
12
+ | "minimax-cn"
13
+ | "openrouter"
14
+ | "deepseek"
15
+ | "moonshot"
16
+ | "moonshot-cn"
17
+ | "baseten"
18
+ | "vercel"
19
+ | "fireworks"
20
+ | "xai";
21
+ export type PiProviderId =
22
+ | "openai-codex"
23
+ | "anthropic"
24
+ | "zai"
25
+ | "zai-coding-cn"
26
+ | "kimi-coding"
27
+ | "minimax"
28
+ | "minimax-cn"
29
+ | "openrouter"
30
+ | "deepseek"
31
+ | "moonshotai"
32
+ | "moonshotai-cn"
33
+ | "baseten"
34
+ | "vercel-ai-gateway"
35
+ | "fireworks"
36
+ | "pi-usage-bars-xai-management";
37
+
38
+ export interface AccountBalance {
39
+ amount: number;
40
+ unit: string;
41
+ label: string;
42
+ }
43
+
44
+ export interface AccountSpend {
45
+ unit: string;
46
+ daily?: number;
47
+ weekly?: number;
48
+ monthly?: number;
49
+ lifetime?: number;
50
+ }
51
+
52
+ export interface UsageData {
53
+ session: number;
54
+ weekly: number;
55
+ quotaHidden?: boolean;
56
+ accountBalance?: AccountBalance;
57
+ accountBalanceDetails?: AccountBalance[];
58
+ accountUsage?: AccountBalance;
59
+ accountSpend?: AccountSpend;
60
+ sessionResetsIn?: string;
61
+ weeklyResetsIn?: string;
62
+ sessionResetsAt?: string;
63
+ weeklyResetsAt?: string;
64
+ extraSpend?: number;
65
+ extraLimit?: number;
66
+ sessionLabel?: string;
67
+ weeklyLabel?: string;
68
+ sessionHidden?: boolean;
69
+ weeklyHidden?: boolean;
70
+ notice?: string;
71
+ warning?: string;
72
+ stale?: boolean;
73
+ fetchedAt?: number;
74
+ error?: string;
75
+ }
76
+
77
+ export type UsageByProvider = Record<ProviderKey, UsageData | null>;
78
+ export type UsageTokens = Partial<Record<ProviderKey, string>>;
79
+
80
+ export interface UsageEndpoints {
81
+ zai: string;
82
+ zaiCn: string;
83
+ kimi: string;
84
+ minimax: string;
85
+ minimaxLegacy: string;
86
+ minimaxCn: string;
87
+ minimaxCnLegacy: string;
88
+ openRouterCredits: string;
89
+ openRouterKey: string;
90
+ deepSeekBalance: string;
91
+ moonshotBalance: string;
92
+ moonshotCnBalance: string;
93
+ basetenUsage: string;
94
+ vercelCredits: string;
95
+ fireworksApi: string;
96
+ fireworksAccountId?: string;
97
+ xaiManagementApi: string;
98
+ }
99
+
100
+ export interface HeadersLike {
101
+ get(name: string): string | null;
102
+ }
103
+
104
+ export interface FetchResponseLike {
105
+ ok: boolean;
106
+ status: number;
107
+ headers?: HeadersLike;
108
+ json(): Promise<unknown>;
109
+ }
110
+
111
+ export type FetchLike = (input: string, init?: RequestInit) => Promise<FetchResponseLike>;
112
+
113
+ export interface RequestConfig {
114
+ fetchFn?: FetchLike;
115
+ timeoutMs?: number;
116
+ signal?: AbortSignal;
117
+ }
118
+
119
+ export interface FetchConfig extends RequestConfig {
120
+ endpoints?: UsageEndpoints;
121
+ env?: NodeJS.ProcessEnv;
122
+ }
123
+
124
+ export interface FetchAllUsagesConfig extends FetchConfig {
125
+ cacheFile?: string;
126
+ nowMs?: number;
127
+ }
128
+
129
+ export interface ClaudeUsageFetchConfig extends RequestConfig {
130
+ cacheFile?: string;
131
+ nowMs?: number;
132
+ }
133
+
134
+ export interface BasetenUsageFetchConfig extends FetchConfig {
135
+ nowMs?: number;
136
+ }
137
+
138
+ export interface FireworksUsageFetchConfig extends FetchConfig {
139
+ nowMs?: number;
140
+ }
141
+
142
+ interface JsonRequestSuccess {
143
+ ok: true;
144
+ data: unknown;
145
+ status: number;
146
+ headers?: HeadersLike;
147
+ }
148
+
149
+ interface JsonRequestError {
150
+ ok: false;
151
+ error: string;
152
+ status: number | null;
153
+ headers?: HeadersLike;
154
+ }
155
+
156
+ type JsonRequestResult = JsonRequestSuccess | JsonRequestError;
157
+
158
+ interface ClaudeUsageAttemptResult {
159
+ usage: UsageData;
160
+ status: number | null;
161
+ retryAfterMs: number | null;
162
+ }
163
+
164
+ interface ClaudeUsageCacheState {
165
+ lastSuccess?: UsageData;
166
+ lastSuccessAt?: number;
167
+ cooldownUntil?: number;
168
+ consecutive429s?: number;
169
+ lastError?: string;
170
+ }
171
+
172
+ interface UsageBarsCacheFile {
173
+ version: 1;
174
+ claude?: ClaudeUsageCacheState;
175
+ }
176
+
177
+ const DEFAULT_FETCH_TIMEOUT_MS = 12_000;
178
+ const CLAUDE_SHARED_FRESH_TTL_MS = 2 * 60 * 1000;
179
+ const CLAUDE_BASE_BACKOFF_MS = 2 * 60 * 1000;
180
+ const CLAUDE_MAX_BACKOFF_MS = 30 * 60 * 1000;
181
+ const CLAUDE_LOCK_WAIT_MS = 4_000;
182
+ const CLAUDE_LOCK_POLL_MS = 125;
183
+ const CLAUDE_LOCK_STALE_MS = 20_000;
184
+
185
+ export const DEFAULT_USAGE_CACHE_FILE = path.join(os.tmpdir(), "pi", "usage-bars-cache.json");
186
+ export const DEFAULT_ZAI_USAGE_ENDPOINT = "https://api.z.ai/api/monitor/usage/quota/limit";
187
+ export const DEFAULT_ZAI_CN_USAGE_ENDPOINT = "https://open.bigmodel.cn/api/monitor/usage/quota/limit";
188
+ export const DEFAULT_KIMI_USAGE_ENDPOINT = "https://api.kimi.com/coding/v1/usages";
189
+ export const DEFAULT_MINIMAX_USAGE_ENDPOINT = "https://api.minimax.io/v1/token_plan/remains";
190
+ export const DEFAULT_MINIMAX_LEGACY_USAGE_ENDPOINT = "https://api.minimax.io/v1/api/openplatform/coding_plan/remains";
191
+ export const DEFAULT_MINIMAX_CN_USAGE_ENDPOINT = "https://api.minimaxi.com/v1/token_plan/remains";
192
+ export const DEFAULT_MINIMAX_CN_LEGACY_USAGE_ENDPOINT = "https://api.minimaxi.com/v1/api/openplatform/coding_plan/remains";
193
+ export const DEFAULT_OPENROUTER_CREDITS_ENDPOINT = "https://openrouter.ai/api/v1/credits";
194
+ export const DEFAULT_OPENROUTER_KEY_ENDPOINT = "https://openrouter.ai/api/v1/key";
195
+ export const DEFAULT_DEEPSEEK_BALANCE_ENDPOINT = "https://api.deepseek.com/user/balance";
196
+ export const DEFAULT_MOONSHOT_BALANCE_ENDPOINT = "https://api.moonshot.ai/v1/users/me/balance";
197
+ export const DEFAULT_MOONSHOT_CN_BALANCE_ENDPOINT = "https://api.moonshot.cn/v1/users/me/balance";
198
+ export const DEFAULT_BASETEN_USAGE_ENDPOINT = "https://api.baseten.co/v1/billing/usage_summary";
199
+ export const DEFAULT_VERCEL_CREDITS_ENDPOINT = "https://ai-gateway.vercel.sh/v1/credits";
200
+ export const DEFAULT_FIREWORKS_API_ENDPOINT = "https://api.fireworks.ai/v1";
201
+ export const DEFAULT_XAI_MANAGEMENT_API_ENDPOINT = "https://management-api.x.ai";
202
+ export const XAI_MANAGEMENT_PROVIDER_ID = "pi-usage-bars-xai-management";
203
+
204
+ export function resolveUsageEndpoints(env: NodeJS.ProcessEnv = process.env): UsageEndpoints {
205
+ const configured = (value: string | undefined, fallback: string) => {
206
+ const trimmed = value?.trim();
207
+ return trimmed || fallback;
208
+ };
209
+
210
+ return {
211
+ zai: configured(env.PI_ZAI_USAGE_ENDPOINT, DEFAULT_ZAI_USAGE_ENDPOINT),
212
+ zaiCn: configured(env.PI_ZAI_CODING_CN_USAGE_ENDPOINT, DEFAULT_ZAI_CN_USAGE_ENDPOINT),
213
+ kimi: configured(env.PI_KIMI_USAGE_ENDPOINT, DEFAULT_KIMI_USAGE_ENDPOINT),
214
+ minimax: configured(env.PI_MINIMAX_USAGE_ENDPOINT, DEFAULT_MINIMAX_USAGE_ENDPOINT),
215
+ minimaxLegacy: configured(env.PI_MINIMAX_LEGACY_USAGE_ENDPOINT, DEFAULT_MINIMAX_LEGACY_USAGE_ENDPOINT),
216
+ minimaxCn: configured(env.PI_MINIMAX_CN_USAGE_ENDPOINT, DEFAULT_MINIMAX_CN_USAGE_ENDPOINT),
217
+ minimaxCnLegacy: configured(env.PI_MINIMAX_CN_LEGACY_USAGE_ENDPOINT, DEFAULT_MINIMAX_CN_LEGACY_USAGE_ENDPOINT),
218
+ openRouterCredits: configured(env.PI_OPENROUTER_CREDITS_ENDPOINT, DEFAULT_OPENROUTER_CREDITS_ENDPOINT),
219
+ openRouterKey: configured(env.PI_OPENROUTER_KEY_ENDPOINT, DEFAULT_OPENROUTER_KEY_ENDPOINT),
220
+ deepSeekBalance: configured(env.PI_DEEPSEEK_BALANCE_ENDPOINT, DEFAULT_DEEPSEEK_BALANCE_ENDPOINT),
221
+ moonshotBalance: configured(env.PI_MOONSHOT_BALANCE_ENDPOINT, DEFAULT_MOONSHOT_BALANCE_ENDPOINT),
222
+ moonshotCnBalance: configured(env.PI_MOONSHOT_CN_BALANCE_ENDPOINT, DEFAULT_MOONSHOT_CN_BALANCE_ENDPOINT),
223
+ basetenUsage: configured(env.PI_BASETEN_USAGE_ENDPOINT, DEFAULT_BASETEN_USAGE_ENDPOINT),
224
+ vercelCredits: configured(env.PI_VERCEL_AI_GATEWAY_CREDITS_ENDPOINT, DEFAULT_VERCEL_CREDITS_ENDPOINT),
225
+ fireworksApi: configured(env.PI_FIREWORKS_API_ENDPOINT, DEFAULT_FIREWORKS_API_ENDPOINT),
226
+ fireworksAccountId: env.PI_FIREWORKS_ACCOUNT_ID?.trim() || undefined,
227
+ xaiManagementApi: configured(env.PI_XAI_MANAGEMENT_API_ENDPOINT, DEFAULT_XAI_MANAGEMENT_API_ENDPOINT),
228
+ };
229
+ }
230
+
231
+ function toErrorMessage(error: unknown, externalSignal?: AbortSignal): string {
232
+ if (error instanceof Error) {
233
+ if (error.name === "AbortError") {
234
+ return externalSignal?.aborted ? "request cancelled" : "request timeout";
235
+ }
236
+ return error.message || String(error);
237
+ }
238
+ return String(error);
239
+ }
240
+
241
+ function asObject(value: unknown): Record<string, unknown> | null {
242
+ if (!value || typeof value !== "object") return null;
243
+ return value as Record<string, unknown>;
244
+ }
245
+
246
+ function normalizeUsagePair(session: number, weekly: number): { session: number; weekly: number } {
247
+ const clean = (value: number) => Number.isFinite(value) ? Number(value.toFixed(2)) : 0;
248
+ return { session: clean(session), weekly: clean(weekly) };
249
+ }
250
+
251
+ function getHeader(headers: HeadersLike | undefined, name: string): string | null {
252
+ if (!headers) return null;
253
+ try {
254
+ return headers.get(name);
255
+ } catch {
256
+ return null;
257
+ }
258
+ }
259
+
260
+ function combineSignals(timeoutSignal: AbortSignal | undefined, externalSignal: AbortSignal | undefined): AbortSignal | undefined {
261
+ if (timeoutSignal && externalSignal) return AbortSignal.any([timeoutSignal, externalSignal]);
262
+ return timeoutSignal ?? externalSignal;
263
+ }
264
+
265
+ async function requestJson(url: string, init: RequestInit, config: RequestConfig = {}): Promise<JsonRequestResult> {
266
+ const fetchFn = config.fetchFn ?? (fetch as unknown as FetchLike);
267
+ const timeoutMs = config.timeoutMs ?? DEFAULT_FETCH_TIMEOUT_MS;
268
+ const timeoutController = timeoutMs > 0 ? new AbortController() : undefined;
269
+ const timeout = timeoutController
270
+ ? setTimeout(() => timeoutController.abort(), timeoutMs)
271
+ : undefined;
272
+ const signal = combineSignals(timeoutController?.signal, config.signal);
273
+
274
+ try {
275
+ if (config.signal?.aborted) {
276
+ return { ok: false, error: "request cancelled", status: null };
277
+ }
278
+
279
+ const response = await fetchFn(url, { ...init, signal });
280
+ if (!response.ok) {
281
+ return { ok: false, error: `HTTP ${response.status}`, status: response.status, headers: response.headers };
282
+ }
283
+
284
+ try {
285
+ return { ok: true, data: await response.json(), status: response.status, headers: response.headers };
286
+ } catch {
287
+ return { ok: false, error: "invalid JSON response", status: response.status, headers: response.headers };
288
+ }
289
+ } catch (error) {
290
+ return { ok: false, error: toErrorMessage(error, config.signal), status: null };
291
+ } finally {
292
+ if (timeout !== undefined) clearTimeout(timeout);
293
+ }
294
+ }
295
+
296
+ export function formatDuration(seconds: number): string {
297
+ if (!Number.isFinite(seconds) || seconds <= 0) return "now";
298
+ const days = Math.floor(seconds / 86400);
299
+ const hours = Math.floor((seconds % 86400) / 3600);
300
+ const minutes = Math.floor((seconds % 3600) / 60);
301
+ if (days > 0 && hours > 0) return `${days}d ${hours}h`;
302
+ if (days > 0) return `${days}d`;
303
+ if (hours > 0 && minutes > 0) return `${hours}h ${minutes}m`;
304
+ if (hours > 0) return `${hours}h`;
305
+ if (minutes > 0) return `${minutes}m`;
306
+ return "<1m";
307
+ }
308
+
309
+ export function formatResetsAt(isoDate: string, nowMs = Date.now()): string {
310
+ const resetTime = new Date(isoDate).getTime();
311
+ if (!Number.isFinite(resetTime)) return "";
312
+ return formatDuration(Math.max(0, resetTime - nowMs) / 1000);
313
+ }
314
+
315
+ export function parseRetryAfterMs(value: string | null | undefined, nowMs = Date.now()): number | null {
316
+ if (!value) return null;
317
+ const numeric = Number(value);
318
+ if (Number.isFinite(numeric) && numeric >= 0) return numeric * 1000;
319
+ const dateMs = new Date(value).getTime();
320
+ return Number.isFinite(dateMs) ? Math.max(0, dateMs - nowMs) : null;
321
+ }
322
+
323
+ function readUsageCache(cacheFile = DEFAULT_USAGE_CACHE_FILE): UsageBarsCacheFile {
324
+ try {
325
+ const parsed = JSON.parse(fs.readFileSync(cacheFile, "utf-8"));
326
+ if (parsed?.version === 1 && typeof parsed === "object") return parsed as UsageBarsCacheFile;
327
+ } catch {
328
+ // Invalid or missing caches are treated as empty.
329
+ }
330
+ return { version: 1 };
331
+ }
332
+
333
+ function writeUsageCache(cache: UsageBarsCacheFile, cacheFile = DEFAULT_USAGE_CACHE_FILE): boolean {
334
+ try {
335
+ const directory = path.dirname(cacheFile);
336
+ if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
337
+ const temporaryPath = `${cacheFile}.tmp-${process.pid}-${Date.now()}`;
338
+ fs.writeFileSync(temporaryPath, JSON.stringify(cache, null, 2), { mode: 0o600 });
339
+ fs.renameSync(temporaryPath, cacheFile);
340
+ return true;
341
+ } catch {
342
+ return false;
343
+ }
344
+ }
345
+
346
+ function sleep(ms: number, signal?: AbortSignal): Promise<void> {
347
+ if (signal?.aborted) return Promise.reject(new DOMException("Aborted", "AbortError"));
348
+ return new Promise((resolve, reject) => {
349
+ const timer = setTimeout(resolve, ms);
350
+ signal?.addEventListener("abort", () => {
351
+ clearTimeout(timer);
352
+ reject(new DOMException("Aborted", "AbortError"));
353
+ }, { once: true });
354
+ });
355
+ }
356
+
357
+ function ensureParentDir(filePath: string): void {
358
+ const directory = path.dirname(filePath);
359
+ if (!fs.existsSync(directory)) fs.mkdirSync(directory, { recursive: true, mode: 0o700 });
360
+ }
361
+
362
+ function safeUnlink(filePath: string): void {
363
+ try {
364
+ fs.unlinkSync(filePath);
365
+ } catch {
366
+ // Ignore cleanup races.
367
+ }
368
+ }
369
+
370
+ async function acquireFileLock(lockFile: string, signal?: AbortSignal): Promise<(() => void) | null> {
371
+ ensureParentDir(lockFile);
372
+ const startedAt = Date.now();
373
+
374
+ while (Date.now() - startedAt <= CLAUDE_LOCK_WAIT_MS) {
375
+ if (signal?.aborted) return null;
376
+ try {
377
+ const fd = fs.openSync(lockFile, "wx", 0o600);
378
+ fs.writeFileSync(fd, JSON.stringify({ pid: process.pid, createdAt: Date.now() }));
379
+ fs.closeSync(fd);
380
+ return () => safeUnlink(lockFile);
381
+ } catch (error: unknown) {
382
+ if ((error as NodeJS.ErrnoException)?.code !== "EEXIST") return null;
383
+ try {
384
+ const stat = fs.statSync(lockFile);
385
+ if (Date.now() - stat.mtimeMs >= CLAUDE_LOCK_STALE_MS) {
386
+ safeUnlink(lockFile);
387
+ continue;
388
+ }
389
+ } catch {
390
+ continue;
391
+ }
392
+ try {
393
+ await sleep(CLAUDE_LOCK_POLL_MS, signal);
394
+ } catch {
395
+ return null;
396
+ }
397
+ }
398
+ }
399
+
400
+ return null;
401
+ }
402
+
403
+ export function readPercentCandidate(value: unknown): number | null {
404
+ if (typeof value !== "number" || !Number.isFinite(value)) return null;
405
+ if (value >= 0 && value <= 1) return Number.isInteger(value) ? value : value * 100;
406
+ return value >= 0 && value <= 100 ? value : null;
407
+ }
408
+
409
+ export function readLimitPercent(limit: unknown): number | null {
410
+ const value = asObject(limit);
411
+ const direct = [
412
+ value?.percentage,
413
+ value?.utilization,
414
+ value?.used_percent,
415
+ value?.usedPercent,
416
+ value?.usagePercent,
417
+ value?.usage_percent,
418
+ ].map(readPercentCandidate).find((candidate) => candidate !== null);
419
+ if (direct !== undefined) return direct;
420
+
421
+ const current = typeof value?.currentValue === "number" ? value.currentValue : null;
422
+ const remaining = typeof value?.remaining === "number" ? value.remaining : null;
423
+ if (current !== null && remaining !== null && current + remaining > 0) {
424
+ return (current / (current + remaining)) * 100;
425
+ }
426
+ return null;
427
+ }
428
+
429
+ export function extractUsageFromPayload(payload: unknown): { session: number; weekly: number } | null {
430
+ const data = payload as any;
431
+ const limitArrays = [data?.data?.limits, data?.limits, data?.quota?.limits, data?.data?.quota?.limits];
432
+ const limits = limitArrays.find(Array.isArray) as unknown[] | undefined;
433
+
434
+ if (limits) {
435
+ const byType = (types: string[]) => limits.find((entry) => {
436
+ const type = String((entry as any)?.type || "").toUpperCase();
437
+ return types.includes(type);
438
+ });
439
+ const session = readLimitPercent(byType(["TIME_LIMIT", "SESSION_LIMIT", "REQUEST_LIMIT", "RPM_LIMIT", "RPD_LIMIT"]));
440
+ const weekly = readLimitPercent(byType(["TOKENS_LIMIT", "TOKEN_LIMIT", "WEEK_LIMIT", "WEEKLY_LIMIT", "TPM_LIMIT", "DAILY_LIMIT"]));
441
+ if (session !== null && weekly !== null) return normalizeUsagePair(session, weekly);
442
+ }
443
+
444
+ const sessionCandidates = [
445
+ data?.session,
446
+ data?.sessionPercent,
447
+ data?.session_percent,
448
+ data?.five_hour?.utilization,
449
+ data?.rate_limit?.primary_window?.used_percent,
450
+ data?.limits?.session?.utilization,
451
+ data?.usage?.session,
452
+ data?.data?.session,
453
+ data?.data?.sessionPercent,
454
+ data?.data?.session_percent,
455
+ data?.data?.usage?.session,
456
+ data?.quota?.session?.percentage,
457
+ data?.data?.quota?.session?.percentage,
458
+ ];
459
+ const weeklyCandidates = [
460
+ data?.weekly,
461
+ data?.weeklyPercent,
462
+ data?.weekly_percent,
463
+ data?.seven_day?.utilization,
464
+ data?.rate_limit?.secondary_window?.used_percent,
465
+ data?.limits?.weekly?.utilization,
466
+ data?.usage?.weekly,
467
+ data?.data?.weekly,
468
+ data?.data?.weeklyPercent,
469
+ data?.data?.weekly_percent,
470
+ data?.data?.usage?.weekly,
471
+ data?.quota?.weekly?.percentage,
472
+ data?.data?.quota?.weekly?.percentage,
473
+ data?.quota?.daily?.percentage,
474
+ data?.data?.quota?.daily?.percentage,
475
+ ];
476
+
477
+ const session = sessionCandidates.map(readPercentCandidate).find((candidate) => candidate !== null);
478
+ const weekly = weeklyCandidates.map(readPercentCandidate).find((candidate) => candidate !== null);
479
+ return session === undefined || weekly === undefined ? null : normalizeUsagePair(session, weekly);
480
+ }
481
+
482
+ function hydrateUsageResets(usage: UsageData, nowMs = Date.now()): UsageData {
483
+ return {
484
+ ...usage,
485
+ sessionResetsIn: usage.sessionResetsAt ? formatResetsAt(usage.sessionResetsAt, nowMs) : usage.sessionResetsIn,
486
+ weeklyResetsIn: usage.weeklyResetsAt ? formatResetsAt(usage.weeklyResetsAt, nowMs) : usage.weeklyResetsIn,
487
+ };
488
+ }
489
+
490
+ function snapshotUsage(usage: UsageData, nowMs = Date.now()): UsageData {
491
+ return {
492
+ session: usage.session,
493
+ weekly: usage.weekly,
494
+ quotaHidden: usage.quotaHidden,
495
+ accountBalance: usage.accountBalance,
496
+ accountBalanceDetails: usage.accountBalanceDetails,
497
+ accountUsage: usage.accountUsage,
498
+ accountSpend: usage.accountSpend,
499
+ sessionResetsAt: usage.sessionResetsAt,
500
+ weeklyResetsAt: usage.weeklyResetsAt,
501
+ sessionResetsIn: usage.sessionResetsIn,
502
+ weeklyResetsIn: usage.weeklyResetsIn,
503
+ extraSpend: usage.extraSpend,
504
+ extraLimit: usage.extraLimit,
505
+ sessionLabel: usage.sessionLabel,
506
+ weeklyLabel: usage.weeklyLabel,
507
+ sessionHidden: usage.sessionHidden,
508
+ weeklyHidden: usage.weeklyHidden,
509
+ notice: usage.notice,
510
+ fetchedAt: usage.fetchedAt ?? nowMs,
511
+ };
512
+ }
513
+
514
+ function staleCachedUsage(cached: UsageData, warning: string, nowMs = Date.now()): UsageData {
515
+ return { ...hydrateUsageResets(snapshotUsage(cached, nowMs), nowMs), stale: true, warning };
516
+ }
517
+
518
+ function readClaudeCacheState(cacheFile = DEFAULT_USAGE_CACHE_FILE): ClaudeUsageCacheState {
519
+ return readUsageCache(cacheFile).claude ?? {};
520
+ }
521
+
522
+ function writeClaudeCacheState(state: ClaudeUsageCacheState, cacheFile = DEFAULT_USAGE_CACHE_FILE): boolean {
523
+ const cache = readUsageCache(cacheFile);
524
+ cache.claude = state;
525
+ return writeUsageCache(cache, cacheFile);
526
+ }
527
+
528
+ function clearClaudeCooldown(state: ClaudeUsageCacheState): ClaudeUsageCacheState {
529
+ return { ...state, cooldownUntil: undefined, consecutive429s: 0, lastError: undefined };
530
+ }
531
+
532
+ function computeClaudeBackoffMs(state: ClaudeUsageCacheState, retryAfterMs: number | null): number {
533
+ if (retryAfterMs !== null && retryAfterMs > 0) {
534
+ return Math.min(CLAUDE_MAX_BACKOFF_MS, Math.max(CLAUDE_BASE_BACKOFF_MS, retryAfterMs));
535
+ }
536
+ const count = Math.max(1, state.consecutive429s ?? 0);
537
+ return Math.min(CLAUDE_MAX_BACKOFF_MS, CLAUDE_BASE_BACKOFF_MS * 2 ** Math.max(0, count - 1));
538
+ }
539
+
540
+ function cooldownMessage(untilMs: number, nowMs = Date.now()): string {
541
+ return `rate limited; retry in ${formatDuration(Math.max(0, untilMs - nowMs) / 1000)}`;
542
+ }
543
+
544
+ function readClaudeCacheOutcome(cacheFile = DEFAULT_USAGE_CACHE_FILE, nowMs = Date.now()): UsageData | null {
545
+ const state = readClaudeCacheState(cacheFile);
546
+ if (state.cooldownUntil && state.cooldownUntil > nowMs) {
547
+ const warning = cooldownMessage(state.cooldownUntil, nowMs);
548
+ return state.lastSuccess
549
+ ? staleCachedUsage(state.lastSuccess, warning, nowMs)
550
+ : { session: 0, weekly: 0, error: warning };
551
+ }
552
+ if (state.lastSuccess && state.lastSuccessAt && nowMs - state.lastSuccessAt <= CLAUDE_SHARED_FRESH_TTL_MS) {
553
+ return hydrateUsageResets(snapshotUsage(state.lastSuccess, state.lastSuccessAt), nowMs);
554
+ }
555
+ return null;
556
+ }
557
+
558
+ export function parseCodexRateLimit(data: any): UsageData {
559
+ const rateLimit = data?.rate_limit ?? data?.rate_limits;
560
+ const primary = rateLimit?.primary_window ?? rateLimit?.primary ?? rateLimit?.five_hour;
561
+ const secondary = rateLimit?.secondary_window ?? rateLimit?.secondary ?? rateLimit?.weekly;
562
+
563
+ let sessionWindow: any = null;
564
+ let weeklyWindow: any = null;
565
+ for (const [position, window] of [["primary", primary], ["secondary", secondary]] as const) {
566
+ if (!window || typeof window !== "object") continue;
567
+ const duration = window.limit_window_seconds;
568
+ if (typeof duration === "number" && Number.isFinite(duration)) {
569
+ // Some Codex accounts return their seven-day quota as primary_window
570
+ // and omit secondary_window, so position alone does not identify it.
571
+ if (duration >= 2 * 24 * 60 * 60) weeklyWindow ??= window;
572
+ else sessionWindow ??= window;
573
+ } else if (position === "primary") {
574
+ sessionWindow ??= window;
575
+ } else {
576
+ weeklyWindow ??= window;
577
+ }
578
+ }
579
+
580
+ const reset = (window: any) =>
581
+ typeof window?.reset_after_seconds === "number" ? formatDuration(window.reset_after_seconds) : undefined;
582
+
583
+ return {
584
+ session: readPercentCandidate(sessionWindow?.used_percent) ?? 0,
585
+ weekly: readPercentCandidate(weeklyWindow?.used_percent) ?? 0,
586
+ ...(!sessionWindow ? { sessionHidden: true } : {}),
587
+ ...(!weeklyWindow ? { weeklyHidden: true } : {}),
588
+ sessionResetsIn: reset(sessionWindow),
589
+ weeklyResetsIn: reset(weeklyWindow),
590
+ };
591
+ }
592
+
593
+ export async function fetchCodexUsage(token: string, config: RequestConfig = {}): Promise<UsageData> {
594
+ const result = await requestJson(
595
+ "https://chatgpt.com/backend-api/wham/usage",
596
+ { headers: { Authorization: `Bearer ${token}` } },
597
+ config,
598
+ );
599
+ if (!result.ok) return { session: 0, weekly: 0, error: result.error };
600
+ return parseCodexRateLimit(result.data);
601
+ }
602
+
603
+ async function fetchClaudeUsageAttempt(
604
+ token: string,
605
+ config: RequestConfig = {},
606
+ nowMs = Date.now(),
607
+ ): Promise<ClaudeUsageAttemptResult> {
608
+ const result = await requestJson(
609
+ "https://api.anthropic.com/api/oauth/usage",
610
+ {
611
+ headers: {
612
+ Authorization: `Bearer ${token}`,
613
+ "anthropic-beta": "oauth-2025-04-20",
614
+ },
615
+ },
616
+ config,
617
+ );
618
+ const retryAfterMs = parseRetryAfterMs(getHeader(result.headers, "retry-after"), nowMs);
619
+ if (!result.ok) {
620
+ return { usage: { session: 0, weekly: 0, error: result.error }, status: result.status, retryAfterMs };
621
+ }
622
+
623
+ const data = result.data as any;
624
+ const usage: UsageData = hydrateUsageResets({
625
+ session: readPercentCandidate(data?.five_hour?.utilization) ?? 0,
626
+ weekly: readPercentCandidate(data?.seven_day?.utilization) ?? 0,
627
+ sessionResetsAt: typeof data?.five_hour?.resets_at === "string" ? data.five_hour.resets_at : undefined,
628
+ weeklyResetsAt: typeof data?.seven_day?.resets_at === "string" ? data.seven_day.resets_at : undefined,
629
+ fetchedAt: nowMs,
630
+ }, nowMs);
631
+
632
+ if (data?.extra_usage?.is_enabled) {
633
+ usage.extraSpend = typeof data.extra_usage.used_credits === "number" ? data.extra_usage.used_credits : undefined;
634
+ usage.extraLimit = typeof data.extra_usage.monthly_limit === "number" ? data.extra_usage.monthly_limit : undefined;
635
+ }
636
+ return { usage, status: result.status, retryAfterMs };
637
+ }
638
+
639
+ export async function fetchClaudeUsage(token: string, config: RequestConfig = {}): Promise<UsageData> {
640
+ return (await fetchClaudeUsageAttempt(token, config)).usage;
641
+ }
642
+
643
+ export async function fetchClaudeUsageWithFallback(
644
+ token: string,
645
+ config: ClaudeUsageFetchConfig = {},
646
+ ): Promise<UsageData> {
647
+ const cacheFile = config.cacheFile ?? DEFAULT_USAGE_CACHE_FILE;
648
+ const nowMs = config.nowMs ?? Date.now();
649
+ const cachedOutcome = readClaudeCacheOutcome(cacheFile, nowMs);
650
+ if (cachedOutcome) return cachedOutcome;
651
+ if (config.signal?.aborted) return { session: 0, weekly: 0, error: "request cancelled" };
652
+
653
+ const lockFile = `${cacheFile}.claude.lock`;
654
+ const releaseLock = await acquireFileLock(lockFile, config.signal);
655
+ if (!releaseLock) {
656
+ const waitedOutcome = readClaudeCacheOutcome(cacheFile, nowMs);
657
+ if (waitedOutcome) return waitedOutcome;
658
+ if (config.signal?.aborted) return { session: 0, weekly: 0, error: "request cancelled" };
659
+ }
660
+
661
+ try {
662
+ const lockOutcome = readClaudeCacheOutcome(cacheFile, nowMs);
663
+ if (lockOutcome) return lockOutcome;
664
+
665
+ let state = readClaudeCacheState(cacheFile);
666
+ const attempt = await fetchClaudeUsageAttempt(token, config, nowMs);
667
+ if (!attempt.usage.error) {
668
+ state = clearClaudeCooldown(state);
669
+ state.lastSuccess = snapshotUsage(attempt.usage, nowMs);
670
+ state.lastSuccessAt = nowMs;
671
+ writeClaudeCacheState(state, cacheFile);
672
+ return attempt.usage;
673
+ }
674
+
675
+ if (attempt.status === 429) {
676
+ const consecutive429s = Math.max(1, (state.consecutive429s ?? 0) + 1);
677
+ const cooldownUntil = nowMs + computeClaudeBackoffMs({ ...state, consecutive429s }, attempt.retryAfterMs);
678
+ state = { ...state, cooldownUntil, consecutive429s, lastError: attempt.usage.error };
679
+ writeClaudeCacheState(state, cacheFile);
680
+ return state.lastSuccess
681
+ ? staleCachedUsage(state.lastSuccess, cooldownMessage(cooldownUntil, nowMs), nowMs)
682
+ : { session: 0, weekly: 0, error: `${attempt.usage.error}; ${cooldownMessage(cooldownUntil, nowMs)}` };
683
+ }
684
+
685
+ return attempt.usage;
686
+ } finally {
687
+ releaseLock?.();
688
+ }
689
+ }
690
+
691
+ function readNumber(value: unknown): number | null {
692
+ if (typeof value === "number" && Number.isFinite(value)) return value;
693
+ if (typeof value === "string" && value.trim()) {
694
+ const parsed = Number(value);
695
+ if (Number.isFinite(parsed)) return parsed;
696
+ }
697
+ return null;
698
+ }
699
+
700
+ function usedPercentFromCounts(
701
+ value: Record<string, unknown> | null | undefined,
702
+ options: { remainingPercent?: string; used?: string; total?: string; remaining?: string } = {},
703
+ ): number | null {
704
+ if (!value) return null;
705
+ const remainingPercent = readNumber(value[options.remainingPercent ?? "remaining_percent"]);
706
+ if (remainingPercent !== null) return Math.max(0, Math.min(100, 100 - remainingPercent));
707
+
708
+ const total = readNumber(value[options.total ?? "limit"]);
709
+ const used = readNumber(value[options.used ?? "used"]);
710
+ const remaining = readNumber(value[options.remaining ?? "remaining"]);
711
+ if (total === null || total <= 0) return null;
712
+ if (used !== null) return Math.max(0, Math.min(100, used / total * 100));
713
+ if (remaining !== null) return Math.max(0, Math.min(100, (total - remaining) / total * 100));
714
+ return null;
715
+ }
716
+
717
+ function normalizeIsoDate(value: unknown): string | undefined {
718
+ if (typeof value !== "string" || !value.trim()) return undefined;
719
+ const normalized = value.trim().replace(/(\.\d{3})\d+(?=Z|[+-]\d\d:\d\d$)/, "$1");
720
+ return Number.isFinite(new Date(normalized).getTime()) ? normalized : undefined;
721
+ }
722
+
723
+ function isoFromEpoch(value: unknown): string | undefined {
724
+ const raw = readNumber(value);
725
+ if (raw === null || raw <= 0) return undefined;
726
+ const milliseconds = raw > 1_000_000_000_000 ? raw : raw * 1000;
727
+ const date = new Date(milliseconds);
728
+ return Number.isFinite(date.getTime()) ? date.toISOString() : undefined;
729
+ }
730
+
731
+ function resetFromRemains(value: unknown, nowMs: number): string | undefined {
732
+ const raw = readNumber(value);
733
+ if (raw === null || raw <= 0) return undefined;
734
+ const milliseconds = raw > 1_000_000 ? raw : raw * 1000;
735
+ return new Date(nowMs + milliseconds).toISOString();
736
+ }
737
+
738
+ export function extractKimiUsageFromPayload(payload: unknown, nowMs = Date.now()): UsageData | null {
739
+ const root = asObject(payload);
740
+ if (!root) return null;
741
+ const webUsages = Array.isArray(root.usages) ? root.usages : undefined;
742
+ const codingUsage = webUsages?.map(asObject).find((entry) =>
743
+ String(entry?.scope ?? "").toUpperCase() === "FEATURE_CODING") ?? root;
744
+ const dataRows = Array.isArray(codingUsage.data) ? codingUsage.data.map(asObject).filter(Boolean) : [];
745
+ const usage = asObject(codingUsage.usage) ?? asObject(codingUsage.detail) ??
746
+ dataRows.find((entry) => String(entry?.model_name ?? entry?.modelName ?? "").toLowerCase() === "all");
747
+ const limits = Array.isArray(codingUsage.limits)
748
+ ? codingUsage.limits
749
+ : dataRows.filter((entry) => entry !== usage);
750
+ const sessionLimit = limits.map(asObject).find((entry) => {
751
+ const window = asObject(entry?.window);
752
+ const duration = readNumber(window?.duration);
753
+ const unit = String(window?.timeUnit ?? window?.time_unit ?? "").toUpperCase();
754
+ return duration === 300 && unit.includes("MINUTE");
755
+ }) ?? limits.map(asObject).find((entry) => entry !== null);
756
+ const sessionDetail = asObject(sessionLimit?.detail) ?? sessionLimit;
757
+
758
+ const session = usedPercentFromCounts(sessionDetail);
759
+ const weekly = usedPercentFromCounts(usage);
760
+ if (session === null || weekly === null) return null;
761
+
762
+ const sessionReset = normalizeIsoDate(sessionDetail?.resetTime ?? sessionDetail?.reset_at ?? sessionDetail?.reset_time);
763
+ const weeklyReset = normalizeIsoDate(usage?.resetTime ?? usage?.reset_at ?? usage?.reset_time);
764
+ return hydrateUsageResets({
765
+ ...normalizeUsagePair(session, weekly),
766
+ sessionLabel: "5-hour",
767
+ weeklyLabel: "Weekly",
768
+ sessionResetsAt: sessionReset,
769
+ weeklyResetsAt: weeklyReset,
770
+ }, nowMs);
771
+ }
772
+
773
+ export async function fetchKimiUsage(token: string, config: FetchConfig = {}): Promise<UsageData> {
774
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
775
+ const result = await requestJson(endpoints.kimi, {
776
+ headers: {
777
+ Authorization: `Bearer ${token}`,
778
+ "User-Agent": "KimiCLI/1.5",
779
+ },
780
+ }, config);
781
+ if (!result.ok) return { session: 0, weekly: 0, error: result.error };
782
+ return extractKimiUsageFromPayload(result.data) ?? {
783
+ session: 0,
784
+ weekly: 0,
785
+ error: "unrecognized response shape",
786
+ };
787
+ }
788
+
789
+ interface MiniMaxWindow {
790
+ percent: number;
791
+ resetsAt?: string;
792
+ }
793
+
794
+ function pickHighestWindow(windows: MiniMaxWindow[]): MiniMaxWindow | undefined {
795
+ return windows.reduce<MiniMaxWindow | undefined>((highest, window) =>
796
+ !highest || window.percent > highest.percent ? window : highest, undefined);
797
+ }
798
+
799
+ function miniMaxResetAt(value: Record<string, unknown>, prefix: "current" | "weekly", nowMs: number): string | undefined {
800
+ const end = prefix === "current"
801
+ ? value.end_time ?? value.endTime
802
+ : value.weekly_end_time ?? value.weeklyEndTime;
803
+ const remains = prefix === "current"
804
+ ? value.remains_time ?? value.remainsTime
805
+ : value.weekly_remains_time ?? value.weeklyRemainsTime;
806
+ const resetsAt = prefix === "current"
807
+ ? value.current_resets_at ?? value.currentResetsAt
808
+ : value.weekly_resets_at ?? value.weeklyResetsAt;
809
+ return normalizeIsoDate(resetsAt) ?? isoFromEpoch(end) ?? resetFromRemains(remains, nowMs);
810
+ }
811
+
812
+ function extractMiniMaxCreditBalance(payload: unknown): AccountBalance | undefined {
813
+ const root = asObject(payload);
814
+ const data = asObject(root?.data) ?? root;
815
+ if (!data) return undefined;
816
+ const amount = readNumber(
817
+ data.points_balance ?? data.pointsBalance ??
818
+ data.point_balance ?? data.pointBalance ??
819
+ data.credits_balance ?? data.creditsBalance ??
820
+ data.credit_balance ?? data.creditBalance,
821
+ );
822
+ return amount === null ? undefined : { amount, unit: "credits", label: "Credit balance" };
823
+ }
824
+
825
+ export function extractMiniMaxUsageFromPayload(payload: unknown, nowMs = Date.now()): UsageData | null {
826
+ const root = asObject(payload);
827
+ const data = asObject(root?.data) ?? root;
828
+ if (!data) return null;
829
+ const accountBalance = extractMiniMaxCreditBalance(payload);
830
+
831
+ const intervalWindows: MiniMaxWindow[] = [];
832
+ const weeklyWindows: MiniMaxWindow[] = [];
833
+ if (Array.isArray(data.services)) {
834
+ for (const rawService of data.services) {
835
+ const service = asObject(rawService);
836
+ if (!service) continue;
837
+ const directPercent = readPercentCandidate(readNumber(service.percent));
838
+ const percent = directPercent ?? usedPercentFromCounts(service, { total: "limit", used: "usage" });
839
+ if (percent === null) continue;
840
+ const windowType = String(service.window_type ?? service.windowType ?? "").toLowerCase();
841
+ const resetsAt = normalizeIsoDate(service.resets_at ?? service.reset_time ?? service.end_time);
842
+ (windowType.includes("week") ? weeklyWindows : intervalWindows).push({ percent, resetsAt });
843
+ }
844
+ }
845
+
846
+ if (Array.isArray(data.model_remains ?? data.modelRemains)) {
847
+ for (const rawModel of (data.model_remains ?? data.modelRemains) as unknown[]) {
848
+ const raw = asObject(rawModel);
849
+ if (!raw) continue;
850
+ const model: Record<string, unknown> = {
851
+ ...raw,
852
+ current_interval_remaining_percent:
853
+ raw.current_interval_remaining_percent ?? raw.currentIntervalRemainingPercent,
854
+ current_interval_total_count: raw.current_interval_total_count ?? raw.currentIntervalTotalCount,
855
+ current_interval_usage_count: raw.current_interval_usage_count ?? raw.currentIntervalUsageCount,
856
+ current_interval_status: raw.current_interval_status ?? raw.currentIntervalStatus,
857
+ current_weekly_remaining_percent:
858
+ raw.current_weekly_remaining_percent ?? raw.currentWeeklyRemainingPercent,
859
+ current_weekly_total_count: raw.current_weekly_total_count ?? raw.currentWeeklyTotalCount,
860
+ current_weekly_usage_count: raw.current_weekly_usage_count ?? raw.currentWeeklyUsageCount,
861
+ current_weekly_status: raw.current_weekly_status ?? raw.currentWeeklyStatus,
862
+ };
863
+ const unavailable = (prefix: "interval" | "weekly") =>
864
+ readNumber(model[`current_${prefix}_status`]) === 3 &&
865
+ (readNumber(model[`current_${prefix}_remaining_percent`]) ?? 0) >= 100 &&
866
+ (readNumber(model[`current_${prefix}_total_count`]) ?? 0) === 0 &&
867
+ (readNumber(model[`current_${prefix}_usage_count`]) ?? 0) === 0;
868
+ const interval = unavailable("interval") ? null : usedPercentFromCounts(model, {
869
+ remainingPercent: "current_interval_remaining_percent",
870
+ total: "current_interval_total_count",
871
+ remaining: "current_interval_usage_count",
872
+ });
873
+ if (interval !== null) {
874
+ intervalWindows.push({ percent: interval, resetsAt: miniMaxResetAt(model, "current", nowMs) });
875
+ }
876
+ const weekly = unavailable("weekly") ? null : usedPercentFromCounts(model, {
877
+ remainingPercent: "current_weekly_remaining_percent",
878
+ total: "current_weekly_total_count",
879
+ remaining: "current_weekly_usage_count",
880
+ });
881
+ if (weekly !== null) {
882
+ weeklyWindows.push({ percent: weekly, resetsAt: miniMaxResetAt(model, "weekly", nowMs) });
883
+ }
884
+ }
885
+ }
886
+
887
+ const session = pickHighestWindow(intervalWindows);
888
+ const weekly = pickHighestWindow(weeklyWindows);
889
+ if (!session) {
890
+ return accountBalance
891
+ ? { session: 0, weekly: 0, quotaHidden: true, accountBalance }
892
+ : null;
893
+ }
894
+ return hydrateUsageResets({
895
+ session: Number(session.percent.toFixed(2)),
896
+ accountBalance,
897
+ weekly: Number((weekly?.percent ?? 0).toFixed(2)),
898
+ sessionLabel: "Interval",
899
+ weeklyLabel: "Weekly",
900
+ weeklyHidden: !weekly,
901
+ sessionResetsAt: session.resetsAt,
902
+ weeklyResetsAt: weekly?.resetsAt,
903
+ }, nowMs);
904
+ }
905
+
906
+ function miniMaxPayloadStatus(payload: unknown): number | null {
907
+ const root = asObject(payload);
908
+ const data = asObject(root?.data);
909
+ const baseResponse = asObject(data?.base_resp ?? data?.baseResp ?? root?.base_resp ?? root?.baseResp);
910
+ return readNumber(baseResponse?.status_code ?? baseResponse?.statusCode);
911
+ }
912
+
913
+ function miniMaxPayloadError(payload: unknown): string | null {
914
+ const root = asObject(payload);
915
+ const data = asObject(root?.data);
916
+ const baseResponse = asObject(data?.base_resp ?? data?.baseResp ?? root?.base_resp ?? root?.baseResp);
917
+ const status = miniMaxPayloadStatus(payload);
918
+ if (status === null || status === 0) return null;
919
+ const message = baseResponse?.status_msg ?? baseResponse?.statusMessage;
920
+ return typeof message === "string" && message.trim()
921
+ ? `API ${status}: ${message.trim()}`
922
+ : `API ${status}`;
923
+ }
924
+
925
+ export async function fetchMiniMaxUsage(
926
+ token: string,
927
+ provider: "minimax" | "minimax-cn" = "minimax",
928
+ config: FetchConfig = {},
929
+ ): Promise<UsageData> {
930
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
931
+ const candidates = provider === "minimax-cn"
932
+ ? [endpoints.minimaxCn, endpoints.minimaxCnLegacy]
933
+ : [endpoints.minimax, endpoints.minimaxLegacy];
934
+ let lastError = "usage request failed";
935
+ let credentialError: string | undefined;
936
+ let noActiveTokenPlan = false;
937
+
938
+ for (const endpoint of [...new Set(candidates)]) {
939
+ const result = await requestJson(endpoint, {
940
+ headers: {
941
+ Authorization: `Bearer ${token}`,
942
+ Accept: "application/json",
943
+ },
944
+ }, config);
945
+ if (!result.ok) {
946
+ lastError = result.error;
947
+ if (result.status === 401 || result.status === 403) credentialError ??= result.error;
948
+ if (config.signal?.aborted) break;
949
+ continue;
950
+ }
951
+ const payloadStatus = miniMaxPayloadStatus(result.data);
952
+ const payloadError = miniMaxPayloadError(result.data);
953
+ const usage = extractMiniMaxUsageFromPayload(result.data);
954
+ if (usage && (!payloadError || usage.quotaHidden)) return usage;
955
+ if (payloadStatus === 2062) {
956
+ noActiveTokenPlan = true;
957
+ continue;
958
+ }
959
+ if (payloadError) {
960
+ lastError = payloadError;
961
+ continue;
962
+ }
963
+ lastError = "unrecognized response shape";
964
+ }
965
+
966
+ if (noActiveTokenPlan) {
967
+ return {
968
+ session: 0,
969
+ weekly: 0,
970
+ quotaHidden: true,
971
+ notice: "No active Token Plan · check Credit balance in the MiniMax console",
972
+ };
973
+ }
974
+ return { session: 0, weekly: 0, error: credentialError ?? lastError };
975
+ }
976
+
977
+ export function extractOpenRouterUsageFromPayloads(
978
+ creditsPayload: unknown,
979
+ keyPayload: unknown,
980
+ ): UsageData | null {
981
+ const credits = asObject(asObject(creditsPayload)?.data) ?? asObject(creditsPayload);
982
+ const key = asObject(asObject(keyPayload)?.data) ?? asObject(keyPayload);
983
+
984
+ const totalCredits = readNumber(credits?.total_credits ?? credits?.totalCredits);
985
+ const totalUsage = readNumber(credits?.total_usage ?? credits?.totalUsage);
986
+ const accountBalance = totalCredits !== null && totalUsage !== null
987
+ ? {
988
+ amount: Number((totalCredits - totalUsage).toFixed(6)),
989
+ unit: "USD",
990
+ label: "Balance",
991
+ }
992
+ : undefined;
993
+
994
+ const spendValues = {
995
+ daily: readNumber(key?.usage_daily ?? key?.usageDaily),
996
+ weekly: readNumber(key?.usage_weekly ?? key?.usageWeekly),
997
+ monthly: readNumber(key?.usage_monthly ?? key?.usageMonthly),
998
+ lifetime: readNumber(key?.usage),
999
+ };
1000
+ const accountSpend = Object.values(spendValues).some((value) => value !== null)
1001
+ ? {
1002
+ unit: "USD",
1003
+ daily: spendValues.daily ?? undefined,
1004
+ weekly: spendValues.weekly ?? undefined,
1005
+ monthly: spendValues.monthly ?? undefined,
1006
+ lifetime: spendValues.lifetime ?? undefined,
1007
+ }
1008
+ : undefined;
1009
+
1010
+ const limit = readNumber(key?.limit);
1011
+ const remaining = readNumber(key?.limit_remaining ?? key?.limitRemaining);
1012
+ const limitUsed = limit !== null && limit > 0 && remaining !== null
1013
+ ? Math.max(0, Math.min(limit, limit - remaining))
1014
+ : null;
1015
+ const limitPercent = limitUsed !== null && limit !== null ? limitUsed / limit * 100 : null;
1016
+ if (!accountBalance && !accountSpend && limitPercent === null) return null;
1017
+
1018
+ return {
1019
+ session: limitPercent === null ? 0 : Number(limitPercent.toFixed(2)),
1020
+ weekly: 0,
1021
+ quotaHidden: limitPercent === null,
1022
+ weeklyHidden: true,
1023
+ sessionLabel: "Key limit",
1024
+ accountBalance,
1025
+ accountSpend,
1026
+ };
1027
+ }
1028
+
1029
+ export async function fetchOpenRouterUsage(token: string, config: FetchConfig = {}): Promise<UsageData> {
1030
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1031
+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
1032
+ const [creditsResult, keyResult] = await Promise.all([
1033
+ requestJson(endpoints.openRouterCredits, { headers }, config),
1034
+ requestJson(endpoints.openRouterKey, { headers }, config),
1035
+ ]);
1036
+ const usage = extractOpenRouterUsageFromPayloads(
1037
+ creditsResult.ok ? creditsResult.data : undefined,
1038
+ keyResult.ok ? keyResult.data : undefined,
1039
+ );
1040
+ if (usage) return usage;
1041
+
1042
+ const errors = [
1043
+ creditsResult.ok ? undefined : `credits: ${creditsResult.error}`,
1044
+ keyResult.ok ? undefined : `key: ${keyResult.error}`,
1045
+ ].filter((value): value is string => Boolean(value));
1046
+ return {
1047
+ session: 0,
1048
+ weekly: 0,
1049
+ error: errors.length > 0 ? errors.join("; ") : "unrecognized response shape",
1050
+ };
1051
+ }
1052
+
1053
+ export function extractDeepSeekBalanceFromPayload(payload: unknown): UsageData | null {
1054
+ const root = asObject(payload);
1055
+ const rawBalances = Array.isArray(root?.balance_infos) ? root.balance_infos : [];
1056
+ const balances = rawBalances.map(asObject).filter((value): value is Record<string, unknown> => value !== null);
1057
+ if (balances.length === 0) return null;
1058
+
1059
+ const parsed = balances.flatMap((balance) => {
1060
+ const unit = typeof balance.currency === "string" ? balance.currency.toUpperCase() : "USD";
1061
+ const total = readNumber(balance.total_balance ?? balance.totalBalance);
1062
+ if (total === null) return [];
1063
+ return [{
1064
+ total: { amount: total, unit, label: "Total balance" } satisfies AccountBalance,
1065
+ toppedUp: readNumber(balance.topped_up_balance ?? balance.toppedUpBalance),
1066
+ granted: readNumber(balance.granted_balance ?? balance.grantedBalance),
1067
+ }];
1068
+ });
1069
+ const primary = parsed[0];
1070
+ if (!primary) return null;
1071
+
1072
+ const details: AccountBalance[] = [];
1073
+ if (primary.toppedUp !== null) {
1074
+ details.push({ amount: primary.toppedUp, unit: primary.total.unit, label: "Topped up" });
1075
+ }
1076
+ if (primary.granted !== null) {
1077
+ details.push({ amount: primary.granted, unit: primary.total.unit, label: "Granted" });
1078
+ }
1079
+ for (const additional of parsed.slice(1)) details.push(additional.total);
1080
+
1081
+ return {
1082
+ session: 0,
1083
+ weekly: 0,
1084
+ quotaHidden: true,
1085
+ accountBalance: primary.total,
1086
+ accountBalanceDetails: details,
1087
+ warning: root?.is_available === false ? "Balance is not currently available for API use" : undefined,
1088
+ };
1089
+ }
1090
+
1091
+ export async function fetchDeepSeekBalance(token: string, config: FetchConfig = {}): Promise<UsageData> {
1092
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1093
+ const result = await requestJson(endpoints.deepSeekBalance, {
1094
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
1095
+ }, config);
1096
+ if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1097
+ return extractDeepSeekBalanceFromPayload(result.data) ?? {
1098
+ session: 0,
1099
+ weekly: 0,
1100
+ error: "unrecognized response shape",
1101
+ };
1102
+ }
1103
+
1104
+ export function extractBasetenUsageFromPayload(payload: unknown): UsageData | null {
1105
+ const root = asObject(payload);
1106
+ if (!root) return null;
1107
+ const sections = [root.dedicated_usage, root.training_usage, root.model_apis_usage].map(asObject);
1108
+ const creditsUsed = sections
1109
+ .map((section) => readNumber(section?.credits_used))
1110
+ .filter((value): value is number => value !== null);
1111
+ if (creditsUsed.length === 0) return null;
1112
+
1113
+ return {
1114
+ session: 0,
1115
+ weekly: 0,
1116
+ quotaHidden: true,
1117
+ accountUsage: {
1118
+ amount: Number(creditsUsed.reduce((sum, value) => sum + value, 0).toFixed(6)),
1119
+ unit: "credits",
1120
+ label: "Credits used this month",
1121
+ },
1122
+ };
1123
+ }
1124
+
1125
+ function basetenMonthRange(nowMs: number): { startDate: string; endDate: string } {
1126
+ const now = new Date(nowMs);
1127
+ return {
1128
+ startDate: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(),
1129
+ endDate: now.toISOString(),
1130
+ };
1131
+ }
1132
+
1133
+ export async function fetchBasetenUsage(token: string, config: BasetenUsageFetchConfig = {}): Promise<UsageData> {
1134
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1135
+ const { startDate, endDate } = basetenMonthRange(config.nowMs ?? Date.now());
1136
+ let url: string;
1137
+ try {
1138
+ const parsed = new URL(endpoints.basetenUsage);
1139
+ parsed.searchParams.set("start_date", startDate);
1140
+ parsed.searchParams.set("end_date", endDate);
1141
+ url = parsed.toString();
1142
+ } catch {
1143
+ return { session: 0, weekly: 0, error: "invalid Baseten usage endpoint" };
1144
+ }
1145
+ const result = await requestJson(url, {
1146
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
1147
+ }, config);
1148
+ if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1149
+ return extractBasetenUsageFromPayload(result.data) ?? {
1150
+ session: 0,
1151
+ weekly: 0,
1152
+ error: "unrecognized response shape",
1153
+ };
1154
+ }
1155
+
1156
+ interface FireworksMoney {
1157
+ currencyCode: string;
1158
+ amount: number;
1159
+ }
1160
+
1161
+ function parseFireworksMoney(value: unknown): FireworksMoney | null {
1162
+ const raw = asObject(value);
1163
+ if (!raw || typeof raw.currencyCode !== "string" || !raw.currencyCode.trim()) return null;
1164
+ const parsedUnits = readNumber(raw.units);
1165
+ const parsedNanos = readNumber(raw.nanos);
1166
+ if ((raw.units !== undefined && parsedUnits === null) || (raw.nanos !== undefined && parsedNanos === null)) {
1167
+ return null;
1168
+ }
1169
+ const units = parsedUnits ?? 0;
1170
+ const nanos = parsedNanos ?? 0;
1171
+ if (!Number.isInteger(nanos) || Math.abs(nanos) >= 1_000_000_000) return null;
1172
+ return {
1173
+ currencyCode: raw.currencyCode.trim().toUpperCase(),
1174
+ amount: units + nanos / 1_000_000_000,
1175
+ };
1176
+ }
1177
+
1178
+ export function extractFireworksSpendFromPayload(payload: unknown): UsageData | null {
1179
+ const root = asObject(payload);
1180
+ if (!root || !Array.isArray(root.lineItems)) return null;
1181
+ const amounts: FireworksMoney[] = [];
1182
+ for (const value of root.lineItems) {
1183
+ const item = asObject(value);
1184
+ const parsed = parseFireworksMoney(item?.totalCost);
1185
+ if (!parsed) return null;
1186
+ amounts.push(parsed);
1187
+ }
1188
+ const currencies = new Set(amounts.map((amount) => amount.currencyCode));
1189
+ if (currencies.size > 1) return null;
1190
+ const unit = amounts[0]?.currencyCode ?? "USD";
1191
+ const monthly = amounts.reduce((sum, amount) => sum + amount.amount, 0);
1192
+ return {
1193
+ session: 0,
1194
+ weekly: 0,
1195
+ quotaHidden: true,
1196
+ accountSpend: { unit, monthly: Number(monthly.toFixed(6)) },
1197
+ };
1198
+ }
1199
+
1200
+ function fireworksMonthRange(nowMs: number): { startTime: string; endTime: string } {
1201
+ const now = new Date(nowMs);
1202
+ return {
1203
+ startTime: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1)).toISOString(),
1204
+ // Fireworks treats the end date as exclusive and aggregates by UTC date.
1205
+ endTime: new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate() + 1)).toISOString(),
1206
+ };
1207
+ }
1208
+
1209
+ function normalizeFireworksAccountId(value: string): string | null {
1210
+ const normalized = value.trim().replace(/^accounts\//, "");
1211
+ return /^[A-Za-z0-9._-]+$/.test(normalized) ? normalized : null;
1212
+ }
1213
+
1214
+ async function requestFireworksJson(
1215
+ url: string,
1216
+ init: RequestInit,
1217
+ config: RequestConfig,
1218
+ ): Promise<JsonRequestResult> {
1219
+ const first = await requestJson(url, init, config);
1220
+ if (first.ok || ![429, 502, 503, 504].includes(first.status ?? 0)) return first;
1221
+
1222
+ const retryAfterMs = parseRetryAfterMs(getHeader(first.headers, "retry-after"));
1223
+ try {
1224
+ await sleep(Math.min(retryAfterMs ?? 250, 2_000), config.signal);
1225
+ } catch {
1226
+ return { ok: false, error: "request cancelled", status: null };
1227
+ }
1228
+ return requestJson(url, init, config);
1229
+ }
1230
+
1231
+ export async function fetchFireworksUsage(
1232
+ token: string,
1233
+ config: FireworksUsageFetchConfig = {},
1234
+ ): Promise<UsageData> {
1235
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1236
+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
1237
+ const apiBase = endpoints.fireworksApi.replace(/\/+$/, "");
1238
+ const accountsResult = await requestFireworksJson(`${apiBase}/accounts?pageSize=200`, { headers }, config);
1239
+ if (!accountsResult.ok) {
1240
+ return { session: 0, weekly: 0, error: `account discovery: ${accountsResult.error}` };
1241
+ }
1242
+
1243
+ const root = asObject(accountsResult.data);
1244
+ const accounts = Array.isArray(root?.accounts) ? root.accounts.map(asObject).filter(Boolean) : [];
1245
+ const accountIds = accounts.flatMap((account) => {
1246
+ const name = typeof account?.name === "string" ? account.name : "";
1247
+ const id = normalizeFireworksAccountId(name);
1248
+ return id ? [id] : [];
1249
+ });
1250
+ const totalSize = readNumber(root?.totalSize);
1251
+ const configuredId = endpoints.fireworksAccountId
1252
+ ? normalizeFireworksAccountId(endpoints.fireworksAccountId)
1253
+ : null;
1254
+ if (endpoints.fireworksAccountId && !configuredId) {
1255
+ return { session: 0, weekly: 0, error: "invalid PI_FIREWORKS_ACCOUNT_ID" };
1256
+ }
1257
+
1258
+ let accountId: string | undefined;
1259
+ if (configuredId) {
1260
+ if (!accountIds.includes(configuredId)) {
1261
+ return { session: 0, weekly: 0, error: "PI_FIREWORKS_ACCOUNT_ID is not accessible with this key" };
1262
+ }
1263
+ accountId = configuredId;
1264
+ } else if (accountIds.length === 1 && (totalSize === null || totalSize <= 1)) {
1265
+ // Fireworks may return totalSize: 0 alongside one account, so trust the
1266
+ // usable resource list unless totalSize explicitly reports more accounts.
1267
+ accountId = accountIds[0];
1268
+ } else if (accountIds.length === 0) {
1269
+ return { session: 0, weekly: 0, error: "no accessible Fireworks account" };
1270
+ } else {
1271
+ return {
1272
+ session: 0,
1273
+ weekly: 0,
1274
+ error: "multiple Fireworks accounts; set PI_FIREWORKS_ACCOUNT_ID",
1275
+ };
1276
+ }
1277
+
1278
+ const { startTime, endTime } = fireworksMonthRange(config.nowMs ?? Date.now());
1279
+ const query = new URLSearchParams({ startTime, endTime });
1280
+ const result = await requestFireworksJson(
1281
+ `${apiBase}/accounts/${encodeURIComponent(accountId)}/billing/summary?${query}`,
1282
+ { headers },
1283
+ config,
1284
+ );
1285
+ if (!result.ok) return { session: 0, weekly: 0, error: `billing summary: ${result.error}` };
1286
+ return extractFireworksSpendFromPayload(result.data) ?? {
1287
+ session: 0,
1288
+ weekly: 0,
1289
+ error: "unrecognized billing summary response shape",
1290
+ };
1291
+ }
1292
+
1293
+ function readXaiUsdCents(value: unknown): number | null {
1294
+ const raw = asObject(value);
1295
+ const cents = readNumber(raw?.val ?? value);
1296
+ return cents === null ? null : Number((cents / 100).toFixed(6));
1297
+ }
1298
+
1299
+ export function extractXaiBillingFromPayloads(
1300
+ prepaidPayload: unknown,
1301
+ invoicePreviewPayload: unknown,
1302
+ ): UsageData | null {
1303
+ const prepaid = asObject(prepaidPayload);
1304
+ const preview = asObject(invoicePreviewPayload);
1305
+ const accountingBalance = readXaiUsdCents(prepaid?.total);
1306
+ const currentCycleTotal = readXaiUsdCents(asObject(preview?.coreInvoice)?.totalWithCorr);
1307
+ if (accountingBalance === null && currentCycleTotal === null) return null;
1308
+
1309
+ return {
1310
+ session: 0,
1311
+ weekly: 0,
1312
+ quotaHidden: true,
1313
+ // xAI represents purchases as negative and spend as positive in its
1314
+ // prepaid accounting ledger, so the available balance is the negated total.
1315
+ accountBalance: accountingBalance === null
1316
+ ? undefined
1317
+ : { amount: -accountingBalance, unit: "USD", label: "Prepaid balance" },
1318
+ accountSpend: currentCycleTotal === null
1319
+ ? undefined
1320
+ : { unit: "USD", monthly: currentCycleTotal },
1321
+ };
1322
+ }
1323
+
1324
+ export async function fetchXaiUsage(token: string, config: FetchConfig = {}): Promise<UsageData> {
1325
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1326
+ const apiBase = endpoints.xaiManagementApi.replace(/\/+$/, "");
1327
+ const headers = { Authorization: `Bearer ${token}`, Accept: "application/json" };
1328
+ const validation = await requestJson(`${apiBase}/auth/management-keys/validation`, { headers }, config);
1329
+ if (!validation.ok) return { session: 0, weekly: 0, error: `key validation: ${validation.error}` };
1330
+
1331
+ const validationBody = asObject(validation.data);
1332
+ const scope = typeof validationBody?.scope === "string" ? validationBody.scope : "";
1333
+ if (scope !== "SCOPE_TEAM") {
1334
+ return {
1335
+ session: 0,
1336
+ weekly: 0,
1337
+ error: "xAI Management Key must be team-scoped",
1338
+ };
1339
+ }
1340
+ const teamId = typeof validationBody?.scopeId === "string" && validationBody.scopeId.trim()
1341
+ ? validationBody.scopeId.trim()
1342
+ : typeof validationBody?.teamId === "string" ? validationBody.teamId.trim() : "";
1343
+ if (!teamId) return { session: 0, weekly: 0, error: "key validation did not return a team ID" };
1344
+
1345
+ const team = encodeURIComponent(teamId);
1346
+ const [prepaid, preview] = await Promise.all([
1347
+ requestJson(`${apiBase}/v1/billing/teams/${team}/prepaid/balance`, { headers }, config),
1348
+ requestJson(`${apiBase}/v1/billing/teams/${team}/postpaid/invoice/preview`, { headers }, config),
1349
+ ]);
1350
+ const usage = extractXaiBillingFromPayloads(
1351
+ prepaid.ok ? prepaid.data : undefined,
1352
+ preview.ok ? preview.data : undefined,
1353
+ );
1354
+ if (!usage) {
1355
+ const errors = [
1356
+ prepaid.ok ? undefined : `prepaid balance: ${prepaid.error}`,
1357
+ preview.ok ? undefined : `invoice preview: ${preview.error}`,
1358
+ ].filter((error): error is string => Boolean(error));
1359
+ return {
1360
+ session: 0,
1361
+ weekly: 0,
1362
+ error: errors.length > 0 ? errors.join("; ") : "unrecognized xAI billing response shape",
1363
+ };
1364
+ }
1365
+ const partialErrors = [
1366
+ prepaid.ok ? undefined : `prepaid balance unavailable (${prepaid.error})`,
1367
+ preview.ok ? undefined : `invoice preview unavailable (${preview.error})`,
1368
+ ].filter((error): error is string => Boolean(error));
1369
+ return { ...usage, warning: partialErrors.length > 0 ? partialErrors.join("; ") : undefined };
1370
+ }
1371
+
1372
+ export function extractVercelCreditsFromPayload(payload: unknown): UsageData | null {
1373
+ const root = asObject(payload);
1374
+ if (!root) return null;
1375
+ const balance = readNumber(root.balance);
1376
+ const totalUsed = readNumber(root.total_used ?? root.totalUsed);
1377
+ if (balance === null && totalUsed === null) return null;
1378
+
1379
+ return {
1380
+ session: 0,
1381
+ weekly: 0,
1382
+ quotaHidden: true,
1383
+ accountBalance: balance === null
1384
+ ? undefined
1385
+ : { amount: balance, unit: "USD", label: "Balance" },
1386
+ accountSpend: totalUsed === null
1387
+ ? undefined
1388
+ : { unit: "USD", lifetime: totalUsed },
1389
+ warning: balance !== null && balance <= 0
1390
+ ? "Balance exhausted; inference requests may be rejected"
1391
+ : undefined,
1392
+ };
1393
+ }
1394
+
1395
+ export async function fetchVercelCredits(token: string, config: FetchConfig = {}): Promise<UsageData> {
1396
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1397
+ const result = await requestJson(endpoints.vercelCredits, {
1398
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
1399
+ }, config);
1400
+ if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1401
+ return extractVercelCreditsFromPayload(result.data) ?? {
1402
+ session: 0,
1403
+ weekly: 0,
1404
+ error: "unrecognized response shape",
1405
+ };
1406
+ }
1407
+
1408
+ export function extractMoonshotBalanceFromPayload(
1409
+ payload: unknown,
1410
+ provider: "moonshot" | "moonshot-cn" = "moonshot",
1411
+ ): UsageData | null {
1412
+ const root = asObject(payload);
1413
+ const data = asObject(root?.data) ?? root;
1414
+ if (!data) return null;
1415
+ const available = readNumber(data.available_balance ?? data.availableBalance);
1416
+ if (available === null) return null;
1417
+ const cash = readNumber(data.cash_balance ?? data.cashBalance);
1418
+ const voucher = readNumber(data.voucher_balance ?? data.voucherBalance);
1419
+ const unit = provider === "moonshot-cn" ? "CNY" : "USD";
1420
+ const details: AccountBalance[] = [];
1421
+ if (cash !== null) details.push({ amount: cash, unit, label: "Cash" });
1422
+ if (voucher !== null) details.push({ amount: voucher, unit, label: "Voucher" });
1423
+
1424
+ return {
1425
+ session: 0,
1426
+ weekly: 0,
1427
+ quotaHidden: true,
1428
+ accountBalance: { amount: available, unit, label: "Available balance" },
1429
+ accountBalanceDetails: details,
1430
+ warning: available <= 0 ? "Balance exhausted; inference requests may be rejected" : undefined,
1431
+ };
1432
+ }
1433
+
1434
+ export async function fetchMoonshotBalance(
1435
+ token: string,
1436
+ provider: "moonshot" | "moonshot-cn" = "moonshot",
1437
+ config: FetchConfig = {},
1438
+ ): Promise<UsageData> {
1439
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1440
+ const endpoint = provider === "moonshot-cn" ? endpoints.moonshotCnBalance : endpoints.moonshotBalance;
1441
+ const result = await requestJson(endpoint, {
1442
+ headers: { Authorization: `Bearer ${token}`, Accept: "application/json" },
1443
+ }, config);
1444
+ if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1445
+ return extractMoonshotBalanceFromPayload(result.data, provider) ?? {
1446
+ session: 0,
1447
+ weekly: 0,
1448
+ error: "unrecognized response shape",
1449
+ };
1450
+ }
1451
+
1452
+ /** Parse ZAI limits where unit 3 is the five-hour window and unit 6 the weekly window. */
1453
+ export function extractZaiUsageFromPayload(payload: unknown, nowMs = Date.now()): UsageData | null {
1454
+ const data = payload as any;
1455
+ const arrays = [data?.data?.limits, data?.limits, data?.quota?.limits, data?.data?.quota?.limits];
1456
+ const limits = arrays.find(Array.isArray) as any[] | undefined;
1457
+ if (!limits?.length) return null;
1458
+
1459
+ // CREDIT_LIMIT (GLM Coding Plan "lite"/credit-based tiers) reports the same
1460
+ // unit/percentage/nextResetTime shape as TOKENS_LIMIT, so treat both as the
1461
+ // quota windows for session (unit 3) and weekly (unit 6).
1462
+ const tokenLimits = limits.filter((entry) => {
1463
+ const type = String(entry?.type || "").toUpperCase();
1464
+ return type === "TOKENS_LIMIT" || type === "CREDIT_LIMIT";
1465
+ });
1466
+ const sessionEntry = tokenLimits.find((entry) => entry?.unit === 3);
1467
+ const weeklyEntry = tokenLimits.find((entry) => entry?.unit === 6);
1468
+ if (!sessionEntry || !weeklyEntry) return null;
1469
+
1470
+ const session = readPercentCandidate(sessionEntry.percentage);
1471
+ const weekly = readPercentCandidate(weeklyEntry.percentage);
1472
+ if (session === null || weekly === null) return null;
1473
+ const normalized = normalizeUsagePair(session, weekly);
1474
+
1475
+ return {
1476
+ ...normalized,
1477
+ sessionResetsIn: typeof sessionEntry.nextResetTime === "number" && sessionEntry.nextResetTime > 0
1478
+ ? formatDuration(Math.max(0, sessionEntry.nextResetTime - nowMs) / 1000)
1479
+ : undefined,
1480
+ weeklyResetsIn: typeof weeklyEntry.nextResetTime === "number" && weeklyEntry.nextResetTime > 0
1481
+ ? formatDuration(Math.max(0, weeklyEntry.nextResetTime - nowMs) / 1000)
1482
+ : undefined,
1483
+ };
1484
+ }
1485
+
1486
+ export async function fetchZaiUsage(
1487
+ token: string,
1488
+ provider: "zai" | "zai-cn" = "zai",
1489
+ config: FetchConfig = {},
1490
+ ): Promise<UsageData> {
1491
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1492
+ const endpoint = provider === "zai-cn" ? endpoints.zaiCn : endpoints.zai;
1493
+ const result = await requestJson(endpoint, { headers: { Authorization: `Bearer ${token}` } }, config);
1494
+ if (!result.ok) return { session: 0, weekly: 0, error: result.error };
1495
+
1496
+ const zaiUsage = extractZaiUsageFromPayload(result.data);
1497
+ if (zaiUsage) return zaiUsage;
1498
+ return extractUsageFromPayload(result.data) ?? { session: 0, weekly: 0, error: "unrecognized response shape" };
1499
+ }
1500
+
1501
+ export function detectProvider(
1502
+ model: { provider?: string } | string | undefined | null,
1503
+ ): ProviderKey | null {
1504
+ if (!model || typeof model === "string") return null;
1505
+ switch ((model.provider || "").toLowerCase()) {
1506
+ case "openai-codex": return "codex";
1507
+ case "anthropic": return "claude";
1508
+ case "zai": return "zai";
1509
+ case "zai-coding-cn": return "zai-cn";
1510
+ case "kimi-coding": return "kimi";
1511
+ case "minimax": return "minimax";
1512
+ case "minimax-cn": return "minimax-cn";
1513
+ case "openrouter": return "openrouter";
1514
+ case "deepseek": return "deepseek";
1515
+ case "moonshotai": return "moonshot";
1516
+ case "moonshotai-cn": return "moonshot-cn";
1517
+ case "baseten": return "baseten";
1518
+ case "vercel-ai-gateway": return "vercel";
1519
+ case "fireworks": return "fireworks";
1520
+ case "xai": return "xai";
1521
+ default: return null;
1522
+ }
1523
+ }
1524
+
1525
+ export function providerToPiProviderId(provider: ProviderKey): PiProviderId {
1526
+ switch (provider) {
1527
+ case "codex": return "openai-codex";
1528
+ case "claude": return "anthropic";
1529
+ case "zai": return "zai";
1530
+ case "zai-cn": return "zai-coding-cn";
1531
+ case "kimi": return "kimi-coding";
1532
+ case "minimax": return "minimax";
1533
+ case "minimax-cn": return "minimax-cn";
1534
+ case "openrouter": return "openrouter";
1535
+ case "deepseek": return "deepseek";
1536
+ case "moonshot": return "moonshotai";
1537
+ case "moonshot-cn": return "moonshotai-cn";
1538
+ case "baseten": return "baseten";
1539
+ case "vercel": return "vercel-ai-gateway";
1540
+ case "fireworks": return "fireworks";
1541
+ case "xai": return XAI_MANAGEMENT_PROVIDER_ID;
1542
+ }
1543
+ }
1544
+
1545
+ export function clampPercent(value: number): number {
1546
+ if (!Number.isFinite(value)) return 0;
1547
+ return Math.max(0, Math.min(100, Math.round(value)));
1548
+ }
1549
+
1550
+ export function colorForPercent(value: number): "success" | "warning" | "error" {
1551
+ if (value >= 90) return "error";
1552
+ if (value >= 70) return "warning";
1553
+ return "success";
1554
+ }
1555
+
1556
+ export async function fetchAllUsages(
1557
+ tokens: UsageTokens,
1558
+ config: FetchAllUsagesConfig = {},
1559
+ ): Promise<UsageByProvider> {
1560
+ const endpoints = config.endpoints ?? resolveUsageEndpoints(config.env);
1561
+ const results: UsageByProvider = {
1562
+ codex: null,
1563
+ claude: null,
1564
+ zai: null,
1565
+ "zai-cn": null,
1566
+ kimi: null,
1567
+ minimax: null,
1568
+ "minimax-cn": null,
1569
+ openrouter: null,
1570
+ deepseek: null,
1571
+ moonshot: null,
1572
+ "moonshot-cn": null,
1573
+ baseten: null,
1574
+ vercel: null,
1575
+ fireworks: null,
1576
+ xai: null,
1577
+ };
1578
+ const tasks: Promise<void>[] = [];
1579
+
1580
+ const assign = (provider: ProviderKey, request: Promise<UsageData>) => {
1581
+ tasks.push(request.then((usage) => {
1582
+ results[provider] = usage;
1583
+ }).catch((error) => {
1584
+ results[provider] = { session: 0, weekly: 0, error: toErrorMessage(error, config.signal) };
1585
+ }));
1586
+ };
1587
+
1588
+ if (tokens.codex) assign("codex", fetchCodexUsage(tokens.codex, config));
1589
+ if (tokens.claude) {
1590
+ assign("claude", fetchClaudeUsageWithFallback(tokens.claude, {
1591
+ ...config,
1592
+ cacheFile: config.cacheFile,
1593
+ nowMs: config.nowMs,
1594
+ }));
1595
+ }
1596
+ if (tokens.zai) assign("zai", fetchZaiUsage(tokens.zai, "zai", { ...config, endpoints }));
1597
+ if (tokens["zai-cn"]) assign("zai-cn", fetchZaiUsage(tokens["zai-cn"], "zai-cn", { ...config, endpoints }));
1598
+ if (tokens.kimi) assign("kimi", fetchKimiUsage(tokens.kimi, { ...config, endpoints }));
1599
+ if (tokens.minimax) assign("minimax", fetchMiniMaxUsage(tokens.minimax, "minimax", { ...config, endpoints }));
1600
+ if (tokens["minimax-cn"]) {
1601
+ assign("minimax-cn", fetchMiniMaxUsage(tokens["minimax-cn"], "minimax-cn", { ...config, endpoints }));
1602
+ }
1603
+ if (tokens.openrouter) assign("openrouter", fetchOpenRouterUsage(tokens.openrouter, { ...config, endpoints }));
1604
+ if (tokens.deepseek) assign("deepseek", fetchDeepSeekBalance(tokens.deepseek, { ...config, endpoints }));
1605
+ if (tokens.moonshot) assign("moonshot", fetchMoonshotBalance(tokens.moonshot, "moonshot", { ...config, endpoints }));
1606
+ if (tokens["moonshot-cn"]) {
1607
+ assign("moonshot-cn", fetchMoonshotBalance(tokens["moonshot-cn"], "moonshot-cn", { ...config, endpoints }));
1608
+ }
1609
+ if (tokens.baseten) assign("baseten", fetchBasetenUsage(tokens.baseten, { ...config, endpoints }));
1610
+ if (tokens.vercel) assign("vercel", fetchVercelCredits(tokens.vercel, { ...config, endpoints }));
1611
+ if (tokens.fireworks) {
1612
+ assign("fireworks", fetchFireworksUsage(tokens.fireworks, { ...config, endpoints, nowMs: config.nowMs }));
1613
+ }
1614
+ if (tokens.xai) assign("xai", fetchXaiUsage(tokens.xai, { ...config, endpoints }));
1615
+
1616
+ await Promise.all(tasks);
1617
+
1618
+ // Pi intentionally uses MOONSHOT_API_KEY for both regional providers. When one
1619
+ // key works in only one region, hide the expected regional auth failure from
1620
+ // the all-provider view while preserving active-provider polling behavior.
1621
+ if (tokens.moonshot && tokens.moonshot === tokens["moonshot-cn"]) {
1622
+ if (results.moonshot && !results.moonshot.error && results["moonshot-cn"]?.error) {
1623
+ results["moonshot-cn"] = null;
1624
+ } else if (results["moonshot-cn"] && !results["moonshot-cn"].error && results.moonshot?.error) {
1625
+ results.moonshot = null;
1626
+ }
1627
+ }
1628
+ return results;
1629
+ }