@specode/pi-subscription-usage 1.5.0 → 2.0.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 CHANGED
@@ -39,7 +39,6 @@ To sign in, run `/login`, pick `Sign in with an account` (Account below) or `Sig
39
39
  | OpenCode Go | API key → `OpenCode Go` | `5h`, `1w`, `1m` | — | |
40
40
  | xAI Grok | Account → `xAI` | `1w` and/or `1m` | — | |
41
41
  | Kimi Coding | Account → `Kimi For Coding` | `5h`, `1w`, membership level | — | |
42
- | Antigravity | Account → `Antigravity` | Gemini (`5h`, `1w`), Claude and GPT (`5h`, `1w`), Gemini 4 Argon (`1w`), plan, email, project | — | [`pi-antigravity`](https://www.npmjs.com/package/pi-antigravity) |
43
42
  | Claude (Claude Code) | None; signed in through Claude Code | `5h`, `1w` | — | [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) 0.9.3 or later |
44
43
 
45
44
  ### Provider Notes
@@ -52,24 +51,9 @@ Sign in to both `OpenAI` and `OpenAI Codex (legacy)` with the same ChatGPT accou
52
51
 
53
52
  Sign in with your SuperGrok account (Account → `xAI`). Signing in with an xAI API key does not show subscription quota. If you use the third-party `pi-xai-oauth` extension instead, its sign-in works too.
54
53
 
55
- #### Antigravity
56
-
57
- Requires [`pi-antigravity`](https://www.npmjs.com/package/pi-antigravity) by Rahul Arya ([GitHub](https://github.com/Rahularya01/pi-antigravity)). Install it with `pi install npm:pi-antigravity`; `Antigravity` then appears under `Sign in with an account` in `/login`. Quota is split into three separate shared pools: Gemini models (`5h` and `1w`), Claude and GPT models (`5h` and `1w`), and Gemini 4 Argon (`1w`). The footer shows the pool of the model you are using: Claude and GPT-OSS models show the Claude and GPT pool, Gemini 4 Argon shows the Argon pool, and other Gemini models show the Gemini pool. Quota data requires a paid Google AI subscription; free-tier accounts show `Unsupported` in `/usage` and display nothing in the footer instead of an error.
58
-
59
- Tested with `pi-antigravity` 0.11.0. Every earlier version back to 0.1.0 registers the same provider id, Google endpoint, and credential format, so they are expected to work too.
60
-
61
- Several packages have similar names. The extension recognizes the `antigravity` provider id and reads quota from Google's Cloud Code API with the credential Pi resolves for it, so the package must register that id and serve models from Google's endpoint. Install only one package that registers `antigravity`. As of October 31, 2026:
62
-
63
- | Package | Result |
64
- | --- | --- |
65
- | `pi-antigravity` | Works |
66
- | `@gwylook/pi-antigravity`, `@dereknex/pi-antigravity` (forks of `pi-antigravity`), `@heyhuynhgiabuu/pi-oauth-antigravity`, `@raquezha/antigravity`, `pi-provider-antigravity` | Same provider id, Google endpoint, and credential format; expected to work, untested |
67
- | `@estebanforge/pi-antigravity-bridge`, `@thoth-agents/pi-antigravity-bridge` | Register `antigravity` but run models through a local Antigravity bridge (`agy-bridge://`): unsupported, so the footer stays empty and `/usage` explains why |
68
- | `@cortexkit/pi-antigravity-auth` (`google`), `pi-antigravity-acp-provider` and `@dapidev/pi-antigravity-pure` (`antigravity-acp`), `@ackneal/pi-agy-bridge` (`agy`) | Register a different provider id; not supported |
69
-
70
54
  #### Claude (Claude Code)
71
55
 
