@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.
- package/README.en.md +155 -0
- package/README.md +101 -2
- package/app.js +1045 -0
- package/auth.html +80 -0
- package/client.js +31 -0
- package/cordis.patch.yml +4 -0
- package/docs/CONNECTIONS.md +77 -0
- package/docs/LIVE-VALIDATION-1.0.1.md +100 -0
- package/docs/RELEASE-1.0.1.md +48 -0
- package/docs/RELEASE-1.0.2.md +8 -0
- package/docs/VALIDATION.md +59 -0
- package/docs/evidence/live-1.0.1.json +135 -0
- package/docs/evidence/release-1.0.1.json +38 -0
- package/index.html +43 -0
- package/package.json +64 -4
- package/providers.js +73 -0
- package/scripts/check-upstreams.mjs +27 -0
- package/scripts/link-peers.js +38 -0
- package/scripts/verify-browser.mjs +297 -0
- package/scripts/verify-host.mjs +431 -0
- package/scripts/verify-live.mjs +268 -0
- package/scripts/verify-package.mjs +168 -0
- package/scripts/verify-persistence.mjs +307 -0
- package/scripts/verify-subscriptions-ui.mjs +321 -0
- package/src/account.js +85 -0
- package/src/account.test.js +52 -0
- package/src/authorization.js +199 -0
- package/src/authorization.test.js +332 -0
- package/src/catalog.js +180 -0
- package/src/catalog.test.js +146 -0
- package/src/chat-recovery.js +110 -0
- package/src/chat-recovery.test.js +261 -0
- package/src/connection-runtime.js +129 -0
- package/src/connection-runtime.test.js +244 -0
- package/src/connections.js +70 -0
- package/src/grants.js +104 -0
- package/src/grants.test.js +340 -0
- package/src/index.js +676 -0
- package/src/local-imports.js +263 -0
- package/src/local-imports.test.js +201 -0
- package/src/media.js +152 -0
- package/src/models.js +610 -0
- package/src/models.test.js +503 -0
- package/src/profile-store.js +51 -0
- package/src/pulls.js +100 -0
- package/src/pulls.test.js +156 -0
- package/src/qwen.js +141 -0
- package/src/qwen.test.js +35 -0
- package/src/request-errors.js +50 -0
- package/src/request-errors.test.js +131 -0
- package/src/routes.js +47 -0
- package/src/routes.test.js +136 -0
- package/src/subscription-models.test.js +160 -0
- package/src/usage/aggregators.js +292 -0
- package/src/usage/aggregators.test.js +316 -0
- package/src/usage/core.js +68 -0
- package/src/usage/index.js +93 -0
- package/src/usage/official.js +339 -0
- package/src/usage/official.test.js +273 -0
- package/src/usage/service.test.js +89 -0
- package/src/xai-browser.js +272 -0
- package/src/xai-browser.test.js +256 -0
- package/src/xai-login.js +121 -0
- package/src/xai-login.test.js +259 -0
- package/styles.css +364 -0
- package/theme.js +118 -0
- package/upstreams.json +10 -0
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
import test from 'node:test';
|
|
2
|
+
import assert from 'node:assert/strict';
|
|
3
|
+
import { aggregatorUsageIds, fetchAggregatorUsage } from './aggregators.js';
|
|
4
|
+
|
|
5
|
+
const ACCESS = 'fixture-inference';
|
|
6
|
+
const BILLING = 'fixture-management';
|
|
7
|
+
const DATE = '2026-11-17T04:00:00.000Z';
|
|
8
|
+
|
|
9
|
+
function mock(responses, extra = {}) {
|
|
10
|
+
const calls = [];
|
|
11
|
+
return {
|
|
12
|
+
calls,
|
|
13
|
+
ctx: {
|
|
14
|
+
access: ACCESS, now: Date.parse('2026-11-16T04:00:00.000Z'), ...extra,
|
|
15
|
+
async request(url, options) {
|
|
16
|
+
calls.push({ url, ...options });
|
|
17
|
+
const item = responses[calls.length - 1];
|
|
18
|
+
assert.notEqual(item, undefined, `Unexpected request to ${url}`);
|
|
19
|
+
if (item instanceof Error) throw item;
|
|
20
|
+
return item;
|
|
21
|
+
},
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function windowBy(result, id) { return result.windows.find(row => row.id === id); }
|
|
27
|
+
function noSecrets(result) {
|
|
28
|
+
const json = JSON.stringify(result);
|
|
29
|
+
assert.equal(json.includes(ACCESS), false);
|
|
30
|
+
assert.equal(json.includes(BILLING), false);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
test('exports only issuer-bound supported adapters and rejects unsupported ids', async () => {
|
|
34
|
+
assert.equal(aggregatorUsageIds.length, 9);
|
|
35
|
+
const { ctx, calls } = mock([]);
|
|
36
|
+
await assert.rejects(fetchAggregatorUsage('__proto__', ctx), e => e.code === 'unsupported');
|
|
37
|
+
await assert.rejects(fetchAggregatorUsage('new-api', ctx), e => e.code === 'unsupported');
|
|
38
|
+
assert.equal(calls.length, 0);
|
|
39
|
+
});
|
|
40
|
+
|
|
41
|
+
test('OpenRouter separates key budgets, shared budgets, free requests, and management-account balance', async () => {
|
|
42
|
+
const { ctx, calls } = mock([
|
|
43
|
+
{ data: { limit: 10, limit_reset: 'daily', limit_remaining: -2, usage: 100, usage_daily: 12, usage_weekly: 50, budgets: [{ scope: 'workspace', limit_usd: 100, spend_usd: 110, remaining_usd: -10, resets_at: DATE }], effective_budget: { scope: 'workspace', limit_usd: 100, spend_usd: 110, remaining_usd: -10 }, free_model_daily_requests: { used: 2, limit: 50, remaining: 48 } } },
|
|
44
|
+
{ data: { total_credits: 20, total_usage: 22 } },
|
|
45
|
+
], { billingAccess: BILLING });
|
|
46
|
+
const out = await fetchAggregatorUsage('openrouter', ctx);
|
|
47
|
+
assert.equal(windowBy(out, 'key-limit').used, 12);
|
|
48
|
+
assert.equal(windowBy(out, 'key-limit').remaining, -2);
|
|
49
|
+
assert.equal(windowBy(out, 'budget-0').remaining, -10);
|
|
50
|
+
assert.equal(windowBy(out, 'budget-0').scope, 'workspace');
|
|
51
|
+
assert.equal(windowBy(out, 'free-model-daily').unit, 'requests');
|
|
52
|
+
assert.equal(out.balances[0].amount, -2);
|
|
53
|
+
assert.equal(calls[0].headers.Authorization, `Bearer ${ACCESS}`);
|
|
54
|
+
assert.equal(calls[1].headers.Authorization, `Bearer ${BILLING}`);
|
|
55
|
+
assert.equal(calls[1].url, 'https://openrouter.ai/api/v1/credits');
|
|
56
|
+
noSecrets(out);
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
test('OpenRouter preserves successful key data when optional billing access fails', async () => {
|
|
60
|
+
const denied = Object.assign(new Error(`forbidden ${BILLING}`), { status: 403 });
|
|
61
|
+
const { ctx } = mock([{ data: { limit: null, usage: 3 } }, denied], { billingAccess: BILLING });
|
|
62
|
+
const out = await fetchAggregatorUsage('openrouter', ctx);
|
|
63
|
+
assert.equal(out.status, 'partial');
|
|
64
|
+
assert.equal(windowBy(out, 'key-limit').unlimited, true);
|
|
65
|
+
assert.equal(out.balances.length, 0);
|
|
66
|
+
assert.equal(windowBy(out, 'key-limit').remaining, undefined);
|
|
67
|
+
noSecrets(out);
|
|
68
|
+
});
|
|
69
|
+
|
|
70
|
+
test('OpenRouter never sends a normal key to management credits automatically', async () => {
|
|
71
|
+
const { ctx, calls } = mock([{ data: { limit: 0, usage: 0, limit_remaining: 0 } }]);
|
|
72
|
+
const out = await fetchAggregatorUsage('openrouter', ctx);
|
|
73
|
+
assert.equal(calls.length, 1);
|
|
74
|
+
assert.equal(out.status, 'partial');
|
|
75
|
+
assert.equal(windowBy(out, 'key-limit').remaining, 0);
|
|
76
|
+
});
|
|
77
|
+
|
|
78
|
+
test('NanoGPT handles fraction percentages, millisecond windows, and image/token units separately', async () => {
|
|
79
|
+
const { ctx, calls } = mock([{
|
|
80
|
+
active: true, limits: { weeklyInputTokens: 1000, dailyImages: 100 },
|
|
81
|
+
weeklyInputTokens: { used: 2.5, remaining: 997.5, percentUsed: 0.0025, resetAt: Date.parse(DATE) },
|
|
82
|
+
dailyImages: { used: 4, remaining: 96, percentUsed: 0.04, resetAt: Date.parse(DATE) },
|
|
83
|
+
dailyInputTokens: null,
|
|
84
|
+
routing: { recommendedMode: 'subscription', subscriptionQuotaAvailable: true },
|
|
85
|
+
}]);
|
|
86
|
+
const out = await fetchAggregatorUsage('nanogpt', ctx);
|
|
87
|
+
assert.equal(windowBy(out, 'weeklyInputTokens').usedPercent, 0.25);
|
|
88
|
+
assert.equal(windowBy(out, 'weeklyInputTokens').resetAt, DATE);
|
|
89
|
+
assert.equal(windowBy(out, 'weeklyInputTokens').unit, 'tokens');
|
|
90
|
+
assert.equal(windowBy(out, 'dailyImages').unit, 'credits');
|
|
91
|
+
assert.equal(windowBy(out, 'dailyInputTokens'), undefined);
|
|
92
|
+
assert.equal(out.balances.length, 0);
|
|
93
|
+
assert.equal(calls[0].url, 'https://api.nano-gpt.com/api/subscription/v1/usage');
|
|
94
|
+
});
|
|
95
|
+
|
|
96
|
+
test('NanoGPT degraded quotas remain unknown despite an advertised limit', async () => {
|
|
97
|
+
const { ctx } = mock([{ active: true, limits: { weeklyInputTokens: 60000000 }, weeklyInputTokens: { used: null, remaining: null, percentUsed: null, degraded: true }, routing: { subscriptionQuotaAvailable: null } }]);
|
|
98
|
+
const out = await fetchAggregatorUsage('nanogpt', ctx);
|
|
99
|
+
assert.equal(out.status, 'partial');
|
|
100
|
+
assert.equal(out.windows.length, 0);
|
|
101
|
+
assert.equal(out.balances.length, 0);
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
test('NanoGPT trials and overage retain source direction without clearing unknown values', async () => {
|
|
105
|
+
const { ctx } = mock([{ active: false, tokenLimits: { total: 10 }, tokens: { used: 12, remaining: -2, percentUsed: 1.2, resetAt: null }, usageUnits: 'tokens' }]);
|
|
106
|
+
const row = windowBy(await fetchAggregatorUsage('nanogpt', ctx), 'tokens');
|
|
107
|
+
assert.equal(row.usedPercent, 120);
|
|
108
|
+
assert.equal(row.remaining, -2);
|
|
109
|
+
assert.equal(row.resetAt, undefined);
|
|
110
|
+
});
|
|
111
|
+
|
|
112
|
+
test('ZenMux requires explicit management access without trying inference key', async () => {
|
|
113
|
+
const { ctx, calls } = mock([]);
|
|
114
|
+
await assert.rejects(fetchAggregatorUsage('zenmux', ctx), e => e.code === 'needs-permission');
|
|
115
|
+
assert.equal(calls.length, 0);
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
test('ZenMux preserves Flow units and cap-only month, with independent PAYG components', async () => {
|
|
119
|
+
const { ctx, calls } = mock([
|
|
120
|
+
{ success: true, data: { plan: { tier: 'pro' }, quota_5_hour: { max_flows: 800, used_flows: 57.2, remaining_flows: 742.8, usage_percentage: 0.0715, resets_at: DATE }, quota_7_day: { max_flows: 6182, usage_percentage: 0.01, resets_at: null }, quota_monthly: { max_flows: 34560, max_value_usd: 1134.33 } } },
|
|
121
|
+
{ success: true, data: { currency: 'usd', total_credits: '482.74', top_up_credits: '35.0', bonus_credits: '447.74' } },
|
|
122
|
+
], { billingAccess: BILLING });
|
|
123
|
+
const out = await fetchAggregatorUsage('zenmux', ctx);
|
|
124
|
+
assert.equal(windowBy(out, 'quota_5_hour').usedPercent, 7.1499999999999995);
|
|
125
|
+
assert.equal(windowBy(out, 'quota_5_hour').unit, 'credits');
|
|
126
|
+
assert.equal(windowBy(out, 'monthly-cap').limit, 34560);
|
|
127
|
+
assert.equal(windowBy(out, 'monthly-cap').used, undefined);
|
|
128
|
+
assert.equal(windowBy(out, 'monthly-cap').remaining, undefined);
|
|
129
|
+
assert.equal(windowBy(out, 'monthly-cap').usedPercent, undefined);
|
|
130
|
+
assert.equal(out.balances.length, 3);
|
|
131
|
+
assert.equal(out.balances[0].amount, '482.74');
|
|
132
|
+
assert.ok(calls.every(c => c.headers.Authorization === `Bearer ${BILLING}`));
|
|
133
|
+
noSecrets(out);
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
test('ZenMux preserves good PAYG balance when subscription fetch is unavailable', async () => {
|
|
137
|
+
const { ctx } = mock([new Error('subscription unavailable'), { success: true, data: { total_credits: 0, top_up_credits: 0, bonus_credits: 0 } }], { billingAccess: BILLING });
|
|
138
|
+
const out = await fetchAggregatorUsage('zenmux', ctx);
|
|
139
|
+
assert.equal(out.status, 'partial');
|
|
140
|
+
assert.equal(out.balances[0].amount, 0);
|
|
141
|
+
assert.equal(out.windows.length, 0);
|
|
142
|
+
});
|
|
143
|
+
|
|
144
|
+
test('ZenMux documented management 422 throttling maps to rate-limited without exposing server text', async () => {
|
|
145
|
+
const limited = Object.assign(new Error(`supplier says ${BILLING}`), { status: 422, retryAt: DATE });
|
|
146
|
+
const { ctx } = mock([limited, limited], { billingAccess: BILLING });
|
|
147
|
+
await assert.rejects(fetchAggregatorUsage('zenmux', ctx), error => error.code === 'rate-limited' && error.retryAt === DATE && !error.message.includes(BILLING));
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
test('OpenCode refuses missing workspace and uses Go-specific organization header', async () => {
|
|
151
|
+
const empty = mock([]);
|
|
152
|
+
await assert.rejects(fetchAggregatorUsage('opencode-go', empty.ctx), e => e.code === 'needs-configuration');
|
|
153
|
+
assert.equal(empty.calls.length, 0);
|
|
154
|
+
const { ctx, calls } = mock([{ usage: { rolling: { percent: 0.5, status: 'ok', resetsAt: DATE }, weekly: { percent: 100, status: 'rate-limited', resetsAt: DATE }, monthly: { percent: 20, status: 'ok', resetsAt: DATE } } }], { organizationId: 'workspace_123' });
|
|
155
|
+
const out = await fetchAggregatorUsage('opencode-go', ctx);
|
|
156
|
+
assert.equal(calls[0].headers['x-opencode-org-id'], 'workspace_123');
|
|
157
|
+
assert.equal(calls[0].headers['x-org-id'], undefined);
|
|
158
|
+
assert.equal(windowBy(out, 'rolling').usedPercent, 0.5);
|
|
159
|
+
assert.equal(windowBy(out, 'rolling').resetAt, DATE);
|
|
160
|
+
assert.equal(windowBy(out, 'rolling').scope, 'workspace:workspace_123:member');
|
|
161
|
+
assert.equal(windowBy(out, 'monthly').windowSeconds, undefined);
|
|
162
|
+
});
|
|
163
|
+
|
|
164
|
+
test('OpenCode Zen preserves shared and per-model budget scopes without summing', async () => {
|
|
165
|
+
const { ctx, calls } = mock([[
|
|
166
|
+
{ ruleID: 'shared', scope: 'combined', per: 'set', limitDollars: 100, spentDollars: 90, resetsAt: DATE },
|
|
167
|
+
{ ruleID: 'models', scope: 'each', per: 'model', limitDollars: 5, spentDollars: 4, resetsAt: DATE, models: [{ modelID: 'm1', spentDollars: 4 }, { modelID: 'm2', spentDollars: 2 }] },
|
|
168
|
+
]], { rawGrant: { metadata: { orgID: 'org_123' } } });
|
|
169
|
+
const out = await fetchAggregatorUsage('opencode-zen', ctx);
|
|
170
|
+
assert.equal(calls[0].headers['x-org-id'], 'org_123');
|
|
171
|
+
assert.equal(calls[0].headers['x-opencode-org-id'], undefined);
|
|
172
|
+
assert.equal(out.windows.length, 3);
|
|
173
|
+
assert.equal(out.windows[0].scope, 'workspace:org_123:shared');
|
|
174
|
+
assert.equal(out.windows[1].remaining, 1);
|
|
175
|
+
assert.equal(out.windows[2].remaining, 3);
|
|
176
|
+
assert.equal(out.balances.length, 0);
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
test('OpenCode empty budgets do not imply zero balance or unlimited allowance', async () => {
|
|
180
|
+
const { ctx } = mock([[]], { workspaceId: 'w' });
|
|
181
|
+
const out = await fetchAggregatorUsage('opencode-zen', ctx);
|
|
182
|
+
assert.equal(out.windows.length, 0);
|
|
183
|
+
assert.equal(out.balances.length, 0);
|
|
184
|
+
});
|
|
185
|
+
|
|
186
|
+
test('Kilo requests only credit and Pass reads, propagates org, scales micro-USD correctly', async () => {
|
|
187
|
+
const { ctx, calls } = mock([[
|
|
188
|
+
{ result: { data: { json: { creditBlocks: [{ amount_mUsd: 10000000, balance_mUsd: 2500000 }, { amount_mUsd: 5000000, balance_mUsd: 0 }], totalBalance_mUsd: 2500000 } } } },
|
|
189
|
+
{ result: { data: { json: { subscription: { tier: 'tier_19', currentPeriodUsageUsd: 7, currentPeriodBaseCreditsUsd: 19, currentPeriodBonusCreditsUsd: 2, nextBillingAt: DATE } } } } },
|
|
190
|
+
]], { organizationId: 'org_123' });
|
|
191
|
+
const out = await fetchAggregatorUsage('kilo', ctx);
|
|
192
|
+
const url = new URL(calls[0].url);
|
|
193
|
+
assert.equal(url.origin, 'https://app.kilo.ai');
|
|
194
|
+
assert.equal(url.pathname, '/api/trpc/user.getCreditBlocks,kiloPass.getState');
|
|
195
|
+
assert.deepEqual(JSON.parse(url.searchParams.get('input')), { 0: { json: null }, 1: { json: null } });
|
|
196
|
+
assert.equal(calls[0].headers['X-KILOCODE-ORGANIZATIONID'], 'org_123');
|
|
197
|
+
assert.equal(out.balances[0].amount, 2.5);
|
|
198
|
+
assert.equal(windowBy(out, 'pass-cycle').limit, 21);
|
|
199
|
+
assert.equal(windowBy(out, 'pass-cycle').remaining, 14);
|
|
200
|
+
assert.equal(windowBy(out, 'pass-cycle').resetAt, undefined);
|
|
201
|
+
assert.equal(out.plan.renewsAt, DATE);
|
|
202
|
+
noSecrets(out);
|
|
203
|
+
});
|
|
204
|
+
|
|
205
|
+
test('Kilo never invents zero used or a full allowance from balance-only or missing bonus', async () => {
|
|
206
|
+
const { ctx } = mock([[
|
|
207
|
+
{ result: { data: { json: { totalBalance_mUsd: 0, creditBlocks: [] } } } },
|
|
208
|
+
{ result: { data: { json: { subscription: { currentPeriodUsageUsd: 4, currentPeriodBaseCreditsUsd: 19 } } } } },
|
|
209
|
+
]]);
|
|
210
|
+
const out = await fetchAggregatorUsage('kilo', ctx);
|
|
211
|
+
assert.equal(out.balances[0].amount, 0);
|
|
212
|
+
assert.equal(windowBy(out, 'pass-cycle').limit, undefined);
|
|
213
|
+
assert.equal(windowBy(out, 'pass-cycle').remaining, undefined);
|
|
214
|
+
});
|
|
215
|
+
|
|
216
|
+
test('Kilo keeps successful credit query when Pass batch entry is denied without exposing errors', async () => {
|
|
217
|
+
const { ctx } = mock([[
|
|
218
|
+
{ result: { data: { json: { totalBalance_mUsd: 1000000 } } } },
|
|
219
|
+
{ error: { json: { message: ACCESS, data: { code: 'FORBIDDEN' } } } },
|
|
220
|
+
]]);
|
|
221
|
+
const out = await fetchAggregatorUsage('kilo', ctx);
|
|
222
|
+
assert.equal(out.status, 'partial');
|
|
223
|
+
assert.equal(out.balances[0].amount, 1);
|
|
224
|
+
noSecrets(out);
|
|
225
|
+
});
|
|
226
|
+
|
|
227
|
+
test('Kilo refuses malformed scope and incomplete block totals', async () => {
|
|
228
|
+
const invalidScope = mock([], { organizationId: 'org\nsecret' });
|
|
229
|
+
await assert.rejects(fetchAggregatorUsage('kilo', invalidScope.ctx), e => e.code === 'needs-configuration');
|
|
230
|
+
assert.equal(invalidScope.calls.length, 0);
|
|
231
|
+
const { ctx } = mock([[
|
|
232
|
+
{ result: { data: { json: { creditBlocks: [{ balance_mUsd: 1000000 }, { balance_mUsd: null }] } } } },
|
|
233
|
+
{ result: { data: { json: { subscription: null } } } },
|
|
234
|
+
]]);
|
|
235
|
+
const out = await fetchAggregatorUsage('kilo', ctx);
|
|
236
|
+
assert.equal(out.balances.find(b => b.id === 'account-balance'), undefined);
|
|
237
|
+
});
|
|
238
|
+
|
|
239
|
+
test('Poe reads only combined points; never infers a subscription reset or dollar balance', async () => {
|
|
240
|
+
const { ctx, calls } = mock([{ current_point_balance: 0 }]);
|
|
241
|
+
const out = await fetchAggregatorUsage('poe', ctx);
|
|
242
|
+
assert.equal(out.balances[0].amount, 0);
|
|
243
|
+
assert.equal(out.balances[0].unit, 'credits');
|
|
244
|
+
assert.equal(out.balances[0].currency, undefined);
|
|
245
|
+
assert.equal(out.windows.length, 0);
|
|
246
|
+
assert.equal(calls[0].url, 'https://api.poe.com/usage/current_balance');
|
|
247
|
+
});
|
|
248
|
+
|
|
249
|
+
test('Synthetic gives new weekly schema priority and distinguishes partial regeneration from reset', async () => {
|
|
250
|
+
const { ctx } = mock([{
|
|
251
|
+
planWeeklyLimit: { percentRemaining: 0.5, nextRegenAt: DATE, nextRegenPercent: 2 },
|
|
252
|
+
rollingFiveHourLimit: { max: 135, remaining: 0, nextTickAt: DATE, tickPercent: 2 },
|
|
253
|
+
weeklyTokenLimit: { maxCredits: '24', remainingCredits: '0', percentRemaining: 0, nextRegenAt: DATE },
|
|
254
|
+
}]);
|
|
255
|
+
const out = await fetchAggregatorUsage('synthetic', ctx);
|
|
256
|
+
assert.equal(out.windows.length, 1);
|
|
257
|
+
assert.equal(out.windows[0].remainingPercent, 0.5);
|
|
258
|
+
assert.equal(out.windows[0].resetAt, undefined);
|
|
259
|
+
assert.equal(out.windows[0].nextRegenAt, DATE);
|
|
260
|
+
assert.equal(out.windows[0].nextRegenPercent, 2);
|
|
261
|
+
});
|
|
262
|
+
|
|
263
|
+
test('Synthetic legacy credit quantities are not interpreted as tokens or wallet dollars', async () => {
|
|
264
|
+
const { ctx } = mock([{ weeklyTokenLimit: { maxCredits: '24.00', remainingCredits: '12.00', percentRemaining: 50, nextRegenAt: DATE } }]);
|
|
265
|
+
const out = await fetchAggregatorUsage('synthetic', ctx);
|
|
266
|
+
assert.equal(out.windows[0].unit, 'credits');
|
|
267
|
+
assert.equal(out.windows[0].remaining, 12);
|
|
268
|
+
assert.equal(out.windows[0].resetAt, undefined);
|
|
269
|
+
assert.equal(out.balances.length, 0);
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
test('Chutes uses service-returned fixed-bucket reset and monetary-equivalent lanes', async () => {
|
|
273
|
+
const { ctx, calls } = mock([{ subscription: true, custom: false, monthly_price: 10, four_hour: { usage: 4.17, cap: 4.17, remaining: 0, reset_at: DATE }, monthly: { usage: 30, cap: 50, remaining: 20, reset_at: '2026-12-01T00:00:00Z' } }]);
|
|
274
|
+
const out = await fetchAggregatorUsage('chutes', ctx);
|
|
275
|
+
assert.equal(out.windows[0].unit, 'money');
|
|
276
|
+
assert.equal(out.windows[0].remaining, 0);
|
|
277
|
+
assert.equal(out.windows[0].resetAt, DATE);
|
|
278
|
+
assert.equal(out.windows[0].windowSeconds, 14400);
|
|
279
|
+
assert.equal(out.balances.length, 0);
|
|
280
|
+
assert.equal(calls[0].url, 'https://api.chutes.ai/users/me/subscription_usage');
|
|
281
|
+
});
|
|
282
|
+
|
|
283
|
+
test('Chutes custom monthly uncapped does not erase the burst cap', async () => {
|
|
284
|
+
const { ctx } = mock([{ subscription: true, custom: true, four_hour: { usage: 1, cap: 5, remaining: 4 }, monthly: { uncapped: true } }]);
|
|
285
|
+
const out = await fetchAggregatorUsage('chutes', ctx);
|
|
286
|
+
assert.equal(windowBy(out, 'monthly').unlimited, true);
|
|
287
|
+
assert.equal(windowBy(out, 'monthly').remaining, undefined);
|
|
288
|
+
assert.equal(windowBy(out, 'four_hour').limit, 5);
|
|
289
|
+
});
|
|
290
|
+
|
|
291
|
+
test('Chutes no-subscription response does not imply zero PAYG balance', async () => {
|
|
292
|
+
const { ctx } = mock([{ subscription: false }]);
|
|
293
|
+
const out = await fetchAggregatorUsage('chutes', ctx);
|
|
294
|
+
assert.equal(out.windows.length, 0);
|
|
295
|
+
assert.equal(out.balances.length, 0);
|
|
296
|
+
});
|
|
297
|
+
|
|
298
|
+
test('each adapter rejects unrecognized, null and nonfinite metrics without inventing allowances', async () => {
|
|
299
|
+
for (const id of aggregatorUsageIds) {
|
|
300
|
+
const responses = id === 'zenmux' ? [{ data: {} }, { data: {} }] : id === 'kilo' ? [[{ result: { data: { json: {} } } }, { result: { data: { json: {} } } }]] : [{}];
|
|
301
|
+
const { ctx } = mock(responses, { billingAccess: BILLING, workspaceId: 'test' });
|
|
302
|
+
await assert.rejects(fetchAggregatorUsage(id, ctx), e => e.code === 'invalid-response', id);
|
|
303
|
+
}
|
|
304
|
+
for (const value of [null, '', false, Infinity, 'NaN']) {
|
|
305
|
+
const { ctx } = mock([{ current_point_balance: value }]);
|
|
306
|
+
await assert.rejects(fetchAggregatorUsage('poe', ctx), e => e.code === 'invalid-response');
|
|
307
|
+
}
|
|
308
|
+
});
|
|
309
|
+
|
|
310
|
+
test('empty or multiline credentials are rejected before a transport call', async () => {
|
|
311
|
+
for (const access of ['', ' ', 'key\nvalue', null]) {
|
|
312
|
+
const { ctx, calls } = mock([], { access });
|
|
313
|
+
await assert.rejects(fetchAggregatorUsage('poe', ctx), e => e.code === 'needs-configuration');
|
|
314
|
+
assert.equal(calls.length, 0);
|
|
315
|
+
}
|
|
316
|
+
});
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
/** Provider quota units and dates are explicit: unknown never means zero. */
|
|
2
|
+
export const finite = value => {
|
|
3
|
+
if (typeof value !== 'number' && !(typeof value === 'string' && /^-?\d+(?:\.\d+)?$/.test(value))) return undefined;
|
|
4
|
+
const number = Number(value);
|
|
5
|
+
return Number.isFinite(number) && Math.abs(number) <= Number.MAX_SAFE_INTEGER ? number : undefined;
|
|
6
|
+
};
|
|
7
|
+
export function iso(value, unit = 'iso') {
|
|
8
|
+
const time = unit === 'iso' ? (typeof value === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(value) ? Date.parse(value) : NaN)
|
|
9
|
+
: finite(value) === undefined ? NaN : finite(value) * (unit === 'seconds' ? 1000 : 1);
|
|
10
|
+
return Number.isFinite(time) && time >= 0 && time <= 8.64e15 ? new Date(time).toISOString() : undefined;
|
|
11
|
+
}
|
|
12
|
+
const compact = row => Object.fromEntries(Object.entries(row).filter(([, value]) => value !== undefined));
|
|
13
|
+
export function quotaWindow(row) {
|
|
14
|
+
const out = { ...row };
|
|
15
|
+
for (const key of ['used', 'limit', 'remaining', 'usedPercent', 'remainingPercent', 'nextRegenPercent']) out[key] = finite(out[key]);
|
|
16
|
+
if (out.limit !== undefined && out.used !== undefined && out.remaining === undefined) out.remaining = out.limit - out.used;
|
|
17
|
+
if (out.limit !== undefined && out.remaining !== undefined && out.used === undefined) out.used = out.limit - out.remaining;
|
|
18
|
+
if (out.usedPercent === undefined && out.remainingPercent !== undefined) out.usedPercent = 100 - out.remainingPercent;
|
|
19
|
+
if (out.usedPercent === undefined && out.limit > 0 && out.used !== undefined) out.usedPercent = 100 * out.used / out.limit;
|
|
20
|
+
if (out.remainingPercent === undefined && out.usedPercent !== undefined) out.remainingPercent = 100 - out.usedPercent;
|
|
21
|
+
return compact(out);
|
|
22
|
+
}
|
|
23
|
+
export function balance(row) {
|
|
24
|
+
if (finite(row.amount) === undefined) throw new UsageError('invalid-response', 'Invalid balance amount.');
|
|
25
|
+
return compact({ ...row });
|
|
26
|
+
}
|
|
27
|
+
export class UsageError extends Error {
|
|
28
|
+
constructor(code, message, { status, retryAt } = {}) {
|
|
29
|
+
super(message);
|
|
30
|
+
this.name = 'UsageError'; this.code = code; this.status = status; this.retryAt = retryAt;
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** No redirects, no response body in errors, bounded size and timeout. */
|
|
35
|
+
export function createUsageRequest({ allowedHosts, fetchImpl = fetch, now = () => Date.now() }) {
|
|
36
|
+
const hosts = new Set(allowedHosts);
|
|
37
|
+
return async (url, options = {}) => {
|
|
38
|
+
const target = new URL(url);
|
|
39
|
+
if (target.protocol !== 'https:' || target.username || target.password || !hosts.has(target.hostname) || target.port && target.port !== '443') {
|
|
40
|
+
throw new UsageError('needs-configuration', 'The usage endpoint is not an approved provider host.');
|
|
41
|
+
}
|
|
42
|
+
const headers = new Headers(options.headers);
|
|
43
|
+
let body = options.body;
|
|
44
|
+
if (body && typeof body === 'object' && !(body instanceof URLSearchParams)) {
|
|
45
|
+
body = JSON.stringify(body);
|
|
46
|
+
if (!headers.has('content-type')) headers.set('content-type', 'application/json');
|
|
47
|
+
}
|
|
48
|
+
let response;
|
|
49
|
+
try {
|
|
50
|
+
response = await fetchImpl(target.toString(), { ...options, body, headers, redirect: 'error', signal: AbortSignal.timeout(15000) });
|
|
51
|
+
} catch { throw new UsageError('unavailable', 'The usage service is temporarily unreachable.'); }
|
|
52
|
+
if (!response.ok) {
|
|
53
|
+
const code = response.status === 401 ? 'reauth-required' : response.status === 403 ? 'needs-permission' : response.status === 429 ? 'rate-limited' : 'unavailable';
|
|
54
|
+
const retry = response.headers.get('retry-after');
|
|
55
|
+
const retryTime = retry && /^\d+$/.test(retry) ? now() + Number(retry) * 1000 : retry ? Date.parse(retry) : NaN;
|
|
56
|
+
await response.body?.cancel();
|
|
57
|
+
throw new UsageError(code, `Usage query returned HTTP ${response.status}.`, { status: response.status, retryAt: Number.isFinite(retryTime) ? new Date(retryTime).toISOString() : undefined });
|
|
58
|
+
}
|
|
59
|
+
let size = 0; const chunks = [];
|
|
60
|
+
if (response.body) for await (const chunk of response.body) {
|
|
61
|
+
size += chunk.length;
|
|
62
|
+
if (size > 2 * 1024 * 1024) throw new UsageError('invalid-response', 'Usage response exceeds the size limit.');
|
|
63
|
+
chunks.push(chunk);
|
|
64
|
+
}
|
|
65
|
+
try { return JSON.parse(Buffer.concat(chunks).toString('utf8')); }
|
|
66
|
+
catch { throw new UsageError('invalid-response', 'The usage service did not return valid JSON.'); }
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { createProfileStore } from '../profile-store.js';
|
|
2
|
+
import { accountFingerprint } from '../connections.js';
|
|
3
|
+
import { createUsageRequest, UsageError, balance, quotaWindow, finite } from './core.js';
|
|
4
|
+
import { fetchOfficialUsage, officialUsageIds } from './official.js';
|
|
5
|
+
import { fetchAggregatorUsage, aggregatorUsageIds } from './aggregators.js';
|
|
6
|
+
|
|
7
|
+
export const usageIds = new Set([...officialUsageIds, ...aggregatorUsageIds, 'deepseek', 'new-api']);
|
|
8
|
+
const hosts = [
|
|
9
|
+
'chatgpt.com', 'api.anthropic.com', 'api.github.com', 'api.kimi.com', 'api.kimi.ai',
|
|
10
|
+
'api.minimax.cn', 'api.minimax.io', 'bigmodel.cn', 'api.z.ai', 'bailian-cs.console.aliyun.com',
|
|
11
|
+
'bailian-singapore-cs.alibabacloud.com', 'daily-cloudcode-pa.googleapis.com', 'cloudcode-pa.googleapis.com',
|
|
12
|
+
'cli-chat-proxy.grok.com', 'portal.nousresearch.com', 'openrouter.ai', 'api.nano-gpt.com',
|
|
13
|
+
'nano-gpt.com', 'zenmux.ai', 'opencode.ai', 'app.kilo.ai', 'api.poe.com',
|
|
14
|
+
'api.synthetic.new', 'api.chutes.ai', 'api.deepseek.com',
|
|
15
|
+
];
|
|
16
|
+
export async function fetchUsage(id, context) {
|
|
17
|
+
if (officialUsageIds.includes(id)) return fetchOfficialUsage(id, context);
|
|
18
|
+
if (aggregatorUsageIds.includes(id)) return fetchAggregatorUsage(id, context);
|
|
19
|
+
const headers = { Authorization: `Bearer ${context.access}`, Accept: 'application/json' };
|
|
20
|
+
if (id === 'deepseek') {
|
|
21
|
+
const data = await context.request('https://api.deepseek.com/user/balance', { headers });
|
|
22
|
+
if (!Array.isArray(data.balance_infos) || !data.balance_infos.length) throw new UsageError('invalid-response', 'No recognized account balance.');
|
|
23
|
+
const balances = data.balance_infos.filter(row => finite(row.total_balance) !== undefined).map((row, i) => balance({ id: `balance-${i}`, label: 'API account balance', unit: 'money', currency: row.currency, amount: row.total_balance, scope: 'account:api' }));
|
|
24
|
+
if (!balances.length) throw new UsageError('invalid-response', 'No recognized account balance.');
|
|
25
|
+
return { windows: [], balances };
|
|
26
|
+
}
|
|
27
|
+
if (id === 'new-api') {
|
|
28
|
+
if (!context.baseURL) throw new UsageError('needs-configuration', 'Configure the New API deployment URL.');
|
|
29
|
+
const url = new URL(context.baseURL);
|
|
30
|
+
const body = await context.request(`${url.origin}/api/usage/token/`, { headers });
|
|
31
|
+
const data = body?.data;
|
|
32
|
+
if (body.success === false || !data || finite(data.total_available) === undefined && finite(data.total_used) === undefined) throw new UsageError('invalid-response', 'This deployment does not expose the expected token quota contract.');
|
|
33
|
+
return { windows: [quotaWindow({ id: 'token-budget', label: 'Deployment token budget', unit: 'quota', scope: 'api-key', remaining: finite(data.total_available), used: finite(data.total_used), limit: finite(data.total_granted), unlimited: data.unlimited_quota === true })], balances: [], notes: ['deployment-quota-units-are-not-currency'] };
|
|
34
|
+
}
|
|
35
|
+
throw new UsageError('unsupported', 'This provider has no verified remote usage reader.');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/** Cached snapshots remain observations, never estimates of a provider balance. */
|
|
39
|
+
export function createUsageService({ directory, contextFor, fetchImpl, now = () => Date.now(), reader = fetchUsage }) {
|
|
40
|
+
const store = createProfileStore(directory, 'dsh-oauth-usage.json');
|
|
41
|
+
const inflight = new Map();
|
|
42
|
+
const generations = new Map();
|
|
43
|
+
const query = async (id, force) => {
|
|
44
|
+
if (!usageIds.has(id)) return { status: 'unsupported', lastAttemptAt: new Date(now()).toISOString() };
|
|
45
|
+
const generation = generations.get(id) ?? 0;
|
|
46
|
+
let context;
|
|
47
|
+
try { context = await contextFor(id); }
|
|
48
|
+
catch { return { status: 'reauth-required', lastAttemptAt: new Date(now()).toISOString(), message: 'Reconnect or renew the source CLI authorization.' }; }
|
|
49
|
+
const fingerprint = accountFingerprint(context.connection, context.rawGrant ?? { access: context.access });
|
|
50
|
+
const cached = await store.read(id);
|
|
51
|
+
const previous = cached?.fingerprint === fingerprint ? cached.result : undefined;
|
|
52
|
+
const age = now() - Date.parse(previous?.lastAttemptAt ?? '');
|
|
53
|
+
if (previous && (age < (force ? 5000 : 60000) || Date.parse(previous.retryAt) > now())) return previous;
|
|
54
|
+
const lastAttemptAt = new Date(now()).toISOString();
|
|
55
|
+
let result;
|
|
56
|
+
try {
|
|
57
|
+
const allowedHosts = id === 'new-api' && context.baseURL ? [new URL(context.baseURL).hostname] : hosts;
|
|
58
|
+
const data = await reader(id, { ...context, now: now(), request: createUsageRequest({ allowedHosts, fetchImpl, now }) });
|
|
59
|
+
const { status, ...snapshot } = data;
|
|
60
|
+
result = { status: status ?? 'fresh', snapshot: { ...snapshot, observedAt: lastAttemptAt, source: 'provider-api' }, lastAttemptAt };
|
|
61
|
+
} catch (error) {
|
|
62
|
+
let status = error instanceof UsageError ? error.code : 'unavailable';
|
|
63
|
+
if (['credential-required', 'source-credential-required'].includes(status)) status = 'reauth-required';
|
|
64
|
+
if (status === 'billing-credential-required') status = 'needs-permission';
|
|
65
|
+
if (status === 'scope-required') status = id === 'anthropic' ? 'needs-permission' : 'needs-configuration';
|
|
66
|
+
if (status === 'invalid-response') status = 'unavailable';
|
|
67
|
+
if (!['needs-permission', 'needs-configuration', 'reauth-required', 'unsupported', 'rate-limited', 'unavailable'].includes(status)) status = 'unavailable';
|
|
68
|
+
const stale = previous?.snapshot && ['unavailable', 'rate-limited'].includes(status);
|
|
69
|
+
result = { status: stale ? 'stale' : status, ...(stale ? { snapshot: previous.snapshot, lastErrorStatus: status } : {}), lastAttemptAt,
|
|
70
|
+
message: error instanceof UsageError ? error.message : 'The provider usage query could not complete.',
|
|
71
|
+
...(error.retryAt ? { retryAt: error.retryAt } : status === 'rate-limited' ? { retryAt: new Date(now() + 60000).toISOString() } : {}),
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
// Disconnect/reconnect while a request is running cannot revive old snapshots.
|
|
75
|
+
if ((generations.get(id) ?? 0) !== generation) return { status: 'reauth-required', lastAttemptAt };
|
|
76
|
+
const current = await Promise.resolve().then(() => contextFor(id)).catch(() => undefined);
|
|
77
|
+
if (!current || accountFingerprint(current.connection, current.rawGrant ?? { access: current.access }) !== fingerprint) return { status: 'reauth-required', lastAttemptAt };
|
|
78
|
+
await store.write(id, { fingerprint, result }, () => (generations.get(id) ?? 0) === generation);
|
|
79
|
+
if ((generations.get(id) ?? 0) !== generation) return { status: 'reauth-required', lastAttemptAt };
|
|
80
|
+
return result;
|
|
81
|
+
};
|
|
82
|
+
return {
|
|
83
|
+
async get(id, { force = false } = {}) {
|
|
84
|
+
if (inflight.has(id)) return inflight.get(id);
|
|
85
|
+
const pending = query(id, force).finally(() => { if (inflight.get(id) === pending) inflight.delete(id); });
|
|
86
|
+
inflight.set(id, pending); return pending;
|
|
87
|
+
},
|
|
88
|
+
async invalidate(id) {
|
|
89
|
+
generations.set(id, (generations.get(id) ?? 0) + 1);
|
|
90
|
+
inflight.delete(id); await store.delete(id);
|
|
91
|
+
},
|
|
92
|
+
};
|
|
93
|
+
}
|