@ds-hu/dsh-token-quota 0.0.0-stage → 2.4.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.
Files changed (60) hide show
  1. package/CHANGELOG.md +123 -0
  2. package/CONTEXT.md +179 -0
  3. package/README.md +270 -2
  4. package/cordis.patch.yml +10 -0
  5. package/docs/windows-desktop-adaptation.md +80 -0
  6. package/icon.svg +21 -0
  7. package/lib/client.js +2371 -0
  8. package/lib/detect.js +448 -0
  9. package/lib/index.js +1161 -0
  10. package/lib/legacy-config.js +129 -0
  11. package/lib/providers.js +1203 -0
  12. package/lib/quota-history.js +303 -0
  13. package/lib/routes.js +13 -0
  14. package/lib/scan-coordinator.js +227 -0
  15. package/lib/scheduler.js +86 -0
  16. package/lib/season.js +271 -0
  17. package/lib/storage.js +453 -0
  18. package/lib/usage.js +87 -0
  19. package/locale/en.json +6 -0
  20. package/locale/zh.json +6 -0
  21. package/package.json +73 -4
  22. package/playwright.config.mjs +6 -0
  23. package/scripts/benchmark-runtime.mjs +227 -0
  24. package/scripts/benchmark-storage.mjs +104 -0
  25. package/scripts/check-package.mjs +46 -0
  26. package/scripts/verify-desktop.mjs +200 -0
  27. package/scripts/verify-lifecycle.cjs +75 -0
  28. package/scripts/verify-web.mjs +170 -0
  29. package/test/browser/edit-identity.spec.mjs +343 -0
  30. package/test/browser/interactions.spec.mjs +690 -0
  31. package/test/browser/server.mjs +123 -0
  32. package/test/browser/shell.html +33 -0
  33. package/test/client-lifecycle.mjs +515 -0
  34. package/test/client.mjs +878 -0
  35. package/test/copy.mjs +47 -0
  36. package/test/css.mjs +63 -0
  37. package/test/desktop-services.mjs +91 -0
  38. package/test/detect.mjs +164 -0
  39. package/test/draft-config.mjs +38 -0
  40. package/test/harness.mjs +136 -0
  41. package/test/legacy-config.mjs +106 -0
  42. package/test/lifecycle.mjs +81 -0
  43. package/test/migration.mjs +127 -0
  44. package/test/mock-dsh.mjs +399 -0
  45. package/test/package-meta.mjs +49 -0
  46. package/test/pagination.mjs +21 -0
  47. package/test/provider-contracts.mjs +145 -0
  48. package/test/quota-history.mjs +191 -0
  49. package/test/reset-times.mjs +68 -0
  50. package/test/route-consistency.mjs +45 -0
  51. package/test/runtime.mjs +389 -0
  52. package/test/scan-coordinator.mjs +353 -0
  53. package/test/scheduler.mjs +98 -0
  54. package/test/season.mjs +173 -0
  55. package/test/smoke.mjs +264 -0
  56. package/test/storage-recovery.mjs +81 -0
  57. package/test/storage.mjs +377 -0
  58. package/test/usage-saves.mjs +107 -0
  59. package/test/usage.mjs +119 -0
  60. package/ui-prototype.html +509 -0
