@narumitw/pi-usage 0.61.2 → 0.62.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +38 -6
- package/dist/chunks/chunk-WEXCFYZX.ts +3005 -0
- package/dist/chunks/chunk-WEXCFYZX.ts.map +7 -0
- package/dist/chunks/openai-companion-auth-Q456G46T.ts +85 -0
- package/dist/chunks/openai-companion-auth-Q456G46T.ts.map +7 -0
- package/dist/chunks/openai-companion-usage-Y3WTMUB2.ts +120 -0
- package/dist/chunks/openai-companion-usage-Y3WTMUB2.ts.map +7 -0
- package/dist/index.ts +544 -3309
- package/dist/index.ts.map +4 -4
- package/docs/providers.md +29 -7
- package/package.json +4 -4
- package/src/format.ts +29 -1
- package/src/openai-companion-auth.ts +103 -0
- package/src/providers/openai-chatgpt.ts +24 -9
- package/src/providers/openai-companion-usage.ts +146 -0
- package/src/query.ts +5 -1
- package/src/settings.ts +5 -0
- package/src/types.ts +4 -0
- package/src/usage-settings-ui.ts +51 -9
- package/src/usage.ts +86 -4
|
@@ -0,0 +1,3005 @@
|
|
|
1
|
+
// @generated by scripts/build-runtime.mjs; do not edit.
|
|
2
|
+
// @ts-nocheck -- generated JavaScript uses a .ts extension for Pi's Jiti loader.
|
|
3
|
+
|
|
4
|
+
// src/core.ts
|
|
5
|
+
import { createHmac } from "node:crypto";
|
|
6
|
+
var UsageCache = class {
|
|
7
|
+
entries = /* @__PURE__ */ new Map();
|
|
8
|
+
ttlMs;
|
|
9
|
+
maxEntries;
|
|
10
|
+
constructor(ttlMs, maxEntries = 32) {
|
|
11
|
+
if (!Number.isFinite(ttlMs) || ttlMs <= 0) throw new Error("Cache TTL must be positive.");
|
|
12
|
+
if (!Number.isSafeInteger(maxEntries) || maxEntries < 1) {
|
|
13
|
+
throw new Error("Cache entry limit must be a positive integer.");
|
|
14
|
+
}
|
|
15
|
+
this.ttlMs = ttlMs;
|
|
16
|
+
this.maxEntries = maxEntries;
|
|
17
|
+
}
|
|
18
|
+
get size() {
|
|
19
|
+
return this.entries.size;
|
|
20
|
+
}
|
|
21
|
+
get(providerId, fingerprint, now = Date.now()) {
|
|
22
|
+
this.sweepExpired(now);
|
|
23
|
+
return this.entries.get(cacheKey(providerId, fingerprint))?.report;
|
|
24
|
+
}
|
|
25
|
+
set(providerId, fingerprint, report2, now = Date.now()) {
|
|
26
|
+
this.sweepExpired(now);
|
|
27
|
+
const key = cacheKey(providerId, fingerprint);
|
|
28
|
+
this.entries.delete(key);
|
|
29
|
+
while (this.entries.size >= this.maxEntries) {
|
|
30
|
+
const oldest = this.entries.keys().next().value;
|
|
31
|
+
if (oldest === void 0) break;
|
|
32
|
+
this.entries.delete(oldest);
|
|
33
|
+
}
|
|
34
|
+
this.entries.set(key, { createdAt: now, report: report2 });
|
|
35
|
+
}
|
|
36
|
+
delete(providerId, fingerprint) {
|
|
37
|
+
this.entries.delete(cacheKey(providerId, fingerprint));
|
|
38
|
+
}
|
|
39
|
+
clearProvider(providerId) {
|
|
40
|
+
for (const key of this.entries.keys()) {
|
|
41
|
+
if (key.startsWith(`${providerId}:`)) this.entries.delete(key);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
clear() {
|
|
45
|
+
this.entries.clear();
|
|
46
|
+
}
|
|
47
|
+
sweepExpired(now) {
|
|
48
|
+
for (const [key, entry] of this.entries) {
|
|
49
|
+
if (now - entry.createdAt >= this.ttlMs) this.entries.delete(key);
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
};
|
|
53
|
+
function fingerprintResolvedAuth(auth, salt) {
|
|
54
|
+
const headers = Object.entries(auth.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]).sort(([left], [right]) => left.localeCompare(right));
|
|
55
|
+
const env = Object.entries(auth.env ?? {}).sort(([left], [right]) => left.localeCompare(right));
|
|
56
|
+
const providerHeaders = Object.entries(auth.providerAuth?.headers ?? {}).map(([name, value]) => [name.toLowerCase(), value]).sort(([left], [right]) => left.localeCompare(right));
|
|
57
|
+
const canonical = JSON.stringify({
|
|
58
|
+
apiKey: auth.apiKey ?? "",
|
|
59
|
+
headers,
|
|
60
|
+
baseUrl: auth.baseUrl ?? "",
|
|
61
|
+
env,
|
|
62
|
+
source: auth.source ?? "",
|
|
63
|
+
providerAuth: {
|
|
64
|
+
apiKey: auth.providerAuth?.apiKey ?? "",
|
|
65
|
+
headers: providerHeaders,
|
|
66
|
+
baseUrl: auth.providerAuth?.baseUrl ?? ""
|
|
67
|
+
}
|
|
68
|
+
});
|
|
69
|
+
return createHmac("sha256", salt).update(canonical).digest("hex");
|
|
70
|
+
}
|
|
71
|
+
async function runWithConcurrency(items, limit, worker, signal) {
|
|
72
|
+
if (signal.aborted) throw abortError();
|
|
73
|
+
if (!Number.isSafeInteger(limit) || limit < 1) throw new Error("Concurrency limit must be positive.");
|
|
74
|
+
const results = new Array(items.length);
|
|
75
|
+
let nextIndex = 0;
|
|
76
|
+
const runners = Array.from({ length: Math.min(limit, items.length) }, async () => {
|
|
77
|
+
while (nextIndex < items.length) {
|
|
78
|
+
if (signal.aborted) throw abortError();
|
|
79
|
+
const index = nextIndex;
|
|
80
|
+
nextIndex += 1;
|
|
81
|
+
try {
|
|
82
|
+
results[index] = {
|
|
83
|
+
status: "fulfilled",
|
|
84
|
+
value: await worker(items[index], index, signal)
|
|
85
|
+
};
|
|
86
|
+
} catch (reason) {
|
|
87
|
+
results[index] = { status: "rejected", reason };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
});
|
|
91
|
+
await Promise.all(runners);
|
|
92
|
+
if (signal.aborted) throw abortError();
|
|
93
|
+
return results;
|
|
94
|
+
}
|
|
95
|
+
async function awaitWithDeadline(operation, signal, timeoutMs, description) {
|
|
96
|
+
if (signal.aborted) throw abortError();
|
|
97
|
+
const controller = new AbortController();
|
|
98
|
+
const abortFromCaller = () => controller.abort();
|
|
99
|
+
signal.addEventListener("abort", abortFromCaller, { once: true });
|
|
100
|
+
const timeout = setTimeout(() => controller.abort(), timeoutMs);
|
|
101
|
+
try {
|
|
102
|
+
return await Promise.race([
|
|
103
|
+
operation,
|
|
104
|
+
new Promise((_resolve, reject) => {
|
|
105
|
+
controller.signal.addEventListener(
|
|
106
|
+
"abort",
|
|
107
|
+
() => {
|
|
108
|
+
reject(
|
|
109
|
+
signal.aborted ? abortError() : Object.assign(new Error(`Timed out after ${Math.round(timeoutMs / 1e3)}s ${description}.`), {
|
|
110
|
+
name: "TimeoutError"
|
|
111
|
+
})
|
|
112
|
+
);
|
|
113
|
+
},
|
|
114
|
+
{ once: true }
|
|
115
|
+
);
|
|
116
|
+
})
|
|
117
|
+
]);
|
|
118
|
+
} finally {
|
|
119
|
+
clearTimeout(timeout);
|
|
120
|
+
signal.removeEventListener("abort", abortFromCaller);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
function sanitizeDisplayText(value, maxChars = 160) {
|
|
124
|
+
let result = "";
|
|
125
|
+
for (let index = 0; index < value.length; ) {
|
|
126
|
+
const codePoint = value.codePointAt(index) ?? 0;
|
|
127
|
+
const character = String.fromCodePoint(codePoint);
|
|
128
|
+
if (codePoint === 27 || codePoint === 155 || codePoint === 157) {
|
|
129
|
+
index = skipTerminalEscape(value, index, codePoint);
|
|
130
|
+
continue;
|
|
131
|
+
}
|
|
132
|
+
if (codePoint <= 31 || codePoint >= 127 && codePoint <= 159) {
|
|
133
|
+
if (codePoint === 9 || codePoint === 10 || codePoint === 13) result += " ";
|
|
134
|
+
index += character.length;
|
|
135
|
+
continue;
|
|
136
|
+
}
|
|
137
|
+
result += character;
|
|
138
|
+
index += character.length;
|
|
139
|
+
}
|
|
140
|
+
return truncate(result.replace(/\s+/gu, " ").trim(), maxChars);
|
|
141
|
+
}
|
|
142
|
+
function redactUsageError(value, secrets = []) {
|
|
143
|
+
let redacted = value;
|
|
144
|
+
for (const secret of [...new Set(secrets)].filter(Boolean).sort((a, b) => b.length - a.length)) {
|
|
145
|
+
redacted = redacted.replace(new RegExp(escapeRegExp(secret), "g"), "<redacted>");
|
|
146
|
+
}
|
|
147
|
+
redacted = redacted.replace(/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer <redacted>").replace(/"(?:access_token|refresh_token|api_key)"\s*:\s*"[^"]+"/gi, (match) => {
|
|
148
|
+
const separator = match.indexOf(":");
|
|
149
|
+
return `${match.slice(0, separator + 1)}"<redacted>"`;
|
|
150
|
+
});
|
|
151
|
+
return sanitizeDisplayText(redacted, 600);
|
|
152
|
+
}
|
|
153
|
+
function errorMessage(error) {
|
|
154
|
+
return sanitizeDisplayText(error instanceof Error ? error.message : String(error), 600);
|
|
155
|
+
}
|
|
156
|
+
function abortError() {
|
|
157
|
+
return Object.assign(new Error("Usage query aborted."), { name: "AbortError" });
|
|
158
|
+
}
|
|
159
|
+
function skipTerminalEscape(value, start, codePoint) {
|
|
160
|
+
let index = start + 1;
|
|
161
|
+
const next = value.charCodeAt(index);
|
|
162
|
+
const isOsc = codePoint === 157 || codePoint === 27 && next === 93;
|
|
163
|
+
if (isOsc) {
|
|
164
|
+
if (codePoint === 27) index += 1;
|
|
165
|
+
while (index < value.length) {
|
|
166
|
+
const current = value.charCodeAt(index);
|
|
167
|
+
if (current === 7) return index + 1;
|
|
168
|
+
if (current === 27 && value.charCodeAt(index + 1) === 92) return index + 2;
|
|
169
|
+
index += 1;
|
|
170
|
+
}
|
|
171
|
+
return index;
|
|
172
|
+
}
|
|
173
|
+
const isCsi = codePoint === 155 || codePoint === 27 && next === 91;
|
|
174
|
+
if (isCsi) {
|
|
175
|
+
if (codePoint === 27) index += 1;
|
|
176
|
+
while (index < value.length) {
|
|
177
|
+
const current = value.charCodeAt(index);
|
|
178
|
+
index += 1;
|
|
179
|
+
if (current >= 64 && current <= 126) break;
|
|
180
|
+
}
|
|
181
|
+
return index;
|
|
182
|
+
}
|
|
183
|
+
return Math.min(value.length, start + (codePoint === 27 ? 2 : 1));
|
|
184
|
+
}
|
|
185
|
+
function cacheKey(providerId, fingerprint) {
|
|
186
|
+
return `${providerId}:${fingerprint}`;
|
|
187
|
+
}
|
|
188
|
+
function escapeRegExp(value) {
|
|
189
|
+
return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
190
|
+
}
|
|
191
|
+
function truncate(value, maxChars) {
|
|
192
|
+
if (value.length <= maxChars) return value;
|
|
193
|
+
return `${value.slice(0, maxChars - 1)}\u2026`;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// src/oauth-credential-source.ts
|
|
197
|
+
import { readStoredCredential } from "@earendil-works/pi-coding-agent";
|
|
198
|
+
var OAUTH_CREDENTIAL_SOURCE_CHANNEL = "oauth:credential-source:v1";
|
|
199
|
+
var OAUTH_CREDENTIAL_READINESS_CHANNEL = "oauth:credential-readiness:v1";
|
|
200
|
+
function createOAuthCredentialCandidateReader(pi, credentialReader = readStoredCredential) {
|
|
201
|
+
const reader = (ctx, providerId) => collectOAuthCredentialCandidates(pi, ctx, providerId, credentialReader);
|
|
202
|
+
reader.waitUntilReady = (ctx, providerId) => waitForOAuthCredentialSources(pi, ctx, providerId);
|
|
203
|
+
return reader;
|
|
204
|
+
}
|
|
205
|
+
function collectOAuthCredentialCandidates(pi, ctx, providerId, credentialReader = readStoredCredential) {
|
|
206
|
+
const candidates = [];
|
|
207
|
+
let collecting = true;
|
|
208
|
+
const request = Object.freeze({
|
|
209
|
+
session: ctx.sessionManager,
|
|
210
|
+
provider: providerId,
|
|
211
|
+
offer(candidate) {
|
|
212
|
+
if (!collecting) return;
|
|
213
|
+
const clone = cloneOAuthCredential(candidate);
|
|
214
|
+
if (clone) candidates.push(clone);
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
try {
|
|
218
|
+
pi.events.emit(OAUTH_CREDENTIAL_SOURCE_CHANNEL, request);
|
|
219
|
+
} catch {
|
|
220
|
+
return { ok: false };
|
|
221
|
+
} finally {
|
|
222
|
+
collecting = false;
|
|
223
|
+
}
|
|
224
|
+
const offeredCount = candidates.length;
|
|
225
|
+
try {
|
|
226
|
+
const fallback = cloneOAuthCredential(credentialReader(providerId));
|
|
227
|
+
if (fallback) candidates.push(fallback);
|
|
228
|
+
} catch {
|
|
229
|
+
}
|
|
230
|
+
return { ok: true, candidates, offeredCount };
|
|
231
|
+
}
|
|
232
|
+
async function waitForOAuthCredentialSources(pi, ctx, providerId) {
|
|
233
|
+
const pending = [];
|
|
234
|
+
let collecting = true;
|
|
235
|
+
const request = Object.freeze({
|
|
236
|
+
session: ctx.sessionManager,
|
|
237
|
+
provider: providerId,
|
|
238
|
+
waitUntil(value) {
|
|
239
|
+
if (!collecting || !(value instanceof Promise)) return;
|
|
240
|
+
pending.push(value);
|
|
241
|
+
}
|
|
242
|
+
});
|
|
243
|
+
try {
|
|
244
|
+
pi.events.emit(OAUTH_CREDENTIAL_READINESS_CHANNEL, request);
|
|
245
|
+
} catch {
|
|
246
|
+
return false;
|
|
247
|
+
} finally {
|
|
248
|
+
collecting = false;
|
|
249
|
+
}
|
|
250
|
+
try {
|
|
251
|
+
await Promise.all(pending);
|
|
252
|
+
return true;
|
|
253
|
+
} catch {
|
|
254
|
+
return false;
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
function fallbackOAuthCredentialCandidates(providerId, credentialReader) {
|
|
258
|
+
try {
|
|
259
|
+
const credential = cloneOAuthCredential(credentialReader(providerId));
|
|
260
|
+
return { ok: true, candidates: credential ? [credential] : [], offeredCount: 0 };
|
|
261
|
+
} catch {
|
|
262
|
+
return { ok: true, candidates: [], offeredCount: 0 };
|
|
263
|
+
}
|
|
264
|
+
}
|
|
265
|
+
function cloneOAuthCredential(value) {
|
|
266
|
+
try {
|
|
267
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
268
|
+
const clone = structuredClone(value);
|
|
269
|
+
if (!clone || typeof clone !== "object" || Array.isArray(clone)) return void 0;
|
|
270
|
+
if (clone.type !== "oauth") return void 0;
|
|
271
|
+
if (typeof clone.access !== "string" || !clone.access) return void 0;
|
|
272
|
+
if (typeof clone.refresh !== "string" || !clone.refresh) return void 0;
|
|
273
|
+
if (typeof clone.expires !== "number" || !Number.isFinite(clone.expires)) return void 0;
|
|
274
|
+
return clone;
|
|
275
|
+
} catch {
|
|
276
|
+
return void 0;
|
|
277
|
+
}
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
// src/providers/baseten.ts
|
|
281
|
+
var DECIMAL_AMOUNT = /^(?:0|[1-9]\d*)(?:\.\d+)?$/u;
|
|
282
|
+
function normalizeBasetenBillingUsagePayload(payload, capturedAt) {
|
|
283
|
+
if (payload.model_apis_usage === void 0 || payload.model_apis_usage === null) {
|
|
284
|
+
return report(capturedAt, [], ["Baseten returned no Model APIs usage for the last 30 days."]);
|
|
285
|
+
}
|
|
286
|
+
const usage = asObject(payload.model_apis_usage);
|
|
287
|
+
if (!usage) throw new Error("Baseten Model APIs usage was not an object.");
|
|
288
|
+
const metrics = [
|
|
289
|
+
metric("gross-usage", "Gross usage", usage.total),
|
|
290
|
+
metric("credits-used", "Credits used", usage.credits_used),
|
|
291
|
+
metric("net-subtotal", "Net subtotal", usage.subtotal)
|
|
292
|
+
];
|
|
293
|
+
return report(capturedAt, metrics);
|
|
294
|
+
}
|
|
295
|
+
function report(capturedAt, metrics, notes) {
|
|
296
|
+
return {
|
|
297
|
+
providerId: "baseten",
|
|
298
|
+
providerName: "Baseten",
|
|
299
|
+
capturedAt,
|
|
300
|
+
source: "baseten-billing-usage-summary",
|
|
301
|
+
semantics: { kind: "api-key", label: "Organization Model APIs spend" },
|
|
302
|
+
buckets: [],
|
|
303
|
+
metrics,
|
|
304
|
+
...notes ? { notes } : {}
|
|
305
|
+
};
|
|
306
|
+
}
|
|
307
|
+
function metric(id, label, value) {
|
|
308
|
+
const amount2 = decimalAmount(value, label);
|
|
309
|
+
return { id, label, value: amount2, unit: "currency", currency: "USD" };
|
|
310
|
+
}
|
|
311
|
+
function decimalAmount(value, label) {
|
|
312
|
+
const normalized = typeof value === "number" && Number.isFinite(value) ? String(value) : value;
|
|
313
|
+
if (typeof normalized !== "string" || normalized.length > 64 || !DECIMAL_AMOUNT.test(normalized)) {
|
|
314
|
+
throw new Error(`Baseten ${label.toLowerCase()} was not a valid nonnegative amount.`);
|
|
315
|
+
}
|
|
316
|
+
return normalized;
|
|
317
|
+
}
|
|
318
|
+
function asObject(value) {
|
|
319
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
320
|
+
return value;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// src/providers/codex.ts
|
|
324
|
+
function normalizeCodexBackendPayload(payload, capturedAt) {
|
|
325
|
+
const buckets = [];
|
|
326
|
+
normalizeRateLimitGroup(buckets, "codex", "Codex", payload.rate_limit, false);
|
|
327
|
+
const additional = Array.isArray(payload.additional_rate_limits) ? payload.additional_rate_limits : [];
|
|
328
|
+
for (const item of additional) {
|
|
329
|
+
const value = asObject2(item);
|
|
330
|
+
const id = asString(value?.metered_feature) ?? asString(value?.limit_name);
|
|
331
|
+
if (!value || !id) continue;
|
|
332
|
+
try {
|
|
333
|
+
normalizeRateLimitGroup(buckets, id, asString(value.limit_name) ?? id, value.rate_limit, true);
|
|
334
|
+
} catch {
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
const metrics = [];
|
|
338
|
+
const credits = asObject2(payload.credits);
|
|
339
|
+
if (credits?.has_credits === true) {
|
|
340
|
+
if (credits.unlimited === true) {
|
|
341
|
+
metrics.push({ id: "credits", label: "Credits", value: "unlimited" });
|
|
342
|
+
} else {
|
|
343
|
+
const balance = asNumber(credits.balance);
|
|
344
|
+
if (balance !== void 0) {
|
|
345
|
+
metrics.push({ id: "credits", label: "Credits", value: balance, unit: "count" });
|
|
346
|
+
} else {
|
|
347
|
+
metrics.push({ id: "credits", label: "Credits", value: "available" });
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
} else if (credits?.has_credits === false) {
|
|
351
|
+
metrics.push({ id: "credits", label: "Credits", value: "none" });
|
|
352
|
+
}
|
|
353
|
+
const resetCredits = asObject2(payload.rate_limit_reset_credits);
|
|
354
|
+
const resetCount = asNonnegativeInteger(resetCredits?.available_count);
|
|
355
|
+
if (resetCount !== void 0) {
|
|
356
|
+
metrics.push({
|
|
357
|
+
id: "reset-credits",
|
|
358
|
+
label: "Usage limit resets",
|
|
359
|
+
value: resetCount,
|
|
360
|
+
unit: "count"
|
|
361
|
+
});
|
|
362
|
+
}
|
|
363
|
+
if (buckets.length === 0 && metrics.length === 0) {
|
|
364
|
+
throw new Error("Codex usage endpoint returned no displayable usage data.");
|
|
365
|
+
}
|
|
366
|
+
const planType = asString(payload.plan_type);
|
|
367
|
+
return {
|
|
368
|
+
providerId: "openai-codex",
|
|
369
|
+
providerName: "OpenAI Codex",
|
|
370
|
+
capturedAt,
|
|
371
|
+
source: "codex-pi-auth",
|
|
372
|
+
semantics: {
|
|
373
|
+
kind: "consumer-subscription",
|
|
374
|
+
label: "ChatGPT subscription limits"
|
|
375
|
+
},
|
|
376
|
+
buckets,
|
|
377
|
+
metrics,
|
|
378
|
+
...planType ? { notes: [`Plan: ${planType}`] } : {}
|
|
379
|
+
};
|
|
380
|
+
}
|
|
381
|
+
function normalizeRateLimitGroup(buckets, groupId, groupLabel, raw, optional) {
|
|
382
|
+
if (raw === void 0 || raw === null) return;
|
|
383
|
+
const details = asObject2(raw);
|
|
384
|
+
if (!details) {
|
|
385
|
+
if (optional) return;
|
|
386
|
+
throw new Error("Codex rate limit was not an object.");
|
|
387
|
+
}
|
|
388
|
+
addWindow(buckets, groupId, groupLabel, "primary", details.primary_window);
|
|
389
|
+
addWindow(buckets, groupId, groupLabel, "secondary", details.secondary_window);
|
|
390
|
+
}
|
|
391
|
+
function addWindow(buckets, groupId, groupLabel, position, raw) {
|
|
392
|
+
if (raw === void 0 || raw === null) return;
|
|
393
|
+
const value = asObject2(raw);
|
|
394
|
+
if (!value) throw new Error("Codex rate-limit window was not an object.");
|
|
395
|
+
const used = asNumber(value.used_percent);
|
|
396
|
+
if (used === void 0) return;
|
|
397
|
+
const seconds = asNumber(value.limit_window_seconds);
|
|
398
|
+
const resetsAt = asNumber(value.reset_at);
|
|
399
|
+
buckets.push({
|
|
400
|
+
id: `${groupId}:${position}`,
|
|
401
|
+
label: position === "primary" ? "Primary limit" : "Secondary limit",
|
|
402
|
+
groupId,
|
|
403
|
+
groupLabel,
|
|
404
|
+
modelKeys: [groupId, groupLabel],
|
|
405
|
+
used,
|
|
406
|
+
remaining: 100 - clampPercent(used),
|
|
407
|
+
limit: 100,
|
|
408
|
+
unit: "percent",
|
|
409
|
+
...seconds !== void 0 && seconds > 0 ? { windowMinutes: Math.ceil(seconds / 60) } : {},
|
|
410
|
+
...resetsAt !== void 0 ? { resetsAt } : {}
|
|
411
|
+
});
|
|
412
|
+
}
|
|
413
|
+
function asObject2(value) {
|
|
414
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
415
|
+
return value;
|
|
416
|
+
}
|
|
417
|
+
function asString(value) {
|
|
418
|
+
if (typeof value !== "string") return void 0;
|
|
419
|
+
return sanitizeDisplayText(value, 160) || void 0;
|
|
420
|
+
}
|
|
421
|
+
function asNumber(value) {
|
|
422
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
423
|
+
if (typeof value === "string" && value.trim()) {
|
|
424
|
+
const parsed = Number(value);
|
|
425
|
+
return Number.isFinite(parsed) ? parsed : void 0;
|
|
426
|
+
}
|
|
427
|
+
return void 0;
|
|
428
|
+
}
|
|
429
|
+
function asNonnegativeInteger(value) {
|
|
430
|
+
const parsed = asNumber(value);
|
|
431
|
+
if (parsed === void 0 || !Number.isSafeInteger(parsed)) return void 0;
|
|
432
|
+
return Math.max(0, parsed);
|
|
433
|
+
}
|
|
434
|
+
function clampPercent(value) {
|
|
435
|
+
return Math.min(100, Math.max(0, value));
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
// src/providers/deepseek.ts
|
|
439
|
+
var CURRENCIES = ["CNY", "USD"];
|
|
440
|
+
var BALANCE_FIELDS = [
|
|
441
|
+
["total", "Total balance", "total_balance"],
|
|
442
|
+
["granted", "Granted balance", "granted_balance"],
|
|
443
|
+
["topped-up", "Topped-up balance", "topped_up_balance"]
|
|
444
|
+
];
|
|
445
|
+
function normalizeDeepSeekBalancePayload(payload, capturedAt) {
|
|
446
|
+
if (typeof payload.is_available !== "boolean") {
|
|
447
|
+
throw new Error("DeepSeek API balance response availability was not a boolean.");
|
|
448
|
+
}
|
|
449
|
+
if (!Array.isArray(payload.balance_infos) || payload.balance_infos.length === 0) {
|
|
450
|
+
throw new Error("DeepSeek API balance response returned no balance information.");
|
|
451
|
+
}
|
|
452
|
+
const balances = /* @__PURE__ */ new Map();
|
|
453
|
+
for (const raw of payload.balance_infos) {
|
|
454
|
+
const balance = asObject3(raw);
|
|
455
|
+
if (!balance) throw new Error("DeepSeek API balance row was not an object.");
|
|
456
|
+
const currency = deepSeekCurrency(balance.currency);
|
|
457
|
+
if (!currency) throw new Error("DeepSeek API balance row returned an unsupported currency.");
|
|
458
|
+
if (balances.has(currency)) {
|
|
459
|
+
throw new Error(`DeepSeek API balance response repeated ${currency}.`);
|
|
460
|
+
}
|
|
461
|
+
for (const [, label, field] of BALANCE_FIELDS) {
|
|
462
|
+
if (!decimalAmount2(balance[field])) {
|
|
463
|
+
throw new Error(`DeepSeek API balance ${label.toLowerCase()} was not a valid amount.`);
|
|
464
|
+
}
|
|
465
|
+
}
|
|
466
|
+
balances.set(currency, balance);
|
|
467
|
+
}
|
|
468
|
+
const metrics = [
|
|
469
|
+
{
|
|
470
|
+
id: "api-availability",
|
|
471
|
+
label: "API calls",
|
|
472
|
+
value: payload.is_available ? "available" : "unavailable"
|
|
473
|
+
}
|
|
474
|
+
];
|
|
475
|
+
for (const currency of CURRENCIES) {
|
|
476
|
+
const balance = balances.get(currency);
|
|
477
|
+
if (!balance) continue;
|
|
478
|
+
for (const [id, label, field] of BALANCE_FIELDS) {
|
|
479
|
+
metrics.push({
|
|
480
|
+
id: `${currency.toLowerCase()}-${id}`,
|
|
481
|
+
label,
|
|
482
|
+
value: balance[field],
|
|
483
|
+
unit: "currency",
|
|
484
|
+
currency
|
|
485
|
+
});
|
|
486
|
+
}
|
|
487
|
+
}
|
|
488
|
+
return {
|
|
489
|
+
providerId: "deepseek",
|
|
490
|
+
providerName: "DeepSeek",
|
|
491
|
+
capturedAt,
|
|
492
|
+
source: "deepseek-balance",
|
|
493
|
+
semantics: { kind: "api-key", label: "DeepSeek API balance" },
|
|
494
|
+
buckets: [],
|
|
495
|
+
metrics
|
|
496
|
+
};
|
|
497
|
+
}
|
|
498
|
+
function asObject3(value) {
|
|
499
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
500
|
+
return value;
|
|
501
|
+
}
|
|
502
|
+
function deepSeekCurrency(value) {
|
|
503
|
+
return CURRENCIES.find((currency) => currency === value);
|
|
504
|
+
}
|
|
505
|
+
function decimalAmount2(value) {
|
|
506
|
+
return typeof value === "string" && value.length <= 64 && /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/u.test(value);
|
|
507
|
+
}
|
|
508
|
+
|
|
509
|
+
// src/providers/fireworks.ts
|
|
510
|
+
var NANOS_PER_UNIT = 1000000000n;
|
|
511
|
+
var CURRENCY_PATTERN = /^[A-Z]{3}$/u;
|
|
512
|
+
var ACCOUNT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._~-]{0,127}$/u;
|
|
513
|
+
var INTEGER_PATTERN = /^-?\d+$/u;
|
|
514
|
+
var INT64_MIN = -(2n ** 63n);
|
|
515
|
+
var INT64_MAX = 2n ** 63n - 1n;
|
|
516
|
+
var MAX_UNITS_CHARS = 20;
|
|
517
|
+
var MAX_NANOS_CHARS = 11;
|
|
518
|
+
var FIREWORKS_BILLING_SUMMARY_ORIGIN = "https://api.fireworks.ai";
|
|
519
|
+
var FIREWORKS_SPEND_WINDOW_DAYS = 30;
|
|
520
|
+
var FIREWORKS_MAX_ACCOUNT_PAGES = 5;
|
|
521
|
+
var SERIES_KEYS = ["serverless", "dedicated", "training", "other"];
|
|
522
|
+
var SERIES_LABELS = {
|
|
523
|
+
serverless: "Serverless",
|
|
524
|
+
dedicated: "Dedicated deployments",
|
|
525
|
+
training: "Training",
|
|
526
|
+
other: "Other"
|
|
527
|
+
};
|
|
528
|
+
function isFireworksAccountId(value) {
|
|
529
|
+
return typeof value === "string" && ACCOUNT_ID_PATTERN.test(value);
|
|
530
|
+
}
|
|
531
|
+
function normalizeFireworksAccountsPayload(payload) {
|
|
532
|
+
if (!Array.isArray(payload.accounts)) {
|
|
533
|
+
throw new Error("Fireworks accounts response did not contain an accounts array.");
|
|
534
|
+
}
|
|
535
|
+
const accounts = [];
|
|
536
|
+
for (const raw of payload.accounts) {
|
|
537
|
+
const account = asObject4(raw);
|
|
538
|
+
if (!account) throw new Error("Fireworks accounts response row was not an object.");
|
|
539
|
+
if (typeof account.name !== "string") {
|
|
540
|
+
throw new Error("Fireworks accounts response omitted the account resource name.");
|
|
541
|
+
}
|
|
542
|
+
const match = /^accounts\/([^/]+)$/u.exec(account.name);
|
|
543
|
+
if (!match || !isFireworksAccountId(match[1])) {
|
|
544
|
+
throw new Error("Fireworks accounts response returned an unsafe account resource name.");
|
|
545
|
+
}
|
|
546
|
+
const accountId = match[1];
|
|
547
|
+
if (accounts.includes(accountId)) {
|
|
548
|
+
throw new Error(`Fireworks accounts response repeated ${accountId}.`);
|
|
549
|
+
}
|
|
550
|
+
accounts.push(accountId);
|
|
551
|
+
}
|
|
552
|
+
return accounts;
|
|
553
|
+
}
|
|
554
|
+
function createFireworksAdapter(fetchProviderJson2) {
|
|
555
|
+
return {
|
|
556
|
+
id: "fireworks",
|
|
557
|
+
displayName: "Fireworks",
|
|
558
|
+
semantics: { kind: "api-key", label: "Fireworks API spend" },
|
|
559
|
+
targets: {
|
|
560
|
+
singularLabel: "account",
|
|
561
|
+
pluralLabel: "accounts",
|
|
562
|
+
async list(auth, signal, timeoutMs, guard) {
|
|
563
|
+
const startedAt = Date.now();
|
|
564
|
+
const accounts = [];
|
|
565
|
+
let pageToken;
|
|
566
|
+
for (let page = 0; page < FIREWORKS_MAX_ACCOUNT_PAGES; page += 1) {
|
|
567
|
+
await guard();
|
|
568
|
+
const payload = await fetchProviderJson2(
|
|
569
|
+
fireworksAccountsUrl(pageToken),
|
|
570
|
+
auth,
|
|
571
|
+
signal,
|
|
572
|
+
remainingTimeout(timeoutMs, startedAt, "fetching Fireworks accounts"),
|
|
573
|
+
"Fireworks accounts endpoint",
|
|
574
|
+
{ redirect: "error" }
|
|
575
|
+
);
|
|
576
|
+
await guard();
|
|
577
|
+
for (const accountId of normalizeFireworksAccountsPayload(payload)) {
|
|
578
|
+
if (accounts.includes(accountId)) {
|
|
579
|
+
throw new Error(`Fireworks accounts listing repeated ${accountId}.`);
|
|
580
|
+
}
|
|
581
|
+
accounts.push(accountId);
|
|
582
|
+
}
|
|
583
|
+
pageToken = fireworksNextPageToken(payload.nextPageToken);
|
|
584
|
+
if (!pageToken) break;
|
|
585
|
+
}
|
|
586
|
+
if (pageToken) {
|
|
587
|
+
throw new Error(`Fireworks account listing exceeded ${FIREWORKS_MAX_ACCOUNT_PAGES} pages.`);
|
|
588
|
+
}
|
|
589
|
+
return accounts.map((id) => ({ id, label: id }));
|
|
590
|
+
}
|
|
591
|
+
},
|
|
592
|
+
async query(auth, signal, timeoutMs, guard, targetId) {
|
|
593
|
+
if (!guard) throw new Error("Fireworks API spend requires request-boundary revalidation.");
|
|
594
|
+
if (!isFireworksAccountId(targetId)) {
|
|
595
|
+
throw new Error("Fireworks billing requires a safe selected account slug.");
|
|
596
|
+
}
|
|
597
|
+
const startedAt = Date.now();
|
|
598
|
+
await guard();
|
|
599
|
+
const billingWindowAt = Date.now();
|
|
600
|
+
const payload = await fetchProviderJson2(
|
|
601
|
+
fireworksBillingSummaryUrl(targetId, billingWindowAt),
|
|
602
|
+
auth,
|
|
603
|
+
signal,
|
|
604
|
+
remainingTimeout(timeoutMs, startedAt, "fetching Fireworks rated spend"),
|
|
605
|
+
"Fireworks billing summary endpoint",
|
|
606
|
+
{ redirect: "error" }
|
|
607
|
+
);
|
|
608
|
+
await guard();
|
|
609
|
+
return normalizeFireworksBillingSummaryPayload(payload, targetId, Date.now());
|
|
610
|
+
}
|
|
611
|
+
};
|
|
612
|
+
}
|
|
613
|
+
function normalizeFireworksBillingSummaryPayload(payload, accountId, capturedAt) {
|
|
614
|
+
if (!isFireworksAccountId(accountId)) {
|
|
615
|
+
throw new Error("Fireworks billing summary received an unsafe account identifier.");
|
|
616
|
+
}
|
|
617
|
+
if (payload.lineItems !== void 0 && !Array.isArray(payload.lineItems)) {
|
|
618
|
+
throw new Error("Fireworks billing summary lineItems was not an array.");
|
|
619
|
+
}
|
|
620
|
+
const totals = /* @__PURE__ */ new Map();
|
|
621
|
+
for (const raw of payload.lineItems ?? []) {
|
|
622
|
+
const lineItem = asObject4(raw);
|
|
623
|
+
if (!lineItem) throw new Error("Fireworks billing line item was not an object.");
|
|
624
|
+
const cost = moneyAmount(lineItem.totalCost, "line item total cost");
|
|
625
|
+
const series = seriesKey(lineItem.series);
|
|
626
|
+
let amounts = totals.get(cost.currency);
|
|
627
|
+
if (!amounts) {
|
|
628
|
+
amounts = /* @__PURE__ */ new Map();
|
|
629
|
+
totals.set(cost.currency, amounts);
|
|
630
|
+
}
|
|
631
|
+
amounts.set(series, (amounts.get(series) ?? 0n) + cost.amount);
|
|
632
|
+
}
|
|
633
|
+
const metrics = [];
|
|
634
|
+
for (const [currency, amounts] of totals) {
|
|
635
|
+
metrics.push({
|
|
636
|
+
id: `${currency.toLowerCase()}-total`,
|
|
637
|
+
label: "Total spend",
|
|
638
|
+
value: formatMoneyAmount(sumSeries(amounts)),
|
|
639
|
+
unit: "currency",
|
|
640
|
+
currency
|
|
641
|
+
});
|
|
642
|
+
for (const series of SERIES_KEYS) {
|
|
643
|
+
const amount2 = amounts.get(series);
|
|
644
|
+
if (amount2 === void 0) continue;
|
|
645
|
+
metrics.push({
|
|
646
|
+
id: `${currency.toLowerCase()}-${series}`,
|
|
647
|
+
label: SERIES_LABELS[series],
|
|
648
|
+
value: formatMoneyAmount(amount2),
|
|
649
|
+
unit: "currency",
|
|
650
|
+
currency
|
|
651
|
+
});
|
|
652
|
+
}
|
|
653
|
+
}
|
|
654
|
+
const notes = ["Rated line items may differ from the final invoice once credits or adjustments are applied."];
|
|
655
|
+
if (metrics.length === 0) {
|
|
656
|
+
notes.push("Fireworks returned no rated line items for the last 30 days.");
|
|
657
|
+
}
|
|
658
|
+
return {
|
|
659
|
+
providerId: "fireworks",
|
|
660
|
+
providerName: "Fireworks",
|
|
661
|
+
capturedAt,
|
|
662
|
+
source: "fireworks-billing-summary",
|
|
663
|
+
semantics: { kind: "api-key", label: "Fireworks API spend" },
|
|
664
|
+
accountLabel: sanitizeDisplayText(accountId, 80),
|
|
665
|
+
buckets: [],
|
|
666
|
+
metrics,
|
|
667
|
+
notes
|
|
668
|
+
};
|
|
669
|
+
}
|
|
670
|
+
function moneyAmount(value, description) {
|
|
671
|
+
const money = asObject4(value);
|
|
672
|
+
if (!money) throw new Error(`Fireworks billing ${description} was not a money object.`);
|
|
673
|
+
const currency = typeof money.currencyCode === "string" ? money.currencyCode : void 0;
|
|
674
|
+
if (!currency || !CURRENCY_PATTERN.test(currency)) {
|
|
675
|
+
throw new Error(`Fireworks billing ${description} currency was not an ISO 4217 code.`);
|
|
676
|
+
}
|
|
677
|
+
const units = money.units === void 0 ? 0n : integerComponent(money.units, description, "whole units", MAX_UNITS_CHARS);
|
|
678
|
+
if (units < INT64_MIN || units > INT64_MAX) {
|
|
679
|
+
throw new Error(`Fireworks billing ${description} whole units exceeded the int64 range.`);
|
|
680
|
+
}
|
|
681
|
+
const nanos = money.nanos === void 0 ? 0n : integerComponent(money.nanos, description, "nano units", MAX_NANOS_CHARS);
|
|
682
|
+
if (nanos <= -NANOS_PER_UNIT || nanos >= NANOS_PER_UNIT) {
|
|
683
|
+
throw new Error(`Fireworks billing ${description} nano units exceeded the Money range.`);
|
|
684
|
+
}
|
|
685
|
+
if (units > 0n && nanos < 0n || units < 0n && nanos > 0n) {
|
|
686
|
+
throw new Error(`Fireworks billing ${description} mixed unit and nano signs.`);
|
|
687
|
+
}
|
|
688
|
+
return { currency, amount: units * NANOS_PER_UNIT + nanos };
|
|
689
|
+
}
|
|
690
|
+
function integerComponent(value, description, component, maxChars) {
|
|
691
|
+
const text = typeof value === "number" && Number.isSafeInteger(value) ? String(value) : typeof value === "string" && INTEGER_PATTERN.test(value) ? value : void 0;
|
|
692
|
+
if (text === void 0 || text.length > maxChars) {
|
|
693
|
+
throw new Error(`Fireworks billing ${description} ${component} was not a bounded integer.`);
|
|
694
|
+
}
|
|
695
|
+
return BigInt(text);
|
|
696
|
+
}
|
|
697
|
+
function seriesKey(value) {
|
|
698
|
+
if (value === void 0 || value === null) return "other";
|
|
699
|
+
if (typeof value !== "string") throw new Error("Fireworks billing line item series was invalid.");
|
|
700
|
+
if (value === "SERVERLESS") return "serverless";
|
|
701
|
+
if (value === "DEDICATED_DEPLOYMENT") return "dedicated";
|
|
702
|
+
if (value === "TRAINING") return "training";
|
|
703
|
+
return "other";
|
|
704
|
+
}
|
|
705
|
+
function sumSeries(amounts) {
|
|
706
|
+
let total = 0n;
|
|
707
|
+
for (const amount2 of amounts.values()) total += amount2;
|
|
708
|
+
return total;
|
|
709
|
+
}
|
|
710
|
+
function formatMoneyAmount(amount2) {
|
|
711
|
+
const negative = amount2 < 0n;
|
|
712
|
+
const magnitude = negative ? -amount2 : amount2;
|
|
713
|
+
const units = magnitude / NANOS_PER_UNIT;
|
|
714
|
+
const nanos = (magnitude % NANOS_PER_UNIT).toString().padStart(9, "0").replace(/0+$/u, "");
|
|
715
|
+
return `${negative ? "-" : ""}${units.toString()}${nanos ? `.${nanos}` : ""}`;
|
|
716
|
+
}
|
|
717
|
+
function fireworksAccountsUrl(pageToken) {
|
|
718
|
+
const url = new URL("/v1/accounts", FIREWORKS_BILLING_SUMMARY_ORIGIN);
|
|
719
|
+
url.searchParams.set("pageSize", "200");
|
|
720
|
+
if (pageToken !== void 0) url.searchParams.set("pageToken", pageToken);
|
|
721
|
+
return url.toString();
|
|
722
|
+
}
|
|
723
|
+
function fireworksNextPageToken(value) {
|
|
724
|
+
if (value === void 0 || value === null) return void 0;
|
|
725
|
+
if (typeof value !== "string" || !value || value.length > 512) {
|
|
726
|
+
throw new Error("Fireworks accounts listing returned an invalid page token.");
|
|
727
|
+
}
|
|
728
|
+
return value;
|
|
729
|
+
}
|
|
730
|
+
function fireworksBillingSummaryUrl(accountId, startedAt) {
|
|
731
|
+
const dayMs = 24 * 60 * 60 * 1e3;
|
|
732
|
+
const dayFloor = (time) => `${new Date(time).toISOString().slice(0, 10)}T00:00:00Z`;
|
|
733
|
+
const url = new URL(`/v1/accounts/${accountId}/billing/summary`, FIREWORKS_BILLING_SUMMARY_ORIGIN);
|
|
734
|
+
url.searchParams.set("startTime", dayFloor(startedAt - (FIREWORKS_SPEND_WINDOW_DAYS - 1) * dayMs));
|
|
735
|
+
url.searchParams.set("endTime", dayFloor(startedAt + dayMs));
|
|
736
|
+
return url.toString();
|
|
737
|
+
}
|
|
738
|
+
function remainingTimeout(timeoutMs, startedAt, description) {
|
|
739
|
+
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
740
|
+
if (remaining <= 0) throw new Error(`Timed out while ${description}.`);
|
|
741
|
+
return remaining;
|
|
742
|
+
}
|
|
743
|
+
function asObject4(value) {
|
|
744
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
745
|
+
return value;
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
// src/providers/github-copilot.ts
|
|
749
|
+
function normalizeGitHubCopilotUsagePayload(payload, capturedAt) {
|
|
750
|
+
const snapshots = asObject5(payload.quota_snapshots);
|
|
751
|
+
const premium = asObject5(snapshots?.premium_interactions);
|
|
752
|
+
const metrics = [];
|
|
753
|
+
let semanticsLabel;
|
|
754
|
+
let bucket;
|
|
755
|
+
if (premium) {
|
|
756
|
+
const tokenBasedBilling = premium.token_based_billing === true;
|
|
757
|
+
const id = tokenBasedBilling ? "ai-credits" : "premium-requests";
|
|
758
|
+
const label = tokenBasedBilling ? "AI credits" : "Premium requests";
|
|
759
|
+
semanticsLabel = tokenBasedBilling ? "GitHub Copilot AI Credits allowance" : "GitHub Copilot premium request quota";
|
|
760
|
+
if (premium.unlimited === true) {
|
|
761
|
+
bucket = { id, label, unit: "count" };
|
|
762
|
+
} else {
|
|
763
|
+
const entitlement = asNonnegativeNumber(premium.entitlement);
|
|
764
|
+
const rawRemaining = asFiniteNumber(premium.remaining) ?? asFiniteNumber(premium.quota_remaining);
|
|
765
|
+
if (entitlement === void 0 || rawRemaining === void 0) {
|
|
766
|
+
throw new Error(`GitHub Copilot ${label.toLowerCase()} quota was incomplete.`);
|
|
767
|
+
}
|
|
768
|
+
const overageUsed = Math.max(asNonnegativeNumber(premium.overage_count) ?? 0, Math.max(0, -rawRemaining));
|
|
769
|
+
if (overageUsed > 0) {
|
|
770
|
+
metrics.push({
|
|
771
|
+
id: "overage-used",
|
|
772
|
+
label: "Additional usage",
|
|
773
|
+
value: overageUsed,
|
|
774
|
+
unit: "count"
|
|
775
|
+
});
|
|
776
|
+
}
|
|
777
|
+
bucket = {
|
|
778
|
+
id,
|
|
779
|
+
label,
|
|
780
|
+
used: asNonnegativeNumber(premium.credits_used) ?? Math.max(0, entitlement - rawRemaining),
|
|
781
|
+
remaining: Math.max(0, rawRemaining),
|
|
782
|
+
limit: entitlement,
|
|
783
|
+
unit: "count",
|
|
784
|
+
period: "monthly",
|
|
785
|
+
...resetTimestamp(payload)
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
} else {
|
|
789
|
+
const limited = asObject5(payload.limited_user_quotas);
|
|
790
|
+
const monthly = asObject5(payload.monthly_quotas);
|
|
791
|
+
const remaining = asNonnegativeNumber(limited?.chat);
|
|
792
|
+
const entitlement = asNonnegativeNumber(monthly?.chat);
|
|
793
|
+
if (remaining === void 0 || entitlement === void 0) {
|
|
794
|
+
throw new Error("GitHub Copilot usage response contained no supported quota.");
|
|
795
|
+
}
|
|
796
|
+
semanticsLabel = "GitHub Copilot Free chat quota";
|
|
797
|
+
bucket = {
|
|
798
|
+
id: "chat-requests",
|
|
799
|
+
label: "Chat requests",
|
|
800
|
+
used: Math.max(0, entitlement - remaining),
|
|
801
|
+
remaining,
|
|
802
|
+
limit: entitlement,
|
|
803
|
+
unit: "count",
|
|
804
|
+
period: "monthly",
|
|
805
|
+
...resetTimestamp(payload)
|
|
806
|
+
};
|
|
807
|
+
}
|
|
808
|
+
const notes = [];
|
|
809
|
+
const plan = asString2(payload.copilot_plan) ?? asString2(payload.access_type_sku);
|
|
810
|
+
if (plan) notes.push(`Plan: ${plan}`);
|
|
811
|
+
return {
|
|
812
|
+
providerId: "github-copilot",
|
|
813
|
+
providerName: "GitHub Copilot",
|
|
814
|
+
capturedAt,
|
|
815
|
+
source: "github-copilot-user",
|
|
816
|
+
semantics: { kind: "consumer-subscription", label: semanticsLabel },
|
|
817
|
+
accountLabel: asString2(payload.login),
|
|
818
|
+
buckets: [bucket],
|
|
819
|
+
metrics,
|
|
820
|
+
...notes.length > 0 ? { notes } : {}
|
|
821
|
+
};
|
|
822
|
+
}
|
|
823
|
+
function resetTimestamp(payload) {
|
|
824
|
+
const raw = asString2(payload.quota_reset_date_utc) ?? asString2(payload.quota_reset_date) ?? asString2(payload.limited_user_reset_date);
|
|
825
|
+
if (!raw) return {};
|
|
826
|
+
const milliseconds = Date.parse(raw);
|
|
827
|
+
return Number.isNaN(milliseconds) ? {} : { resetsAt: Math.floor(milliseconds / 1e3) };
|
|
828
|
+
}
|
|
829
|
+
function asObject5(value) {
|
|
830
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
831
|
+
return value;
|
|
832
|
+
}
|
|
833
|
+
function asString2(value) {
|
|
834
|
+
if (typeof value !== "string") return void 0;
|
|
835
|
+
return sanitizeDisplayText(value, 80) || void 0;
|
|
836
|
+
}
|
|
837
|
+
function asFiniteNumber(value) {
|
|
838
|
+
if (typeof value !== "number" || !Number.isFinite(value)) return void 0;
|
|
839
|
+
return value;
|
|
840
|
+
}
|
|
841
|
+
function asNonnegativeNumber(value) {
|
|
842
|
+
const number = asFiniteNumber(value);
|
|
843
|
+
return number === void 0 || number < 0 ? void 0 : number;
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// src/providers/kimi-coding.ts
|
|
847
|
+
var FIVE_HOUR_WINDOW_MINUTES = 300;
|
|
848
|
+
var DAILY_WINDOW_MINUTES = 1440;
|
|
849
|
+
var WEEKLY_WINDOW_MINUTES = 10080;
|
|
850
|
+
var FIXED_POINT_UNITS_PER_CENT = 1e6;
|
|
851
|
+
var RATIO_WINDOWS = [
|
|
852
|
+
{ key: "limit_5h", id: "five-hour", label: "Five-hour window", windowMinutes: FIVE_HOUR_WINDOW_MINUTES },
|
|
853
|
+
{ key: "limit_week", id: "weekly", label: "Weekly window", windowMinutes: WEEKLY_WINDOW_MINUTES },
|
|
854
|
+
{ key: "limit_month_total", id: "monthly", label: "Monthly window" }
|
|
855
|
+
];
|
|
856
|
+
function normalizeKimiCodingUsagePayload(payload, capturedAt) {
|
|
857
|
+
const root = asObject6(payload);
|
|
858
|
+
if (!root) throw new Error("Kimi Coding usage response was not an object.");
|
|
859
|
+
const candidates = [];
|
|
860
|
+
const explicitWindows = /* @__PURE__ */ new Set();
|
|
861
|
+
let omittedWindow = false;
|
|
862
|
+
if (root.usage !== void 0) explicitWindows.add(WEEKLY_WINDOW_MINUTES);
|
|
863
|
+
const summary = parseUsageRow(root.usage, WEEKLY_WINDOW_MINUTES, "Weekly window");
|
|
864
|
+
if (summary) candidates.push(summary);
|
|
865
|
+
else if (root.usage !== void 0) omittedWindow = true;
|
|
866
|
+
if (Array.isArray(root.limits)) {
|
|
867
|
+
for (const raw of root.limits) {
|
|
868
|
+
const item = asObject6(raw);
|
|
869
|
+
const windowMinutes = parseWindowMinutes(item?.window);
|
|
870
|
+
if (windowMinutes !== void 0) explicitWindows.add(windowMinutes);
|
|
871
|
+
const label = sanitizedLabel(item?.name);
|
|
872
|
+
const bucket = windowMinutes === void 0 ? void 0 : parseUsageRow(item?.detail, windowMinutes, label ?? defaultWindowLabel(windowMinutes));
|
|
873
|
+
if (bucket) candidates.push(bucket);
|
|
874
|
+
else omittedWindow = true;
|
|
875
|
+
}
|
|
876
|
+
} else if (root.limits !== void 0) {
|
|
877
|
+
omittedWindow = true;
|
|
878
|
+
}
|
|
879
|
+
const buckets = [];
|
|
880
|
+
const byWindow = /* @__PURE__ */ new Map();
|
|
881
|
+
for (const bucket of candidates) {
|
|
882
|
+
const windowMinutes = bucket.windowMinutes;
|
|
883
|
+
byWindow.set(windowMinutes, [...byWindow.get(windowMinutes) ?? [], bucket]);
|
|
884
|
+
}
|
|
885
|
+
for (const rows of byWindow.values()) {
|
|
886
|
+
if (rows.length === 1) buckets.push(rows[0]);
|
|
887
|
+
else omittedWindow = true;
|
|
888
|
+
}
|
|
889
|
+
const usages = asObject6(root.usages);
|
|
890
|
+
if (root.usages !== void 0 && !usages) omittedWindow = true;
|
|
891
|
+
if (usages) {
|
|
892
|
+
for (const window of RATIO_WINDOWS) {
|
|
893
|
+
const raw = usages[window.key];
|
|
894
|
+
if (raw === void 0 || "windowMinutes" in window && explicitWindows.has(window.windowMinutes)) continue;
|
|
895
|
+
const bucket = parseRatioWindow(raw, window.id, window.label);
|
|
896
|
+
if (bucket) {
|
|
897
|
+
buckets.push({
|
|
898
|
+
...bucket,
|
|
899
|
+
..."windowMinutes" in window ? { windowMinutes: window.windowMinutes } : {}
|
|
900
|
+
});
|
|
901
|
+
} else omittedWindow = true;
|
|
902
|
+
}
|
|
903
|
+
}
|
|
904
|
+
buckets.sort((left, right) => (left.windowMinutes ?? Infinity) - (right.windowMinutes ?? Infinity));
|
|
905
|
+
const metrics = parseBoosterWallet(root.boosterWallet === void 0 ? root.booster_wallet : root.boosterWallet);
|
|
906
|
+
if (buckets.length === 0 && metrics.length === 0) {
|
|
907
|
+
throw new Error("Kimi Coding usage endpoint returned no displayable usage data.");
|
|
908
|
+
}
|
|
909
|
+
return {
|
|
910
|
+
providerId: "kimi-coding",
|
|
911
|
+
providerName: "Kimi For Coding",
|
|
912
|
+
capturedAt,
|
|
913
|
+
source: "kimi-managed-usage",
|
|
914
|
+
semantics: { kind: "consumer-subscription", label: "Kimi Coding Plan usage" },
|
|
915
|
+
buckets,
|
|
916
|
+
metrics,
|
|
917
|
+
...omittedWindow ? { notes: ["Unsupported, malformed, or duplicate plan windows were unavailable."] } : {}
|
|
918
|
+
};
|
|
919
|
+
}
|
|
920
|
+
function parseUsageRow(value, windowMinutes, label) {
|
|
921
|
+
const row = asObject6(value);
|
|
922
|
+
if (!row) return void 0;
|
|
923
|
+
const limit = asNonnegativeInteger2(row.limit);
|
|
924
|
+
if (limit === void 0 || limit === 0) return void 0;
|
|
925
|
+
const usedRaw = asNonnegativeInteger2(row.used);
|
|
926
|
+
const remainingRaw = asNonnegativeInteger2(row.remaining);
|
|
927
|
+
if (row.used !== void 0 && usedRaw === void 0 || row.remaining !== void 0 && remainingRaw === void 0) {
|
|
928
|
+
return void 0;
|
|
929
|
+
}
|
|
930
|
+
const used = usedRaw ?? (remainingRaw === void 0 ? 0 : Math.max(0, limit - remainingRaw));
|
|
931
|
+
const remaining = remainingRaw ?? Math.max(0, limit - used);
|
|
932
|
+
const resetsAt = asIsoEpochSeconds(row.resetTime);
|
|
933
|
+
return {
|
|
934
|
+
id: windowId(windowMinutes),
|
|
935
|
+
label,
|
|
936
|
+
used,
|
|
937
|
+
remaining,
|
|
938
|
+
limit,
|
|
939
|
+
unit: "count",
|
|
940
|
+
windowMinutes,
|
|
941
|
+
...resetsAt !== void 0 ? { resetsAt } : {}
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
function parseRatioWindow(value, id, label) {
|
|
945
|
+
const row = asObject6(value);
|
|
946
|
+
const ratio = row?.used_ratio;
|
|
947
|
+
if (typeof ratio !== "number" || !Number.isFinite(ratio) || ratio < 0 || ratio > 1) return void 0;
|
|
948
|
+
const resetsAt = asIsoEpochSeconds(row?.reset_time);
|
|
949
|
+
const used = ratio * 100;
|
|
950
|
+
return {
|
|
951
|
+
id,
|
|
952
|
+
label,
|
|
953
|
+
used,
|
|
954
|
+
remaining: 100 - used,
|
|
955
|
+
unit: "percent",
|
|
956
|
+
...resetsAt !== void 0 ? { resetsAt } : {}
|
|
957
|
+
};
|
|
958
|
+
}
|
|
959
|
+
function parseWindowMinutes(value) {
|
|
960
|
+
const window = asObject6(value);
|
|
961
|
+
if (!window) return void 0;
|
|
962
|
+
const duration = asPositiveInteger(window.duration);
|
|
963
|
+
if (duration === void 0) return void 0;
|
|
964
|
+
const multiplier = window.timeUnit === "TIME_UNIT_MINUTE" ? 1 : window.timeUnit === "TIME_UNIT_HOUR" ? 60 : window.timeUnit === "TIME_UNIT_DAY" ? 1440 : window.timeUnit === "TIME_UNIT_WEEK" ? 10080 : void 0;
|
|
965
|
+
if (multiplier === void 0) return void 0;
|
|
966
|
+
const minutes = duration * multiplier;
|
|
967
|
+
return Number.isSafeInteger(minutes) ? minutes : void 0;
|
|
968
|
+
}
|
|
969
|
+
function parseBoosterWallet(value) {
|
|
970
|
+
const wallet = asObject6(value);
|
|
971
|
+
const balance = asObject6(wallet?.balance);
|
|
972
|
+
if (!wallet || !balance || balance.type !== "BOOSTER") return [];
|
|
973
|
+
const totalRaw = asPositiveInteger(balance.amount);
|
|
974
|
+
if (totalRaw === void 0) return [];
|
|
975
|
+
const leftRaw = asNonnegativeInteger2(balance.amountLeft) ?? 0;
|
|
976
|
+
const monthlyLimit = parseMoney(wallet.monthlyChargeLimit);
|
|
977
|
+
const monthlyUsed = parseMoney(wallet.monthlyUsed);
|
|
978
|
+
const currencies = new Set(
|
|
979
|
+
[monthlyLimit?.currency, monthlyUsed?.currency].filter((currency2) => currency2 !== void 0)
|
|
980
|
+
);
|
|
981
|
+
if (currencies.size !== 1) return [];
|
|
982
|
+
const currency = currencies.values().next().value;
|
|
983
|
+
if (!currency) return [];
|
|
984
|
+
const total = fixedPointToMajor(totalRaw);
|
|
985
|
+
const left = fixedPointToMajor(leftRaw);
|
|
986
|
+
if (total === void 0 || left === void 0) return [];
|
|
987
|
+
const metrics = [
|
|
988
|
+
{ id: "booster-balance", label: "Balance", value: left, unit: "currency", currency },
|
|
989
|
+
{ id: "booster-total", label: "Total balance", value: total, unit: "currency", currency }
|
|
990
|
+
];
|
|
991
|
+
if (monthlyUsed) {
|
|
992
|
+
metrics.push({
|
|
993
|
+
id: "booster-monthly-used",
|
|
994
|
+
label: "Used this month",
|
|
995
|
+
value: monthlyUsed.cents / 100,
|
|
996
|
+
unit: "currency",
|
|
997
|
+
currency
|
|
998
|
+
});
|
|
999
|
+
}
|
|
1000
|
+
if (wallet.monthlyChargeLimitEnabled === false) {
|
|
1001
|
+
metrics.push({
|
|
1002
|
+
id: "booster-monthly-limit",
|
|
1003
|
+
label: "Monthly limit",
|
|
1004
|
+
value: "unlimited",
|
|
1005
|
+
unit: "currency",
|
|
1006
|
+
currency
|
|
1007
|
+
});
|
|
1008
|
+
} else if (wallet.monthlyChargeLimitEnabled === true && monthlyLimit) {
|
|
1009
|
+
metrics.push({
|
|
1010
|
+
id: "booster-monthly-limit",
|
|
1011
|
+
label: "Monthly limit",
|
|
1012
|
+
value: monthlyLimit.cents / 100,
|
|
1013
|
+
unit: "currency",
|
|
1014
|
+
currency
|
|
1015
|
+
});
|
|
1016
|
+
}
|
|
1017
|
+
return metrics;
|
|
1018
|
+
}
|
|
1019
|
+
function parseMoney(value) {
|
|
1020
|
+
const money = asObject6(value);
|
|
1021
|
+
if (!money) return void 0;
|
|
1022
|
+
const cents = asNonnegativeInteger2(money.priceInCents);
|
|
1023
|
+
if (cents === void 0) return void 0;
|
|
1024
|
+
const currency = asCurrency(money.currency);
|
|
1025
|
+
if (!currency) return void 0;
|
|
1026
|
+
return { cents, currency };
|
|
1027
|
+
}
|
|
1028
|
+
function fixedPointToMajor(value) {
|
|
1029
|
+
const cents = value / FIXED_POINT_UNITS_PER_CENT;
|
|
1030
|
+
const roundedCents = cents > 0 && cents < 1 ? 1 : Math.round(cents);
|
|
1031
|
+
const major = roundedCents / 100;
|
|
1032
|
+
return Number.isSafeInteger(roundedCents) && Number.isFinite(major) ? major : void 0;
|
|
1033
|
+
}
|
|
1034
|
+
function asObject6(value) {
|
|
1035
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
1036
|
+
return value;
|
|
1037
|
+
}
|
|
1038
|
+
function asNonnegativeInteger2(value) {
|
|
1039
|
+
if (typeof value === "string" && !/^\d+$/u.test(value)) return void 0;
|
|
1040
|
+
const number = typeof value === "string" ? Number(value) : value;
|
|
1041
|
+
if (typeof number !== "number" || !Number.isSafeInteger(number) || number < 0) return void 0;
|
|
1042
|
+
return number;
|
|
1043
|
+
}
|
|
1044
|
+
function asPositiveInteger(value) {
|
|
1045
|
+
const number = asNonnegativeInteger2(value);
|
|
1046
|
+
return number !== void 0 && number > 0 ? number : void 0;
|
|
1047
|
+
}
|
|
1048
|
+
function asIsoEpochSeconds(value) {
|
|
1049
|
+
if (typeof value !== "string") return void 0;
|
|
1050
|
+
const match = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d+)?(?:Z|([+-])(\d{2}):(\d{2}))$/u.exec(value);
|
|
1051
|
+
if (!match) return void 0;
|
|
1052
|
+
const [, yearText, monthText, dayText, hourText, minuteText, secondText, , offsetHour, offsetMinute] = match;
|
|
1053
|
+
const year = Number(yearText);
|
|
1054
|
+
const month = Number(monthText);
|
|
1055
|
+
const day = Number(dayText);
|
|
1056
|
+
const hour = Number(hourText);
|
|
1057
|
+
const minute = Number(minuteText);
|
|
1058
|
+
const second = Number(secondText);
|
|
1059
|
+
if (month < 1 || month > 12 || day < 1 || day > new Date(Date.UTC(year, month, 0)).getUTCDate() || hour > 23 || minute > 59 || second > 59 || offsetHour !== void 0 && Number(offsetHour) > 23 || offsetMinute !== void 0 && Number(offsetMinute) > 59) {
|
|
1060
|
+
return void 0;
|
|
1061
|
+
}
|
|
1062
|
+
const millis = Date.parse(value);
|
|
1063
|
+
return Number.isFinite(millis) && millis >= 0 ? Math.floor(millis / 1e3) : void 0;
|
|
1064
|
+
}
|
|
1065
|
+
function sanitizedLabel(value) {
|
|
1066
|
+
if (typeof value !== "string") return void 0;
|
|
1067
|
+
return sanitizeDisplayText(value, 80) || void 0;
|
|
1068
|
+
}
|
|
1069
|
+
function asCurrency(value) {
|
|
1070
|
+
if (typeof value !== "string") return void 0;
|
|
1071
|
+
const currency = sanitizeDisplayText(value, 3).toUpperCase();
|
|
1072
|
+
return /^[A-Z]{3}$/u.test(currency) ? currency : void 0;
|
|
1073
|
+
}
|
|
1074
|
+
function windowId(minutes) {
|
|
1075
|
+
if (minutes === FIVE_HOUR_WINDOW_MINUTES) return "five-hour";
|
|
1076
|
+
if (minutes === DAILY_WINDOW_MINUTES) return "daily";
|
|
1077
|
+
if (minutes === WEEKLY_WINDOW_MINUTES) return "weekly";
|
|
1078
|
+
return `window-${minutes}-minutes`;
|
|
1079
|
+
}
|
|
1080
|
+
function defaultWindowLabel(minutes) {
|
|
1081
|
+
if (minutes === WEEKLY_WINDOW_MINUTES) return "Weekly window";
|
|
1082
|
+
if (minutes % 10080 === 0) return `${minutes / 10080}w window`;
|
|
1083
|
+
if (minutes % 1440 === 0) return `${minutes / 1440}d window`;
|
|
1084
|
+
if (minutes % 60 === 0) return `${minutes / 60}h window`;
|
|
1085
|
+
return `${minutes}m window`;
|
|
1086
|
+
}
|
|
1087
|
+
|
|
1088
|
+
// src/providers/minimax.ts
|
|
1089
|
+
var PROVIDERS = {
|
|
1090
|
+
minimax: { name: "MiniMax", currency: "USD" },
|
|
1091
|
+
"minimax-cn": { name: "MiniMax CN", currency: "CNY" }
|
|
1092
|
+
};
|
|
1093
|
+
var DECIMAL_AMOUNT2 = /^-?(?:0|[1-9]\d*)(?:\.\d+)?$/u;
|
|
1094
|
+
var PERCENT_TOLERANCE = 1;
|
|
1095
|
+
function miniMaxUsageKind(apiKey) {
|
|
1096
|
+
return apiKey.startsWith("sk-api-") ? "account-balance" : "token-plan";
|
|
1097
|
+
}
|
|
1098
|
+
function normalizeMiniMaxUsagePayload(providerId, kind, payload, capturedAt) {
|
|
1099
|
+
return kind === "account-balance" ? normalizeBalance(providerId, payload, capturedAt) : normalizeTokenPlan(providerId, payload, capturedAt);
|
|
1100
|
+
}
|
|
1101
|
+
function normalizeBalance(providerId, payload, capturedAt) {
|
|
1102
|
+
assertSuccess(payload);
|
|
1103
|
+
const provider = PROVIDERS[providerId];
|
|
1104
|
+
const metrics = [
|
|
1105
|
+
balanceMetric("available-balance", "Available balance", payload.available_amount, provider.currency),
|
|
1106
|
+
balanceMetric("cash-balance", "Cash balance", payload.cash_balance, provider.currency, true),
|
|
1107
|
+
balanceMetric("voucher-balance", "Voucher balance", payload.voucher_balance, provider.currency),
|
|
1108
|
+
balanceMetric("credit-balance", "Credit balance", payload.credit_balance, provider.currency),
|
|
1109
|
+
balanceMetric("owed-amount", "Owed amount", payload.owed_amount, provider.currency)
|
|
1110
|
+
];
|
|
1111
|
+
return {
|
|
1112
|
+
providerId,
|
|
1113
|
+
providerName: provider.name,
|
|
1114
|
+
capturedAt,
|
|
1115
|
+
source: "minimax-account-balance",
|
|
1116
|
+
semantics: { kind: "api-key", label: "MiniMax pay-as-you-go account balance" },
|
|
1117
|
+
buckets: [],
|
|
1118
|
+
metrics
|
|
1119
|
+
};
|
|
1120
|
+
}
|
|
1121
|
+
function normalizeTokenPlan(providerId, payload, capturedAt) {
|
|
1122
|
+
assertSuccess(payload);
|
|
1123
|
+
if (!Array.isArray(payload.model_remains) || payload.model_remains.length === 0) {
|
|
1124
|
+
throw new Error("MiniMax Token Plan returned no quota rows.");
|
|
1125
|
+
}
|
|
1126
|
+
const provider = PROVIDERS[providerId];
|
|
1127
|
+
const buckets = [];
|
|
1128
|
+
const groups = /* @__PURE__ */ new Set();
|
|
1129
|
+
for (const [index, raw] of payload.model_remains.entries()) {
|
|
1130
|
+
const row = asObject7(raw);
|
|
1131
|
+
if (!row) throw new Error("MiniMax Token Plan quota row was not an object.");
|
|
1132
|
+
const groupLabel = safeLabel(row.model_name, `Quota ${index + 1}`);
|
|
1133
|
+
const groupId = uniqueGroupId(groupLabel, index, groups);
|
|
1134
|
+
buckets.push(
|
|
1135
|
+
normalizeWindow(row, {
|
|
1136
|
+
id: `${groupId}:interval`,
|
|
1137
|
+
label: "Rolling window",
|
|
1138
|
+
groupId,
|
|
1139
|
+
groupLabel,
|
|
1140
|
+
countField: "current_interval_usage_count",
|
|
1141
|
+
totalField: "current_interval_total_count",
|
|
1142
|
+
percentField: "current_interval_remaining_percent",
|
|
1143
|
+
statusField: "current_interval_status",
|
|
1144
|
+
startField: "start_time",
|
|
1145
|
+
endField: "end_time"
|
|
1146
|
+
}),
|
|
1147
|
+
normalizeWindow(row, {
|
|
1148
|
+
id: `${groupId}:weekly`,
|
|
1149
|
+
label: "Weekly window",
|
|
1150
|
+
groupId,
|
|
1151
|
+
groupLabel,
|
|
1152
|
+
countField: "current_weekly_usage_count",
|
|
1153
|
+
totalField: "current_weekly_total_count",
|
|
1154
|
+
percentField: "current_weekly_remaining_percent",
|
|
1155
|
+
statusField: "current_weekly_status",
|
|
1156
|
+
startField: "weekly_start_time",
|
|
1157
|
+
endField: "weekly_end_time",
|
|
1158
|
+
boostPermille: row.weekly_boost_permille
|
|
1159
|
+
})
|
|
1160
|
+
);
|
|
1161
|
+
}
|
|
1162
|
+
return {
|
|
1163
|
+
providerId,
|
|
1164
|
+
providerName: provider.name,
|
|
1165
|
+
capturedAt,
|
|
1166
|
+
source: "minimax-token-plan",
|
|
1167
|
+
semantics: { kind: "consumer-subscription", label: "MiniMax Token Plan quota" },
|
|
1168
|
+
buckets,
|
|
1169
|
+
metrics: []
|
|
1170
|
+
};
|
|
1171
|
+
}
|
|
1172
|
+
function normalizeWindow(row, fields) {
|
|
1173
|
+
const status = optionalInteger(row[fields.statusField], fields.statusField);
|
|
1174
|
+
if (status !== void 0 && ![1, 2, 3].includes(status)) {
|
|
1175
|
+
throw new Error(`MiniMax Token Plan ${fields.label} status was unsupported.`);
|
|
1176
|
+
}
|
|
1177
|
+
const percent = optionalPercent(row[fields.percentField], fields.percentField);
|
|
1178
|
+
validateBoost(fields.boostPermille);
|
|
1179
|
+
const start = timestamp(row[fields.startField], fields.startField);
|
|
1180
|
+
const end = timestamp(row[fields.endField], fields.endField);
|
|
1181
|
+
if (end < start) throw new Error(`MiniMax Token Plan ${fields.label} timestamps were reversed.`);
|
|
1182
|
+
const resetsAt = Math.floor(end / 1e3);
|
|
1183
|
+
const windowMinutes = Math.max(1, Math.round((end - start) / 6e4));
|
|
1184
|
+
if (status === 3) {
|
|
1185
|
+
return {
|
|
1186
|
+
id: fields.id,
|
|
1187
|
+
label: fields.label,
|
|
1188
|
+
groupId: fields.groupId,
|
|
1189
|
+
groupLabel: fields.groupLabel,
|
|
1190
|
+
remaining: 100,
|
|
1191
|
+
unit: "percent",
|
|
1192
|
+
period: "unlimited",
|
|
1193
|
+
windowMinutes
|
|
1194
|
+
};
|
|
1195
|
+
}
|
|
1196
|
+
const total = nonnegativeInteger(row[fields.totalField], fields.totalField);
|
|
1197
|
+
const count = nonnegativeInteger(row[fields.countField], fields.countField);
|
|
1198
|
+
if (total === 0) {
|
|
1199
|
+
if (count !== 0) {
|
|
1200
|
+
throw new Error(`MiniMax Token Plan ${fields.label} counts were inconsistent.`);
|
|
1201
|
+
}
|
|
1202
|
+
if (percent === void 0) {
|
|
1203
|
+
throw new Error(`MiniMax Token Plan ${fields.label} returned no quota and no percent.`);
|
|
1204
|
+
}
|
|
1205
|
+
return {
|
|
1206
|
+
id: fields.id,
|
|
1207
|
+
label: fields.label,
|
|
1208
|
+
groupId: fields.groupId,
|
|
1209
|
+
groupLabel: fields.groupLabel,
|
|
1210
|
+
remaining: percent,
|
|
1211
|
+
used: 100 - percent,
|
|
1212
|
+
limit: 0,
|
|
1213
|
+
unit: "percent",
|
|
1214
|
+
windowMinutes,
|
|
1215
|
+
resetsAt
|
|
1216
|
+
};
|
|
1217
|
+
}
|
|
1218
|
+
const resolved = resolveQuotaCounts(count, total, percent);
|
|
1219
|
+
if (!resolved) throw new Error(`MiniMax Token Plan ${fields.label} counts were inconsistent.`);
|
|
1220
|
+
return {
|
|
1221
|
+
id: fields.id,
|
|
1222
|
+
label: fields.label,
|
|
1223
|
+
groupId: fields.groupId,
|
|
1224
|
+
groupLabel: fields.groupLabel,
|
|
1225
|
+
...resolved,
|
|
1226
|
+
unit: "count",
|
|
1227
|
+
windowMinutes,
|
|
1228
|
+
resetsAt
|
|
1229
|
+
};
|
|
1230
|
+
}
|
|
1231
|
+
function resolveQuotaCounts(reportedCount, total, remainingPercent) {
|
|
1232
|
+
if (total <= 0 || reportedCount > total) return void 0;
|
|
1233
|
+
let remaining = reportedCount;
|
|
1234
|
+
if (remainingPercent !== void 0) {
|
|
1235
|
+
const asRemaining = reportedCount / total * 100;
|
|
1236
|
+
const asUsed = (total - reportedCount) / total * 100;
|
|
1237
|
+
const remainingDistance = Math.abs(asRemaining - remainingPercent);
|
|
1238
|
+
const usedDistance = Math.abs(asUsed - remainingPercent);
|
|
1239
|
+
if (Math.min(remainingDistance, usedDistance) > PERCENT_TOLERANCE) return void 0;
|
|
1240
|
+
if (usedDistance < remainingDistance) remaining = total - reportedCount;
|
|
1241
|
+
}
|
|
1242
|
+
return { used: total - remaining, remaining, limit: total };
|
|
1243
|
+
}
|
|
1244
|
+
function assertSuccess(payload) {
|
|
1245
|
+
const base = asObject7(payload.base_resp);
|
|
1246
|
+
if (base?.status_code !== 0) {
|
|
1247
|
+
throw new Error("MiniMax usage response did not report success.");
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
function balanceMetric(id, label, value, currency, allowNegative = false) {
|
|
1251
|
+
if (typeof value !== "string" || value.length > 64 || !DECIMAL_AMOUNT2.test(value) || !allowNegative && value.startsWith("-")) {
|
|
1252
|
+
throw new Error(`MiniMax ${label.toLowerCase()} was not a valid amount.`);
|
|
1253
|
+
}
|
|
1254
|
+
return { id, label, value, unit: "currency", currency };
|
|
1255
|
+
}
|
|
1256
|
+
function asObject7(value) {
|
|
1257
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
1258
|
+
return value;
|
|
1259
|
+
}
|
|
1260
|
+
function safeLabel(value, fallback) {
|
|
1261
|
+
if (typeof value !== "string") throw new Error("MiniMax Token Plan model name was not a string.");
|
|
1262
|
+
return sanitizeDisplayText(value, 80) || fallback;
|
|
1263
|
+
}
|
|
1264
|
+
function uniqueGroupId(label, index, groups) {
|
|
1265
|
+
const base = label.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-|-$/gu, "") || "quota";
|
|
1266
|
+
const id = groups.has(base) ? `${base}-${index + 1}` : base;
|
|
1267
|
+
groups.add(id);
|
|
1268
|
+
return id;
|
|
1269
|
+
}
|
|
1270
|
+
function nonnegativeInteger(value, field) {
|
|
1271
|
+
if (!Number.isSafeInteger(value) || value < 0) {
|
|
1272
|
+
throw new Error(`MiniMax Token Plan ${field} was not a nonnegative safe integer.`);
|
|
1273
|
+
}
|
|
1274
|
+
return value;
|
|
1275
|
+
}
|
|
1276
|
+
function optionalInteger(value, field) {
|
|
1277
|
+
if (value === void 0 || value === null) return void 0;
|
|
1278
|
+
return nonnegativeInteger(value, field);
|
|
1279
|
+
}
|
|
1280
|
+
function optionalPercent(value, field) {
|
|
1281
|
+
if (value === void 0 || value === null) return void 0;
|
|
1282
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 100) {
|
|
1283
|
+
throw new Error(`MiniMax Token Plan ${field} was not a percentage.`);
|
|
1284
|
+
}
|
|
1285
|
+
return value;
|
|
1286
|
+
}
|
|
1287
|
+
function validateBoost(boost) {
|
|
1288
|
+
if (boost === void 0 || boost === null) return;
|
|
1289
|
+
const permille = nonnegativeInteger(boost, "weekly_boost_permille");
|
|
1290
|
+
if (permille > 1e4) throw new Error("MiniMax Token Plan weekly boost was unreasonable.");
|
|
1291
|
+
}
|
|
1292
|
+
function timestamp(value, field) {
|
|
1293
|
+
if (!Number.isSafeInteger(value) || value <= 0) {
|
|
1294
|
+
throw new Error(`MiniMax Token Plan ${field} was not a valid timestamp.`);
|
|
1295
|
+
}
|
|
1296
|
+
return value;
|
|
1297
|
+
}
|
|
1298
|
+
|
|
1299
|
+
// src/providers/moonshot.ts
|
|
1300
|
+
var PROVIDERS2 = {
|
|
1301
|
+
moonshotai: { name: "Moonshot AI", currency: "USD" },
|
|
1302
|
+
"moonshotai-cn": { name: "Moonshot AI CN", currency: "CNY" }
|
|
1303
|
+
};
|
|
1304
|
+
function normalizeMoonshotBalancePayload(providerId, payload, capturedAt) {
|
|
1305
|
+
if (payload.code !== 0 || payload.status !== true) {
|
|
1306
|
+
throw new Error("Moonshot AI balance response did not report success.");
|
|
1307
|
+
}
|
|
1308
|
+
const data = asObject8(payload.data);
|
|
1309
|
+
if (!data) throw new Error("Moonshot AI balance response data was not an object.");
|
|
1310
|
+
const provider = PROVIDERS2[providerId];
|
|
1311
|
+
const available = amount(data.available_balance, "available balance", false);
|
|
1312
|
+
const voucher = amount(data.voucher_balance, "voucher balance", false);
|
|
1313
|
+
const cash = amount(data.cash_balance, "cash balance", true);
|
|
1314
|
+
const metrics = [
|
|
1315
|
+
currencyMetric("available-balance", "Available balance", available, provider.currency),
|
|
1316
|
+
currencyMetric("voucher-balance", "Voucher balance", voucher, provider.currency),
|
|
1317
|
+
currencyMetric("cash-balance", "Cash balance", cash, provider.currency)
|
|
1318
|
+
];
|
|
1319
|
+
return {
|
|
1320
|
+
providerId,
|
|
1321
|
+
providerName: provider.name,
|
|
1322
|
+
capturedAt,
|
|
1323
|
+
source: "moonshot-balance",
|
|
1324
|
+
semantics: { kind: "api-key", label: "Moonshot API account balance" },
|
|
1325
|
+
buckets: [],
|
|
1326
|
+
metrics
|
|
1327
|
+
};
|
|
1328
|
+
}
|
|
1329
|
+
function currencyMetric(id, label, value, currency) {
|
|
1330
|
+
return { id, label, value, unit: "currency", currency };
|
|
1331
|
+
}
|
|
1332
|
+
function asObject8(value) {
|
|
1333
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
1334
|
+
return value;
|
|
1335
|
+
}
|
|
1336
|
+
function amount(value, label, allowNegative) {
|
|
1337
|
+
if (typeof value !== "number" || !Number.isFinite(value) || !allowNegative && value < 0 || Math.abs(value) > Number.MAX_SAFE_INTEGER) {
|
|
1338
|
+
throw new Error(`Moonshot AI ${label} was not a valid amount.`);
|
|
1339
|
+
}
|
|
1340
|
+
return String(value);
|
|
1341
|
+
}
|
|
1342
|
+
|
|
1343
|
+
// src/providers/openai-chatgpt.ts
|
|
1344
|
+
var CHATGPT_USAGE_SETTINGS_URL = "https://chatgpt.com/settings/usage";
|
|
1345
|
+
var DIRECT_TOKEN_SCOPE = "chatgpt.tokens.use.direct";
|
|
1346
|
+
var UnsupportedOpenAIUsageAuthError = class extends Error {
|
|
1347
|
+
name = "UnsupportedOpenAIUsageAuthError";
|
|
1348
|
+
constructor() {
|
|
1349
|
+
super("OpenAI API-key usage reporting is not supported; ChatGPT plan status requires native /login openai OAuth.");
|
|
1350
|
+
}
|
|
1351
|
+
};
|
|
1352
|
+
var OPENAI_CHATGPT_ADAPTER = {
|
|
1353
|
+
id: "openai",
|
|
1354
|
+
displayName: "OpenAI",
|
|
1355
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT plan authentication status" },
|
|
1356
|
+
invalidateCacheOnFailure: true,
|
|
1357
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
1358
|
+
if (auth.openaiCompanion) {
|
|
1359
|
+
const { queryOpenAICompanionUsage } = await import("./openai-companion-usage-Y3WTMUB2.ts");
|
|
1360
|
+
signal.throwIfAborted();
|
|
1361
|
+
return queryOpenAICompanionUsage(auth, signal, timeoutMs, guard);
|
|
1362
|
+
}
|
|
1363
|
+
if (!guard) throw new Error("ChatGPT plan status requires runtime-auth revalidation.");
|
|
1364
|
+
signal.throwIfAborted();
|
|
1365
|
+
await guard();
|
|
1366
|
+
signal.throwIfAborted();
|
|
1367
|
+
return {
|
|
1368
|
+
providerId: "openai",
|
|
1369
|
+
providerName: "OpenAI",
|
|
1370
|
+
capturedAt: Date.now(),
|
|
1371
|
+
source: "openai-chatgpt-auth",
|
|
1372
|
+
semantics: { kind: "consumer-subscription", label: "ChatGPT plan authentication status" },
|
|
1373
|
+
buckets: [],
|
|
1374
|
+
metrics: [{ id: "plan-auth", label: "ChatGPT plan authentication", value: "Connected (native OAuth)" }],
|
|
1375
|
+
notes: [
|
|
1376
|
+
"Numerical usage and reset times are unavailable in pi-usage for native OpenAI OAuth.",
|
|
1377
|
+
`Manage usage: ${CHATGPT_USAGE_SETTINGS_URL}`,
|
|
1378
|
+
...auth.openaiCompanionEnabled ? [
|
|
1379
|
+
"Experimental companion usage requires /login openai-codex with the same ChatGPT account/workspace; native inference stays on openai."
|
|
1380
|
+
] : [],
|
|
1381
|
+
"Fast mode and earned reset redemption remain legacy openai-codex features."
|
|
1382
|
+
]
|
|
1383
|
+
};
|
|
1384
|
+
}
|
|
1385
|
+
};
|
|
1386
|
+
function resolveOpenAIChatGPTAuth(auth, providerAuth, source, model, candidates) {
|
|
1387
|
+
if (source !== "OAuth") throw new UnsupportedOpenAIUsageAuthError();
|
|
1388
|
+
const access = openAIAuthAccessToken(auth);
|
|
1389
|
+
if (!access || access !== openAIAuthAccessToken(providerAuth)) {
|
|
1390
|
+
throw new Error("The active OpenAI model authorization does not match its resolved OAuth credential.");
|
|
1391
|
+
}
|
|
1392
|
+
const matches = /* @__PURE__ */ new Map();
|
|
1393
|
+
for (const candidate of candidates) {
|
|
1394
|
+
if (!candidate || typeof candidate !== "object" || Array.isArray(candidate)) continue;
|
|
1395
|
+
const credential = candidate;
|
|
1396
|
+
if (credential.type !== "oauth" || credential.access !== access) continue;
|
|
1397
|
+
if (typeof credential.refresh !== "string" || !credential.refresh || typeof credential.expires !== "number" || !Number.isFinite(credential.expires) || typeof credential.clientId !== "string" || !credential.clientId.trim() || !Array.isArray(credential.scopes) || !credential.scopes.every((scope) => typeof scope === "string") || !credential.scopes.includes(DIRECT_TOKEN_SCOPE)) {
|
|
1398
|
+
throw new Error(
|
|
1399
|
+
"The matching OpenAI OAuth credential is not a complete native ChatGPT grant; reconnect with /login openai."
|
|
1400
|
+
);
|
|
1401
|
+
}
|
|
1402
|
+
matches.set(JSON.stringify([credential.clientId, credential.refresh]), {
|
|
1403
|
+
refresh: credential.refresh,
|
|
1404
|
+
clientId: credential.clientId
|
|
1405
|
+
});
|
|
1406
|
+
}
|
|
1407
|
+
if (matches.size > 1)
|
|
1408
|
+
throw new Error("Conflicting native ChatGPT credentials match the active OpenAI runtime account.");
|
|
1409
|
+
const match = matches.values().next().value;
|
|
1410
|
+
if (!match)
|
|
1411
|
+
throw new Error("The active OpenAI runtime account does not match an available native ChatGPT OAuth credential.");
|
|
1412
|
+
const authorization = `Bearer ${access}`;
|
|
1413
|
+
return {
|
|
1414
|
+
openaiClientId: match.clientId,
|
|
1415
|
+
apiKey: access,
|
|
1416
|
+
headers: { Authorization: authorization },
|
|
1417
|
+
fingerprint: "",
|
|
1418
|
+
secrets: [access, match.refresh, authorization, match.clientId],
|
|
1419
|
+
model
|
|
1420
|
+
};
|
|
1421
|
+
}
|
|
1422
|
+
function openAIAuthAccessToken(auth) {
|
|
1423
|
+
if (!auth) return void 0;
|
|
1424
|
+
const authorization = Object.entries(auth.headers ?? {}).filter(([name]) => name.toLowerCase() === "authorization");
|
|
1425
|
+
if (authorization.length > 1) throw new Error("OpenAI runtime authorization headers are ambiguous.");
|
|
1426
|
+
if (authorization.length === 1) return /^Bearer\s+(.+)$/iu.exec(authorization[0]?.[1] ?? "")?.[1];
|
|
1427
|
+
return auth.apiKey;
|
|
1428
|
+
}
|
|
1429
|
+
|
|
1430
|
+
// src/providers/opencode-zen.ts
|
|
1431
|
+
var ZEN_WINDOWS = [
|
|
1432
|
+
{ key: "rolling", label: "Rolling" },
|
|
1433
|
+
{ key: "weekly", label: "Weekly" },
|
|
1434
|
+
{ key: "monthly", label: "Monthly" }
|
|
1435
|
+
];
|
|
1436
|
+
function normalizeOpenCodeZenPayload(payload, capturedAt) {
|
|
1437
|
+
const usage = asObject9(payload.usage);
|
|
1438
|
+
if (!usage) throw new Error("OpenCode Zen usage response was not an object.");
|
|
1439
|
+
const buckets = [];
|
|
1440
|
+
const notes = [];
|
|
1441
|
+
for (const window of ZEN_WINDOWS) {
|
|
1442
|
+
const raw = asObject9(usage[window.key]);
|
|
1443
|
+
if (!raw) continue;
|
|
1444
|
+
const status = asString3(raw.status);
|
|
1445
|
+
if (status !== "ok" && status !== "rate-limited") {
|
|
1446
|
+
notes.push(`${window.label} window unavailable (${status ?? "unknown status"}).`);
|
|
1447
|
+
continue;
|
|
1448
|
+
}
|
|
1449
|
+
const used = asNonnegativeNumber2(raw.percent);
|
|
1450
|
+
if (used === void 0) continue;
|
|
1451
|
+
const resetsAt = asEpochSeconds(raw.resetsAt);
|
|
1452
|
+
buckets.push({
|
|
1453
|
+
id: window.key,
|
|
1454
|
+
label: `${window.label} window`,
|
|
1455
|
+
used,
|
|
1456
|
+
remaining: 100 - clampPercent2(used),
|
|
1457
|
+
limit: 100,
|
|
1458
|
+
unit: "percent",
|
|
1459
|
+
...resetsAt !== void 0 ? { resetsAt } : {}
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
if (buckets.length === 0) {
|
|
1463
|
+
throw new Error("OpenCode Zen usage endpoint returned no displayable usage data.");
|
|
1464
|
+
}
|
|
1465
|
+
return {
|
|
1466
|
+
providerId: "opencode-go",
|
|
1467
|
+
providerName: "OpenCode Go",
|
|
1468
|
+
capturedAt,
|
|
1469
|
+
source: "opencode-zen-usage",
|
|
1470
|
+
semantics: {
|
|
1471
|
+
kind: "consumer-subscription",
|
|
1472
|
+
label: "OpenCode Zen plan usage"
|
|
1473
|
+
},
|
|
1474
|
+
buckets,
|
|
1475
|
+
metrics: [],
|
|
1476
|
+
...notes.length > 0 ? { notes } : {}
|
|
1477
|
+
};
|
|
1478
|
+
}
|
|
1479
|
+
function asObject9(value) {
|
|
1480
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
1481
|
+
return value;
|
|
1482
|
+
}
|
|
1483
|
+
function asString3(value) {
|
|
1484
|
+
if (typeof value !== "string") return void 0;
|
|
1485
|
+
return sanitizeDisplayText(value, 80) || void 0;
|
|
1486
|
+
}
|
|
1487
|
+
function asNonnegativeNumber2(value) {
|
|
1488
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
|
|
1489
|
+
return value;
|
|
1490
|
+
}
|
|
1491
|
+
function asEpochSeconds(value) {
|
|
1492
|
+
if (typeof value !== "string" || !value.trim()) return void 0;
|
|
1493
|
+
const parsed = Date.parse(value);
|
|
1494
|
+
if (Number.isNaN(parsed)) return void 0;
|
|
1495
|
+
return Math.floor(parsed / 1e3);
|
|
1496
|
+
}
|
|
1497
|
+
function clampPercent2(value) {
|
|
1498
|
+
return Math.min(100, Math.max(0, value));
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
// src/providers/openrouter.ts
|
|
1502
|
+
function normalizeOpenRouterKeyPayload(payload, capturedAt) {
|
|
1503
|
+
const data = asObject10(payload.data);
|
|
1504
|
+
if (!data) throw new Error("OpenRouter key response data was not an object.");
|
|
1505
|
+
const limit = asNonnegativeNumber3(data.limit);
|
|
1506
|
+
const remaining = asNonnegativeNumber3(data.limit_remaining);
|
|
1507
|
+
const period = asString4(data.limit_reset);
|
|
1508
|
+
const totalUsage = asNonnegativeNumber3(data.usage);
|
|
1509
|
+
const buckets = [];
|
|
1510
|
+
if (limit !== void 0) {
|
|
1511
|
+
buckets.push({
|
|
1512
|
+
id: "key-limit",
|
|
1513
|
+
label: "Key limit",
|
|
1514
|
+
...remaining !== void 0 ? { used: Math.max(0, limit - remaining), remaining } : {},
|
|
1515
|
+
limit,
|
|
1516
|
+
unit: "usd",
|
|
1517
|
+
...period ? { period } : {}
|
|
1518
|
+
});
|
|
1519
|
+
}
|
|
1520
|
+
const metrics = [];
|
|
1521
|
+
addUsageMetric(metrics, "usage-daily", "Usage today", data.usage_daily);
|
|
1522
|
+
addUsageMetric(metrics, "usage-weekly", "Usage this week", data.usage_weekly);
|
|
1523
|
+
addUsageMetric(metrics, "usage-monthly", "Usage this month", data.usage_monthly);
|
|
1524
|
+
addUsageMetric(metrics, "usage-total", "All-time usage", totalUsage);
|
|
1525
|
+
if (buckets.length === 0 && metrics.length === 0) {
|
|
1526
|
+
throw new Error("OpenRouter key response returned no displayable usage data.");
|
|
1527
|
+
}
|
|
1528
|
+
const notes = [];
|
|
1529
|
+
if (data.limit === null) notes.push("No per-key spend cap");
|
|
1530
|
+
else if (limit === void 0) notes.push("Per-key spend cap unavailable");
|
|
1531
|
+
if (data.is_free_tier === true) notes.push("Free-tier API key");
|
|
1532
|
+
return {
|
|
1533
|
+
providerId: "openrouter",
|
|
1534
|
+
providerName: "OpenRouter",
|
|
1535
|
+
capturedAt,
|
|
1536
|
+
source: "openrouter-key",
|
|
1537
|
+
semantics: { kind: "api-key", label: "API-key spend limits" },
|
|
1538
|
+
accountLabel: asString4(data.label),
|
|
1539
|
+
buckets,
|
|
1540
|
+
metrics,
|
|
1541
|
+
...notes.length > 0 ? { notes } : {}
|
|
1542
|
+
};
|
|
1543
|
+
}
|
|
1544
|
+
function addUsageMetric(metrics, id, label, value) {
|
|
1545
|
+
const amount2 = typeof value === "number" ? asNonnegativeNumber3(value) : void 0;
|
|
1546
|
+
if (amount2 === void 0) return;
|
|
1547
|
+
metrics.push({ id, label, value: amount2, unit: "usd" });
|
|
1548
|
+
}
|
|
1549
|
+
function asObject10(value) {
|
|
1550
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
1551
|
+
return value;
|
|
1552
|
+
}
|
|
1553
|
+
function asString4(value) {
|
|
1554
|
+
if (typeof value !== "string") return void 0;
|
|
1555
|
+
return sanitizeDisplayText(value, 80) || void 0;
|
|
1556
|
+
}
|
|
1557
|
+
function asNonnegativeNumber3(value) {
|
|
1558
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
|
|
1559
|
+
return value;
|
|
1560
|
+
}
|
|
1561
|
+
|
|
1562
|
+
// src/providers/vercel-ai-gateway.ts
|
|
1563
|
+
var DECIMAL_AMOUNT3 = /^(?:0|[1-9]\d*)(?:\.\d+)?$/u;
|
|
1564
|
+
function normalizeVercelAIGatewayCreditsPayload(payload, capturedAt) {
|
|
1565
|
+
const balance = decimalAmount3(payload.balance, "balance");
|
|
1566
|
+
const totalUsed = decimalAmount3(payload.total_used, "total used");
|
|
1567
|
+
const metrics = [
|
|
1568
|
+
{
|
|
1569
|
+
id: "credit-balance",
|
|
1570
|
+
label: "Credit balance",
|
|
1571
|
+
value: balance,
|
|
1572
|
+
unit: "currency",
|
|
1573
|
+
currency: "USD"
|
|
1574
|
+
},
|
|
1575
|
+
{
|
|
1576
|
+
id: "lifetime-spend",
|
|
1577
|
+
label: "Lifetime spend",
|
|
1578
|
+
value: totalUsed,
|
|
1579
|
+
unit: "currency",
|
|
1580
|
+
currency: "USD"
|
|
1581
|
+
}
|
|
1582
|
+
];
|
|
1583
|
+
return {
|
|
1584
|
+
providerId: "vercel-ai-gateway",
|
|
1585
|
+
providerName: "Vercel AI Gateway",
|
|
1586
|
+
capturedAt,
|
|
1587
|
+
source: "vercel-ai-gateway-credits",
|
|
1588
|
+
semantics: { kind: "api-key", label: "AI Gateway credits and lifetime spend" },
|
|
1589
|
+
buckets: [],
|
|
1590
|
+
metrics
|
|
1591
|
+
};
|
|
1592
|
+
}
|
|
1593
|
+
function decimalAmount3(value, label) {
|
|
1594
|
+
if (typeof value !== "string" || value.length > 64 || !DECIMAL_AMOUNT3.test(value)) {
|
|
1595
|
+
throw new Error(`Vercel AI Gateway ${label} was not a valid nonnegative amount.`);
|
|
1596
|
+
}
|
|
1597
|
+
return value;
|
|
1598
|
+
}
|
|
1599
|
+
|
|
1600
|
+
// src/providers/xai.ts
|
|
1601
|
+
var MAX_SAFE_CENTS = Number.MAX_SAFE_INTEGER;
|
|
1602
|
+
function normalizeXaiBillingPayload(payload, subscriptionTier, capturedAt) {
|
|
1603
|
+
const configValue = payload.config;
|
|
1604
|
+
if (configValue !== null && configValue !== void 0 && !isRecord(configValue)) {
|
|
1605
|
+
throw new Error("xAI billing response config was not an object or null.");
|
|
1606
|
+
}
|
|
1607
|
+
const config = isRecord(configValue) ? configValue : void 0;
|
|
1608
|
+
const buckets = [];
|
|
1609
|
+
const metrics = [];
|
|
1610
|
+
const notes = [];
|
|
1611
|
+
if (config) {
|
|
1612
|
+
const period = normalizePeriod(config.currentPeriod, config.billingPeriodStart, config.billingPeriodEnd);
|
|
1613
|
+
const preferredPercent = optionalPercent2(config.creditUsagePercent, "creditUsagePercent");
|
|
1614
|
+
if (preferredPercent !== void 0) {
|
|
1615
|
+
buckets.push({
|
|
1616
|
+
id: "included-allowance",
|
|
1617
|
+
label: "Included allowance",
|
|
1618
|
+
used: preferredPercent,
|
|
1619
|
+
remaining: 100 - preferredPercent,
|
|
1620
|
+
unit: "percent",
|
|
1621
|
+
...period
|
|
1622
|
+
});
|
|
1623
|
+
} else {
|
|
1624
|
+
const limit = optionalUsd(config.monthlyLimit, "monthlyLimit");
|
|
1625
|
+
const used = optionalUsd(config.used, "used");
|
|
1626
|
+
if (limit !== void 0 || used !== void 0) {
|
|
1627
|
+
buckets.push({
|
|
1628
|
+
id: "included-allowance",
|
|
1629
|
+
label: "Included allowance",
|
|
1630
|
+
...limit !== void 0 ? { limit } : {},
|
|
1631
|
+
...used !== void 0 ? { used } : {},
|
|
1632
|
+
...limit !== void 0 && used !== void 0 ? { remaining: limit - used } : {},
|
|
1633
|
+
unit: "usd",
|
|
1634
|
+
...period
|
|
1635
|
+
});
|
|
1636
|
+
} else if (period.period || period.resetsAt !== void 0) {
|
|
1637
|
+
buckets.push({
|
|
1638
|
+
id: "included-allowance",
|
|
1639
|
+
label: "Included allowance",
|
|
1640
|
+
unit: "percent",
|
|
1641
|
+
...period
|
|
1642
|
+
});
|
|
1643
|
+
}
|
|
1644
|
+
}
|
|
1645
|
+
const onDemandCap = optionalUsd(config.onDemandCap, "onDemandCap");
|
|
1646
|
+
const onDemandUsed = optionalUsd(config.onDemandUsed, "onDemandUsed");
|
|
1647
|
+
if (onDemandCap !== void 0 || onDemandUsed !== void 0) {
|
|
1648
|
+
buckets.push({
|
|
1649
|
+
id: "on-demand",
|
|
1650
|
+
label: "On-demand usage",
|
|
1651
|
+
...onDemandCap !== void 0 ? { limit: onDemandCap } : {},
|
|
1652
|
+
...onDemandUsed !== void 0 ? { used: onDemandUsed } : {},
|
|
1653
|
+
...onDemandCap !== void 0 && onDemandUsed !== void 0 ? { remaining: onDemandCap - onDemandUsed } : {},
|
|
1654
|
+
unit: "usd"
|
|
1655
|
+
});
|
|
1656
|
+
}
|
|
1657
|
+
const prepaidBalance = optionalUsd(config.prepaidBalance, "prepaidBalance");
|
|
1658
|
+
if (prepaidBalance !== void 0) {
|
|
1659
|
+
metrics.push({
|
|
1660
|
+
id: "prepaid-balance",
|
|
1661
|
+
label: "Prepaid balance",
|
|
1662
|
+
value: prepaidBalance,
|
|
1663
|
+
unit: "usd"
|
|
1664
|
+
});
|
|
1665
|
+
}
|
|
1666
|
+
}
|
|
1667
|
+
const tier = optionalTier(subscriptionTier);
|
|
1668
|
+
if (tier) metrics.push({ id: "subscription-tier", label: "Plan tier", value: tier });
|
|
1669
|
+
if (!config) notes.push("No xAI consumer billing configuration is available for this account.");
|
|
1670
|
+
else if (buckets.length === 0 && metrics.length === 0) {
|
|
1671
|
+
notes.push("The xAI consumer billing response contained no displayable usage fields.");
|
|
1672
|
+
}
|
|
1673
|
+
return {
|
|
1674
|
+
providerId: "xai",
|
|
1675
|
+
providerName: "xAI",
|
|
1676
|
+
capturedAt,
|
|
1677
|
+
source: "cli-chat-proxy.grok.com consumer billing",
|
|
1678
|
+
semantics: {
|
|
1679
|
+
kind: "consumer-subscription",
|
|
1680
|
+
label: "xAI consumer subscription usage"
|
|
1681
|
+
},
|
|
1682
|
+
buckets,
|
|
1683
|
+
metrics,
|
|
1684
|
+
...notes.length > 0 ? { notes } : {}
|
|
1685
|
+
};
|
|
1686
|
+
}
|
|
1687
|
+
function normalizePeriod(currentPeriod, legacyStart, legacyEnd) {
|
|
1688
|
+
if (currentPeriod !== void 0 && currentPeriod !== null && !isRecord(currentPeriod)) {
|
|
1689
|
+
throw new Error("xAI billing currentPeriod was not an object or null.");
|
|
1690
|
+
}
|
|
1691
|
+
if (isRecord(currentPeriod)) {
|
|
1692
|
+
const type = optionalString(currentPeriod.type, "currentPeriod.type");
|
|
1693
|
+
const start2 = optionalTimestamp(currentPeriod.start, "currentPeriod.start");
|
|
1694
|
+
const end2 = optionalTimestamp(currentPeriod.end, "currentPeriod.end");
|
|
1695
|
+
return {
|
|
1696
|
+
...periodLabel(type, start2) ? { period: periodLabel(type, start2) } : {},
|
|
1697
|
+
...end2 !== void 0 ? { resetsAt: end2 } : {}
|
|
1698
|
+
};
|
|
1699
|
+
}
|
|
1700
|
+
const start = optionalTimestamp(legacyStart, "billingPeriodStart");
|
|
1701
|
+
const end = optionalTimestamp(legacyEnd, "billingPeriodEnd");
|
|
1702
|
+
return {
|
|
1703
|
+
...start !== void 0 ? { period: "Monthly" } : {},
|
|
1704
|
+
...end !== void 0 ? { resetsAt: end } : {}
|
|
1705
|
+
};
|
|
1706
|
+
}
|
|
1707
|
+
function periodLabel(type, start) {
|
|
1708
|
+
if (type === "USAGE_PERIOD_TYPE_WEEKLY") return "Weekly";
|
|
1709
|
+
if (type === "USAGE_PERIOD_TYPE_MONTHLY") return "Monthly";
|
|
1710
|
+
if (type) return sanitizeDisplayText(type.replace(/^USAGE_PERIOD_TYPE_/u, "").replaceAll("_", " "), 40);
|
|
1711
|
+
return start === void 0 ? void 0 : "Current period";
|
|
1712
|
+
}
|
|
1713
|
+
function optionalUsd(value, field) {
|
|
1714
|
+
if (value === void 0 || value === null) return void 0;
|
|
1715
|
+
if (!isRecord(value)) throw new Error(`xAI billing ${field} was not a cent wrapper.`);
|
|
1716
|
+
const cents = value.val === void 0 ? 0 : value.val;
|
|
1717
|
+
if (!Number.isSafeInteger(cents) || Math.abs(cents) > MAX_SAFE_CENTS) {
|
|
1718
|
+
throw new Error(`xAI billing ${field}.val was not a safe signed integer.`);
|
|
1719
|
+
}
|
|
1720
|
+
return cents / 100;
|
|
1721
|
+
}
|
|
1722
|
+
function optionalPercent2(value, field) {
|
|
1723
|
+
if (value === void 0 || value === null) return void 0;
|
|
1724
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0 || value > 100) {
|
|
1725
|
+
throw new Error(`xAI billing ${field} was outside 0\u2013100.`);
|
|
1726
|
+
}
|
|
1727
|
+
return value;
|
|
1728
|
+
}
|
|
1729
|
+
function optionalTimestamp(value, field) {
|
|
1730
|
+
if (value === void 0 || value === null) return void 0;
|
|
1731
|
+
if (typeof value !== "string" || value.length > 80) {
|
|
1732
|
+
throw new Error(`xAI billing ${field} was not a bounded timestamp.`);
|
|
1733
|
+
}
|
|
1734
|
+
const milliseconds = Date.parse(value);
|
|
1735
|
+
if (!Number.isFinite(milliseconds)) throw new Error(`xAI billing ${field} was invalid.`);
|
|
1736
|
+
return Math.floor(milliseconds / 1e3);
|
|
1737
|
+
}
|
|
1738
|
+
function optionalString(value, field) {
|
|
1739
|
+
if (value === void 0 || value === null) return void 0;
|
|
1740
|
+
if (typeof value !== "string" || value.length > 80) {
|
|
1741
|
+
throw new Error(`xAI billing ${field} was not a bounded string.`);
|
|
1742
|
+
}
|
|
1743
|
+
return value;
|
|
1744
|
+
}
|
|
1745
|
+
function optionalTier(value) {
|
|
1746
|
+
if (value === void 0 || value === null) return void 0;
|
|
1747
|
+
if (typeof value !== "string" || value.length > 160) {
|
|
1748
|
+
throw new Error("xAI subscription tier was not a bounded string or null.");
|
|
1749
|
+
}
|
|
1750
|
+
return sanitizeDisplayText(value, 80) || void 0;
|
|
1751
|
+
}
|
|
1752
|
+
function isRecord(value) {
|
|
1753
|
+
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
// src/providers/zai-errors.ts
|
|
1757
|
+
var ERROR_MESSAGES = {
|
|
1758
|
+
"1000": "Authentication failed. Check your API key.",
|
|
1759
|
+
"1001": "Authentication header missing. Check your API key.",
|
|
1760
|
+
"1003": "Authentication token expired. Obtain a new token.",
|
|
1761
|
+
"1005": "Two-factor authentication required.",
|
|
1762
|
+
"1113": "Insufficient balance or no resource package. Recharge your account.",
|
|
1763
|
+
"1200": "API call error. Try again later.",
|
|
1764
|
+
"1210": "Invalid API parameter. Check the API documentation.",
|
|
1765
|
+
"1211": "Unknown model. Check the model ID.",
|
|
1766
|
+
"1212": "This model does not support the requested method.",
|
|
1767
|
+
"1213": "A required parameter is missing.",
|
|
1768
|
+
"1214": "Invalid parameter. Check the API documentation.",
|
|
1769
|
+
"1215": "Conflicting parameters. Check the API documentation.",
|
|
1770
|
+
"1220": "Access denied. Check your permissions.",
|
|
1771
|
+
"1221": "This API has been taken offline.",
|
|
1772
|
+
"1222": "This API does not exist.",
|
|
1773
|
+
"1230": "API processing error. Try again later.",
|
|
1774
|
+
"1234": "Network error. Try again later.",
|
|
1775
|
+
"1261": "Prompt too long. Reduce the input length.",
|
|
1776
|
+
"1301": "Content rejected by the safety policy.",
|
|
1777
|
+
"1302": "Request rate limit reached. Try again later.",
|
|
1778
|
+
"1305": "Service overloaded. Try again later.",
|
|
1779
|
+
"1308": "Usage limit reached. Wait for the quota reset.",
|
|
1780
|
+
"1309": "GLM Coding Plan expired. Renew your subscription.",
|
|
1781
|
+
"1310": "Weekly or monthly limit exhausted. Wait for the quota reset.",
|
|
1782
|
+
"1311": "Your subscription does not include this model.",
|
|
1783
|
+
"1313": "Request frequency restricted by the Fair Usage Policy. Contact support.",
|
|
1784
|
+
"1314": "Enterprise package expired. Contact your administrator.",
|
|
1785
|
+
"1315": "This API key requires an enterprise coding package scenario. Replace the key.",
|
|
1786
|
+
"1316": "5-hour limit reached; insufficient balance for extra usage. Wait for reset.",
|
|
1787
|
+
"1317": "7-day limit reached; insufficient balance for extra usage. Wait for reset.",
|
|
1788
|
+
"1318": "5-hour limit reached; extra usage blocked by monthly spend limit.",
|
|
1789
|
+
"1319": "7-day limit reached; extra usage blocked by monthly spend limit.",
|
|
1790
|
+
"1320": "5-hour limit reached; extra usage blocked by monthly spend limit.",
|
|
1791
|
+
"1321": "7-day limit reached; extra usage blocked by monthly spend limit."
|
|
1792
|
+
};
|
|
1793
|
+
var HTTP_MESSAGES = {
|
|
1794
|
+
400: "Invalid request. Check the API documentation.",
|
|
1795
|
+
401: "Authentication failed. Check your API key.",
|
|
1796
|
+
403: "Access denied. Check your permissions.",
|
|
1797
|
+
429: "Request or usage limit reached. Try again later.",
|
|
1798
|
+
500: "Internal error. Try again later."
|
|
1799
|
+
};
|
|
1800
|
+
function zaiPayloadError(payload) {
|
|
1801
|
+
const object = asObject11(payload);
|
|
1802
|
+
if (!object) return void 0;
|
|
1803
|
+
const nested = asObject11(object.error);
|
|
1804
|
+
const rawCode = nested?.code === void 0 ? object.code : nested.code;
|
|
1805
|
+
const code = errorCode(rawCode);
|
|
1806
|
+
if (object.error === void 0 && object.success !== false && (rawCode === void 0 || code === "0" || code === "200")) {
|
|
1807
|
+
return void 0;
|
|
1808
|
+
}
|
|
1809
|
+
return code && code !== "0" && code !== "200" ? `Z.AI ${code}: ${ERROR_MESSAGES[code] ?? "API request failed."}` : "Z.AI: API request failed.";
|
|
1810
|
+
}
|
|
1811
|
+
function zaiResponseError(status, text) {
|
|
1812
|
+
let payload;
|
|
1813
|
+
try {
|
|
1814
|
+
payload = JSON.parse(text);
|
|
1815
|
+
} catch {
|
|
1816
|
+
if (status >= 200 && status < 300) return "Z.AI: Invalid JSON response.";
|
|
1817
|
+
}
|
|
1818
|
+
const error = zaiPayloadError(payload);
|
|
1819
|
+
if (error) return error;
|
|
1820
|
+
if (status < 200 || status >= 300) {
|
|
1821
|
+
return `Z.AI HTTP ${status}: ${HTTP_MESSAGES[status] ?? "API request failed."}`;
|
|
1822
|
+
}
|
|
1823
|
+
return void 0;
|
|
1824
|
+
}
|
|
1825
|
+
function errorCode(value) {
|
|
1826
|
+
if (typeof value === "number" && Number.isInteger(value) && value >= 0 && value <= 9999) {
|
|
1827
|
+
return String(value);
|
|
1828
|
+
}
|
|
1829
|
+
return typeof value === "string" && /^(?:0|[1-9]\d{0,3})$/u.test(value) ? value : void 0;
|
|
1830
|
+
}
|
|
1831
|
+
function asObject11(value) {
|
|
1832
|
+
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : void 0;
|
|
1833
|
+
}
|
|
1834
|
+
|
|
1835
|
+
// src/providers/zai.ts
|
|
1836
|
+
var FIVE_HOUR_WINDOW_MINUTES2 = 300;
|
|
1837
|
+
var WEEKLY_WINDOW_MINUTES2 = 10080;
|
|
1838
|
+
function normalizeZaiQuotaPayload(providerId, providerName, payload, capturedAt, plan) {
|
|
1839
|
+
const error = zaiPayloadError(payload);
|
|
1840
|
+
if (error) throw new Error(error);
|
|
1841
|
+
const data = asObject12(payload.data);
|
|
1842
|
+
if (!data) throw new Error("Z.AI quota response data was not an object.");
|
|
1843
|
+
const limits = Array.isArray(data.limits) ? data.limits : [];
|
|
1844
|
+
const buckets = [];
|
|
1845
|
+
const metrics = [];
|
|
1846
|
+
for (const raw of limits) {
|
|
1847
|
+
const limit = asObject12(raw);
|
|
1848
|
+
if (!limit) continue;
|
|
1849
|
+
const type = asString5(limit.type);
|
|
1850
|
+
const unit = asNonnegativeNumber4(limit.unit);
|
|
1851
|
+
const isPlanUsage = type === "TOKENS_LIMIT" || type === "CREDIT_LIMIT";
|
|
1852
|
+
if (type === "TIME_LIMIT") {
|
|
1853
|
+
addCountBucket(buckets, limit, "mcp-monthly", "MCP monthly allowance");
|
|
1854
|
+
addUsageDetailMetrics(metrics, limit.usageDetails);
|
|
1855
|
+
} else if (isPlanUsage && unit === 3) {
|
|
1856
|
+
addPercentBucket(buckets, limit, "five-hour", sessionWindowLabel(limit), sessionWindowMinutes(limit));
|
|
1857
|
+
} else if (isPlanUsage && unit === 6) {
|
|
1858
|
+
const used = asNonnegativeNumber4(limit.currentValue);
|
|
1859
|
+
const quota = asNonnegativeNumber4(limit.usage);
|
|
1860
|
+
if (used !== void 0 && quota !== void 0) {
|
|
1861
|
+
addCountBucket(buckets, limit, "weekly", "Weekly window", weeklyWindowMinutes(limit));
|
|
1862
|
+
} else {
|
|
1863
|
+
addPercentBucket(buckets, limit, "weekly", "Weekly window", weeklyWindowMinutes(limit));
|
|
1864
|
+
}
|
|
1865
|
+
}
|
|
1866
|
+
}
|
|
1867
|
+
if (buckets.length === 0) {
|
|
1868
|
+
throw new Error("Z.AI quota endpoint returned no displayable usage data.");
|
|
1869
|
+
}
|
|
1870
|
+
const notes = [];
|
|
1871
|
+
const level = asString5(data.level);
|
|
1872
|
+
const planLabel = plan?.name ?? level;
|
|
1873
|
+
if (planLabel) {
|
|
1874
|
+
notes.push(plan?.renewsAt ? `Plan: ${planLabel} \xB7 renews ${plan.renewsAt}` : `Plan: ${planLabel}`);
|
|
1875
|
+
}
|
|
1876
|
+
return {
|
|
1877
|
+
providerId,
|
|
1878
|
+
providerName,
|
|
1879
|
+
capturedAt,
|
|
1880
|
+
source: "zai-quota",
|
|
1881
|
+
semantics: { kind: "consumer-subscription", label: "GLM Coding Plan usage" },
|
|
1882
|
+
buckets,
|
|
1883
|
+
metrics,
|
|
1884
|
+
...notes.length > 0 ? { notes } : {}
|
|
1885
|
+
};
|
|
1886
|
+
}
|
|
1887
|
+
function normalizeZaiSubscriptionPayload(payload) {
|
|
1888
|
+
if (zaiPayloadError(payload)) return void 0;
|
|
1889
|
+
if (!Array.isArray(payload.data)) return void 0;
|
|
1890
|
+
const candidates = [];
|
|
1891
|
+
for (const raw of payload.data) {
|
|
1892
|
+
const entry = asObject12(raw);
|
|
1893
|
+
if (!entry) continue;
|
|
1894
|
+
const name = asString5(entry.productName);
|
|
1895
|
+
if (!name) continue;
|
|
1896
|
+
const renewsAt = planRenewalDate(entry.nextRenewTime);
|
|
1897
|
+
const status = asString5(entry.status)?.toUpperCase();
|
|
1898
|
+
const inCurrentPeriod = asBoolean(entry.inCurrentPeriod);
|
|
1899
|
+
candidates.push({
|
|
1900
|
+
plan: { name, ...renewsAt !== void 0 ? { renewsAt } : {} },
|
|
1901
|
+
...status !== void 0 ? { status } : {},
|
|
1902
|
+
...inCurrentPeriod !== void 0 ? { inCurrentPeriod } : {}
|
|
1903
|
+
});
|
|
1904
|
+
}
|
|
1905
|
+
const hasStateMetadata = candidates.some(
|
|
1906
|
+
(candidate) => candidate.status !== void 0 || candidate.inCurrentPeriod !== void 0
|
|
1907
|
+
);
|
|
1908
|
+
if (!hasStateMetadata) return candidates[0]?.plan;
|
|
1909
|
+
return candidates.find((candidate) => candidate.inCurrentPeriod === true && candidate.status === "VALID")?.plan ?? candidates.find((candidate) => candidate.inCurrentPeriod === true && candidate.status === void 0)?.plan ?? candidates.find((candidate) => candidate.status === "VALID" && candidate.inCurrentPeriod === void 0)?.plan;
|
|
1910
|
+
}
|
|
1911
|
+
function planRenewalDate(value) {
|
|
1912
|
+
if (typeof value === "string" && /^\d{4}-\d{2}-\d{2}/u.test(value)) return value.slice(0, 10);
|
|
1913
|
+
const millis = asNonnegativeNumber4(value);
|
|
1914
|
+
if (millis === void 0 || millis === 0) return void 0;
|
|
1915
|
+
return new Date(millis).toISOString().slice(0, 10);
|
|
1916
|
+
}
|
|
1917
|
+
function sessionWindowMinutes(limit) {
|
|
1918
|
+
const hours = asPositiveNumber(limit.number);
|
|
1919
|
+
return hours === void 0 ? FIVE_HOUR_WINDOW_MINUTES2 : Math.round(hours * 60);
|
|
1920
|
+
}
|
|
1921
|
+
function sessionWindowLabel(limit) {
|
|
1922
|
+
const minutes = sessionWindowMinutes(limit);
|
|
1923
|
+
return minutes === FIVE_HOUR_WINDOW_MINUTES2 ? "5h window" : `${Math.round(minutes / 60)}h window`;
|
|
1924
|
+
}
|
|
1925
|
+
function weeklyWindowMinutes(limit) {
|
|
1926
|
+
const weeks = asPositiveNumber(limit.number);
|
|
1927
|
+
return weeks === void 0 ? WEEKLY_WINDOW_MINUTES2 : Math.round(weeks * WEEKLY_WINDOW_MINUTES2);
|
|
1928
|
+
}
|
|
1929
|
+
function addPercentBucket(buckets, limit, id, label, windowMinutes) {
|
|
1930
|
+
const used = asNonnegativeNumber4(limit.percentage);
|
|
1931
|
+
if (used === void 0) return;
|
|
1932
|
+
const percent = clampPercent3(used);
|
|
1933
|
+
const resetsAt = asEpochSeconds2(limit.nextResetTime);
|
|
1934
|
+
buckets.push({
|
|
1935
|
+
id,
|
|
1936
|
+
label,
|
|
1937
|
+
used: percent,
|
|
1938
|
+
remaining: 100 - percent,
|
|
1939
|
+
limit: 100,
|
|
1940
|
+
unit: "percent",
|
|
1941
|
+
windowMinutes,
|
|
1942
|
+
...resetsAt !== void 0 ? { resetsAt } : {}
|
|
1943
|
+
});
|
|
1944
|
+
}
|
|
1945
|
+
function addCountBucket(buckets, limit, id, label, windowMinutes) {
|
|
1946
|
+
const used = asNonnegativeNumber4(limit.currentValue);
|
|
1947
|
+
const quota = asNonnegativeNumber4(limit.usage);
|
|
1948
|
+
if (used === void 0 || quota === void 0) return;
|
|
1949
|
+
const resetsAt = asEpochSeconds2(limit.nextResetTime);
|
|
1950
|
+
buckets.push({
|
|
1951
|
+
id,
|
|
1952
|
+
label,
|
|
1953
|
+
used,
|
|
1954
|
+
remaining: Math.max(0, quota - used),
|
|
1955
|
+
limit: quota,
|
|
1956
|
+
unit: "count",
|
|
1957
|
+
...windowMinutes !== void 0 ? { windowMinutes } : {},
|
|
1958
|
+
...resetsAt !== void 0 ? { resetsAt } : {}
|
|
1959
|
+
});
|
|
1960
|
+
}
|
|
1961
|
+
function addUsageDetailMetrics(metrics, value) {
|
|
1962
|
+
if (!Array.isArray(value)) return;
|
|
1963
|
+
for (const raw of value) {
|
|
1964
|
+
const detail = asObject12(raw);
|
|
1965
|
+
if (!detail) continue;
|
|
1966
|
+
const label = asString5(detail.modelCode);
|
|
1967
|
+
const usage = asNonnegativeNumber4(detail.usage);
|
|
1968
|
+
if (!label || usage === void 0) continue;
|
|
1969
|
+
metrics.push({ id: `mcp-${kebabCase(label)}`, label, value: usage, unit: "count" });
|
|
1970
|
+
}
|
|
1971
|
+
}
|
|
1972
|
+
function asObject12(value) {
|
|
1973
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
1974
|
+
return value;
|
|
1975
|
+
}
|
|
1976
|
+
function asString5(value) {
|
|
1977
|
+
if (typeof value !== "string") return void 0;
|
|
1978
|
+
return sanitizeDisplayText(value, 80) || void 0;
|
|
1979
|
+
}
|
|
1980
|
+
function asNonnegativeNumber4(value) {
|
|
1981
|
+
if (typeof value !== "number" || !Number.isFinite(value) || value < 0) return void 0;
|
|
1982
|
+
return value;
|
|
1983
|
+
}
|
|
1984
|
+
function asPositiveNumber(value) {
|
|
1985
|
+
const number = asNonnegativeNumber4(value);
|
|
1986
|
+
return number !== void 0 && number > 0 ? number : void 0;
|
|
1987
|
+
}
|
|
1988
|
+
function asBoolean(value) {
|
|
1989
|
+
if (typeof value === "boolean") return value;
|
|
1990
|
+
if (value === 1) return true;
|
|
1991
|
+
if (value === 0) return false;
|
|
1992
|
+
return void 0;
|
|
1993
|
+
}
|
|
1994
|
+
function asEpochSeconds2(value) {
|
|
1995
|
+
const millis = asNonnegativeNumber4(value);
|
|
1996
|
+
if (millis === void 0) return void 0;
|
|
1997
|
+
return Math.floor(millis / 1e3);
|
|
1998
|
+
}
|
|
1999
|
+
function kebabCase(label) {
|
|
2000
|
+
return label.toLowerCase().replace(/[^a-z0-9]+/gu, "-").replace(/^-+|-+$/gu, "") || "tool";
|
|
2001
|
+
}
|
|
2002
|
+
function clampPercent3(value) {
|
|
2003
|
+
return Math.min(100, Math.max(0, value));
|
|
2004
|
+
}
|
|
2005
|
+
|
|
2006
|
+
// src/usage-targets.ts
|
|
2007
|
+
var MAX_TARGETS = 1e3;
|
|
2008
|
+
var MAX_TARGET_ID_CHARS = 256;
|
|
2009
|
+
var MAX_TARGET_LABEL_CHARS = 120;
|
|
2010
|
+
var MAX_TARGET_DESCRIPTION_CHARS = 180;
|
|
2011
|
+
async function resolveUsageTarget(adapter, auth, rememberedTargetId, signal, timeoutMs, guard) {
|
|
2012
|
+
if (!adapter.targets) return { kind: "selected" };
|
|
2013
|
+
if (rememberedTargetId !== void 0 && !isBoundedTargetId(rememberedTargetId)) {
|
|
2014
|
+
throw new Error(`The remembered ${adapter.targets.singularLabel} identifier was invalid.`);
|
|
2015
|
+
}
|
|
2016
|
+
const choices = await listUsageTargets(adapter, auth, signal, timeoutMs, guard);
|
|
2017
|
+
if (rememberedTargetId) {
|
|
2018
|
+
return choices.some((choice) => choice.id === rememberedTargetId) ? { kind: "selected", targetId: rememberedTargetId } : { kind: "selection-required", choices };
|
|
2019
|
+
}
|
|
2020
|
+
if (choices.length === 1) return { kind: "selected", targetId: choices[0]?.id };
|
|
2021
|
+
return { kind: "selection-required", choices };
|
|
2022
|
+
}
|
|
2023
|
+
async function listUsageTargets(adapter, auth, signal, timeoutMs, guard) {
|
|
2024
|
+
if (!adapter.targets) return [];
|
|
2025
|
+
const startedAt = Date.now();
|
|
2026
|
+
await guard();
|
|
2027
|
+
const listed = await adapter.targets.list(auth, signal, remainingTargetTimeout(timeoutMs, startedAt), guard);
|
|
2028
|
+
await guard();
|
|
2029
|
+
remainingTargetTimeout(timeoutMs, startedAt);
|
|
2030
|
+
const choices = normalizeUsageTargets(listed);
|
|
2031
|
+
if (choices.length === 0) {
|
|
2032
|
+
throw new Error(`${adapter.targets.pluralLabel} discovery returned no choices.`);
|
|
2033
|
+
}
|
|
2034
|
+
return choices;
|
|
2035
|
+
}
|
|
2036
|
+
function normalizeUsageTargets(targets) {
|
|
2037
|
+
if (!Array.isArray(targets)) throw new Error("Target discovery did not return a choices array.");
|
|
2038
|
+
if (targets.length > MAX_TARGETS) {
|
|
2039
|
+
throw new Error(`Target discovery exceeded ${MAX_TARGETS} choices.`);
|
|
2040
|
+
}
|
|
2041
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2042
|
+
return targets.map((target) => {
|
|
2043
|
+
if (!target || typeof target !== "object" || Array.isArray(target)) {
|
|
2044
|
+
throw new Error("Target discovery returned an invalid choice.");
|
|
2045
|
+
}
|
|
2046
|
+
const { id, label, description } = target;
|
|
2047
|
+
if (!isBoundedTargetId(id)) throw new Error("Target discovery returned an invalid ID.");
|
|
2048
|
+
if (seen.has(id)) throw new Error(`Target discovery repeated ${id}.`);
|
|
2049
|
+
seen.add(id);
|
|
2050
|
+
if (typeof label !== "string") {
|
|
2051
|
+
throw new Error("Target discovery returned an invalid display label.");
|
|
2052
|
+
}
|
|
2053
|
+
if (description !== void 0 && typeof description !== "string") {
|
|
2054
|
+
throw new Error("Target discovery returned an invalid description.");
|
|
2055
|
+
}
|
|
2056
|
+
const safeLabel2 = sanitizeDisplayText(label, MAX_TARGET_LABEL_CHARS);
|
|
2057
|
+
if (!safeLabel2) throw new Error("Target discovery returned an empty display label.");
|
|
2058
|
+
const safeDescription = description ? sanitizeDisplayText(description, MAX_TARGET_DESCRIPTION_CHARS) : void 0;
|
|
2059
|
+
return { id, label: safeLabel2, ...safeDescription ? { description: safeDescription } : {} };
|
|
2060
|
+
});
|
|
2061
|
+
}
|
|
2062
|
+
function createUsageTargetSelectOptions(targets) {
|
|
2063
|
+
const normalized = normalizeUsageTargets(targets);
|
|
2064
|
+
const ids = /* @__PURE__ */ new Map();
|
|
2065
|
+
const options = normalized.map((target) => {
|
|
2066
|
+
const base = target.description ? `${target.label} \u2014 ${target.description}` : target.label;
|
|
2067
|
+
let option = base;
|
|
2068
|
+
if (ids.has(option)) {
|
|
2069
|
+
const safeId = sanitizeDisplayText(target.id, 80) || "target";
|
|
2070
|
+
option = `${base} \xB7 ${safeId}`;
|
|
2071
|
+
let duplicate = 2;
|
|
2072
|
+
while (ids.has(option)) {
|
|
2073
|
+
option = `${base} \xB7 ${safeId} (${duplicate})`;
|
|
2074
|
+
duplicate += 1;
|
|
2075
|
+
}
|
|
2076
|
+
}
|
|
2077
|
+
ids.set(option, target.id);
|
|
2078
|
+
return option;
|
|
2079
|
+
});
|
|
2080
|
+
return { options, targetIdFor: (option) => ids.get(option) };
|
|
2081
|
+
}
|
|
2082
|
+
function remainingTargetTimeout(timeoutMs, startedAt) {
|
|
2083
|
+
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
2084
|
+
if (remaining <= 0) throw new Error("Timed out while discovering provider targets.");
|
|
2085
|
+
return remaining;
|
|
2086
|
+
}
|
|
2087
|
+
function isBoundedTargetId(value) {
|
|
2088
|
+
return typeof value === "string" && value.length > 0 && value.length <= MAX_TARGET_ID_CHARS && ![...value].some((character) => {
|
|
2089
|
+
const codePoint = character.codePointAt(0) ?? 0;
|
|
2090
|
+
return codePoint <= 31 || codePoint >= 127 && codePoint <= 159;
|
|
2091
|
+
});
|
|
2092
|
+
}
|
|
2093
|
+
|
|
2094
|
+
// src/query.ts
|
|
2095
|
+
import { randomBytes } from "node:crypto";
|
|
2096
|
+
import { readStoredCredential as readStoredCredential2 } from "@earendil-works/pi-coding-agent";
|
|
2097
|
+
var BASETEN_BILLING_USAGE_URL = "https://api.baseten.co/v1/billing/usage_summary";
|
|
2098
|
+
var BASETEN_USAGE_WINDOW_DAYS = 30;
|
|
2099
|
+
var CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
2100
|
+
var DEEPSEEK_BALANCE_URL = "https://api.deepseek.com/user/balance";
|
|
2101
|
+
var GITHUB_COPILOT_USAGE_URL = "https://api.github.com/copilot_internal/user";
|
|
2102
|
+
var OPENROUTER_KEY_URL = "https://openrouter.ai/api/v1/key";
|
|
2103
|
+
var VERCEL_AI_GATEWAY_CREDITS_URL = "https://ai-gateway.vercel.sh/v1/credits";
|
|
2104
|
+
var OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
2105
|
+
var KIMI_CODING_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
|
|
2106
|
+
var MINIMAX_API_ROOTS = Object.freeze({
|
|
2107
|
+
minimax: "https://api.minimax.io",
|
|
2108
|
+
"minimax-cn": "https://api.minimaxi.com"
|
|
2109
|
+
});
|
|
2110
|
+
var MOONSHOT_BALANCE_URLS = Object.freeze({
|
|
2111
|
+
moonshotai: "https://api.moonshot.ai/v1/users/me/balance",
|
|
2112
|
+
"moonshotai-cn": "https://api.moonshot.cn/v1/users/me/balance"
|
|
2113
|
+
});
|
|
2114
|
+
var SHARED_MOONSHOT_ENV_VAR = "MOONSHOT_API_KEY";
|
|
2115
|
+
var XAI_USER_URL = "https://cli-chat-proxy.grok.com/v1/user?include=subscription";
|
|
2116
|
+
var XAI_BILLING_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
|
|
2117
|
+
var XAI_CLIENT_HEADERS = Object.freeze({
|
|
2118
|
+
"X-XAI-Token-Auth": "xai-grok-cli",
|
|
2119
|
+
"x-grok-client-version": "1.0.10",
|
|
2120
|
+
"x-grok-client-mode": "interactive"
|
|
2121
|
+
});
|
|
2122
|
+
var MAX_SUCCESS_BODY_BYTES = 64 * 1024;
|
|
2123
|
+
var MAX_ERROR_BODY_BYTES = 4 * 1024;
|
|
2124
|
+
var AUTH_FINGERPRINT_SALT = randomBytes(32);
|
|
2125
|
+
var SUPPORTED_ADAPTERS = [
|
|
2126
|
+
{
|
|
2127
|
+
id: "baseten",
|
|
2128
|
+
displayName: "Baseten",
|
|
2129
|
+
semantics: { kind: "api-key", label: "Organization Model APIs spend" },
|
|
2130
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2131
|
+
if (!guard) throw new Error("Baseten billing usage requires request-boundary revalidation.");
|
|
2132
|
+
const startedAt = Date.now();
|
|
2133
|
+
await guard();
|
|
2134
|
+
const windowAt = Date.now();
|
|
2135
|
+
const payload = await fetchProviderJson(
|
|
2136
|
+
basetenBillingUsageUrl(windowAt),
|
|
2137
|
+
auth,
|
|
2138
|
+
signal,
|
|
2139
|
+
remainingTimeout2(timeoutMs, startedAt, "fetching Baseten billing usage"),
|
|
2140
|
+
"Baseten billing usage endpoint",
|
|
2141
|
+
{ redirect: "error" }
|
|
2142
|
+
);
|
|
2143
|
+
await guard();
|
|
2144
|
+
return normalizeBasetenBillingUsagePayload(payload, Date.now());
|
|
2145
|
+
}
|
|
2146
|
+
},
|
|
2147
|
+
OPENAI_CHATGPT_ADAPTER,
|
|
2148
|
+
{
|
|
2149
|
+
id: "openai-codex",
|
|
2150
|
+
displayName: "OpenAI Codex",
|
|
2151
|
+
semantics: {
|
|
2152
|
+
kind: "consumer-subscription",
|
|
2153
|
+
label: "ChatGPT subscription limits"
|
|
2154
|
+
},
|
|
2155
|
+
async query(auth, signal, timeoutMs) {
|
|
2156
|
+
const payload = await fetchProviderJson(CODEX_USAGE_URL, auth, signal, timeoutMs, "Codex usage endpoint");
|
|
2157
|
+
return normalizeCodexBackendPayload(payload, Date.now());
|
|
2158
|
+
}
|
|
2159
|
+
},
|
|
2160
|
+
{
|
|
2161
|
+
id: "deepseek",
|
|
2162
|
+
displayName: "DeepSeek",
|
|
2163
|
+
semantics: { kind: "api-key", label: "DeepSeek API balance" },
|
|
2164
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2165
|
+
if (!guard) throw new Error("DeepSeek API balance requires request-boundary revalidation.");
|
|
2166
|
+
const startedAt = Date.now();
|
|
2167
|
+
await guard();
|
|
2168
|
+
const remainingMs = timeoutMs - (Date.now() - startedAt);
|
|
2169
|
+
if (remainingMs <= 0) throw new Error("Timed out while revalidating DeepSeek runtime auth.");
|
|
2170
|
+
const payload = await fetchProviderJson(
|
|
2171
|
+
DEEPSEEK_BALANCE_URL,
|
|
2172
|
+
auth,
|
|
2173
|
+
signal,
|
|
2174
|
+
remainingMs,
|
|
2175
|
+
"DeepSeek API balance endpoint",
|
|
2176
|
+
{ redirect: "error" }
|
|
2177
|
+
);
|
|
2178
|
+
return normalizeDeepSeekBalancePayload(payload, Date.now());
|
|
2179
|
+
}
|
|
2180
|
+
},
|
|
2181
|
+
{
|
|
2182
|
+
id: "github-copilot",
|
|
2183
|
+
displayName: "GitHub Copilot",
|
|
2184
|
+
semantics: {
|
|
2185
|
+
kind: "consumer-subscription",
|
|
2186
|
+
label: "GitHub Copilot account allowance"
|
|
2187
|
+
},
|
|
2188
|
+
async query(auth, signal, timeoutMs) {
|
|
2189
|
+
const payload = await fetchProviderJson(
|
|
2190
|
+
GITHUB_COPILOT_USAGE_URL,
|
|
2191
|
+
auth,
|
|
2192
|
+
signal,
|
|
2193
|
+
timeoutMs,
|
|
2194
|
+
"GitHub Copilot usage endpoint"
|
|
2195
|
+
);
|
|
2196
|
+
return normalizeGitHubCopilotUsagePayload(payload, Date.now());
|
|
2197
|
+
}
|
|
2198
|
+
},
|
|
2199
|
+
{
|
|
2200
|
+
id: "openrouter",
|
|
2201
|
+
displayName: "OpenRouter",
|
|
2202
|
+
semantics: { kind: "api-key", label: "API-key spend limits" },
|
|
2203
|
+
async query(auth, signal, timeoutMs) {
|
|
2204
|
+
const payload = await fetchProviderJson(OPENROUTER_KEY_URL, auth, signal, timeoutMs, "OpenRouter key endpoint");
|
|
2205
|
+
return normalizeOpenRouterKeyPayload(payload, Date.now());
|
|
2206
|
+
}
|
|
2207
|
+
},
|
|
2208
|
+
{
|
|
2209
|
+
id: "vercel-ai-gateway",
|
|
2210
|
+
displayName: "Vercel AI Gateway",
|
|
2211
|
+
semantics: { kind: "api-key", label: "AI Gateway credits and lifetime spend" },
|
|
2212
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2213
|
+
if (!guard) throw new Error("Vercel AI Gateway usage requires request-boundary revalidation.");
|
|
2214
|
+
const startedAt = Date.now();
|
|
2215
|
+
await guard();
|
|
2216
|
+
const payload = await fetchProviderJson(
|
|
2217
|
+
VERCEL_AI_GATEWAY_CREDITS_URL,
|
|
2218
|
+
auth,
|
|
2219
|
+
signal,
|
|
2220
|
+
remainingTimeout2(timeoutMs, startedAt, "fetching Vercel AI Gateway credits"),
|
|
2221
|
+
"Vercel AI Gateway credits endpoint",
|
|
2222
|
+
{ redirect: "error" }
|
|
2223
|
+
);
|
|
2224
|
+
await guard();
|
|
2225
|
+
return normalizeVercelAIGatewayCreditsPayload(payload, Date.now());
|
|
2226
|
+
}
|
|
2227
|
+
},
|
|
2228
|
+
createFireworksAdapter(fetchProviderJson),
|
|
2229
|
+
{
|
|
2230
|
+
id: "opencode-go",
|
|
2231
|
+
displayName: "OpenCode Go",
|
|
2232
|
+
semantics: { kind: "consumer-subscription", label: "OpenCode Zen plan usage" },
|
|
2233
|
+
async query(auth, signal, timeoutMs) {
|
|
2234
|
+
const payload = await fetchProviderJson(
|
|
2235
|
+
OPENCODE_GO_USAGE_URL,
|
|
2236
|
+
auth,
|
|
2237
|
+
signal,
|
|
2238
|
+
timeoutMs,
|
|
2239
|
+
"OpenCode Zen usage endpoint"
|
|
2240
|
+
);
|
|
2241
|
+
return normalizeOpenCodeZenPayload(payload, Date.now());
|
|
2242
|
+
}
|
|
2243
|
+
},
|
|
2244
|
+
{
|
|
2245
|
+
id: "kimi-coding",
|
|
2246
|
+
displayName: "Kimi For Coding",
|
|
2247
|
+
semantics: { kind: "consumer-subscription", label: "Kimi Coding Plan usage" },
|
|
2248
|
+
async query(auth, signal, timeoutMs) {
|
|
2249
|
+
const payload = await fetchProviderJson(
|
|
2250
|
+
KIMI_CODING_USAGE_URL,
|
|
2251
|
+
auth,
|
|
2252
|
+
signal,
|
|
2253
|
+
timeoutMs,
|
|
2254
|
+
"Kimi Coding usage endpoint",
|
|
2255
|
+
{ redirect: "error" }
|
|
2256
|
+
);
|
|
2257
|
+
return normalizeKimiCodingUsagePayload(payload, Date.now());
|
|
2258
|
+
}
|
|
2259
|
+
},
|
|
2260
|
+
{
|
|
2261
|
+
id: "minimax",
|
|
2262
|
+
displayName: "MiniMax",
|
|
2263
|
+
semantics: { kind: "consumer-subscription", label: "MiniMax usage" },
|
|
2264
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2265
|
+
return queryMiniMaxUsage("minimax", auth, signal, timeoutMs, guard);
|
|
2266
|
+
}
|
|
2267
|
+
},
|
|
2268
|
+
{
|
|
2269
|
+
id: "minimax-cn",
|
|
2270
|
+
displayName: "MiniMax CN",
|
|
2271
|
+
semantics: { kind: "consumer-subscription", label: "MiniMax usage" },
|
|
2272
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2273
|
+
return queryMiniMaxUsage("minimax-cn", auth, signal, timeoutMs, guard);
|
|
2274
|
+
}
|
|
2275
|
+
},
|
|
2276
|
+
{
|
|
2277
|
+
id: "moonshotai",
|
|
2278
|
+
displayName: "Moonshot AI",
|
|
2279
|
+
semantics: { kind: "api-key", label: "Moonshot API account balance" },
|
|
2280
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2281
|
+
return queryMoonshotBalance("moonshotai", auth, signal, timeoutMs, guard);
|
|
2282
|
+
}
|
|
2283
|
+
},
|
|
2284
|
+
{
|
|
2285
|
+
id: "moonshotai-cn",
|
|
2286
|
+
displayName: "Moonshot AI CN",
|
|
2287
|
+
semantics: { kind: "api-key", label: "Moonshot API account balance" },
|
|
2288
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2289
|
+
return queryMoonshotBalance("moonshotai-cn", auth, signal, timeoutMs, guard);
|
|
2290
|
+
}
|
|
2291
|
+
},
|
|
2292
|
+
{
|
|
2293
|
+
id: "zai",
|
|
2294
|
+
displayName: "Z.AI",
|
|
2295
|
+
invalidateCacheOnFailure: true,
|
|
2296
|
+
semantics: { kind: "consumer-subscription", label: "GLM Coding Plan usage" },
|
|
2297
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2298
|
+
return queryZaiUsage("zai", "Z.AI", auth, signal, timeoutMs, guard);
|
|
2299
|
+
}
|
|
2300
|
+
},
|
|
2301
|
+
{
|
|
2302
|
+
id: "zai-coding-cn",
|
|
2303
|
+
displayName: "Z.AI Coding CN",
|
|
2304
|
+
invalidateCacheOnFailure: true,
|
|
2305
|
+
semantics: { kind: "consumer-subscription", label: "GLM Coding Plan usage" },
|
|
2306
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2307
|
+
return queryZaiUsage("zai-coding-cn", "Z.AI Coding CN", auth, signal, timeoutMs, guard);
|
|
2308
|
+
}
|
|
2309
|
+
}
|
|
2310
|
+
];
|
|
2311
|
+
var XAI_ADAPTER = {
|
|
2312
|
+
id: "xai",
|
|
2313
|
+
displayName: "xAI",
|
|
2314
|
+
semantics: {
|
|
2315
|
+
kind: "consumer-subscription",
|
|
2316
|
+
label: "xAI consumer subscription usage"
|
|
2317
|
+
},
|
|
2318
|
+
publishesStatusline: false,
|
|
2319
|
+
async query(auth, signal, timeoutMs, guard) {
|
|
2320
|
+
if (!guard) throw new Error("xAI usage requires request-boundary revalidation.");
|
|
2321
|
+
const startedAt = Date.now();
|
|
2322
|
+
const clientAuth = {
|
|
2323
|
+
...auth,
|
|
2324
|
+
headers: { ...auth.headers, ...XAI_CLIENT_HEADERS }
|
|
2325
|
+
};
|
|
2326
|
+
await guard();
|
|
2327
|
+
const userPayload = await fetchProviderJson(
|
|
2328
|
+
XAI_USER_URL,
|
|
2329
|
+
clientAuth,
|
|
2330
|
+
signal,
|
|
2331
|
+
remainingTimeout2(timeoutMs, startedAt),
|
|
2332
|
+
"xAI consumer identity endpoint",
|
|
2333
|
+
{ redirect: "error", userAgent: false }
|
|
2334
|
+
);
|
|
2335
|
+
await guard();
|
|
2336
|
+
const userId = validatedXaiUserId(userPayload.userId);
|
|
2337
|
+
const billingAuth = {
|
|
2338
|
+
...clientAuth,
|
|
2339
|
+
headers: { ...clientAuth.headers, "x-userid": userId },
|
|
2340
|
+
secrets: [...clientAuth.secrets, userId]
|
|
2341
|
+
};
|
|
2342
|
+
await guard();
|
|
2343
|
+
const billingPayload = await fetchProviderJson(
|
|
2344
|
+
XAI_BILLING_URL,
|
|
2345
|
+
billingAuth,
|
|
2346
|
+
signal,
|
|
2347
|
+
remainingTimeout2(timeoutMs, startedAt),
|
|
2348
|
+
"xAI consumer billing endpoint",
|
|
2349
|
+
{ redirect: "error", userAgent: false }
|
|
2350
|
+
);
|
|
2351
|
+
await guard();
|
|
2352
|
+
return normalizeXaiBillingPayload(billingPayload, userPayload.subscriptionTier, Date.now());
|
|
2353
|
+
}
|
|
2354
|
+
};
|
|
2355
|
+
function usageAdapters() {
|
|
2356
|
+
return [...SUPPORTED_ADAPTERS, XAI_ADAPTER];
|
|
2357
|
+
}
|
|
2358
|
+
function adapterForProvider(providerId) {
|
|
2359
|
+
return usageAdapters().find((adapter) => adapter.id === providerId);
|
|
2360
|
+
}
|
|
2361
|
+
function isStaleExtensionContextError(error) {
|
|
2362
|
+
return error instanceof Error && error.message.includes("This extension ctx is stale after session replacement or reload");
|
|
2363
|
+
}
|
|
2364
|
+
async function resolveUsageAuth(ctx, adapter, salt = AUTH_FINGERPRINT_SALT, credentialReader = readStoredCredential2, candidateReader, openaiCompanionUsage = false) {
|
|
2365
|
+
if (ctx.model?.provider === adapter.id && !hasOfficialOrigin(ctx.model, adapter.id)) {
|
|
2366
|
+
throw new Error(
|
|
2367
|
+
`${adapter.displayName} usage cannot send a custom provider base URL credential to the official usage endpoint.`
|
|
2368
|
+
);
|
|
2369
|
+
}
|
|
2370
|
+
const model = candidateModels(ctx, adapter.id).find((candidate) => hasOfficialOrigin(candidate, adapter.id));
|
|
2371
|
+
if (!model) return void 0;
|
|
2372
|
+
if (["github-copilot", "openai", "xai"].includes(adapter.id) && candidateReader?.waitUntilReady && !await candidateReader.waitUntilReady(ctx, adapter.id)) {
|
|
2373
|
+
throw new Error(`${adapter.displayName} OAuth credential readiness failed closed.`);
|
|
2374
|
+
}
|
|
2375
|
+
const registry = ctx.modelRegistry;
|
|
2376
|
+
const provider = registry.getProvider?.(adapter.id);
|
|
2377
|
+
if (provider?.baseUrl && !hasOfficialUrlOrigin(provider.baseUrl, adapter.id)) {
|
|
2378
|
+
throw new Error(
|
|
2379
|
+
`${adapter.displayName} usage cannot send an overridden provider credential to the official usage endpoint.`
|
|
2380
|
+
);
|
|
2381
|
+
}
|
|
2382
|
+
let modelAuth;
|
|
2383
|
+
const currentModel = ctx.model?.provider === adapter.id ? ctx.model : void 0;
|
|
2384
|
+
const resolveCurrentModelAuth = async () => {
|
|
2385
|
+
if (!currentModel || typeof registry.getApiKeyAndHeaders !== "function") return void 0;
|
|
2386
|
+
const result = await registry.getApiKeyAndHeaders(currentModel);
|
|
2387
|
+
if (!result.ok) throw new Error(redactUsageError(result.error));
|
|
2388
|
+
return adapter.id === "openai" || authorizationFrom(result) ? result : void 0;
|
|
2389
|
+
};
|
|
2390
|
+
const resolveSelectedAuthLast = ["deepseek", "minimax", "minimax-cn", "openai"].includes(adapter.id);
|
|
2391
|
+
if (!resolveSelectedAuthLast) modelAuth = await resolveCurrentModelAuth();
|
|
2392
|
+
if (typeof registry.getProviderAuth !== "function") {
|
|
2393
|
+
throw new Error("pi-usage requires Pi 0.81.0 or newer to validate resolved provider auth.");
|
|
2394
|
+
}
|
|
2395
|
+
if (!moonshotProviderAuthIsAllowed(ctx, adapter.id)) return void 0;
|
|
2396
|
+
const providerResult = await registry.getProviderAuth(adapter.id);
|
|
2397
|
+
if (!moonshotProviderAuthIsAllowed(ctx, adapter.id)) return void 0;
|
|
2398
|
+
if (providerResult?.auth.baseUrl && !hasOfficialUrlOrigin(providerResult.auth.baseUrl, adapter.id)) {
|
|
2399
|
+
throw new Error(
|
|
2400
|
+
`${adapter.displayName} usage cannot send a proxy-resolved credential to the official usage endpoint.`
|
|
2401
|
+
);
|
|
2402
|
+
}
|
|
2403
|
+
if (resolveSelectedAuthLast) modelAuth = await resolveCurrentModelAuth();
|
|
2404
|
+
if (modelAuth?.baseUrl && !hasOfficialUrlOrigin(modelAuth.baseUrl, adapter.id)) {
|
|
2405
|
+
throw new Error(
|
|
2406
|
+
`${adapter.displayName} usage cannot send model-resolved proxy credentials to the official usage endpoint.`
|
|
2407
|
+
);
|
|
2408
|
+
}
|
|
2409
|
+
const auth = modelAuth ?? providerResult?.auth;
|
|
2410
|
+
if (!auth) return void 0;
|
|
2411
|
+
const finalize = (resolved) => {
|
|
2412
|
+
const preservedAuth = { ...providerResult?.auth ?? auth };
|
|
2413
|
+
const env = providerResult?.env ?? modelAuth?.env;
|
|
2414
|
+
const source = providerResult?.source;
|
|
2415
|
+
const effectiveBaseUrl = modelAuth?.baseUrl ?? providerResult?.auth.baseUrl ?? provider?.baseUrl ?? model.baseUrl;
|
|
2416
|
+
const redactionInputs = [
|
|
2417
|
+
preservedAuth.apiKey,
|
|
2418
|
+
...Object.values(preservedAuth.headers ?? {}),
|
|
2419
|
+
...Object.values(env ?? {}),
|
|
2420
|
+
modelAuth?.apiKey,
|
|
2421
|
+
...Object.values(modelAuth?.headers ?? {})
|
|
2422
|
+
].filter((value) => typeof value === "string" && value.length > 0);
|
|
2423
|
+
return {
|
|
2424
|
+
...resolved,
|
|
2425
|
+
auth: preservedAuth,
|
|
2426
|
+
...env ? { env: { ...env } } : {},
|
|
2427
|
+
...source ? { source } : {},
|
|
2428
|
+
effectiveBaseUrl,
|
|
2429
|
+
secrets: [.../* @__PURE__ */ new Set([...resolved.secrets, ...redactionInputs])],
|
|
2430
|
+
fingerprint: fingerprintResolvedAuth(
|
|
2431
|
+
{
|
|
2432
|
+
apiKey: resolved.apiKey,
|
|
2433
|
+
headers: resolved.headers,
|
|
2434
|
+
baseUrl: effectiveBaseUrl,
|
|
2435
|
+
env,
|
|
2436
|
+
source,
|
|
2437
|
+
providerAuth: preservedAuth
|
|
2438
|
+
},
|
|
2439
|
+
salt
|
|
2440
|
+
)
|
|
2441
|
+
};
|
|
2442
|
+
};
|
|
2443
|
+
if (adapter.id === "openai") {
|
|
2444
|
+
if (!providerResult) return void 0;
|
|
2445
|
+
if (providerResult.source !== "OAuth") throw new UnsupportedOpenAIUsageAuthError();
|
|
2446
|
+
const offered = candidateReader ? await candidateReader(ctx, adapter.id) : fallbackOAuthCredentialCandidates(adapter.id, credentialReader);
|
|
2447
|
+
if (!offered.ok) throw new Error("OpenAI OAuth credential discovery failed closed.");
|
|
2448
|
+
const native = finalize(
|
|
2449
|
+
resolveOpenAIChatGPTAuth(auth, providerResult.auth, providerResult.source, model, offered.candidates)
|
|
2450
|
+
);
|
|
2451
|
+
if (!openaiCompanionUsage) return native;
|
|
2452
|
+
const { resolveOpenAICompanionAuth } = await import("./openai-companion-auth-Q456G46T.ts");
|
|
2453
|
+
return resolveOpenAICompanionAuth(ctx, native, salt, credentialReader, candidateReader);
|
|
2454
|
+
}
|
|
2455
|
+
if (adapter.id === "github-copilot") {
|
|
2456
|
+
const offered = candidateReader ? await candidateReader(ctx, adapter.id) : fallbackOAuthCredentialCandidates(adapter.id, credentialReader);
|
|
2457
|
+
if (!offered.ok) {
|
|
2458
|
+
throw new Error("GitHub Copilot OAuth credential discovery failed closed.");
|
|
2459
|
+
}
|
|
2460
|
+
return finalize(resolveGitHubCopilotUsageAuth(auth, model, salt, offered.candidates, offered.offeredCount === 0));
|
|
2461
|
+
}
|
|
2462
|
+
if (adapter.id === "xai") {
|
|
2463
|
+
const offered = candidateReader ? await candidateReader(ctx, adapter.id) : fallbackOAuthCredentialCandidates(adapter.id, credentialReader);
|
|
2464
|
+
if (!offered.ok) throw new Error("xAI OAuth credential discovery failed closed.");
|
|
2465
|
+
return finalize(resolveXaiUsageAuth(auth, model, salt, offered.candidates));
|
|
2466
|
+
}
|
|
2467
|
+
if (adapter.id === "deepseek") {
|
|
2468
|
+
const resolvedAuthorization = authorizationFrom(auth);
|
|
2469
|
+
const access = bearerToken(resolvedAuthorization);
|
|
2470
|
+
if (!access) throw new Error("DeepSeek API balance requires Bearer authentication.");
|
|
2471
|
+
const authorization2 = `Bearer ${access}`;
|
|
2472
|
+
const headers2 = { Authorization: authorization2 };
|
|
2473
|
+
return finalize({
|
|
2474
|
+
apiKey: access,
|
|
2475
|
+
headers: headers2,
|
|
2476
|
+
fingerprint: "",
|
|
2477
|
+
secrets: [
|
|
2478
|
+
access,
|
|
2479
|
+
auth.apiKey,
|
|
2480
|
+
headerValue(auth.headers, "Authorization"),
|
|
2481
|
+
resolvedAuthorization,
|
|
2482
|
+
authorization2
|
|
2483
|
+
].filter((value) => Boolean(value)),
|
|
2484
|
+
model
|
|
2485
|
+
});
|
|
2486
|
+
}
|
|
2487
|
+
const authorization = authorizationFrom(auth);
|
|
2488
|
+
if (!authorization) return void 0;
|
|
2489
|
+
const headers = { Authorization: authorization };
|
|
2490
|
+
const secrets = [auth.apiKey, headerValue(auth.headers, "Authorization"), authorization].filter(
|
|
2491
|
+
(value) => Boolean(value)
|
|
2492
|
+
);
|
|
2493
|
+
return finalize({
|
|
2494
|
+
apiKey: auth.apiKey,
|
|
2495
|
+
headers,
|
|
2496
|
+
fingerprint: "",
|
|
2497
|
+
secrets,
|
|
2498
|
+
model
|
|
2499
|
+
});
|
|
2500
|
+
}
|
|
2501
|
+
async function queryProviderUsage(adapter, auth, signal, timeoutMs, guard, targetOrSettings) {
|
|
2502
|
+
const startedAt = Date.now();
|
|
2503
|
+
let targetId = typeof targetOrSettings === "string" ? targetOrSettings : adapter.id === "fireworks" ? targetOrSettings?.fireworksAccountId : void 0;
|
|
2504
|
+
let resolvedLegacyFireworksTarget = false;
|
|
2505
|
+
try {
|
|
2506
|
+
if (adapter.id === "fireworks" && typeof targetOrSettings !== "string" && adapter.targets && guard) {
|
|
2507
|
+
const target = await resolveUsageTarget(
|
|
2508
|
+
adapter,
|
|
2509
|
+
auth,
|
|
2510
|
+
targetId,
|
|
2511
|
+
signal,
|
|
2512
|
+
remainingTimeout2(timeoutMs, startedAt, "resolving the Fireworks account"),
|
|
2513
|
+
guard
|
|
2514
|
+
);
|
|
2515
|
+
if (target.kind === "selection-required") {
|
|
2516
|
+
throw new Error("Fireworks account selection is required.");
|
|
2517
|
+
}
|
|
2518
|
+
targetId = target.targetId;
|
|
2519
|
+
resolvedLegacyFireworksTarget = true;
|
|
2520
|
+
}
|
|
2521
|
+
return await adapter.query(
|
|
2522
|
+
auth,
|
|
2523
|
+
signal,
|
|
2524
|
+
resolvedLegacyFireworksTarget ? remainingTimeout2(timeoutMs, startedAt, `querying ${adapter.displayName} usage`) : timeoutMs,
|
|
2525
|
+
guard,
|
|
2526
|
+
targetId
|
|
2527
|
+
);
|
|
2528
|
+
} catch (error) {
|
|
2529
|
+
if (isStaleExtensionContextError(error) || isAbortError(error)) throw error;
|
|
2530
|
+
throw new Error(redactUsageError(errorMessage(error), auth.secrets));
|
|
2531
|
+
}
|
|
2532
|
+
}
|
|
2533
|
+
function providerIsConfigured(ctx, providerId) {
|
|
2534
|
+
try {
|
|
2535
|
+
const status = ctx.modelRegistry.getProviderAuthStatus(providerId);
|
|
2536
|
+
return status.configured && moonshotProviderAuthSourceIsAllowed(ctx, providerId, status.source, status.label);
|
|
2537
|
+
} catch {
|
|
2538
|
+
return !isMoonshotSiblingProvider(ctx, providerId) && candidateModels(ctx, providerId).length > 0;
|
|
2539
|
+
}
|
|
2540
|
+
}
|
|
2541
|
+
function moonshotProviderAuthIsAllowed(ctx, providerId) {
|
|
2542
|
+
if (!isMoonshotSiblingProvider(ctx, providerId)) return true;
|
|
2543
|
+
try {
|
|
2544
|
+
const status = ctx.modelRegistry.getProviderAuthStatus(providerId);
|
|
2545
|
+
return moonshotProviderAuthSourceIsAllowed(ctx, providerId, status.source, status.label);
|
|
2546
|
+
} catch {
|
|
2547
|
+
return false;
|
|
2548
|
+
}
|
|
2549
|
+
}
|
|
2550
|
+
function moonshotProviderAuthSourceIsAllowed(ctx, providerId, source, label) {
|
|
2551
|
+
if (!isMoonshotSiblingProvider(ctx, providerId)) return true;
|
|
2552
|
+
if (source === void 0) return false;
|
|
2553
|
+
if (source !== "environment") return true;
|
|
2554
|
+
return label !== void 0 && !label.split(",").map((name) => name.trim()).includes(SHARED_MOONSHOT_ENV_VAR);
|
|
2555
|
+
}
|
|
2556
|
+
function isMoonshotSiblingProvider(ctx, providerId) {
|
|
2557
|
+
return (providerId === "moonshotai" || providerId === "moonshotai-cn") && ctx.model?.provider !== providerId;
|
|
2558
|
+
}
|
|
2559
|
+
function candidateModels(ctx, providerId) {
|
|
2560
|
+
const candidates = [];
|
|
2561
|
+
const seen = /* @__PURE__ */ new Set();
|
|
2562
|
+
const add = (model) => {
|
|
2563
|
+
if (!model || model.provider !== providerId) return;
|
|
2564
|
+
const key = `${model.provider}/${model.id}`;
|
|
2565
|
+
if (seen.has(key)) return;
|
|
2566
|
+
seen.add(key);
|
|
2567
|
+
candidates.push(model);
|
|
2568
|
+
};
|
|
2569
|
+
add(ctx.model);
|
|
2570
|
+
for (const model of ctx.modelRegistry.getAvailable()) add(model);
|
|
2571
|
+
for (const model of ctx.modelRegistry.getAll()) add(model);
|
|
2572
|
+
return candidates;
|
|
2573
|
+
}
|
|
2574
|
+
async function fetchProviderJson(url, auth, signal, timeoutMs, description, request = {}) {
|
|
2575
|
+
const controller = new AbortController();
|
|
2576
|
+
let timedOut = false;
|
|
2577
|
+
const abortFromCaller = () => controller.abort();
|
|
2578
|
+
if (signal.aborted) controller.abort();
|
|
2579
|
+
else signal.addEventListener("abort", abortFromCaller, { once: true });
|
|
2580
|
+
const timeout = setTimeout(() => {
|
|
2581
|
+
timedOut = true;
|
|
2582
|
+
controller.abort();
|
|
2583
|
+
}, timeoutMs);
|
|
2584
|
+
try {
|
|
2585
|
+
const headers = { ...auth.headers };
|
|
2586
|
+
if (request.userAgent !== false && !hasHeader(headers, "User-Agent")) {
|
|
2587
|
+
headers["User-Agent"] = "pi-usage";
|
|
2588
|
+
}
|
|
2589
|
+
if (request.body && !hasHeader(headers, "Content-Type")) {
|
|
2590
|
+
headers["Content-Type"] = "application/json";
|
|
2591
|
+
}
|
|
2592
|
+
const response = await fetch(url, {
|
|
2593
|
+
method: request.method ?? "GET",
|
|
2594
|
+
headers,
|
|
2595
|
+
...request.body ? { body: JSON.stringify(request.body) } : {},
|
|
2596
|
+
...request.redirect ? { redirect: request.redirect } : {},
|
|
2597
|
+
signal: controller.signal
|
|
2598
|
+
});
|
|
2599
|
+
if (response.redirected) throw new Error(`${description} refused a redirected response.`);
|
|
2600
|
+
if (controller.signal.aborted) throw Object.assign(new Error("Usage query aborted."), { name: "AbortError" });
|
|
2601
|
+
const text = await readBoundedResponse(
|
|
2602
|
+
response,
|
|
2603
|
+
response.ok ? MAX_SUCCESS_BODY_BYTES : MAX_ERROR_BODY_BYTES,
|
|
2604
|
+
!response.ok,
|
|
2605
|
+
description,
|
|
2606
|
+
controller.signal
|
|
2607
|
+
);
|
|
2608
|
+
if (controller.signal.aborted) throw Object.assign(new Error("Usage query aborted."), { name: "AbortError" });
|
|
2609
|
+
const responseError = request.responseError?.(response.status, text);
|
|
2610
|
+
if (responseError) throw new Error(responseError);
|
|
2611
|
+
if (!response.ok) {
|
|
2612
|
+
throw new Error(
|
|
2613
|
+
`${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`
|
|
2614
|
+
);
|
|
2615
|
+
}
|
|
2616
|
+
let parsed;
|
|
2617
|
+
try {
|
|
2618
|
+
parsed = JSON.parse(text);
|
|
2619
|
+
} catch (error) {
|
|
2620
|
+
throw new Error(`${description} returned invalid JSON: ${errorMessage(error)}`);
|
|
2621
|
+
}
|
|
2622
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
2623
|
+
throw new Error(`${description} response was not an object.`);
|
|
2624
|
+
}
|
|
2625
|
+
return parsed;
|
|
2626
|
+
} catch (error) {
|
|
2627
|
+
if (timedOut) {
|
|
2628
|
+
throw new Error(`Timed out after ${Math.round(timeoutMs / 1e3)}s while fetching usage.`);
|
|
2629
|
+
}
|
|
2630
|
+
if (signal.aborted) throw Object.assign(new Error("Usage query aborted."), { name: "AbortError" });
|
|
2631
|
+
throw error;
|
|
2632
|
+
} finally {
|
|
2633
|
+
clearTimeout(timeout);
|
|
2634
|
+
signal.removeEventListener("abort", abortFromCaller);
|
|
2635
|
+
}
|
|
2636
|
+
}
|
|
2637
|
+
async function readBoundedResponse(response, maxBytes, truncateOverflow, description, signal) {
|
|
2638
|
+
if (!response.body) return "";
|
|
2639
|
+
const reader = response.body.getReader();
|
|
2640
|
+
const chunks = [];
|
|
2641
|
+
let total = 0;
|
|
2642
|
+
let truncated = false;
|
|
2643
|
+
const abort = () => void reader.cancel().catch(() => void 0);
|
|
2644
|
+
if (signal.aborted) abort();
|
|
2645
|
+
else signal.addEventListener("abort", abort, { once: true });
|
|
2646
|
+
try {
|
|
2647
|
+
while (true) {
|
|
2648
|
+
const { done, value } = await reader.read();
|
|
2649
|
+
if (done) break;
|
|
2650
|
+
const remaining = maxBytes - total;
|
|
2651
|
+
if (value.byteLength > remaining) {
|
|
2652
|
+
if (remaining > 0) chunks.push(value.subarray(0, remaining));
|
|
2653
|
+
total = maxBytes;
|
|
2654
|
+
truncated = true;
|
|
2655
|
+
await reader.cancel();
|
|
2656
|
+
break;
|
|
2657
|
+
}
|
|
2658
|
+
chunks.push(value);
|
|
2659
|
+
total += value.byteLength;
|
|
2660
|
+
}
|
|
2661
|
+
} finally {
|
|
2662
|
+
signal.removeEventListener("abort", abort);
|
|
2663
|
+
reader.releaseLock();
|
|
2664
|
+
}
|
|
2665
|
+
if (truncated && !truncateOverflow) {
|
|
2666
|
+
throw new Error(`${description} response exceeded ${maxBytes} bytes.`);
|
|
2667
|
+
}
|
|
2668
|
+
const body = new Uint8Array(total);
|
|
2669
|
+
let offset = 0;
|
|
2670
|
+
for (const chunk of chunks) {
|
|
2671
|
+
body.set(chunk, offset);
|
|
2672
|
+
offset += chunk.byteLength;
|
|
2673
|
+
}
|
|
2674
|
+
const text = new TextDecoder().decode(body);
|
|
2675
|
+
return truncated ? `${text}\u2026` : text;
|
|
2676
|
+
}
|
|
2677
|
+
function resolveXaiUsageAuth(auth, model, salt, candidates) {
|
|
2678
|
+
const resolvedAccess = bearerToken(headerValue(auth.headers, "Authorization")) ?? auth.apiKey;
|
|
2679
|
+
if (!resolvedAccess) throw new Error("xAI runtime authentication was incomplete.");
|
|
2680
|
+
let sawOAuth = false;
|
|
2681
|
+
let sawMatchingAccess = false;
|
|
2682
|
+
let sawIncompleteMatch = false;
|
|
2683
|
+
const matches = [];
|
|
2684
|
+
for (const candidate of candidates) {
|
|
2685
|
+
try {
|
|
2686
|
+
const credential = asObject13(candidate);
|
|
2687
|
+
if (credential?.type !== "oauth") continue;
|
|
2688
|
+
sawOAuth = true;
|
|
2689
|
+
if (credential.access !== resolvedAccess) continue;
|
|
2690
|
+
sawMatchingAccess = true;
|
|
2691
|
+
if (typeof credential.access !== "string" || !credential.access || typeof credential.refresh !== "string" || !credential.refresh || typeof credential.expires !== "number" || !Number.isFinite(credential.expires)) {
|
|
2692
|
+
sawIncompleteMatch = true;
|
|
2693
|
+
continue;
|
|
2694
|
+
}
|
|
2695
|
+
matches.push({ access: credential.access, refresh: credential.refresh });
|
|
2696
|
+
} catch {
|
|
2697
|
+
}
|
|
2698
|
+
}
|
|
2699
|
+
if (sawIncompleteMatch) throw new Error("The matching xAI OAuth credential was incomplete.");
|
|
2700
|
+
if (matches.length > 1) {
|
|
2701
|
+
throw new Error("Multiple OAuth credentials match the active xAI runtime account.");
|
|
2702
|
+
}
|
|
2703
|
+
const match = matches[0];
|
|
2704
|
+
if (!match) {
|
|
2705
|
+
if (!sawOAuth) {
|
|
2706
|
+
throw new Error(
|
|
2707
|
+
"xAI consumer usage requires the OAuth subscription account configured through Pi /login; XAI_API_KEY users can review API spend at console.x.ai."
|
|
2708
|
+
);
|
|
2709
|
+
}
|
|
2710
|
+
if (sawMatchingAccess) throw new Error("The matching xAI OAuth credential was incomplete.");
|
|
2711
|
+
throw new Error("The active xAI runtime account does not match Pi's stored OAuth account.");
|
|
2712
|
+
}
|
|
2713
|
+
const authorization = `Bearer ${match.access}`;
|
|
2714
|
+
const headers = { Authorization: authorization };
|
|
2715
|
+
return {
|
|
2716
|
+
apiKey: match.access,
|
|
2717
|
+
headers,
|
|
2718
|
+
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
|
2719
|
+
secrets: [
|
|
2720
|
+
match.access,
|
|
2721
|
+
match.refresh,
|
|
2722
|
+
resolvedAccess,
|
|
2723
|
+
auth.apiKey,
|
|
2724
|
+
headerValue(auth.headers, "Authorization"),
|
|
2725
|
+
authorization
|
|
2726
|
+
].filter((value) => Boolean(value)),
|
|
2727
|
+
model
|
|
2728
|
+
};
|
|
2729
|
+
}
|
|
2730
|
+
function resolveGitHubCopilotUsageAuth(auth, model, salt, candidates, standaloneFallback) {
|
|
2731
|
+
const resolvedAccess = bearerToken(headerValue(auth.headers, "Authorization")) ?? auth.apiKey;
|
|
2732
|
+
if (!resolvedAccess) throw new Error("GitHub Copilot OAuth credentials were incomplete.");
|
|
2733
|
+
let sawOAuth = false;
|
|
2734
|
+
let sawMatchingAccess = false;
|
|
2735
|
+
let sawIncompleteMatch = false;
|
|
2736
|
+
let sawEnterpriseMatch = false;
|
|
2737
|
+
const matches = /* @__PURE__ */ new Map();
|
|
2738
|
+
for (const candidate of candidates) {
|
|
2739
|
+
try {
|
|
2740
|
+
const credential = asObject13(candidate);
|
|
2741
|
+
if (credential?.type !== "oauth") continue;
|
|
2742
|
+
sawOAuth = true;
|
|
2743
|
+
const storedAccess2 = typeof credential.access === "string" && credential.access ? credential.access : void 0;
|
|
2744
|
+
if (storedAccess2 !== resolvedAccess) continue;
|
|
2745
|
+
sawMatchingAccess = true;
|
|
2746
|
+
const enterpriseUrl = credential.enterpriseUrl;
|
|
2747
|
+
if (typeof enterpriseUrl === "string" && enterpriseUrl && !isPublicGitHubDomain(enterpriseUrl)) {
|
|
2748
|
+
sawEnterpriseMatch = true;
|
|
2749
|
+
continue;
|
|
2750
|
+
}
|
|
2751
|
+
const refresh2 = typeof credential.refresh === "string" && credential.refresh ? credential.refresh : void 0;
|
|
2752
|
+
if (!refresh2) {
|
|
2753
|
+
sawIncompleteMatch = true;
|
|
2754
|
+
continue;
|
|
2755
|
+
}
|
|
2756
|
+
matches.set(`${storedAccess2.length}:${storedAccess2}${refresh2}`, { refresh: refresh2, storedAccess: storedAccess2 });
|
|
2757
|
+
} catch {
|
|
2758
|
+
}
|
|
2759
|
+
}
|
|
2760
|
+
if (sawEnterpriseMatch) {
|
|
2761
|
+
throw new Error("GitHub Copilot usage does not yet support GitHub Enterprise accounts.");
|
|
2762
|
+
}
|
|
2763
|
+
if (sawIncompleteMatch) throw new Error("GitHub Copilot OAuth credentials were incomplete.");
|
|
2764
|
+
if (matches.size > 1) {
|
|
2765
|
+
throw new Error("Conflicting OAuth credentials match the active GitHub Copilot runtime account.");
|
|
2766
|
+
}
|
|
2767
|
+
const match = matches.values().next().value;
|
|
2768
|
+
if (!match) {
|
|
2769
|
+
if (!sawOAuth) {
|
|
2770
|
+
throw new Error(
|
|
2771
|
+
standaloneFallback ? "GitHub Copilot usage requires the OAuth account configured through Pi /login." : "GitHub Copilot usage requires an OAuth account configured through Pi /login or a compatible credential source."
|
|
2772
|
+
);
|
|
2773
|
+
}
|
|
2774
|
+
if (sawMatchingAccess) throw new Error("GitHub Copilot OAuth credentials were incomplete.");
|
|
2775
|
+
throw new Error(
|
|
2776
|
+
standaloneFallback ? "The active GitHub Copilot runtime account does not match Pi's stored OAuth account." : "The active GitHub Copilot runtime account does not match any available OAuth account."
|
|
2777
|
+
);
|
|
2778
|
+
}
|
|
2779
|
+
const { refresh, storedAccess } = match;
|
|
2780
|
+
const authorization = `Bearer ${refresh}`;
|
|
2781
|
+
const headers = {
|
|
2782
|
+
Authorization: authorization,
|
|
2783
|
+
"X-GitHub-Api-Version": "2025-05-01"
|
|
2784
|
+
};
|
|
2785
|
+
return {
|
|
2786
|
+
apiKey: refresh,
|
|
2787
|
+
headers,
|
|
2788
|
+
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
|
2789
|
+
secrets: [refresh, storedAccess, resolvedAccess, authorization],
|
|
2790
|
+
model
|
|
2791
|
+
};
|
|
2792
|
+
}
|
|
2793
|
+
function authorizationFrom(auth) {
|
|
2794
|
+
return headerValue(auth.headers, "Authorization") ?? (auth.apiKey ? `Bearer ${auth.apiKey}` : void 0);
|
|
2795
|
+
}
|
|
2796
|
+
function bearerToken(authorization) {
|
|
2797
|
+
const match = /^Bearer\s+(.+)$/iu.exec(authorization ?? "");
|
|
2798
|
+
return match?.[1];
|
|
2799
|
+
}
|
|
2800
|
+
function asObject13(value) {
|
|
2801
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return void 0;
|
|
2802
|
+
return value;
|
|
2803
|
+
}
|
|
2804
|
+
function isPublicGitHubDomain(value) {
|
|
2805
|
+
try {
|
|
2806
|
+
const url = new URL(value.includes("://") ? value : `https://${value}`);
|
|
2807
|
+
return url.hostname.toLowerCase() === "github.com";
|
|
2808
|
+
} catch {
|
|
2809
|
+
return false;
|
|
2810
|
+
}
|
|
2811
|
+
}
|
|
2812
|
+
function hasOfficialOrigin(model, providerId) {
|
|
2813
|
+
return hasOfficialUrlOrigin(model.baseUrl, providerId);
|
|
2814
|
+
}
|
|
2815
|
+
function hasOfficialUrlOrigin(value, providerId) {
|
|
2816
|
+
try {
|
|
2817
|
+
const url = new URL(value);
|
|
2818
|
+
if (providerId === "baseten") {
|
|
2819
|
+
return ["https://inference.baseten.co", "https://api.baseten.co"].includes(url.origin);
|
|
2820
|
+
}
|
|
2821
|
+
if (providerId === "openai") return url.origin === "https://api.openai.com";
|
|
2822
|
+
if (providerId === "openai-codex") return url.origin === "https://chatgpt.com";
|
|
2823
|
+
if (providerId === "deepseek") return url.origin === "https://api.deepseek.com";
|
|
2824
|
+
if (providerId === "fireworks") return url.origin === "https://api.fireworks.ai";
|
|
2825
|
+
if (providerId === "openrouter") return url.origin === "https://openrouter.ai";
|
|
2826
|
+
if (providerId === "vercel-ai-gateway") return url.origin === "https://ai-gateway.vercel.sh";
|
|
2827
|
+
if (providerId === "opencode-go") return url.origin === "https://opencode.ai";
|
|
2828
|
+
if (providerId === "kimi-coding") return url.origin === "https://api.kimi.com";
|
|
2829
|
+
if (providerId === "minimax") return url.origin === "https://api.minimax.io";
|
|
2830
|
+
if (providerId === "minimax-cn") return url.origin === "https://api.minimaxi.com";
|
|
2831
|
+
if (providerId === "moonshotai") return url.origin === "https://api.moonshot.ai";
|
|
2832
|
+
if (providerId === "moonshotai-cn") return url.origin === "https://api.moonshot.cn";
|
|
2833
|
+
if (providerId === "xai") return url.origin === "https://api.x.ai";
|
|
2834
|
+
if (providerId === "zai") return url.origin === "https://api.z.ai";
|
|
2835
|
+
if (providerId === "zai-coding-cn") return url.origin === "https://open.bigmodel.cn";
|
|
2836
|
+
if (providerId === "github-copilot") {
|
|
2837
|
+
return url.protocol === "https:" && /^api\.[a-z0-9-]+\.githubcopilot\.com$/u.test(url.hostname);
|
|
2838
|
+
}
|
|
2839
|
+
return false;
|
|
2840
|
+
} catch {
|
|
2841
|
+
return false;
|
|
2842
|
+
}
|
|
2843
|
+
}
|
|
2844
|
+
function headerValue(headers, name) {
|
|
2845
|
+
const entry = Object.entries(headers ?? {}).find(([candidate]) => candidate.toLowerCase() === name.toLowerCase());
|
|
2846
|
+
return entry?.[1] ?? void 0;
|
|
2847
|
+
}
|
|
2848
|
+
function hasHeader(headers, name) {
|
|
2849
|
+
return Object.keys(headers).some((key) => key.toLowerCase() === name.toLowerCase());
|
|
2850
|
+
}
|
|
2851
|
+
function validatedXaiUserId(value) {
|
|
2852
|
+
if (typeof value !== "string" || !/^[A-Za-z0-9._~-]{1,128}$/u.test(value)) {
|
|
2853
|
+
throw new Error("xAI consumer identity returned an unsafe canonical user ID.");
|
|
2854
|
+
}
|
|
2855
|
+
return value;
|
|
2856
|
+
}
|
|
2857
|
+
function basetenBillingUsageUrl(windowAt) {
|
|
2858
|
+
const url = new URL(BASETEN_BILLING_USAGE_URL);
|
|
2859
|
+
url.searchParams.set(
|
|
2860
|
+
"start_date",
|
|
2861
|
+
new Date(windowAt - BASETEN_USAGE_WINDOW_DAYS * 24 * 60 * 60 * 1e3).toISOString()
|
|
2862
|
+
);
|
|
2863
|
+
url.searchParams.set("end_date", new Date(windowAt).toISOString());
|
|
2864
|
+
return url.toString();
|
|
2865
|
+
}
|
|
2866
|
+
async function queryMiniMaxUsage(providerId, auth, signal, timeoutMs, guard) {
|
|
2867
|
+
if (!guard) throw new Error("MiniMax usage requires request-boundary revalidation.");
|
|
2868
|
+
const apiKey = bearerToken(headerValue(auth.headers, "Authorization")) ?? auth.apiKey;
|
|
2869
|
+
if (!apiKey) throw new Error("MiniMax runtime API key was unavailable.");
|
|
2870
|
+
const kind = miniMaxUsageKind(apiKey);
|
|
2871
|
+
const path = kind === "account-balance" ? "/account/query_balance" : "/v1/token_plan/remains";
|
|
2872
|
+
const startedAt = Date.now();
|
|
2873
|
+
await guard();
|
|
2874
|
+
const payload = await fetchProviderJson(
|
|
2875
|
+
`${MINIMAX_API_ROOTS[providerId]}${path}`,
|
|
2876
|
+
auth,
|
|
2877
|
+
signal,
|
|
2878
|
+
remainingTimeout2(timeoutMs, startedAt, "fetching MiniMax usage"),
|
|
2879
|
+
"MiniMax usage endpoint",
|
|
2880
|
+
{ redirect: "error" }
|
|
2881
|
+
);
|
|
2882
|
+
await guard();
|
|
2883
|
+
return normalizeMiniMaxUsagePayload(providerId, kind, payload, Date.now());
|
|
2884
|
+
}
|
|
2885
|
+
async function queryMoonshotBalance(providerId, auth, signal, timeoutMs, guard) {
|
|
2886
|
+
if (!guard) throw new Error("Moonshot AI balance requires request-boundary revalidation.");
|
|
2887
|
+
const startedAt = Date.now();
|
|
2888
|
+
await guard();
|
|
2889
|
+
const payload = await fetchProviderJson(
|
|
2890
|
+
MOONSHOT_BALANCE_URLS[providerId],
|
|
2891
|
+
auth,
|
|
2892
|
+
signal,
|
|
2893
|
+
remainingTimeout2(timeoutMs, startedAt, "fetching Moonshot AI balance"),
|
|
2894
|
+
"Moonshot AI balance endpoint",
|
|
2895
|
+
{ redirect: "error" }
|
|
2896
|
+
);
|
|
2897
|
+
await guard();
|
|
2898
|
+
return normalizeMoonshotBalancePayload(providerId, payload, Date.now());
|
|
2899
|
+
}
|
|
2900
|
+
function remainingTimeout2(timeoutMs, startedAt, description = "fetching xAI consumer usage") {
|
|
2901
|
+
const remaining = timeoutMs - (Date.now() - startedAt);
|
|
2902
|
+
if (remaining <= 0) throw new Error(`Timed out while ${description}.`);
|
|
2903
|
+
return remaining;
|
|
2904
|
+
}
|
|
2905
|
+
function zaiOrigin(baseUrl) {
|
|
2906
|
+
const base = baseUrl?.trim();
|
|
2907
|
+
if (!base) throw new Error("Z.AI model base URL is unavailable.");
|
|
2908
|
+
return new URL(base).origin;
|
|
2909
|
+
}
|
|
2910
|
+
function zaiMonitorUrl(baseUrl) {
|
|
2911
|
+
return `${zaiOrigin(baseUrl)}/api/monitor/usage/quota/limit`;
|
|
2912
|
+
}
|
|
2913
|
+
function zaiMonitorAuth(auth) {
|
|
2914
|
+
const authorization = headerValue(auth.headers, "Authorization");
|
|
2915
|
+
const token = authorization === void 0 ? void 0 : bearerToken(authorization) ?? authorization;
|
|
2916
|
+
if (token === void 0 || token === authorization) return auth;
|
|
2917
|
+
return { ...auth, headers: { ...auth.headers, Authorization: token } };
|
|
2918
|
+
}
|
|
2919
|
+
async function queryZaiUsage(providerId, providerName, auth, signal, timeoutMs, guard) {
|
|
2920
|
+
if (!guard) throw new Error("Z.AI usage requires request-boundary revalidation.");
|
|
2921
|
+
const startedAt = Date.now();
|
|
2922
|
+
await guard();
|
|
2923
|
+
const payload = await fetchProviderJson(
|
|
2924
|
+
zaiMonitorUrl(auth.model.baseUrl),
|
|
2925
|
+
zaiMonitorAuth(auth),
|
|
2926
|
+
signal,
|
|
2927
|
+
remainingTimeout2(timeoutMs, startedAt, `fetching ${providerName} quota`),
|
|
2928
|
+
`${providerName} quota endpoint`,
|
|
2929
|
+
{ responseError: zaiResponseError }
|
|
2930
|
+
);
|
|
2931
|
+
await guard();
|
|
2932
|
+
const planTimeoutMs = timeoutMs - (Date.now() - startedAt);
|
|
2933
|
+
const plan = await fetchZaiPlan(providerName, auth, signal, planTimeoutMs);
|
|
2934
|
+
return normalizeZaiQuotaPayload(providerId, providerName, payload, Date.now(), plan);
|
|
2935
|
+
}
|
|
2936
|
+
async function fetchZaiPlan(providerName, auth, signal, timeoutMs) {
|
|
2937
|
+
if (timeoutMs <= 0 || signal.aborted) return void 0;
|
|
2938
|
+
try {
|
|
2939
|
+
const payload = await fetchProviderJson(
|
|
2940
|
+
`${zaiOrigin(auth.model.baseUrl)}/api/biz/subscription/list`,
|
|
2941
|
+
zaiMonitorAuth(auth),
|
|
2942
|
+
signal,
|
|
2943
|
+
timeoutMs,
|
|
2944
|
+
`${providerName} plan endpoint`,
|
|
2945
|
+
{ responseError: zaiResponseError }
|
|
2946
|
+
);
|
|
2947
|
+
return normalizeZaiSubscriptionPayload(payload);
|
|
2948
|
+
} catch (error) {
|
|
2949
|
+
if (isAbortError(error)) throw error;
|
|
2950
|
+
return void 0;
|
|
2951
|
+
}
|
|
2952
|
+
}
|
|
2953
|
+
function isAbortError(error) {
|
|
2954
|
+
return error instanceof Error && error.name === "AbortError";
|
|
2955
|
+
}
|
|
2956
|
+
|
|
2957
|
+
export {
|
|
2958
|
+
UsageCache,
|
|
2959
|
+
fingerprintResolvedAuth,
|
|
2960
|
+
runWithConcurrency,
|
|
2961
|
+
awaitWithDeadline,
|
|
2962
|
+
sanitizeDisplayText,
|
|
2963
|
+
redactUsageError,
|
|
2964
|
+
errorMessage,
|
|
2965
|
+
abortError,
|
|
2966
|
+
createOAuthCredentialCandidateReader,
|
|
2967
|
+
fallbackOAuthCredentialCandidates,
|
|
2968
|
+
normalizeBasetenBillingUsagePayload,
|
|
2969
|
+
normalizeCodexBackendPayload,
|
|
2970
|
+
normalizeDeepSeekBalancePayload,
|
|
2971
|
+
isFireworksAccountId,
|
|
2972
|
+
normalizeFireworksAccountsPayload,
|
|
2973
|
+
createFireworksAdapter,
|
|
2974
|
+
normalizeFireworksBillingSummaryPayload,
|
|
2975
|
+
normalizeGitHubCopilotUsagePayload,
|
|
2976
|
+
normalizeKimiCodingUsagePayload,
|
|
2977
|
+
miniMaxUsageKind,
|
|
2978
|
+
normalizeMiniMaxUsagePayload,
|
|
2979
|
+
normalizeMoonshotBalancePayload,
|
|
2980
|
+
CHATGPT_USAGE_SETTINGS_URL,
|
|
2981
|
+
UnsupportedOpenAIUsageAuthError,
|
|
2982
|
+
openAIAuthAccessToken,
|
|
2983
|
+
normalizeOpenCodeZenPayload,
|
|
2984
|
+
normalizeOpenRouterKeyPayload,
|
|
2985
|
+
normalizeVercelAIGatewayCreditsPayload,
|
|
2986
|
+
normalizeXaiBillingPayload,
|
|
2987
|
+
normalizeZaiQuotaPayload,
|
|
2988
|
+
normalizeZaiSubscriptionPayload,
|
|
2989
|
+
resolveUsageTarget,
|
|
2990
|
+
listUsageTargets,
|
|
2991
|
+
normalizeUsageTargets,
|
|
2992
|
+
createUsageTargetSelectOptions,
|
|
2993
|
+
isBoundedTargetId,
|
|
2994
|
+
AUTH_FINGERPRINT_SALT,
|
|
2995
|
+
SUPPORTED_ADAPTERS,
|
|
2996
|
+
XAI_ADAPTER,
|
|
2997
|
+
usageAdapters,
|
|
2998
|
+
adapterForProvider,
|
|
2999
|
+
isStaleExtensionContextError,
|
|
3000
|
+
resolveUsageAuth,
|
|
3001
|
+
queryProviderUsage,
|
|
3002
|
+
providerIsConfigured,
|
|
3003
|
+
fetchProviderJson
|
|
3004
|
+
};
|
|
3005
|
+
//# sourceMappingURL=chunk-WEXCFYZX.ts.map
|