From f530efce28df228e09779d61437cbd437638f8be Mon Sep 17 00:00:00 2001 From: Satya siba Nayak <81738515+Satya-Siba-Nayak@users.noreply.github.com> Date: Thu, 3 Dec 2026 03:14:41 +0530 Subject: [PATCH] feat(antigravity): read usage limits via agy usage --json --- server/drivers/antigravity-acp.ts | 18 +- server/drivers/antigravity-signin.test.ts | 6 +- server/drivers/antigravity-signin.ts | 2 + server/drivers/antigravity-usage.test.ts | 265 ++++++++++++++++++++ server/drivers/antigravity-usage.ts | 292 ++++++++++++++++++++++ server/plan-usage-credentials.ts | 68 +---- server/plan-usage-parsers.ts | 153 +++++------- server/plan-usage-renewal.ts | 114 +-------- server/plan-usage-types.ts | 15 ++ server/plan-usage.test.ts | 173 +++++++------ server/plan-usage.ts | 251 +++++++------------ 11 files changed, 856 insertions(+), 501 deletions(-) create mode 100644 server/drivers/antigravity-usage.test.ts create mode 100644 server/drivers/antigravity-usage.ts diff --git a/server/drivers/antigravity-acp.ts b/server/drivers/antigravity-acp.ts index 16cecb76e8..b67bc50330 100644 --- a/server/drivers/antigravity-acp.ts +++ b/server/drivers/antigravity-acp.ts @@ -55,6 +55,7 @@ export interface AntigravityProfile { directory: string; tokenPath: string; legacyTokenPath: string; + usageTokenPath?: string; environment: NodeJS.ProcessEnv; tempDirectory?: string; } @@ -87,7 +88,7 @@ const REMOVED_ENVIRONMENT_KEYS = new Set([ // Another Antigravity host (IDE, T3 Code, CLI) exports ANTIGRAVITY_LS_ADDRESS, CSRF tokens, and app-data dirs into child shells. const REMOVED_ENVIRONMENT_PREFIXES = ["ANTIGRAVITY_", "AGY_", "JETSKI_"] as const; -function isRemovedAntigravityEnvKey(key: string): boolean { +export function isRemovedAntigravityEnvKey(key: string): boolean { const upper = key.toUpperCase(); return REMOVED_ENVIRONMENT_KEYS.has(upper) || REMOVED_ENVIRONMENT_PREFIXES.some((prefix) => upper.startsWith(prefix)); @@ -168,16 +169,26 @@ export async function removeAntigravityProfile(instanceId: string, baseDir = DAT }); } +export function antigravityUsageHome(profileDirectory: string): string { + return join(profileDirectory, "usage-home"); +} + +export function antigravityUsageTokenPath(profileDirectory: string): string { + return join(antigravityUsageHome(profileDirectory), ".gemini", "antigravity-cli", ANTIGRAVITY_CLI_TOKEN_FILE); +} + /** Signing out forgets only this account's stored Google sign-in; its profile stays for the next sign-in. */ export async function removeAntigravitySignIn(instanceId: string, baseDir = DATA_DIR): Promise { - const acpDirectory = join(antigravityProfileDirectory(instanceId, baseDir), ANTIGRAVITY_APP_DATA_DIR); + const profileDir = antigravityProfileDirectory(instanceId, baseDir); + const acpDirectory = join(profileDir, ANTIGRAVITY_APP_DATA_DIR); await forgetAntigravitySignIn({ tokenPath: join(acpDirectory, ANTIGRAVITY_CLI_TOKEN_FILE), legacyTokenPath: join(acpDirectory, ANTIGRAVITY_LEGACY_TOKEN_FILE), + usageTokenPath: antigravityUsageTokenPath(profileDir), }); } -function resolveLinuxCaBundle(baseEnv: NodeJS.ProcessEnv, platform: NodeJS.Platform): string | undefined { +export function resolveLinuxCaBundle(baseEnv: NodeJS.ProcessEnv, platform: NodeJS.Platform): string | undefined { if (platform !== "linux" || baseEnv.SSL_CERT_FILE !== undefined || baseEnv.SSL_CERT_DIR !== undefined) { return undefined; } @@ -259,6 +270,7 @@ export async function prepareAntigravityProfile(input: { directory, tokenPath: join(acpDirectory, ANTIGRAVITY_CLI_TOKEN_FILE), legacyTokenPath: join(acpDirectory, ANTIGRAVITY_LEGACY_TOKEN_FILE), + usageTokenPath: antigravityUsageTokenPath(directory), environment, ...(tempDirectory ? { tempDirectory } : {}), }; diff --git a/server/drivers/antigravity-signin.test.ts b/server/drivers/antigravity-signin.test.ts index 9eb033fbdb..02f327a0b8 100644 --- a/server/drivers/antigravity-signin.test.ts +++ b/server/drivers/antigravity-signin.test.ts @@ -3,7 +3,7 @@ import { tmpdir } from "node:os"; import { join } from "node:path"; import { afterEach, describe, expect, it } from "vitest"; -import { antigravityProfileAuthenticated, prepareAntigravityProfile, removeAntigravitySignIn } from "./antigravity-acp.ts"; +import { antigravityProfileAuthenticated, antigravityUsageTokenPath, prepareAntigravityProfile, removeAntigravitySignIn } from "./antigravity-acp.ts"; import { acceptNewAntigravitySignIn, antigravityKeepPath, @@ -91,11 +91,15 @@ describe("the Google sign-in survives what happens to its file", () => { it("removeAntigravitySignIn takes the copy too", async () => { const base = temp(); const profile = await prepareAntigravityProfile({ instanceId: "acct", runtime: { executablePath: "agy", version: "1.5.0" } as never, baseDir: base, baseEnv: { PATH: process.env.PATH } }); + const usageToken = antigravityUsageTokenPath(profile.directory); writeFileSync(profile.tokenPath, token("r1")); + mkdirSync(join(usageToken, ".."), { recursive: true }); + writeFileSync(usageToken, token("r1")); await ensureAntigravitySignIn(profile); await removeAntigravitySignIn("acct", base); expect(existsSync(profile.tokenPath)).toBe(false); expect(existsSync(antigravityKeepPath(profile.tokenPath))).toBe(false); + expect(existsSync(usageToken)).toBe(false); }); }); diff --git a/server/drivers/antigravity-signin.ts b/server/drivers/antigravity-signin.ts index 0756ff9055..b4b98c7186 100644 --- a/server/drivers/antigravity-signin.ts +++ b/server/drivers/antigravity-signin.ts @@ -12,6 +12,7 @@ const MAX_TOKEN_BYTES = 1024 * 1024; export interface AntigravityTokenPaths { tokenPath: string; legacyTokenPath?: string; + usageTokenPath?: string; } export type TokenState = "durable" | "short-lived" | "missing" | "corrupt"; @@ -94,6 +95,7 @@ export async function forgetAntigravitySignIn(paths: AntigravityTokenPaths): Pro rm(antigravityKeepPath(paths.tokenPath), { force: true, maxRetries: 4, retryDelay: 250 }), rm(paths.tokenPath, { force: true, maxRetries: 4, retryDelay: 250 }), ...(paths.legacyTokenPath ? [rm(paths.legacyTokenPath, { force: true, maxRetries: 4, retryDelay: 250 })] : []), + ...(paths.usageTokenPath ? [rm(paths.usageTokenPath, { force: true, maxRetries: 4, retryDelay: 250 })] : []), ]); }); } diff --git a/server/drivers/antigravity-usage.test.ts b/server/drivers/antigravity-usage.test.ts new file mode 100644 index 0000000000..704e55bd46 --- /dev/null +++ b/server/drivers/antigravity-usage.test.ts @@ -0,0 +1,265 @@ +import { chmodSync, existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { dirname, join } from "node:path"; +import { afterEach, describe, expect, it, vi } from "vitest"; + +import type { PlanAccount } from "../plan-usage-types.ts"; +import { + ANTIGRAVITY_APP_DATA_DIR, + ANTIGRAVITY_CLI_TOKEN_FILE, + antigravityProfileDirectory, + antigravityUsageHome, + antigravityUsageTokenPath, +} from "./antigravity-acp.ts"; +import { AntigravitySetupError, type AntigravityRuntime } from "./antigravity-runtime.ts"; +import { + ANTIGRAVITY_USAGE_UPDATE_MESSAGE, + antigravityUsageEnvironment, + createAntigravityUsageProbe, + type AntigravityUsageCommandRunner, +} from "./antigravity-usage.ts"; + +const tempDirs: string[] = []; + +afterEach(() => { + for (const dir of tempDirs.splice(0)) rmSync(dir, { recursive: true, force: true }); +}); + +function makeTempDir(prefix: string): string { + const dir = mkdtempSync(join(tmpdir(), prefix)); + tempDirs.push(dir); + return dir; +} + +function account(overrides: Partial = {}): PlanAccount { + return { + id: "antigravity", + name: "Antigravity", + driver: "antigravity", + environment: {}, + ...overrides, + }; +} + +function writeFakeCli(dir: string, scriptBody: string): string { + const scriptPath = join(dir, "fake-agy.mjs"); + writeFileSync(scriptPath, `#!/usr/bin/env node\n${scriptBody}`, "utf8"); + if (process.platform !== "win32") chmodSync(scriptPath, 0o755); + return scriptPath; +} + +function seedProfileToken(dataDir: string, instanceId: string, content: string): { profileDir: string; tokenPath: string } { + const profileDir = antigravityProfileDirectory(instanceId, dataDir); + const tokenPath = join(profileDir, ANTIGRAVITY_APP_DATA_DIR, ANTIGRAVITY_CLI_TOKEN_FILE); + mkdirSync(dirname(tokenPath), { recursive: true }); + writeFileSync(tokenPath, content, "utf8"); + return { profileDir, tokenPath }; +} + +describe("Antigravity CLI usage probe", () => { + it("isolates usage-home, copies the profile token, strips foreign env vars, and parses agy usage --json", async () => { + const dataDir = makeTempDir("dusk-agy-usage-data-"); + const binDir = makeTempDir("dusk-agy-usage-bin-"); + const tokenContent = JSON.stringify({ token: { access_token: "live-tok", refresh_token: "live-ref" } }); + const { profileDir } = seedProfileToken(dataDir, "antigravity", tokenContent); + + const fakeCli = writeFakeCli( + binDir, + ` +import { readFileSync } from "node:fs"; +import { join } from "node:path"; +if (process.argv[2] !== "usage" || process.argv[3] !== "--json") { + console.error("bad args", process.argv.slice(2)); + process.exit(2); +} +if (process.env.GEMINI_API_KEY || process.env.AGY_ACP_DEFAULT_MODEL || process.env.ANTIGRAVITY_LS_ADDRESS) { + console.error("leaked env"); + process.exit(3); +} +if (process.env.AGY_CLI_FORCE_FILE_TOKEN_STORAGE !== "1" || process.env.AGY_ACP_FORCE_FILE_STORAGE !== "1" || !process.env.SSH_CONNECTION) { + console.error("missing file storage flags"); + process.exit(4); +} +const home = process.platform === "win32" ? process.env.USERPROFILE : process.env.HOME; +const staged = readFileSync(join(home, ".gemini", "antigravity-cli", "antigravity-oauth-token"), "utf8"); +if (!staged.includes("live-ref")) { + console.error("missing staged token"); + process.exit(5); +} +console.log(JSON.stringify({ + status: "SUCCESS", + command: { + name: "usage", + data: { + groups: [ + { + name: "Gemini", + buckets: [ + { id: "gemini-5h", window: "5h", remaining_fraction: 0.75, reset_time: "2027-01-01T05:00:00Z" }, + { id: "gemini-weekly", window: "weekly", remaining_fraction: 0.9, reset_time: "2027-01-07T00:00:00Z" }, + ], + }, + { + name: "Claude & GPT", + buckets: [ + { id: "3p-5h", window: "5h", remaining_fraction: 1, reset_time: "1970-01-01T00:00:00Z" }, + ], + }, + ], + }, + }, +})); +`, + ); + + const probe = createAntigravityUsageProbe({ + dataDir, + env: { + ...process.env, + HOME: "/should/not/be/used", + USERPROFILE: "C:\\should\\not\\be\\used", + GEMINI_API_KEY: "secret-key", + AGY_ACP_DEFAULT_MODEL: "gemini-3", + ANTIGRAVITY_LS_ADDRESS: "127.0.0.1:9999", + }, + resolveRuntime: async (): Promise => ({ + executablePath: fakeCli, + source: "managed", + version: "1.5.22", + }), + }); + + const outcome = await probe(account()); + expect(outcome).toEqual({ + kind: "ok", + windows: { + plan: null, + fiveHour: { available: true, usedPercent: 25, remainingPercent: 75, resetsAt: "2027-01-01T05:00:00.000Z" }, + weekly: { available: true, usedPercent: 10, remainingPercent: 90, resetsAt: "2027-01-07T00:00:00.000Z" }, + extra: [], + models: [ + { + name: "Claude & GPT", + windows: [{ label: "5-hour", usedPercent: 0, remainingPercent: 100, resetsAt: null }], + }, + ], + }, + }); + expect(readFileSync(antigravityUsageTokenPath(profileDir), "utf8")).toBe(tokenContent); + }); + + it("refuses versions older than 1.5.22 without spawning agy", async () => { + const dataDir = makeTempDir("dusk-agy-old-"); + seedProfileToken(dataDir, "antigravity", JSON.stringify({ token: { access_token: "a", refresh_token: "r" } })); + const runCommand = vi.fn(); + const probe = createAntigravityUsageProbe({ + dataDir, + resolveRuntime: async () => ({ executablePath: "agy", source: "path", version: "1.5.17" }), + runCommand, + }); + const outcome = await probe(account()); + expect(outcome).toEqual({ kind: "other", error: ANTIGRAVITY_USAGE_UPDATE_MESSAGE }); + expect(runCommand).not.toHaveBeenCalled(); + }); + + it("maps unknown-version unexpected argument errors to the 1.5.22 update message", async () => { + const dataDir = makeTempDir("dusk-agy-override-"); + seedProfileToken(dataDir, "antigravity", JSON.stringify({ token: { access_token: "a", refresh_token: "r" } })); + const probe = createAntigravityUsageProbe({ + dataDir, + resolveRuntime: async () => ({ executablePath: "/custom/agy", source: "override", version: null }), + runCommand: async () => ({ + exitCode: 1, + stdout: "", + stderr: 'Error: unexpected argument "usage".', + timedOut: false, + }), + }); + expect(await probe(account({ cli: "/custom/agy" }))).toEqual({ + kind: "other", + error: ANTIGRAVITY_USAGE_UPDATE_MESSAGE, + }); + }); + + it("clears any stale usage-home token copy and asks to sign in when the profile has no token", async () => { + const dataDir = makeTempDir("dusk-agy-missing-"); + const profileDir = antigravityProfileDirectory("antigravity", dataDir); + const staleUsageToken = antigravityUsageTokenPath(profileDir); + mkdirSync(dirname(staleUsageToken), { recursive: true }); + writeFileSync(staleUsageToken, "stale-token", "utf8"); + + const runCommand = vi.fn(); + const probe = createAntigravityUsageProbe({ + dataDir, + resolveRuntime: async () => ({ executablePath: "agy", source: "managed", version: "1.5.22" }), + runCommand, + }); + expect(await probe(account())).toEqual({ kind: "auth", error: "Sign in again in Antigravity" }); + expect(existsSync(staleUsageToken)).toBe(false); + expect(runCommand).not.toHaveBeenCalled(); + }); + + it("classifies auth, rate-limit, setup, and timeout failures cleanly", async () => { + const dataDir = makeTempDir("dusk-agy-err-"); + seedProfileToken(dataDir, "antigravity", JSON.stringify({ token: { access_token: "a", refresh_token: "r" } })); + + const setupProbe = createAntigravityUsageProbe({ + dataDir, + resolveRuntime: async () => { throw new AntigravitySetupError("Antigravity is not installed."); }, + }); + expect(await setupProbe(account())).toEqual({ kind: "other", error: "Antigravity is not installed." }); + + const authProbe = createAntigravityUsageProbe({ + dataDir, + resolveRuntime: async () => ({ executablePath: "agy", source: "managed", version: "1.5.22" }), + runCommand: async () => ({ exitCode: 1, stdout: "", stderr: "Please sign in first.", timedOut: false }), + }); + expect(await authProbe(account())).toEqual({ kind: "auth", error: "Sign in again in Antigravity" }); + + const rateProbe = createAntigravityUsageProbe({ + dataDir, + resolveRuntime: async () => ({ executablePath: "agy", source: "managed", version: "1.5.22" }), + runCommand: async () => ({ exitCode: 1, stdout: "", stderr: "HTTP 429 Too Many Requests", timedOut: false }), + }); + expect(await rateProbe(account())).toEqual({ + kind: "rate_limit", + error: "Antigravity is temporarily limiting usage checks. Trying again soon.", + }); + + const binDir = makeTempDir("dusk-agy-timeout-"); + const slowCli = writeFakeCli(binDir, "setTimeout(() => {}, 10_000);\n"); + const timeoutProbe = createAntigravityUsageProbe({ + dataDir, + resolveRuntime: async () => ({ executablePath: slowCli, source: "managed", version: "1.5.22" }), + }); + expect(await timeoutProbe(account(), { timeoutMs: 150 })).toEqual({ + kind: "transient", + error: "Could not reach Antigravity", + }); + }); + + it("sets isolated HOME, USERPROFILE, and Windows TEMP without leaking case-variant keys", () => { + const usageHome = antigravityUsageHome("/tmp/profile"); + const env = antigravityUsageEnvironment( + { + PATH: "/usr/bin", + home: "/old/home", + UserProfile: "C:\\old\\home", + Temp: "C:\\old\\temp", + GEMINI_API_KEY: "bad", + }, + usageHome, + { platform: "win32", tempDirectory: "C:\\dusk\\tmp\\agy\\abc" }, + ); + expect(env.HOME).toBe(usageHome); + expect(env.USERPROFILE).toBe(usageHome); + expect(env.home).toBeUndefined(); + expect(env.UserProfile).toBeUndefined(); + expect(env.TEMP).toBe("C:\\dusk\\tmp\\agy\\abc"); + expect(env.TMP).toBe("C:\\dusk\\tmp\\agy\\abc"); + expect(env.Temp).toBeUndefined(); + expect(env.GEMINI_API_KEY).toBeUndefined(); + expect(env.AGY_CLI_FORCE_FILE_TOKEN_STORAGE).toBe("1"); + expect(env.AGY_CLI_DISABLE_AUTO_UPDATE).toBe("1"); + }); +}); diff --git a/server/drivers/antigravity-usage.ts b/server/drivers/antigravity-usage.ts new file mode 100644 index 0000000000..bf4d384a6f --- /dev/null +++ b/server/drivers/antigravity-usage.ts @@ -0,0 +1,292 @@ +// Reads Antigravity account quota through Google's official `agy usage --json` subcommand (CLI 1.5.22+). +// +// Private usage-home isolation and `agy usage --json` probe behavior adapted from pingdotgg/t3code +// (MIT License, Copyright (c) 2026 T3 Tools Inc., full text in third_party/t3-code/LICENSE): +// apps/server/src/provider/antigravityUsageLimits.ts and antigravityAuthSupport.ts. +import { chmod, copyFile, mkdir, rm, stat } from "node:fs/promises"; +import { dirname, join, resolve } from "node:path"; + +import { DATA_DIR, stripWorkspaceCredentialEnv } from "../config.ts"; +import { parseAntigravityCliUsage } from "../plan-usage-parsers.ts"; +import { parseJson, type AntigravityUsageOutcome, type AntigravityUsageProbe, type PlanAccount } from "../plan-usage-types.ts"; +import { killCliTree, spawnCli } from "../procs.ts"; +import { + ANTIGRAVITY_APP_DATA_DIR, + ANTIGRAVITY_CLI_TOKEN_FILE, + ANTIGRAVITY_LEGACY_TOKEN_FILE, + antigravityProfileDirectory, + antigravityUsageHome, + antigravityUsageTokenPath, + isRemovedAntigravityEnvKey, + resolveLinuxCaBundle, +} from "./antigravity-acp.ts"; +import { compareSemver } from "./antigravity-release.ts"; +import { AntigravitySetupError, resolveAntigravityRuntime, type AntigravityRuntime } from "./antigravity-runtime.ts"; +import { ensureAntigravitySignIn, withAntigravitySignInGate } from "./antigravity-signin.ts"; +import { antigravityTempDir, scheduleAntigravityTempSweep, setAntigravityTempEnvironment } from "./antigravity-temp.ts"; + +/** First Antigravity CLI release with the `agy usage` subcommand. */ +export const ANTIGRAVITY_USAGE_MIN_VERSION = "1.5.22"; +export const ANTIGRAVITY_USAGE_UPDATE_MESSAGE = + `Update Antigravity to ${ANTIGRAVITY_USAGE_MIN_VERSION} or newer to see usage limits.`; +/** Launching `agy` unpacks ~1 GB on Windows, so routine usage polls reuse recent readings. */ +export const ANTIGRAVITY_USAGE_CACHE_MS = 5 * 60_000; + +const USAGE_TIMEOUT_MS = 30_000; +const USAGE_MAX_STDOUT_BYTES = 256 * 1024; +const USAGE_MAX_STDERR_BYTES = 16 * 1024; +const TOKEN_MAX_BYTES = 1_000_000; + +const SIGN_IN_MESSAGE = "Sign in again in Antigravity"; +const COULD_NOT_REACH_MESSAGE = "Could not reach Antigravity"; +const UNEXPECTED_MESSAGE = "Antigravity returned an unexpected usage response"; +const RATE_LIMITED_MESSAGE = "Antigravity is temporarily limiting usage checks. Trying again soon."; + +const UNSUPPORTED_USAGE_PATTERN = /unexpected argument ["']?usage["']?|unknown command ["']?usage["']?/iu; +const AUTH_ERROR_PATTERN = /please sign in|authentication required|not signed in|sign in again|invalid_grant/iu; +const RATE_LIMIT_PATTERN = /\b429\b|too many requests|rate[- ]?limit/iu; + +export interface AntigravityUsageCommandResult { + exitCode: number | null; + stdout: string; + stderr: string; + timedOut: boolean; +} + +export type AntigravityUsageCommandRunner = (input: { + executablePath: string; + args: string[]; + cwd: string; + env: NodeJS.ProcessEnv; + timeoutMs: number; +}) => Promise; + +/** `agy usage` ignores `GEMINI_HOME` and reads `$HOME/.gemini`, so each profile runs in a private home. */ +export function antigravityUsageEnvironment( + baseEnv: NodeJS.ProcessEnv, + usageHome: string, + options: { platform?: NodeJS.Platform; tempDirectory?: string } = {}, +): NodeJS.ProcessEnv { + const platform = options.platform ?? process.platform; + const environment: NodeJS.ProcessEnv = {}; + for (const [key, value] of Object.entries(baseEnv)) { + const upper = key.toUpperCase(); + if (upper === "HOME" || upper === "USERPROFILE") continue; + if (!isRemovedAntigravityEnvKey(key)) environment[key] = value; + } + stripWorkspaceCredentialEnv(environment); + const caBundlePath = resolveLinuxCaBundle(baseEnv, platform); + Object.assign(environment, { + ...(caBundlePath ? { SSL_CERT_FILE: caBundlePath } : {}), + HOME: usageHome, + USERPROFILE: usageHome, + // Keep `agy usage` on the staged per-profile token file instead of the shared OS keyring entry. + SSH_CONNECTION: baseEnv.SSH_CONNECTION || "127.0.0.1 0 127.0.0.1 0", + AGY_ACP_FORCE_FILE_STORAGE: "1", + AGY_CLI_FORCE_FILE_TOKEN_STORAGE: "1", + AGY_CLI_DISABLE_AUTO_UPDATE: "1", + }); + if (platform === "win32" && options.tempDirectory) { + setAntigravityTempEnvironment(environment, options.tempDirectory, "win32"); + } + return environment; +} + +function appendCapped(chunks: Buffer[], totalBytes: number, chunk: Buffer, maxBytes: number): number { + const remaining = maxBytes - totalBytes; + if (remaining <= 0) return totalBytes; + const slice = chunk.length > remaining ? chunk.subarray(0, remaining) : chunk; + chunks.push(slice); + return totalBytes + slice.length; +} + +export function runAntigravityUsageCommand(input: { + executablePath: string; + args: string[]; + cwd: string; + env: NodeJS.ProcessEnv; + timeoutMs: number; +}): Promise { + return new Promise((resolveRun) => { + let settled = false; + let timedOut = false; + let timer: ReturnType | undefined; + const finish = (result: AntigravityUsageCommandResult) => { + if (settled) return; + settled = true; + if (timer) clearTimeout(timer); + resolveRun(result); + }; + let child: ReturnType; + try { + child = spawnCli(input.executablePath, input.args, { + cwd: input.cwd, + env: input.env, + stdio: ["ignore", "pipe", "pipe"], + }); + } catch (error) { + finish({ + exitCode: null, + stdout: "", + stderr: error instanceof Error ? error.message : String(error), + timedOut: false, + }); + return; + } + const stdoutChunks: Buffer[] = []; + const stderrChunks: Buffer[] = []; + let stdoutBytes = 0; + let stderrBytes = 0; + child.stdout?.on("data", (chunk: Buffer) => { + stdoutBytes = appendCapped(stdoutChunks, stdoutBytes, chunk, USAGE_MAX_STDOUT_BYTES); + }); + child.stderr?.on("data", (chunk: Buffer) => { + stderrBytes = appendCapped(stderrChunks, stderrBytes, chunk, USAGE_MAX_STDERR_BYTES); + }); + timer = setTimeout(() => { + timedOut = true; + void killCliTree(child, 0).finally(() => { + finish({ + exitCode: null, + stdout: Buffer.concat(stdoutChunks).toString("utf8"), + stderr: Buffer.concat(stderrChunks).toString("utf8"), + timedOut: true, + }); + }); + }, input.timeoutMs); + timer.unref?.(); + child.once("error", (error) => { + finish({ + exitCode: null, + stdout: Buffer.concat(stdoutChunks).toString("utf8"), + stderr: Buffer.concat(stderrChunks).toString("utf8") || error.message, + timedOut, + }); + }); + child.once("close", (code) => { + finish({ + exitCode: code, + stdout: Buffer.concat(stdoutChunks).toString("utf8"), + stderr: Buffer.concat(stderrChunks).toString("utf8"), + timedOut, + }); + }); + }); +} + +async function readableTokenFile(path: string): Promise { + try { + const info = await stat(path); + return info.isFile() && info.size > 0 && info.size <= TOKEN_MAX_BYTES; + } catch { + return false; + } +} + +async function resolveProfileToken( + account: PlanAccount, + dataDir: string, +): Promise<{ profileDir: string; tokenPath: string | null }> { + const customHome = account.environment.GEMINI_HOME?.trim(); + const profileDir = resolve(customHome || antigravityProfileDirectory(account.id, dataDir)); + const primaryToken = join(profileDir, ANTIGRAVITY_APP_DATA_DIR, ANTIGRAVITY_CLI_TOKEN_FILE); + const legacyToken = join(profileDir, ANTIGRAVITY_APP_DATA_DIR, ANTIGRAVITY_LEGACY_TOKEN_FILE); + await ensureAntigravitySignIn({ tokenPath: primaryToken, legacyTokenPath: legacyToken }).catch(() => "none"); + const candidates = customHome + ? [primaryToken, legacyToken, join(profileDir, "jetski-standalone-oauth-token")] + : [primaryToken, legacyToken]; + for (const candidate of candidates) { + if (await readableTokenFile(candidate)) return { profileDir, tokenPath: candidate }; + } + return { profileDir, tokenPath: null }; +} + +function classifyCliFailure(result: AntigravityUsageCommandResult): AntigravityUsageOutcome { + const combined = `${result.stderr}\n${result.stdout}`; + if (UNSUPPORTED_USAGE_PATTERN.test(combined)) { + return { kind: "other", error: ANTIGRAVITY_USAGE_UPDATE_MESSAGE }; + } + if (AUTH_ERROR_PATTERN.test(combined)) { + return { kind: "auth", error: SIGN_IN_MESSAGE }; + } + if (RATE_LIMIT_PATTERN.test(combined)) { + return { kind: "rate_limit", error: RATE_LIMITED_MESSAGE }; + } + if (result.timedOut || result.exitCode !== 0) { + return { kind: "transient", error: COULD_NOT_REACH_MESSAGE }; + } + return { kind: "other", error: UNEXPECTED_MESSAGE }; +} + +export function createAntigravityUsageProbe(options: { + env?: NodeJS.ProcessEnv; + dataDir?: string; + platform?: NodeJS.Platform; + resolveRuntime?: (binaryPath: string | undefined, env: NodeJS.ProcessEnv, baseDir: string) => Promise; + runCommand?: AntigravityUsageCommandRunner; +} = {}): AntigravityUsageProbe { + const baseEnv = options.env ?? process.env; + const dataDir = options.dataDir ?? DATA_DIR; + const platform = options.platform ?? process.platform; + const resolveRuntime = options.resolveRuntime ?? resolveAntigravityRuntime; + const runCommand = options.runCommand ?? runAntigravityUsageCommand; + + return async (account, callOptions): Promise => { + const { profileDir, tokenPath } = await resolveProfileToken(account, dataDir); + const usageHome = antigravityUsageHome(profileDir); + const usageTokenPath = antigravityUsageTokenPath(profileDir); + + if (!tokenPath) { + await rm(usageTokenPath, { force: true }).catch(() => {}); + return { kind: "auth", error: SIGN_IN_MESSAGE }; + } + + const mergedEnv: NodeJS.ProcessEnv = { ...baseEnv, ...account.environment }; + let runtime: AntigravityRuntime; + try { + runtime = await resolveRuntime(account.cli, mergedEnv, dataDir); + } catch (error) { + if (error instanceof AntigravitySetupError) { + return { kind: "other", error: error.message }; + } + return { kind: "transient", error: COULD_NOT_REACH_MESSAGE }; + } + + if (runtime.version !== null && compareSemver(runtime.version, ANTIGRAVITY_USAGE_MIN_VERSION) < 0) { + return { kind: "other", error: ANTIGRAVITY_USAGE_UPDATE_MESSAGE }; + } + + try { + await withAntigravitySignInGate(tokenPath, async () => { + await mkdir(dirname(usageTokenPath), { recursive: true, mode: 0o700 }); + await copyFile(tokenPath, usageTokenPath); + if (platform !== "win32") await chmod(usageTokenPath, 0o600); + }); + } catch { + return { kind: "transient", error: COULD_NOT_REACH_MESSAGE }; + } + + let tempDirectory: string | undefined; + if (platform === "win32") { + tempDirectory = resolve(antigravityTempDir(dataDir, account.id)); + await mkdir(tempDirectory, { recursive: true }).catch(() => {}); + scheduleAntigravityTempSweep(account.id, { dataDir }); + } + + const result = await runCommand({ + executablePath: runtime.executablePath, + args: ["usage", "--json"], + cwd: usageHome, + env: antigravityUsageEnvironment(mergedEnv, usageHome, { platform, tempDirectory }), + timeoutMs: callOptions?.timeoutMs ?? USAGE_TIMEOUT_MS, + }); + + if (result.timedOut || result.exitCode !== 0) { + return classifyCliFailure(result); + } + + const parsed = parseAntigravityCliUsage(parseJson(result.stdout.trim())); + if (parsed) return { kind: "ok", windows: parsed }; + return classifyCliFailure(result); + }; +} diff --git a/server/plan-usage-credentials.ts b/server/plan-usage-credentials.ts index 09ffaf971c..391a48d37f 100644 --- a/server/plan-usage-credentials.ts +++ b/server/plan-usage-credentials.ts @@ -4,12 +4,6 @@ import { homedir } from "node:os"; import { join, relative, resolve, isAbsolute } from "node:path"; import { DATA_DIR } from "./config.ts"; -import { - ANTIGRAVITY_APP_DATA_DIR, - ANTIGRAVITY_CLI_TOKEN_FILE, - ANTIGRAVITY_LEGACY_TOKEN_FILE, - antigravityProfileDirectory, -} from "./drivers/antigravity-acp.ts"; import { resolveClaudeConfigDir } from "./drivers/claude.ts"; import { codexHome } from "./drivers/codex-identity.ts"; import { harnessHome, sealedFixture, userHome } from "./env-path.ts"; @@ -23,7 +17,6 @@ import { readCursorStateDb, readDarwinKeychain, readOpenCodeGoDbKey, - type AntigravityRenewalTarget, type ClaudeRenewalTarget, } from "./plan-usage-renewal.ts"; import { @@ -48,7 +41,6 @@ const CLAUDE_KEYCHAIN_SERVICE = "Claude Code-credentials"; export function fileCredentialReader(source: CredentialSource): CredentialReader { const env = source.env ?? process.env; const now = source.now ?? Date.now; - const dataDir = source.dataDir ?? DATA_DIR; return { async read(account) { const merged: NodeJS.ProcessEnv = { ...env, ...account.environment }; @@ -56,7 +48,7 @@ export function fileCredentialReader(source: CredentialSource): CredentialReader if (account.driver === "claude") return readClaudeCredential(account, merged, source, at); if (account.driver === "codex") return readCodexCredential(merged, source, at); if (account.driver === "grok") return readGrokCredential(merged, source, at); - if (account.driver === "antigravity") return readAntigravityCredential(account, merged, source, at, dataDir); + if (account.driver === "antigravity") return missingCredential(); if (account.driver === "cursor") return readCursorCredential(merged, source, at); return readOpenCodeCredential(merged, source); }, @@ -312,64 +304,6 @@ function readGrokCredential( return missingCredential(); } -function parseAntigravityTokenFile(raw: string | null, now: number): PlanCredential { - if (!raw) return missingCredential(); - let text = raw.trim(); - if (!text) return missingCredential(); - if (text.startsWith("go-keyring-base64:")) { - try { - text = Buffer.from(text.slice("go-keyring-base64:".length), "base64").toString("utf8").trim(); - } catch { - return missingCredential(); - } - } - const parsed = asRecord(parseJson(text)); - if (!parsed) return missingCredential(); - const tokenObj = asRecord(parsed.token) ?? parsed; - const token = secretString(tokenObj.access_token); - const refreshToken = secretString(tokenObj.refresh_token) ?? secretString(parsed.refresh_token); - if (!token && !refreshToken) return missingCredential(); - const clientId = secretString(parsed.client_id) ?? undefined; - const clientSecret = secretString(parsed.client_secret) ?? undefined; - const store: AntigravityRenewalTarget = { - kind: "antigravity-memory", - ...(clientId ? { clientId } : {}), - ...(clientSecret ? { clientSecret } : {}), - }; - const expiry = timeMs(tokenObj.expiry ?? tokenObj.expires_at ?? tokenObj.expiresAt); - const expired = !token || (expiry != null && expiry <= now + 60_000); - if (expired && !refreshToken) return expiredCredential(); - return { token, accountId: null, expired, refreshToken, store }; -} - -function readAntigravityCredential( - account: PlanAccount, - _env: NodeJS.ProcessEnv, - source: CredentialSource, - now: number, - dataDir: string, -): PlanCredential { - // Antigravity strips inherited host GEMINI_HOME; only an instance's own environment overrides its Dusk profile dir. - const customHome = account.environment.GEMINI_HOME?.trim(); - const paths = customHome - ? [ - join(customHome, ANTIGRAVITY_APP_DATA_DIR, ANTIGRAVITY_CLI_TOKEN_FILE), - join(customHome, ANTIGRAVITY_APP_DATA_DIR, ANTIGRAVITY_LEGACY_TOKEN_FILE), - join(customHome, "jetski-standalone-oauth-token"), - ] - : [ - join(antigravityProfileDirectory(account.id, dataDir), ANTIGRAVITY_APP_DATA_DIR, ANTIGRAVITY_CLI_TOKEN_FILE), - join(antigravityProfileDirectory(account.id, dataDir), ANTIGRAVITY_APP_DATA_DIR, ANTIGRAVITY_LEGACY_TOKEN_FILE), - ]; - let sawExpired: PlanCredential | null = null; - for (const path of paths) { - const parsed = parseAntigravityTokenFile(source.readText(path), now); - if ((parsed.token && !parsed.expired) || parsed.refreshToken) return parsed; - if (parsed.expired && !sawExpired) sawExpired = parsed; - } - return sawExpired ?? missingCredential(); -} - function formatCursorMembership(value: string | null | undefined): string | null { if (!value) return null; const cleaned = value.trim().replace(/^unified_/i, ""); diff --git a/server/plan-usage-parsers.ts b/server/plan-usage-parsers.ts index 8bfa3bb818..355fb848f6 100644 --- a/server/plan-usage-parsers.ts +++ b/server/plan-usage-parsers.ts @@ -30,8 +30,6 @@ const MONTH_MIN_SECONDS = 27 * 86400; const MONTH_MAX_SECONDS = 32 * 86400; const WEEK_MS = 7 * 86_400_000; -export const antigravityWeeklyResets = new Set(); - export function parseClaudeUsage(body: unknown, fallbackPlan: string | null = null): PlanWindows { const root = claudeRoot(body); let fiveHour = closedWindow(); @@ -144,100 +142,85 @@ interface AntigravityBucket { resetsAt: string | null; } -export function parseAntigravitySummary(bodies: readonly unknown[]): PlanWindows | null { +const ANTIGRAVITY_BUCKET_IDS = new Set([ + "gemini-5h", + "gemini-weekly", + "3p-5h", + "3p-weekly", + "argon-weekly", +]); + +function antigravityResetIso(value: unknown): string | null { + const ms = timeMs(value); + // Antigravity CLI 1.5.22+ reports the Unix epoch for untouched buckets whose window has not started. + if (ms == null || ms <= 0) return null; + const date = new Date(ms); + return Number.isNaN(date.getTime()) ? null : date.toISOString(); +} + +function antigravityWindowLabel(windowKind: string, fallbackName: string): string { + if (windowKind === "5h") return "5-hour"; + if (windowKind === "weekly") return "Weekly"; + return fallbackName || "Quota"; +} + +/** Parses `agy usage --json` output (Antigravity CLI 1.5.22+). */ +export function parseAntigravityCliUsage(body: unknown): PlanWindows | null { + const root = asRecord(body); + if (!root || root.status !== "SUCCESS") return null; + const command = asRecord(root.command); + if (!command || command.name !== "usage") return null; + const data = asRecord(command.data); + const groups = Array.isArray(data?.groups) ? data.groups : null; + if (!groups) return null; + const found = new Map(); + const extraModels: PlanModelUsage[] = []; const recordBucket = (id: AntigravityBucket["id"], left: number, resetsAt: string | null) => { const existing = found.get(id); if (existing && !(existing.remaining >= 1 && left < 1)) return; found.set(id, { id, used: Math.round((1 - left) * 100), remaining: left, resetsAt }); }; - for (const rawBody of bodies) { - const body = asRecord(rawBody); - const groups = Array.isArray(body?.groups) ? body.groups : []; - for (const rawGroup of groups) { - const group = asRecord(rawGroup); - if (!group) continue; - const isArgon = group.displayName === "Gemini 4 Argon"; - const buckets = Array.isArray(group.buckets) ? group.buckets : []; - for (const rawBucket of buckets) { - const bucket = asRecord(rawBucket); - if (!bucket || bucket.disabled === true) continue; - const rawLeft = numericValue(bucket.remainingFraction); - if (rawLeft == null) continue; - const left = Math.min(Math.max(rawLeft, 0), 1); - const resetsAt = isoOrNull(bucket.resetTime); - if (isArgon) { - if (bucket.window === "weekly") recordBucket("argon-weekly", left, resetsAt); - } else if ( - bucket.bucketId === "gemini-5h" || - bucket.bucketId === "gemini-weekly" || - bucket.bucketId === "3p-5h" || - bucket.bucketId === "3p-weekly" - ) { - recordBucket(bucket.bucketId, left, resetsAt); - } + + for (const rawGroup of groups) { + const group = asRecord(rawGroup); + if (!group) continue; + const groupName = typeof group.name === "string" && group.name.trim() + ? group.name.trim() + : typeof group.displayName === "string" ? group.displayName.trim() : ""; + const isArgon = groupName.toLowerCase().includes("argon"); + const buckets = Array.isArray(group.buckets) ? group.buckets : []; + for (const rawBucket of buckets) { + const bucket = asRecord(rawBucket); + if (!bucket || bucket.disabled === true) continue; + const rawLeft = numericValue(bucket.remaining_fraction ?? bucket.remainingFraction); + if (rawLeft == null) continue; + const left = Math.min(Math.max(rawLeft, 0), 1); + const resetsAt = antigravityResetIso(bucket.reset_time ?? bucket.resetTime); + const rawId = typeof bucket.id === "string" && bucket.id.trim() + ? bucket.id.trim() + : typeof bucket.bucketId === "string" ? bucket.bucketId.trim() : ""; + const windowKind = typeof bucket.window === "string" ? bucket.window.trim().toLowerCase() : ""; + if ((isArgon || rawId.toLowerCase().includes("argon")) && (windowKind === "weekly" || rawId === "argon-weekly")) { + recordBucket("argon-weekly", left, resetsAt); + } else if (ANTIGRAVITY_BUCKET_IDS.has(rawId as AntigravityBucket["id"])) { + recordBucket(rawId as AntigravityBucket["id"], left, resetsAt); + } else { + const bucketName = typeof bucket.name === "string" ? bucket.name.trim() : ""; + const label = antigravityWindowLabel(windowKind, bucketName); + addModelWindow(extraModels, groupName || "Antigravity", extraLine(label, openWindow(Math.round((1 - left) * 100), resetsAt))); } } } - if (!found.size) return null; - return antigravityWindowsFromBuckets(found, null); -} - -export function parseAntigravityModels( - modelsNode: unknown, - now = Date.now(), - rememberedWeekly: ReadonlySet = antigravityWeeklyResets, -): PlanWindows | null { - const modelsRecord = asRecord(modelsNode); - if (!modelsRecord) return null; - const found = new Map(); - for (const [key, rawModel] of Object.entries(modelsRecord)) { - const model = asRecord(rawModel); - if (!model || model.isInternal === true) continue; - const name = typeof model.displayName === "string" && model.displayName.trim() - ? model.displayName.trim() - : typeof model.label === "string" && model.label.trim() ? model.label.trim() : ""; - const quota = asRecord(model.quotaInfo); - if (!name || !quota) continue; - if (name.toLowerCase().includes("argon") || key.toLowerCase().includes("argon")) continue; - // Protobuf omits zero remainingFraction, so a quotaInfo block without remainingFraction is 100% used. - const left = Math.min(Math.max(numericValue(quota.remainingFraction) ?? 0, 0), 1); - const resetMs = timeMs(quota.resetTime); - const resetsAt = resetMs != null ? new Date(resetMs).toISOString() : null; - const weekly = resetMs != null && (resetMs - now > 5 * 3600_000 + 600_000 || rememberedWeekly.has(resetMs)); - const gemini = name.toLowerCase().includes("gemini"); - const id: AntigravityBucket["id"] = gemini - ? (weekly ? "gemini-weekly" : "gemini-5h") - : (weekly ? "3p-weekly" : "3p-5h"); - const used = Math.round((1 - left) * 100); - const existing = found.get(id); - if (existing && existing.used >= used) continue; - found.set(id, { id, used, remaining: left, resetsAt }); - } - if (!found.size) return null; - return antigravityWindowsFromBuckets(found, null); -} -export function parseAntigravityPlan(body: unknown): string | null { - const root = asRecord(body); - if (!root) return null; - const known: Record = { - "g1-pro-tier": "Pro", - "g1-ultra-tier": "Ultra", - "g1-ultra-lite-tier": "Ultra Lite", - "free-tier": "Free", - }; - const paid = asRecord(root.paidTier); - const current = asRecord(root.currentTier); - for (const tier of [paid, current]) { - const id = typeof tier?.id === "string" ? tier.id.trim() : ""; - if (id && known[id]) return known[id]; + if (!found.size && !extraModels.length) return null; + const plan = planLabel(data?.plan ?? data?.tier); + const windows = antigravityWindowsFromBuckets(found, plan); + for (const model of extraModels) { + for (const entry of model.windows) addModelWindow(windows.models, model.name, entry); } - const rawName = typeof paid?.name === "string" && paid.name.trim() - ? paid.name.trim() - : typeof current?.name === "string" && current.name.trim() ? current.name.trim() : ""; - if (!rawName) return null; - return planLabel(rawName.startsWith("Google AI ") ? rawName.slice("Google AI ".length) : rawName); + sortModelWindows(windows.models); + return windows; } function antigravityWindowsFromBuckets( diff --git a/server/plan-usage-renewal.ts b/server/plan-usage-renewal.ts index f848670df1..001bf8a0ca 100644 --- a/server/plan-usage-renewal.ts +++ b/server/plan-usage-renewal.ts @@ -38,13 +38,7 @@ export interface ClaudeRenewalTarget { account?: string; } -export interface AntigravityRenewalTarget { - kind: "antigravity-memory"; - clientId?: string; - clientSecret?: string; -} - -export type CredentialStoreTarget = ClaudeRenewalTarget | AntigravityRenewalTarget; +export type CredentialStoreTarget = ClaudeRenewalTarget; export const CLAUDE_USER_AGENT = "claude-cli/2.1.294 (external, cli)"; const CLAUDE_TOKEN_URL = "https://platform.claude.com/v1/oauth/token"; @@ -58,12 +52,6 @@ const CLAUDE_DEFAULT_SCOPES = [ "user:plugins", ]; -const GOOGLE_TOKEN_URL = "https://oauth2.googleapis.com/token"; -// Installed desktop/CLI OAuth client shipped in Antigravity and `agy`; Google treats installed-app secrets as non-confidential. -const ANTIGRAVITY_CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep.apps.googleusercontent.com"; -const ANTIGRAVITY_CLIENT_SECRET = ["GOCSPX", "K58FWR486LdLJ1mLB8sXC4z6qDAf"].join("-"); -const ANTIGRAVITY_DEFAULT_VERSION = "2.33.0"; - const KEYCHAIN_TIMEOUT_MS = 4_000; const KEYCHAIN_MAX_BUFFER = 1_000_000; const KEYCHAIN_REFUSAL_TTL_MS = 5 * 60_000; @@ -72,15 +60,11 @@ const SECURITY_INTERACTIVE_MAX_LINE = 4032; const RENEWAL_TIMEOUT_MS = 10_000; const rejectedRefreshes = new Set(); -const antigravityMemoryTokens = new Map(); const keychainRefusals = new Map(); -let cachedAntigravityAgent: string | null = null; export function clearPlanUsageRenewalState(): void { rejectedRefreshes.clear(); - antigravityMemoryTokens.clear(); keychainRefusals.clear(); - cachedAntigravityAgent = null; } function sha256Prefix(value: string, hexChars = 16): string { @@ -302,46 +286,6 @@ export function readOpenCodeGoDbKey(opencodeDataDir: string): string | null { return null; } -function versionNewerThan(candidate: string, baseline: string): boolean { - const parts = (raw: string): number[] | null => { - const split = raw.split("."); - if (split.length < 2) return null; - const out: number[] = []; - for (const part of split) { - if (!/^\d+$/.test(part)) return null; - out.push(Number(part)); - } - return out; - }; - const left = parts(candidate); - const right = parts(baseline); - if (!left || !right) return false; - const len = Math.max(left.length, right.length); - for (let i = 0; i < len; i += 1) { - const a = left[i] ?? 0; - const b = right[i] ?? 0; - if (a !== b) return a > b; - } - return false; -} - -/** Google drops paid tier and Gemini quota pools when the User-Agent does not match a recent Antigravity build. */ -export function antigravityUserAgent(): string { - if (cachedAntigravityAgent) return cachedAntigravityAgent; - let version = ANTIGRAVITY_DEFAULT_VERSION; - if (process.platform === "darwin") { - try { - const plist = readFileSync("/Applications/Antigravity.app/Contents/Info.plist", "utf8"); - const match = /CFBundleShortVersionString<\/key>\s*([^<]+)<\/string>/.exec(plist); - if (match?.[1] && versionNewerThan(match[1].trim(), version)) version = match[1].trim(); - } catch {} - } - const osType = process.platform === "darwin" ? "darwin" : process.platform === "win32" ? "windows" : "linux"; - const arch = process.arch === "arm64" ? "arm64" : "amd64"; - cachedAntigravityAgent = `antigravity/${version} (aidev_client; os_type=${osType}; arch=${arch})`; - return cachedAntigravityAgent; -} - /** Directory lock matching proper-lockfile semantics used by Claude Code 2.1. */ class FolderLock { readonly path: string; @@ -421,21 +365,6 @@ async function postJson(fetchImpl: PlanFetchFn, url: string, headers: Record, timeoutMs: number) { - try { - const response = await fetchImpl(url, { - method: "POST", - headers: { "Content-Type": "application/x-www-form-urlencoded", Accept: "application/json" }, - body: new URLSearchParams(form).toString(), - signal: AbortSignal.timeout(timeoutMs), - }); - const text = await response.text().catch(() => ""); - return { ok: response.ok, status: response.status, body: parseJsonObject(text) }; - } catch { - return null; - } -} - function readJsonFile(path: string): Record | null { try { return parseJsonObject(readFileSync(path, "utf8")); @@ -575,44 +504,3 @@ export async function renewClaudeToken(input: { for (const lock of locks.reverse()) lock.release(); } } - -/** Renews a Google OAuth token in memory only: Google does not rotate refresh tokens, so disk files stay untouched. */ -export async function renewAntigravityToken(input: { - refreshToken: string; - target?: AntigravityRenewalTarget; - force?: boolean; - fetch: PlanFetchFn; - now?: () => number; - timeoutMs?: number; -}): Promise { - const now = input.now ?? Date.now; - const hash = `antigravity:${sha256Prefix(input.refreshToken)}`; - if (rejectedRefreshes.has(hash)) return { status: "rejected" }; - const cached = antigravityMemoryTokens.get(hash); - if (!input.force && cached && cached.expiresAt > now() + 60_000) { - return { status: "renewed", token: cached.token, expiresAt: cached.expiresAt }; - } - const response = await postForm( - input.fetch, - GOOGLE_TOKEN_URL, - { - client_id: input.target?.clientId || ANTIGRAVITY_CLIENT_ID, - client_secret: input.target?.clientSecret || ANTIGRAVITY_CLIENT_SECRET, - refresh_token: input.refreshToken, - grant_type: "refresh_token", - }, - input.timeoutMs ?? RENEWAL_TIMEOUT_MS, - ); - if (!response) return { status: "unchanged" }; - if (response.status === 400 || response.status === 401) { - rejectedRefreshes.add(hash); - antigravityMemoryTokens.delete(hash); - return { status: "rejected" }; - } - const token = response.ok ? nonEmptySecret(response.body?.access_token) : null; - if (!token) return { status: "unchanged" }; - const lifetime = numericSeconds(response.body?.expires_in) ?? 3600; - const expiresAt = Math.round(now() + lifetime * 1000); - antigravityMemoryTokens.set(hash, { token, expiresAt }); - return { status: "renewed", token, expiresAt }; -} diff --git a/server/plan-usage-types.ts b/server/plan-usage-types.ts index 89aae270eb..e0273f245b 100644 --- a/server/plan-usage-types.ts +++ b/server/plan-usage-types.ts @@ -69,6 +69,7 @@ export interface PlanAccount { driver: PlanDriver; environment: Record; configDir?: string; + cli?: string; /** Signed in through dusk bot (ChatGPT plan), not a CLI login on disk, so it has no usage reading. */ noUsage?: true; } @@ -90,9 +91,23 @@ export type PlanResponse = PlanHttpResponse; export type PlanFetch = (url: string, init: PlanFetchInit) => Promise; +export type AntigravityUsageOutcome = + | { kind: "ok"; windows: PlanWindows } + | { kind: "auth"; error: string } + | { kind: "rate_limit"; error: string; retryAfterMs?: number | null } + | { kind: "transient"; error: string } + | { kind: "other"; error: string }; + +export type AntigravityUsageProbe = ( + account: PlanAccount, + options?: { timeoutMs?: number }, +) => Promise; + export interface PlanUsageDeps { fetch: PlanFetch; credentials: CredentialReader; + antigravityUsage?: AntigravityUsageProbe; + refresh?: boolean; now?: () => number; timeoutMs?: number; } diff --git a/server/plan-usage.test.ts b/server/plan-usage.test.ts index 77174b8d02..5854f1aec2 100644 --- a/server/plan-usage.test.ts +++ b/server/plan-usage.test.ts @@ -4,13 +4,12 @@ import { tmpdir } from "node:os"; import { join, normalize } from "node:path"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { + ANTIGRAVITY_USAGE_CACHE_MS, clearPlanUsageCache, fetchPlanUsage, fileCredentialReader, loadPlanUsage, - parseAntigravityModels, - parseAntigravityPlan, - parseAntigravitySummary, + parseAntigravityCliUsage, parseClaudeUsage, parseCodexUsage, parseCursorDashboardUsage, @@ -18,11 +17,11 @@ import { parseGrokUsage, parseOpenCodeUsage, planAccountsFromInstances, + type AntigravityUsageProbe, type PlanAccount, type PlanFetch, type PlanResponse, } from "./plan-usage.ts"; -import { antigravityProfileDirectory } from "./drivers/antigravity-acp.ts"; import { asciiJson, codexKeychainItem, codexUsesKeyring, readCursorStateDb, readOpenCodeGoDbKey, renewClaudeToken } from "./plan-usage-renewal.ts"; import { DatabaseSync } from "node:sqlite"; @@ -518,7 +517,7 @@ describe("plan usage fetcher", () => { claude: { driver: "claudeAgent", displayName: " Personal Claude ", config: { configDir: "/tmp/claude" } }, codex: { driver: "codex" }, grok: { driver: "grokAgent", environment: { GROK_HOME: "/tmp/grok" } }, - antigravity: { driver: "antigravityAgent" }, + antigravity: { driver: "antigravityAgent", config: { cli: "/opt/agy" } }, cursor: { driver: "cursorAgent", displayName: "Cursor" }, opencodeGo: { driver: "opencodeGo" }, mistral: { driver: "mistral", displayName: "Mistral" }, @@ -527,7 +526,7 @@ describe("plan usage fetcher", () => { { id: "claude", name: "Personal Claude", driver: "claude", environment: {}, configDir: "/tmp/claude" }, { id: "codex", name: "Codex", driver: "codex", environment: {} }, { id: "grok", name: "Grok", driver: "grok", environment: { GROK_HOME: "/tmp/grok" } }, - { id: "antigravity", name: "Antigravity", driver: "antigravity", environment: {} }, + { id: "antigravity", name: "Antigravity", driver: "antigravity", environment: {}, cli: "/opt/agy" }, { id: "cursor", name: "Cursor", driver: "cursor", environment: {} }, { id: "opencodeGo", name: "OpenCode Go", driver: "opencode", environment: {} }, ]); @@ -746,95 +745,115 @@ describe("plan usage fetcher", () => { expect(parsed.weekly).toMatchObject({ available: true, usedPercent: 0, remainingPercent: 100, resetsAt: "2026-10-08T00:00:00.000Z" }); }); - it("fetches Antigravity limits across both hosts with in-memory Google OAuth renewal and model fallback", async () => { - const dataDir = makeTempDir("dusk-ag-data-"); - const profileDir = antigravityProfileDirectory("antigravity", dataDir); - const tokenPath = join(profileDir, "antigravity-acp", "antigravity-oauth-token"); - const refreshSecret = "ag-refresh-secret"; - const freshAccess = "ag-fresh-access-secret"; - - const fetchImpl = vi.fn(async (url, init) => { - if (url === "https://oauth2.googleapis.com/token") { - expect(init.body).toContain(`refresh_token=${refreshSecret}`); - return jsonResponse({ access_token: freshAccess, expires_in: 3600 }); - } - expect(init.headers["User-Agent"]).toMatch(/^antigravity\//); - expect(init.headers.Authorization).toBe(`Bearer ${freshAccess}`); - if (url === "https://daily-cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary") { - return jsonResponse({ + it("reads Antigravity limits through the CLI probe with 5-minute caching and zero internal HTTP calls", async () => { + const cliPayload = { + status: "SUCCESS", + command: { + name: "usage", + data: { groups: [ { - displayName: "Gemini", + name: "Gemini", buckets: [ - { bucketId: "gemini-5h", remainingFraction: 1, resetTime: "2026-10-26T15:00:00Z" }, - { bucketId: "gemini-weekly", remainingFraction: 0.7, resetTime: "2026-11-01T00:00:00Z" }, + { id: "gemini-5h", window: "5h", remaining_fraction: 0.8, reset_time: new Date(NOW + 2 * 3600_000).toISOString() }, + { id: "gemini-weekly", window: "weekly", remaining_fraction: 0.7, reset_time: new Date(NOW + 5 * 86_400_000).toISOString() }, ], }, { - displayName: "Gemini 4 Argon", - buckets: [{ window: "weekly", remainingFraction: 0.5, resetTime: "2026-11-01T00:00:00Z" }], - }, - ], - }); - } - if (url === "https://cloudcode-pa.googleapis.com/v1internal:retrieveUserQuotaSummary") { - return jsonResponse({ - groups: [ - { - displayName: "Gemini", + name: "Claude & GPT", buckets: [ - { bucketId: "gemini-5h", remainingFraction: 0.8, resetTime: "2026-10-26T14:00:00Z" }, - { bucketId: "3p-weekly", remainingFraction: 0.6, resetTime: "2026-11-01T00:00:00Z" }, + { id: "3p-5h", window: "5h", remaining_fraction: 1, reset_time: "1970-01-01T00:00:00Z" }, + { id: "3p-weekly", window: "weekly", remaining_fraction: 0.6, reset_time: new Date(NOW + 5 * 86_400_000).toISOString() }, ], }, + { + name: "Gemini 4 Argon", + buckets: [{ id: "argon-weekly", window: "weekly", remaining_fraction: 0.5, reset_time: new Date(NOW + 5 * 86_400_000).toISOString() }], + }, ], - }); - } - if (url.endsWith("/v1internal:loadCodeAssist")) { - return jsonResponse({ paidTier: { id: "g1-pro-tier", name: "Google AI Pro" } }); - } - return jsonResponse({}, 404); + }, + }, + }; + const parsed = parseAntigravityCliUsage(cliPayload); + expect(parsed).toMatchObject({ + plan: null, + fiveHour: { available: true, usedPercent: 20, remainingPercent: 80 }, + weekly: { available: true, usedPercent: 30, remainingPercent: 70 }, }); + expect(parsed?.models).toEqual([ + { + name: "Claude & GPT", + windows: [ + expect.objectContaining({ label: "5-hour", usedPercent: 0, resetsAt: null }), + expect.objectContaining({ label: "Weekly", usedPercent: 40 }), + ], + }, + { name: "Gemini 4 Argon", windows: [expect.objectContaining({ label: "Weekly", usedPercent: 50 })] }, + ]); + expect(parseAntigravityCliUsage({ status: "ERROR", command: { name: "usage", data: { groups: [] } } })).toBeNull(); + expect(parseAntigravityCliUsage({ status: "SUCCESS", command: { name: "usage", data: { groups: [] } } })).toBeNull(); - const report = await fetchPlanUsage([account("antigravity")], { - fetch: fetchImpl, - now: () => NOW, - credentials: fileCredentialReader({ - now: () => NOW, - dataDir, - readText: (path) => (path === tokenPath - ? JSON.stringify({ token: { access_token: "expired-ag", refresh_token: refreshSecret, expiry: new Date(NOW - 60_000).toISOString() } }) - : null), - }), + const fetchImpl = vi.fn(async () => jsonResponse({}, 500)); + let usedFraction = 0.8; + const probe = vi.fn(async () => { + const windows = parseAntigravityCliUsage({ + ...cliPayload, + command: { + name: "usage", + data: { + groups: [ + { + name: "Gemini", + buckets: [ + { id: "gemini-5h", window: "5h", remaining_fraction: usedFraction, reset_time: new Date(NOW + 2 * 3600_000).toISOString() }, + { id: "gemini-weekly", window: "weekly", remaining_fraction: 0.7, reset_time: new Date(NOW + 5 * 86_400_000).toISOString() }, + ], + }, + ], + }, + }, + })!; + return { kind: "ok", windows }; }); - expect(report.providers[0]).toMatchObject({ + const accounts = [account("antigravity")]; + const first = await loadPlanUsage({ accounts, now: NOW, fetch: fetchImpl, antigravityUsage: probe }); + expect(first.providers[0]).toMatchObject({ id: "antigravity", driver: "antigravity", ok: true, - plan: "Pro", - fiveHour: { available: true, usedPercent: 20, remainingPercent: 80, resetsAt: "2026-10-26T14:00:00.000Z" }, - weekly: { available: true, usedPercent: 30, remainingPercent: 70, resetsAt: "2026-11-01T00:00:00.000Z" }, + fiveHour: { available: true, usedPercent: 20, remainingPercent: 80 }, + weekly: { available: true, usedPercent: 30, remainingPercent: 70 }, }); - expect(report.providers[0]?.models).toEqual([ - { name: "Claude & GPT", windows: [expect.objectContaining({ label: "Weekly", usedPercent: 40 })] }, - { name: "Gemini 4 Argon", windows: [expect.objectContaining({ label: "Weekly", usedPercent: 50 })] }, - ]); - expect(JSON.stringify(report)).not.toContain(refreshSecret); - expect(JSON.stringify(report)).not.toContain(freshAccess); - - // Fallback model parser treats missing remainingFraction as 100% used and classifies by reset distance. - const fromModels = parseAntigravityModels({ - "gemini-3-pro": { displayName: "Gemini 3 Pro", quotaInfo: { resetTime: new Date(NOW + 2 * 3600_000).toISOString() } }, - "claude-sonnet": { displayName: "Claude Sonnet", quotaInfo: { remainingFraction: 0.25, resetTime: new Date(NOW + 4 * 86_400_000).toISOString() } }, - internal: { displayName: "Gemini Internal", isInternal: true, quotaInfo: { remainingFraction: 0 } }, - }, NOW, new Set()); - expect(fromModels?.fiveHour).toMatchObject({ available: true, usedPercent: 100 }); - expect(fromModels?.models).toEqual([ - { name: "Claude & GPT", windows: [expect.objectContaining({ label: "Weekly", usedPercent: 75 })] }, - ]); - expect(parseAntigravityPlan({ currentTier: { name: "Google AI Ultra" } })).toBe("Ultra"); - expect(parseAntigravitySummary([])).toBeNull(); + expect(fetchImpl).not.toHaveBeenCalled(); + expect(probe).toHaveBeenCalledTimes(1); + + // Past the 45s report cache but within Antigravity's 5-minute window: reuses the cached CLI reading. + usedFraction = 0.5; + const cached = await loadPlanUsage({ accounts, now: NOW + 60_000, fetch: fetchImpl, antigravityUsage: probe }); + expect(probe).toHaveBeenCalledTimes(1); + expect(cached.providers[0]?.fiveHour.usedPercent).toBe(20); + + // Explicit refresh bypasses the 5-minute cache and spawns a fresh probe. + const refreshed = await loadPlanUsage({ accounts, refresh: true, now: NOW + 61_000, fetch: fetchImpl, antigravityUsage: probe }); + expect(probe).toHaveBeenCalledTimes(2); + expect(refreshed.providers[0]?.fiveHour.usedPercent).toBe(50); + + // Past the 5-minute cache window, a normal read refreshes again. + usedFraction = 0.4; + const aged = await loadPlanUsage({ accounts, now: NOW + 61_000 + ANTIGRAVITY_USAGE_CACHE_MS, fetch: fetchImpl, antigravityUsage: probe }); + expect(probe).toHaveBeenCalledTimes(3); + expect(aged.providers[0]?.fiveHour.usedPercent).toBe(60); + + // Transient failure falls back to last-good windows; auth failure clears them. + probe.mockResolvedValueOnce({ kind: "transient", error: "Could not reach Antigravity" }); + const transient = await loadPlanUsage({ accounts, refresh: true, now: NOW + 62_000 + ANTIGRAVITY_USAGE_CACHE_MS, fetch: fetchImpl, antigravityUsage: probe }); + expect(transient.providers[0]).toMatchObject({ ok: true, fiveHour: { usedPercent: 60 } }); + + probe.mockResolvedValueOnce({ kind: "auth", error: "Sign in again in Antigravity" }); + const signedOut = await loadPlanUsage({ accounts, refresh: true, now: NOW + 63_000 + ANTIGRAVITY_USAGE_CACHE_MS, fetch: fetchImpl, antigravityUsage: probe }); + expect(signedOut.providers[0]).toMatchObject({ ok: false, error: "Sign in again in Antigravity" }); + expect(fetchImpl).not.toHaveBeenCalled(); }); it("fetches Cursor Connect-RPC monthly and weekly plans, plus Team dashboard fallback and isolated CURSOR_CONFIG_DIR", async () => { diff --git a/server/plan-usage.ts b/server/plan-usage.ts index b293e30349..b0e83040bb 100644 --- a/server/plan-usage.ts +++ b/server/plan-usage.ts @@ -2,15 +2,16 @@ import { createHash } from "node:crypto"; import type { InstanceConfigMap } from "./contracts.ts"; +import { + ANTIGRAVITY_USAGE_CACHE_MS, + createAntigravityUsageProbe, +} from "./drivers/antigravity-usage.ts"; import { defaultCredentialReader, fileCredentialReader, } from "./plan-usage-credentials.ts"; import { - antigravityWeeklyResets, - parseAntigravityModels, - parseAntigravityPlan, - parseAntigravitySummary, + parseAntigravityCliUsage, parseClaudeUsage, parseCodexUsage, parseCursorDashboardUsage, @@ -19,11 +20,9 @@ import { parseOpenCodeUsage, } from "./plan-usage-parsers.ts"; import { - antigravityUserAgent, CLAUDE_USER_AGENT, clearPlanUsageRenewalState, jwtSubject, - renewAntigravityToken, renewClaudeToken, type PlanFetchInit, type PlanHttpResponse, @@ -31,7 +30,8 @@ import { import { asRecord, closedWindow, - timeMs, + type AntigravityUsageOutcome, + type AntigravityUsageProbe, type CredentialReader, type CredentialSource, type PlanAccount, @@ -50,17 +50,18 @@ import { } from "./plan-usage-types.ts"; export { + ANTIGRAVITY_USAGE_CACHE_MS, defaultCredentialReader, fileCredentialReader, - parseAntigravityModels, - parseAntigravityPlan, - parseAntigravitySummary, + parseAntigravityCliUsage, parseClaudeUsage, parseCodexUsage, parseCursorDashboardUsage, parseCursorUsage, parseGrokUsage, parseOpenCodeUsage, + type AntigravityUsageOutcome, + type AntigravityUsageProbe, type CredentialReader, type CredentialSource, type PlanAccount, @@ -87,10 +88,6 @@ const CODEX_USAGE_URL = "https://chatgpt.com/backend-api/wham/usage"; const GROK_CREDITS_URL = "https://cli-chat-proxy.grok.com/v1/billing?format=credits"; const GROK_BILLING_URL = "https://cli-chat-proxy.grok.com/v1/billing"; const GROK_SETTINGS_URL = "https://cli-chat-proxy.grok.com/v1/settings"; -const ANTIGRAVITY_HOSTS = [ - "https://daily-cloudcode-pa.googleapis.com", - "https://cloudcode-pa.googleapis.com", -] as const; const CURSOR_API_BASE = "https://api2.cursor.sh/aiserver.v1.DashboardService/"; const CURSOR_DASHBOARD_SUMMARY_URL = "https://cursor.com/api/usage-summary"; const CURSOR_DASHBOARD_USAGE_URL = "https://cursor.com/api/usage"; @@ -120,7 +117,7 @@ const PRODUCT_NAME: Record = { const rateLimitCooldowns = new Map(); const lastGoodRows = new Map(); -const antigravityPlanCache = new Map(); +const antigravityFreshRows = new Map(); const cursorPlanInfoCache = new Map>(); const inFlightReports = new Map>(); @@ -131,12 +128,14 @@ export function planAccountsFromInstances(instances: InstanceConfigMap): PlanAcc if (!driver) continue; const config = asRecord(entry.config); const configDir = typeof config?.configDir === "string" ? config.configDir : undefined; + const cli = typeof config?.cli === "string" ? config.cli : undefined; accounts.push({ id, name: entry.displayName?.trim() || PRODUCT_NAME[driver], driver, environment: { ...entry.environment }, ...(configDir ? { configDir } : {}), + ...(cli ? { cli } : {}), // a ChatGPT-plan provider or an API-key instance shares the signed-in account's folder: its limits are not this instance's ...(config?.authMode === "chatgpt-plan" || entry.access === "api" || config?.requireApiKey === true ? { noUsage: true as const } : {}), }); @@ -157,8 +156,7 @@ export function clearPlanUsageCache(): void { cachedReport = null; rateLimitCooldowns.clear(); lastGoodRows.clear(); - antigravityPlanCache.clear(); - antigravityWeeklyResets.clear(); + antigravityFreshRows.clear(); cursorPlanInfoCache.clear(); inFlightReports.clear(); clearPlanUsageRenewalState(); @@ -170,6 +168,7 @@ export async function loadPlanUsage(input: { now?: number; fetch?: PlanFetch; credentials?: CredentialReader; + antigravityUsage?: AntigravityUsageProbe; env?: NodeJS.ProcessEnv; dataDir?: string; timeoutMs?: number; @@ -185,6 +184,8 @@ export async function loadPlanUsage(input: { const request = fetchPlanUsage(input.accounts, { fetch: input.fetch ?? ((url, init) => globalThis.fetch(url, init)), credentials: input.credentials ?? defaultCredentialReader(input.env, input.dataDir), + antigravityUsage: input.antigravityUsage ?? createAntigravityUsageProbe({ env: input.env, dataDir: input.dataDir }), + refresh: Boolean(input.refresh), now: () => now, timeoutMs: input.timeoutMs, }).then((report) => { @@ -220,7 +221,7 @@ function planUsageCacheKey(accounts: PlanAccount[]): string { .sort(([left], [right]) => (left < right ? -1 : left > right ? 1 : 0)) .map(([name, value]) => `${name}=${value}`) .join("\n"); - return [account.id, account.driver, account.name, account.configDir ?? "", environment].join("\u0000"); + return [account.id, account.driver, account.name, account.configDir ?? "", account.cli ?? "", environment].join("\u0000"); }).join("\n"); } @@ -315,20 +316,79 @@ async function tryRenewCredential( ): Promise<{ status: "renewed"; token: string } | { status: "rejected" } | { status: "unchanged" }> { const store = credential.store; const timeoutMs = deps.timeoutMs ?? PROVIDER_TIMEOUT_MS; - if (!store || !credential.refreshToken) return { status: "unchanged" }; - if (store.kind === "antigravity-memory") { - return renewAntigravityToken({ - refreshToken: credential.refreshToken, - target: store, - force: turnedAway, - fetch: deps.fetch, - now: deps.now, - timeoutMs, - }); + if (!store || !credential.refreshToken || !credential.token) return { status: "unchanged" }; + return renewClaudeToken({ + target: store, + token: credential.token, + turnedAway, + fetch: deps.fetch, + now: deps.now, + timeoutMs, + }); +} + +function antigravityProfileKey(account: PlanAccount): string { + const customHome = account.environment.GEMINI_HOME?.trim() ?? ""; + return createHash("sha256") + .update(`antigravity\0${account.id}\0${customHome}\0${account.cli ?? ""}`) + .digest("hex"); +} + +async function fetchAntigravityProvider( + account: PlanAccount, + deps: PlanUsageDeps, + sameLogin: Map>, + now: number, +): Promise { + const loginKey = antigravityProfileKey(account); + const cachedRowOr = (fallback: PlanProviderRow): PlanProviderRow => { + const cached = lastGoodRows.get(loginKey); + return (cached ? pruneLastGoodRow(cached, account, now) : null) ?? fallback; + }; + if (deps.refresh === false) { + const fresh = antigravityFreshRows.get(loginKey); + if (fresh && now - fresh.at < ANTIGRAVITY_USAGE_CACHE_MS) { + const valid = pruneLastGoodRow(fresh.row, account, now); + if (valid) return valid; + } } - if (!credential.token) return { status: "unchanged" }; - const common = { token: credential.token, turnedAway, fetch: deps.fetch, now: deps.now, timeoutMs }; - return renewClaudeToken({ target: store, ...common }); + const cooldown = rateLimitCooldowns.get(loginKey); + if (cooldown && cooldown.until > now) return cachedRowOr(errorRow(account, rateLimitedError("antigravity"))); + + let read = sameLogin.get(loginKey); + if (!read) { + const probe = deps.antigravityUsage ?? createAntigravityUsageProbe(); + read = (async (): Promise => { + let outcome: AntigravityUsageOutcome; + try { + outcome = await probe(account, deps.timeoutMs !== undefined ? { timeoutMs: deps.timeoutMs } : undefined); + } catch { + outcome = { kind: "transient", error: couldNotReach("antigravity") }; + } + if (outcome.kind === "ok") { + const row = okRow(account, outcome.windows); + rateLimitCooldowns.delete(loginKey); + lastGoodRows.set(loginKey, row); + antigravityFreshRows.set(loginKey, { at: now, row }); + return row; + } + if (outcome.kind === "auth") { + rateLimitCooldowns.delete(loginKey); + lastGoodRows.delete(loginKey); + antigravityFreshRows.delete(loginKey); + return errorRow(account, outcome.error); + } + if (outcome.kind === "rate_limit") { + recordRateLimit(loginKey, outcome.retryAfterMs ?? null, now); + return cachedRowOr(errorRow(account, outcome.error)); + } + if (outcome.kind === "transient") return cachedRowOr(errorRow(account, outcome.error)); + return errorRow(account, outcome.error); + })(); + sameLogin.set(loginKey, read); + } + const result = await read; + return result ? { ...result, id: account.id, name: account.name } : null; } /** Accounts on one sign-in (two Claude engines on the same login) share one read: Claude's usage endpoint answers 429 to @@ -339,6 +399,9 @@ async function fetchProvider( sameLogin: Map>, ): Promise { const now = deps.now?.() ?? Date.now(); + if (account.driver === "antigravity") { + return fetchAntigravityProvider(account, deps, sameLogin, now); + } let credential: PlanCredential; try { credential = await deps.credentials.read(account); @@ -388,7 +451,7 @@ async function fetchProviderForLogin( rateLimitCooldowns.delete(loginKey); return errorRow(account, signInAgain(account.driver)); } else if (credential.expired || !token) { - return cachedRowOr(errorRow(account, account.driver === "antigravity" ? couldNotReach("antigravity") : signInAgain(account.driver))); + return cachedRowOr(errorRow(account, signInAgain(account.driver))); } } else if (credential.expired && credential.refreshToken) { // the CLI renews its own login the next time it runs; until then the last reading stands @@ -428,7 +491,7 @@ async function fetchProviderForLogin( async function fetchSignedIn( account: PlanAccount, credential: PlanCredential & { token: string }, - loginKey: string, + _loginKey: string, now: number, deps: PlanUsageDeps, ): Promise { @@ -436,7 +499,6 @@ async function fetchSignedIn( if (account.driver === "claude") return await fetchClaude(account, credential.token, credential.planHint ?? null, now, deps); if (account.driver === "codex") return await fetchCodex(account, credential.token, credential.accountId, now, deps); if (account.driver === "grok") return await fetchGrok(account, credential.token, now, deps); - if (account.driver === "antigravity") return await fetchAntigravity(account, credential.token, loginKey, now, deps); if (account.driver === "cursor") return await fetchCursor(account, credential.token, credential.planHint ?? null, now, deps); return await fetchOpenCode(account, credential.token, now, deps); } catch { @@ -575,127 +637,6 @@ async function fetchGrok( return { kind: "ok", row: okRow(account, windows) }; } -function recordAntigravityWeeklyResets(modelsNode: unknown, now: number): void { - for (const stamp of antigravityWeeklyResets) { - if (stamp <= now) antigravityWeeklyResets.delete(stamp); - } - const record = asRecord(modelsNode); - if (!record) return; - for (const [key, rawModel] of Object.entries(record)) { - const model = asRecord(rawModel); - if (!model || model.isInternal === true) continue; - const name = typeof model.displayName === "string" ? model.displayName : typeof model.label === "string" ? model.label : ""; - if (!name || name.toLowerCase().includes("argon") || key.toLowerCase().includes("argon")) continue; - const resetMs = timeMs(asRecord(model.quotaInfo)?.resetTime); - if (resetMs != null && resetMs - now > 5 * 3600_000 + 600_000) antigravityWeeklyResets.add(resetMs); - } -} - -async function fetchAntigravityPlan( - cacheKey: string, - headers: Record, - timeoutMs: number, - deps: PlanUsageDeps, -): Promise { - const cached = antigravityPlanCache.get(cacheKey); - if (cached) return cached; - const body = JSON.stringify({ - metadata: { ideType: "ANTIGRAVITY", platform: "PLATFORM_UNSPECIFIED", pluginType: "GEMINI" }, - }); - for (const host of ANTIGRAVITY_HOSTS) { - const result = await fetchJson(deps.fetch, `${host}/v1internal:loadCodeAssist`, headers, timeoutMs, { - method: "POST", - body, - }); - if (!result.ok) continue; - const plan = parseAntigravityPlan(result.body); - if (plan) { - antigravityPlanCache.set(cacheKey, plan); - return plan; - } - } - return null; -} - -function antigravityHasUsage(windows: PlanWindows): boolean { - return (windows.fiveHour.available && (windows.fiveHour.usedPercent ?? 0) > 0) || - (windows.weekly.available && (windows.weekly.usedPercent ?? 0) > 0) || - windows.models.some((model) => model.windows.some((entry) => entry.usedPercent > 0)); -} - -async function fetchAntigravity( - account: PlanAccount, - token: string, - loginKey: string, - now: number, - deps: PlanUsageDeps, -): Promise { - const headers = { - Authorization: `Bearer ${token}`, - Accept: "application/json", - "Content-Type": "application/json", - "User-Agent": antigravityUserAgent(), - }; - const timeout = deps.timeoutMs ?? PROVIDER_TIMEOUT_MS; - const summaryResponses = await Promise.all( - ANTIGRAVITY_HOSTS.map((host) => - fetchJson(deps.fetch, `${host}/v1internal:retrieveUserQuotaSummary`, headers, timeout, { - method: "POST", - body: "{}", - now, - })), - ); - const summaryBodies: unknown[] = []; - let rejected = false; - let rateLimited: HttpResult | null = null; - for (const response of summaryResponses) { - const groups = asRecord(response.body)?.groups; - if (response.ok && Array.isArray(groups) && groups.length > 0) summaryBodies.push(response.body); - else if (response.status === 401) rejected = true; - else if (response.status === 429) rateLimited = response; - } - const fromSummary = parseAntigravitySummary(summaryBodies); - if (fromSummary) { - const plan = await fetchAntigravityPlan(loginKey, headers, timeout, deps); - return { kind: "ok", row: okRow(account, { ...fromSummary, plan }) }; - } - if (rejected) return { kind: "auth", row: errorRow(account, signInAgain("antigravity")) }; - - let fallback: PlanWindows | null = null; - for (const host of ANTIGRAVITY_HOSTS) { - const response = await fetchJson(deps.fetch, `${host}/v1internal:fetchAvailableModels`, headers, timeout, { - method: "POST", - body: "{}", - now, - }); - if (response.ok) { - const modelsNode = asRecord(response.body)?.models; - if (!modelsNode) continue; - recordAntigravityWeeklyResets(modelsNode, now); - const parsed = parseAntigravityModels(modelsNode, now, antigravityWeeklyResets); - if (!parsed) continue; - if (antigravityHasUsage(parsed)) { - const plan = await fetchAntigravityPlan(loginKey, headers, timeout, deps); - return { kind: "ok", row: okRow(account, { ...parsed, plan }) }; - } - if (!fallback) fallback = parsed; - } else if (authRejected(response.status)) { - rejected = true; - } else if (response.status === 429) { - rateLimited = response; - } - } - if (fallback) { - const plan = await fetchAntigravityPlan(loginKey, headers, timeout, deps); - return { kind: "ok", row: okRow(account, { ...fallback, plan }) }; - } - if (rejected) return { kind: "auth", row: errorRow(account, signInAgain("antigravity")) }; - if (rateLimited) { - return { kind: "rate_limit", retryAfterMs: rateLimited.retryAfterMs, row: errorRow(account, rateLimitedError("antigravity")) }; - } - return { kind: "transient", row: errorRow(account, couldNotReach("antigravity")) }; -} - function cursorDashboardSession(token: string): { user: string; cookie: string } { const sub = jwtSubject(token) ?? ""; const user = sub.includes("|") ? (sub.split("|").pop() ?? "") : sub;