@lks347/dsh-oauth 0.0.0-stage → 1.0.2

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 (67) hide show
  1. package/README.en.md +155 -0
  2. package/README.md +101 -2
  3. package/app.js +1045 -0
  4. package/auth.html +80 -0
  5. package/client.js +31 -0
  6. package/cordis.patch.yml +4 -0
  7. package/docs/CONNECTIONS.md +77 -0
  8. package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
  9. package/docs/RELEASE-1.0.1.md +48 -0
  10. package/docs/RELEASE-1.0.2.md +8 -0
  11. package/docs/VALIDATION.md +59 -0
  12. package/docs/evidence/live-1.0.1.json +135 -0
  13. package/docs/evidence/release-1.0.1.json +38 -0
  14. package/index.html +43 -0
  15. package/package.json +64 -4
  16. package/providers.js +73 -0
  17. package/scripts/check-upstreams.mjs +27 -0
  18. package/scripts/link-peers.js +38 -0
  19. package/scripts/verify-browser.mjs +297 -0
  20. package/scripts/verify-host.mjs +431 -0
  21. package/scripts/verify-live.mjs +268 -0
  22. package/scripts/verify-package.mjs +168 -0
  23. package/scripts/verify-persistence.mjs +307 -0
  24. package/scripts/verify-subscriptions-ui.mjs +321 -0
  25. package/src/account.js +85 -0
  26. package/src/account.test.js +52 -0
  27. package/src/authorization.js +199 -0
  28. package/src/authorization.test.js +332 -0
  29. package/src/catalog.js +180 -0
  30. package/src/catalog.test.js +146 -0
  31. package/src/chat-recovery.js +110 -0
  32. package/src/chat-recovery.test.js +261 -0
  33. package/src/connection-runtime.js +129 -0
  34. package/src/connection-runtime.test.js +244 -0
  35. package/src/connections.js +70 -0
  36. package/src/grants.js +104 -0
  37. package/src/grants.test.js +340 -0
  38. package/src/index.js +676 -0
  39. package/src/local-imports.js +263 -0
  40. package/src/local-imports.test.js +201 -0
  41. package/src/media.js +152 -0
  42. package/src/models.js +610 -0
  43. package/src/models.test.js +503 -0
  44. package/src/profile-store.js +51 -0
  45. package/src/pulls.js +100 -0
  46. package/src/pulls.test.js +156 -0
  47. package/src/qwen.js +141 -0
  48. package/src/qwen.test.js +35 -0
  49. package/src/request-errors.js +50 -0
  50. package/src/request-errors.test.js +131 -0
  51. package/src/routes.js +47 -0
  52. package/src/routes.test.js +136 -0
  53. package/src/subscription-models.test.js +160 -0
  54. package/src/usage/aggregators.js +292 -0
  55. package/src/usage/aggregators.test.js +316 -0
  56. package/src/usage/core.js +68 -0
  57. package/src/usage/index.js +93 -0
  58. package/src/usage/official.js +339 -0
  59. package/src/usage/official.test.js +273 -0
  60. package/src/usage/service.test.js +89 -0
  61. package/src/xai-browser.js +272 -0
  62. package/src/xai-browser.test.js +256 -0
  63. package/src/xai-login.js +121 -0
  64. package/src/xai-login.test.js +259 -0
  65. package/styles.css +364 -0
  66. package/theme.js +118 -0
  67. package/upstreams.json +10 -0
