tokenusage-cli 0.4.3 → 0.4.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -3,6 +3,51 @@
3
3
  本包(`tokenusage-cli`)的用户可见变更记录。发版时在顶部新增一节,
4
4
  `## <版本号>` 行会被 release workflow 取作 GitHub Release 正文。
5
5
 
6
+ ## 0.4.4
7
+
8
+ 2026-11-04。契约 v2 落地:小时用量桶按项目名拆行(`project_key`),项目键向上回退到真实
9
+ 项目目录;新增 DeepSeek 余额/状态卡、`status --json` 的计价出处块、`doctor` 计价覆盖自检;
10
+ curated 定价扩到 191 条,Cursor / Kimi / Grok 限额卡补磁盘缓存回退。旧 `tokentracker-*`
11
+ 别名已在服务端移除,仍打旧路径的钉版客户端会得到有声失败(GET 404 / 写动词 405),本地队列不丢。
12
+
13
+ - **服务端 breaking:旧 `tokentracker-*` API 路径别名已移除**(契约 §1.5,2026-11-03
14
+ 操作者拍板)。指向本后端的钉版旧 CLI(tokentracker-cli@1.4.x)上传会得到
15
+ GET 404 / 写动词 405——有声失败、本地 `queue.jsonl` 数据保留,升级到本包后随下次
16
+ `sync` 补传,不丢历史。
17
+ - **桶级 `project_key`(契约 v2,2026-11-03)**:小时用量桶按项目名拆行——每个项目一行,
18
+ 再加一条 `project_key` 为空的余量行,两者相加等于原聚合值,不重复计数;无法归因的
19
+ 历史/账户级用量留在余量行(`docs/cli-contract.md` §2.4、`docs/projects-page-plan.md` §5)。
20
+ - **项目键父级回退(2026-11-04)**:`projectKey()` 不再把 `<repo>/.claude/worktrees/<id>`、
21
+ `<repo>/worktrees/<id>`、`<project>/<session>/subagents` 这类工具目录当成项目名,而是向上
22
+ 取真实项目目录;qoder-cn 子代理转录继承记录里的 `cwd`。只影响新采集——历史键不回填
23
+ (会话落库键含 `session_id`,同会话只更新不改名)。`~/.codex/worktrees/<id>` 无上游项目
24
+ 规则,保持旧行为。
25
+ - **新增 DeepSeek 余额卡与 DeepSeek 服务状态**:`status` 限额面板新增第 18 家提供商
26
+ (pay-as-you-go 余额,含 12h TTL 磁盘缓存与 API key 指纹绑定,凭据错误不回退缓存),
27
+ 服务状态探测接入 status.deepseek.com。
28
+ - **`status --json` 暴露计价数据出处**:新增 `pricing` 块(数据来源、seed 快照日期、
29
+ LiteLLM/curated 条目数),成本为 0 时可直接区分「未采集」与「未定价」。
30
+ - **`doctor` 新增计价覆盖自检**:近 7 天本地队列的桶/token 计价命中率、Top 未定价模型
31
+ (零 token 的积分桶单独计数、不再误报),以及 unknown 模型「对齐到同时段主导模型」的
32
+ 只读 dry-run 预览(不改变任何历史归属)。
33
+ - **计价覆盖大幅扩充**:curated exact 91 → 191。同步上游 TokenTracker 新增的 29+9 条
34
+ (claude-opus-4-5/4-6、gpt-5.4/5.5 系、kimi-k3.1-pro 等);从 juejin-usage 选摘
35
+ volcengine/alibaba-cn/xiaomi/muse 四组 69 条(署名见 THIRD_PARTY_NOTICES);补
36
+ Unisound `u2-flash` 与 StepFun `step-5-preview` 官价。本机 7 天窗口 token 计价覆盖率
37
+ 97.3% → 100%。
38
+ - **Cursor / Kimi / Grok 限额卡新增磁盘缓存回退**:请求超时或 5xx 时展示最近一次成功
39
+ 读数(卡片标 `stale` + 原 `cached_at`),不再整卡空白。缓存文件各为
40
+ `cursor/kimi/grok-usage-limits-cache.json`(`~/.tokenusage/tracker/`,0600 原子写、
41
+ 只在成功时写、reset_at 已过期的窗口自动丢弃);身份指纹绑定(cursor=规范
42
+ userId、kimi=profile 标识、grok=JWT sub),换号不串用;凭据类错误(401/403/过期)
43
+ 不回退、原样上面板。**全部 limits 磁盘缓存的 stale TTL 统一为 12h**(含既有的
44
+ claude/codex/opencodeGo/antigravity/qoder 五家与 DeepSeek 余额卡——额度/余额类读数
45
+ 一天内即过时;qoder 促销活动缓存 24h、opencodeGo 本地估算缓存 1h 属不同语义,不动)。
46
+ - 单测:`pricing-parity`(CLI/web 两份定价数据逐字节一致守卫)、`pricing-meta`、
47
+ `pricing-coverage`、`deepseek-limits` / `deepseek-status`,以及
48
+ `cursor/grok/kimi-limits-cache-fallback`(命中/过期/失败回退/换号不串用/凭据错误直通/
49
+ 无缓存失败,共 22 例)。
50
+
6
51
  ## 0.4.3