@@ -0,0 +1,1203 @@
1
+ // lib/providers.js — 数据层(供应商注册表,元数据驱动)
2
+ //
3
+ // 移植自 Token-Consumption-Monitoring(Gitea lqy/Token-Consumption-Monitoring)main
4
+ // 「统一查询方法」架构下 docs/query-coverage.md(1.3.x)的官方查询覆盖,只保留纯 HTTP
5
+ // 方法;Windows 专属方法(WebView2 控制台、本地 SQLite、本机 Codex CLI 登录)按规格丢弃。
6
+ //
7
+ // 供应商按「凭据类别 × 地域」拆分(与上游「一个页面保存一种凭据」对应):
8
+ // - api-key(普通 Key,可从 DSH harness 密钥自动识别)
9
+ // deepseek DeepSeek 余额(多币种,严格官方地址校验)
10
+ // moonshot-cn Moonshot 国内余额 api.moonshot.cn(CNY)
11
+ // moonshot-intl Moonshot 国际余额 api.moonshot.ai(USD)
12
+ // zai Z.ai Coding Plan api.z.ai(Authorization 原样;窗口按 unit 分类)
13
+ // zai-cn 智谱 Coding Plan open.bigmodel.cn(CN;同一实现)
14
+ // minimax MiniMax Token Plan www.minimax.io(国际)
15
+ // minimax-cn MiniMax Token Plan www.minimaxi.com(CN)
16
+ // openrouter OpenRouter 普通 Key:周期额度 + 今日报告费用
17
+ // - management-key(Management Key,DSH 无此类接缝 → 手动配置)
18
+ // openrouter-account OpenRouter 账户 credits
19
+ // - admin-key(Admin Key,DSH 无此类接缝 → 手动配置)
20
+ // openai-org OpenAI 组织用量/费用(最近完整 UTC 日,分页)
21
+ // anthropic-org Anthropic 组织用量/费用(x-api-key + anthropic-version)
22
+ // - 私有兼容来源(继续支持,标记 compat;上游列为有条件/私有路径)
23
+ // opencode OpenCode Go 5h/周/月窗口 + allowance
24
+ // commandcode Command Code 5h/周窗口 + 套餐月额度
25
+ //
26
+ // 每个 query(cfg) 返回归一化结构:
27
+ // { state: 'ok'|'warn'|'crit'|'err'|'off', error?: {code, message},
28
+ // entries: [{name, kind:'win'|'bal'|'usage'|'cost', limit, used, remain, pct, reset, note}],
29
+ // headline: {kind:'pct'|'amt', pct?, amt?, reset} }
30
+ //
31
+ // 安全与解析边界(对齐上游 docs/query-coverage.md「数据与安全边界」):
32
+ // - 官方方法只接受对应 HTTPS 主机 + 已知基础路径,拒绝端口/用户信息/查询参数/重定向;
33
+ // 地址不匹配时不发送请求。
34
+ // - 缺字段/越界桶/重复游标/业务错误不转成零值;分页失败不发布已累计的部分总数。
35
+ // - 无限额度/未知余额保留为未知(null),不冒充 0。
36
+
37
+ import { AsyncLocalStorage } from "node:async_hooks";
38
+ const queryContext = new AsyncLocalStorage();
39
+ const REQUEST_TIMEOUT_MS = 20_000;
40
+ const MAX_PAGES = 100;
41
+
42
+ // ---------- 通用工具 ----------
43
+
44
+ /** 规约 URL 为 https://host(忽略路径),仅用于「兼容来源」的 baseUrl 收敛。 */
45
+ function deriveServer(baseUrl, fallback) {
46
+ try {
47
+ const url = new URL(baseUrl);
48
+ if (url.host) return `${url.protocol}//${url.host}`;
49
+ } catch {
50
+ /* 忽略 */
51
+ }
52
+ return fallback;
53
+ }
54
+
55
+ /** 把 fetch 错误归一化为带 code 的 Error;code ∈ auth|schema|network|http:N。 */
56
+ async function httpJson(url, { auth = "bearer", key = "", extraHeaders = {}, timeoutMs = REQUEST_TIMEOUT_MS } = {}) {
57
+ const controller = new AbortController();
58
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
59
+ const headers = { ...extraHeaders };
60
+ if (key && auth === "bearer") headers.authorization = `Bearer ${key}`;
61
+ else if (key && auth === "x-api-key") {
62
+ headers["x-api-key"] = key;
63
+ headers["anthropic-version"] = headers["anthropic-version"] || "2023-06-01";
64
+ } else if (key && auth === "raw") headers.authorization = key; // Z.ai:第一方插件 Authorization 原样不带 Bearer
65
+ try {
66
+ const response = await fetch(url, {
67
+ signal: queryContext.getStore()
68
+ ? AbortSignal.any([controller.signal, queryContext.getStore()]) : controller.signal,
69
+ headers,
70
+ redirect: "error", // 拒绝重定向(官方查询安全边界)
71
+ });
72
+ const text = await response.text();
73
+ if (!response.ok) {
74
+ const err = new Error(`HTTP ${response.status}`);
75
+ if (response.status === 401 || response.status === 403) err.code = "auth";
76
+ else err.code = `http:${response.status}`;
77
+ throw err;
78
+ }
79
+ return text ? JSON.parse(text) : null;
80
+ } catch (error) {
81
+ if (error.name === "AbortError" || error.name === "TimeoutError") {
82
+ const err = new Error("请求超时");
83
+ err.code = "network";
84
+ throw err;
85
+ }
86
+ if (error.code) throw error;
87
+ if (error.name === "TypeError") {
88
+ // fetch redirect:'error' 与纯网络错误都可能落到 TypeError
89
+ const err = new Error("网络错误或重定向被拒绝");
90
+ err.code = "network";
91
+ throw err;
92
+ }
93
+ if (error instanceof SyntaxError) {
94
+ const err = new Error("响应不是有效 JSON");
95
+ err.code = "schema";
96
+ throw err;
97
+ }
98
+ const err = new Error(error.message || "网络错误");
99
+ err.code = "network";
100
+ throw err;
101
+ } finally {
102
+ clearTimeout(timer);
103
+ }
104
+ }
105
+
106
+ /** 校验官方端点:https + 默认端口 + 无 userinfo/query/hash + 主机与基础路径白名单。 */
107
+ function officialEndpoint(baseUrl, { hosts, basePaths, defaultBase }) {
108
+ const fallback = { origin: null, error: { code: "endpoint", message: `Base URL 需为官方 HTTPS 地址(${hosts.join(" / ")})` } };
109
+ try {
110
+ // 未配置 baseUrl 时使用供应商官方默认地址(注册表默认);显式配置的越界地址仍被拒绝
111
+ const url = new URL(String((baseUrl || "").trim() || defaultBase));
112
+ const host = url.hostname.toLowerCase();
113
+ const isHttps = url.protocol === "https:";
114
+ const defaultPort = !url.port || (url.protocol === "https:" && url.port === "443");
115
+ if (!isHttps || !defaultPort) return fallback;
116
+ if (url.username || url.password || url.search || url.hash) return fallback;
117
+ if (!hosts.includes(host)) return fallback;
118
+ const basePath = url.pathname === "/" ? "" : url.pathname.replace(/\/+$/, "");
119
+ if (!basePaths.includes(basePath)) return fallback;
120
+ return { origin: url.origin, error: null };
121
+ } catch {
122
+ return fallback;
123
+ }
124
+ }
125
+
126
+ // ---------- 官方地址策略(唯一事实来源)----------
127
+ // 查询函数与自动探测校验必须引用同一份主机/基础路径策略:任何一方单独改动都会让
128
+ // 「探测可采纳的地址」与「查询可使用的地址」出现分歧。这里在注册表构造之前完成初始化,
129
+ // 避免依赖注册表求值顺序(历史上策略表放在文件末尾,靠 PROVIDERS 已求值才没出问题)。
130
+ const DEEPSEEK = { hosts: ["api.deepseek.com"], basePaths: ["", "/v1"] };
131
+ const ZAI_BASE_PATHS = ["", "/api/anthropic", "/api/paas/v4", "/api/coding/paas/v4"];
132
+ const OPENROUTER = { hosts: ["openrouter.ai"], basePaths: ["", "/api", "/api/v1"] };
133
+
134
+ /** 各官方供应商允许的主机与基础路径(无该键 = 私有兼容来源,不做官方地址约束)。 */
135
+ export const OFFICIAL_ENDPOINTS = {
136
+ deepseek: DEEPSEEK,
137
+ "moonshot-cn": { hosts: ["api.moonshot.cn"], basePaths: ["", "/v1"] },
138
+ "moonshot-intl": { hosts: ["api.moonshot.ai"], basePaths: ["", "/v1"] },
139
+ zai: { hosts: ["api.z.ai"], basePaths: ZAI_BASE_PATHS },
140
+ "zai-cn": { hosts: ["open.bigmodel.cn"], basePaths: ZAI_BASE_PATHS },
141
+ minimax: { hosts: ["www.minimax.io"], basePaths: ["", "/v1"] },
142
+ "minimax-cn": { hosts: ["www.minimaxi.com"], basePaths: ["", "/v1"] },
143
+ openrouter: OPENROUTER,
144
+ "openrouter-account": OPENROUTER,
145
+ "openai-org": { hosts: ["api.openai.com"], basePaths: ["", "/v1"] },
146
+ "anthropic-org": { hosts: ["api.anthropic.com"], basePaths: ["", "/v1"] },
147
+ };
148
+
149
+ /** 各官方供应商允许的主机(无该键 = 私有兼容来源,不做官方地址约束)。 */
150
+ export const OFFICIAL_HOSTS = Object.fromEntries(
151
+ Object.entries(OFFICIAL_ENDPOINTS).map(([id, spec]) => [id, spec.hosts]),
152
+ );
153
+
154
+ /** DSH 路由带进来的 baseURL 是否可直接作为该供应商的官方查询地址。 */
155
+ export function isOfficialBaseUrl(supplierId, baseUrl) {
156
+ const spec = OFFICIAL_ENDPOINTS[supplierId];
157
+ if (!spec) return false;
158
+ const { error } = officialEndpoint(baseUrl, spec);
159
+ return !error;
160
+ }
161
+
162
+ function parseNumber(value) {
163
+ if (typeof value === "number") return Number.isFinite(value) ? value : null;
164
+ if (typeof value === "string" && value.trim() !== "") {
165
+ const n = Number(value);
166
+ return Number.isFinite(n) ? n : null;
167
+ }
168
+ return null;
169
+ }
170
+
171
+ // 查询中的数字日期字段按 epoch-毫秒契约解析。2001-09 之前的值属于占位或错误单位,
172
+ // 不得作为当前服务的配额窗口时刻;不会猜测为秒数或推算重置日期。
173
+ const MIN_RESET_EPOCH_MS = 1e12;
174
+
175
+ function parseDate(value) {
176
+ let date;
177
+ if (value instanceof Date) date = value;
178
+ else if (typeof value === "number") date = new Date(value);
179
+ else if (typeof value === "string" && value.trim() !== "") {
180
+ const text = value.trim();
181
+ // 数字串也必须按毫秒处理,避免 Date("0") 被解释成 2000 年 1 月。
182
+ const numeric = Number(text);
183
+ date = new Date(Number.isFinite(numeric) ? numeric : text);
184
+ } else return null;
185
+ const ms = date.getTime();
186
+ return Number.isFinite(ms) && ms >= MIN_RESET_EPOCH_MS ? date : null;
187
+ }
188
+
189
+ function parseEpochMs(value) {
190
+ const n = parseNumber(value);
191
+ if (n === null) return null;
192
+ return parseDate(n);
193
+ }
194
+
195
+ /** 依据 pct(已用百分比)与阈值归并条目,得出供应商状态。 */
196
+ function stateFromPct(pct, warnPct, critPct) {
197
+ if (pct === null || pct === undefined) return "ok";
198
+ if (pct >= critPct) return "crit";
199
+ if (pct >= warnPct) return "warn";
200
+ return "ok";
201
+ }
202
+
203
+ /** 重置时间人话化:「约 X 小时后重置」/「M月D日 重置」。 */
204
+ export function formatReset(resetsAt) {
205
+ const target = parseDate(resetsAt);
206
+ if (!target) return "—";
207
+ const diffMs = target.getTime() - Date.now();
208
+ if (diffMs > 0 && diffMs < 48 * 3600 * 1000) {
209
+ const hours = Math.max(1, Math.round(diffMs / 3600_000));
210
+ return `约 ${hours} 小时后重置`;
211
+ }
212
+ return `${target.getMonth() + 1}月${target.getDate()}日 重置`;
213
+ }
214
+
215
+ /**
216
+ * 重置时刻的原始 epoch-毫秒(无时刻返回 null)。
217
+ *
218
+ * 与 formatReset 并存:formatReset 把「还有多久」四舍五入成整小时后塞进文案(最多 ±30 分钟误差),
219
+ * 客户端要显示精确倒计时(如 2h13m / 1d19h)就必须拿到原始时刻自己算。
220
+ * 只在供应商**确实给出**时刻时返回非空——绝不为了排版推算一个时刻出来。
221
+ */
222
+ export function resetAtMs(resetsAt) {
223
+ return parseDate(resetsAt)?.getTime() ?? null;
224
+ }
225
+
226
+ /** 金额格式化:两位小数 + 千分位。 */
227
+ export function formatMoney(value, currency = "") {
228
+ if (value === null || value === undefined) return "—";
229
+ const n = Number(value);
230
+ if (!Number.isFinite(n)) return "—";
231
+ const formatted = n.toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 });
232
+ return currency && currency !== "USD" && currency !== "CNY"
233
+ ? `${formatted} ${currency}`
234
+ : `${currencySymbol(currency)}${formatted}`;
235
+ }
236
+
237
+ function currencySymbol(currency) {
238
+ if (currency === "USD") return "$";
239
+ if (currency === "CNY") return "¥";
240
+ return "";
241
+ }
242
+
243
+ const SYMBOLS = [
244
+ { value: 1, symbol: "" },
245
+ { value: 1e3, symbol: "K" },
246
+ { value: 1e6, symbol: "M" },
247
+ { value: 1e9, symbol: "B" },
248
+ ];
249
+
250
+ /** 大数缩写(≥10 万用 K/M 缩写;级内千分位)。 */
251
+ export function formatBig(value, unit = "") {
252
+ const n = Number(value);
253
+ if (!Number.isFinite(n)) return "—";
254
+ const abs = Math.abs(n);
255
+ let scale = SYMBOLS[0];
256
+ for (const s of SYMBOLS) {
257
+ if (abs >= s.value) scale = s;
258
+ }
259
+ if (scale.value === 1) return `${Math.round(n).toLocaleString()}${unit && ` ${unit}`}`;
260
+ return `${(n / scale.value).toLocaleString(undefined, { maximumFractionDigits: 1 })}${scale.symbol}${unit && ` ${unit}`}`;
261
+ }
262
+
263
+ /** Token/请求数友好文本。 */
264
+ const tokensText = (n) => (n === null || n === undefined ? "—" : `${formatBig(n)}`);
265
+
266
+ function makePctHeadline(tightest, entries) {
267
+ if (tightest === null) {
268
+ const bal = entries.find((e) => e.kind === "bal");
269
+ if (bal) return { kind: "amt", amt: bal.remain, reset: bal.reset, resetAt: bal.resetAt ?? null };
270
+ const usage = entries.find((e) => e.kind === "usage" || e.kind === "cost");
271
+ if (usage) return { kind: "amt", amt: usage.used, reset: usage.reset, resetAt: usage.resetAt ?? null };
272
+ return { kind: "pct", pct: null, amt: "—", reset: "—", resetAt: null };
273
+ }
274
+ const tight = entries.find((e) => e.pct === tightest) || entries[0];
275
+ return { kind: "pct", pct: `${tightest}%`, amt: `余 ${tight.pct === null || tight.kind === "bal" ? tight.remain : `${100 - tightest}%`}`, reset: tight.reset, resetAt: tight.resetAt ?? null };
276
+ }
277
+
278
+ function offResult(message = "未配置 API Key") {
279
+ return { state: "off", error: { code: "auth", message }, entries: [], headline: { kind: "amt", amt: "未配置" } };
280
+ }
281
+
282
+ function errResult(code, message) {
283
+ return { state: "err", error: { code, message }, entries: [], headline: { kind: "amt", amt: "—" } };
284
+ }
285
+
286
+ function wrapQuery(fn, missingKey = () => false) {
287
+ return async (cfg) => {
288
+ try {
289
+ if (missingKey(cfg)) return offResult("未配置所需密钥");
290
+ return await fn(cfg);
291
+ } catch (error) {
292
+ return errResult(error.code || "network", error.message || "网络错误");
293
+ }
294
+ };
295
+ }
296
+
297
+ // ---------- DeepSeek:余额(严格官方地址 + 多币种) ----------
298
+
299
+ const queryDeepSeek = wrapQuery(async (cfg) => {
300
+ const { origin, error } = officialEndpoint(cfg.baseUrl, { ...DEEPSEEK, defaultBase: "https://api.deepseek.com" });
301
+ if (error) return errResult(error.code, error.message);
302
+ const body = await httpJson(`${origin}/user/balance`, { auth: "bearer", key: cfg.apiKey });
303
+ const infos = Array.isArray(body?.balance_infos) ? body.balance_infos : [];
304
+ if (!infos.length) return errResult("schema", "余额接口未返回数据");
305
+ const entries = [];
306
+ const currencyToAmount = new Map(); // 多币种并存,保留全部币种
307
+ for (const info of infos) {
308
+ const balance = parseNumber(info?.total_balance);
309
+ const currency = info?.currency || "CNY";
310
+ if (balance === null) continue;
311
+ const note = [];
312
+ const topped = parseNumber(info.topped_up_balance);
313
+ const granted = parseNumber(info.granted_balance);
314
+ if (topped !== null) note.push(`到账 ${formatMoney(topped, currency)}`);
315
+ if (granted !== null) note.push(`赠送 ${formatMoney(granted, currency)}`);
316
+ entries.push({
317
+ name: `余额 · ${currency}`,
318
+ kind: "bal",
319
+ limit: "—",
320
+ used: "—",
321
+ remain: formatMoney(balance, currency),
322
+ pct: null,
323
+ reset: "—",
324
+ note: note.join(" · "),
325
+ });
326
+ if (!currencyToAmount.has(currency)) currencyToAmount.set(currency, balance);
327
+ }
328
+ if (!entries.length) return errResult("schema", "余额接口未返回可用数据");
329
+ const headlineAmt = [...currencyToAmount.entries()].map(([c, v]) => formatMoney(v, c)).join(" · ");
330
+ return { state: "ok", entries, headline: { kind: "amt", amt: headlineAmt, reset: "—" } };
331
+ }, (cfg) => !cfg.apiKey);
332
+
333
+ // ---------- OpenRouter:普通 Key 周期额度 + 今日费用 ----------
334
+ // (主机/基础路径策略见文件开头的 OFFICIAL_ENDPOINTS)
335
+
336
+ const OPENROUTER_PERIOD = { daily: "每日重置", weekly: "每周重置", monthly: "每月重置", null: "无周期重置" };
337
+
338
+ const queryOpenRouter = wrapQuery(async (cfg) => {
339
+ const { origin, error } = officialEndpoint(cfg.baseUrl, { ...OPENROUTER, defaultBase: "https://openrouter.ai/api/v1" });
340
+ if (error) return errResult(error.code, error.message);
341
+ const body = await httpJson(`${origin}/api/v1/key`, { key: cfg.apiKey });
342
+ const data = body?.data;
343
+ if (!data || typeof data !== "object") return errResult("schema", "OpenRouter 响应缺少 data");
344
+ const entries = [];
345
+ let tightest = null;
346
+ // 周期额度:无限额度(limit/remaining 均缺省)是合法状态,保留未知不冒充 0。
347
+ const limit = parseNumber(data.limit);
348
+ const remaining = parseNumber(data.limit_remaining);
349
+ if (limit !== null || remaining !== null) {
350
+ if (limit !== null && limit < 0) return errResult("schema", "OpenRouter 额度上限无效");
351
+ const period = OPENROUTER_PERIOD[data.limit_reset] ?? "服务方定义的周期";
352
+ const used = limit !== null && remaining !== null ? Math.max(0, limit - remaining) : null;
353
+ const pct = limit !== null && remaining !== null && limit > 0
354
+ ? Math.min(100, Math.round((used / limit) * 100))
355
+ : null;
356
+ entries.push({
357
+ name: `周期额度 · ${period}`,
358
+ key: "credit.period",
359
+ short: "额度",
360
+ kind: "bal",
361
+ limit: limit === null ? "无限" : formatMoney(limit, "USD"),
362
+ used: used === null ? "—" : formatMoney(used, "USD"),
363
+ remain: remaining === null ? "—" : formatMoney(remaining, "USD"),
364
+ pct,
365
+ reset: "—",
366
+ note: limit === null ? "公开契约允许无限额度" : "",
367
+ });
368
+ if (pct !== null && (tightest === null || pct > tightest)) tightest = pct;
369
+ }
370
+ // 今日报告费用(usage_daily):不把终身 usage 配到月额度。
371
+ const daily = parseNumber(data.usage_daily);
372
+ if (daily !== null) {
373
+ entries.push({
374
+ name: "今日费用",
375
+ kind: "cost",
376
+ limit: "—",
377
+ used: formatMoney(daily, "USD"),
378
+ remain: "—",
379
+ pct: null,
380
+ reset: "—",
381
+ note: "当前 Key · UTC 今日报告费用",
382
+ });
383
+ }
384
+ if (!entries.length) return errResult("no-data", "OpenRouter 未报告额度与今日费用");
385
+ return { state: stateFromPct(tightest, cfg.warnPct, cfg.critPct), entries, headline: makePctHeadline(tightest, entries) };
386
+ }, (cfg) => !cfg.apiKey);
387
+
388
+ // ---------- OpenRouter:Management Key 账户 credits ----------
389
+
390
+ const queryOpenRouterAccount = wrapQuery(async (cfg) => {
391
+ const { origin, error } = officialEndpoint(cfg.baseUrl, { ...OPENROUTER, defaultBase: "https://openrouter.ai/api/v1" });
392
+ if (error) return errResult(error.code, error.message);
393
+ const body = await httpJson(`${origin}/api/v1/credits`, { key: cfg.apiKey });
394
+ const data = body?.data;
395
+ if (!data || typeof data !== "object") return errResult("schema", "OpenRouter credits 响应缺少 data");
396
+ const credits = parseNumber(data.total_credits);
397
+ const used = parseNumber(data.total_usage);
398
+ if (credits === null || used === null) return errResult("schema", "OpenRouter credits 缺少数值字段");
399
+ const remain = credits - used;
400
+ return {
401
+ state: "ok",
402
+ entries: [{ name: "账户 credits", kind: "bal", limit: "—", used: "—", remain: formatMoney(remain, "USD"), pct: null, reset: "—", note: "管理密钥 · total_credits − total_usage" }],
403
+ headline: { kind: "amt", amt: formatMoney(remain, "USD"), reset: "—" },
404
+ };
405
+ }, (cfg) => !cfg.apiKey);
406
+
407
+ // ---------- Moonshot 国内 / 国际:余额 ----------
408
+
409
+ function moonshotQuery(host, currency) {
410
+ return wrapQuery(async (cfg) => {
411
+ const { origin, error } = officialEndpoint(cfg.baseUrl, { hosts: [host], basePaths: ["", "/v1"], defaultBase: `https://${host}/v1` });
412
+ if (error) return errResult(error.code, error.message);
413
+ const body = await httpJson(`${origin}/v1/users/me/balance`, { key: cfg.apiKey });
414
+ if (parseNumber(body?.code) !== 0 || body?.status !== true) return errResult("schema", "Moonshot 余额业务响应未成功");
415
+ const available = parseNumber(body?.data?.available_balance);
416
+ if (available === null) return errResult("schema", "Moonshot 响应缺少 available_balance");
417
+ return {
418
+ state: "ok",
419
+ entries: [{ name: "可用余额", kind: "bal", limit: "—", used: "—", remain: formatMoney(available, currency), pct: null, reset: "—", note: "" }],
420
+ headline: { kind: "amt", amt: formatMoney(available, currency), reset: "—" },
421
+ };
422
+ }, (cfg) => !cfg.apiKey);
423
+ }
424
+
425
+ // ---------- Z.ai / 智谱:Coding Plan 窗口(Authorization 原样,无 Bearer) ----------
426
+
427
+ // 供应商已把用量桶的类型名从 TOKENS_LIMIT 改名为 CREDIT_LIMIT(同一批窗口,仅换拼写):
428
+ // 滚动发布期可能一行一个拼写,两种都要读,且不得互相当成陌生态。
429
+ // 窗口身份只由 unit 判定,不看数组位置——供应商可以重排 limits 或插入新桶,
430
+ // 按位置取值会把周窗口的百分比挂到 5 小时窗口的标签下。
431
+ // unit 3 = 5 小时窗口;unit 6 = 周窗口;unit 未知的桶丢弃(不外推到别的标签下)。
432
+ // TIME_LIMIT 仍是月度 MCP 工具上限。时限本身取供应商公布的 number/unit,不在本地换算。
433
+ const ZAI_UNIT_LABELS = new Map([
434
+ [3, { label: "Token 用量(5 小时)", key: "window.5h", short: "5h" }],
435
+ [6, { label: "Token 用量(周)", key: "window.weekly", short: "周" }],
436
+ ]);
437
+ /** 用量桶的两种拼写(旧名 / 改名后)。 */
438
+ const ZAI_USAGE_TYPES = new Set(["TOKENS_LIMIT", "CREDIT_LIMIT"]);
439
+
440
+ function zaiQuery(host) {
441
+ return wrapQuery(async (cfg) => {
442
+ const { origin, error } = officialEndpoint(cfg.baseUrl, { hosts: [host], basePaths: ZAI_BASE_PATHS, defaultBase: `https://${host}/api/anthropic` });
443
+ if (error) return errResult(error.code, error.message);
444
+ const body = await httpJson(`${origin}/api/monitor/usage/quota/limit`, {
445
+ auth: "raw",
446
+ key: cfg.apiKey,
447
+ extraHeaders: { "accept-language": "en-US,en" },
448
+ });
449
+ // 业务失败藏在 HTTP 200 的响应体里(success:false + 非 200 code,如 401「token expired」)。
450
+ // 只看 HTTP 状态码会把密钥失效报成解析失败,必须按信封判定,并把鉴权失败归到 auth。
451
+ const code = parseNumber(body?.code);
452
+ if (body?.success === false || (code !== null && code !== 0 && code !== 200)) {
453
+ const message = String(body?.msg ?? "").trim() || "未提供失败原因";
454
+ return errResult(code === 401 || code === 403 ? "auth" : "schema",
455
+ `Coding Plan 业务响应未成功(code ${code ?? "—"}):${message}`);
456
+ }
457
+ const rows = body?.data?.limits;
458
+ if (!Array.isArray(rows)) return errResult("schema", "Coding Plan 响应缺少 data.limits");
459
+
460
+ const buckets = new Map(); // unit → 行;已按 unit 去重
461
+ let usageRows = 0;
462
+ let mcp = null;
463
+ for (const row of rows) {
464
+ const type = typeof row?.type === "string" ? row.type : "";
465
+ if (type === "TIME_LIMIT") {
466
+ if (mcp) return errResult("schema", "配额响应包含重复的 TIME_LIMIT 窗口");
467
+ mcp = row;
468
+ continue;
469
+ }
470
+ if (!ZAI_USAGE_TYPES.has(type)) continue;
471
+ usageRows += 1;
472
+ const unit = parseNumber(row?.unit);
473
+ if (unit === null || !ZAI_UNIT_LABELS.has(unit)) continue; // 无标识/未知窗口 → 不猜、不上标签
474
+ if (buckets.has(unit)) return errResult("schema", `配额响应包含重复的窗口 unit ${unit}`);
475
+ buckets.set(unit, row);
476
+ }
477
+ // 有用量桶却一个都认不出来 = 供应商再次改版,不能退化成「没有窗口」的假象
478
+ if (usageRows && !buckets.size) {
479
+ return errResult("schema", "配额响应无法按 unit 区分 Coding Plan 窗口(供应商已改版)");
480
+ }
481
+
482
+ // 展示顺序固定:5 小时 → 周 → MCP,与数组位置无关
483
+ const windows = [...ZAI_UNIT_LABELS.keys()].filter((unit) => buckets.has(unit))
484
+ .map((unit) => ({ ...ZAI_UNIT_LABELS.get(unit), row: buckets.get(unit) }));
485
+ if (mcp) windows.push({ label: "MCP 用量(月)", key: "window.monthly", short: "月", row: mcp });
486
+
487
+ const entries = [];
488
+ let tightest = null;
489
+ for (const { label: name, key, short, row } of windows) {
490
+ const percent = parseNumber(row?.percentage);
491
+ if (percent === null) return errResult("schema", `Coding Plan「${name}」未提供百分比`);
492
+ if (percent < 0 || percent > 100) return errResult("schema", `Coding Plan「${name}」百分比超出已支持范围`);
493
+ // 取整后再比较:headline 的 pct 必须与某个条目的 pct 相等,否则 headline 会指向另一个窗口
494
+ const pct = Math.round(percent);
495
+ const resetAt = row?.nextResetTime ?? null;
496
+ entries.push({
497
+ name, key, short, kind: "win", limit: "—",
498
+ used: `${pct}%`, remain: `${Math.max(0, 100 - pct)}%`, pct,
499
+ reset: formatReset(resetAt), resetAt: resetAtMs(resetAt),
500
+ note: "官方插件字段",
501
+ });
502
+ if (tightest === null || pct > tightest) tightest = pct;
503
+ }
504
+ if (!entries.length) return errResult("no-data", "未解析到已公开的 Coding Plan 窗口");
505
+ return { state: stateFromPct(tightest, cfg.warnPct, cfg.critPct), entries, headline: makePctHeadline(tightest, entries) };
506
+ }, (cfg) => !cfg.apiKey);
507
+ }
508
+
509
+ // ---------- MiniMax:Token Plan 窗口(显式剩余百分比,不猜旧计数) ----------
510
+
511
+ function minimaxQuery(host) {
512
+ return wrapQuery(async (cfg) => {
513
+ const { origin, error } = officialEndpoint(cfg.baseUrl, { hosts: [host], basePaths: ["", "/v1"], defaultBase: `https://${host}` });
514
+ if (error) return errResult(error.code, error.message);
515
+ const body = await httpJson(`${origin}/v1/token_plan/remains`, { key: cfg.apiKey });
516
+ if (parseNumber(body?.base_resp?.status_code) !== 0) return errResult("schema", "MiniMax 套餐查询业务响应未成功");
517
+ const rows = body?.model_remains;
518
+ if (!Array.isArray(rows)) return errResult("schema", "MiniMax 响应缺少 model_remains");
519
+ const seen = new Set();
520
+ const entries = [];
521
+ let tightest = null;
522
+ let ambiguous = false;
523
+ const addWindow = (row, model, weekly) => {
524
+ const prefix = weekly ? "current_weekly" : "current_interval";
525
+ if (parseNumber(row[`${prefix}_status`]) === 3) return;
526
+ const remaining = parseNumber(row[`${prefix}_remaining_percent`]);
527
+ if (remaining === null) { ambiguous = true; return; }
528
+ if (remaining < 0 || remaining > 100) throw Object.assign(new Error("MiniMax 原始剩余百分比超出已支持范围"), { code: "schema" });
529
+ const start = parseEpochMs(row[weekly ? "weekly_start_time" : "start_time"]);
530
+ const end = parseEpochMs(row[weekly ? "weekly_end_time" : "end_time"]);
531
+ if (!start || !end || end.getTime() <= start.getTime()) throw Object.assign(new Error("MiniMax 返回无效的配额窗口"), { code: "schema" });
532
+ const usedPct = Math.round(100 - remaining);
533
+ const boost = weekly ? parseNumber(row.weekly_boost_permille) : null;
534
+ const note = boost !== null && boost > 0 && boost !== 1000
535
+ ? `按当前分配额度显示;周加成 ${(boost / 1000).toLocaleString(undefined, { maximumFractionDigits: 3 })}×`
536
+ : "按当前分配额度显示";
537
+ entries.push({
538
+ name: `${model} · ${weekly ? "周窗口" : "当前窗口"}`,
539
+ // key 含模型名:同一账号可能返回多个模型的窗口,槽位不能共用
540
+ key: `window.${model}.${weekly ? "weekly" : "interval"}`,
541
+ short: weekly ? "周" : "窗口",
542
+ kind: "win",
543
+ limit: "—",
544
+ used: `${usedPct}%`,
545
+ remain: `${Math.round(remaining)}%`,
546
+ pct: usedPct,
547
+ reset: formatReset(end),
548
+ resetAt: resetAtMs(end),
549
+ note,
550
+ });
551
+ if (tightest === null || usedPct > tightest) tightest = usedPct;
552
+ };
553
+ for (const row of rows) {
554
+ const model = typeof row?.model_name === "string" && row.model_name ? row.model_name : "";
555
+ if (!model) continue;
556
+ if (seen.has(model)) throw Object.assign(new Error("MiniMax 返回重复的模型配额"), { code: "schema" });
557
+ seen.add(model);
558
+ addWindow(row, model, false);
559
+ addWindow(row, model, true);
560
+ }
561
+ if (!entries.length) {
562
+ return errResult(ambiguous ? "schema" : "no-data", ambiguous
563
+ ? "MiniMax 未返回可确认的显式剩余百分比,未使用旧计数推算"
564
+ : "MiniMax 未返回可展示的窗口");
565
+ }
566
+ return { state: stateFromPct(tightest, cfg.warnPct, cfg.critPct), entries, headline: makePctHeadline(tightest, entries) };
567
+ }, (cfg) => !cfg.apiKey);
568
+ }
569
+
570
+ // ---------- OpenAI / Anthropic 组织:Admin Key 用量与费用(最近完整 UTC 日) ----------
571
+
572
+ /** 组织统计的通用日期:最近一个已完成的 UTC 日 [start, end)。 */
573
+ function orgDayRange(now = Date.now()) {
574
+ const end = new Date(now);
575
+ end.setUTCHours(0, 0, 0, 0);
576
+ const start = new Date(end.getTime() - 24 * 3600_000);
577
+ return { start, end };
578
+ }
579
+
580
+ function orgDateNote(label) {
581
+ return `${label} · UTC 昨日(最近已完成的 UTC 日)`;
582
+ }
583
+
584
+ const makeOpenAiOrgQuery = (kind) => wrapQuery(async (cfg) => {
585
+ const { origin, error } = officialEndpoint(cfg.baseUrl, { hosts: ["api.openai.com"], basePaths: ["", "/v1"], defaultBase: "https://api.openai.com" });
586
+ if (error) return errResult(error.code, error.message);
587
+ const { start, end } = orgDayRange();
588
+ const base = kind === "cost"
589
+ ? `${origin}/v1/organization/costs?start_time=${Math.floor(start.getTime() / 1000)}&end_time=${Math.floor(end.getTime() / 1000)}&bucket_width=1d&limit=1`
590
+ : `${origin}/v1/organization/usage/completions?start_time=${Math.floor(start.getTime() / 1000)}&end_time=${Math.floor(end.getTime() / 1000)}&bucket_width=1d&limit=1&group_by%5B%5D=model`;
591
+ const seenPages = new Set();
592
+ let next = null;
593
+ let hadRows = false;
594
+ const costs = new Map(); // currency -> amount
595
+ const models = new Map(); // model -> {tokens, input, output, requests}
596
+ let total = 0;
597
+ let requests = 0;
598
+ for (let page = 0; page < MAX_PAGES; page++) {
599
+ const path = base + (next === null ? "" : `&page=${encodeURIComponent(next)}`);
600
+ const body = await httpJson(path, { key: cfg.apiKey });
601
+ const buckets = Array.isArray(body?.data) ? body.data : [];
602
+ for (const bucket of buckets) {
603
+ const bucketStart = parseNumber(bucket?.start_time);
604
+ const bucketEnd = parseNumber(bucket?.end_time);
605
+ if (bucketStart === null || bucketEnd === null) throw Object.assign(new Error("组织统计时间桶字段缺失"), { code: "schema" });
606
+ if (bucketStart < Math.floor(start.getTime() / 1000) || bucketEnd > Math.floor(end.getTime() / 1000) || bucketEnd <= bucketStart) {
607
+ throw Object.assign(new Error("组织统计返回了请求范围以外的时间桶"), { code: "schema" });
608
+ }
609
+ const rows = Array.isArray(bucket?.results) ? bucket.results : [];
610
+ for (const row of rows) {
611
+ hadRows = true;
612
+ if (kind === "cost") {
613
+ const amount = row?.amount || {};
614
+ const value = parseNumber(amount.value);
615
+ const currency = String(amount.currency || "USD").toUpperCase();
616
+ if (value === null || !currency) throw Object.assign(new Error("组织费用字段缺失"), { code: "schema" });
617
+ costs.set(currency, (costs.get(currency) || 0) + value);
618
+ } else {
619
+ const input = parseNumber(row.input_tokens);
620
+ const output = parseNumber(row.output_tokens);
621
+ const cached = row.input_cached_tokens !== undefined && row.input_cached_tokens !== null ? parseNumber(row.input_cached_tokens) : 0;
622
+ const req = parseNumber(row.num_model_requests);
623
+ if (input === null || output === null || req === null) throw Object.assign(new Error("组织用量字段缺失"), { code: "schema" });
624
+ const tokens = input + output;
625
+ const model = typeof row.model === "string" && row.model ? row.model : "未分模型";
626
+ total += tokens;
627
+ requests += req;
628
+ const prev = models.get(model) || { tokens: 0, input: 0, output: 0, requests: 0 };
629
+ models.set(model, { tokens: prev.tokens + tokens, input: prev.input + input, output: prev.output + output, requests: prev.requests + req });
630
+ }
631
+ }
632
+ }
633
+ if (body?.has_more !== true) break;
634
+ next = typeof body?.next_page === "string" ? body.next_page : null;
635
+ if (!next || seenPages.has(next)) throw Object.assign(new Error("组织统计分页游标重复,未发布部分结果"), { code: "schema" });
636
+ seenPages.add(next);
637
+ if (page === MAX_PAGES - 1) throw Object.assign(new Error("组织统计超过分页上限,未发布部分结果"), { code: "schema" });
638
+ }
639
+ if (!hadRows) return errResult("no-data", "组织统计未返回数据");
640
+ if (kind === "cost") {
641
+ const entries = [...costs.entries()].map(([currency, amount]) => ({
642
+ name: `组织费用 · ${currency}`,
643
+ kind: "cost",
644
+ limit: "—",
645
+ used: formatMoney(amount, currency),
646
+ remain: "—",
647
+ pct: null,
648
+ reset: "—",
649
+ note: orgDateNote("组织报告费用") + "(账单可能延迟)",
650
+ }));
651
+ const headlineAmt = [...costs.entries()].map(([c, v]) => formatMoney(v, c)).join(" · ");
652
+ return { state: "ok", entries, headline: { kind: "amt", amt: headlineAmt, reset: "—" } };
653
+ }
654
+ const entries = [{
655
+ name: "组织 Token 用量(汇总)",
656
+ kind: "usage",
657
+ limit: "—",
658
+ used: tokensText(total),
659
+ remain: "—",
660
+ pct: null,
661
+ reset: "—",
662
+ note: `请求数 ${tokensText(requests)} · ${orgDateNote("Completions 用量接口,不覆盖全部产品计量")}`,
663
+ }];
664
+ for (const [model, m] of models) {
665
+ entries.push({
666
+ name: `模型 · ${model}`,
667
+ kind: "usage",
668
+ limit: "—",
669
+ used: tokensText(m.tokens),
670
+ remain: "—",
671
+ pct: null,
672
+ reset: "—",
673
+ note: `输入 ${tokensText(m.input)} · 输出 ${tokensText(m.output)} · 请求 ${tokensText(m.requests)}`,
674
+ });
675
+ }
676
+ return { state: "ok", entries, headline: { kind: "amt", amt: tokensText(total), reset: "—" } };
677
+ }, (cfg) => !cfg.apiKey);
678
+
679
+ /** OpenAI 组织用量与组织费用共用一把 Admin Key,分别实现两个注册项。 */
680
+ const queryOpenAiUsage = makeOpenAiOrgQuery("usage");
681
+ const queryOpenAiCost = makeOpenAiOrgQuery("cost");
682
+
683
+ const makeAnthropicOrgQuery = (kind) => wrapQuery(async (cfg) => {
684
+ const { origin, error } = officialEndpoint(cfg.baseUrl, { hosts: ["api.anthropic.com"], basePaths: ["", "/v1"], defaultBase: "https://api.anthropic.com" });
685
+ if (error) return errResult(error.code, error.message);
686
+ const { start, end } = orgDayRange();
687
+ const iso = (d) => d.toISOString();
688
+ const path = kind === "cost"
689
+ ? `${origin}/v1/organizations/cost_report?starting_at=${encodeURIComponent(iso(start))}&ending_at=${encodeURIComponent(iso(end))}&bucket_width=1d&limit=1`
690
+ : `${origin}/v1/organizations/usage_report/messages?starting_at=${encodeURIComponent(iso(start))}&ending_at=${encodeURIComponent(iso(end))}&bucket_width=1d&limit=1`;
691
+ const body = await httpJson(path, { auth: "x-api-key", key: cfg.apiKey });
692
+ if (body?.has_more === true) return errResult("schema", "组织统计尚有后续分页,未发布部分结果");
693
+ const buckets = Array.isArray(body?.data) ? body.data : [];
694
+ const seenStart = new Set();
695
+ let hadRows = false;
696
+ const costs = new Map();
697
+ const models = new Map();
698
+ let total = 0;
699
+ for (const bucket of buckets) {
700
+ const bucketStart = new Date(String(bucket?.starting_at || ""));
701
+ const bucketEnd = new Date(String(bucket?.ending_at || ""));
702
+ if (Number.isNaN(bucketStart.getTime()) || Number.isNaN(bucketEnd.getTime())) throw Object.assign(new Error("组织统计时间桶字段缺失"), { code: "schema" });
703
+ if (bucketStart < start || bucketEnd > end || bucketEnd <= bucketStart) throw Object.assign(new Error("组织统计返回了请求范围以外的时间桶"), { code: "schema" });
704
+ if (seenStart.has(bucketStart.toISOString())) throw Object.assign(new Error("组织统计返回重复时间桶"), { code: "schema" });
705
+ seenStart.add(bucketStart.toISOString());
706
+ const rows = Array.isArray(bucket?.results) ? bucket.results : [];
707
+ for (const row of rows) {
708
+ hadRows = true;
709
+ if (kind === "cost") {
710
+ const cents = parseNumber(row?.amount);
711
+ const currency = String(row?.currency || "USD").toUpperCase();
712
+ if (cents === null || !currency) throw Object.assign(new Error("组织费用字段缺失"), { code: "schema" });
713
+ costs.set(currency, (costs.get(currency) || 0) + cents / 100); // 美元美分 → USD
714
+ } else {
715
+ const uncached = parseNumber(row.uncached_input_tokens);
716
+ const cachedRead = parseNumber(row.cache_read_input_tokens);
717
+ const output = parseNumber(row.output_tokens);
718
+ const creation = row?.cache_creation || {};
719
+ const eph1h = parseNumber(creation.ephemeral_1h_input_tokens);
720
+ const eph5m = parseNumber(creation.ephemeral_5m_input_tokens);
721
+ if (uncached === null || cachedRead === null || output === null || eph1h === null || eph5m === null) {
722
+ throw Object.assign(new Error("组织用量字段缺失"), { code: "schema" });
723
+ }
724
+ const input = uncached + cachedRead + eph1h + eph5m;
725
+ const tokens = input + output;
726
+ const model = typeof row.model === "string" && row.model ? row.model : "未分模型";
727
+ total += tokens;
728
+ const prev = models.get(model) || { tokens: 0, input: 0, output: 0 };
729
+ models.set(model, { tokens: prev.tokens + tokens, input: prev.input + input, output: prev.output + output });
730
+ }
731
+ }
732
+ }
733
+ if (!hadRows) return errResult("no-data", "组织统计未返回数据");
734
+ if (kind === "cost") {
735
+ const entries = [...costs.entries()].map(([currency, amount]) => ({
736
+ name: `组织费用 · ${currency}`,
737
+ kind: "cost",
738
+ limit: "—",
739
+ used: formatMoney(amount, currency),
740
+ remain: "—",
741
+ pct: null,
742
+ reset: "—",
743
+ note: orgDateNote("组织报告费用") + "(报告美分按 1/100 转为美元)",
744
+ }));
745
+ const headlineAmt = [...costs.entries()].map(([c, v]) => formatMoney(v, c)).join(" · ");
746
+ return { state: "ok", entries, headline: { kind: "amt", amt: headlineAmt, reset: "—" } };
747
+ }
748
+ const entries = [{
749
+ name: "组织 Messages 用量(汇总)",
750
+ kind: "usage",
751
+ limit: "—",
752
+ used: tokensText(total),
753
+ remain: "—",
754
+ pct: null,
755
+ reset: "—",
756
+ note: orgDateNote("Messages 用量;未报告请求数保留未知"),
757
+ }];
758
+ for (const [model, m] of models) {
759
+ entries.push({
760
+ name: `模型 · ${model}`,
761
+ kind: "usage",
762
+ limit: "—",
763
+ used: tokensText(m.tokens),
764
+ remain: "—",
765
+ pct: null,
766
+ reset: "—",
767
+ note: `输入 ${tokensText(m.input)} · 输出 ${tokensText(m.output)}`,
768
+ });
769
+ }
770
+ return { state: "ok", entries, headline: { kind: "amt", amt: tokensText(total), reset: "—" } };
771
+ }, (cfg) => !cfg.apiKey);
772
+
773
+ const queryAnthropicUsage = makeAnthropicOrgQuery("usage");
774
+ const queryAnthropicCost = makeAnthropicOrgQuery("cost");
775
+
776
+ // ---------- OpenCode:窗口用量 + allowance(私有兼容来源,保留) ----------
777
+
778
+ async function queryOpenCode(cfg) {
779
+ const server = deriveServer(cfg.baseUrl || "", "https://opencode.ai");
780
+ const entries = [];
781
+ let tightest = null;
782
+ const warnings = [];
783
+
784
+ if (cfg.apiKey) {
785
+ try {
786
+ const body = await httpJson(`${server}/zen/go/v1/usage`, { key: cfg.apiKey });
787
+ const usage = body?.usage;
788
+ if (usage && typeof usage === "object") {
789
+ for (const [field, label, short] of [["rolling", "5h 滚动", "5h"], ["weekly", "周用量", "周"], ["monthly", "月用量", "月"]]) {
790
+ const w = usage[field];
791
+ if (!w || typeof w !== "object") continue;
792
+ const pct = parseNumber(w.percent);
793
+ const resetsAt = parseDate(w.resetsAt);
794
+ entries.push({
795
+ name: label,
796
+ key: `window.${field}`,
797
+ short,
798
+ kind: "win",
799
+ limit: "—",
800
+ used: pct === null ? "—" : `${pct}%`,
801
+ remain: pct === null ? "—" : `${Math.max(0, 100 - pct)}%`,
802
+ pct,
803
+ reset: formatReset(resetsAt),
804
+ resetAt: resetAtMs(resetsAt),
805
+ note: w.status || "",
806
+ });
807
+ if (pct !== null && (tightest === null || pct > tightest)) tightest = pct;
808
+ }
809
+ }
810
+ } catch (error) {
811
+ warnings.push(`窗口用量:${error.code}:${error.message}`);
812
+ }
813
+ }
814
+
815
+ if (cfg.allowanceToken) {
816
+ try {
817
+ const headers = {};
818
+ if (cfg.orgId) headers["x-org-id"] = String(cfg.orgId);
819
+ const body = await httpJson(`${server}/api/go/status`, { key: cfg.allowanceToken, extraHeaders: headers });
820
+ const meters = Array.isArray(body?.meters) ? body.meters : [];
821
+ for (const m of meters) {
822
+ const limitUsd = parseNumber(m.limitMicroCents) !== null ? parseNumber(m.limitMicroCents) / 1_000_000 : null;
823
+ const remainUsd = parseNumber(m.remainingMicroCents) !== null ? parseNumber(m.remainingMicroCents) / 1_000_000 : null;
824
+ const usedUsd = limitUsd !== null && remainUsd !== null ? Math.max(0, limitUsd - remainUsd) : null;
825
+ const pct = limitUsd > 0 && remainUsd !== null ? Math.round(((limitUsd - remainUsd) / limitUsd) * 100) : null;
826
+ const meterResetsAt = parseDate(m.resetsAt);
827
+ entries.push({
828
+ name: `allowance${m.kind ? ` · ${m.kind}` : ""}`,
829
+ key: `allowance.${m.kind || "auto"}`,
830
+ short: "额度",
831
+ kind: "bal",
832
+ limit: formatMoney(limitUsd, "USD"),
833
+ used: usedUsd === null ? "—" : formatMoney(usedUsd, "USD"),
834
+ remain: formatMoney(remainUsd, "USD"),
835
+ pct,
836
+ reset: formatReset(meterResetsAt),
837
+ resetAt: resetAtMs(meterResetsAt),
838
+ note: "",
839
+ });
840
+ if (pct !== null && (tightest === null || pct > tightest)) tightest = pct;
841
+ }
842
+ } catch (error) {
843
+ warnings.push(`allowance:${error.code}:${error.message}`);
844
+ }
845
+ }
846
+
847
+ if (!cfg.apiKey && !cfg.allowanceToken) {
848
+ return { state: "off", error: { code: "auth", message: "未配置 API Key / allowance Token" }, entries: [], headline: { kind: "pct", pct: null, amt: "未配置" } };
849
+ }
850
+ if (warnings.length) {
851
+ return {
852
+ state: "err",
853
+ error: { code: "partial", message: warnings.join(";") },
854
+ entries,
855
+ headline: makePctHeadline(tightest, entries),
856
+ };
857
+ }
858
+ if (!entries.length) return errResult("no-data", "OpenCode 未返回可识别的用量或额度");
859
+ return { state: stateFromPct(tightest, cfg.warnPct, cfg.critPct), entries, headline: makePctHeadline(tightest, entries) };
860
+ }
861
+
862
+ // ---------- Command Code:5h/周窗口 + 月额度(私有兼容来源,保留) ----------
863
+
864
+ const PLAN_MONTHLY_CREDITS = {
865
+ "individual-go": 10,
866
+ "individual-goat": 70,
867
+ "individual-pro": 30,
868
+ "individual-pro-v1": 80,
869
+ "individual-provider": 15,
870
+ "individual-max": 150,
871
+ "individual-ultra": 300,
872
+ "teams-pro": 40,
873
+ };
874
+
875
+ const PLAN_NAMES = {
876
+ "individual-go": "Go",
877
+ "individual-goat": "GOAT",
878
+ "individual-pro": "Pro",
879
+ "individual-pro-v1": "Pro",
880
+ "individual-provider": "Provider",
881
+ "individual-max": "Max",
882
+ "individual-ultra": "Ultra",
883
+ "teams-pro": "Teams Pro",
884
+ };
885
+
886
+ async function queryCommandCode(cfg) {
887
+ const baseUrl = deriveServer(cfg.baseUrl || "", "https://api.commandcode.ai");
888
+ if (!cfg.apiKey) {
889
+ return { state: "off", error: { code: "auth", message: "未配置 API Key" }, entries: [], headline: { kind: "amt", amt: "未配置" } };
890
+ }
891
+ try {
892
+ let orgId = null;
893
+ try {
894
+ const who = await httpJson(`${baseUrl}/alpha/whoami`, { key: cfg.apiKey });
895
+ orgId = who?.org?.id ?? null;
896
+ } catch (error) {
897
+ if (error.code === "auth") throw error;
898
+ }
899
+ const org = orgId ? `?orgId=${encodeURIComponent(orgId)}` : "";
900
+ const [creditsBody, subsBody] = await Promise.all([
901
+ httpJson(`${baseUrl}/alpha/billing/credits${org}`, { key: cfg.apiKey }),
902
+ httpJson(`${baseUrl}/alpha/billing/subscriptions${org}`, { key: cfg.apiKey }),
903
+ ]);
904
+
905
+ const credits = creditsBody?.credits;
906
+ const sub = subsBody?.data;
907
+ const planId = credits?.planId ?? sub?.planId ?? null;
908
+ const planName = PLAN_NAMES[planId] || planId || "套餐";
909
+
910
+ const periodStart = parseDate(sub?.currentPeriodStart);
911
+ let totalCost = null;
912
+ if (periodStart && !Number.isNaN(periodStart.getTime())) {
913
+ try {
914
+ const summary = await httpJson(
915
+ `${baseUrl}/alpha/usage/summary${org ? `${org}&` : "?"}since=${encodeURIComponent(periodStart.toISOString())}`,
916
+ { key: cfg.apiKey },
917
+ );
918
+ totalCost = parseNumber(summary?.totalCost);
919
+ } catch {
920
+ /* 周期消费取不到时不伪造月剩余 */
921
+ }
922
+ }
923
+
924
+ const entries = [];
925
+ let tightest = null;
926
+
927
+ const windowLimits = creditsBody?.windowLimits;
928
+ for (const [field, label, slot, short] of [
929
+ ["fiveHour", "5h 窗口", "window.5h", "5h"],
930
+ ["weekly", "周窗口", "window.weekly", "周"],
931
+ ]) {
932
+ const w = windowLimits?.[field];
933
+ if (!w || typeof w !== "object") continue;
934
+ // 上游契约别名容忍:limit??cap、used??(cap−remaining)、reset??resetAt
935
+ // (真实载荷 resetAt 为 epoch-毫秒数字,parseDate 已按 ISO/毫秒/毫秒数字串宽容解析)
936
+ const cap = parseNumber(w.cap ?? w.limit);
937
+ let used = parseNumber(w.used);
938
+ if (used === null && cap !== null) {
939
+ const remaining = parseNumber(w.remaining);
940
+ if (remaining !== null) used = Math.max(0, cap - remaining);
941
+ }
942
+ if (cap === null || cap <= 0) continue;
943
+ const pct = used === null ? null : Math.min(100, Math.round((used / cap) * 100));
944
+ const remain = used === null ? null : Math.max(0, cap - used);
945
+ const resetDate = parseDate(w.resetAt ?? w.reset);
946
+ entries.push({
947
+ name: `${label} · ${planName}`,
948
+ key: slot,
949
+ short,
950
+ kind: "win",
951
+ limit: formatMoney(cap, "USD"),
952
+ used: used === null ? "—" : formatMoney(used, "USD"),
953
+ remain: remain === null ? "—" : formatMoney(remain, "USD"),
954
+ pct,
955
+ reset: formatReset(resetDate),
956
+ resetAt: resetAtMs(resetDate),
957
+ note: resetDate ? "" : "未提供重置时刻",
958
+ });
959
+ if (pct !== null && (tightest === null || pct > tightest)) tightest = pct;
960
+ }
961
+
962
+ const planLimit = PLAN_MONTHLY_CREDITS[planId] ?? parseNumber(credits?.monthlyCredits);
963
+ if (planLimit !== null && planLimit > 0) {
964
+ let remaining = parseNumber(credits?.monthlyCredits);
965
+ let estimated = false;
966
+ if (remaining === null && totalCost !== null) {
967
+ remaining = Math.max(0, planLimit - totalCost);
968
+ estimated = true;
969
+ }
970
+ if (remaining !== null) {
971
+ const used = Math.max(0, planLimit - remaining);
972
+ const pct = Math.min(100, Math.round((used / planLimit) * 100));
973
+ // 月重置时刻只认订阅周期结束 currentPeriodEnd;currentPeriodStart 是计费周期起点
974
+ // (usage/summary 的 since 锚点),绝不当作重置时间展示
975
+ const periodEnd = parseDate(sub?.currentPeriodEnd);
976
+ const noteParts = [];
977
+ if (estimated) noteParts.push("月度消费估算(套餐总额 − 周期消费)");
978
+ if (sub?.status) noteParts.push(`订阅 ${sub.status}`);
979
+ if (sub && !periodEnd) noteParts.push("周期结束未公布");
980
+ entries.push({
981
+ name: `月额度 · ${planName}`,
982
+ key: "window.monthly",
983
+ short: "月",
984
+ kind: "win",
985
+ limit: formatMoney(planLimit, "USD"),
986
+ used: formatMoney(used, "USD"),
987
+ remain: formatMoney(remaining, "USD"),
988
+ pct,
989
+ reset: formatReset(periodEnd),
990
+ resetAt: resetAtMs(periodEnd),
991
+ note: noteParts.join(";"),
992
+ });
993
+ if (pct !== null && (tightest === null || pct > tightest)) tightest = pct;
994
+ }
995
+ }
996
+
997
+ if (!entries.length) {
998
+ return errResult("no-data", "未解析到窗口/额度数据");
999
+ }
1000
+ return { state: stateFromPct(tightest, cfg.warnPct, cfg.critPct), entries, headline: makePctHeadline(tightest, entries) };
1001
+ } catch (error) {
1002
+ return errResult(error.code || "network", error.message || "网络错误");
1003
+ }
1004
+ }
1005
+
1006
+ // ---------- 注册表 ----------
1007
+
1008
+ function supplierMeta(meta) {
1009
+ return meta;
1010
+ }
1011
+
1012
+ const supplier = (meta) => supplierMeta(meta);
1013
+
1014
+ export const PROVIDERS = {
1015
+ deepseek: supplier({
1016
+ id: "deepseek",
1017
+ name: "DeepSeek",
1018
+ credentialClass: "api-key",
1019
+ credentialKey: "apiKey",
1020
+ credentialLabel: "API Key",
1021
+ baseUrlDefault: "https://api.deepseek.com",
1022
+ official: "官方稳定",
1023
+ needs: [{ key: "apiKey", label: "API Key", secret: true }],
1024
+ query: queryDeepSeek,
1025
+ }),
1026
+ "moonshot-cn": supplier({
1027
+ id: "moonshot-cn",
1028
+ name: "Moonshot 国内",
1029
+ credentialClass: "api-key",
1030
+ credentialKey: "apiKey",
1031
+ credentialLabel: "API Key",
1032
+ region: "cn",
1033
+ baseUrlDefault: "https://api.moonshot.cn/v1",
1034
+ official: "官方稳定",
1035
+ needs: [{ key: "apiKey", label: "API Key", secret: true }],
1036
+ query: moonshotQuery("api.moonshot.cn", "CNY"),
1037
+ }),
1038
+ "moonshot-intl": supplier({
1039
+ id: "moonshot-intl",
1040
+ name: "Moonshot 国际",
1041
+ credentialClass: "api-key",
1042
+ credentialKey: "apiKey",
1043
+ credentialLabel: "API Key",
1044
+ region: "intl",
1045
+ baseUrlDefault: "https://api.moonshot.ai/v1",
1046
+ official: "官方稳定",
1047
+ needs: [{ key: "apiKey", label: "API Key", secret: true }],
1048
+ query: moonshotQuery("api.moonshot.ai", "USD"),
1049
+ }),
1050
+ zai: supplier({
1051
+ id: "zai",
1052
+ name: "Z.ai",
1053
+ credentialClass: "api-key",
1054
+ credentialKey: "codingPlanKey",
1055
+ credentialLabel: "Coding Plan Key",
1056
+ region: "intl",
1057
+ baseUrlDefault: "https://api.z.ai/api/anthropic",
1058
+ official: "官方插件字段",
1059
+ needs: [{ key: "apiKey", label: "Coding Plan Key", secret: true }],
1060
+ query: zaiQuery("api.z.ai"),
1061
+ }),
1062
+ "zai-cn": supplier({
1063
+ id: "zai-cn",
1064
+ name: "智谱 Coding Plan",
1065
+ credentialClass: "api-key",
1066
+ credentialKey: "codingPlanKey",
1067
+ credentialLabel: "Coding Plan Key",
1068
+ region: "cn",
1069
+ baseUrlDefault: "https://open.bigmodel.cn/api/anthropic",
1070
+ official: "官方插件字段",
1071
+ needs: [{ key: "apiKey", label: "Coding Plan Key", secret: true }],
1072
+ query: zaiQuery("open.bigmodel.cn"),
1073
+ }),
1074
+ minimax: supplier({
1075
+ id: "minimax",
1076
+ name: "MiniMax 国际",
1077
+ credentialClass: "api-key",
1078
+ credentialKey: "tokenPlanKey",
1079
+ credentialLabel: "Token Plan Key",
1080
+ region: "intl",
1081
+ baseUrlDefault: "https://www.minimax.io",
1082
+ official: "官方(第一方类型已核验)",
1083
+ needs: [{ key: "apiKey", label: "Token Plan Key", secret: true }],
1084
+ query: minimaxQuery("www.minimax.io"),
1085
+ }),
1086
+ "minimax-cn": supplier({
1087
+ id: "minimax-cn",
1088
+ name: "MiniMax 国内",
1089
+ credentialClass: "api-key",
1090
+ credentialKey: "tokenPlanKey",
1091
+ credentialLabel: "Token Plan Key",
1092
+ region: "cn",
1093
+ baseUrlDefault: "https://www.minimaxi.com",
1094
+ official: "官方(第一方类型已核验)",
1095
+ needs: [{ key: "apiKey", label: "Token Plan Key", secret: true }],
1096
+ query: minimaxQuery("www.minimaxi.com"),
1097
+ }),
1098
+ openrouter: supplier({
1099
+ id: "openrouter",
1100
+ name: "OpenRouter",
1101
+ credentialClass: "api-key",
1102
+ credentialKey: "apiKey",
1103
+ credentialLabel: "API Key",
1104
+ baseUrlDefault: "https://openrouter.ai/api/v1",
1105
+ official: "官方稳定",
1106
+ needs: [{ key: "apiKey", label: "API Key", secret: true }],
1107
+ query: queryOpenRouter,
1108
+ }),
1109
+ "openrouter-account": supplier({
1110
+ id: "openrouter-account",
1111
+ name: "OpenRouter 账户 credits",
1112
+ credentialClass: "management-key",
1113
+ credentialKey: "managementKey",
1114
+ credentialLabel: "Management Key",
1115
+ baseUrlDefault: "https://openrouter.ai/api/v1",
1116
+ official: "官方条件(需 Management Key)",
1117
+ needs: [{ key: "apiKey", label: "Management Key", secret: true }],
1118
+ query: queryOpenRouterAccount,
1119
+ }),
1120
+ "openai-org": supplier({
1121
+ id: "openai-org",
1122
+ name: "OpenAI 组织",
1123
+ credentialClass: "admin-key",
1124
+ credentialKey: "adminKey",
1125
+ credentialLabel: "组织 Admin Key",
1126
+ baseUrlDefault: "https://api.openai.com",
1127
+ official: "官方条件(需组织 Admin Key)",
1128
+ needs: [{ key: "apiKey", label: "Admin Key", secret: true }],
1129
+ query: async (cfg) => {
1130
+ const [usage, cost] = await Promise.all([queryOpenAiUsage(cfg), queryOpenAiCost(cfg)]);
1131
+ return mergeOrgResults(usage, cost);
1132
+ },
1133
+ }),
1134
+ "anthropic-org": supplier({
1135
+ id: "anthropic-org",
1136
+ name: "Anthropic 组织",
1137
+ credentialClass: "admin-key",
1138
+ credentialKey: "adminKey",
1139
+ credentialLabel: "组织 Admin Key",
1140
+ baseUrlDefault: "https://api.anthropic.com",
1141
+ official: "官方条件(需组织 Admin Key)",
1142
+ needs: [{ key: "apiKey", label: "Admin Key", secret: true }],
1143
+ query: async (cfg) => {
1144
+ const [usage, cost] = await Promise.all([queryAnthropicUsage(cfg), queryAnthropicCost(cfg)]);
1145
+ return mergeOrgResults(usage, cost);
1146
+ },
1147
+ }),
1148
+ opencode: supplier({
1149
+ id: "opencode",
1150
+ name: "OpenCode",
1151
+ credentialClass: "api-key",
1152
+ credentialKey: "apiKey",
1153
+ credentialLabel: "API Key / OAuth",
1154
+ compat: "私有兼容来源",
1155
+ baseUrlDefault: "https://opencode.ai",
1156
+ needs: [
1157
+ { key: "apiKey", label: "API Key(窗口用量)", secret: true },
1158
+ { key: "allowanceToken", label: "allowance Token(OAuth)", secret: true },
1159
+ { key: "orgId", label: "org id(可选)", secret: false },
1160
+ ],
1161
+ query: queryOpenCode,
1162
+ }),
1163
+ commandcode: supplier({
1164
+ id: "commandcode",
1165
+ name: "Command Code",
1166
+ credentialClass: "api-key",
1167
+ credentialKey: "apiKey",
1168
+ credentialLabel: "API Key",
1169
+ compat: "私有兼容来源",
1170
+ baseUrlDefault: "https://api.commandcode.ai",
1171
+ needs: [{ key: "apiKey", label: "API Key", secret: true }],
1172
+ query: queryCommandCode,
1173
+ }),
1174
+ };
1175
+
1176
+ /** Admin 供应商:用量与费用两把独立查询合并为一次供应商取数。 */
1177
+ function mergeOrgResults(usage, cost) {
1178
+ if (usage.state === "off" && cost.state === "off") return usage;
1179
+ const entries = [...(usage.entries || []), ...(cost.entries || [])];
1180
+ const errors = [];
1181
+ for (const [label, r] of [["用量", usage], ["费用", cost]]) {
1182
+ if (r.state === "err" || r.state === "off") errors.push(`${label}:${r.error?.message || r.error?.code}`);
1183
+ }
1184
+ const headline = usage.headline && usage.state !== "err" && usage.state !== "off"
1185
+ ? usage.headline
1186
+ : (cost.headline && cost.state !== "err" && cost.state !== "off"
1187
+ ? cost.headline
1188
+ : { kind: "amt", amt: "—" });
1189
+ if (errors.length) {
1190
+ return { state: "err", error: { code: [usage, cost].some((r) => r.error?.code === "auth") ? "auth" : "partial", message: errors.join(";") }, entries, headline };
1191
+ }
1192
+ return { state: stateFromPct(null, 80, 95), entries, headline };
1193
+ }
1194
+
1195
+
1196
+ export const SUPPLIER_IDS = Object.keys(PROVIDERS);
1197
+
1198
+ // 同一次多端点、分页查询共享取消信号;直接测试连接也有总时限。
1199
+ for (const provider of Object.values(PROVIDERS)) {
1200
+ const query = provider.query;
1201
+ provider.query = (config, { signal = AbortSignal.timeout(120_000) } = {}) =>
1202
+ queryContext.run(signal, () => query(config));
1203
+ }