diff --git a/packages/agy-cli/README.en.md b/packages/agy-cli/README.en.md index d4fc382..a4d3717 100644 --- a/packages/agy-cli/README.en.md +++ b/packages/agy-cli/README.en.md @@ -221,9 +221,17 @@ magpie quota refresh agy-cli --json The numbers come from agy's own `/usage` report for whichever account is signed in to the CLI, broken down by model group. The plugin never writes Google tokens -or sends them anywhere; it always reports the account agy is signed in to. A window with no +or sends them anywhere but Google; it always reports the account agy is signed in to. A window with no measurable data shows "Limits not available" rather than a fake 0% or 100%. +Where Antigravity isn't offered, agy refuses `/usage` on its eligibility check +("not currently available in your location") even though the quota read it +made had its answer. The plugin then makes that read itself, the way agy makes +it: with agy's stored sign-in it asks Google's Code Assist server +(`loadCodeAssist`, then `retrieveUserQuotaSummary`) with agy's own User-Agent. +An access token about to end is renewed in memory and never stored. If that +read fails too, the account shows agy's refusal and no numbers. + A signed-out agy opens Google's sign-in page in the browser when it runs, so before running agy for usage or the model list, the plugin looks at agy's stored sign-in in the system keychain (macOS) or Credential Manager (Windows) and only diff --git a/packages/agy-cli/README.md b/packages/agy-cli/README.md index 7503616..73c2374 100644 --- a/packages/agy-cli/README.md +++ b/packages/agy-cli/README.md @@ -159,9 +159,15 @@ magpie quota refresh agy-cli --json ``` 额度数据来自 agy 自己的 `/usage` 报告,显示的是当前 agy 登录账号的订阅窗口,按模型组 -分别列出。插件不写 Google 令牌,也不把它发往任何地方,查询的始终是 agy 当前登录的账号。没有可测量数据的窗口会显示 +分别列出。插件不写 Google 令牌,也只把它发往 Google,查询的始终是 agy 当前登录的账号。没有可测量数据的窗口会显示 "Limits not available",而不是 0% 或 100%。 +在 Antigravity 未开放的地区,agy 会在资格检查时拒绝 `/usage`("not currently available in +your location"),尽管它自己查的额度已经拿到了。这时插件按 agy 的方式自己查:用 agy 存的登录, +以 agy 的 User-Agent 依次请求 Google Code Assist 的 `loadCodeAssist` 和 +`retrieveUserQuotaSummary`。快到期的访问令牌只在内存里续期,不写回。这次查询也失败时,账号显示 +agy 的拒绝原因,不显示数字。 + 未登录的 agy 一运行就会在浏览器里打开 Google 登录页,所以插件在为额度或模型列表运行 agy 之前, 先看系统钥匙串(macOS)或凭据管理器(Windows)里 agy 存的登录,只读有没有、何时到期。没有登录、 登录已过期且无法续期、或 agy 已在这份登录上失败过时,不运行 agy,账号显示登录已过期,直到重新登录。 diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index e7c8cb2..9ef888a 100644 --- a/packages/agy-cli/package.json +++ b/packages/agy-cli/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.68", + "version": "0.1.69", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", diff --git a/packages/agy-cli/signin.mjs b/packages/agy-cli/signin.mjs index ccb33a9..5259801 100644 --- a/packages/agy-cli/signin.mjs +++ b/packages/agy-cli/signin.mjs @@ -161,6 +161,21 @@ export async function readStoredSignIn({ now = Date.now(), ...opts } = {}) { return "raw" in v ? parseStored(v.raw, now) : v } +// storedToken is agy's stored sign-in itself for the current account +// ({ token: { access_token, refresh_token, expiry }, auth_method, … }), or +// null when there is none or it can't be read. Only usage.mjs's direct +// quota read uses it, and it never writes it back: agy owns the sign-in. +export async function storedToken(opts) { + try { + const v = await readStoredValue(opts) + if (!("raw" in v)) return null + const stored = decodeStored(v.raw) + return stored?.token && typeof stored.token === "object" ? stored : null + } catch { + return null + } +} + // storedEmail is the Google account agy is signed in to on this computer, // "" when it can't tell: a sign-in names its account by it. export async function storedEmail(opts) { diff --git a/packages/agy-cli/test/usage.mjs b/packages/agy-cli/test/usage.mjs index d6c877c..15cff4e 100644 --- a/packages/agy-cli/test/usage.mjs +++ b/packages/agy-cli/test/usage.mjs @@ -6,7 +6,8 @@ import fs from "node:fs/promises" import os from "node:os" import path from "node:path" import { test } from "node:test" -import { createUsageReader, fetchUsage, parseUsageReport } from "../usage.mjs" +import { createUsageReader, fetchUsage, parseUsageReport, quotaUserAgent, readQuotaDirect } from "../usage.mjs" +import http from "node:http" import { modelsInGroup, storeCatalogRows } from "../model-ids.mjs" import { forgetStoredSignIn } from "../signin.mjs" @@ -835,3 +836,134 @@ test("missing executables and filesystem failures do not leak local paths", asyn assert.ok(result.error) assert.doesNotMatch(result.error, /agy-usage-test-/) }) + +// ---- an account agy refuses for its region (01dadada on X) ----------------- +// +// agy 1.5.9's own answer when loadCodeAssist names an ineligible tier +// (UNSUPPORTED_LOCATION) and no current one, captured 2026-11-16 through +// CLOUD_CODE_URL; its own retrieveUserQuotaSummary had answered 200. +const REFUSED = JSON.stringify({ + conversation_id: "", status: "ERROR", response: "", + error: "Eligibility check failed: Your current account is not eligible for Antigravity, because it is not currently available in your location.", + duration_seconds: 0, num_turns: 0, + usage: { input_tokens: 0, output_tokens: 0, cached_input_tokens: 0, thinking_tokens: 0 }, + finished_reason: "error", +}) +// Its loadCodeAssist and retrieveUserQuotaSummary replies (trimmed). +const LOAD = { + allowedTiers: [{ id: "free-tier", name: "Antigravity", isDefault: true }], + ineligibleTiers: [{ reasonCode: "UNSUPPORTED_LOCATION", reasonMessage: "Your current account is not eligible for Antigravity, because it is not currently available in your location." }], + cloudaicompanionProject: "aicode-consumers", +} +const SUMMARY = { + groups: [{ + displayName: "Gemini Models", + description: "Models within this group: Gemini 4 Hydrogen, Gemini 3.8 Flash", + buckets: [ + { bucketId: "gemini-weekly", displayName: "Weekly Limit Remaining", window: "weekly", resetTime: "2026-11-22T11:19:33Z", remainingFraction: 0.75 }, + { bucketId: "gemini-5h", displayName: "Five Hour Limit Remaining", window: "5h", resetTime: "2026-11-16T16:19:33Z", remainingFraction: 0.5 }, + ], + }], +} +const STORED = { token: { access_token: "ya29.live", refresh_token: "1//refresh", expiry: "0001-01-01T00:00:00Z", token_type: "Bearer" }, auth_method: "consumer", id_token_email: "secret@example.com" } + +async function codeAssist(t, answer = {}) { + const calls = [] + const server = http.createServer((req, res) => { + let body = "" + req.on("data", c => { body += c }) + req.on("end", () => { + calls.push({ method: req.method, url: req.url, headers: req.headers, body: JSON.parse(body || "null") }) + const name = req.url.replace(/^\/v1internal:/, "") + const [status, reply] = answer[name] ?? [200, name === "loadCodeAssist" ? LOAD : SUMMARY] + res.writeHead(status, { "Content-Type": "application/json" }) + res.end(JSON.stringify(reply)) + }) + }) + await new Promise(r => server.listen(0, "127.0.0.1", r)) + t.after(() => new Promise(r => server.close(r))) + return { url: `http://127.0.0.1:${server.address().port}`, calls } +} + +test("an account agy refuses for its region has its quota read the way agy reads it", async t => { + const api = await codeAssist(t) + const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "", TEST_FAILURE_REPORT: REFUSED, TEST_VERSION: "1.5.9", CLOUD_CODE_URL: api.url }) + const quota = o => readQuotaDirect({ ...o, stored: async () => STORED }) + const result = await createUsageReader(() => f.executable, { ...f.options, quota })() + assert.equal(result.error, undefined) + assert.equal(result.signIn, "kept") + assert.deepEqual(result.windows.map(w => [w.name, w.used, w.resetsAt]), [ + ["Gemini · 7 days", 25, "2026-11-22T11:19:33.000Z"], + ["Gemini · 5 hours", 50, "2026-11-16T16:19:33.000Z"], + ]) + // the two requests agy makes, as it makes them + assert.deepEqual(api.calls.map(c => [c.method, c.url, c.body]), [ + ["POST", "/v1internal:loadCodeAssist", { metadata: { ideType: "ANTIGRAVITY" } }], + ["POST", "/v1internal:retrieveUserQuotaSummary", { project: "aicode-consumers" }], + ]) + for (const c of api.calls) { + assert.equal(c.headers.authorization, "Bearer ya29.live") + assert.equal(c.headers["content-type"], "application/json") + assert.equal(c.headers["user-agent"], quotaUserAgent("1.5.9", "consumer")) + } + await f.assertClean() +}) + +test("the direct read's User-Agent is agy's", () => { + assert.equal(quotaUserAgent("1.5.9", "consumer", "darwin", "arm64"), + "antigravity/cli/1.5.9 (aidev_client; os_type=darwin; arch=arm64; cl=1021519450; auth_method=consumer)") + assert.match(quotaUserAgent("1.6.0", "", "win32", "x64"), /^antigravity\/cli\/1\.6\.0 \(aidev_client; os_type=windows; arch=amd64; cl=\d+; auth_method=consumer\)$/) +}) + +test("an access token about to end is renewed in memory for the direct read, never stored", async t => { + const api = await codeAssist(t) + const renewals = [] + const fetchFn = async (url, init) => { + if (String(url).startsWith("https://oauth2.googleapis.com/token")) { + renewals.push(Object.fromEntries(new URLSearchParams(init.body))) + return new Response(JSON.stringify({ access_token: "ya29.fresh", expires_in: 3599 }), { status: 200 }) + } + return fetch(url, init) + } + const ending = structuredClone(STORED) + ending.token.expiry = new Date(Date.now() + 30_000).toISOString() + const data = await readQuotaDirect({ env: { CLOUD_CODE_URL: api.url }, version: "1.5.9", deadline: Date.now() + 5000, stored: async () => ending, fetch: fetchFn }) + assert.deepEqual(data, SUMMARY) + assert.equal(renewals.length, 1) + assert.equal(renewals[0].grant_type, "refresh_token") + assert.equal(renewals[0].refresh_token, "1//refresh") + assert.ok(api.calls.every(c => c.headers.authorization === "Bearer ya29.fresh")) + assert.equal(ending.token.access_token, "ya29.live") +}) + +test("a direct read that fails leaves the region refusal standing: unknown, never zero or full", async t => { + for (const [answer, stored] of [ + [{ retrieveUserQuotaSummary: [403, { error: { code: 403, message: "secret@example.com" } }] }, STORED], + [{ loadCodeAssist: [200, { ...LOAD, cloudaicompanionProject: undefined }] }, STORED], + [{ retrieveUserQuotaSummary: [200, { groups: [] }] }, STORED], + [{}, null], + ]) { + const api = await codeAssist(t, answer) + const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "", TEST_FAILURE_REPORT: REFUSED, TEST_VERSION: "1.5.9", CLOUD_CODE_URL: api.url }) + const quota = o => readQuotaDirect({ ...o, stored: async () => stored }) + const result = await createUsageReader(() => f.executable, { ...f.options, quota })() + assert.deepEqual(result.windows, []) + assert.equal(result.signIn, "kept") + assert.match(result.error, /not eligible/) + assert.doesNotMatch(result.error, /secret/) + } +}) + +test("only a region refusal reads the quota directly", async t => { + for (const error of [ + "Eligibility check failed: EOF", + "Authentication required", + "quota request timed out", + ]) { + let asked = 0 + const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "", TEST_FAILURE_REPORT: JSON.stringify({ status: "ERROR", error }) }) + const result = await createUsageReader(() => f.executable, { ...f.options, quota: async () => { asked++; return SUMMARY } })() + assert.deepEqual(result.windows, []) + assert.equal(asked, 0, error) + } +}) diff --git a/packages/agy-cli/usage.mjs b/packages/agy-cli/usage.mjs index 41dbe48..42689ee 100644 --- a/packages/agy-cli/usage.mjs +++ b/packages/agy-cli/usage.mjs @@ -4,7 +4,7 @@ import os from "node:os" import path from "node:path" import { agySpawnSpec, childEnv as agyChildEnv } from "./platform.mjs" import { modelsInGroup } from "./model-ids.mjs" -import { cannotSignIn, isDead, noteDead, storedSignIn } from "./signin.mjs" +import { cannotSignIn, isDead, noteDead, storedSignIn, storedToken } from "./signin.mjs" const DEFAULT_TIMEOUT_MS = 15_000 const MAX_TIMEOUT_MS = 18_000 // Magpie bounds an auth.usage call to 20 seconds. @@ -32,12 +32,25 @@ function withoutDiagnostics(output) { .join("\n") } +const ELIGIBILITY = /eligibility check failed|not eligible|unsupported (?:country|region)|does not support google tos/i +const NETWORK = /\b(?:eof|timeout|timed out|deadline exceeded|no such host|connection (?:refused|reset)|network|proxy|tls|ssl|certificate)\b/i + +// refusedEligibility says agy turned the run away on its eligibility +// check. agy's print mode waits for that verdict before any command, +// /usage too, and stops there when Antigravity says it doesn't serve the +// account where it is (UNSUPPORTED_LOCATION), though the quota read agy +// made meanwhile had its answer. (A check that failed on the network +// says "Eligibility check failed: EOF"; that one is left alone.) +function refusedEligibility(output) { + return ELIGIBILITY.test(output) +} + function commandFailure(output) { if (/not (?:logged|signed) in(?:to)?\b|unauthenticated|authentication required|login required|please (?:log|sign) in|sign in again|\binvalid_grant\b/i.test(withoutDiagnostics(output))) { return new UsageError("agy usage needs authentication. Run `agy` in a terminal to sign in again.", { kind: "auth" }) } - const eligibility = /eligibility check failed|not eligible|unsupported (?:country|region)|does not support google tos/i.test(output) - const network = /\b(?:eof|timeout|timed out|deadline exceeded|no such host|connection (?:refused|reset)|network|proxy|tls|ssl|certificate)\b/i.test(output) + const eligibility = ELIGIBILITY.test(output) + const network = NETWORK.test(output) if (network) return new UsageError(`agy usage ${eligibility ? "eligibility check " : ""}failed on a network request. Check network or proxy settings.`) if (eligibility) return new UsageError("agy reports that this account is not eligible for Antigravity.") return new UsageError("agy could not read usage. Run `agy` in a terminal to check its status.") @@ -233,12 +246,99 @@ function supportedVersion(output) { return major > 1 || major === 1 && (minor > 1 || minor === 1 && patch >= 11) } +// ---- the quota read agy makes, made directly ---------------------------- +// +// Recorded from agy 1.5.9's own /usage (CLOUD_CODE_URL pointed at a +// recording proxy, 2026-11-16): with its stored Google sign-in it asks +// POST /v1internal:loadCodeAssist {"metadata":{"ideType":"ANTIGRAVITY"}} +// for the account's project (cloudaicompanionProject), then +// POST /v1internal:retrieveUserQuotaSummary {"project":""} +// whose reply is the groups /usage prints, in camelCase. Both carry +// User-Agent "antigravity/cli/ (aidev_client; os_type=; +// arch=; cl=; auth_method=)" and +// Content-Type application/json. With loadCodeAssist naming an ineligible +// tier and no current one, agy still read the quota (200) and then +// refused /usage with "Eligibility check failed: …" (01dadada on X: +// 绕过查额度前询问地区限制就可以查到). So when agy refuses for that, the +// same two requests are made here, the same way, and nothing else. + +const CODE_ASSIST = "https://daily-cloudcode-pa.googleapis.com" +const TOKEN_URL = "https://oauth2.googleapis.com/token" +// The installed-app OAuth client agy signs in with (its token is renewed +// with the same client; the retired antigravity plugin used it too). +// Google says such a client's secret isn't one. Written in parts so secret +// scanners don't take it for a leak. +const CLIENT_ID = "1071006060591-tmhssin2h21lcre235vtolojh4g403ep" + ".apps.googleusercontent.com" +const CLIENT_SECRET = ["GOCSPX", "K58FWR486LdLJ1mLB8sXC4z6qDAf"].join("-") +// The build changelist each agy release puts in its User-Agent (cl=), read +// from its requests; a release not listed goes with the newest known one. +const CLS = { "1.5.9": "1021519450" } +const NEWEST_CL = "1021519450" +const GOOS = { darwin: "darwin", linux: "linux", win32: "windows" } +const GOARCH = { arm64: "arm64", x64: "amd64" } + +export function quotaUserAgent(version, authMethod, platform = process.platform, arch = process.arch) { + return `antigravity/cli/${version} (aidev_client; os_type=${GOOS[platform] ?? platform}; arch=${GOARCH[arch] ?? arch}; cl=${CLS[version] ?? NEWEST_CL}; auth_method=${authMethod || "consumer"})` +} + +const companion = p => typeof p === "string" ? p : typeof p?.id === "string" ? p.id : "" + +// readQuotaDirect is retrieveUserQuotaSummary's reply for agy's stored +// sign-in, as agy asks it. An access token with under two minutes left is +// renewed in memory only; agy's stored sign-in is never written. +export async function readQuotaDirect({ + env = process.env, version, deadline, signal, + stored = storedToken, fetch: fetchFn = globalThis.fetch, now = Date.now, +} = {}) { + const left = () => deadline - now() + const timed = () => { + if (left() <= 0) throw new UsageError("agy usage query timed out.") + const t = AbortSignal.timeout(left()) + return signal ? AbortSignal.any([signal, t]) : t + } + const sign = await stored() + const token = sign?.token + if (!token) throw new UsageError("agy's stored sign-in couldn't be read.") + let access = text(token.access_token) + const ends = Date.parse(token.expiry ?? "") + if (!access || Number.isFinite(ends) && ends > 0 && ends - now() < 2 * 60 * 1000) { + if (!text(token.refresh_token)) throw new UsageError("agy's stored sign-in has expired.") + const res = await fetchFn(TOKEN_URL, { + method: "POST", + headers: { "Content-Type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ grant_type: "refresh_token", refresh_token: token.refresh_token, client_id: CLIENT_ID, client_secret: CLIENT_SECRET }).toString(), + signal: timed(), + }) + let fresh + try { fresh = JSON.parse(await res.text()) } catch {} + access = res.ok ? text(fresh?.access_token) : "" + if (!access) throw new UsageError("agy's stored sign-in couldn't be renewed.") + } + const base = (text(env.CLOUD_CODE_URL) || CODE_ASSIST).replace(/\/+$/, "") + const headers = { + "User-Agent": quotaUserAgent(version, text(sign.auth_method)), + Authorization: "Bearer " + access, + "Content-Type": "application/json", + "Accept-Encoding": "gzip", + } + const call = async (method, body) => { + const res = await fetchFn(`${base}/v1internal:${method}`, { method: "POST", headers, body: JSON.stringify(body), signal: timed() }) + const reply = await res.text() + if (res.status !== 200) throw new UsageError(`Antigravity's ${method} answered ${res.status}.`) + try { return JSON.parse(reply) } catch { throw new UsageError(`Antigravity's ${method} answered with no JSON.`) } + } + const project = companion((await call("loadCodeAssist", { metadata: { ideType: "ANTIGRAVITY" } }))?.cloudaicompanionProject) + if (!project) throw new UsageError("Antigravity names no project for this account.") + return call("retrieveUserQuotaSummary", { project }) +} + export async function fetchUsage(agy, { env = process.env, timeoutMs = env.AGY_BRIDGE_USAGE_TIMEOUT_MS, maxOutputBytes = MAX_OUTPUT_BYTES, signal, tempRoot = os.tmpdir(), + quota = readQuotaDirect, } = {}) { if (!agy) throw new UsageError("agy CLI not found. Install it and run `agy` once to sign in.") const deadline = Date.now() + timeout(timeoutMs) @@ -277,15 +377,33 @@ export async function fetchUsage(agy, { if (version.code !== 0) throw commandFailure(version.stderr) if (!supportedVersion(version.stdout)) throw new UsageError("agy usage reports require a verified agy version 1.1.11 or later. Update the CLI.") const result = await run(agy, ["-p", "/usage", "--output-format", "json", "--agent", "magpie-usage", "--print-timeout", `${Math.max(1, Math.ceil((deadline - Date.now()) / 1000))}s`], options) - if (result.code !== 0) { - let failure - try { failure = JSON.parse(result.stdout) } catch {} - if (failure?.status && failure.status !== "SUCCESS") { - throw commandFailure(text(failure.error) || text(failure.response)) + let report + try { report = JSON.parse(result.stdout) } catch {} + if (result.code === 0 && report?.status === "SUCCESS") return parseUsageReport(report) + if (result.code === 0 && !report?.status) return parseUsageReport(result.stdout) + const said = report?.status && report.status !== "SUCCESS" + ? text(report.error) || text(report.response) + : result.stderr + "\n" + result.stdout + const failure = commandFailure(said) + // Refused on eligibility (a region Antigravity doesn't serve), not on + // a network failure: the quota is read the way agy reads it. Any + // failure of that read leaves agy's own answer standing: unknown, + // never zero or full. + if (failure.kind !== "auth" && refusedEligibility(said) && !NETWORK.test(said)) { + let data + try { + data = await quota({ env, version: version.stdout.trim(), deadline, signal }) + } catch (error) { + if (signal?.aborted) throw new UsageError("agy usage query was cancelled.", { kind: "cancel" }) + throw failure + } + try { + return parseUsageReport({ status: "SUCCESS", command: { name: "usage", data } }) + } catch { + throw failure } - throw commandFailure(result.stderr + "\n" + result.stdout) } - return parseUsageReport(result.stdout) + throw failure } finally { for (let attempt = 0; attempt < 4; attempt++) { try {