7
52
 
8
53
  2026-11-01。两处只有真机首跑才暴露的问题:调度摘要依旧看不出拒绝原因(修的过程中又追出
@@ -11,6 +11,21 @@ upstream repository and were then modified for the token-usage contract
11
11
  (`docs/cli-contract.md` in the repository root). The upstream MIT license text
12
12
  and copyright notice are preserved in this package's `LICENSE` file.
13
13
 
14
- 本包不含其他第三方资产:运行时依赖(如 `undici`)的许可随
15
- `node_modules` 一同分发;品牌图标、字体与定价快照属于 Web 端,登记在仓库根目录的
14
+ ## juejin-usage (pricing data)
15
+
16
+ `src/lib/pricing/curated-overrides.json` 中的 volcengine / xiaomi / meta(muse) /
17
+ alibaba-cn / moonshotai-cn 五组共 69 条 exact 定价条目(2026-11-03 导入)取自
18
+ [juejin-usage](https://github.com/juejin-cn/juejin-usage)(MIT License,
19
+ Copyright (c) juejin-cn)commit `f72ca4d` 的 `packages/core/src/pricing/pricing.json`
20
+ (models.dev 官方渠道价格集)。juejin-usage 的 MIT 许可要求复制时保留其版权与许可声明:
21
+
22
+ > MIT License, Copyright (c) 2026 juejin-cn — Permission is hereby granted,
23
+ > free of charge, to any person obtaining a copy of this software and
24
+ > associated documentation files, to deal in the Software without restriction,
25
+ > subject to the condition that the above copyright notice and this permission
26
+ > notice shall be included in all copies or substantial portions of the
27
+ > Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND.
28
+
29
+ 本包其余部分不含其他第三方资产:运行时依赖(如 `undici`)的许可随
30
+ `node_modules` 一同分发;品牌图标、字体与定价快照(LiteLLM seed)的登记见仓库根目录的
16
31
  `THIRD_PARTY_NOTICES.md`。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "tokenusage-cli",
3
- "version": "0.4.3",
3
+ "version": "0.4.4",
4
4
  "description": "Self-hosted AI coding token usage collector for the Token Usage dashboard.",
5
5
  "keywords": [
6
6
  "token-usage",
@@ -41,9 +41,9 @@
41
41
  "prepublishOnly": "npm test"
42
42
  },
43
43
  "dependencies": {
44
- "@journeyapps/wa-sqlite": "2.0.7",
45
- "smol-toml": "^1.9.0",
46
- "undici": "8.12.2",
44
+ "@journeyapps/wa-sqlite": "2.0.10",
45
+ "smol-toml": "^1.9.1",
46
+ "undici": "8.12.3",
47
47
  "yauzl": "^3.4.0"
48
48
  },
49
49
  "pnpm": {
@@ -161,9 +161,11 @@ function resolveWindow(opts, nowMs) {
161
161
  return { fromMs: clampedFrom, toMs, clamped: clampedFrom !== effectiveFrom };
162
162
  }
163
163
 
164
- function bucketKey(hourMs, source, model) {
165
- // JSON over a delimiter: model names may contain `|`.
166
- return JSON.stringify([new Date(hourMs).toISOString(), source, model]);
164
+ function bucketKey(hourMs, source, model, project = "") {
165
+ // JSON over a delimiter: model names may contain `|`. contract v2
166
+ // (2026-11-03): project_key joins the identity; '' = unattributed (rows
167
+ // from a pre-v2 server have no project_key at all and land here too).
168
+ return JSON.stringify([new Date(hourMs).toISOString(), source, model, project]);
167
169
  }
168
170
 
169
171
  // Local baseline: every usage row in queue.jsonl, normalized/sanitized exactly
@@ -206,7 +208,8 @@ async function collectBuckets({ queuePath, fromMs, toMs, start = 0 }) {
206
208
  });
207
209
  const sanitized = sanitizeBucketForUpload(row);
208
210
  if (!sanitized) continue;
209
- buckets.set(bucketKey(hourMs, source, model), sanitized);
211
+ const project = typeof sanitized.project_key === "string" ? sanitized.project_key.trim() : "";
212
+ buckets.set(bucketKey(hourMs, source, model, project), sanitized);
210
213
  }
211
214
  } finally {
212
215
  await handle.close();
@@ -283,7 +286,9 @@ async function fetchServerBuckets({ baseUrl, anonKey, deviceToken, from, to, lim
283
286
  if (!Number.isFinite(hourMs)) continue;
284
287
  const source = String(row.source);
285
288
  const model = String(row.model);
286
- buckets.set(bucketKey(hourMs, source, model), row);
289
+ // Pre-v2 servers omit project_key entirely; treat as unattributed ('').
290
+ const project = typeof row.project_key === "string" ? row.project_key : "";
291
+ buckets.set(bucketKey(hourMs, source, model, project), row);
287
292
  }
288
293
  if (rows.length < pageSize) break;
289
294
  offset += rows.length;
@@ -48,6 +48,7 @@ const {
48
48
  } = require("../lib/openclaw-session-plugin");
49
49
  const { resolveTrackerPaths } = require("../lib/tracker-paths");
50
50
  const { resolveDeviceTokenPresence } = require("../lib/cloud-device-token");
51
+ const { getPricingMeta } = require("../lib/pricing");
51
52
  const {
52
53
  isCollectionPaused,
53
54
  isRunReportEnabled,
@@ -1281,6 +1282,9 @@ async function cmdStatus(argv = []) {
1281
1282
  }
1282
1283
  : {}),
1283
1284
  subscriptions,
1285
+ // Pricing data provenance + staleness, so a $0 cost row can be triaged
1286
+ // as "not collected" vs "not priced" from `status --json` alone.
1287
+ pricing: getPricingMeta(),
1284
1288
  };
1285
1289
 
1286
1290
  if (opts.json) {
@@ -242,7 +242,11 @@ function fetchCursorUsageSummary({ cookie, timeoutMs = 30000, fetchImpl = fetch
242
242
  signal: AbortSignal.timeout(timeoutMs),
243
243
  }).then(async (res) => {
244
244
  if (res.status === 401 || res.status === 403) {
245
- throw new Error("Cursor session expired — re-login in Cursor to refresh");
245
+ // The code marks the error actionable (re-login) so the limits
246
+ // disk-cache fallback never hides it.
247
+ const error = new Error("Cursor session expired — re-login in Cursor to refresh");
248
+ error.code = "AUTH_EXPIRED";
249
+ throw error;
246
250
  }
247
251
  if (!res.ok) {
248
252
  throw new Error(`Cursor API returned ${res.status}`);
@@ -0,0 +1,280 @@
1
+ "use strict";
2
+
3
+ // DeepSeek (platform.deepseek.com, pay-as-you-go) balance monitoring.
4
+ //
5
+ // DeepSeek has no quota windows at all: it is a prepaid API platform, and the
6
+ // only documented programmatic data source is the balance endpoint
7
+ // (GET https://api.deepseek.com/user/balance, Bearer API key). It returns
8
+ // `is_available` plus `balance_infos[]` entries whose numeric fields are all
9
+ // STRINGS ("110.02"), and more than one currency (CNY + USD) can be present
10
+ // at the same time. Concurrency rate limits (flash 2500 / v4-pro 500, 429)
11
+ // are not quota windows, so nothing here produces a window bar — the panel
12
+ // renders a balance card instead (issue #960).
13
+ //
14
+ // The API key comes from DEEPSEEK_API_KEY when set, otherwise from the key
15
+ // saved in the Limits panel (provider-api-key-store.js). The stored key exists
16
+ // so users never need a machine-wide `launchctl setenv`, which reaches every
17
+ // launchd app on macOS and not just Token Usage (#837).
18
+ //
19
+ // Balance only decreases between top-ups and there is no reset instant to
20
+ // check, so the last-good disk-cache fallback (0600 JSON, written only on a
21
+ // live success) is gated by a pure TTL — the same "unknown reset" rule the
22
+ // ark providers use — and by a fingerprint of the API key that produced it,
23
+ // so a swapped key can never serve the previous account's balance.
24
+
25
+ const crypto = require("node:crypto");
26
+ const fs = require("node:fs");
27
+ const os = require("node:os");
28
+ const path = require("node:path");
29
+ const { readStoredApiKey } = require("./provider-api-key-store");
30
+
31
+ const DEEPSEEK_BALANCE_URL = "https://api.deepseek.com/user/balance";
32
+ const DEEPSEEK_LIMITS_CACHE_FILE = "deepseek-limits-cache.json";
33
+ const DEEPSEEK_ENV_NAME = "DEEPSEEK_API_KEY";
34
+ const DEEPSEEK_REQUEST_TIMEOUT_MS = 10_000;
35
+ const DEEPSEEK_BALANCE_CACHE_TTL_MS = 12 * 60 * 60 * 1000;
36
+
37
+ function readDeepseekApiKey({ home, trackerDir, env = process.env } = {}) {
38
+ const envKey =
39
+ env && typeof env === "object" && typeof env[DEEPSEEK_ENV_NAME] === "string"
40
+ ? env[DEEPSEEK_ENV_NAME].trim()
41
+ : "";
42
+ if (envKey) return { apiKey: envKey, source: "env" };
43
+ const stored = readStoredApiKey({ provider: "deepseek", trackerDir, home });
44
+ return stored ? { apiKey: stored, source: "stored" } : null;
45
+ }
46
+
47
+ // Balance payloads are strings; a malformed or negative entry must drop out
48
+ // rather than coerce into a misleading 0 ("" and " " both coerce to 0).
49
+ function balanceNumber(value) {
50
+ if (typeof value === "string") {
51
+ const trimmed = value.trim();
52
+ if (!trimmed) return null;
53
+ const n = Number(trimmed);
54
+ return Number.isFinite(n) && n >= 0 ? n : null;
55
+ }
56
+ if (typeof value !== "number") return null;
57
+ return Number.isFinite(value) && value >= 0 ? value : null;
58
+ }
59
+
60
+ /**
61
+ * Normalize the GET /user/balance payload into one row per currency, API
62
+ * order preserved (the panel renders each currency side by side; picking a
63
+ * single "primary" currency is an owner decision, not a parser concern).
64
+ * Throws when the payload shape is unusable so the caller can fall back to
65
+ * the disk cache.
66
+ */
67
+ function normalizeDeepseekBalanceResponse(body) {
68
+ if (!body || typeof body !== "object") {
69
+ throw new Error("DeepSeek balance response is not an object.");
70
+ }
71
+ if (typeof body.is_available !== "boolean") {
72
+ throw new Error("DeepSeek balance response is missing is_available.");
73
+ }
74
+ const entries = Array.isArray(body.balance_infos) ? body.balance_infos : [];
75
+ const balances = [];
76
+ for (const entry of entries) {
77
+ const currency = typeof entry?.currency === "string" ? entry.currency.trim() : "";
78
+ const total = balanceNumber(entry?.total_balance);
79
+ if (!currency || total === null) continue;
80
+ balances.push({
81
+ currency,
82
+ total,
83
+ granted: balanceNumber(entry?.granted_balance) ?? 0,
84
+ topped_up: balanceNumber(entry?.topped_up_balance) ?? 0,
85
+ });
86
+ }
87
+ if (balances.length === 0) {
88
+ throw new Error("DeepSeek balance response contains no usable balance entries.");
89
+ }
90
+ return balances;
91
+ }
92
+
93
+ // The fingerprint labels a credential, so it must come from a memory-hard
94
+ // KDF rather than a bare fast hash (CodeQL flags sha256 over key-store/env
95
+ // credentials; the ark apiKey-prefix label hit the same alert before #950).
96
+ // Memoized per key: scrypt is intentionally slow.
97
+ const DEEPSEEK_FINGERPRINT_SALT = "tokenusage/deepseek-limits-cache/v1";
98
+ let fingerprintMemo = null;
99
+
100
+ function keyFingerprint(apiKey) {
101
+ const key = String(apiKey);
102
+ if (fingerprintMemo?.key === key) return fingerprintMemo.hex;
103
+ const hex = crypto
104
+ .scryptSync(key, DEEPSEEK_FINGERPRINT_SALT, 16, {
105
+ N: 2 ** 15,
106
+ r: 8,
107
+ p: 1,
108
+ maxmem: 128 * 2 ** 15 * 8 * 2,
109
+ })
110
+ .toString("hex");
111
+ fingerprintMemo = { key, hex };
112
+ return hex;
113
+ }
114
+
115
+ function resolveDeepseekLimitsCachePath({ trackerDir, home } = {}) {
116
+ const dir =
117
+ typeof trackerDir === "string" && trackerDir.trim()
118
+ ? trackerDir.trim()
119
+ : path.join(home || os.homedir(), ".tokenusage", "tracker");
120
+ return path.join(dir, DEEPSEEK_LIMITS_CACHE_FILE);
121
+ }
122
+
123
+ /**
124
+ * Last-good balance snapshot. `keyFingerprint` (when given) must match the
125
+ * key that produced the cache — a different key is a different account, and
126
+ * its balance would be a wrong answer, not a stale one.
127
+ */
128
+ function readDeepseekLimitsCache({ trackerDir, home, nowMs = Date.now(), keyFingerprint: expectedFingerprint } = {}) {
129
+ const cachePath = resolveDeepseekLimitsCachePath({ trackerDir, home });
130
+ let parsed;
131
+ try {
132
+ parsed = JSON.parse(fs.readFileSync(cachePath, "utf8"))?.deepseek;
133
+ } catch (_error) {
134
+ return null;
135
+ }
136
+ const cachedAtMs = Date.parse(parsed?.cached_at || "");
137
+ if (!Number.isFinite(cachedAtMs)) return null;
138
+ if (cachedAtMs > nowMs + 60_000) return null;
139
+ // Pure TTL: balances have no reset instant, so freshness decays with age
140
+ // alone (ark's unknown-reset rule).
141
+ if (nowMs - cachedAtMs > DEEPSEEK_BALANCE_CACHE_TTL_MS) return null;
142
+ if (expectedFingerprint && parsed?.key_fingerprint !== expectedFingerprint) return null;
143
+ const balances = Array.isArray(parsed?.balances)
144
+ ? parsed.balances.filter(
145
+ (entry) =>
146
+ entry &&
147
+ typeof entry.currency === "string" &&
148
+ entry.currency.trim() &&
149
+ balanceNumber(entry.total) !== null,
150
+ )
151
+ : [];
152
+ if (balances.length === 0) return null;
153
+ return {
154
+ configured: true,
155
+ error: null,
156
+ is_available: parsed.is_available === true,
157
+ balances,
158
+ source: "disk-cache",
159
+ stale: true,
160
+ cached_at: parsed.cached_at,
161
+ };
162
+ }
163
+
164
+ function writeDeepseekLimitsCache(limits, { trackerDir, home, nowMs = Date.now(), keyFingerprint: fingerprint } = {}) {
165
+ if (!limits?.configured || limits.error || !Array.isArray(limits.balances) || limits.balances.length === 0) return;
166
+ const cachePath = resolveDeepseekLimitsCachePath({ trackerDir, home });
167
+ const payload = {
168
+ deepseek: {
169
+ is_available: limits.is_available === true,
170
+ balances: limits.balances,
171
+ key_fingerprint: fingerprint || null,
172
+ cached_at: new Date(nowMs).toISOString(),
173
+ },
174
+ };
175
+ try {
176
+ fs.mkdirSync(path.dirname(cachePath), { recursive: true });
177
+ const tmpPath = `${cachePath}.${process.pid}.tmp`;
178
+ fs.writeFileSync(tmpPath, JSON.stringify(payload, null, 2), { encoding: "utf8", mode: 0o600 });
179
+ fs.renameSync(tmpPath, cachePath);
180
+ } catch (_error) {}
181
+ }
182
+
183
+ /**
184
+ * One live GET /user/balance read. Returns {ok, is_available, balances} on a
185
+ * usable payload, {auth_error: true, error} when the key itself is rejected
186
+ * (actionable — must not be masked by stale cache), {error} otherwise.
187
+ */
188
+ async function fetchDeepseekBalance({ apiKey, fetchImpl, timeoutMs = DEEPSEEK_REQUEST_TIMEOUT_MS } = {}) {
189
+ let response;
190
+ try {
191
+ response = await fetchImpl(DEEPSEEK_BALANCE_URL, {
192
+ method: "GET",
193
+ headers: {
194
+ Authorization: `Bearer ${apiKey}`,
195
+ Accept: "application/json",
196
+ },
197
+ });
198
+ } catch (err) {
199
+ return { error: `DeepSeek balance request failed: ${err?.message || err}` };
200
+ }
201
+ if (response.status === 401 || response.status === 403) {
202
+ return {
203
+ auth_error: true,
204
+ error: `DeepSeek API key was rejected (${response.status}). Check the key in the DeepSeek platform console.`,
205
+ };
206
+ }
207
+ if (!response.ok) {
208
+ return { error: `DeepSeek balance API returned ${response.status}` };
209
+ }
210
+ let body;
211
+ try {
212
+ body = JSON.parse(await response.text());
213
+ } catch (err) {
214
+ return { error: `Could not parse DeepSeek balance response: ${err?.message || err}` };
215
+ }
216
+ try {
217
+ return { ok: true, is_available: body.is_available === true, balances: normalizeDeepseekBalanceResponse(body) };
218
+ } catch (err) {
219
+ return { error: err?.message || "DeepSeek balance response could not be parsed." };
220
+ }
221
+ }
222
+
223
+ /**
224
+ * Fetch the DeepSeek balance card. `persistCache: false` lets the caller
225
+ * suppress the disk write while its aggregate cache generation is stale
226
+ * (a provider-key save mid-fetch must not republish pre-save data, #837).
227
+ */
228
+ async function fetchDeepseekLimits({
229
+ home = os.homedir(),
230
+ trackerDir,
231
+ env = process.env,
232
+ fetchImpl = fetch,
233
+ nowMs = Date.now(),
234
+ timeoutMs = DEEPSEEK_REQUEST_TIMEOUT_MS,
235
+ persistCache = true,
236
+ } = {}) {
237
+ const credential = readDeepseekApiKey({ home, trackerDir, env });
238
+ if (!credential) return { configured: false };
239
+ const fingerprint = keyFingerprint(credential.apiKey);
240
+
241
+ const live = await fetchDeepseekBalance({ apiKey: credential.apiKey, fetchImpl, timeoutMs });
242
+ if (live.ok) {
243
+ const result = {
244
+ configured: true,
245
+ error: null,
246
+ is_available: live.is_available,
247
+ balances: live.balances,
248
+ credential_source: credential.source,
249
+ source: "provider-api",
250
+ stale: false,
251
+ cached_at: new Date(nowMs).toISOString(),
252
+ };
253
+ if (persistCache) {
254
+ writeDeepseekLimitsCache(result, { trackerDir, home, nowMs, keyFingerprint: fingerprint });
255
+ }
256
+ return result;
257
+ }
258
+ if (live.auth_error) {
259
+ return { configured: true, error: live.error, auth_error: true, credential_source: credential.source };
260
+ }
261
+ const cached = readDeepseekLimitsCache({ trackerDir, home, nowMs, keyFingerprint: fingerprint });
262
+ if (cached) return { ...cached, credential_source: credential.source };
263
+ return { configured: true, error: live.error, credential_source: credential.source };
264
+ }
265
+
266
+ module.exports = {
267
+ DEEPSEEK_BALANCE_URL,
268
+ DEEPSEEK_LIMITS_CACHE_FILE,
269
+ DEEPSEEK_ENV_NAME,
270
+ DEEPSEEK_BALANCE_CACHE_TTL_MS,
271
+ balanceNumber,
272
+ fetchDeepseekBalance,
273
+ fetchDeepseekLimits,
274
+ keyFingerprint,
275
+ normalizeDeepseekBalanceResponse,
276
+ readDeepseekApiKey,
277
+ readDeepseekLimitsCache,
278
+ resolveDeepseekLimitsCachePath,
279
+ writeDeepseekLimitsCache,
280
+ };
@@ -0,0 +1,157 @@
1
+ // DeepSeek service-status probe.
2
+ //
3
+ // status.deepseek.com is a Flashcat(快猫)-hosted Next.js app. Unlike Statuspage.io
4
+ // it exposes no public JSON API and sends no CORS headers, so a browser cannot
5
+ // read it directly. The page state is, however, inlined in the server render as
6
+ // React Server Component "flight" data: the client script pushes JSON chunks via
7
+ // self.__next_f.push([1, "<json string>"]). We concatenate those chunks and read
8
+ // the single machine-readable signal — the live `active_changes` array.
9
+ //
10
+ // Semantics (Flashcat change status -> Statuspage.io indicator):
11
+ // operational -> none
12
+ // degraded / degraded_performance / maintenance -> minor
13
+ // partial_outage -> major
14
+ // major_outage / full_outage -> critical
15
+ // An empty active_changes array means everything is operational. Anything we
16
+ // cannot parse throws, so the caller falls back instead of inventing "all good".
17
+
18
+ const DEEPSEEK_STATUS_URL = "https://status.deepseek.com/";
19
+
20
+ const RSC_PUSH_RE = /self\.__next_f\.push\(\[1,("(?:[^"\\]|\\.)*")\]\)/g;
21
+
22
+ const CHANGE_STATUS_TO_INDICATOR = {
23
+ operational: "none",
24
+ degraded: "minor",
25
+ degraded_performance: "minor",
26
+ maintenance: "minor",
27
+ under_maintenance: "minor",
28
+ partial_outage: "major",
29
+ major_outage: "critical",
30
+ full_outage: "critical",
31
+ outage: "critical",
32
+ };
33
+
34
+ const INDICATOR_RANK = { none: 0, minor: 1, major: 2, critical: 3 };
35
+
36
+ function extractFlight(html) {
37
+ if (typeof html !== "string" || html.length === 0) {
38
+ throw new Error("DeepSeek status: expected an HTML document");
39
+ }
40
+ let flight = "";
41
+ let chunks = 0;
42
+ RSC_PUSH_RE.lastIndex = 0;
43
+ let match;
44
+ while ((match = RSC_PUSH_RE.exec(html))) {
45
+ try {
46
+ flight += JSON.parse(match[1]);
47
+ } catch (_error) {
48
+ throw new Error("DeepSeek status: malformed RSC chunk");
49
+ }
50
+ chunks += 1;
51
+ }
52
+ if (chunks === 0) {
53
+ throw new Error("DeepSeek status: no RSC data found");
54
+ }
55
+ return flight;
56
+ }
57
+
58
+ // Return the balanced JSON array that starts at `start` (a '[' in flight).
59
+ function sliceJsonArray(flight, start) {
60
+ let depth = 0;
61
+ let inString = false;
62
+ let escaped = false;
63
+ for (let i = start; i < flight.length; i += 1) {
64
+ const ch = flight[i];
65
+ if (inString) {
66
+ if (escaped) escaped = false;
67
+ else if (ch === "\\") escaped = true;
68
+ else if (ch === '"') inString = false;
69
+ continue;
70
+ }
71
+ if (ch === '"') inString = true;
72
+ else if (ch === "[") depth += 1;
73
+ else if (ch === "]") {
74
+ depth -= 1;
75
+ if (depth === 0) return flight.slice(start, i + 1);
76
+ }
77
+ }
78
+ throw new Error("DeepSeek status: unterminated active_changes array");
79
+ }
80
+
81
+ function readUpdatedAt(flight) {
82
+ const match = /"initialDataUpdatedAt":(\d{10,})/.exec(flight);
83
+ if (!match) return undefined;
84
+ const ms = Number(match[1]);
85
+ return Number.isFinite(ms) ? new Date(ms).toISOString() : undefined;
86
+ }
87
+
88
+ /**
89
+ * Parse the status.deepseek.com HTML into a Statuspage.io-shaped payload:
90
+ * { status: { indicator, description }, page: { updated_at } }
91
+ * Throws when the page structure is not understood, so callers fall back
92
+ * instead of reporting a false "operational".
93
+ */
94
+ function parseDeepSeekStatusPage(html) {
95
+ const flight = extractFlight(html);
96
+ const marker = '"active_changes":';
97
+ const markerIndex = flight.indexOf(marker);
98
+ if (markerIndex === -1) {
99
+ throw new Error("DeepSeek status: active_changes not found");
100
+ }
101
+ // The value must be an array. If upstream ever reports null / an object /
102
+ // anything else, refuse to guess a healthier-looking array further along the
103
+ // document — throwing keeps the caller on its last-good / "unknown" path
104
+ // instead of inventing a false "operational".
105
+ let arrayStart = markerIndex + marker.length;
106
+ while (arrayStart < flight.length && /\s/.test(flight[arrayStart])) arrayStart += 1;
107
+ if (flight[arrayStart] !== "[") {
108
+ throw new Error("DeepSeek status: active_changes is not an array");
109
+ }
110
+ let changes;
111
+ try {
112
+ changes = JSON.parse(sliceJsonArray(flight, arrayStart));
113
+ } catch (error) {
114
+ throw new Error("DeepSeek status: cannot parse active_changes (" + error.message + ")");
115
+ }
116
+ if (!Array.isArray(changes)) {
117
+ throw new Error("DeepSeek status: active_changes is not an array");
118
+ }
119
+
120
+ const updatedAt = readUpdatedAt(flight);
121
+ if (changes.length === 0) {
122
+ return { status: { indicator: "none", description: "" }, page: { updated_at: updatedAt } };
123
+ }
124
+
125
+ let worstIndicator = "none";
126
+ let worstRank = -1;
127
+ let descriptions = [];
128
+ for (const change of changes) {
129
+ if (!change || typeof change !== "object") continue;
130
+ const rawStatus = String(change.status || change.change_status || change.impact || "").toLowerCase();
131
+ const indicator = CHANGE_STATUS_TO_INDICATOR[rawStatus] || "minor";
132
+ const rank = INDICATOR_RANK[indicator];
133
+ const description = typeof change.name === "string" ? change.name
134
+ : typeof change.title === "string" ? change.title
135
+ : typeof change.description === "string" ? change.description
136
+ : "";
137
+ if (rank > worstRank) {
138
+ worstRank = rank;
139
+ worstIndicator = indicator;
140
+ descriptions = description ? [description] : [];
141
+ } else if (rank === worstRank && description) {
142
+ descriptions.push(description);
143
+ }
144
+ }
145
+ // A non-empty array with no readable change is still "something is wrong".
146
+ if (worstRank < 0) worstIndicator = "minor";
147
+
148
+ return {
149
+ status: { indicator: worstIndicator, description: descriptions.join("; ") },
150
+ page: { updated_at: updatedAt },
151
+ };
152
+ }
153
+
154
+ module.exports = {
155
+ parseDeepSeekStatusPage,
156
+ DEEPSEEK_STATUS_URL,
157
+ };
package/src/lib/doctor.js CHANGED
@@ -1,7 +1,9 @@
1
1
  const fs = require("node:fs/promises");
2
+ const path = require("node:path");
2
3
  const { constants } = require("node:fs");
3
4
 
4
5
  const { readJsonStrict } = require("./fs");
6
+ const { collectPricingCoverage } = require("./pricing-coverage");
5
7
 
6
8
  async function buildDoctorReport({
7
9
  runtime = {},
@@ -17,6 +19,7 @@ async function buildDoctorReport({
17
19
  if (paths.trackerDir) {
18
20
  checks.push(await checkTrackerDir(paths.trackerDir));
19
21
  checks.push(await checkRuntimeCopy(paths.trackerDir));
22
+ checks.push(await checkPricingCoverage(paths.trackerDir));
20
23
  }
21
24
  if (paths.configPath) {
22
25
  checks.push(await checkConfigJson(paths.configPath));
@@ -177,6 +180,53 @@ async function checkTrackerDir(trackerDir) {
177
180
  }
178
181
  }
179
182
 
183
+ // B3 (docs/upstream-comparison-plan.md §2): pricing coverage of the local
184
+ // last-wins queue over the trailing 7 days, plus the C2 unknown-alignment
185
+ // dry-run preview. Informational only — never critical, never writes.
186
+ async function checkPricingCoverage(trackerDir) {
187
+ const queuePath = path.join(trackerDir, "queue.jsonl");
188
+ try {
189
+ const report = await collectPricingCoverage({ queuePath });
190
+ const { coverage, unknown_alignment_preview: alignment } = report;
191
+ if (coverage.buckets === 0) {
192
+ return {
193
+ id: "pricing.coverage",
194
+ status: "ok",
195
+ critical: false,
196
+ detail: `no local buckets in the last ${report.window.days}d`,
197
+ meta: report,
198
+ };
199
+ }
200
+ const parts = [
201
+ `last ${report.window.days}d: ${(coverage.token_coverage * 100).toFixed(1)}% of tokens priced ` +
202
+ `(${coverage.covered_buckets}/${coverage.buckets} buckets covered)`,
203
+ ];
204
+ const top = coverage.top_unpriced[0];
205
+ if (top) {
206
+ parts.push(`top unpriced: ${top.model} (${top.sources.join("/")}, ${top.total_tokens} tokens)`);
207
+ }
208
+ if (alignment.alignable_buckets > 0) {
209
+ parts.push(
210
+ `unknown dry-run: ${alignment.alignable_buckets} bucket(s) / ${alignment.alignable_tokens} token(s) would re-attribute to a dominant known model`,
211
+ );
212
+ }
213
+ return {
214
+ id: "pricing.coverage",
215
+ status: coverage.token_coverage >= 0.95 ? "ok" : "warn",
216
+ critical: false,
217
+ detail: parts.join("; "),
218
+ meta: report,
219
+ };
220
+ } catch (error) {
221
+ return {
222
+ id: "pricing.coverage",
223
+ status: "warn",
224
+ critical: false,
225
+ detail: `coverage check failed: ${error?.message || error}`,
226
+ };
227
+ }
228
+ }
229
+
180
230
  // The init-copied runtime (`<trackerDir>/app`) is what notify hooks and the
181
231
  // hidden task prefer; without its readiness marker they fall back to the
182
232
  // installed CLI. Surface that state instead of leaving it invisible.