dsh-sidebar-usage 0.0.0-stage → 1.0.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.
@@ -0,0 +1,1009 @@
1
+ /**
2
+ * dsh-deepseek-usage — 多提供商账户查询(余额 / 订阅用量 / OAuth 订阅余量)。
3
+ *
4
+ * 三种 kind:
5
+ * · balance —— 有"用 API Key 查余额"的接口,返回金额 + 币种;
6
+ * · usage —— 订阅制,没有余额接口,但有关键字用量接口(百分比 + 重置时间);
7
+ * · oauth —— 只有 OAuth 订阅令牌能读的接口(Claude Code / Codex),令牌由用户
8
+ * 在插件页主动粘贴,经凭证服务存取,宿主外任何位置都看不到它;
9
+ * · none —— 上述都不成立(云厂商 AK/SK、OAuth-only 但无可用接口等)。
10
+ *
11
+ * 设计约束:
12
+ * · 每个取数器都是"一个纯解析函数 + 一次 HTTP 调用",解析函数单独导出供测试,
13
+ * 不联网也能覆盖全部字段映射与失败分类。
14
+ * · 解析不出字段就报 `shape`,绝不猜数字:各家接口字段来自其官方文档或长期稳定
15
+ * 的社区实现,但本插件无法在发布前逐一用真实账号验证;宁可显示"无法识别",
16
+ * 也不要显示一个与账单无关的数字。
17
+ * · 数字一律走 toFinite:缺失 / 非数字 / 空串都是 null,由界面显示占位符。
18
+ * Number(null) 是 0,直接把 null 转成数字会把"读不到"显示成"余额 0"。
19
+ *
20
+ * 密钥引用:DSH 的模型页把用户键入的 Key 写到 `<ROUTE>_API_KEY`(route id 大写、
21
+ * 非字母数字换成下划线),所以派生引用优先;适配器自己声明的环境名(pi-ai 的
22
+ * PROVIDER_DATA.nativeAuth.env)作为第二条路径,覆盖用户在 shell / .env 里导出的
23
+ * 情况。两者都不是机密本身,可以出现在错误文案里告诉用户该配哪一个。
24
+ */
25
+
26
+ import { customHeaders, customTargets, parseCustomPayload } from './custom.js';
27
+
28
+ /** 失败分类(宿主据此选文案,界面只看到一句人话)。 */
29
+ export const ACCOUNT_EMPTY = 'empty'; // 有响应,但没有可用数值
30
+ export const ACCOUNT_SHAPE = 'shape'; // 有响应,但字段不认得
31
+ export const ACCOUNT_UNAVAILABLE = 'unavailable'; // 账户被供应商标记为不可用
32
+
33
+ /**
34
+ * API Key 可查余额的提供商。
35
+ *
36
+ * `hosts` 按顺序尝试:不同 host 的响应形状相同,只是域名/区域不同(如 Moonshot 的
37
+ * 国际站与国内站)。第一个返回可用数值的 host 胜出,全部失败时报最后一个的失败分类。
38
+ * `auth` 描述 Authorization 头的形态——`bearer` 是 `Bearer <key>`,`raw` 是把 Key
39
+ * 原样放进头(智谱国内站 open.bigmodel.cn 的口径)。
40
+ */
41
+ const BALANCE_PROVIDERS = {
42
+ // DeepSeek 官方有三条路由(api-key / account / pi-ai 目录里的 deepseek),
43
+ // 余额接口与密钥引用完全相同。`hosts` 为空表示端点由 lib/index.js 拼
44
+ // (要兼容 DEEPSEEK_BASE_URL 覆盖)。
45
+ //
46
+ // api-key 规格只有 `deepseek-official` 一个映射目标:`deepseek` 是 pi-ai 目录
47
+ // 里同一笔余额的另一条路由,见 aliasableProviderIds()。
48
+ 'deepseek-official': {
49
+ id: 'deepseek-official',
50
+ displayName: 'DeepSeek',
51
+ kind: 'balance',
52
+ refs: ['DEEPSEEK_API_KEY'],
53
+ hosts: [],
54
+ },
55
+ // DSH 账号登录路由:余额接口与官方 api-key 路由相同,但凭证是宿主登录换来的
56
+ // grant(lib/index.js 从凭证记录里取),请求头也不是 Bearer —— 见 `header`。
57
+ 'deepseek-account': {
58
+ id: 'deepseek-account',
59
+ displayName: 'DeepSeek Account',
60
+ kind: 'balance',
61
+ refs: [],
62
+ header: 'x-dsh-auth-token',
63
+ hosts: [],
64
+ },
65
+ deepseek: {
66
+ id: 'deepseek',
67
+ displayName: 'DeepSeek',
68
+ kind: 'balance',
69
+ refs: ['DEEPSEEK_API_KEY'],
70
+ hosts: [],
71
+ },
72
+ moonshotai: {
73
+ id: 'moonshotai',
74
+ displayName: 'Moonshot',
75
+ kind: 'balance',
76
+ refs: ['MOONSHOTAI_API_KEY', 'MOONSHOT_API_KEY'],
77
+ hosts: [
78
+ { host: 'https://api.moonshot.ai', path: '/v1/users/me/balance', auth: 'bearer', currency: 'USD' },
79
+ { host: 'https://api.moonshot.cn', path: '/v1/users/me/balance', auth: 'bearer', currency: 'CNY' },
80
+ ],
81
+ },
82
+ zai: {
83
+ id: 'zai',
84
+ displayName: 'Z.ai (GLM)',
85
+ kind: 'balance',
86
+ refs: ['ZAI_API_KEY', 'ZAI_CODING_CN_API_KEY'],
87
+ hosts: [
88
+ { host: 'https://api.z.ai', path: '/api/biz/account/query-customer-account-report', auth: 'bearer' },
89
+ { host: 'https://open.bigmodel.cn', path: '/api/biz/account/query-customer-account-report', auth: 'raw' },
90
+ ],
91
+ },
92
+ openrouter: {
93
+ id: 'openrouter',
94
+ displayName: 'OpenRouter',
95
+ kind: 'balance',
96
+ refs: ['OPENROUTER_API_KEY'],
97
+ hosts: [
98
+ { host: 'https://openrouter.ai', path: '/api/v1/key', auth: 'bearer' },
99
+ ],
100
+ // 单个 Key 没有限额时(limit_remaining 为 null),回落查账户总余额。
101
+ // 该接口要求 management key,普通 Key 会 403,因此失败分类照常上报。
102
+ fallback: { host: 'https://openrouter.ai', path: '/api/v1/credits', auth: 'bearer' },
103
+ },
104
+ };
105
+
106
+ /**
107
+ * 订阅用量类提供商:没有余额接口,但关键字配额接口。
108
+ * `windows` 声明窗口 key 的展示顺序(客户端本地化成 5 小时 / 7 天 / 30 天)。
109
+ */
110
+ const USAGE_PROVIDERS = {
111
+ 'kimi-coding': {
112
+ id: 'kimi-coding',
113
+ displayName: 'Kimi For Coding',
114
+ kind: 'usage',
115
+ refs: ['KIMI_CODING_API_KEY', 'KIMI_API_KEY'],
116
+ hosts: [{ host: 'https://api.kimi.com', path: '/coding/v1/usages', auth: 'bearer' }],
117
+ windows: ['5h', '7d', '30d'],
118
+ },
119
+ opencode: {
120
+ id: 'opencode',
121
+ displayName: 'OpenCode',
122
+ kind: 'usage',
123
+ refs: ['OPENCODE_API_KEY'],
124
+ hosts: [{ host: 'https://opencode.ai', path: '/zen/go/v1/usage', auth: 'dual' }],
125
+ windows: ['5h', '7d', '30d'],
126
+ },
127
+ 'opencode-go': {
128
+ id: 'opencode-go',
129
+ displayName: 'OpenCode Go',
130
+ kind: 'usage',
131
+ refs: ['OPENCODE_GO_API_KEY', 'OPENCODE_API_KEY'],
132
+ hosts: [{ host: 'https://opencode.ai', path: '/zen/go/v1/usage', auth: 'dual' }],
133
+ windows: ['5h', '7d', '30d'],
134
+ },
135
+ minimax: {
136
+ id: 'minimax',
137
+ displayName: 'MiniMax',
138
+ kind: 'usage',
139
+ refs: ['MINIMAX_API_KEY'],
140
+ hosts: [{ host: 'https://www.minimax.io', path: '/v1/token_plan/remains', auth: 'bearer' }],
141
+ windows: ['cycle', '7d'],
142
+ },
143
+ 'minimax-cn': {
144
+ id: 'minimax-cn',
145
+ displayName: 'MiniMax (CN)',
146
+ kind: 'usage',
147
+ refs: ['MINIMAX_CN_API_KEY', 'MINIMAX_API_KEY'],
148
+ hosts: [{ host: 'https://api.minimaxi.com', path: '/v1/token_plan/remains', auth: 'bearer' }],
149
+ windows: ['cycle', '7d'],
150
+ },
151
+ };
152
+
153
+ /**
154
+ * OAuth 订阅类提供商:接口只有 OAuth 令牌能读,令牌由用户在插件页粘贴。
155
+ * `usage` 是完整令牌的查询端点;`probe` 是 setup-token 的兜底——一次最小推理请求,
156
+ * 从响应头里读节流状态(5h / 7d 两个窗口)。
157
+ */
158
+ const OAUTH_PROVIDERS = {
159
+ anthropic: {
160
+ id: 'anthropic',
161
+ displayName: 'Claude Code',
162
+ kind: 'oauth',
163
+ tokenRef: 'DSH_USAGE_CLAUDE_OAUTH_TOKEN',
164
+ usage: {
165
+ host: 'https://api.anthropic.com',
166
+ path: '/api/oauth/usage',
167
+ method: 'GET',
168
+ // 该端点要求 user:profile scope;claude setup-token 产的令牌只有
169
+ // user:inference,会拿到 403,此时走 probe 兜底。
170
+ headers: { 'anthropic-beta': 'oauth-2025-04-20' },
171
+ },
172
+ probe: {
173
+ host: 'https://api.anthropic.com',
174
+ path: '/v1/messages',
175
+ method: 'POST',
176
+ headers: {
177
+ 'anthropic-beta': 'oauth-2025-04-20',
178
+ 'anthropic-version': '2023-06-01',
179
+ 'content-type': 'application/json',
180
+ },
181
+ // 只取响应头,内容丢弃;max_tokens: 1 是社区实现沿用的最小请求。
182
+ body: { model: 'claude-haiku-4-5-20251001', max_tokens: 1, messages: [{ role: 'user', content: '.' }] },
183
+ },
184
+ windows: ['5h', '7d', '7d-opus'],
185
+ },
186
+ 'openai-codex': {
187
+ id: 'openai-codex',
188
+ displayName: 'OpenAI Codex',
189
+ kind: 'oauth',
190
+ tokenRef: 'DSH_USAGE_CODEX_OAUTH_TOKEN',
191
+ // ChatGPT-Account-Id 头是账号标识而非机密,与令牌同走凭证 seam 一处管理。
192
+ accountRef: 'DSH_USAGE_CODEX_ACCOUNT_ID',
193
+ usage: {
194
+ host: 'https://chatgpt.com',
195
+ path: '/backend-api/wham/usage',
196
+ method: 'GET',
197
+ },
198
+ windows: ['5h', '7d'],
199
+ },
200
+ };
201
+
202
+ /**
203
+ * 查不到账户数据的提供商及原因。`reason` 是给用户看的一句"为什么",
204
+ * 由客户端本地化;这里只给分类键。
205
+ */
206
+ const UNSUPPORTED_PROVIDERS = {
207
+ 'github-copilot': 'oauthOnly',
208
+ google: 'cloudAuthOnly',
209
+ 'google-vertex': 'cloudAuthOnly',
210
+ 'amazon-bedrock': 'cloudAuthOnly',
211
+ azure: 'cloudAuthOnly',
212
+ };
213
+
214
+ /**
215
+ * provider 路由 id 别名 → 能力表里的规范 id。
216
+ *
217
+ * 同一个订阅接口会被不同插件注册成不同的路由 id:第三方 Codex 插件把 ChatGPT
218
+ * 订阅注册成 `chatgpt-codex`,另一套工具用 `openai-codex`。能力表按路由 id 索引,
219
+ * 不做归一化时别名会被判成「不支持的提供商」,账户卡片整张置空、只剩一句
220
+ * `当前插件不支持 chatgpt-codex`,而同一份令牌本来是能读的。
221
+ */
222
+ const PROVIDER_ID_ALIASES = new Map([['chatgpt-codex', 'openai-codex']]);
223
+
224
+ /** 把路由 id 归一成能力表里的规范 id(大小写/空白容错;未知 id 原样返回)。 */
225
+ export function canonicalProviderId(providerId) {
226
+ if (typeof providerId !== 'string') return providerId;
227
+ const id = providerId.trim().toLowerCase();
228
+ return PROVIDER_ID_ALIASES.get(id) ?? id;
229
+ }
230
+
231
+ /** 所有 provider id → 能力条目。 */
232
+ export function accountCapabilityOf(providerId) {
233
+ if (typeof providerId !== 'string') return null;
234
+ const id = canonicalProviderId(providerId);
235
+ const found = BALANCE_PROVIDERS[id] ?? USAGE_PROVIDERS[id] ?? OAUTH_PROVIDERS[id];
236
+ if (found) return found;
237
+ const reason = UNSUPPORTED_PROVIDERS[id];
238
+ if (reason !== undefined) return { id, displayName: id, kind: 'none', reason };
239
+ return null;
240
+ }
241
+
242
+ /**
243
+ * 一个 provider 的候选密钥引用(按优先级)。
244
+ * DSH 模型页写入的派生引用在前(与 ui-settings-models 的 deriveKeyRef 同规则),
245
+ * 适配器原生环境名在后。
246
+ */
247
+ export function candidateRefsOf(providerId) {
248
+ const entry = accountCapabilityOf(providerId);
249
+ if (!entry || entry.kind !== 'balance' && entry.kind !== 'usage') return [];
250
+ const derived = `${String(providerId).toUpperCase().replace(/[^A-Z0-9]+/g, '_')}_API_KEY`;
251
+ const refs = [derived, ...(entry.refs ?? [])];
252
+ return [...new Set(refs)];
253
+ }
254
+
255
+ /** OAuth 提供商的令牌引用(未配置 OAuth 的 provider 返回 null)。 */
256
+ export function oauthProviderOf(providerId) {
257
+ if (typeof providerId !== 'string') return null;
258
+ return OAUTH_PROVIDERS[canonicalProviderId(providerId)] ?? null;
259
+ }
260
+
261
+ /** 支持 OAuth 订阅令牌的 provider id 全集。 */
262
+ export function oauthProviderIds() {
263
+ return Object.keys(OAUTH_PROVIDERS);
264
+ }
265
+
266
+ /** 受支持(kind 不是 none)的 provider id 全集。 */
267
+ export function supportedProviderIds() {
268
+ return [
269
+ ...Object.keys(BALANCE_PROVIDERS),
270
+ ...Object.keys(USAGE_PROVIDERS),
271
+ ...Object.keys(OAUTH_PROVIDERS),
272
+ ];
273
+ }
274
+
275
+ /**
276
+ * 可以作为「用户映射」目标的 provider id:有可查账户的路由。
277
+ *
278
+ * 包含 balance / usage(凭据是 API Key)与 oauth(凭据是订阅令牌,令牌由插件页
279
+ * 单独写入凭据服务,映射行不填凭据引用)。排除 `deepseek-account`(走宿主登录
280
+ * grant,不读 API Key)与 `deepseek`(pi-ai 目录里读同一笔 DeepSeek 余额的另一条
281
+ * 路由,只保留 `deepseek-official` 作为目标,免得下拉出现两个语义相同的选项)。
282
+ * 顺序沿用能力表声明顺序——设置页的下拉与 Config 的枚举共用这一份,新增能力条目时
283
+ * 不用另改两处。
284
+ */
285
+ export function aliasableProviderIds() {
286
+ return supportedProviderIds().filter((id) => {
287
+ if (id === 'deepseek-account' || id === 'deepseek') return false;
288
+ const entry = accountCapabilityOf(id);
289
+ return entry !== null;
290
+ });
291
+ }
292
+
293
+ /** 不可查原因的分类键(未登记的 provider 返回 null)。 */
294
+ export function unsupportedReasonOf(providerId) {
295
+ if (typeof providerId !== 'string') return null;
296
+ return UNSUPPORTED_PROVIDERS[providerId.trim().toLowerCase()] ?? null;
297
+ }
298
+
299
+ /** 容忍字符串/数字,返回有限数或 NaN。 */
300
+ function toFinite(value) {
301
+ if (typeof value === 'number') return Number.isFinite(value) ? value : NaN;
302
+ if (typeof value === 'string' && value.trim() !== '') {
303
+ const n = Number(value);
304
+ return Number.isFinite(n) ? n : NaN;
305
+ }
306
+ return NaN;
307
+ }
308
+
309
+ /** 取有限数或 null(绝不把缺失变成 0)。 */
310
+ function finiteOrNull(value) {
311
+ const n = toFinite(value);
312
+ return Number.isFinite(n) ? n : null;
313
+ }
314
+
315
+ /** 解析时间戳:秒 / 毫秒 / ISO 字符串 → ms 或 null。 */
316
+ function toEpochMs(value) {
317
+ const n = toFinite(value);
318
+ if (Number.isFinite(n)) {
319
+ // 10 位按秒、13 位按毫秒;其余量级不当时间戳。
320
+ if (n > 1e11) return n;
321
+ if (n > 1e8) return n * 1000;
322
+ return null;
323
+ }
324
+ if (typeof value === 'string' && value.trim() !== '') {
325
+ const t = Date.parse(value);
326
+ return Number.isFinite(t) ? t : null;
327
+ }
328
+ return null;
329
+ }
330
+
331
+ /** 归一成空余额(拿不到时界面显示占位符,不是 0)。 */
332
+ function emptyBalance() {
333
+ return { isAvailable: null, total: null, currency: null };
334
+ }
335
+
336
+ function ok(balance) {
337
+ return { ok: true, balance, usage: null };
338
+ }
339
+
340
+ /** 归一成一次成功的用量读数。 */
341
+ function okUsage(usage) {
342
+ return { ok: true, balance: null, usage };
343
+ }
344
+
345
+ function fail(code) {
346
+ return { ok: false, balance: null, usage: null, code };
347
+ }
348
+
349
+ // ---- DeepSeek 官方余额 ----------------------------------------------------
350
+
351
+ /** 是否大陆账号的 CNY 钱包(币种大小写/空白容错)。 */
352
+ function isCnyWallet(info) {
353
+ return typeof info?.currency === 'string' && info.currency.trim().toUpperCase() === 'CNY';
354
+ }
355
+
356
+ /**
357
+ * 解析 DeepSeek `GET /user/balance`:
358
+ * { is_available, balance_infos: [{ currency, total_balance, … }] }
359
+ *
360
+ * 一个响应可能有多个钱包,大陆账号把 USD(0) 排在 CNY(有余额) 前面。先滤掉
361
+ * 没有数值的钱包,再优先取真正有余额的那个;多个都有余额时优先 CNY;全都
362
+ * 没有余额就退回第一条。
363
+ */
364
+ export function parseDeepSeekBalance(body) {
365
+ // 可用性是账户级状态,与钱包列表无关:即使响应没带任何余额,也要报"不可用"
366
+ // 而不是"没有数值",否则用户会以为读取失败而非账户被停用。
367
+ if (body?.is_available === false) return fail(ACCOUNT_UNAVAILABLE);
368
+ const infos = body && Array.isArray(body.balance_infos) ? body.balance_infos : [];
369
+ const withTotal = infos.filter((info) => finiteOrNull(info?.total_balance) !== null);
370
+ const funded = withTotal.filter((info) => finiteOrNull(info.total_balance) > 0);
371
+ const first = funded.find(isCnyWallet) ?? funded[0] ?? withTotal[0] ?? infos[0] ?? {};
372
+ const total = finiteOrNull(first.total_balance);
373
+ if (total === null) return fail(ACCOUNT_EMPTY);
374
+ const balance = emptyBalance();
375
+ balance.isAvailable = body?.is_available !== false;
376
+ balance.total = total;
377
+ balance.currency = typeof first.currency === 'string' && first.currency.trim() !== '' ? first.currency.trim() : null;
378
+ return ok(balance);
379
+ }
380
+
381
+ // ---- Moonshot / Kimi 余额 -------------------------------------------------
382
+
383
+ /**
384
+ * 解析 Moonshot `GET /v1/users/me/balance`:
385
+ * { code: 0, data: { available_balance, voucher_balance, cash_balance }, status: true }
386
+ * code 非 0 是业务错误(401 等),按"无法识别的内容"处理。
387
+ */
388
+ export function parseMoonshotBalance(body) {
389
+ // 没有 data 对象就是形状不对(空 body、HTML 错误页、数组等)。
390
+ const data = body && typeof body.data === 'object' && body.data !== null ? body.data : null;
391
+ if (data === null) return fail(ACCOUNT_SHAPE);
392
+ const code = toFinite(body.code);
393
+ // code 非 0 是业务错误(401 / 1001 等),不是"没有数据"。
394
+ if (Number.isFinite(code) && code !== 0) return fail(ACCOUNT_SHAPE);
395
+ const total = finiteOrNull(data.available_balance);
396
+ if (total === null) return fail(ACCOUNT_EMPTY);
397
+ const balance = emptyBalance();
398
+ balance.isAvailable = true;
399
+ balance.total = total;
400
+ // 接口不返回币种,由调用方按 host 补(国际站 USD / 国内站 CNY)。
401
+ return ok(balance);
402
+ }
403
+
404
+ // ---- 智谱 GLM 标准 API 余额 ----------------------------------------------
405
+
406
+ /**
407
+ * 解析智谱 `GET /api/biz/account/query-customer-account-report`:
408
+ * { success: true, data: { balance, availableBalance, rechargeAmount, … } }
409
+ * success 为 false 是业务错误;data 为空对象视为没有数据。
410
+ */
411
+ export function parseZaiBalance(body) {
412
+ if (body && body.success === false) return fail(ACCOUNT_SHAPE);
413
+ const data = body && typeof body.data === 'object' && body.data !== null ? body.data : null;
414
+ if (data === null) return fail(ACCOUNT_SHAPE);
415
+ const total = finiteOrNull(data.availableBalance ?? data.balance);
416
+ if (total === null) return fail(ACCOUNT_EMPTY);
417
+ const balance = emptyBalance();
418
+ balance.isAvailable = true;
419
+ balance.total = total;
420
+ balance.currency = 'CNY';
421
+ return ok(balance);
422
+ }
423
+
424
+ // ---- OpenRouter 余额 ------------------------------------------------------
425
+
426
+ /**
427
+ * 解析 OpenRouter `GET /api/v1/key`:
428
+ * { data: { limit, limit_remaining, usage, … } }
429
+ * limit_remaining 为 null 表示这个 Key 没有限额——此时调用方回落 /api/v1/credits。
430
+ */
431
+ export function parseOpenRouterKey(body) {
432
+ const data = body && typeof body.data === 'object' && body.data !== null ? body.data : null;
433
+ if (data === null) return fail(ACCOUNT_SHAPE);
434
+ const remaining = data.limit_remaining;
435
+ if (remaining === null || remaining === undefined) return fail(ACCOUNT_EMPTY);
436
+ const total = finiteOrNull(remaining);
437
+ if (total === null) return fail(ACCOUNT_SHAPE);
438
+ const balance = emptyBalance();
439
+ balance.isAvailable = true;
440
+ balance.total = total;
441
+ balance.currency = 'USD';
442
+ return ok(balance);
443
+ }
444
+
445
+ /**
446
+ * 解析 OpenRouter `GET /api/v1/credits`(management key):
447
+ * { data: { total_credits, total_usage } }
448
+ */
449
+ export function parseOpenRouterCredits(body) {
450
+ const data = body && typeof body.data === 'object' && body.data !== null ? body.data : null;
451
+ if (data === null) return fail(ACCOUNT_SHAPE);
452
+ const total = finiteOrNull(data.total_credits);
453
+ const used = finiteOrNull(data.total_usage);
454
+ if (total === null || used === null) return fail(ACCOUNT_EMPTY);
455
+ const balance = emptyBalance();
456
+ balance.isAvailable = true;
457
+ balance.total = total - used;
458
+ balance.currency = 'USD';
459
+ return ok(balance);
460
+ }
461
+
462
+ // ---- Kimi For Coding 用量 -------------------------------------------------
463
+
464
+ /**
465
+ * 解析 Kimi Coding `GET /coding/v1/usages`。
466
+ *
467
+ * 同一响应里有三种窗口来源(社区实现实测;字段随账号与接口版本略有出入):
468
+ * · `usage.limit` / `usage.used` / `usage.remaining` + `usage.resetTime` —— 周窗口;
469
+ * · `usage.limits[]`:`window.duration` + `timeUnit` 定长度,`detail` 里是
470
+ * `limit` / `used` / `remaining`(也接受 usedPercent 一类旧字段)—— 通常是 5 小时;
471
+ * · `usages.limit_5h` / `limit_month_total` / `limit_month_code`:`used_ratio`
472
+ * (0..1)+ `reset_time` —— 比例池,其中 month_* 是月窗口。
473
+ *
474
+ * 百分比优先用接口明确给的;没有就用 used/limit 或 (limit-remaining)/limit 换算。
475
+ * 同一个窗口 key 出现多次时保留已用百分比更高的那条(最先撞限的那条)。
476
+ */
477
+ export function parseKimiCodingUsage(body) {
478
+ const usage = body?.usage;
479
+ const usages = body?.usages;
480
+ const usageOk = usage !== null && typeof usage === 'object';
481
+ const usagesOk = usages !== null && typeof usages === 'object';
482
+ if (!usageOk && !usagesOk) return fail(ACCOUNT_SHAPE);
483
+ const windows = [];
484
+ const push = (key, percent, resetsAt) => {
485
+ if (percent === null) return;
486
+ const seen = windows.find((w) => w.key === key);
487
+ if (seen === undefined) windows.push({ key, percent, resetsAt });
488
+ else if (percent > seen.percent) {
489
+ seen.percent = percent;
490
+ seen.resetsAt = resetsAt;
491
+ }
492
+ };
493
+ if (usageOk) {
494
+ // 周窗口:顶层 limit / used / remaining。
495
+ push('7d', usedPercentOf(usage), toEpochMs(usage.resetTime ?? usage.reset_time ?? usage.resetsAt));
496
+ if (Array.isArray(usage.limits)) {
497
+ for (const limit of usage.limits) {
498
+ const window = limit?.window ?? limit ?? {};
499
+ const detail = limit?.detail ?? limit ?? {};
500
+ push(
501
+ windowKeyOf(window),
502
+ usedPercentOf(detail),
503
+ toEpochMs(detail.resetTime ?? detail.reset_time ?? detail.resetsAt),
504
+ );
505
+ }
506
+ }
507
+ }
508
+ if (usagesOk) {
509
+ const map = { limit_5h: '5h', limit_month_total: '30d', limit_month_code: '30d' };
510
+ for (const [field, key] of Object.entries(map)) {
511
+ const entry = usages[field];
512
+ if (entry === null || typeof entry !== 'object') continue;
513
+ push(key, usedPercentOf(entry), toEpochMs(entry.reset_time ?? entry.resetTime));
514
+ }
515
+ }
516
+ if (windows.length === 0) return fail(ACCOUNT_EMPTY);
517
+ return okUsage({ plan: null, windows });
518
+ }
519
+
520
+ /**
521
+ * 从各家用量条目里取"已用百分比":显式百分比 → used_ratio → used/limit →
522
+ * (limit-remaining)/limit。都没有时返回 null(该窗口跳过,不当成 0)。
523
+ */
524
+ function usedPercentOf(entry) {
525
+ if (entry === null || typeof entry !== 'object') return null;
526
+ const explicit = finiteOrNull(entry.usedPercent ?? entry.used_percent ?? entry.percent);
527
+ if (explicit !== null) return explicit;
528
+ const ratio = finiteOrNull(entry.used_ratio ?? entry.usedRatio);
529
+ if (ratio !== null) return ratio * 100;
530
+ const limit = finiteOrNull(entry.limit ?? entry.total);
531
+ if (limit === null || limit <= 0) return null;
532
+ const used = finiteOrNull(entry.used);
533
+ if (used !== null) return (used / limit) * 100;
534
+ const remaining = finiteOrNull(entry.remaining ?? entry.remains ?? entry.left);
535
+ if (remaining !== null) return ((limit - remaining) / limit) * 100;
536
+ return null;
537
+ }
538
+
539
+ /**
540
+ * 窗口时长 → 卡片上的窗口标签。
541
+ *
542
+ * 先把 duration + timeUnit 归一成分钟,再按长度分档:≤ 5 小时是 `5h`,
543
+ * > 5 小时且 ≤ 8 天是 `7d`,其余是 `cycle`(Kimi 只暴露这两档,其余长度不猜)。
544
+ * 缺 duration 或单位时不猜,直接 `cycle`。
545
+ */
546
+ function windowKeyOf(window) {
547
+ const duration = toFinite(window?.duration);
548
+ if (!Number.isFinite(duration)) return 'cycle';
549
+ // Kimi 的接口给的是枚举值 `TIME_UNIT_MINUTE`,不是裸的 `MINUTE`;
550
+ // 不剥前缀会让 5h/7d 窗口落到 cycle,卡片上显示成「周期」。
551
+ const unit = String(window?.timeUnit ?? window?.time_unit ?? '')
552
+ .toUpperCase().replace(/^TIME_UNIT_/, '');
553
+ const perUnit = { MINUTE: 1, HOUR: 60, DAY: 1440, SECOND: 1 / 60 };
554
+ const minutes = duration * (perUnit[unit] ?? NaN);
555
+ if (!Number.isFinite(minutes)) return 'cycle';
556
+ if (minutes <= 5 * 60) return '5h';
557
+ if (minutes <= 8 * 1440) return '7d';
558
+ return 'cycle';
559
+ }
560
+
561
+ // ---- OpenCode Zen 用量 ----------------------------------------------------
562
+
563
+ /**
564
+ * 解析 OpenCode `GET /zen/go/v1/usage`:
565
+ * { usage: { rolling: { status, percent, resetsAt }, weekly: {…}, monthly: {…} } }
566
+ * percent 是已用百分比;status 非 ok 的窗口跳过(未订阅/无数据)。
567
+ */
568
+ export function parseOpenCodeUsage(body) {
569
+ const usage = body?.usage;
570
+ if (usage === null || typeof usage !== 'object') return fail(ACCOUNT_SHAPE);
571
+ const map = { rolling: '5h', weekly: '7d', monthly: '30d' };
572
+ const windows = [];
573
+ for (const [field, key] of Object.entries(map)) {
574
+ const entry = usage[field];
575
+ if (entry === null || typeof entry !== 'object') continue;
576
+ if (typeof entry.status === 'string' && entry.status !== 'ok') continue;
577
+ const percent = finiteOrNull(entry.percent);
578
+ if (percent === null) continue;
579
+ windows.push({ key, percent, resetsAt: toEpochMs(entry.resetsAt ?? entry.resets_at) });
580
+ }
581
+ if (windows.length === 0) return fail(ACCOUNT_EMPTY);
582
+ return okUsage({ plan: null, windows });
583
+ }
584
+
585
+ // ---- MiniMax Coding Plan 用量 ---------------------------------------------
586
+
587
+ /**
588
+ * 解析 MiniMax `GET /v1/token_plan/remains`:
589
+ * { base_resp: { status_code }, model_remains: [ { …,
590
+ * current_interval_remaining_percent, end_time,
591
+ * current_weekly_remaining_percent, weekly_end_time } ] }
592
+ * model_remains 按模型 / 配额桶分多条,每条自带区间窗口与周窗口。卡片是摘要:
593
+ * 每个窗口取所有桶里已用百分比最高的那条(最先撞限),区间窗口标成 cycle
594
+ * (长度随套餐与桶而变),周窗口标成 7d。
595
+ * 各家实现对"已用"的口径不一致(有的把 usage 当剩余),这里只采信剩余百分比与
596
+ * 总数/剩余数:剩余百分比缺失且总数也缺失时不猜,直接跳过该窗口。
597
+ */
598
+ export function parseMiniMaxRemains(body) {
599
+ if (body?.base_resp && toFinite(body.base_resp.status_code) !== 0) return fail(ACCOUNT_SHAPE);
600
+ const rows = body?.model_remains;
601
+ if (!Array.isArray(rows) || rows.length === 0) return fail(ACCOUNT_EMPTY);
602
+ const best = { cycle: null, '7d': null };
603
+ for (const row of rows) {
604
+ const candidates = [
605
+ ['cycle', usedPercentFromRemaining(row.current_interval_remaining_percent), row.end_time ?? row.remains_time,
606
+ usedPercentFromCounts(row.current_interval_total_count, row.current_interval_remaining_count ?? row.current_interval_remains_count)],
607
+ ['7d', usedPercentFromRemaining(row.current_weekly_remaining_percent), row.weekly_end_time,
608
+ usedPercentFromCounts(row.current_weekly_total_count, row.current_weekly_remaining_count)],
609
+ ];
610
+ for (const [key, fromPercent, resetsAt, fromCounts] of candidates) {
611
+ const value = fromPercent ?? fromCounts;
612
+ if (value === null) continue;
613
+ const clamped = Math.max(0, Math.min(100, value));
614
+ if (best[key] === null || clamped > best[key].percent) {
615
+ best[key] = { key, percent: clamped, resetsAt: toEpochMs(resetsAt) };
616
+ }
617
+ }
618
+ }
619
+ const windows = Object.values(best).filter((w) => w !== null);
620
+ if (windows.length === 0) return fail(ACCOUNT_EMPTY);
621
+ return okUsage({ plan: null, windows });
622
+ }
623
+
624
+ /** 剩余百分比 → 已用百分比(接口给的是剩余)。 */
625
+ function usedPercentFromRemaining(remainingPercent) {
626
+ const remaining = finiteOrNull(remainingPercent);
627
+ return remaining === null ? null : 100 - remaining;
628
+ }
629
+
630
+ /** 总数 + 剩余数 → 已用百分比;任一缺失或总数为 0 时返回 null。 */
631
+ function usedPercentFromCounts(totalValue, remainingValue) {
632
+ const total = finiteOrNull(totalValue);
633
+ const remaining = finiteOrNull(remainingValue);
634
+ if (total === null || remaining === null || total <= 0) return null;
635
+ return ((total - remaining) / total) * 100;
636
+ }
637
+
638
+ // ---- Claude Code OAuth 用量 ----------------------------------------------
639
+
640
+ /**
641
+ * 解析 Claude `GET /api/oauth/usage`:
642
+ * { five_hour: { utilization, resets_at }, seven_day: {…}, seven_day_opus: {…},
643
+ * extra_usage: { is_enabled, used_credits, monthly_limit, currency } }
644
+ * utilization 是 0–100 的已用百分比;null 表示该窗口未启用。
645
+ * seven_day_opus 是模型专属的周窗口,key 与 seven_day 分开,界面上才不会被
646
+ * 合并成两个同名窗口。extra_usage 是按量超额(金额),不是时间窗口,不在此列。
647
+ */
648
+ export function parseClaudeOAuthUsage(body) {
649
+ if (body === null || typeof body !== 'object') return fail(ACCOUNT_SHAPE);
650
+ const map = { five_hour: '5h', seven_day: '7d', seven_day_opus: '7d-opus' };
651
+ const windows = [];
652
+ for (const [field, key] of Object.entries(map)) {
653
+ const entry = body[field];
654
+ if (entry === null || typeof entry !== 'object') continue;
655
+ const percent = finiteOrNull(entry.utilization);
656
+ if (percent === null) continue;
657
+ windows.push({ key, percent, resetsAt: toEpochMs(entry.resets_at) });
658
+ }
659
+ if (windows.length === 0) return fail(ACCOUNT_EMPTY);
660
+ return okUsage({ plan: null, windows });
661
+ }
662
+
663
+ /**
664
+ * 从 Claude 推理响应头合成用量窗口(setup-token 兜底路径)。
665
+ *
666
+ * 头名:anthropic-ratelimit-unified-{5h,7d}-utilization(0..1 小数)
667
+ * anthropic-ratelimit-unified-{5h,7d}-reset(unix 秒)
668
+ * 任意一个窗口都取不到时返回 null——调用方据此判断"这个令牌读不到用量"。
669
+ */
670
+ export function parseClaudeRateLimitHeaders(headers) {
671
+ const pick = (name) => {
672
+ const raw = headers?.[name];
673
+ const value = Array.isArray(raw) ? raw[0] : raw;
674
+ if (value === undefined || value === null) return null;
675
+ const n = Number(value);
676
+ return Number.isFinite(n) ? n : null;
677
+ };
678
+ const windows = [];
679
+ for (const [suffix, key] of [['5h', '5h'], ['7d', '7d']]) {
680
+ const utilization = pick(`anthropic-ratelimit-unified-${suffix}-utilization`);
681
+ if (utilization === null) continue;
682
+ const resetSecs = pick(`anthropic-ratelimit-unified-${suffix}-reset`);
683
+ windows.push({
684
+ key,
685
+ percent: Math.max(0, Math.min(100, utilization * 100)),
686
+ resetsAt: resetSecs === null ? null : resetSecs * 1000,
687
+ });
688
+ }
689
+ if (windows.length === 0) return null;
690
+ return { ok: true, balance: null, usage: { plan: null, windows } };
691
+ }
692
+
693
+ // ---- OpenAI Codex 用量 ----------------------------------------------------
694
+
695
+ /**
696
+ * 解析 Codex `GET /backend-api/wham/usage`:
697
+ * { plan_type, rate_limit: { primary_window: { used_percent, reset_at,
698
+ * limit_window_seconds }, secondary_window: {…} },
699
+ * credits: { has_credits, unlimited, balance } }
700
+ * primary / secondary 是位置化的:窗口长度由各自的 limit_window_seconds 决定
701
+ * (当前为 5 小时会话窗口与 7 天窗口)。优先按秒数标注窗口,缺字段时才退回
702
+ * "primary=5h / secondary=7d" 的历史口径。credits.balance 是余额,与窗口分开
703
+ * 返回:余额有值时作为 usage.balance 一并给出,界面优先显示余额。
704
+ */
705
+ export function parseCodexUsage(body) {
706
+ if (body === null || typeof body !== 'object') return fail(ACCOUNT_SHAPE);
707
+ const rate = body.rate_limit;
708
+ if (rate === null || typeof rate !== 'object') return fail(ACCOUNT_SHAPE);
709
+ const windows = [];
710
+ const fallbacks = [[rate.primary_window, '5h'], [rate.secondary_window, '7d']];
711
+ for (const [entry, fallbackKey] of fallbacks) {
712
+ if (entry === null || typeof entry !== 'object') continue;
713
+ const percent = finiteOrNull(entry.used_percent);
714
+ if (percent === null) continue;
715
+ windows.push({
716
+ key: windowKeyOfSeconds(entry.limit_window_seconds) ?? fallbackKey,
717
+ percent,
718
+ resetsAt: toEpochMs(entry.reset_at),
719
+ });
720
+ }
721
+ const credits = body.credits;
722
+ let balance = null;
723
+ if (credits && typeof credits === 'object' && credits.has_credits === true && credits.unlimited !== true) {
724
+ const total = finiteOrNull(credits.balance);
725
+ if (total !== null) {
726
+ balance = { isAvailable: true, total, currency: 'USD' };
727
+ }
728
+ }
729
+ if (windows.length === 0 && balance === null) return fail(ACCOUNT_EMPTY);
730
+ return { ok: true, balance, usage: { plan: typeof body.plan_type === 'string' ? body.plan_type : null, windows } };
731
+ }
732
+
733
+ /**
734
+ * 窗口秒数 → 卡片标签 key:18000 秒是 `5h`、604800 秒是 `7d`;其它长度按
735
+ * 整小时 / 整天的通用写法(如 `1h`、`3d`),由界面本地化。非数字返回 null,
736
+ * 调用方据此退回位置化口径。
737
+ */
738
+ function windowKeyOfSeconds(value) {
739
+ const seconds = toFinite(value);
740
+ if (!Number.isFinite(seconds) || seconds <= 0) return null;
741
+ if (Math.abs(seconds - 18000) <= 60) return '5h';
742
+ if (Math.abs(seconds - 604800) <= 3600) return '7d';
743
+ if (seconds < 72 * 3600) return `${Math.max(1, Math.round(seconds / 3600))}h`;
744
+ return `${Math.max(1, Math.round(seconds / 86400))}d`;
745
+ }
746
+
747
+ // ---- 通用 HTTP 取数 -------------------------------------------------------
748
+
749
+ /** 取数器的运行环境(宿主注入,便于测试替身)。 */
750
+ export function makeAccountReader({
751
+ fetchImpl = globalThis.fetch,
752
+ timeoutMs = 15000,
753
+ maxBodyBytes = 64 * 1024,
754
+ /** DeepSeek 官方余额端点(lib/index.js 传入以兼容 DEEPSEEK_BASE_URL 覆盖)。 */
755
+ deepseekUrl = null,
756
+ } = {}) {
757
+ /** 发一次 GET,返回 { status, headers, text };超时/网络错误抛出带 name 的 Error。 */
758
+ async function request(url, { method = 'GET', headers = {}, body = null } = {}) {
759
+ const response = await fetchImpl(url, {
760
+ method,
761
+ headers: { Accept: 'application/json', ...headers },
762
+ body: body === null ? undefined : JSON.stringify(body),
763
+ signal: AbortSignal.timeout(timeoutMs),
764
+ });
765
+ const text = await response.text();
766
+ return { status: response.status, headers: response.headers, text };
767
+ }
768
+
769
+ /** 解析 JSON;失败抛错(调用方按 shape 处理)。 */
770
+ function parseJson(text, bytes) {
771
+ if (bytes > maxBodyBytes) throw new Error('payload-too-large');
772
+ return JSON.parse(text);
773
+ }
774
+
775
+ /**
776
+ * 按能力表取一个提供商的账户数据。
777
+ *
778
+ * @param entry accountCapabilityOf 的返回值(kind 不能是 none)
779
+ * @param secret 已解析出的密钥 / OAuth 令牌(调用方已做形状校验)
780
+ * @param extra { accountId } —— Codex 的 ChatGPT-Account-Id
781
+ * @returns 归一结果 { ok, balance, usage, code? }
782
+ */
783
+ async function read(entry, secret, extra = {}) {
784
+ if (entry.kind === 'oauth') return readOAuth(entry, secret, extra);
785
+ // 自定义 provider(配置项 customProviders):地址、路径、字段全部由用户给出。
786
+ if (entry.custom !== undefined) return readCustom(entry, secret);
787
+ // DeepSeek 官方余额的端点由宿主拼(兼容 DEEPSEEK_BASE_URL),不写在能力表里。
788
+ if (entry.id === 'deepseek' || entry.id === 'deepseek-official' || entry.id === 'deepseek-account') {
789
+ if (deepseekUrl === null) return fail(ACCOUNT_EMPTY);
790
+ try {
791
+ // `header` 出现的提供商把凭证原样放进指定请求头:DeepSeek 账号登录的
792
+ // grant 只认 x-dsh-auth-token,套成 Bearer 会被上游 401 拒掉。
793
+ const headers = entry.header === undefined
794
+ ? { Authorization: authHeader('bearer', secret) }
795
+ : { [entry.header]: secret };
796
+ const res = await request(deepseekUrl, { headers });
797
+ if (!(res.status >= 200 && res.status < 300)) return fail(ACCOUNT_SHAPE);
798
+ let body;
799
+ try {
800
+ body = parseJson(res.text, Buffer.byteLength(res.text, 'utf8'));
801
+ } catch {
802
+ return fail(ACCOUNT_SHAPE);
803
+ }
804
+ return parseDeepSeekBalance(body);
805
+ } catch (error) {
806
+ const name = error instanceof Error ? error.name : '';
807
+ return fail(name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network');
808
+ }
809
+ }
810
+ const hosts = entry.hosts ?? [];
811
+ let last = fail(ACCOUNT_EMPTY);
812
+ for (const endpoint of hosts) {
813
+ const url = `${endpoint.host}${endpoint.path}`;
814
+ const headers = { Authorization: authHeader(endpoint.auth, secret) };
815
+ // OpenCode 的用量接口要求同时带 Authorization 与 x-api-key。
816
+ if (endpoint.auth === 'dual') headers['x-api-key'] = secret;
817
+ try {
818
+ const res = await request(url, { headers });
819
+ if (!(res.status >= 200 && res.status < 300)) {
820
+ last = fail(ACCOUNT_SHAPE);
821
+ continue;
822
+ }
823
+ let body;
824
+ try {
825
+ body = parseJson(res.text, Buffer.byteLength(res.text, 'utf8'));
826
+ } catch {
827
+ last = fail(ACCOUNT_SHAPE);
828
+ continue;
829
+ }
830
+ const parsed = dispatch(entry.id, body, endpoint);
831
+ if (parsed.ok) return parsed;
832
+ last = parsed;
833
+ // 明确没有数据时换下一个 host 也没意义(同形状),但区域差异可能造成
834
+ // "有响应无数值",继续尝试其余 host 更稳妥。
835
+ } catch (error) {
836
+ const name = error instanceof Error ? error.name : '';
837
+ // 网络类失败(超时、连接被拒)对所有 host 都一样:继续试第二个只会把
838
+ // "连不上"掩盖成"形状不认",所以直接返回。
839
+ if (name === 'TimeoutError' || name === 'AbortError') return fail('timeout');
840
+ return fail('network');
841
+ }
842
+ }
843
+ // OpenRouter 单 Key 无限额时回落查账户总余额。
844
+ if (entry.fallback !== undefined && last.code === ACCOUNT_EMPTY) {
845
+ const endpoint = entry.fallback;
846
+ try {
847
+ const res = await request(`${endpoint.host}${endpoint.path}`, {
848
+ headers: { Authorization: authHeader(endpoint.auth, secret) },
849
+ });
850
+ if (res.status >= 200 && res.status < 300) {
851
+ const body = parseJson(res.text, Buffer.byteLength(res.text, 'utf8'));
852
+ const parsed = parseOpenRouterCredits(body);
853
+ if (parsed.ok) return parsed;
854
+ last = parsed;
855
+ }
856
+ } catch (error) {
857
+ const name = error instanceof Error ? error.name : '';
858
+ last = { ok: false, balance: null, usage: null, code: name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network' };
859
+ }
860
+ }
861
+ return last;
862
+ }
863
+
864
+ /** OAuth 提供商:先查 usage 端点,403 时走最小推理请求的响应头兜底。 */
865
+ async function readOAuth(entry, token, extra) {
866
+ const endpoint = entry.usage;
867
+ const url = `${endpoint.host}${endpoint.path}`;
868
+ const headers = {
869
+ Authorization: `Bearer ${token}`,
870
+ ...endpoint.headers,
871
+ };
872
+ if (entry.accountRef !== undefined && typeof extra.accountId === 'string' && extra.accountId !== '') {
873
+ headers['ChatGPT-Account-Id'] = extra.accountId;
874
+ }
875
+ let sawUnauthorized = false;
876
+ try {
877
+ const res = await request(url, { method: endpoint.method ?? 'GET', headers });
878
+ if (res.status === 401 || res.status === 403) {
879
+ sawUnauthorized = true;
880
+ } else if (res.status >= 200 && res.status < 300) {
881
+ let body;
882
+ try {
883
+ body = parseJson(res.text, Buffer.byteLength(res.text, 'utf8'));
884
+ } catch {
885
+ return fail(ACCOUNT_SHAPE);
886
+ }
887
+ const parsed = entry.id === 'openai-codex' ? parseCodexUsage(body) : parseClaudeOAuthUsage(body);
888
+ if (parsed.ok) return parsed;
889
+ if (parsed.code !== ACCOUNT_EMPTY) return parsed;
890
+ } else {
891
+ return fail(ACCOUNT_SHAPE);
892
+ }
893
+ } catch (error) {
894
+ const name = error instanceof Error ? error.name : '';
895
+ if (name !== 'TimeoutError' && name !== 'AbortError') return fail('network');
896
+ return fail('timeout');
897
+ }
898
+ // 403 且该提供商有 probe(setup-token 只带 user:inference)→ 兜底读响应头。
899
+ if (sawUnauthorized && entry.probe !== undefined) {
900
+ return readProbe(entry, token);
901
+ }
902
+ if (sawUnauthorized) return fail('unauthorized');
903
+ return fail(ACCOUNT_EMPTY);
904
+ }
905
+
906
+ /** 一次最小推理请求,从响应头合成用量窗口。 */
907
+ async function readProbe(entry, token) {
908
+ const probe = entry.probe;
909
+ const url = `${probe.host}${probe.path}`;
910
+ const headers = {
911
+ Authorization: `Bearer ${token}`,
912
+ ...probe.headers,
913
+ };
914
+ try {
915
+ const res = await request(url, { method: probe.method ?? 'POST', headers, body: probe.body });
916
+ if (!(res.status >= 200 && res.status < 300)) {
917
+ // 调用方是在 usage 端点 401/403 之后才走到这里的,令牌无效已经成立;
918
+ // 兜底再失败(限流、模型下线、网络)都改报同一个结论,让界面提示重新填写。
919
+ return fail('unauthorized');
920
+ }
921
+ const parsed = parseClaudeRateLimitHeaders(Object.fromEntries(res.headers.entries()));
922
+ if (parsed === null) return fail(ACCOUNT_EMPTY);
923
+ return parsed;
924
+ } catch (error) {
925
+ const name = error instanceof Error ? error.name : '';
926
+ return fail(name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network');
927
+ }
928
+ }
929
+
930
+ /**
931
+ * 自定义 provider:按配置里的地址打 1~2 个 GET,把 JSON 交给 custom.js 解析。
932
+ *
933
+ * 认证头由配置决定(bearer / raw / none);401、403 归为 unauthorized(界面提示
934
+ * 重新填 Key),其余非 2xx 归为 shape(有响应但读不出数值),网络与超时单独分类。
935
+ * 不缓存任何上游原文,错误里也不带响应体。
936
+ */
937
+ async function readCustom(entry, secret) {
938
+ const spec = entry.custom;
939
+ const payloads = {};
940
+ for (const target of customTargets(spec)) {
941
+ // 两段式账单里第一段是额度(new-api 恒为 1e8 哨兵、OpenAI 也基本不动),
942
+ // 每 10 分钟才重新取一次;usage 那段每次都取。中转站按调用次数限额时这能省掉一半。
943
+ if (target.key === "main") {
944
+ const cached = customMainCache.get(target.url);
945
+ if (cached !== undefined && Date.now() - cached.at < CUSTOM_MAIN_TTL_MS) {
946
+ payloads.main = cached.body;
947
+ continue;
948
+ }
949
+ }
950
+ let res;
951
+ try {
952
+ res = await request(target.url, { headers: customHeaders(spec.auth, secret) });
953
+ } catch (error) {
954
+ const name = error instanceof Error ? error.name : '';
955
+ return fail(name === 'TimeoutError' || name === 'AbortError' ? 'timeout' : 'network');
956
+ }
957
+ if (res.status === 401 || res.status === 403) return fail('unauthorized');
958
+ if (!(res.status >= 200 && res.status < 300)) return fail(ACCOUNT_SHAPE);
959
+ try {
960
+ const body = parseJson(res.text, Buffer.byteLength(res.text, 'utf8'));
961
+ payloads[target.key] = body;
962
+ if (target.key === "main") customMainCache.set(target.url, { at: Date.now(), body });
963
+ } catch {
964
+ return fail(ACCOUNT_SHAPE);
965
+ }
966
+ }
967
+ return parseCustomPayload(entry, payloads);
968
+ }
969
+
970
+ return { read };
971
+ }
972
+
973
+ /** 自定义 provider 第一段(额度/订阅)响应的进程内缓存:省掉反复打同一个接口。 */
974
+ const CUSTOM_MAIN_TTL_MS = 10 * 60 * 1000;
975
+ const customMainCache = new Map();
976
+
977
+ /** Authorization 头形态。 */
978
+ function authHeader(kind, secret) {
979
+ return kind === 'raw' ? secret : `Bearer ${secret}`;
980
+ }
981
+
982
+ /** 按 provider id 选解析函数。 */
983
+ function dispatch(id, body, endpoint) {
984
+ switch (id) {
985
+ case 'deepseek':
986
+ return parseDeepSeekBalance(body);
987
+ case 'moonshotai': {
988
+ const parsed = parseMoonshotBalance(body);
989
+ if (parsed.ok && parsed.balance.currency === null && endpoint.currency) {
990
+ return { ...parsed, balance: { ...parsed.balance, currency: endpoint.currency } };
991
+ }
992
+ return parsed;
993
+ }
994
+ case 'zai':
995
+ return parseZaiBalance(body);
996
+ case 'openrouter':
997
+ return parseOpenRouterKey(body);
998
+ case 'kimi-coding':
999
+ return parseKimiCodingUsage(body);
1000
+ case 'opencode':
1001
+ case 'opencode-go':
1002
+ return parseOpenCodeUsage(body);
1003
+ case 'minimax':
1004
+ case 'minimax-cn':
1005
+ return parseMiniMaxRemains(body);
1006
+ default:
1007
+ return fail(ACCOUNT_SHAPE);
1008
+ }
1009
+ }