tokenusage-cli 0.4.2 → 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 +68 -0
- package/README.md +4 -1
- package/THIRD_PARTY_NOTICES.md +17 -2
- package/package.json +4 -4
- package/src/commands/reconcile.js +87 -13
- package/src/commands/status.js +4 -0
- package/src/lib/cursor-config.js +5 -1
- package/src/lib/deepseek-limits.js +280 -0
- package/src/lib/deepseek-status.js +157 -0
- package/src/lib/doctor.js +50 -0
- package/src/lib/grok-limits.js +40 -1
- package/src/lib/ingest-sanitize.js +9 -0
- package/src/lib/pricing/curated-overrides.json +627 -0
- package/src/lib/pricing/index.js +16 -0
- package/src/lib/pricing-coverage.js +205 -0
- package/src/lib/provider-api-key-store.js +111 -0
- package/src/lib/provider-status.js +14 -2
- package/src/lib/qoder-limits.js +4 -1
- package/src/lib/rollout.js +286 -58
- package/src/lib/scheduled-task.js +77 -8
- package/src/lib/session-analytics.js +52 -2
- package/src/lib/upload-queue.js +4 -1
- package/src/lib/usage-limits.js +536 -22
|
@@ -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.
|
package/src/lib/grok-limits.js
CHANGED
|
@@ -264,6 +264,29 @@ function grokEntryAccessToken(entry) {
|
|
|
264
264
|
return entry && typeof entry.key === "string" ? entry.key.trim() : "";
|
|
265
265
|
}
|
|
266
266
|
|
|
267
|
+
// auth.x.ai issues JWT access tokens (RFC 9068), so the OIDC `sub` claim is a
|
|
268
|
+
// non-secret, locally derivable account id — the cache-partition key for the
|
|
269
|
+
// limits disk-cache fallback. An opaque token yields null (fail-closed).
|
|
270
|
+
function grokTokenSubject(token) {
|
|
271
|
+
if (typeof token !== "string" || !token.trim()) return null;
|
|
272
|
+
try {
|
|
273
|
+
const parts = token.split(".");
|
|
274
|
+
if (parts.length !== 3) return null;
|
|
275
|
+
const payload = JSON.parse(Buffer.from(parts[1], "base64url").toString("utf8"));
|
|
276
|
+
const subject = payload?.sub;
|
|
277
|
+
return typeof subject === "string" && subject.trim() ? subject.trim() : null;
|
|
278
|
+
} catch (_error) {
|
|
279
|
+
return null;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// Errors that tell the user to re-login. They are actionable and must surface
|
|
284
|
+
// instead of being masked by the stale disk-cache fallback (opencode-go
|
|
285
|
+
// auth_error precedent).
|
|
286
|
+
function isGrokAuthErrorCode(error) {
|
|
287
|
+
return error?.code === "GROK_AUTH_REQUIRED" || error?.code === "GROK_REAUTH_REQUIRED";
|
|
288
|
+
}
|
|
289
|
+
|
|
267
290
|
/**
|
|
268
291
|
* Public xAI OIDC client refresh (auth method "none").
|
|
269
292
|
* Matches Grok Build CLI's refresh against https://auth.x.ai/oauth2/token.
|
|
@@ -775,6 +798,10 @@ async function fetchGrokLimits({ home, env, fetchImpl = fetch, timeoutMs, nowMs
|
|
|
775
798
|
return {
|
|
776
799
|
configured: true,
|
|
777
800
|
error: error?.message || "Unknown error",
|
|
801
|
+
// A rejected refresh is actionable (re-login) and must not be hidden
|
|
802
|
+
// behind the stale disk-cache fallback. Internal marker — stripped
|
|
803
|
+
// before the payload is served.
|
|
804
|
+
...(isGrokAuthErrorCode(error) ? { auth_error: true } : {}),
|
|
778
805
|
};
|
|
779
806
|
}
|
|
780
807
|
|
|
@@ -785,13 +812,16 @@ async function fetchGrokLimits({ home, env, fetchImpl = fetch, timeoutMs, nowMs
|
|
|
785
812
|
return {
|
|
786
813
|
configured: true,
|
|
787
814
|
error: resolved.error?.message || grokAuthError().message,
|
|
815
|
+
...(isGrokAuthErrorCode(resolved.error) ? { auth_error: true } : {}),
|
|
788
816
|
};
|
|
789
817
|
}
|
|
790
818
|
|
|
791
819
|
const startedAtMs = Date.now();
|
|
820
|
+
// Hoisted so the catch below can still derive the cache identity from the
|
|
821
|
+
// token the failing attempt used.
|
|
822
|
+
let accessToken = resolved.accessToken;
|
|
792
823
|
try {
|
|
793
824
|
let body;
|
|
794
|
-
let accessToken = resolved.accessToken;
|
|
795
825
|
try {
|
|
796
826
|
body = await fetchGrokBilling(resolved.accessToken, { fetchImpl, env, timeoutMs });
|
|
797
827
|
} catch (error) {
|
|
@@ -830,11 +860,19 @@ async function fetchGrokLimits({ home, env, fetchImpl = fetch, timeoutMs, nowMs
|
|
|
830
860
|
configured: true,
|
|
831
861
|
error: null,
|
|
832
862
|
...limits,
|
|
863
|
+
// Internal cache-partition key (stripped before the payload is served).
|
|
864
|
+
// An opaque token yields null → the cache write/read is refused, so an
|
|
865
|
+
// unattributable login can never pin another account's bars (no token
|
|
866
|
+
// fingerprint fallback: credentials must not enter even a label hash —
|
|
867
|
+
// CodeQL js/insufficient-password-hash precedent).
|
|
868
|
+
cache_identity: grokTokenSubject(accessToken),
|
|
833
869
|
};
|
|
834
870
|
} catch (error) {
|
|
835
871
|
return {
|
|
836
872
|
configured: true,
|
|
837
873
|
error: error?.message || "Unknown error",
|
|
874
|
+
...(isGrokAuthErrorCode(error) ? { auth_error: true } : {}),
|
|
875
|
+
cache_identity: grokTokenSubject(accessToken),
|
|
838
876
|
};
|
|
839
877
|
}
|
|
840
878
|
}
|
|
@@ -848,6 +886,7 @@ module.exports = {
|
|
|
848
886
|
loadGrokAuthEntry,
|
|
849
887
|
readGrokAccessToken,
|
|
850
888
|
isGrokAccessTokenExpired,
|
|
889
|
+
grokTokenSubject,
|
|
851
890
|
resolveGrokOidcClientId,
|
|
852
891
|
resolveGrokOidcIssuer,
|
|
853
892
|
resolveGrokTokenEndpoint,
|
|
@@ -44,6 +44,15 @@ function sanitizeBucketForUpload(bucket) {
|
|
|
44
44
|
} else {
|
|
45
45
|
delete sanitized.credits;
|
|
46
46
|
}
|
|
47
|
+
// project_key (contract v2, 2026-11-03): optional pass-through, string only
|
|
48
|
+
// (anything else is a producer bug — drop the field, not the row); the
|
|
49
|
+
// server applies the basename/control-char cleanup. Trimmed-empty is
|
|
50
|
+
// dropped so unattributed rows keep the old wire shape.
|
|
51
|
+
if (typeof bucket.project_key === "string" && bucket.project_key.trim()) {
|
|
52
|
+
sanitized.project_key = bucket.project_key;
|
|
53
|
+
} else {
|
|
54
|
+
delete sanitized.project_key;
|
|
55
|
+
}
|
|
47
56
|
return sanitized;
|
|
48
57
|
}
|
|
49
58
|
|