@specode/pi-subscription-usage 1.3.1 → 1.5.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.
@@ -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
+ }
@@ -0,0 +1,118 @@
1
+ // pi-claude-bridge has no usage endpoint Pi can call: Claude Code reports plan
2
+ // usage as rate_limit_event messages, which the bridge replays to Pi as
3
+ // `anthropic-ratelimit-unified-*` headers on after_provider_response.
4
+ // This module turns those headers into a report; nothing here sends a request.
5
+ import type { UsageBucket, UsageReport } from "../types.ts";
6
+
7
+ export const CLAUDE_BRIDGE_PROVIDER_ID = "claude-bridge";
8
+
9
+ const HEADER_PREFIX = "anthropic-ratelimit-unified-";
10
+ // Observed: utilization is a 0..1 fraction. Anything far above 1 means the
11
+ // scale changed, and a guessed percentage would be worse than none.
12
+ const MAX_UTILIZATION = 1.5;
13
+ // Unix seconds; a millisecond value would land past this bound.
14
+ const MAX_EPOCH_SECONDS = 10_000_000_000;
15
+
16
+ const CLAUDE_WINDOWS: readonly {
17
+ abbreviation: string;
18
+ id: string;
19
+ label: string;
20
+ windowMinutes: number;
21
+ }[] = [
22
+ { abbreviation: "5h", id: "five-hour", label: "5h window", windowMinutes: 300 },
23
+ { abbreviation: "7d", id: "seven-day", label: "Weekly window", windowMinutes: 10_080 },
24
+ ];
25
+
26
+ /** Undefined when the headers carry no usable window, so a non-Claude response leaves the last observation alone. */
27
+ export function normalizeClaudeRateLimitHeaders(
28
+ headers: Record<string, string | undefined>,
29
+ capturedAt: number,
30
+ ): UsageReport | undefined {
31
+ const lookup = new Map(
32
+ Object.entries(headers).map(([name, value]) => [name.toLowerCase(), value]),
33
+ );
34
+ // The event names no provider, and a model switch mid-stream can deliver a
35
+ // real Anthropic response under claude-bridge with the same header names.
36
+ // Only the bridge's synthetic response consists of nothing but these.
37
+ if ([...lookup.keys()].some((name) => !name.startsWith(HEADER_PREFIX))) {
38
+ return undefined;
39
+ }
40
+ const buckets: UsageBucket[] = [];
41
+ for (const window of CLAUDE_WINDOWS) {
42
+ const utilization = parseNumber(
43
+ lookup.get(`${HEADER_PREFIX}${window.abbreviation}-utilization`),
44
+ );
45
+ if (
46
+ utilization === undefined ||
47
+ utilization < 0 ||
48
+ utilization > MAX_UTILIZATION
49
+ ) {
50
+ continue;
51
+ }
52
+ const used = utilization * 100;
53
+ const resetsAt = parseNumber(
54
+ lookup.get(`${HEADER_PREFIX}${window.abbreviation}-reset`),
55
+ );
56
+ buckets.push({
57
+ id: window.id,
58
+ label: window.label,
59
+ used,
60
+ remaining: Math.max(0, 100 - used),
61
+ unit: "percent",
62
+ windowMinutes: window.windowMinutes,
63
+ ...(resetsAt !== undefined && resetsAt > 0 && resetsAt < MAX_EPOCH_SECONDS
64
+ ? { resetsAt: Math.floor(resetsAt) }
65
+ : {}),
66
+ });
67
+ }
68
+ if (buckets.length === 0) return undefined;
69
+ return {
70
+ providerId: CLAUDE_BRIDGE_PROVIDER_ID,
71
+ providerName: "Claude (Claude Code)",
72
+ capturedAt,
73
+ source: "claude-code-rate-limit-event",
74
+ semantics: {
75
+ kind: "consumer-subscription",
76
+ label: "Claude subscription limits",
77
+ },
78
+ buckets,
79
+ metrics: [],
80
+ };
81
+ }
82
+
83
+ /**
84
+ * Claude Code only reports usage after a request, so an observation outlives
85
+ * its windows. A window whose reset has passed starts empty; showing the old
86
+ * percentage would overstate usage until the next response.
87
+ */
88
+ export function settleClaudeReport(
89
+ report: UsageReport,
90
+ nowMs: number,
91
+ ): UsageReport {
92
+ const nowSeconds = nowMs / 1_000;
93
+ return {
94
+ ...report,
95
+ buckets: report.buckets.map((bucket) => {
96
+ if (bucket.resetsAt === undefined || bucket.resetsAt > nowSeconds) {
97
+ return bucket;
98
+ }
99
+ const { resetsAt: _expired, ...rest } = bucket;
100
+ return { ...rest, used: 0, remaining: 100 };
101
+ }),
102
+ notes: [`Observed after the last Claude response at ${formatClock(report.capturedAt)}; Claude Code reports usage only with its responses.`],
103
+ };
104
+ }
105
+
106
+ function parseNumber(value: string | undefined): number | undefined {
107
+ if (value === undefined || !value.trim()) return undefined;
108
+ const parsed = Number(value);
109
+ return Number.isFinite(parsed) ? parsed : undefined;
110
+ }
111
+
112
+ function formatClock(epochMs: number): string {
113
+ const date = new Date(epochMs);
114
+ if (Number.isNaN(date.getTime())) return "an unknown time";
115
+ const hour = date.getHours().toString().padStart(2, "0");
116
+ const minute = date.getMinutes().toString().padStart(2, "0");
117
+ return `${hour}:${minute}`;
118
+ }