@fenlyin/pi-subscription-usage 0.0.0-stage → 2.0.1

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/src/query.ts ADDED
@@ -0,0 +1,511 @@
1
+ // Runtime-auth and origin checks adapted from @narumitw/pi-usage@0.53.0 (MIT).
2
+ import { randomBytes } from "node:crypto";
3
+ import { createRequire } from "node:module";
4
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
5
+ import {
6
+ errorMessage,
7
+ fingerprintResolvedAuth,
8
+ isAbortError,
9
+ redactUsageError,
10
+ } from "./core.ts";
11
+ import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
12
+ import {
13
+ codexAccountIdFromAccessToken,
14
+ normalizeCodexResetCreditsPayload,
15
+ } from "./codex-reset-core.ts";
16
+ import {
17
+ codexEmailFromAuthorization,
18
+ normalizeCodexUsage,
19
+ } from "./providers/codex.ts";
20
+ import {
21
+ grokRequestHeaders,
22
+ normalizeGrokBilling,
23
+ normalizeGrokIdentity,
24
+ requiresGrokMonthlyQuota,
25
+ shouldProbeGrokMonthly,
26
+ } from "./providers/grok.ts";
27
+ import { normalizeKimiUsage } from "./providers/kimi.ts";
28
+ import {
29
+ OPENAI_PROVIDER_ID,
30
+ normalizeOpenAIPlanUsage,
31
+ openaiClientIdFromAuthorization,
32
+ } from "./providers/openai.ts";
33
+ import { normalizeOpenCodeGoUsage } from "./providers/opencode-go.ts";
34
+ import type {
35
+ ResolvedUsageAuth,
36
+ UsageProviderAdapter,
37
+ UsageReport,
38
+ } from "./types.ts";
39
+
40
+ const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
41
+ const RESET_CREDITS_URL =
42
+ "https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
43
+ const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
44
+ const KIMI_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
45
+ const GROK_USER_URL = "https://cli-chat-proxy.grok.com/v1/user";
46
+ const GROK_CREDITS_URL =
47
+ "https://cli-chat-proxy.grok.com/v1/billing?format=credits";
48
+ const GROK_MONTHLY_URL = "https://cli-chat-proxy.grok.com/v1/billing";
49
+ const MAX_SUCCESS_BODY_BYTES = 64 * 1024;
50
+ const MAX_ERROR_BODY_BYTES = 4 * 1024;
51
+ const PACKAGE_METADATA = createRequire(import.meta.url)("../package.json") as {
52
+ name: string;
53
+ version: string;
54
+ };
55
+ const USER_AGENT = `${PACKAGE_METADATA.name}/${PACKAGE_METADATA.version}`;
56
+
57
+ type PiModel = NonNullable<ExtensionContext["model"]>;
58
+
59
+ export const AUTH_FINGERPRINT_SALT = randomBytes(32);
60
+
61
+ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
62
+ {
63
+ id: OPENAI_PROVIDER_ID,
64
+ displayName: "OpenAI (ChatGPT subscription)",
65
+ providerIds: [OPENAI_PROVIDER_ID],
66
+ officialOrigins: ["https://api.openai.com"],
67
+ requiresOAuth: true,
68
+ semantics: { kind: "consumer-subscription", label: "ChatGPT plan and app limits" },
69
+ async query(auth, signal, timeoutMs) {
70
+ if (!auth.openaiClientId) throw new Error("OpenAI application identity is unavailable.");
71
+ const [appPayload, planPayload] = await Promise.all([
72
+ fetchProviderJson(`${CODEX_USAGE_URL}/chatpass/apps`, auth, signal, timeoutMs, "OpenAI app usage endpoint"),
73
+ fetchProviderJson(CODEX_USAGE_URL, auth, signal, timeoutMs, "OpenAI plan usage endpoint"),
74
+ ]);
75
+ const report = normalizeOpenAIPlanUsage(appPayload, planPayload, auth.openaiClientId, Date.now());
76
+ const resetCount = await fetchRedeemableResetCount(auth, signal, timeoutMs);
77
+ if (resetCount === undefined) {
78
+ report.notes = ["Account reset availability could not be verified."];
79
+ } else {
80
+ report.metrics.push({ id: "reset-credits", label: "Account Resets", value: resetCount, unit: "count" });
81
+ }
82
+ return report;
83
+ },
84
+ },
85
+ {
86
+ id: CODEX_PROVIDER_ID,
87
+ displayName: "OpenAI Codex",
88
+ providerIds: [CODEX_PROVIDER_ID],
89
+ officialOrigins: ["https://chatgpt.com"],
90
+ semantics: {
91
+ kind: "consumer-subscription",
92
+ label: "ChatGPT subscription limits",
93
+ },
94
+ async query(auth, signal, timeoutMs) {
95
+ const [payload, resetCount] = await Promise.all([
96
+ fetchProviderJson(
97
+ CODEX_USAGE_URL,
98
+ auth,
99
+ signal,
100
+ timeoutMs,
101
+ "Codex usage endpoint",
102
+ ),
103
+ fetchRedeemableResetCount(auth, signal, timeoutMs),
104
+ ]);
105
+ // The usage summary also counts tickets the reset menu would refuse.
106
+ const report = normalizeCodexUsage(
107
+ {
108
+ ...payload,
109
+ rate_limit_reset_credits:
110
+ resetCount === undefined ? undefined : { available_count: resetCount },
111
+ },
112
+ Date.now(),
113
+ codexEmailFromAuthorization(auth.headers.Authorization),
114
+ );
115
+ if (resetCount === undefined) {
116
+ report.notes = ["Reset availability could not be verified."];
117
+ }
118
+ return report;
119
+ },
120
+ },
121
+ {
122
+ id: "opencode-go",
123
+ displayName: "OpenCode Go",
124
+ providerIds: ["opencode-go"],
125
+ officialOrigins: ["https://opencode.ai"],
126
+ semantics: { kind: "consumer-subscription", label: "OpenCode Go plan usage" },
127
+ async query(auth, signal, timeoutMs) {
128
+ return normalizeOpenCodeGoUsage(
129
+ await fetchProviderJson(
130
+ OPENCODE_GO_USAGE_URL,
131
+ auth,
132
+ signal,
133
+ timeoutMs,
134
+ "OpenCode Go usage endpoint",
135
+ ),
136
+ Date.now(),
137
+ );
138
+ },
139
+ },
140
+ {
141
+ id: "kimi-coding",
142
+ displayName: "Kimi Coding",
143
+ providerIds: ["kimi-coding"],
144
+ officialOrigins: ["https://api.kimi.com"],
145
+ semantics: { kind: "consumer-subscription", label: "Kimi Coding plan usage" },
146
+ async query(auth, signal, timeoutMs) {
147
+ return normalizeKimiUsage(
148
+ await fetchProviderJson(
149
+ KIMI_USAGE_URL,
150
+ auth,
151
+ signal,
152
+ timeoutMs,
153
+ "Kimi usage endpoint",
154
+ ),
155
+ Date.now(),
156
+ );
157
+ },
158
+ },
159
+ {
160
+ id: "xai",
161
+ displayName: "Grok",
162
+ providerIds: ["xai", "xai-auth"],
163
+ officialOrigins: ["https://api.x.ai", "https://cli-chat-proxy.grok.com"],
164
+ semantics: {
165
+ kind: "consumer-subscription",
166
+ label: "SuperGrok subscription usage",
167
+ },
168
+ requiresOAuth: true,
169
+ async query(auth, signal, timeoutMs) {
170
+ const identity = await fetchProviderJson(
171
+ GROK_USER_URL,
172
+ auth,
173
+ signal,
174
+ timeoutMs,
175
+ "Grok identity endpoint",
176
+ { headers: grokRequestHeaders() },
177
+ );
178
+ const userId = normalizeGrokIdentity(identity);
179
+ const request = { headers: grokRequestHeaders(userId) };
180
+ const credits = await fetchProviderJson(
181
+ GROK_CREDITS_URL,
182
+ auth,
183
+ signal,
184
+ timeoutMs,
185
+ "Grok billing endpoint",
186
+ request,
187
+ );
188
+ const capturedAt = Date.now();
189
+ const monthlyRequired = requiresGrokMonthlyQuota(credits);
190
+ let monthly: Record<string, unknown> | null | undefined;
191
+ if (shouldProbeGrokMonthly(credits)) {
192
+ try {
193
+ monthly = await fetchProviderJson(
194
+ GROK_MONTHLY_URL,
195
+ auth,
196
+ signal,
197
+ timeoutMs,
198
+ "Grok monthly billing endpoint",
199
+ request,
200
+ );
201
+ } catch (error) {
202
+ if (isAbortError(error) || monthlyRequired) throw error;
203
+ monthly = null;
204
+ }
205
+ }
206
+ return normalizeGrokBilling(credits, capturedAt, monthly);
207
+ },
208
+ },
209
+ ];
210
+
211
+ export function adapterForProvider(
212
+ providerId: string | undefined,
213
+ ): UsageProviderAdapter | undefined {
214
+ return SUPPORTED_ADAPTERS.find((adapter) =>
215
+ providerId ? adapter.providerIds.includes(providerId) : false,
216
+ );
217
+ }
218
+
219
+ /** A configured provider mode that does not offer subscription usage. */
220
+ export class UsageUnsupportedError extends Error {
221
+ name = "UsageUnsupportedError";
222
+ }
223
+
224
+ export async function resolveUsageAuth(
225
+ ctx: ExtensionContext,
226
+ adapter: UsageProviderAdapter,
227
+ salt: Uint8Array = AUTH_FINGERPRINT_SALT,
228
+ ): Promise<ResolvedUsageAuth | undefined> {
229
+ const current = ctx.model;
230
+ const UnsupportedModeError = adapter.id === OPENAI_PROVIDER_ID
231
+ ? UsageUnsupportedError
232
+ : Error;
233
+ if (
234
+ current &&
235
+ adapter.providerIds.includes(current.provider) &&
236
+ !hasOfficialOrigin(current.baseUrl, adapter)
237
+ ) {
238
+ throw new UnsupportedModeError(
239
+ `${adapter.displayName} usage cannot send a custom provider credential to an official usage endpoint.`,
240
+ );
241
+ }
242
+ const candidates = candidateModels(ctx, adapter.providerIds).filter(
243
+ (candidate) => hasOfficialOrigin(candidate.baseUrl, adapter),
244
+ );
245
+ const currentModel =
246
+ current && adapter.providerIds.includes(current.provider)
247
+ ? current
248
+ : undefined;
249
+ const model =
250
+ currentModel ??
251
+ candidates.find(
252
+ (candidate) =>
253
+ !adapter.requiresOAuth || ctx.modelRegistry.isUsingOAuth(candidate),
254
+ );
255
+ if (!model) return undefined;
256
+ if (adapter.requiresOAuth && !ctx.modelRegistry.isUsingOAuth(model)) {
257
+ throw new UnsupportedModeError(
258
+ `${adapter.displayName} usage requires Pi OAuth; API-key auth is not accepted.`,
259
+ );
260
+ }
261
+ const result = await ctx.modelRegistry.getProviderAuth(model.provider);
262
+ if (!result) return undefined;
263
+ if (result.auth.baseUrl && !hasOfficialOrigin(result.auth.baseUrl, adapter)) {
264
+ throw new UnsupportedModeError(
265
+ `${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
266
+ );
267
+ }
268
+ const authorization =
269
+ headerValue(result.auth.headers, "Authorization") ??
270
+ (result.auth.apiKey ? `Bearer ${result.auth.apiKey}` : undefined);
271
+ if (!authorization) return undefined;
272
+ const headers = { Authorization: authorization };
273
+ const secrets = [
274
+ result.auth.apiKey,
275
+ headerValue(result.auth.headers, "Authorization"),
276
+ authorization,
277
+ ].filter((value): value is string => Boolean(value));
278
+ if (adapter.id === OPENAI_PROVIDER_ID) {
279
+ const clientId = openaiClientIdFromAuthorization(authorization);
280
+ const codexAdapter = adapterForProvider(CODEX_PROVIDER_ID)!;
281
+ const companion = await resolveUsageAuth(ctx, { ...codexAdapter, requiresOAuth: true }, salt);
282
+ if (!companion) {
283
+ // ChatGPT backend usage rejects these app tokens (401 rejected_by_access_enforcement).
284
+ throw new Error("OpenAI rejects Sign in with ChatGPT tokens for ChatGPT usage and reset data. Run /login openai-codex once with the same ChatGPT account/workspace; it is used only to read usage, so keep OpenAI as the active model. You can also check https://chatgpt.com/settings/usage.");
285
+ }
286
+ return {
287
+ actualProviderId: model.provider,
288
+ model,
289
+ openaiClientId: clientId,
290
+ // Only the backend credential is sent to ChatGPT. The active API token
291
+ // is used locally for registration matching and cache invalidation.
292
+ headers: companion.headers,
293
+ fingerprint: fingerprintResolvedAuth({ apiKey: authorization, headers: companion.headers }, salt),
294
+ secrets: [...secrets, ...companion.secrets, clientId],
295
+ };
296
+ }
297
+ return {
298
+ actualProviderId: model.provider,
299
+ apiKey: result.auth.apiKey,
300
+ headers,
301
+ fingerprint: fingerprintResolvedAuth({ headers }, salt),
302
+ secrets,
303
+ model,
304
+ };
305
+ }
306
+
307
+ /**
308
+ * Undefined means unverified: usage still displays, but no reset is offered.
309
+ * Scope the listing to the backend token's own account, as redemption does.
310
+ */
311
+ async function fetchRedeemableResetCount(
312
+ auth: ResolvedUsageAuth,
313
+ signal: AbortSignal,
314
+ timeoutMs: number,
315
+ ): Promise<number | undefined> {
316
+ const access = /^Bearer\s+(\S+)$/iu.exec(
317
+ headerValue(auth.headers, "Authorization") ?? "",
318
+ )?.[1];
319
+ const accountId = access ? codexAccountIdFromAccessToken(access) : undefined;
320
+ if (!accountId) return undefined;
321
+ try {
322
+ return normalizeCodexResetCreditsPayload(
323
+ await fetchProviderJson(
324
+ RESET_CREDITS_URL,
325
+ auth,
326
+ signal,
327
+ timeoutMs,
328
+ "Reset credits endpoint",
329
+ { headers: { "chatgpt-account-id": accountId } },
330
+ ),
331
+ ).availableCount;
332
+ } catch (error) {
333
+ if (isAbortError(error) || signal.aborted) throw error;
334
+ return undefined;
335
+ }
336
+ }
337
+
338
+ export async function queryProviderUsage(
339
+ adapter: UsageProviderAdapter,
340
+ auth: ResolvedUsageAuth,
341
+ signal: AbortSignal,
342
+ timeoutMs: number,
343
+ ): Promise<UsageReport> {
344
+ try {
345
+ return await adapter.query(auth, signal, timeoutMs);
346
+ } catch (error) {
347
+ if (error instanceof Error && error.name === "AbortError") throw error;
348
+ throw new Error(redactUsageError(errorMessage(error), auth.secrets));
349
+ }
350
+ }
351
+
352
+ export async function fetchProviderJson(
353
+ url: string,
354
+ auth: ResolvedUsageAuth,
355
+ signal: AbortSignal,
356
+ timeoutMs: number,
357
+ description: string,
358
+ request: {
359
+ method?: "GET" | "POST";
360
+ body?: Record<string, unknown>;
361
+ headers?: Record<string, string>;
362
+ } = {},
363
+ ): Promise<Record<string, unknown>> {
364
+ const controller = new AbortController();
365
+ let timedOut = false;
366
+ const abortFromCaller = () => controller.abort();
367
+ if (signal.aborted) controller.abort();
368
+ else signal.addEventListener("abort", abortFromCaller, { once: true });
369
+ const timeout = setTimeout(() => {
370
+ timedOut = true;
371
+ controller.abort();
372
+ }, timeoutMs);
373
+ try {
374
+ const headers: Record<string, string> = {
375
+ Accept: "application/json",
376
+ "User-Agent": USER_AGENT,
377
+ ...auth.headers,
378
+ ...request.headers,
379
+ };
380
+ if (request.body) headers["Content-Type"] = "application/json";
381
+ const response = await fetch(url, {
382
+ method: request.method ?? "GET",
383
+ headers,
384
+ redirect: "error",
385
+ ...(request.body ? { body: JSON.stringify(request.body) } : {}),
386
+ signal: controller.signal,
387
+ });
388
+ const text = await readBoundedResponse(
389
+ response,
390
+ response.ok ? MAX_SUCCESS_BODY_BYTES : MAX_ERROR_BODY_BYTES,
391
+ !response.ok,
392
+ description,
393
+ );
394
+ if (!response.ok) {
395
+ throw new Error(
396
+ `${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
397
+ );
398
+ }
399
+ let parsed: unknown;
400
+ try {
401
+ parsed = JSON.parse(text);
402
+ } catch (error) {
403
+ throw new Error(
404
+ `${description} returned invalid JSON: ${errorMessage(error)}`,
405
+ );
406
+ }
407
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
408
+ throw new Error(`${description} response was not an object.`);
409
+ }
410
+ return parsed as Record<string, unknown>;
411
+ } catch (error) {
412
+ if (timedOut) {
413
+ throw new Error(
414
+ `Timed out after ${Math.round(timeoutMs / 1_000)}s while fetching usage.`,
415
+ );
416
+ }
417
+ if (signal.aborted) {
418
+ throw Object.assign(new Error("Usage query aborted."), {
419
+ name: "AbortError",
420
+ });
421
+ }
422
+ throw error;
423
+ } finally {
424
+ clearTimeout(timeout);
425
+ signal.removeEventListener("abort", abortFromCaller);
426
+ }
427
+ }
428
+
429
+ async function readBoundedResponse(
430
+ response: Response,
431
+ maxBytes: number,
432
+ truncateOverflow: boolean,
433
+ description: string,
434
+ ): Promise<string> {
435
+ if (!response.body) return "";
436
+ const reader = response.body.getReader();
437
+ const chunks: Uint8Array[] = [];
438
+ let total = 0;
439
+ let truncated = false;
440
+ try {
441
+ while (true) {
442
+ const { done, value } = await reader.read();
443
+ if (done) break;
444
+ const remaining = maxBytes - total;
445
+ if (value.byteLength > remaining) {
446
+ if (remaining > 0) chunks.push(value.subarray(0, remaining));
447
+ total = maxBytes;
448
+ truncated = true;
449
+ await reader.cancel();
450
+ break;
451
+ }
452
+ chunks.push(value);
453
+ total += value.byteLength;
454
+ }
455
+ } finally {
456
+ reader.releaseLock();
457
+ }
458
+ if (truncated && !truncateOverflow) {
459
+ throw new Error(`${description} response exceeded ${maxBytes} bytes.`);
460
+ }
461
+ const body = new Uint8Array(total);
462
+ let offset = 0;
463
+ for (const chunk of chunks) {
464
+ body.set(chunk, offset);
465
+ offset += chunk.byteLength;
466
+ }
467
+ const text = new TextDecoder().decode(body);
468
+ return truncated ? `${text}…` : text;
469
+ }
470
+
471
+ function candidateModels(
472
+ ctx: ExtensionContext,
473
+ providerIds: readonly string[],
474
+ ): PiModel[] {
475
+ const candidates: PiModel[] = [];
476
+ const seen = new Set<string>();
477
+ const add = (model: PiModel | undefined) => {
478
+ if (!model || !providerIds.includes(model.provider)) return;
479
+ const key = `${model.provider}/${model.id}`;
480
+ if (seen.has(key)) return;
481
+ seen.add(key);
482
+ candidates.push(model);
483
+ };
484
+ add(ctx.model);
485
+ for (const model of ctx.modelRegistry.getAvailable()) add(model);
486
+ for (const model of ctx.modelRegistry.getAll()) add(model);
487
+ return candidates;
488
+ }
489
+
490
+ function hasOfficialOrigin(
491
+ value: string | undefined,
492
+ adapter: UsageProviderAdapter,
493
+ ): boolean {
494
+ if (!value) return false;
495
+ try {
496
+ return adapter.officialOrigins.includes(new URL(value).origin);
497
+ } catch {
498
+ return false;
499
+ }
500
+ }
501
+
502
+ function headerValue(
503
+ headers: Record<string, string | null> | undefined,
504
+ name: string,
505
+ ): string | undefined {
506
+ return (
507
+ Object.entries(headers ?? {}).find(
508
+ ([candidate]) => candidate.toLowerCase() === name.toLowerCase(),
509
+ )?.[1] ?? undefined
510
+ );
511
+ }