From b7ab57b096b91dced8fabe8f26a4154e711f6209 Mon Sep 17 00:00:00 2001 From: Kameron Smith Date: Fri, 20 Nov 2026 19:34:27 -0500 Subject: [PATCH] fix(server): read Antigravity quota from the CLI sign-in agy 1.5 stores the Google access token in the keyring and does not write acp_token.json, so T3 treated a signed-in account as signed out. The usage probe now sends that saved access token, and it does not treat untouched Claude/GPT placeholder buckets as the Gemini reading. Model: grok-4.7 Task: fix Agent: grok-4.7 --- .../provider/antigravityUsageLimits.test.ts | 265 ++++++++++++++- .../src/provider/antigravityUsageLimits.ts | 310 +++++++++++++++--- 2 files changed, 522 insertions(+), 53 deletions(-) diff --git a/apps/server/src/provider/antigravityUsageLimits.test.ts b/apps/server/src/provider/antigravityUsageLimits.test.ts index 360b913412ca8..1086f05935901 100644 --- a/apps/server/src/provider/antigravityUsageLimits.test.ts +++ b/apps/server/src/provider/antigravityUsageLimits.test.ts @@ -8,9 +8,14 @@ import * as Effect from "effect/Effect"; import * as FileSystem from "effect/FileSystem"; import * as Path from "effect/Path"; import * as TestClock from "effect/testing/TestClock"; +import * as HostProcess from "@t3tools/shared/HostProcess"; import { FetchHttpClient, HttpClient, HttpClientResponse } from "effect/http"; -import { makeAntigravityUsageProbe } from "./antigravityUsageLimits.ts"; +import { + makeAntigravityUsageProbe, + parseAntigravityCliCredential, + type AntigravityCliAccess, +} from "./antigravityUsageLimits.ts"; const summary = { groups: [ @@ -66,11 +71,18 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( userInfoAt?: number; missingToken?: boolean; authMethod?: "oauth-personal" | "oauth-business" | "gemini-api-key"; + /** Uses this bearer and sends no project id. Skips the OAuth refresh call. */ + cliAccess?: AntigravityCliAccess | "expired"; + /** Reads CLI credential files and this secret instead of the real keyring. */ + discover?: boolean; + readStoredSecret?: Effect.Effect; + directAccess?: string; } = {}, ) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; const profileDirectory = yield* fs.makeTempDirectoryScoped(); + const homeDirectory = yield* fs.makeTempDirectoryScoped(); yield* fs.makeDirectory(path.join(profileDirectory, "antigravity-acp")); const tokenPath = path.join(profileDirectory, "antigravity-acp", "acp_token.json"); const writeToken = (refreshToken: string) => @@ -83,7 +95,15 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( project_id: "project-id", }), ); - if (!options.missingToken) yield* writeToken(options.refreshToken ?? "refresh-a"); + const suppliedAccess = + options.cliAccess && typeof options.cliAccess === "object" + ? options.cliAccess.accessToken + : undefined; + const bearer = suppliedAccess ?? options.directAccess ?? "access-token"; + const quotaBody = suppliedAccess || options.directAccess ? {} : { project: "project-id" }; + if (!options.missingToken && !options.discover && options.cliAccess === undefined) { + yield* writeToken(options.refreshToken ?? "refresh-a"); + } const requests: Array<{ url: string; body: string }> = []; const http = HttpClient.make((request, url, _signal, fiber) => Effect.sync(() => { @@ -102,7 +122,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( ), ); } - expect(request.headers.authorization).toBe("Bearer access-token"); + expect(request.headers.authorization).toBe(`Bearer ${bearer}`); if (request.url.endsWith("/userinfo")) { return HttpClientResponse.fromWeb( request, @@ -111,7 +131,7 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( : Response.json({}, { status: 403 }), ); } - expect(JSON.parse(body)).toEqual({ project: "project-id" }); + expect(JSON.parse(body)).toEqual(quotaBody); expect(request.headers["user-agent"]).toMatch(/^antigravity\/hub\/2\.24\.0 /); return HttpClientResponse.fromWeb( request, @@ -132,8 +152,14 @@ const fixture = Effect.fn("AntigravityUsageTest.fixture")(function* ( const usage = yield* makeAntigravityUsageProbe({ profileDirectory, authMethod: options.authMethod ?? "oauth-personal", - }).pipe(Effect.provideService(HttpClient.HttpClient, http)); - return { ...usage, requests, writeToken, tokenPath }; + ...(options.discover + ? { readStoredSecret: options.readStoredSecret ?? Effect.succeed(null) } + : { cliAccess: options.cliAccess ?? null }), + }).pipe( + Effect.provideService(HttpClient.HttpClient, http), + Effect.provideService(HostProcess.HomeDirectory, homeDirectory), + ); + return { ...usage, requests, writeToken, tokenPath, profileDirectory, homeDirectory }; }); describe("Antigravity subscription limits", () => { @@ -673,4 +699,231 @@ describe("Antigravity subscription limits", () => { expect(signedOut.requests).toEqual([]); }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), ); + + it("parses the keyring credential agy stores, including a nanosecond expiry", () => { + const now = Date.parse("2026-11-20T12:00:00.000Z"); + expect( + parseAntigravityCliCredential( + JSON.stringify({ + token: { + access_token: "access", + refresh_token: "refresh", + expiry: "2026-11-20T19:22:44.180377856Z", + }, + }), + now, + ), + ).toEqual({ + accessToken: "access", + identity: "refresh", + expiresAtMs: Date.parse("2026-11-20T19:22:44.180Z"), + }); + expect(parseAntigravityCliCredential(JSON.stringify({ access_token: "flat" }), now)).toEqual({ + accessToken: "flat", + identity: "flat", + }); + expect( + parseAntigravityCliCredential( + JSON.stringify({ token: { access_token: "old", expiry: "2026-11-20T11:00:00Z" } }), + now, + ), + ).toBe("expired"); + expect(parseAntigravityCliCredential("{", now)).toBeUndefined(); + expect(parseAntigravityCliCredential("{}", now)).toBeUndefined(); + }); + + it.effect("uses a saved Antigravity access token without calling the token endpoint", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-20T12:00:00Z"))); + const { probe, requests } = yield* fixture({ + missingToken: true, + userId: "google-user-9", + cliAccess: { + accessToken: "cli-access-token", + identity: "cli-refresh-token", + expiresAtMs: DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-20T13:00:00Z")), + }, + }); + const limits = yield* probe; + expect(limits.unavailable).toBeUndefined(); + expect(limits.windows.some((window) => window.id === "gemini-5h")).toBe(true); + expect(requests.some((request) => request.url.endsWith("/token"))).toBe(false); + expect(limits.credentialFingerprint).toMatch(/^[0-9a-f]{64}$/); + expect(JSON.stringify(limits)).not.toMatch(/cli-access-token|cli-refresh-token/); + yield* probe; + expect(requests.filter((request) => request.url.endsWith("/userinfo"))).toHaveLength(1); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("re-reads an access token once its unknown expiry cache elapses", () => + Effect.gen(function* () { + const { probe, requests } = yield* fixture({ + missingToken: true, + cliAccess: { accessToken: "cli-access-token", identity: "cli-refresh-token" }, + }); + yield* probe; + yield* TestClock.adjust("6 minutes"); + yield* probe; + expect(requests.filter((request) => request.url.endsWith("/userinfo"))).toHaveLength(2); + expect(requests.some((request) => request.url.endsWith("/token"))).toBe(false); + expect(JSON.stringify(yield* probe)).not.toMatch(/cli-access-token|cli-refresh-token/); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("does not send a lapsed Antigravity access token", () => + Effect.gen(function* () { + const { probe, requests } = yield* fixture({ missingToken: true, cliAccess: "expired" }); + const limits = yield* probe; + expect(limits.windows).toEqual([]); + expect(limits.unavailable).toEqual({ + reason: "probeFailed", + message: + "Antigravity's saved access token has lapsed. A running agy session refreshes it; the Antigravity app does not need to be open.", + }); + expect(requests).toEqual([]); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("reads the profile OAuth file and does not open the keyring", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-20T12:00:00Z"))); + const { probe, requests, profileDirectory } = yield* fixture({ + discover: true, + directAccess: "file-access-token", + readStoredSecret: Effect.die("keyring should stay unread"), + }); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.writeFileString( + path.join(profileDirectory, "antigravity-acp", "antigravity-oauth-token"), + JSON.stringify({ + token: { + access_token: "file-access-token", + refresh_token: "file-refresh-token", + expiry: "2026-11-20T19:22:44.180377856Z", + }, + }), + ); + const limits = yield* probe; + expect(limits.unavailable).toBeUndefined(); + expect(requests.some((request) => request.url.endsWith("/token"))).toBe(false); + expect(JSON.stringify(limits)).not.toMatch(/file-access-token|file-refresh-token/); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("uses a fresh home credential when the profile credential has lapsed", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-20T12:00:00Z"))); + const { probe, profileDirectory, homeDirectory } = yield* fixture({ + discover: true, + directAccess: "home-access-token", + readStoredSecret: Effect.die("keyring should stay unread"), + }); + const fs = yield* FileSystem.FileSystem; + const path = yield* Path.Path; + yield* fs.writeFileString( + path.join(profileDirectory, "antigravity-oauth-token"), + JSON.stringify({ + token: { access_token: "old-access-token", expiry: "2020-01-01T00:00:00Z" }, + }), + ); + const directory = path.join(homeDirectory, ".gemini", "antigravity-cli"); + yield* fs.makeDirectory(directory, { recursive: true }); + yield* fs.writeFileString( + path.join(directory, "antigravity-oauth-token"), + JSON.stringify({ + access_token: "home-access-token", + refresh_token: "home-refresh-token", + expiry: "2099-01-01T00:00:00Z", + }), + ); + const limits = yield* probe; + expect(limits.unavailable).toBeUndefined(); + expect(JSON.stringify(limits)).not.toMatch( + /old-access-token|home-access-token|home-refresh-token/, + ); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("uses the keyring access token when no credential file exists", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-20T12:00:00Z"))); + const { probe, requests } = yield* fixture({ + discover: true, + directAccess: "keyring-access-token", + readStoredSecret: Effect.succeed( + JSON.stringify({ + token: { + access_token: "keyring-access-token", + refresh_token: "keyring-refresh-token", + expiry: "2026-11-20T19:22:44.180377856Z", + }, + }), + ), + }); + const limits = yield* probe; + expect(limits.windows.some((window) => window.id === "gemini-weekly")).toBe(true); + expect(requests.some((request) => request.url.endsWith("/token"))).toBe(false); + expect(JSON.stringify(limits)).not.toMatch(/keyring-access-token|keyring-refresh-token/); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("reports a lapsed keyring token without sending it", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-11-20T12:00:00Z"))); + const { probe, requests } = yield* fixture({ + discover: true, + readStoredSecret: Effect.succeed( + JSON.stringify({ + token: { access_token: "lapsed-access-token", expiry: "2020-01-01T00:00:00Z" }, + }), + ), + }); + const limits = yield* probe; + expect(limits.unavailable?.reason).toBe("probeFailed"); + expect(requests).toEqual([]); + expect(JSON.stringify(limits)).not.toMatch(/lapsed-access-token/); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); + + it.effect("asks for model quotas when the summary is only untouched placeholders", () => + Effect.gen(function* () { + yield* TestClock.setTime(DateTime.toEpochMillis(DateTime.makeUnsafe("2026-10-21T10:16:04Z"))); + const { probe, requests } = yield* fixture({ + summary: { + groups: [ + { + displayName: "Claude and GPT models", + buckets: [ + { + bucketId: "3p-5h", + window: "5h", + remainingFraction: 1, + resetTime: "2026-10-21T15:16:05Z", + }, + { + bucketId: "3p-weekly", + window: "weekly", + remainingFraction: 1, + resetTime: "2026-10-28T10:16:05Z", + }, + ], + }, + ], + }, + models: { + models: { + "gemini-a": { + modelProvider: "MODEL_PROVIDER_GOOGLE", + quotaInfo: { remainingFraction: 0.74, resetTime: "2026-10-21T13:40:58Z" }, + }, + }, + }, + }); + const limits = yield* probe; + expect(limits.windows.map((window) => window.id)).toEqual(["gemini-quota"]); + expect(limits.windows[0]?.usedPercent).toBeCloseTo(26, 5); + expect(requests.some((request) => request.url.endsWith(":fetchAvailableModels"))).toBe(true); + }).pipe(Effect.scoped, Effect.provide(Layer.mergeAll(NodeServices.layer, NodeCrypto.layer))), + ); }); diff --git a/apps/server/src/provider/antigravityUsageLimits.ts b/apps/server/src/provider/antigravityUsageLimits.ts index 852225d3c9205..d1beaae1b609e 100644 --- a/apps/server/src/provider/antigravityUsageLimits.ts +++ b/apps/server/src/provider/antigravityUsageLimits.ts @@ -9,6 +9,7 @@ import * as Option from "effect/Option"; import * as Path from "effect/Path"; import * as Schema from "effect/Schema"; import { FetchHttpClient, HttpClient, HttpClientRequest, HttpClientResponse } from "effect/http"; +import { ChildProcess, ChildProcessSpawner } from "effect/process"; import { makeUnavailableUsageLimits, @@ -124,6 +125,121 @@ function summaryResetTime( return untouched ? undefined : bucket.resetTime; } +const CLI_ACCESS_CACHE_MS = 5 * 60 * 1000; +const KEYRING_SERVICE = "gemini"; +const KEYRING_ACCOUNT = "antigravity"; + +export interface AntigravityCliAccess { + readonly accessToken: string; + readonly identity: string; + readonly expiresAtMs?: number; +} + +/** Google writes nanoseconds. `Date.parse` only has to accept milliseconds. */ +function trimAntigravityTimestamp(value: string) { + const normalized = value.endsWith("Z") ? `${value.slice(0, -1)}+00:00` : value; + const dot = normalized.indexOf("."); + if (dot < 0) return normalized; + let index = dot + 1; + let digits = ""; + while ( + index < normalized.length && + normalized.charCodeAt(index) >= 48 && + normalized.charCodeAt(index) <= 57 + ) { + if (digits.length < 3) digits += normalized[index]; + index += 1; + } + return `${normalized.slice(0, dot)}${digits ? `.${digits}` : ""}${normalized.slice(index)}`; +} + +function timestampMillis(value: unknown): number | undefined { + if (typeof value === "number" && Number.isFinite(value)) { + return value < 10_000_000_000 ? value * 1000 : value; + } + if (typeof value !== "string" || value.length === 0) return undefined; + const parsed = Date.parse(trimAntigravityTimestamp(value)); + return Number.isFinite(parsed) ? parsed : undefined; +} + +/** + * `agy` 1.5 stores this JSON in the Secret Service (service `gemini`, account + * `antigravity`) and does not write `acp_token.json`. There is no client secret, + * so the access token is used as-is. + */ +export function parseAntigravityCliCredential( + raw: string, + nowMs: number, +): AntigravityCliAccess | "expired" | undefined { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch { + return undefined; + } + if (!parsed || typeof parsed !== "object") return undefined; + const record = parsed as Record; + const token = + record.token && typeof record.token === "object" + ? (record.token as Record) + : record; + const accessToken = typeof token.access_token === "string" ? token.access_token : ""; + if (!accessToken) return undefined; + const refreshToken = typeof token.refresh_token === "string" ? token.refresh_token : ""; + const expiresAtMs = timestampMillis(token.expiry ?? record.expiry); + if (expiresAtMs !== undefined && expiresAtMs <= nowMs) return "expired"; + return { + accessToken, + identity: refreshToken || accessToken, + ...(expiresAtMs === undefined ? {} : { expiresAtMs }), + }; +} + +// The stored value is the OAuth token. Keep it out of span attributes. +const readDefaultStoredSecret = Effect.fnUntraced(function* ( + spawner: ChildProcessSpawner.ChildProcessSpawner["Service"], +) { + const fromModule = yield* Effect.tryPromise({ + try: async () => { + const keyring = (await import("@napi-rs/keyring")) as { + readonly AsyncEntry?: new ( + service: string, + account: string, + ) => { getPassword(): Promise }; + readonly Entry?: new ( + service: string, + account: string, + ) => { getPassword(): Promise | string | null }; + }; + const Entry = keyring.AsyncEntry ?? keyring.Entry; + if (!Entry) return null; + const secret = await new Entry(KEYRING_SERVICE, KEYRING_ACCOUNT).getPassword(); + return typeof secret === "string" && secret.length > 0 ? secret : null; + }, + catch: () => null, + }).pipe(Effect.orElseSucceed(() => null)); + if (fromModule) return fromModule; + const platform = yield* HostProcess.Platform; + const command = + platform === "linux" + ? { + command: "secret-tool", + args: ["lookup", "service", KEYRING_SERVICE, "username", KEYRING_ACCOUNT], + } + : platform === "darwin" + ? { + command: "security", + args: ["find-generic-password", "-s", KEYRING_SERVICE, "-a", KEYRING_ACCOUNT, "-w"], + } + : undefined; + if (!command) return null; + const output = yield* spawner + .string(ChildProcess.make(command.command, command.args, { stderr: "ignore" })) + .pipe(Effect.orElseSucceed(() => "")); + const secret = output.trim(); + return secret.length > 0 ? secret : null; +}); + const sha256 = Effect.fnUntraced(function* (text: string) { const digest = yield* (yield* Digest.Digest).digest( Digest.sha256, @@ -207,9 +323,52 @@ function modelWindows(models: typeof Models.Type) { return [...windows.values()]; } +const discoverAntigravityCliAccess = Effect.fn("AntigravityUsageProbe.discoverCliAccess")( + function* (input: { + readonly fs: FileSystem.FileSystem; + readonly path: Path.Path; + readonly homeDirectory: string; + readonly profileDirectory: string; + readonly nowMs: number; + readonly readStoredSecret?: Effect.Effect; + readonly spawner: ChildProcessSpawner.ChildProcessSpawner["Service"]; + }) { + const files = [ + input.path.join(input.profileDirectory, "antigravity-acp", "antigravity-oauth-token"), + input.path.join(input.profileDirectory, "antigravity-oauth-token"), + input.path.join(input.homeDirectory, ".gemini", "antigravity-cli", "antigravity-oauth-token"), + ]; + let expired = false; + for (const file of files) { + if (!(yield* input.fs.exists(file))) continue; + const raw = yield* input.fs.readFileString(file).pipe(Effect.orElseSucceed(() => "")); + const parsed = parseAntigravityCliCredential(raw, input.nowMs); + if (parsed === "expired") { + expired = true; + continue; + } + if (parsed) return parsed; + } + const secret = yield* input.readStoredSecret ?? readDefaultStoredSecret(input.spawner); + if (secret) { + const parsed = parseAntigravityCliCredential(secret, input.nowMs); + if (parsed === "expired") return "expired" as const; + if (parsed) return parsed; + } + return expired ? ("expired" as const) : null; + }, +); + export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")(function* (input: { readonly profileDirectory: string; readonly authMethod: AntigravitySettings["authMethod"]; + /** + * Present only in tests. `null` is signed out, `"expired"` is a lapsed CLI + * token, and an access value is used directly. Omitting it reads the CLI files + * and the keyring. + */ + readonly cliAccess?: AntigravityCliAccess | "expired" | null; + readonly readStoredSecret?: Effect.Effect; }) { const fs = yield* FileSystem.FileSystem; const path = yield* Path.Path; @@ -217,6 +376,8 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( const crypto = yield* Digest.Digest; const platform = yield* HostProcess.Platform; const architecture = yield* HostProcess.Architecture; + const homeDirectory = yield* HostProcess.HomeDirectory; + const spawner = yield* ChildProcessSpawner.ChildProcessSpawner; const tokenPath = path.join(input.profileDirectory, "antigravity-acp", "acp_token.json"); let cached: | { fingerprint: string; account: string; accessToken: string; expiresAt: number } @@ -241,54 +402,106 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( "Not applicable: Antigravity API keys and Agent Platform are billed by Google. T3 has no quota window for them.", }); } - if (!(yield* fs.exists(tokenPath))) { - cached = undefined; - return makeUnavailableUsageLimits({ - checkedAt, - reason: "unsupported", - message: "Sign in with Google to see limits.", - }); - } - const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); - const fingerprint = yield* sha256( - `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`, - ); const now = yield* Clock.currentTimeMillis; + const signedOut = makeUnavailableUsageLimits({ + checkedAt, + reason: "unsupported", + message: "Sign in with Google to see limits.", + }); + const lapsed = makeUnavailableUsageLimits({ + checkedAt, + reason: "probeFailed", + message: + "Antigravity's saved access token has lapsed. A running agy session refreshes it; the Antigravity app does not need to be open.", + }); let accessToken: string; let account: string; - if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { - cached = undefined; - const refreshed = yield* request( - HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( - HttpClientRequest.bodyUrlParams({ - client_id: token.client_id, - client_secret: token.client_secret, - refresh_token: token.refresh_token, - grant_type: "refresh_token", - }), - ), - ).pipe(Effect.flatMap(decodeTokenResponse)); - accessToken = refreshed.access_token; - // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. - account = yield* request( - HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( - HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), - ), - ).pipe( - Effect.flatMap(antigravityAccountFingerprint), - Effect.orElseSucceed(() => fingerprint), + let projectId: string | undefined; + if (yield* fs.exists(tokenPath)) { + const token = yield* fs.readFileString(tokenPath).pipe(Effect.flatMap(decodeTokenFile)); + projectId = token.project_id; + const fingerprint = yield* sha256( + `${token.client_id}\0${token.refresh_token}\0${token.project_id ?? ""}`, ); - if (generation === startedGeneration) { - cached = { - fingerprint, - account, - accessToken, - expiresAt: now + refreshed.expires_in * 1000, - }; + if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now + 60_000) { + cached = undefined; + const refreshed = yield* request( + HttpClientRequest.post("https://oauth2.googleapis.com/token").pipe( + HttpClientRequest.bodyUrlParams({ + client_id: token.client_id, + client_secret: token.client_secret, + refresh_token: token.refresh_token, + grant_type: "refresh_token", + }), + ), + ).pipe(Effect.flatMap(decodeTokenResponse)); + accessToken = refreshed.access_token; + // Use Google account IDs to merge accounts across environments; refresh tokens differ per machine. + account = yield* request( + HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( + HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), + ), + ).pipe( + Effect.flatMap(antigravityAccountFingerprint), + Effect.orElseSucceed(() => fingerprint), + ); + if (generation === startedGeneration) { + cached = { + fingerprint, + account, + accessToken, + expiresAt: now + refreshed.expires_in * 1000, + }; + } + } else { + accessToken = cached.accessToken; + account = cached.account; } } else { - accessToken = cached.accessToken; - account = cached.account; + const cli = + "cliAccess" in input + ? (input.cliAccess ?? null) + : yield* discoverAntigravityCliAccess({ + fs, + path, + homeDirectory, + profileDirectory: input.profileDirectory, + nowMs: now, + spawner, + ...(input.readStoredSecret ? { readStoredSecret: input.readStoredSecret } : {}), + }); + if (cli === null) { + cached = undefined; + return signedOut; + } + if (cli === "expired") { + cached = undefined; + return lapsed; + } + const fingerprint = yield* sha256(`cli-access\0${cli.identity}`); + if (cached?.fingerprint !== fingerprint || cached.expiresAt <= now) { + cached = undefined; + accessToken = cli.accessToken; + account = yield* request( + HttpClientRequest.get("https://www.googleapis.com/oauth2/v2/userinfo").pipe( + HttpClientRequest.setHeaders({ Authorization: `Bearer ${accessToken}` }), + ), + ).pipe( + Effect.flatMap(antigravityAccountFingerprint), + Effect.orElseSucceed(() => fingerprint), + ); + if (generation === startedGeneration) { + cached = { + fingerprint, + account, + accessToken, + expiresAt: cli.expiresAtMs ?? now + CLI_ACCESS_CACHE_MS, + }; + } + } else { + accessToken = cached.accessToken; + account = cached.account; + } } const endpoints = ENDPOINTS[input.authMethod]; // Merge endpoints because quota groups differ; the metered host's reading of a bucket wins. @@ -311,9 +524,7 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( Authorization: `Bearer ${accessToken}`, "User-Agent": antigravityUserAgent(platform, architecture), }), - HttpClientRequest.bodyJsonUnsafe( - token.project_id ? { project: token.project_id } : {}, - ), + HttpClientRequest.bodyJsonUnsafe(projectId ? { project: projectId } : {}), ), ).pipe( Effect.flatMap((response) => parse(response, requestedAt)), @@ -329,11 +540,16 @@ export const makeAntigravityUsageProbe = Effect.fn("makeAntigravityUsageProbe")( return [...windows.values()]; }); const summary = yield* fetchWindows("retrieveUserQuotaSummary", antigravitySummaryWindows); - const windows = summary.length - ? summary + // A summary of only untouched buckets is not a Gemini reading. + const metered = summary.some( + (window) => window.usedPercent > 0 || window.resetsAt !== undefined, + ); + const models = metered + ? [] : yield* fetchWindows("fetchAvailableModels", (response) => decodeModels(response).pipe(Effect.map(modelWindows)), ); + const windows = models.length > 0 ? models : summary; if (windows.length === 0) { return makeUnavailableUsageLimits({ checkedAt,