@specode/pi-subscription-usage 1.3.0 → 1.4.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 +83 -85
- package/README.zh-CN.md +85 -87
- package/package.json +4 -3
- package/src/codex-reset-core.ts +9 -17
- package/src/codex-resets.ts +6 -7
- package/src/providers/antigravity.ts +372 -0
- package/src/query.ts +203 -18
- package/src/types.ts +1 -0
- package/src/usage.ts +25 -25
|
@@ -0,0 +1,372 @@
|
|
|
1
|
+
import { sanitizeDisplayText } from "../core.ts";
|
|
2
|
+
import type { UsageBucket, UsageMetric, UsageReport } from "../types.ts";
|
|
3
|
+
|
|
4
|
+
export const ANTIGRAVITY_PROVIDER_ID = "antigravity";
|
|
5
|
+
export const ANTIGRAVITY_DEFAULT_ENDPOINT = "https://daily-cloudcode-pa.googleapis.com";
|
|
6
|
+
export const ANTIGRAVITY_OFFICIAL_ORIGINS = [
|
|
7
|
+
"https://daily-cloudcode-pa.googleapis.com",
|
|
8
|
+
"https://daily-cloudcode-pa.sandbox.googleapis.com",
|
|
9
|
+
"https://cloudcode-pa.googleapis.com",
|
|
10
|
+
] as const;
|
|
11
|
+
|
|
12
|
+
export const ANTIGRAVITY_DEFAULT_GROUP_ID = "gemini-models";
|
|
13
|
+
export const ANTIGRAVITY_3P_GROUP_ID = "claude-and-gpt-models";
|
|
14
|
+
export const ANTIGRAVITY_ARGON_GROUP_ID = "gemini-argon";
|
|
15
|
+
|
|
16
|
+
export const ANTIGRAVITY_USER_AGENT =
|
|
17
|
+
process.env.ANTIGRAVITY_USER_AGENT ||
|
|
18
|
+
process.env.NOAGY_USER_AGENT ||
|
|
19
|
+
"antigravity/cli/1.4.0 (aidev_client; os_type=linux; arch=amd64; cl=982146307; auth_method=consumer)";
|
|
20
|
+
|
|
21
|
+
export const ANTIGRAVITY_LOAD_CODE_ASSIST_BODY = {
|
|
22
|
+
metadata: {
|
|
23
|
+
ideType: "ANTIGRAVITY",
|
|
24
|
+
platform: "PLATFORM_UNSPECIFIED",
|
|
25
|
+
pluginType: "GEMINI",
|
|
26
|
+
},
|
|
27
|
+
} as const;
|
|
28
|
+
|
|
29
|
+
export function antigravityRequestHeaders(): Record<string, string> {
|
|
30
|
+
return {
|
|
31
|
+
"User-Agent": ANTIGRAVITY_USER_AGENT,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
const ANTIGRAVITY_RETRYABLE_STATUSES = new Set([
|
|
36
|
+
403, 404, 429, 500, 502, 503, 504,
|
|
37
|
+
]);
|
|
38
|
+
|
|
39
|
+
export function antigravityQueryOrigins(baseUrl: string | undefined): string[] {
|
|
40
|
+
const origins: string[] = [];
|
|
41
|
+
const add = (origin: string) => {
|
|
42
|
+
if (
|
|
43
|
+
ANTIGRAVITY_OFFICIAL_ORIGINS.includes(
|
|
44
|
+
origin as (typeof ANTIGRAVITY_OFFICIAL_ORIGINS)[number],
|
|
45
|
+
) &&
|
|
46
|
+
!origins.includes(origin)
|
|
47
|
+
) {
|
|
48
|
+
origins.push(origin);
|
|
49
|
+
}
|
|
50
|
+
};
|
|
51
|
+
if (baseUrl) {
|
|
52
|
+
try {
|
|
53
|
+
add(new URL(baseUrl).origin);
|
|
54
|
+
} catch {
|
|
55
|
+
// A malformed model URL falls through to the official list.
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
for (const origin of ANTIGRAVITY_OFFICIAL_ORIGINS) add(origin);
|
|
59
|
+
return origins;
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** HTTP failures carry `status`; network failures surface as fetch's TypeError. */
|
|
63
|
+
export function isRetryableAntigravityError(error: unknown): boolean {
|
|
64
|
+
if (error instanceof TypeError) return true;
|
|
65
|
+
const status = httpStatus(error);
|
|
66
|
+
return status !== undefined && ANTIGRAVITY_RETRYABLE_STATUSES.has(status);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Free-tier accounts cannot read the aggregate quota summary. */
|
|
70
|
+
export function isAntigravitySubscriptionRequired(error: unknown): boolean {
|
|
71
|
+
return (
|
|
72
|
+
httpStatus(error) === 403 &&
|
|
73
|
+
error instanceof Error &&
|
|
74
|
+
/SUBSCRIPTION_REQUIRED|(?:lack|missing)[^\n]*license/iu.test(error.message)
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function httpStatus(error: unknown): number | undefined {
|
|
79
|
+
const status = (error as { status?: unknown } | null)?.status;
|
|
80
|
+
return typeof status === "number" ? status : undefined;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function extractAntigravityAuth(
|
|
84
|
+
apiKey: string | undefined,
|
|
85
|
+
existingAuthHeader: string | undefined,
|
|
86
|
+
): { authorization?: string; token?: string; email?: string } {
|
|
87
|
+
const fromKey = apiKey ? parseCredentialMaterial(apiKey) : undefined;
|
|
88
|
+
const fromHeader =
|
|
89
|
+
!fromKey?.token && existingAuthHeader
|
|
90
|
+
? parseBearerCredential(existingAuthHeader)
|
|
91
|
+
: undefined;
|
|
92
|
+
const token = fromKey?.token ?? fromHeader?.token;
|
|
93
|
+
const email = fromKey?.email ?? fromHeader?.email;
|
|
94
|
+
if (!token) {
|
|
95
|
+
if (fromKey?.json || fromHeader?.json) return { email };
|
|
96
|
+
return { authorization: existingAuthHeader, email };
|
|
97
|
+
}
|
|
98
|
+
return { authorization: `Bearer ${token}`, token, email };
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
export function emailFromAntigravityCredential(
|
|
102
|
+
credential: unknown,
|
|
103
|
+
): string | undefined {
|
|
104
|
+
const record = asObject(credential);
|
|
105
|
+
if (record?.type !== "oauth") return undefined;
|
|
106
|
+
return asEmail(record.email);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function normalizeAntigravityUsage(
|
|
110
|
+
payload: unknown,
|
|
111
|
+
capturedAt: number,
|
|
112
|
+
planPayload?: unknown,
|
|
113
|
+
accountEmail?: string,
|
|
114
|
+
): UsageReport {
|
|
115
|
+
const root = asObject(payload);
|
|
116
|
+
if (!root || !Array.isArray(root.groups)) {
|
|
117
|
+
throw new Error("Antigravity usage response was not an object.");
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const buckets: UsageBucket[] = [];
|
|
121
|
+
for (const rawGroup of root.groups) {
|
|
122
|
+
const group = asObject(rawGroup);
|
|
123
|
+
if (!group) continue;
|
|
124
|
+
const classification = classifyGroup(group);
|
|
125
|
+
const rawBuckets = Array.isArray(group.buckets) ? group.buckets : [];
|
|
126
|
+
for (const rawBucket of rawBuckets) {
|
|
127
|
+
const b = asObject(rawBucket);
|
|
128
|
+
if (!b) continue;
|
|
129
|
+
const remainingFraction = asNumber(b.remainingFraction);
|
|
130
|
+
if (remainingFraction === undefined) continue;
|
|
131
|
+
|
|
132
|
+
const clampedFraction = Math.min(1, Math.max(0, remainingFraction));
|
|
133
|
+
const remaining = clampPercent(roundPercent(clampedFraction * 100));
|
|
134
|
+
const used = clampPercent(roundPercent(100 - remaining));
|
|
135
|
+
|
|
136
|
+
const bucketId =
|
|
137
|
+
asString(b.bucketId) || asString(b.displayName) || "bucket";
|
|
138
|
+
const windowMinutes = parseWindowMinutes(b.window, bucketId);
|
|
139
|
+
const resetsAt = asEpochSeconds(b.resetTime);
|
|
140
|
+
const label = asString(b.displayName) || "Limit";
|
|
141
|
+
|
|
142
|
+
buckets.push({
|
|
143
|
+
id: `${classification.groupId}:${bucketId}`,
|
|
144
|
+
label,
|
|
145
|
+
groupId: classification.groupId,
|
|
146
|
+
groupLabel: classification.groupLabel,
|
|
147
|
+
modelKeys: classification.modelKeys,
|
|
148
|
+
used,
|
|
149
|
+
remaining,
|
|
150
|
+
limit: 100,
|
|
151
|
+
unit: "percent",
|
|
152
|
+
...(windowMinutes !== undefined ? { windowMinutes } : {}),
|
|
153
|
+
...(resetsAt !== undefined ? { resetsAt } : {}),
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (buckets.length === 0) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
"Antigravity usage endpoint returned no displayable usage data.",
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
const metrics: UsageMetric[] = [];
|
|
165
|
+
const email = asEmail(accountEmail);
|
|
166
|
+
if (email) {
|
|
167
|
+
metrics.push({ id: "email", label: "Email", value: email });
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const plan = extractPlanName(planPayload);
|
|
171
|
+
if (plan) {
|
|
172
|
+
metrics.push({ id: "plan", label: "Plan", value: plan });
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
const project = extractProject(planPayload);
|
|
176
|
+
if (project) {
|
|
177
|
+
metrics.push({ id: "project", label: "Project", value: project });
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
const defaultGroupId = buckets.some(
|
|
181
|
+
(b) => b.groupId === ANTIGRAVITY_DEFAULT_GROUP_ID,
|
|
182
|
+
)
|
|
183
|
+
? ANTIGRAVITY_DEFAULT_GROUP_ID
|
|
184
|
+
: buckets[0]?.groupId;
|
|
185
|
+
|
|
186
|
+
return {
|
|
187
|
+
providerId: ANTIGRAVITY_PROVIDER_ID,
|
|
188
|
+
providerName: "Antigravity",
|
|
189
|
+
capturedAt,
|
|
190
|
+
source: "antigravity-quota",
|
|
191
|
+
semantics: {
|
|
192
|
+
kind: "consumer-subscription",
|
|
193
|
+
label: "Antigravity subscription limits",
|
|
194
|
+
},
|
|
195
|
+
defaultGroupId,
|
|
196
|
+
buckets,
|
|
197
|
+
metrics,
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function classifyGroup(group: Record<string, unknown>): {
|
|
202
|
+
groupId: string;
|
|
203
|
+
groupLabel: string;
|
|
204
|
+
modelKeys: string[];
|
|
205
|
+
} {
|
|
206
|
+
const displayName = asString(group.displayName) ?? "";
|
|
207
|
+
const rawBuckets = Array.isArray(group.buckets) ? group.buckets : [];
|
|
208
|
+
const bucketIds = rawBuckets
|
|
209
|
+
.map((b) => asString(asObject(b)?.bucketId)?.toLowerCase() ?? "")
|
|
210
|
+
.filter(Boolean);
|
|
211
|
+
|
|
212
|
+
if (bucketIds.some((id) => id.includes("argon"))) {
|
|
213
|
+
return {
|
|
214
|
+
groupId: ANTIGRAVITY_ARGON_GROUP_ID,
|
|
215
|
+
groupLabel: displayName || "Gemini 4 Argon",
|
|
216
|
+
modelKeys: ["argon", "gemini-4-argon"],
|
|
217
|
+
};
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
if (
|
|
221
|
+
bucketIds.some(
|
|
222
|
+
(id) => id.startsWith("3p") || id.includes("claude") || id.includes("gpt"),
|
|
223
|
+
)
|
|
224
|
+
) {
|
|
225
|
+
return {
|
|
226
|
+
groupId: ANTIGRAVITY_3P_GROUP_ID,
|
|
227
|
+
groupLabel: displayName || "Claude and GPT models",
|
|
228
|
+
modelKeys: ["claude", "gpt-oss"],
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
if (bucketIds.some((id) => id.includes("gemini"))) {
|
|
233
|
+
return {
|
|
234
|
+
groupId: ANTIGRAVITY_DEFAULT_GROUP_ID,
|
|
235
|
+
groupLabel: displayName || "Gemini Models",
|
|
236
|
+
modelKeys: ["gemini-flash", "gemini-pro", "gemini"],
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const fallbackSlug =
|
|
241
|
+
displayName
|
|
242
|
+
.toLowerCase()
|
|
243
|
+
.replace(/[^a-z0-9]+/gu, "-")
|
|
244
|
+
.replace(/^-+|-+$/gu, "") || "other";
|
|
245
|
+
|
|
246
|
+
return {
|
|
247
|
+
groupId: fallbackSlug,
|
|
248
|
+
groupLabel: displayName || "Other Models",
|
|
249
|
+
modelKeys: [fallbackSlug],
|
|
250
|
+
};
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function parseWindowMinutes(
|
|
254
|
+
windowValue: unknown,
|
|
255
|
+
bucketId: string,
|
|
256
|
+
): number | undefined {
|
|
257
|
+
const str = asString(windowValue)?.toLowerCase();
|
|
258
|
+
if (str === "weekly" || str === "1w" || str === "week") return 10_080;
|
|
259
|
+
if (str === "monthly" || str === "1m" || str === "month") return 43_200;
|
|
260
|
+
if (str === "5h") return 300;
|
|
261
|
+
if (str) {
|
|
262
|
+
const hourMatch = /^(\d+)\s*h$/iu.exec(str);
|
|
263
|
+
if (hourMatch) return Number.parseInt(hourMatch[1], 10) * 60;
|
|
264
|
+
const dayMatch = /^(\d+)\s*d$/iu.exec(str);
|
|
265
|
+
if (dayMatch) return Number.parseInt(dayMatch[1], 10) * 1_440;
|
|
266
|
+
const minMatch = /^(\d+)\s*m$/iu.exec(str);
|
|
267
|
+
if (minMatch) return Number.parseInt(minMatch[1], 10);
|
|
268
|
+
}
|
|
269
|
+
const id = bucketId.toLowerCase();
|
|
270
|
+
if (id.includes("5h")) return 300;
|
|
271
|
+
if (id.includes("weekly") || id.includes("1w")) return 10_080;
|
|
272
|
+
if (id.includes("monthly") || id.includes("1m")) return 43_200;
|
|
273
|
+
return undefined;
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function extractPlanName(planPayload: unknown): string | undefined {
|
|
277
|
+
const root = asObject(planPayload);
|
|
278
|
+
if (!root) return undefined;
|
|
279
|
+
const paidTier = asObject(root.paidTier);
|
|
280
|
+
const paidName = asString(paidTier?.name);
|
|
281
|
+
if (paidName) return paidName;
|
|
282
|
+
const currentTier = asObject(root.currentTier);
|
|
283
|
+
const currentName = asString(currentTier?.name);
|
|
284
|
+
if (currentName) return currentName;
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
function extractProject(planPayload: unknown): string | undefined {
|
|
289
|
+
const root = asObject(planPayload);
|
|
290
|
+
if (!root) return undefined;
|
|
291
|
+
return asString(root.cloudaicompanionProject);
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
function parseCredentialMaterial(value: string): {
|
|
295
|
+
token?: string;
|
|
296
|
+
email?: string;
|
|
297
|
+
json: boolean;
|
|
298
|
+
} {
|
|
299
|
+
const trimmed = value.trim();
|
|
300
|
+
const json = trimmed.startsWith("{") && trimmed.endsWith("}");
|
|
301
|
+
if (!json) return { token: trimmed || undefined, json: false };
|
|
302
|
+
try {
|
|
303
|
+
const parsed = JSON.parse(trimmed) as {
|
|
304
|
+
token?: unknown;
|
|
305
|
+
access?: unknown;
|
|
306
|
+
email?: unknown;
|
|
307
|
+
};
|
|
308
|
+
const token =
|
|
309
|
+
typeof parsed.token === "string" && parsed.token.trim()
|
|
310
|
+
? parsed.token.trim()
|
|
311
|
+
: typeof parsed.access === "string" && parsed.access.trim()
|
|
312
|
+
? parsed.access.trim()
|
|
313
|
+
: undefined;
|
|
314
|
+
const email =
|
|
315
|
+
typeof parsed.email === "string" && parsed.email.trim()
|
|
316
|
+
? parsed.email.trim()
|
|
317
|
+
: undefined;
|
|
318
|
+
return { token, email, json: true };
|
|
319
|
+
} catch {
|
|
320
|
+
return { json: true };
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function parseBearerCredential(header: string): {
|
|
325
|
+
token?: string;
|
|
326
|
+
email?: string;
|
|
327
|
+
json: boolean;
|
|
328
|
+
} | undefined {
|
|
329
|
+
const match = /^Bearer\s+(\S.*)$/iu.exec(header.trim());
|
|
330
|
+
return match ? parseCredentialMaterial(match[1]) : undefined;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
function asObject(value: unknown): Record<string, unknown> | undefined {
|
|
334
|
+
return value && typeof value === "object" && !Array.isArray(value)
|
|
335
|
+
? (value as Record<string, unknown>)
|
|
336
|
+
: undefined;
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
function asString(value: unknown): string | undefined {
|
|
340
|
+
return typeof value === "string"
|
|
341
|
+
? sanitizeDisplayText(value, 160) || undefined
|
|
342
|
+
: undefined;
|
|
343
|
+
}
|
|
344
|
+
|
|
345
|
+
function asNumber(value: unknown): number | undefined {
|
|
346
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
347
|
+
if (typeof value === "string" && value.trim()) {
|
|
348
|
+
const parsed = Number(value);
|
|
349
|
+
return Number.isFinite(parsed) ? parsed : undefined;
|
|
350
|
+
}
|
|
351
|
+
return undefined;
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function asEmail(value: unknown): string | undefined {
|
|
355
|
+
if (typeof value !== "string" || value.length > 254) return undefined;
|
|
356
|
+
const email = sanitizeDisplayText(value, 254).toLowerCase();
|
|
357
|
+
return /^[^\s@]+@[^\s@]+$/u.test(email) ? email : undefined;
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
function asEpochSeconds(value: unknown): number | undefined {
|
|
361
|
+
if (typeof value !== "string" || !value.trim()) return undefined;
|
|
362
|
+
const parsed = Date.parse(value);
|
|
363
|
+
return Number.isNaN(parsed) ? undefined : Math.floor(parsed / 1000);
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
function clampPercent(value: number): number {
|
|
367
|
+
return Math.min(100, Math.max(0, value));
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function roundPercent(value: number): number {
|
|
371
|
+
return Math.round(value * 1_000_000) / 1_000_000;
|
|
372
|
+
}
|
package/src/query.ts
CHANGED
|
@@ -9,7 +9,22 @@ import {
|
|
|
9
9
|
redactUsageError,
|
|
10
10
|
} from "./core.ts";
|
|
11
11
|
import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
|
|
12
|
-
import {
|
|
12
|
+
import {
|
|
13
|
+
ANTIGRAVITY_LOAD_CODE_ASSIST_BODY,
|
|
14
|
+
ANTIGRAVITY_OFFICIAL_ORIGINS,
|
|
15
|
+
ANTIGRAVITY_PROVIDER_ID,
|
|
16
|
+
antigravityQueryOrigins,
|
|
17
|
+
antigravityRequestHeaders,
|
|
18
|
+
emailFromAntigravityCredential,
|
|
19
|
+
extractAntigravityAuth,
|
|
20
|
+
isAntigravitySubscriptionRequired,
|
|
21
|
+
isRetryableAntigravityError,
|
|
22
|
+
normalizeAntigravityUsage,
|
|
23
|
+
} from "./providers/antigravity.ts";
|
|
24
|
+
import {
|
|
25
|
+
codexAccountIdFromAccessToken,
|
|
26
|
+
normalizeCodexResetCreditsPayload,
|
|
27
|
+
} from "./codex-reset-core.ts";
|
|
13
28
|
import {
|
|
14
29
|
codexEmailFromAuthorization,
|
|
15
30
|
normalizeCodexUsage,
|
|
@@ -35,6 +50,8 @@ import type {
|
|
|
35
50
|
} from "./types.ts";
|
|
36
51
|
|
|
37
52
|
const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage";
|
|
53
|
+
const RESET_CREDITS_URL =
|
|
54
|
+
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits";
|
|
38
55
|
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
39
56
|
const KIMI_USAGE_URL = "https://api.kimi.com/coding/v1/usages";
|
|
40
57
|
const GROK_USER_URL = "https://cli-chat-proxy.grok.com/v1/user";
|
|
@@ -68,15 +85,11 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
68
85
|
fetchProviderJson(CODEX_USAGE_URL, auth, signal, timeoutMs, "OpenAI plan usage endpoint"),
|
|
69
86
|
]);
|
|
70
87
|
const report = normalizeOpenAIPlanUsage(appPayload, planPayload, auth.openaiClientId, Date.now());
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
"https://chatgpt.com/backend-api/wham/rate-limit-reset-credits",
|
|
74
|
-
auth, signal, timeoutMs, "Account reset credits endpoint",
|
|
75
|
-
), { requireExplicitCredit: true });
|
|
76
|
-
report.metrics.push({ id: "reset-credits", label: "Account Resets", value: credits.availableCount, unit: "count" });
|
|
77
|
-
} catch (error) {
|
|
78
|
-
if (isAbortError(error) || signal.aborted) throw error;
|
|
88
|
+
const resetCount = await fetchRedeemableResetCount(auth, signal, timeoutMs);
|
|
89
|
+
if (resetCount === undefined) {
|
|
79
90
|
report.notes = ["Account reset availability could not be verified."];
|
|
91
|
+
} else {
|
|
92
|
+
report.metrics.push({ id: "reset-credits", label: "Account Resets", value: resetCount, unit: "count" });
|
|
80
93
|
}
|
|
81
94
|
return report;
|
|
82
95
|
},
|
|
@@ -91,17 +104,30 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
91
104
|
label: "ChatGPT subscription limits",
|
|
92
105
|
},
|
|
93
106
|
async query(auth, signal, timeoutMs) {
|
|
94
|
-
|
|
95
|
-
|
|
107
|
+
const [payload, resetCount] = await Promise.all([
|
|
108
|
+
fetchProviderJson(
|
|
96
109
|
CODEX_USAGE_URL,
|
|
97
110
|
auth,
|
|
98
111
|
signal,
|
|
99
112
|
timeoutMs,
|
|
100
113
|
"Codex usage endpoint",
|
|
101
114
|
),
|
|
115
|
+
fetchRedeemableResetCount(auth, signal, timeoutMs),
|
|
116
|
+
]);
|
|
117
|
+
// The usage summary also counts tickets the reset menu would refuse.
|
|
118
|
+
const report = normalizeCodexUsage(
|
|
119
|
+
{
|
|
120
|
+
...payload,
|
|
121
|
+
rate_limit_reset_credits:
|
|
122
|
+
resetCount === undefined ? undefined : { available_count: resetCount },
|
|
123
|
+
},
|
|
102
124
|
Date.now(),
|
|
103
125
|
codexEmailFromAuthorization(auth.headers.Authorization),
|
|
104
126
|
);
|
|
127
|
+
if (resetCount === undefined) {
|
|
128
|
+
report.notes = ["Reset availability could not be verified."];
|
|
129
|
+
}
|
|
130
|
+
return report;
|
|
105
131
|
},
|
|
106
132
|
},
|
|
107
133
|
{
|
|
@@ -192,8 +218,112 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
|
|
|
192
218
|
return normalizeGrokBilling(credits, capturedAt, monthly);
|
|
193
219
|
},
|
|
194
220
|
},
|
|
221
|
+
{
|
|
222
|
+
id: ANTIGRAVITY_PROVIDER_ID,
|
|
223
|
+
displayName: "Antigravity",
|
|
224
|
+
providerIds: [ANTIGRAVITY_PROVIDER_ID],
|
|
225
|
+
officialOrigins: ANTIGRAVITY_OFFICIAL_ORIGINS,
|
|
226
|
+
semantics: {
|
|
227
|
+
kind: "consumer-subscription",
|
|
228
|
+
label: "Antigravity subscription limits",
|
|
229
|
+
},
|
|
230
|
+
async query(auth, signal, timeoutMs) {
|
|
231
|
+
const origins = antigravityQueryOrigins(auth.model?.baseUrl);
|
|
232
|
+
// Plan metadata is optional; attach the handler now so a quota failure
|
|
233
|
+
// cannot leave this request as an unhandled rejection.
|
|
234
|
+
const plan = fetchAntigravityJson(
|
|
235
|
+
origins,
|
|
236
|
+
"/v1internal:loadCodeAssist",
|
|
237
|
+
auth,
|
|
238
|
+
signal,
|
|
239
|
+
timeoutMs,
|
|
240
|
+
"Antigravity code assist endpoint",
|
|
241
|
+
ANTIGRAVITY_LOAD_CODE_ASSIST_BODY,
|
|
242
|
+
).then(
|
|
243
|
+
(result) => result.payload,
|
|
244
|
+
() => undefined,
|
|
245
|
+
);
|
|
246
|
+
const quota = await fetchAntigravityJson(
|
|
247
|
+
origins,
|
|
248
|
+
"/v1internal:retrieveUserQuotaSummary",
|
|
249
|
+
auth,
|
|
250
|
+
signal,
|
|
251
|
+
timeoutMs,
|
|
252
|
+
"Antigravity quota endpoint",
|
|
253
|
+
{},
|
|
254
|
+
);
|
|
255
|
+
const planPayload = await plan;
|
|
256
|
+
if (signal.aborted) {
|
|
257
|
+
throw Object.assign(new Error("Usage query aborted."), {
|
|
258
|
+
name: "AbortError",
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
return normalizeAntigravityUsage(
|
|
263
|
+
quota.payload,
|
|
264
|
+
Date.now(),
|
|
265
|
+
planPayload,
|
|
266
|
+
auth.accountEmail,
|
|
267
|
+
);
|
|
268
|
+
},
|
|
269
|
+
},
|
|
195
270
|
];
|
|
196
271
|
|
|
272
|
+
async function readAntigravityStoredCredential(): Promise<unknown> {
|
|
273
|
+
try {
|
|
274
|
+
const { readStoredCredential } = await import(
|
|
275
|
+
"@earendil-works/pi-coding-agent",
|
|
276
|
+
);
|
|
277
|
+
return readStoredCredential(ANTIGRAVITY_PROVIDER_ID);
|
|
278
|
+
} catch {
|
|
279
|
+
return undefined;
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
async function fetchAntigravityJson(
|
|
284
|
+
origins: readonly string[],
|
|
285
|
+
path: string,
|
|
286
|
+
auth: ResolvedUsageAuth,
|
|
287
|
+
signal: AbortSignal,
|
|
288
|
+
timeoutMs: number,
|
|
289
|
+
description: string,
|
|
290
|
+
body: Record<string, unknown>,
|
|
291
|
+
): Promise<{ origin: string; payload: Record<string, unknown> }> {
|
|
292
|
+
let lastError: unknown;
|
|
293
|
+
for (const origin of origins) {
|
|
294
|
+
try {
|
|
295
|
+
return {
|
|
296
|
+
origin,
|
|
297
|
+
payload: await fetchProviderJson(
|
|
298
|
+
`${origin}${path}`,
|
|
299
|
+
auth,
|
|
300
|
+
signal,
|
|
301
|
+
timeoutMs,
|
|
302
|
+
description,
|
|
303
|
+
{
|
|
304
|
+
method: "POST",
|
|
305
|
+
body,
|
|
306
|
+
headers: antigravityRequestHeaders(),
|
|
307
|
+
},
|
|
308
|
+
),
|
|
309
|
+
};
|
|
310
|
+
} catch (error) {
|
|
311
|
+
if (isAbortError(error) || signal.aborted) throw error;
|
|
312
|
+
// Free-tier accounts get this on every origin; it is not a fault.
|
|
313
|
+
if (isAntigravitySubscriptionRequired(error)) {
|
|
314
|
+
throw new UsageUnsupportedError(
|
|
315
|
+
"Antigravity quota summary requires a paid Google AI subscription.",
|
|
316
|
+
);
|
|
317
|
+
}
|
|
318
|
+
lastError = error;
|
|
319
|
+
if (!isRetryableAntigravityError(error)) throw error;
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
throw lastError instanceof Error
|
|
323
|
+
? lastError
|
|
324
|
+
: new Error(`${description} failed.`);
|
|
325
|
+
}
|
|
326
|
+
|
|
197
327
|
export function adapterForProvider(
|
|
198
328
|
providerId: string | undefined,
|
|
199
329
|
): UsageProviderAdapter | undefined {
|
|
@@ -251,13 +381,28 @@ export async function resolveUsageAuth(
|
|
|
251
381
|
`${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
|
|
252
382
|
);
|
|
253
383
|
}
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
384
|
+
let authorization = headerValue(result.auth.headers, "Authorization");
|
|
385
|
+
let extractedToken: string | undefined;
|
|
386
|
+
let accountEmail: string | undefined;
|
|
387
|
+
|
|
388
|
+
if (adapter.id === ANTIGRAVITY_PROVIDER_ID) {
|
|
389
|
+
const extracted = extractAntigravityAuth(result.auth.apiKey, authorization);
|
|
390
|
+
authorization = extracted.authorization;
|
|
391
|
+
extractedToken = extracted.token;
|
|
392
|
+
accountEmail =
|
|
393
|
+
extracted.email ??
|
|
394
|
+
emailFromAntigravityCredential(
|
|
395
|
+
await readAntigravityStoredCredential(),
|
|
396
|
+
);
|
|
397
|
+
} else if (!authorization && result.auth.apiKey) {
|
|
398
|
+
authorization = `Bearer ${result.auth.apiKey}`;
|
|
399
|
+
}
|
|
400
|
+
|
|
257
401
|
if (!authorization) return undefined;
|
|
258
402
|
const headers = { Authorization: authorization };
|
|
259
403
|
const secrets = [
|
|
260
404
|
result.auth.apiKey,
|
|
405
|
+
extractedToken && extractedToken !== result.auth.apiKey ? extractedToken : undefined,
|
|
261
406
|
headerValue(result.auth.headers, "Authorization"),
|
|
262
407
|
authorization,
|
|
263
408
|
].filter((value): value is string => Boolean(value));
|
|
@@ -266,12 +411,14 @@ export async function resolveUsageAuth(
|
|
|
266
411
|
const codexAdapter = adapterForProvider(CODEX_PROVIDER_ID)!;
|
|
267
412
|
const companion = await resolveUsageAuth(ctx, { ...codexAdapter, requiresOAuth: true }, salt);
|
|
268
413
|
if (!companion) {
|
|
269
|
-
|
|
414
|
+
// ChatGPT backend usage rejects these app tokens (401 rejected_by_access_enforcement).
|
|
415
|
+
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.");
|
|
270
416
|
}
|
|
271
417
|
return {
|
|
272
418
|
actualProviderId: model.provider,
|
|
273
419
|
model,
|
|
274
420
|
openaiClientId: clientId,
|
|
421
|
+
accountEmail,
|
|
275
422
|
// Only the backend credential is sent to ChatGPT. The active API token
|
|
276
423
|
// is used locally for registration matching and cache invalidation.
|
|
277
424
|
headers: companion.headers,
|
|
@@ -281,6 +428,7 @@ export async function resolveUsageAuth(
|
|
|
281
428
|
}
|
|
282
429
|
return {
|
|
283
430
|
actualProviderId: model.provider,
|
|
431
|
+
accountEmail,
|
|
284
432
|
apiKey: result.auth.apiKey,
|
|
285
433
|
headers,
|
|
286
434
|
fingerprint: fingerprintResolvedAuth({ headers }, salt),
|
|
@@ -289,6 +437,37 @@ export async function resolveUsageAuth(
|
|
|
289
437
|
};
|
|
290
438
|
}
|
|
291
439
|
|
|
440
|
+
/**
|
|
441
|
+
* Undefined means unverified: usage still displays, but no reset is offered.
|
|
442
|
+
* Scope the listing to the backend token's own account, as redemption does.
|
|
443
|
+
*/
|
|
444
|
+
async function fetchRedeemableResetCount(
|
|
445
|
+
auth: ResolvedUsageAuth,
|
|
446
|
+
signal: AbortSignal,
|
|
447
|
+
timeoutMs: number,
|
|
448
|
+
): Promise<number | undefined> {
|
|
449
|
+
const access = /^Bearer\s+(\S+)$/iu.exec(
|
|
450
|
+
headerValue(auth.headers, "Authorization") ?? "",
|
|
451
|
+
)?.[1];
|
|
452
|
+
const accountId = access ? codexAccountIdFromAccessToken(access) : undefined;
|
|
453
|
+
if (!accountId) return undefined;
|
|
454
|
+
try {
|
|
455
|
+
return normalizeCodexResetCreditsPayload(
|
|
456
|
+
await fetchProviderJson(
|
|
457
|
+
RESET_CREDITS_URL,
|
|
458
|
+
auth,
|
|
459
|
+
signal,
|
|
460
|
+
timeoutMs,
|
|
461
|
+
"Reset credits endpoint",
|
|
462
|
+
{ headers: { "chatgpt-account-id": accountId } },
|
|
463
|
+
),
|
|
464
|
+
).availableCount;
|
|
465
|
+
} catch (error) {
|
|
466
|
+
if (isAbortError(error) || signal.aborted) throw error;
|
|
467
|
+
return undefined;
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
|
|
292
471
|
export async function queryProviderUsage(
|
|
293
472
|
adapter: UsageProviderAdapter,
|
|
294
473
|
auth: ResolvedUsageAuth,
|
|
@@ -299,7 +478,10 @@ export async function queryProviderUsage(
|
|
|
299
478
|
return await adapter.query(auth, signal, timeoutMs);
|
|
300
479
|
} catch (error) {
|
|
301
480
|
if (error instanceof Error && error.name === "AbortError") throw error;
|
|
302
|
-
|
|
481
|
+
const message = redactUsageError(errorMessage(error), auth.secrets);
|
|
482
|
+
throw error instanceof UsageUnsupportedError
|
|
483
|
+
? new UsageUnsupportedError(message)
|
|
484
|
+
: new Error(message);
|
|
303
485
|
}
|
|
304
486
|
}
|
|
305
487
|
|
|
@@ -346,8 +528,11 @@ export async function fetchProviderJson(
|
|
|
346
528
|
description,
|
|
347
529
|
);
|
|
348
530
|
if (!response.ok) {
|
|
349
|
-
throw
|
|
350
|
-
|
|
531
|
+
throw Object.assign(
|
|
532
|
+
new Error(
|
|
533
|
+
`${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
|
|
534
|
+
),
|
|
535
|
+
{ status: response.status },
|
|
351
536
|
);
|
|
352
537
|
}
|
|
353
538
|
let parsed: unknown;
|
package/src/types.ts
CHANGED
|
@@ -53,6 +53,7 @@ export interface ResolvedUsageAuth {
|
|
|
53
53
|
openaiClientId?: string;
|
|
54
54
|
/** Original usage identity, retained when reset auth adds account headers. */
|
|
55
55
|
usageFingerprint?: string;
|
|
56
|
+
accountEmail?: string;
|
|
56
57
|
apiKey?: string;
|
|
57
58
|
headers: Record<string, string>;
|
|
58
59
|
fingerprint: string;
|