72
- Requires [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) by elidickinson ([GitHub](https://github.com/elidickinson/pi-claude-bridge)), version 0.9.3 or later. 0.9.3 is the first version that passes Claude Code's usage reports on to Pi. Install it with `pi install npm:pi-claude-bridge` and sign in to Claude Code itself; there is no Pi login. Usage covers models under the `claude-bridge` provider; Claude models served by Antigravity use the Antigravity pool above.
56
+ Requires [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) by elidickinson ([GitHub](https://github.com/elidickinson/pi-claude-bridge)), version 0.9.3 or later. 0.9.3 is the first version that passes Claude Code's usage reports on to Pi. Install it with `pi install npm:pi-claude-bridge` and sign in to Claude Code itself; there is no Pi login. Usage covers models under the `claude-bridge` provider.
73
57
 
74
58
  The bridge has no usage endpoint to query: Claude Code attaches your plan usage to its responses, and the extension reads that report. So the footer stays empty in each new session until the first report arrives, `/usage` shows the last reported values with the time they were reported instead of fetching, and a window whose reset time has passed shows as unused until the next report. The extension never reads Claude Code's credentials.
75
59
 
package/README.zh-CN.md CHANGED
@@ -39,7 +39,6 @@ OpenAI Codex
39
39
  | OpenCode Go | API key → `OpenCode Go` | `5h`、`1w`、`1m` | — | |
40
40
  | xAI Grok | Account → `xAI` | `1w` 和/或 `1m` | — | |
41
41
  | Kimi Coding | Account → `Kimi For Coding` | `5h`、`1w`、会员等级 | — | |
42
- | Antigravity | Account → `Antigravity` | Gemini(`5h`、`1w`)、Claude 与 GPT(`5h`、`1w`)、Gemini 4 Argon(`1w`)、套餐、邮箱、项目 | — | [`pi-antigravity`](https://www.npmjs.com/package/pi-antigravity) |
43
42
  | Claude (Claude Code) | 无需在 Pi 登录,使用 Claude Code 的登录 | `5h`、`1w` | — | [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge) 0.9.3 及以上 |
44
43
 
45
44
  ### 提供商说明
@@ -52,24 +51,9 @@ OpenAI Codex
52
51
 
53
52
  用 SuperGrok 账号登录(Account → `xAI`)。用 xAI 的 API Key 登录看不到订阅额度。如果你装的是第三方扩展 `pi-xai-oauth`,用它登录也可以。
54
53
 
55
- #### Antigravity
56
-
57
- 需要 Rahul Arya 发布的 [`pi-antigravity`](https://www.npmjs.com/package/pi-antigravity)([GitHub](https://github.com/Rahularya01/pi-antigravity))。用 `pi install npm:pi-antigravity` 安装,之后 `/login` 的 `Sign in with an account` 列表里才会出现 `Antigravity`。额度分为三个独立的共享池:Gemini 模型(`5h` 与 `1w`)、Claude 与 GPT 模型(`5h` 与 `1w`)、Gemini 4 Argon(`1w`)。底部状态栏显示当前所用模型对应的额度池:用 Claude 或 GPT-OSS 模型时显示 Claude 与 GPT 池,用 Gemini 4 Argon 时显示 Argon 池,其他 Gemini 模型显示 Gemini 池。额度数据只对 Google AI 付费订阅开放;免费账号在 `/usage` 里显示 `Unsupported`,底部状态栏不显示内容,不会报错。
58
-
59
- 已用 `pi-antigravity` 0.11.0 测试。0.1.0 以来的各个版本注册的 provider id、Google 接口地址和凭据格式都相同,预计同样可用。
60
-
61
- npm 上有好几个名字相近的包。扩展按 `antigravity` 这个 provider id 识别,并用 Pi 为它提供的凭据向 Google 的 Cloud Code 接口查询额度,所以所用的包既要注册这个 id,模型也要走 Google 的接口。注册 `antigravity` 的包只装一个。截至 2026 年 10 月 31 日:
62
-
63
- | 包 | 结果 |
64
- | --- | --- |
65
- | `pi-antigravity` | 可用 |
66
- | `@gwylook/pi-antigravity`、`@dereknex/pi-antigravity`(`pi-antigravity` 的 fork)、`@heyhuynhgiabuu/pi-oauth-antigravity`、`@raquezha/antigravity`、`pi-provider-antigravity` | provider id、Google 接口地址和凭据格式都相同,预计可用,未测试 |
67
- | `@estebanforge/pi-antigravity-bridge`、`@thoth-agents/pi-antigravity-bridge` | 注册了 `antigravity`,但模型经由本地 Antigravity 桥(`agy-bridge://`)运行:不支持,底部状态栏为空,`/usage` 会说明原因 |
68
- | `@cortexkit/pi-antigravity-auth`(`google`)、`pi-antigravity-acp-provider` 与 `@dapidev/pi-antigravity-pure`(`antigravity-acp`)、`@ackneal/pi-agy-bridge`(`agy`) | 注册的是别的 provider id,不支持 |
69
-
70
54
  #### Claude (Claude Code)
71
55
 
72
- 需要 elidickinson 发布的 [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge)([GitHub](https://github.com/elidickinson/pi-claude-bridge))0.9.3 及以上版本,0.9.3 是第一个把 Claude Code 的用量数据转交给 Pi 的版本。用 `pi install npm:pi-claude-bridge` 安装,并在 Claude Code 里登录,Pi 这边不用登录。这里指 `claude-bridge` 提供商下的模型;通过 Antigravity 使用的 Claude 模型按上文的 Antigravity 额度池显示。
56
+ 需要 elidickinson 发布的 [`pi-claude-bridge`](https://www.npmjs.com/package/pi-claude-bridge)([GitHub](https://github.com/elidickinson/pi-claude-bridge))0.9.3 及以上版本,0.9.3 是第一个把 Claude Code 的用量数据转交给 Pi 的版本。用 `pi install npm:pi-claude-bridge` 安装,并在 Claude Code 里登录,Pi 这边不用登录。这里指 `claude-bridge` 提供商下的模型。
73
57
 
74
58
  bridge 没有可查询的用量接口:Claude Code 会在回复中附带当前套餐用量,扩展读取的就是这份数据。因此每个新会话要等收到第一份用量数据,底部状态栏才有内容;`/usage` 不会重新查询,只显示最近一次收到的数值和对应时间;如果某个窗口的重置时间已过,在收到下一份数据之前按未使用显示。扩展不会读取 Claude Code 的凭据。
75
59
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@specode/pi-subscription-usage",
3
- "version": "1.5.0",
4
- "description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, Kimi, Antigravity, and Claude (via pi-claude-bridge), plus OpenAI and Codex account reset credits in Pi",
3
+ "version": "2.0.0",
4
+ "description": "Show subscription quota for OpenAI, Codex, OpenCode Go, Grok, Kimi, and Claude (via pi-claude-bridge), plus OpenAI and Codex account reset credits in Pi",
5
5
  "type": "module",
6
6
  "license": "MIT",
7
7
  "author": "Specode",
@@ -23,7 +23,6 @@
23
23
  "opencode",
24
24
  "grok",
25
25
  "kimi",
26
- "antigravity",
27
26
  "claude"
28
27
  ],
29
28
  "files": [
package/src/query.ts CHANGED
@@ -7,21 +7,8 @@ import {
7
7
  fingerprintResolvedAuth,
8
8
  isAbortError,
9
9
  redactUsageError,
10
- sanitizeDisplayText,
11
10
  } from "./core.ts";
12
11
  import { CODEX_PROVIDER_ID } from "./providers/codex-constants.ts";
13
- import {
14
- ANTIGRAVITY_LOAD_CODE_ASSIST_BODY,
15
- ANTIGRAVITY_OFFICIAL_ORIGINS,
16
- ANTIGRAVITY_PROVIDER_ID,
17
- antigravityQueryOrigins,
18
- antigravityRequestHeaders,
19
- emailFromAntigravityCredential,
20
- extractAntigravityAuth,
21
- isAntigravitySubscriptionRequired,
22
- isRetryableAntigravityError,
23
- normalizeAntigravityUsage,
24
- } from "./providers/antigravity.ts";
25
12
  import {
26
13
  codexAccountIdFromAccessToken,
27
14
  normalizeCodexResetCreditsPayload,
@@ -219,112 +206,8 @@ export const SUPPORTED_ADAPTERS: readonly UsageProviderAdapter[] = [
219
206
  return normalizeGrokBilling(credits, capturedAt, monthly);
220
207
  },
221
208
  },
222
- {
223
- id: ANTIGRAVITY_PROVIDER_ID,
224
- displayName: "Antigravity",
225
- providerIds: [ANTIGRAVITY_PROVIDER_ID],
226
- officialOrigins: ANTIGRAVITY_OFFICIAL_ORIGINS,
227
- semantics: {
228
- kind: "consumer-subscription",
229
- label: "Antigravity subscription limits",
230
- },
231
- async query(auth, signal, timeoutMs) {
232
- const origins = antigravityQueryOrigins(auth.model?.baseUrl);
233
- // Plan metadata is optional; attach the handler now so a quota failure
234
- // cannot leave this request as an unhandled rejection.
235
- const plan = fetchAntigravityJson(
236
- origins,
237
- "/v1internal:loadCodeAssist",
238
- auth,
239
- signal,
240
- timeoutMs,
241
- "Antigravity code assist endpoint",
242
- ANTIGRAVITY_LOAD_CODE_ASSIST_BODY,
243
- ).then(
244
- (result) => result.payload,
245
- () => undefined,
246
- );
247
- const quota = await fetchAntigravityJson(
248
- origins,
249
- "/v1internal:retrieveUserQuotaSummary",
250
- auth,
251
- signal,
252
- timeoutMs,
253
- "Antigravity quota endpoint",
254
- {},
255
- );
256
- const planPayload = await plan;
257
- if (signal.aborted) {
258
- throw Object.assign(new Error("Usage query aborted."), {
259
- name: "AbortError",
260
- });
261
- }
262
-
263
- return normalizeAntigravityUsage(
264
- quota.payload,
265
- Date.now(),
266
- planPayload,
267
- auth.accountEmail,
268
- );
269
- },
270
- },
271
209
  ];
272
210
 
273
- async function readAntigravityStoredCredential(): Promise<unknown> {
274
- try {
275
- const { readStoredCredential } = await import(
276
- "@earendil-works/pi-coding-agent",
277
- );
278
- return readStoredCredential(ANTIGRAVITY_PROVIDER_ID);
279
- } catch {
280
- return undefined;
281
- }
282
- }
283
-
284
- async function fetchAntigravityJson(
285
- origins: readonly string[],
286
- path: string,
287
- auth: ResolvedUsageAuth,
288
- signal: AbortSignal,
289
- timeoutMs: number,
290
- description: string,
291
- body: Record<string, unknown>,
292
- ): Promise<{ origin: string; payload: Record<string, unknown> }> {
293
- let lastError: unknown;
294
- for (const origin of origins) {
295
- try {
296
- return {
297
- origin,
298
- payload: await fetchProviderJson(
299
- `${origin}${path}`,
300
- auth,
301
- signal,
302
- timeoutMs,
303
- description,
304
- {
305
- method: "POST",
306
- body,
307
- headers: antigravityRequestHeaders(),
308
- },
309
- ),
310
- };
311
- } catch (error) {
312
- if (isAbortError(error) || signal.aborted) throw error;
313
- // Free-tier accounts get this on every origin; it is not a fault.
314
- if (isAntigravitySubscriptionRequired(error)) {
315
- throw new UsageUnsupportedError(
316
- "Antigravity quota summary requires a paid Google AI subscription.",
317
- );
318
- }
319
- lastError = error;
320
- if (!isRetryableAntigravityError(error)) throw error;
321
- }
322
- }
323
- throw lastError instanceof Error
324
- ? lastError
325
- : new Error(`${description} failed.`);
326
- }
327
-
328
211
  export function adapterForProvider(
329
212
  providerId: string | undefined,
330
213
  ): UsageProviderAdapter | undefined {
@@ -347,18 +230,6 @@ export async function resolveUsageAuth(
347
230
  const UnsupportedModeError = adapter.id === OPENAI_PROVIDER_ID
348
231
  ? UsageUnsupportedError
349
232
  : Error;
350
- // Packages that reuse a provider id over another transport (for example
351
- // pi-antigravity-bridge's agy-bridge://) are not a proxy to refuse loudly.
352
- if (
353
- current &&
354
- adapter.providerIds.includes(current.provider) &&
355
- current.baseUrl &&
356
- !isHttpUrl(current.baseUrl)
357
- ) {
358
- throw new UsageUnsupportedError(
359
- `${adapter.displayName} usage is unavailable for models served over ${sanitizeDisplayText(current.baseUrl, 60)}; only the provider's own HTTPS API reports quota.`,
360
- );
361
- }
362
233
  if (
363
234
  current &&
364
235
  adapter.providerIds.includes(current.provider) &&
@@ -394,28 +265,13 @@ export async function resolveUsageAuth(
394
265
  `${adapter.displayName} usage cannot send a proxy-resolved credential to an official usage endpoint.`,
395
266
  );
396
267
  }
397
- let authorization = headerValue(result.auth.headers, "Authorization");
398
- let extractedToken: string | undefined;
399
- let accountEmail: string | undefined;
400
-
401
- if (adapter.id === ANTIGRAVITY_PROVIDER_ID) {
402
- const extracted = extractAntigravityAuth(result.auth.apiKey, authorization);
403
- authorization = extracted.authorization;
404
- extractedToken = extracted.token;
405
- accountEmail =
406
- extracted.email ??
407
- emailFromAntigravityCredential(
408
- await readAntigravityStoredCredential(),
409
- );
410
- } else if (!authorization && result.auth.apiKey) {
411
- authorization = `Bearer ${result.auth.apiKey}`;
412
- }
413
-
268
+ const authorization =
269
+ headerValue(result.auth.headers, "Authorization") ??
270
+ (result.auth.apiKey ? `Bearer ${result.auth.apiKey}` : undefined);
414
271
  if (!authorization) return undefined;
415
272
  const headers = { Authorization: authorization };
416
273
  const secrets = [
417
274
  result.auth.apiKey,
418
- extractedToken && extractedToken !== result.auth.apiKey ? extractedToken : undefined,
419
275
  headerValue(result.auth.headers, "Authorization"),
420
276
  authorization,
421
277
  ].filter((value): value is string => Boolean(value));
@@ -431,7 +287,6 @@ export async function resolveUsageAuth(
431
287
  actualProviderId: model.provider,
432
288
  model,
433
289
  openaiClientId: clientId,
434
- accountEmail,
435
290
  // Only the backend credential is sent to ChatGPT. The active API token
436
291
  // is used locally for registration matching and cache invalidation.
437
292
  headers: companion.headers,
@@ -441,7 +296,6 @@ export async function resolveUsageAuth(
441
296
  }
442
297
  return {
443
298
  actualProviderId: model.provider,
444
- accountEmail,
445
299
  apiKey: result.auth.apiKey,
446
300
  headers,
447
301
  fingerprint: fingerprintResolvedAuth({ headers }, salt),
@@ -491,10 +345,7 @@ export async function queryProviderUsage(
491
345
  return await adapter.query(auth, signal, timeoutMs);
492
346
  } catch (error) {
493
347
  if (error instanceof Error && error.name === "AbortError") throw error;
494
- const message = redactUsageError(errorMessage(error), auth.secrets);
495
- throw error instanceof UsageUnsupportedError
496
- ? new UsageUnsupportedError(message)
497
- : new Error(message);
348
+ throw new Error(redactUsageError(errorMessage(error), auth.secrets));
498
349
  }
499
350
  }
500
351
 
@@ -541,11 +392,8 @@ export async function fetchProviderJson(
541
392
  description,
542
393
  );
543
394
  if (!response.ok) {
544
- throw Object.assign(
545
- new Error(
546
- `${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
547
- ),
548
- { status: response.status },
395
+ throw new Error(
396
+ `${description} returned ${response.status} ${response.statusText}: ${redactUsageError(text, auth.secrets)}`,
549
397
  );
550
398
  }
551
399
  let parsed: unknown;
@@ -639,15 +487,6 @@ function candidateModels(
639
487
  return candidates;
640
488
  }
641
489
 
642
- function isHttpUrl(value: string): boolean {
643
- try {
644
- const { protocol } = new URL(value);
645
- return protocol === "https:" || protocol === "http:";
646
- } catch {
647
- return false;
648
- }
649
- }
650
-
651
490
  function hasOfficialOrigin(
652
491
  value: string | undefined,
653
492
  adapter: UsageProviderAdapter,
package/src/types.ts CHANGED
@@ -53,7 +53,6 @@ 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;
57
56
  apiKey?: string;
58
57
  headers: Record<string, string>;
59
58
  fingerprint: string;
package/src/usage.ts CHANGED
@@ -75,10 +75,7 @@ type StableCurrent = {
75
75
 
76
76
  export default function subscriptionUsage(pi: ExtensionAPI): void {
77
77
  const cache = new UsageCache(CACHE_TTL_MS);
78
- const failureBackoff = new Map<
79
- string,
80
- { until: number; message: string; status: "unsupported" | "query-failed" }
81
- >();
78
+ const failureBackoff = new Map<string, { until: number; message: string }>();
82
79
  const activeControllers = new Set<AbortController>();
83
80
  let sessionActive = false;
84
81
  let displayMode: UsageDisplayMode = DEFAULT_USAGE_DISPLAY_MODE;
@@ -238,7 +235,7 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
238
235
  state: {
239
236
  providerId: adapter.id,
240
237
  providerName: adapter.displayName,
241
- status: failure.status,
238
+ status: "query-failed",
242
239
  message: failure.message,
243
240
  },
244
241
  fingerprint: auth.fingerprint,
@@ -265,19 +262,15 @@ export default function subscriptionUsage(pi: ExtensionAPI): void {
265
262
  } catch (error) {
266
263
  if (isAbortError(error) || !sessionActive) throw error;
267
264
  const message = errorMessage(error);
268
- const status = error instanceof UsageUnsupportedError
269
- ? "unsupported"
270
- : "query-failed";
271
265
  failureBackoff.set(failureKey, {
272
266
  until: Date.now() + FAILURE_BACKOFF_MS,
273
267
  message,
274
- status,
275
268
  });
276
269
  return {
277
270
  state: {
278
271
  providerId: adapter.id,
279
272
  providerName: adapter.displayName,
280
- status,
273
+ status: "query-failed",
281
274
  message,
282
275
  },
283
276
  fingerprint: auth.fingerprint,
@@ -1,372 +0,0 @@
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
- }