@@ -0,0 +1,339 @@
1
+ import { UsageError } from './core.js';
2
+
3
+ // Wire contracts are pinned in the external quota research reports (2026-11-16).
4
+ // These readers never refresh credentials, discover local files, onboard projects,
5
+ // or issue inference requests. The caller owns transport, identity and lifecycle.
6
+ export const officialUsageIds = Object.freeze([
7
+ 'openai-codex', 'anthropic', 'github-copilot', 'kimi-coding', 'minimax',
8
+ 'zai', 'aliyun-token-plan', 'google-antigravity', 'google-gemini-cli', 'xai', 'nous',
9
+ ]);
10
+
11
+ const record = value => value !== null && typeof value === 'object' && !Array.isArray(value);
12
+ const array = value => Array.isArray(value) ? value.slice(0, 200) : [];
13
+ const compact = value => Object.fromEntries(Object.entries(value).filter(([, item]) => item !== undefined));
14
+ function number(value) {
15
+ if (typeof value !== 'number' && !(typeof value === 'string' && /^-?\d+(?:\.\d+)?$/.test(value))) return undefined;
16
+ const result = Number(value);
17
+ return Number.isFinite(result) && Math.abs(result) <= Number.MAX_SAFE_INTEGER ? result : undefined;
18
+ }
19
+ const positive = value => { const n = number(value); return n !== undefined && n >= 0 ? n : undefined; };
20
+ function label(value) {
21
+ return typeof value === 'string' && value.trim() ? value.replace(/[\x00-\x1f\x7f]/g, ' ').trim().slice(0, 160) : undefined;
22
+ }
23
+ function date(value, unit = 'iso') {
24
+ let time;
25
+ if (unit === 'iso') {
26
+ if (typeof value !== 'string' || !/^\d{4}-\d{2}-\d{2}(?:T.*)?$/.test(value)) return undefined;
27
+ time = Date.parse(value);
28
+ } else { const n = number(value); if (n !== undefined) time = n * (unit === 'seconds' ? 1000 : 1); }
29
+ return Number.isFinite(time) && time > 0 && time <= 8.64e15 ? new Date(time).toISOString() : undefined;
30
+ }
31
+ function percentage(id, title, used, extra = {}) {
32
+ used = positive(used);
33
+ return used === undefined ? undefined : compact({ id, label: title, unit: 'percent', usedPercent: used, remainingPercent: 100 - used, ...extra });
34
+ }
35
+ function counts(id, title, unit, used, limit, remaining, extra = {}) {
36
+ used = positive(used); limit = positive(limit); remaining = number(remaining);
37
+ if (used === undefined && remaining !== undefined && limit !== undefined && remaining <= limit) used = limit - remaining;
38
+ if (remaining === undefined && used !== undefined && limit !== undefined) remaining = limit - used;
39
+ if (used === undefined && remaining === undefined && !extra.unlimited) return undefined;
40
+ return compact({ id, label: title, unit, used, limit, remaining, ...extra });
41
+ }
42
+ function wallet(id, title, amount, unit = 'money', currency) {
43
+ amount = number(amount);
44
+ return amount === undefined ? undefined : compact({ id, label: title, amount, unit, currency });
45
+ }
46
+ function plan(name, id = name) { name = label(name); id = label(id); return name || id ? compact({ name, id }) : undefined; }
47
+ function result(windows = [], balances = [], extra = {}) {
48
+ windows = windows.filter(Boolean); balances = balances.filter(Boolean);
49
+ if (!windows.length && !balances.length && !extra.plan) throw new UsageError('invalid-response', 'The provider returned no recognized usage data.');
50
+ return compact({ windows, balances, ...extra, status: windows.length || balances.length ? (extra.status ?? 'fresh') : 'partial' });
51
+ }
52
+ function requireRecord(data) { if (!record(data)) throw new UsageError('invalid-response', 'The provider usage response is invalid.'); return data; }
53
+ function token(value, code = 'credential-required') {
54
+ if (typeof value !== 'string' || !value.trim() || /[\r\n]/.test(value)) throw new UsageError(code, 'The required usage credential is unavailable.');
55
+ return value;
56
+ }
57
+ const bearer = access => ({ Authorization: `Bearer ${token(access)}`, Accept: 'application/json' });
58
+ const scope = ctx => [ctx.organizationId && `organization:${label(ctx.organizationId)}`, ctx.projectId && `project:${label(ctx.projectId)}`, ctx.workspaceId && `workspace:${label(ctx.workspaceId)}`].filter(Boolean).join('/') || 'account';
59
+
60
+ export function parseCodexUsage(data, ctx = {}) {
61
+ requireRecord(data);
62
+ const windows = [];
63
+ const read = (rate, prefix = 'codex', title = 'Codex') => {
64
+ if (!record(rate)) return;
65
+ for (const [key, name] of [['primary_window', 'Primary'], ['secondary_window', 'Secondary']]) {
66
+ const row = rate[key]; if (!record(row)) continue;
67
+ const delay = positive(row.reset_after_seconds);
68
+ const resetAt = date(row.reset_at, 'seconds') ?? (delay !== undefined && number(ctx.now) !== undefined ? date(ctx.now + delay * 1000, 'milliseconds') : undefined);
69
+ windows.push(percentage(`${prefix}:${key}`, `${title} ${name}`, row.used_percent, { resetAt, windowSeconds: positive(row.limit_window_seconds), scope: 'account' }));
70
+ }
71
+ };
72
+ read(data.rate_limit);
73
+ for (const [i, row] of array(data.additional_rate_limits).entries()) if (record(row)) read(row.rate_limit, `codex:additional:${i}`, label(row.limit_name) ?? label(row.metered_feature) ?? 'Additional allowance');
74
+ const balances = [];
75
+ if (record(data.credits)) {
76
+ balances.push(wallet('codex:credits', 'Codex credits', data.credits.balance, 'credits'));
77
+ if (data.credits.unlimited === true) windows.push({ id: 'codex:credits-unlimited', label: 'Codex credits', unit: 'credits', unlimited: true, scope: 'account' });
78
+ }
79
+ const control = data.spend_control?.individual_limit;
80
+ if (record(control)) windows.push(counts('codex:spend-control', 'Individual spending limit', 'credits', control.used, control.limit, control.remaining, { resetAt: date(control.reset_at, 'seconds'), scope: 'individual' }));
81
+ return result(windows, balances, { plan: plan(data.plan_type), notes: data.rate_limit?.limit_reached === true ? ['The provider reports an exhausted allowance.'] : undefined });
82
+ }
83
+
84
+ export function parseClaudeUsage(data) {
85
+ requireRecord(data);
86
+ const windows = [];
87
+ for (const [id, title, duration] of [['five_hour', 'Five-hour allowance', 18000], ['seven_day', 'Weekly allowance', 604800], ['seven_day_sonnet', 'Sonnet weekly allowance', 604800], ['seven_day_opus', 'Opus weekly allowance', 604800], ['seven_day_oauth_apps', 'OAuth apps weekly allowance', 604800]]) {
88
+ const row = data[id]; if (!record(row)) continue;
89
+ // The generic weekly field supersedes its OAuth-app fallback, not model-specific buckets.
90
+ if (id === 'seven_day_oauth_apps' && record(data.seven_day)) continue;
91
+ windows.push(percentage(id, title, row.utilization, { resetAt: date(row.resets_at), windowSeconds: duration, scope: id.includes('sonnet') ? 'model:sonnet' : id.includes('opus') ? 'model:opus' : 'account' }));
92
+ }
93
+ for (const [i, row] of array(data.limits).entries()) if (record(row)) windows.push(percentage(`claude:limit:${i}`, label(row.scope?.model?.display_name) ?? 'Model allowance', row.utilization, { resetAt: date(row.resets_at), scope: label(row.scope?.model?.id) }));
94
+ const extra = data.extra_usage;
95
+ const balances = [];
96
+ if (record(extra) && extra.is_enabled === true) {
97
+ const used = positive(extra.used_credits), limit = positive(extra.monthly_limit);
98
+ windows.push(counts('claude:extra-usage', 'Extra usage spending cap', 'money', used === undefined ? undefined : used / 100, limit === undefined ? undefined : limit / 100, undefined, { scope: 'extra-usage' }));
99
+ if (used !== undefined && limit !== undefined) balances.push(wallet('claude:extra-remaining', 'Extra usage budget remaining', (limit - used) / 100, 'money', /^[A-Z]{3}$/.test(extra.currency ?? '') ? extra.currency : undefined));
100
+ }
101
+ return result(windows, balances, { notes: record(extra) && extra.is_enabled === true && !extra.currency ? ['Extra usage amounts are converted from cents; the response did not identify a currency.'] : undefined });
102
+ }
103
+
104
+ export function parseCopilotUsage(data) {
105
+ requireRecord(data);
106
+ const windows = [], seen = new Set();
107
+ const resetAt = date(data.quota_reset_date ?? data.quota_reset_date_utc);
108
+ const isCredits = data.token_based_billing === true;
109
+ for (const [id, row] of Object.entries(record(data.quota_snapshots) ? data.quota_snapshots : {}).slice(0, 200)) {
110
+ if (!record(row)) continue;
111
+ const pool = label(row.quota_id); if (pool && seen.has(pool)) continue;
112
+ if (pool) seen.add(pool);
113
+ const unit = isCredits ? 'credits' : 'requests';
114
+ if (row.unlimited === true) { windows.push({ id: `copilot:${id}`, label: label(id) ?? 'Copilot', unit, unlimited: true, scope: 'account' }); continue; }
115
+ const limit = positive(row.entitlement), remaining = positive(row.remaining), used = positive(row.credits_used);
116
+ if (limit === 0 && remaining === 0) {
117
+ if (used !== undefined) windows.push(counts(`copilot:${id}`, label(id) ?? 'Copilot credits', 'credits', used, undefined, undefined, { scope: 'account', resetAt }));
118
+ continue;
119
+ }
120
+ const rowWindow = counts(`copilot:${id}`, label(id) ?? 'Copilot', unit, isCredits ? used : undefined, limit, remaining, { scope: 'account', resetAt });
121
+ const rp = positive(row.percent_remaining);
122
+ if (rowWindow) windows.push({ ...rowWindow, ...(rp !== undefined && rp <= 100 ? { remainingPercent: rp, usedPercent: 100 - rp } : {}) });
123
+ else if (rp !== undefined && rp <= 100) windows.push(percentage(`copilot:${id}`, label(id) ?? 'Copilot', 100 - rp, { scope: 'account', resetAt }));
124
+ }
125
+ return result(windows, [], { plan: plan(data.copilot_plan), notes: isCredits ? ['Copilot reports AI-credit billing; this is not a premium-request count.'] : undefined });
126
+ }
127
+
128
+ export function parseKimiUsage(data) {
129
+ requireRecord(data);
130
+ const windows = [];
131
+ for (const [id, title, duration] of [['limit_5h', 'Five-hour allowance', 18000], ['limit_7d', 'Weekly allowance', 604800], ['limit_month_total', 'Monthly total allowance'], ['limit_month_code', 'Monthly coding allowance']]) {
132
+ const row = data.usages?.[id]; if (!record(row)) continue;
133
+ const ratio = positive(row.used_ratio);
134
+ windows.push(percentage(id, title, ratio === undefined ? undefined : ratio * 100, { resetAt: date(row.reset_time), windowSeconds: duration, scope: id === 'limit_month_code' ? 'coding' : 'account' }));
135
+ }
136
+ const balances = [], extra = data.boosterWallet;
137
+ if (record(extra) && extra.balance?.type === 'BOOSTER') {
138
+ const currency = label(extra.monthlyChargeLimit?.currency) ?? label(extra.monthlyUsed?.currency);
139
+ const remaining = number(extra.balance.amountLeft), total = number(extra.balance.amount);
140
+ // The wire amount is 1,000,000 fixed-point units per cent, i.e. 100,000,000 per currency unit.
141
+ balances.push(wallet('kimi:booster', 'Extra usage wallet', remaining === undefined ? undefined : remaining / 100_000_000, 'money', currency));
142
+ if (total !== undefined && remaining !== undefined) windows.push(counts('kimi:booster-budget', 'Extra usage wallet allocation', 'money', undefined, total / 100_000_000, remaining / 100_000_000, { scope: 'booster' }));
143
+ if (extra.monthlyChargeLimitEnabled === true) {
144
+ const used = positive(extra.monthlyUsed?.priceInCents), limit = positive(extra.monthlyChargeLimit?.priceInCents);
145
+ windows.push(counts('kimi:extra-monthly', 'Extra usage monthly cap', 'money', used === undefined ? undefined : used / 100, limit === undefined ? undefined : limit / 100, undefined, { scope: 'booster' }));
146
+ }
147
+ }
148
+ return result(windows, balances);
149
+ }
150
+
151
+ export function resolveMiniMaxCounts(reported, total, remainingPercent) {
152
+ reported = positive(reported); total = positive(total); remainingPercent = positive(remainingPercent);
153
+ if (reported === undefined || !total || reported > total) return undefined;
154
+ let remaining = reported;
155
+ if (remainingPercent !== undefined) {
156
+ const asRemaining = Math.abs(reported / total * 100 - remainingPercent);
157
+ const asUsed = Math.abs((total - reported) / total * 100 - remainingPercent);
158
+ if (Math.min(asRemaining, asUsed) > 1) return undefined;
159
+ if (asUsed < asRemaining) remaining = total - reported;
160
+ }
161
+ return { used: total - remaining, limit: total, remaining };
162
+ }
163
+
164
+ export function parseMiniMaxUsage(data, ctx = {}) {
165
+ requireRecord(data);
166
+ if (data.base_resp?.status_code !== undefined && data.base_resp.status_code !== 0) throw new UsageError('invalid-response', 'MiniMax could not return subscription usage.');
167
+ const windows = [], notes = [];
168
+ for (const [i, row] of array(data.model_remains).entries()) {
169
+ if (!record(row)) continue;
170
+ if (number(row.current_interval_total_count) === 0 && number(row.current_weekly_total_count) === 0 && number(row.current_interval_status) === 3 && number(row.current_weekly_status) === 3) { notes.push('A service not included in this plan was omitted.'); continue; }
171
+ for (const [kind, startKey, endKey, remainingKey] of [['interval', 'start_time', 'end_time', 'remains_time'], ['weekly', 'weekly_start_time', 'weekly_end_time', 'weekly_remains_time']]) {
172
+ const id = `minimax:${i}:${kind}`, title = `${label(row.model_name) ?? 'Service'} ${kind}`;
173
+ const start = positive(row[startKey]), end = positive(row[endKey]), wait = positive(row[remainingKey]);
174
+ const extra = compact({ scope: label(row.model_name), resetAt: date(end, 'milliseconds') ?? (wait !== undefined && number(ctx.now) !== undefined ? date(ctx.now + wait, 'milliseconds') : undefined), windowSeconds: start !== undefined && end !== undefined && end > start ? (end - start) / 1000 : undefined });
175
+ if (number(row[`current_${kind}_status`]) === 3) { windows.push({ id, label: title, unit: 'requests', unlimited: true, ...extra }); continue; }
176
+ const rp = positive(row[`current_${kind}_remaining_percent`]);
177
+ const values = resolveMiniMaxCounts(row[`current_${kind}_usage_count`], row[`current_${kind}_total_count`], rp);
178
+ if (values) windows.push({ id, label: title, unit: 'requests', ...values, ...(rp !== undefined ? { remainingPercent: rp, usedPercent: 100 - rp } : {}), ...extra });
179
+ else if (rp !== undefined && rp <= 100) windows.push(percentage(id, title, 100 - rp, extra));
180
+ if (values && rp === undefined) notes.push('MiniMax legacy counters are interpreted as remaining counts.');
181
+ }
182
+ const boost = positive(row.weekly_boost_permille);
183
+ if (boost !== undefined && boost !== 1000) notes.push(`Weekly allowance multiplier: ${boost / 1000}. Percentages retain the provider's base allowance.`);
184
+ }
185
+ return result(windows, [], { notes: notes.length ? [...new Set(notes)] : undefined });
186
+ }
187
+
188
+ export function parseZaiUsage(data, ctx = {}) {
189
+ requireRecord(data);
190
+ if (data.success === false || (data.code !== undefined && data.code !== 200)) throw new UsageError('invalid-response', 'The Coding Plan usage request was not successful.');
191
+ const windows = [];
192
+ for (const [i, row] of array(data.data?.limits).entries()) {
193
+ if (!record(row) || !['TOKENS_LIMIT', 'CREDIT_LIMIT', 'TIME_LIMIT'].includes(row.type)) continue;
194
+ const duration = row.unit === 3 ? 3600 : row.unit === 6 ? 604800 : undefined;
195
+ const n = positive(row.number);
196
+ const extra = { scope: scope(ctx), resetAt: date(row.nextResetTime, 'milliseconds'), windowSeconds: duration && n ? duration * n : undefined };
197
+ const title = row.type === 'TIME_LIMIT' ? 'Tool allowance' : 'Coding Plan allowance';
198
+ if (row.type === 'TIME_LIMIT') {
199
+ const w = counts(`zai:${i}`, title, 'requests', row.currentValue, row.usage, row.remaining, extra);
200
+ windows.push(w ?? percentage(`zai:${i}`, title, row.percentage, extra));
201
+ } else windows.push(percentage(`zai:${i}`, title, row.percentage, extra));
202
+ }
203
+ return result(windows, [], { plan: plan(data.data?.level) });
204
+ }
205
+
206
+ export function parseAliyunUsage(data) {
207
+ requireRecord(data);
208
+ let body = data;
209
+ // Console gateway envelopes are bounded; never recursively search arbitrary documents.
210
+ for (let i = 0; i < 7; i++) {
211
+ const badCode = body.success !== true && body.successResponse !== true && body.errorCode !== undefined && !['0', '200'].includes(String(body.errorCode));
212
+ if (body.success === false || body.successResponse === false || body.failed === true || badCode || array(body.ret).some(value => typeof value === 'string' && !value.startsWith('SUCCESS::'))) throw new UsageError('invalid-response', 'The Console did not return Token Plan usage.');
213
+ if (Object.keys(body).some(key => /^per\d+(Hour|Day|Week|Month)Percentage$/.test(key)) || body.hasQuotaData === false) break;
214
+ const nested = Object.hasOwn(body, 'DataV2') ? body.DataV2 : body.data;
215
+ if (!record(nested)) break;
216
+ body = nested;
217
+ }
218
+ if (body.hasQuotaData === false) throw new UsageError('unavailable', 'The Console has no quota data for this account.');
219
+ const windows = [];
220
+ for (const [key, value] of Object.entries(body)) {
221
+ const m = /^per(\d+)(Hour|Day|Week|Month)Percentage$/.exec(key); if (!m) continue;
222
+ const ratio = positive(value); if (ratio === undefined) continue;
223
+ const prefix = `per${m[1]}${m[2]}`;
224
+ const seconds = { Hour: 3600, Day: 86400, Week: 604800 }[m[2]];
225
+ windows.push(percentage(prefix, `${m[1]} ${m[2]} allowance`, ratio * 100, { resetAt: date(body[`${prefix}ResetTime`], 'milliseconds'), windowSeconds: seconds ? Number(m[1]) * seconds : undefined, scope: 'personal-token-plan' }));
226
+ }
227
+ return result(windows);
228
+ }
229
+
230
+ export function parseAntigravityUsage(data, ctx = {}) {
231
+ requireRecord(data);
232
+ const body = record(data.response) ? data.response : record(data.summary) ? data.summary : data;
233
+ const windows = [];
234
+ for (const [gi, group] of array(body.groups).entries()) for (const [bi, row] of array(group?.buckets).entries()) {
235
+ if (!record(row) || row.disabled === true) continue;
236
+ const fraction = positive(row.remainingFraction ?? row.remaining?.remainingFraction ?? (row.remaining?.case === 'remainingFraction' ? row.remaining.value : undefined));
237
+ if (fraction === undefined || fraction > 1) continue;
238
+ const id = label(row.bucketId ?? row.id); if (!id) continue;
239
+ windows.push(percentage(`antigravity:${gi}:${bi}:${id}`, [label(group.displayName ?? group.name), label(row.displayName ?? row.name) ?? id].filter(Boolean).join(' / '), (1 - fraction) * 100, { resetAt: date(row.resetTime), scope: scope(ctx) }));
240
+ }
241
+ return result(windows, [], { notes: ['Read-only remote quota summary; no project onboarding is performed.'] });
242
+ }
243
+
244
+ export function parseGeminiUsage(data, ctx = {}) {
245
+ requireRecord(data);
246
+ const windows = [];
247
+ for (const [i, row] of array(data.buckets).entries()) {
248
+ if (!record(row)) continue;
249
+ const fraction = positive(row.remainingFraction); if (fraction === undefined || fraction > 1) continue;
250
+ windows.push(percentage(`gemini:${i}`, label(row.modelId) ?? 'Code Assist allowance', (1 - fraction) * 100, { resetAt: date(row.resetTime), scope: `${scope(ctx)}${label(row.tokenType) ? `/${label(row.tokenType)}` : ''}` }));
251
+ // remainingAmount is deliberately not called tokens or requests: tokenType is not a stable unit contract.
252
+ }
253
+ const balances = [];
254
+ for (const [i, row] of array(data.remainingCredits).entries()) if (record(row)) balances.push(wallet(`gemini:credits:${i}`, label(row.creditType) ?? 'AI credits', row.creditAmount, 'credits'));
255
+ return result(windows, balances);
256
+ }
257
+
258
+ export function parseXaiUsage(data) {
259
+ requireRecord(data); const config = requireRecord(data.config);
260
+ const end = date(config.currentPeriod?.end) ?? date(config.billingPeriodEnd);
261
+ const start = date(config.currentPeriod?.end) ? date(config.currentPeriod?.start) : date(config.billingPeriodStart);
262
+ const extra = { resetAt: end, windowSeconds: start && end && Date.parse(end) > Date.parse(start) ? (Date.parse(end) - Date.parse(start)) / 1000 : undefined, scope: 'account' };
263
+ const windows = [percentage('xai:included', 'Included allowance', config.creditUsagePercent, extra)];
264
+ for (const [i, row] of array(config.productUsage).entries()) if (record(row)) windows.push(percentage(`xai:product:${i}`, label(row.product) ?? 'Product usage', row.usagePercent, { ...extra, scope: `product:${label(row.product) ?? i}` }));
265
+ let cents = number(config.prepaidBalance?.val);
266
+ // Proto3's present empty Cent object explicitly encodes zero, unlike an absent wallet.
267
+ if (record(config.prepaidBalance) && !Object.keys(config.prepaidBalance).length) cents = 0;
268
+ return result(windows, [wallet('xai:prepaid', 'Prepaid balance', cents === undefined ? undefined : cents / 100, 'money', 'USD')], { plan: plan(config.subscriptionTier ?? data.subscriptionTier) });
269
+ }
270
+
271
+ export function parseNousUsage(data) {
272
+ requireRecord(data);
273
+ const windows = [], balances = [];
274
+ for (const [i, row] of array(data.usage_window?.gauges).entries()) {
275
+ if (!record(row)) continue;
276
+ const bp = positive(row.used_bp); if (bp === undefined) continue;
277
+ windows.push(percentage(`nous:${label(row.id) ?? i}`, label(row.label) ?? 'Subscription allowance', bp / 100, { resetAt: date(row.resets_at_ms, 'milliseconds'), scope: label(row.scope) }));
278
+ }
279
+ const subscription = data.subscription, access = data.paid_service_access;
280
+ if (record(subscription)) {
281
+ const cap = positive(subscription.monthly_credits), remaining = positive(subscription.credits_remaining);
282
+ balances.push(wallet('nous:subscription', 'Subscription credits', access?.subscription_credits_remaining ?? remaining, 'money', 'USD'));
283
+ balances.push(wallet('nous:rollover', 'Rollover credits', subscription.rollover_credits, 'money', 'USD'));
284
+ if (cap && remaining !== undefined && remaining <= cap) windows.push(counts('nous:monthly-credits', 'Monthly subscription credits', 'money', undefined, cap, remaining, { resetAt: date(subscription.current_period_end), scope: 'subscription' }));
285
+ }
286
+ if (record(access)) {
287
+ balances.push(wallet('nous:purchased', 'Purchased credits', access.purchased_credits_remaining, 'money', 'USD'));
288
+ balances.push(wallet('nous:total', 'Total usable credits', access.total_usable_credits, 'money', 'USD'));
289
+ }
290
+ return result(windows, balances, { plan: plan(subscription?.plan), notes: ['Total usable credits overlap the component balances; do not add them together.'] });
291
+ }
292
+
293
+ export async function fetchOfficialUsage(id, ctx) {
294
+ if (!officialUsageIds.includes(id)) throw new UsageError('unsupported', 'This provider has no official usage adapter.');
295
+ if (!ctx || typeof ctx.request !== 'function') throw new UsageError('unavailable', 'Usage transport is unavailable.');
296
+ const request = ctx.request;
297
+ switch (id) {
298
+ case 'openai-codex': {
299
+ const accountId = label(ctx.rawGrant?.accountId ?? ctx.rawGrant?.account_id);
300
+ return parseCodexUsage(await request('https://chatgpt.com/backend-api/wham/usage', { headers: { ...bearer(ctx.access), ...(accountId ? { 'ChatGPT-Account-Id': accountId } : {}) } }), ctx);
301
+ }
302
+ case 'anthropic': {
303
+ const rawScopes = ctx.rawGrant?.scope ?? ctx.rawGrant?.scopes;
304
+ const scopes = typeof rawScopes === 'string' ? rawScopes.split(/\s+/) : rawScopes;
305
+ if (Array.isArray(scopes) && !scopes.includes('user:profile')) throw new UsageError('scope-required', 'Claude usage requires the user:profile scope.');
306
+ return parseClaudeUsage(await request('https://api.anthropic.com/api/oauth/usage', { headers: { ...bearer(ctx.access), 'anthropic-beta': 'oauth-2025-04-20' } }));
307
+ }
308
+ case 'github-copilot':
309
+ return parseCopilotUsage(await request('https://api.github.com/copilot_internal/user', { headers: { Authorization: `token ${token(ctx.rawGrant?.access, 'source-credential-required')}`, Accept: 'application/json', 'Editor-Version': 'vscode/1.96.2', 'Editor-Plugin-Version': 'copilot-chat/0.26.7', 'User-Agent': 'GitHubCopilotChat/0.26.7', 'X-Github-Api-Version': '2025-04-01' } }));
310
+ case 'kimi-coding':
311
+ return parseKimiUsage(await request(`https://${ctx.region === 'cn' ? 'api.kimi.com' : 'api.kimi.ai'}/coding/v1/usages`, { headers: bearer(ctx.access) }));
312
+ case 'minimax':
313
+ return parseMiniMaxUsage(await request(`https://${ctx.region === 'cn' ? 'api.minimax.cn' : 'api.minimax.io'}/v1/token_plan/remains`, { headers: bearer(ctx.access) }), ctx);
314
+ case 'zai': {
315
+ const team = Boolean(ctx.organizationId || ctx.projectId);
316
+ if (team && (!ctx.organizationId || !ctx.projectId)) throw new UsageError('scope-required', 'Team usage requires both organization and project.');
317
+ const headers = { authorization: token(ctx.access), Accept: 'application/json', ...(team ? { 'bigmodel-organization': token(ctx.organizationId), 'bigmodel-project': token(ctx.projectId) } : {}) };
318
+ return parseZaiUsage(await request(`https://${ctx.region === 'cn' ? 'bigmodel.cn' : 'api.z.ai'}/api/monitor/usage/quota/limit${team ? '?type=2' : ''}`, { headers }), ctx);
319
+ }
320
+ case 'aliyun-token-plan': {
321
+ const access = token(ctx.billingAccess, 'billing-credential-required');
322
+ const cn = ctx.region === 'cn', region = cn ? 'cn-beijing' : 'ap-southeast-1';
323
+ const api = 'zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage';
324
+ const params = { Api: api, V: '1.0', Data: { cornerstoneParam: { protocol: 'V2', console: 'ONE_CONSOLE', productCode: 'p_efm', switchUserType: 3, consoleSite: 'BAILIAN_ALIYUN' } } };
325
+ const body = new URLSearchParams({ params: JSON.stringify(params), region }).toString();
326
+ return parseAliyunUsage(await request(`https://${cn ? 'bailian-cs.console.aliyun.com' : 'bailian-singapore-cs.alibabacloud.com'}/cli/api.json?action=${cn ? 'BroadScopeAspnGateway' : 'IntlBroadScopeAspnGateway'}&product=sfm_bailian&api=${encodeURIComponent(api)}`, { method: 'POST', headers: { ...bearer(access), 'Content-Type': 'application/x-www-form-urlencoded' }, body }));
327
+ }
328
+ case 'google-antigravity':
329
+ return parseAntigravityUsage(await request('https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary', { method: 'POST', headers: { ...bearer(ctx.access), 'Content-Type': 'application/json', 'User-Agent': `antigravity/hub/2.9.1 ${process.platform === 'linux' ? 'linux' : 'darwin'}/${process.arch === 'arm64' ? 'arm64' : 'amd64'}` }, body: JSON.stringify(ctx.projectId ? { project: token(ctx.projectId) } : {}) }), ctx);
330
+ case 'google-gemini-cli': {
331
+ if (!ctx.projectId) throw new UsageError('scope-required', 'Code Assist usage requires its authorized project.');
332
+ return parseGeminiUsage(await request('https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuota', { method: 'POST', headers: { ...bearer(ctx.access), 'Content-Type': 'application/json' }, body: JSON.stringify({ project: token(ctx.projectId) }) }), ctx);
333
+ }
334
+ case 'xai':
335
+ return parseXaiUsage(await request('https://cli-chat-proxy.grok.com/v1/billing?format=credits', { headers: { ...bearer(ctx.access), 'x-xai-token-auth': 'xai-grok-cli' } }));
336
+ case 'nous':
337
+ return parseNousUsage(await request('https://portal.nousresearch.com/api/oauth/account', { headers: bearer(ctx.rawGrant?.type === 'api_key' ? token(ctx.billingAccess, 'needs-permission') : ctx.access) }));
338
+ }
339
+ }
@@ -0,0 +1,273 @@
1
+ import test from 'node:test';
2
+ import assert from 'node:assert/strict';
3
+ import {
4
+ officialUsageIds, fetchOfficialUsage, parseCodexUsage, parseClaudeUsage, parseCopilotUsage,
5
+ parseKimiUsage, parseMiniMaxUsage, resolveMiniMaxCounts, parseZaiUsage, parseAliyunUsage,
6
+ parseAntigravityUsage, parseGeminiUsage, parseXaiUsage, parseNousUsage,
7
+ } from './official.js';
8
+
9
+ const NOW = Date.parse('2026-11-16T12:00:00Z');
10
+ const RESET = '2026-11-17T12:00:00.000Z';
11
+ const fixtures = {
12
+ 'openai-codex': { plan_type: 'plus', rate_limit: { primary_window: { used_percent: 12.5, limit_window_seconds: 18000, reset_at: Date.parse(RESET) / 1000 } }, credits: { balance: '1.25', has_credits: true } },
13
+ anthropic: { five_hour: { utilization: 30, resets_at: RESET }, seven_day: null },
14
+ 'github-copilot': { copilot_plan: 'individual', quota_reset_date: '2026-12-01', quota_snapshots: { premium_interactions: { entitlement: 300, remaining: 240, percent_remaining: 80, quota_id: 'premium' } } },
15
+ 'kimi-coding': { usages: { limit_5h: { used_ratio: 0.125, reset_time: RESET } } },
16
+ minimax: { model_remains: [{ model_name: 'general', current_interval_total_count: 1000, current_interval_usage_count: 200, current_interval_remaining_percent: 80, start_time: NOW, end_time: NOW + 18000000 }] },
17
+ zai: { code: 200, success: true, data: { level: 'pro', limits: [{ type: 'TOKENS_LIMIT', unit: 3, number: 5, percentage: 30, nextResetTime: Date.parse(RESET) }] } },
18
+ 'aliyun-token-plan': { data: { success: true, DataV2: { success: true, data: { per1MonthPercentage: 0.25, per1MonthResetTime: Date.parse(RESET) } } } },
19
+ 'google-antigravity': { summary: { groups: [{ displayName: 'Model group', buckets: [{ bucketId: 'weekly', displayName: 'Week', remaining: { remainingFraction: 0.75 }, resetTime: RESET }] }] } },
20
+ 'google-gemini-cli': { buckets: [{ modelId: 'model-a', remainingFraction: 0.8, remainingAmount: '120', tokenType: 'REQUESTS', resetTime: RESET }] },
21
+ xai: { config: { creditUsagePercent: 25, subscriptionTier: 'supergrok', currentPeriod: { start: '2026-11-01T00:00:00Z', end: '2026-12-01T00:00:00Z' }, prepaidBalance: { val: '1234' } } },
22
+ nous: { subscription: { plan: 'plus', monthly_credits: 100, credits_remaining: 65, current_period_end: RESET }, usage_window: { gauges: [{ id: 'daily', label: 'Daily', scope: 'all', used_bp: 1250, resets_at_ms: Date.parse(RESET) }] }, paid_service_access: { purchased_credits_remaining: 10, total_usable_credits: 75 } },
23
+ };
24
+ const parsers = {
25
+ 'openai-codex': parseCodexUsage, anthropic: parseClaudeUsage, 'github-copilot': parseCopilotUsage,
26
+ 'kimi-coding': parseKimiUsage, minimax: parseMiniMaxUsage, zai: parseZaiUsage,
27
+ 'aliyun-token-plan': parseAliyunUsage, 'google-antigravity': parseAntigravityUsage,
28
+ 'google-gemini-cli': parseGeminiUsage, xai: parseXaiUsage, nous: parseNousUsage,
29
+ };
30
+
31
+ test('all official provider IDs have a parser and a sanitized fixture', () => {
32
+ assert.deepEqual([...officialUsageIds].sort(), Object.keys(fixtures).sort());
33
+ for (const id of officialUsageIds) {
34
+ const input = structuredClone(fixtures[id]);
35
+ const before = JSON.stringify(input);
36
+ const out = parsers[id](input, { now: NOW, projectId: 'project-fixture' });
37
+ assert.ok(out.windows.length || out.balances.length, id);
38
+ assert.equal(JSON.stringify(input), before, `${id}: parser must be pure`);
39
+ assert.equal(out.status, 'fresh');
40
+ assert.equal(JSON.stringify(out).includes('undefined'), false);
41
+ }
42
+ });
43
+
44
+ for (const id of officialUsageIds) {
45
+ test(`${id}: unknown, null, and error-only bodies never become zero quota`, () => {
46
+ for (const input of [{}, null, [], { error: { message: 'sensitive-upstream-message' } }]) {
47
+ assert.throws(() => parsers[id](input, { now: NOW }), error => error.code === 'invalid-response' && !error.message.includes('sensitive'));
48
+ }
49
+ });
50
+ test(`${id}: fixed issuer and selected identity are used by the injected transport`, async () => {
51
+ const calls = [];
52
+ const ctx = {
53
+ access: 'synthetic-access', rawGrant: { access: 'synthetic-github-long-token', accountId: 'account-fixture', scope: 'user:profile user:inference', resourceUrl: 'https://untrusted.example' },
54
+ billingAccess: 'synthetic-console-token', projectId: 'project-fixture', organizationId: 'org-fixture', workspaceId: 'workspace-fixture', region: 'global', now: NOW,
55
+ request: async (url, options) => { calls.push({ url, options }); return structuredClone(fixtures[id]); },
56
+ };
57
+ await fetchOfficialUsage(id, ctx);
58
+ assert.equal(calls.length, 1);
59
+ const { url, options } = calls[0];
60
+ assert.equal(new URL(url).protocol, 'https:');
61
+ assert.equal(url.includes('untrusted.example'), false);
62
+ assert.equal(url.includes('synthetic-'), false);
63
+ assert.equal(/onboard|generate|completions/.test(url), false);
64
+ const header = options.headers.Authorization ?? options.headers.authorization;
65
+ assert.equal(header, id === 'github-copilot' ? 'token synthetic-github-long-token' : id === 'zai' ? 'synthetic-access' : `Bearer ${id === 'aliyun-token-plan' ? 'synthetic-console-token' : 'synthetic-access'}`);
66
+ if (id === 'openai-codex') assert.equal(options.headers['ChatGPT-Account-Id'], 'account-fixture');
67
+ if (id === 'zai') { assert.equal(options.headers['bigmodel-organization'], 'org-fixture'); assert.equal(options.headers['bigmodel-project'], 'project-fixture'); assert.ok(url.endsWith('?type=2')); }
68
+ if (id.startsWith('google-')) { assert.equal(options.method, 'POST'); assert.deepEqual(JSON.parse(options.body), { project: 'project-fixture' }); }
69
+ if (id === 'aliyun-token-plan') { const form = new URLSearchParams(options.body); assert.equal(form.get('region'), 'ap-southeast-1'); assert.equal(JSON.parse(form.get('params')).Api, 'zeldaHttp.apikeyMgr./tokenplan/personal/api/v2/usage'); }
70
+ });
71
+ }
72
+
73
+ test('Codex percentage, duration seconds and absolute reset seconds preserve exact semantics', () => {
74
+ const out = parseCodexUsage(fixtures['openai-codex']);
75
+ assert.equal(out.windows[0].usedPercent, 12.5);
76
+ assert.equal(out.windows[0].remainingPercent, 87.5);
77
+ assert.equal(out.windows[0].windowSeconds, 18000);
78
+ assert.equal(out.windows[0].resetAt, RESET);
79
+ assert.deepEqual(out.balances[0], { id: 'codex:credits', label: 'Codex credits', amount: 1.25, unit: 'credits' });
80
+ });
81
+
82
+ test('Codex additional buckets and relative reset are separate, missing values do not become zero', () => {
83
+ const out = parseCodexUsage({ rate_limit: { primary_window: { reset_after_seconds: 60 } }, additional_rate_limits: [{ limit_name: 'Feature', rate_limit: { secondary_window: { used_percent: 0, reset_after_seconds: 60 } } }] }, { now: NOW });
84
+ assert.equal(out.windows.length, 1);
85
+ assert.equal(out.windows[0].resetAt, new Date(NOW + 60000).toISOString());
86
+ assert.equal(out.windows[0].usedPercent, 0);
87
+ assert.equal(out.windows[0].limit, undefined);
88
+ });
89
+
90
+ test('Claude OAuth usage cents become currency units, explicit null windows stay absent', () => {
91
+ const out = parseClaudeUsage({ five_hour: null, seven_day: { utilization: 0.5 }, extra_usage: { is_enabled: true, used_credits: 123, monthly_limit: 1000, currency: 'USD' } });
92
+ assert.equal(out.windows[0].usedPercent, 0.5);
93
+ assert.equal(out.windows.find(x => x.id === 'claude:extra-usage').used, 1.23);
94
+ assert.equal(out.balances[0].amount, 8.77);
95
+ assert.equal(out.balances[0].currency, 'USD');
96
+ });
97
+
98
+ test('Claude disabled extra usage and invalid scope are not queried or shown', async () => {
99
+ assert.throws(() => parseClaudeUsage({ extra_usage: { is_enabled: false, monthly_limit: 100 } }), { code: 'invalid-response' });
100
+ await assert.rejects(fetchOfficialUsage('anthropic', { access: 'test', rawGrant: { scope: 'user:inference' }, request: () => assert.fail('must not query') }), { code: 'scope-required' });
101
+ });
102
+
103
+ test('Copilot request counters, credit billing, unlimited and zero placeholders remain distinct', () => {
104
+ const requests = parseCopilotUsage(fixtures['github-copilot']);
105
+ assert.equal(requests.windows[0].unit, 'requests');
106
+ assert.equal(requests.windows[0].used, 60);
107
+ assert.equal(requests.windows[0].resetAt, '2026-12-01T00:00:00.000Z');
108
+ const credits = parseCopilotUsage({ token_based_billing: true, copilot_plan: 'business', quota_snapshots: {
109
+ premium_interactions: { entitlement: 0, remaining: 0, percent_remaining: 100, credits_used: 12.5 },
110
+ chat: { unlimited: true },
111
+ } });
112
+ assert.equal(credits.windows[0].used, 12.5);
113
+ assert.equal(credits.windows[0].limit, undefined);
114
+ assert.equal(credits.windows[0].usedPercent, undefined);
115
+ assert.equal(credits.windows[1].unlimited, true);
116
+ assert.equal(credits.windows[1].usedPercent, undefined);
117
+ const placeholder = parseCopilotUsage({ copilot_plan: 'business', quota_snapshots: { chat: { entitlement: 0, remaining: 0, percent_remaining: 100 } } });
118
+ assert.equal(placeholder.windows.length, 0);
119
+ assert.equal(placeholder.status, 'partial');
120
+ });
121
+
122
+ test('Copilot mirrored credit pools are not added twice and short inference token is never fallback', async () => {
123
+ const row = { quota_id: 'one-pool', entitlement: 100, remaining: 90 };
124
+ assert.equal(parseCopilotUsage({ quota_snapshots: { chat: row, completions: row } }).windows.length, 1);
125
+ await assert.rejects(fetchOfficialUsage('github-copilot', { access: 'short-inference-token', request: () => assert.fail('must not query') }), { code: 'source-credential-required' });
126
+ });
127
+
128
+ test('Kimi keeps all observed buckets and converts fixed-point booster amounts without rounding', () => {
129
+ const out = parseKimiUsage({ usages: { limit_month_total: { used_ratio: '0.5', reset_time: RESET }, limit_month_code: { used_ratio: 0 } }, boosterWallet: {
130
+ balance: { type: 'BOOSTER', amount: '1000000000', amountLeft: '123456789' },
131
+ monthlyChargeLimitEnabled: true, monthlyChargeLimit: { priceInCents: 2000, currency: 'USD' }, monthlyUsed: { priceInCents: 150, currency: 'USD' },
132
+ } });
133
+ assert.equal(out.windows[0].usedPercent, 50);
134
+ assert.equal(out.windows[1].usedPercent, 0);
135
+ assert.equal(out.balances[0].amount, 1.23456789);
136
+ assert.equal(out.windows.find(x => x.id === 'kimi:extra-monthly').used, 1.5);
137
+ assert.equal(out.windows.find(x => x.id === 'kimi:extra-monthly').limit, 20);
138
+ });
139
+
140
+ test('Kimi missing wallet fields are not invented and non-booster money is ignored', () => {
141
+ const out = parseKimiUsage({ ...fixtures['kimi-coding'], boosterWallet: { balance: { type: 'BOOSTER', amount: 1000000 } } });
142
+ assert.equal(out.balances.length, 0);
143
+ assert.equal(out.windows.length, 1);
144
+ assert.throws(() => parseKimiUsage({ boosterWallet: { balance: { type: 'OTHER', amountLeft: 1000 } } }), { code: 'invalid-response' });
145
+ });
146
+
147
+ test('MiniMax official ambiguity algorithm handles consumed, remaining, mismatch, and legacy fields', () => {
148
+ for (const reported of [200, 800]) assert.deepEqual(resolveMiniMaxCounts(reported, 1000, 80), { used: 200, limit: 1000, remaining: 800 });
149
+ assert.equal(resolveMiniMaxCounts(200, 1000, 50), undefined);
150
+ assert.deepEqual(resolveMiniMaxCounts(200, 1000), { used: 800, limit: 1000, remaining: 200 });
151
+ for (const args of [[0, 0], [-1, 10], [11, 10], ['', 10], [true, 10]]) assert.equal(resolveMiniMaxCounts(...args), undefined);
152
+ const out = parseMiniMaxUsage({ model_remains: [{ model_name: 'general', current_interval_total_count: 1000, current_interval_usage_count: 200, current_interval_remaining_percent: 50 }] });
153
+ assert.equal(out.windows[0].unit, 'percent');
154
+ assert.equal(out.windows[0].remainingPercent, 50);
155
+ assert.equal(out.windows[0].remaining, undefined);
156
+ });
157
+
158
+ test('MiniMax milliseconds, excluded services, unlimited windows and weekly boosts are preserved', () => {
159
+ const included = { model_name: 'video', current_interval_status: 3, current_weekly_total_count: 100, current_weekly_usage_count: 50, current_weekly_remaining_percent: 50, weekly_boost_permille: 1500, weekly_start_time: NOW, weekly_end_time: NOW + 604800000 };
160
+ const excluded = { model_name: 'not-in-plan', current_interval_total_count: 0, current_weekly_total_count: 0, current_interval_status: 3, current_weekly_status: 3 };
161
+ const out = parseMiniMaxUsage({ model_remains: [excluded, included] });
162
+ assert.equal(out.windows.length, 2);
163
+ assert.equal(out.windows[0].unlimited, true);
164
+ assert.equal(out.windows[1].windowSeconds, 604800);
165
+ assert.equal(out.windows[1].resetAt, new Date(NOW + 604800000).toISOString());
166
+ assert.equal(out.windows[1].remainingPercent, 50);
167
+ assert.ok(out.notes.some(note => note.includes('1.5')));
168
+ });
169
+
170
+ test('ZAI percentages are not mislabeled raw tokens and tools use request counters', () => {
171
+ const out = parseZaiUsage({ success: true, data: { level: 'max', limits: [{ type: 'CREDIT_LIMIT', percentage: 1, unit: 6, number: 1 }, { type: 'TIME_LIMIT', usage: 100, currentValue: 7, remaining: 93, unit: 5, number: 1 }] } }, { organizationId: 'team', projectId: 'proj' });
172
+ assert.equal(out.windows[0].unit, 'percent');
173
+ assert.equal(out.windows[0].usedPercent, 1);
174
+ assert.equal(out.windows[0].windowSeconds, 604800);
175
+ assert.equal(out.windows[1].unit, 'requests');
176
+ assert.equal(out.windows[1].remaining, 93);
177
+ assert.equal(out.windows[1].resetAt, undefined);
178
+ assert.match(out.windows[0].scope, /organization:team\/project:proj/);
179
+ });
180
+
181
+ test('ZAI rejects incomplete team scope and HTTP-200 API failures safely', async () => {
182
+ await assert.rejects(fetchOfficialUsage('zai', { access: 'key', organizationId: 'team', request: () => assert.fail('must not query') }), { code: 'scope-required' });
183
+ assert.throws(() => parseZaiUsage({ success: false, msg: 'secret', data: fixtures.zai.data }), error => error.code === 'invalid-response' && !error.message.includes('secret'));
184
+ });
185
+
186
+ test('Aliyun dynamically parses current windows and refuses error envelopes or no-quota markers', () => {
187
+ const out = parseAliyunUsage({ DataV2: { data: { per2DayPercentage: '0.125', per2DayResetTime: Date.parse(RESET), per1MonthPercentage: 0 } } });
188
+ assert.equal(out.windows[0].usedPercent, 12.5);
189
+ assert.equal(out.windows[0].windowSeconds, 172800);
190
+ assert.equal(out.windows[0].resetAt, RESET);
191
+ assert.equal(out.windows[1].windowSeconds, undefined);
192
+ for (const data of [{ success: false, data: { per1MonthPercentage: 0 } }, { DataV2: { failed: true, data: { per1MonthPercentage: 0 } } }, { ret: ['FAIL::secret'], data: { per1MonthPercentage: 0 } }]) assert.throws(() => parseAliyunUsage(data), { code: 'invalid-response' });
193
+ assert.throws(() => parseAliyunUsage({ hasQuotaData: false, per1MonthPercentage: 0 }), { code: 'unavailable' });
194
+ });
195
+
196
+ test('Aliyun model keys cannot replace a Console credential', async () => {
197
+ await assert.rejects(fetchOfficialUsage('aliyun-token-plan', { access: 'model-key', request: () => assert.fail('must not query') }), { code: 'billing-credential-required' });
198
+ });
199
+
200
+ test('Antigravity accepts documented wrappers and oneof fractions without onboarding or fabricated windows', () => {
201
+ const out = parseAntigravityUsage({ response: { groups: [{ buckets: [{ id: 'week', remaining: { case: 'remainingFraction', value: 0.5 }, resetTime: RESET }, { id: 'disabled', remainingFraction: 1, disabled: true }, { id: 'unknown' }] }] } }, { projectId: 'p' });
202
+ assert.equal(out.windows.length, 1);
203
+ assert.equal(out.windows[0].usedPercent, 50);
204
+ assert.equal(out.windows[0].resetAt, RESET);
205
+ assert.equal(out.windows[0].scope, 'project:p');
206
+ assert.equal(out.windows[0].windowSeconds, undefined);
207
+ });
208
+
209
+ test('Gemini fractions and independent AI credits do not conflate unknown bucket units', () => {
210
+ const out = parseGeminiUsage({ ...fixtures['google-gemini-cli'], remainingCredits: [{ creditType: 'GOOGLE_ONE_AI', creditAmount: '100' }] }, { projectId: 'p' });
211
+ assert.ok(Math.abs(out.windows[0].usedPercent - 20) < 1e-10);
212
+ assert.equal(out.windows[0].remaining, undefined);
213
+ assert.equal(out.balances[0].amount, 100);
214
+ assert.equal(out.balances[0].unit, 'credits');
215
+ });
216
+
217
+ test('Google missing project does not trigger a setup request; Antigravity supports empty summary context', async () => {
218
+ await assert.rejects(fetchOfficialUsage('google-gemini-cli', { access: 'a', request: () => assert.fail('must not query') }), { code: 'scope-required' });
219
+ await fetchOfficialUsage('google-antigravity', { access: 'a', request: async (url, options) => { assert.equal(options.body, '{}'); assert.match(options.headers['User-Agent'], /^antigravity\/hub\//); assert.equal(url.includes('onboard'), false); return fixtures['google-antigravity']; } });
220
+ });
221
+
222
+ test('Grok percentage, period and prepaid cents remain separate', () => {
223
+ const out = parseXaiUsage(fixtures.xai);
224
+ assert.equal(out.windows[0].usedPercent, 25);
225
+ assert.equal(out.windows[0].windowSeconds, 30 * 86400);
226
+ assert.equal(out.balances[0].amount, 12.34);
227
+ assert.equal(out.balances[0].currency, 'USD');
228
+ assert.equal(parseXaiUsage({ config: { prepaidBalance: {} } }).balances[0].amount, 0);
229
+ assert.throws(() => parseXaiUsage({ config: {} }), { code: 'invalid-response' });
230
+ });
231
+
232
+ test('Nous basis points, milliseconds, rollover and credits are not summed twice', () => {
233
+ const out = parseNousUsage(fixtures.nous);
234
+ assert.equal(out.windows[0].usedPercent, 12.5);
235
+ assert.equal(out.windows[0].resetAt, RESET);
236
+ assert.equal(out.balances.find(x => x.id === 'nous:total').amount, 75);
237
+ const rollover = parseNousUsage({ subscription: { plan: 'plus', monthly_credits: 100, credits_remaining: 150, rollover_credits: 50 } });
238
+ assert.equal(rollover.windows.length, 0);
239
+ assert.equal(rollover.balances.length, 2);
240
+ assert.ok(rollover.notes[0].includes('overlap'));
241
+ });
242
+
243
+ test('regional endpoints do not depend on locale or an injected arbitrary base URL', async () => {
244
+ for (const [id, host] of [['kimi-coding', 'api.kimi.com'], ['minimax', 'api.minimax.cn'], ['zai', 'bigmodel.cn'], ['aliyun-token-plan', 'bailian-cs.console.aliyun.com']]) {
245
+ await fetchOfficialUsage(id, { region: 'cn', locale: 'en-US', baseURL: 'https://attacker.invalid', access: 'a', billingAccess: 'b', request: async (url) => { assert.equal(new URL(url).hostname, host); return fixtures[id]; } });
246
+ }
247
+ });
248
+
249
+ test('numeric poison, invalid timestamps and arbitrary upstream messages stay out of output', () => {
250
+ const out = parseCodexUsage({ rate_limit: { primary_window: { used_percent: true, reset_at: 1 }, secondary_window: { used_percent: 0, reset_at: 'not-a-date', limit_window_seconds: Infinity } } });
251
+ assert.equal(out.windows.length, 1);
252
+ assert.equal(out.windows[0].resetAt, undefined);
253
+ assert.equal(out.windows[0].windowSeconds, undefined);
254
+ });
255
+
256
+ test('transport errors pass through unchanged and unknown IDs do not issue requests', async () => {
257
+ const throttled = Object.assign(new Error('safe throttled message'), { code: 'rate-limited', retryAt: RESET });
258
+ await assert.rejects(fetchOfficialUsage('openai-codex', { access: 'a', request: async () => { throw throttled; } }), error => error === throttled);
259
+ await assert.rejects(fetchOfficialUsage('unknown', { request: () => assert.fail('must not query') }), { code: 'unsupported' });
260
+ });
261
+
262
+ test('Nous API inference key requires a separate Portal credential', async () => {
263
+ await assert.rejects(fetchOfficialUsage('nous', { access: 'inference-key', rawGrant: { type: 'api_key', access: 'inference-key' }, request: () => assert.fail('must not send an inference key to Portal') }), { code: 'needs-permission' });
264
+ await fetchOfficialUsage('nous', { access: 'inference-key', rawGrant: { type: 'api_key' }, billingAccess: 'portal-oauth', request: async (url, options) => { assert.equal(options.headers.Authorization, 'Bearer portal-oauth'); return fixtures.nous; } });
265
+ });
266
+
267
+ test('malformed optional array members cannot discard valid neighboring quota', () => {
268
+ assert.ok(parseCodexUsage({ ...fixtures['openai-codex'], additional_rate_limits: [null] }).windows.length);
269
+ assert.ok(parseClaudeUsage({ ...fixtures.anthropic, limits: [null] }).windows.length);
270
+ assert.ok(parseGeminiUsage({ ...fixtures['google-gemini-cli'], remainingCredits: [null] }).windows.length);
271
+ assert.ok(parseXaiUsage({ config: { ...fixtures.xai.config, productUsage: [null] } }).windows.length);
272
+ assert.ok(parseNousUsage({ ...fixtures.nous, usage_window: { gauges: [null] } }).windows.length);
273
+ });