diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index 8021063..bb7f848 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -9,7 +9,7 @@ import path from "node:path" import { fileURLToPath } from "node:url" import { ACCOUNT_DISABLED_REFUSED, agyRefusal, createUsageReader, verifyLinkIn, verifyRefused } from "./usage.mjs" import { catalogRows, storeCatalogRows } from "./model-ids.mjs" -import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, storedEmail, storedSignInNow } from "./signin.mjs" +import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, signedInEmail, storedEmail, storedSignInNow } from "./signin.mjs" import { sanitizePatternFields } from "./re2-pattern.mjs" import { startLogin } from "./login.mjs" import { accountsDir, currentHome, dropHome, homeIdOfAuth, homeOf, inAccount, newHome, tokenFile } from "./account.mjs" @@ -6742,7 +6742,7 @@ function noAgy() { // (account.mjs) keeps the home's name with it, and a key of its own, so // two accounts whose email can't be read aren't taken for one. async function signedInAs(homeId = "") { - const email = await storedEmail() + const email = await signedInEmail() const metadata = { ...(email ? { email } : {}), ...(homeId ? { agyHome: homeId } : {}) } return { type: "success", key: homeId ? `agy:${homeId}` : "agy", ...(Object.keys(metadata).length ? { metadata } : {}) } } diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 12caf80..2adecae 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.96", + "version": "0.1.97", "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 5259801..0fd25d8 100644 --- a/packages/agy-cli/signin.mjs +++ b/packages/agy-cli/signin.mjs @@ -187,6 +187,29 @@ export async function storedEmail(opts) { } } +// signedInEmail is storedEmail, else, for a sign-in that doesn't name its +// account (id_token_email), who Google says its access token is for: the +// userinfo agy itself asks at sign-in, with the token agy stored. "" when +// neither tells; a token that has ended is not renewed for it. An account +// saved without its email is listed as "API key" (tmr11235 on X), which +// it isn't. +export async function signedInEmail(opts = {}, { fetch: fetchFn = globalThis.fetch, timeoutMs = 5_000 } = {}) { + const email = await storedEmail(opts) + if (email) return email + const access = (await storedToken(opts))?.token?.access_token + if (typeof access !== "string" || !access) return "" + try { + const res = await fetchFn(USERINFO_URL, { headers: { Authorization: `Bearer ${access}` }, signal: AbortSignal.timeout(timeoutMs) }) + if (!res.ok) return "" + const who = await res.json() + return typeof who?.email === "string" && who.email.includes("@") ? who.email.trim().slice(0, 200) : "" + } catch { + return "" + } +} + +const USERINFO_URL = "https://www.googleapis.com/oauth2/v2/userinfo" + // cannotSignIn is why a stored sign-in can't serve agy without a new // Google sign-in, or "" when it may. export function cannotSignIn(s) { diff --git a/packages/agy-cli/test/signin.mjs b/packages/agy-cli/test/signin.mjs index 8d973c8..d4254b1 100644 --- a/packages/agy-cli/test/signin.mjs +++ b/packages/agy-cli/test/signin.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict" import { test } from "node:test" -import { backgroundBlocked, cannotSignIn, emailOf, forgetStoredSignIn, isDead, noteDead, parseStored, readStoredSignIn, storedEmail, storedSignIn, storedSignInNow } from "../signin.mjs" +import { backgroundBlocked, cannotSignIn, emailOf, forgetStoredSignIn, isDead, noteDead, parseStored, readStoredSignIn, signedInEmail, storedEmail, storedSignIn, storedSignInNow } from "../signin.mjs" const NOW = Date.parse("2026-11-13T00:00:00Z") const stored = (token, extra = {}) => JSON.stringify({ token, auth_method: "consumer", id_token_email: "someone@example.com", ...extra }) @@ -106,6 +106,27 @@ test("storedSignInNow answers from the last read without waiting, and reads agai // Archivemylife on X: the account showed as "API key", and signing in to // another Google account looked like nothing happened. A sign-in names the // account by the email agy stored; the cached read still doesn't carry it. +// tmr11235 on X (v0.1.4520): agy's own sign-in, taken again after the +// account was removed, was listed as "API key". A stored sign-in that +// doesn't name its account is named by who Google says its token is for. +test("signedInEmail asks Google who a sign-in is for when agy's doesn't say", async () => { + const mac = (raw) => async () => ({ code: 0, stdout: b64(raw) }) + const asked = [] + const google = (reply, status = 200) => async (url, init) => { + asked.push([url, init.headers.Authorization]) + return new Response(JSON.stringify(reply), { status }) + } + const named = stored({ access_token: "a" }) + assert.equal(await signedInEmail({ platform: "darwin", exec: mac(named), env: {} }, { fetch: google({ email: "other@example.com" }) }), "someone@example.com") + assert.equal(asked.length, 0, "a sign-in that names its account isn't asked about") + const unnamed = stored({ access_token: "tok" }, { id_token_email: undefined }) + assert.equal(await signedInEmail({ platform: "darwin", exec: mac(unnamed), env: {} }, { fetch: google({ email: "who@example.com" }) }), "who@example.com") + assert.deepEqual(asked, [["https://www.googleapis.com/oauth2/v2/userinfo", "Bearer tok"]]) + assert.equal(await signedInEmail({ platform: "darwin", exec: mac(unnamed), env: {} }, { fetch: google({ error: "x" }, 401) }), "") + assert.equal(await signedInEmail({ platform: "darwin", exec: mac(unnamed), env: {} }, { fetch: async () => { throw new Error("offline") } }), "") + assert.equal(await signedInEmail({ platform: "darwin", exec: async () => ({ code: 44, stdout: "" }), env: {} }, { fetch: google({ email: "who@example.com" }) }), "") +}) + test("storedEmail is the Google account agy's keyring is signed in to, on macOS and Windows", async () => { const value = stored({ access_token: "a", refresh_token: "r", expiry: "2026-11-12T00:00:00Z" }) assert.equal(emailOf(b64(value)), "someone@example.com") diff --git a/packages/agy-cli/test/usage.mjs b/packages/agy-cli/test/usage.mjs index 8ce62f1..443b668 100644 --- a/packages/agy-cli/test/usage.mjs +++ b/packages/agy-cli/test/usage.mjs @@ -661,6 +661,44 @@ test("reports sanitized failures and preserves the bridge sign-in; failures back } }) +// tmr11235 on X (magpie v0.1.4520): the account's usage said "agy CLI not +// found" while its chats ran through agy. A read made before agy was there +// was held for the backoff, which grows to hours; agy found since is read +// at once, and a failure held for one agy isn't another's. +test("no agy found is not held: an agy found since is read at once", async t => { + const f = await fixture(t) + let agy = null + const clock = 1_000_000 + const read = createUsageReader(() => agy, { ...f.options, now: () => clock }) + for (let i = 0; i < 3; i++) { + const missing = await read() + assert.deepEqual(missing.windows, []) + assert.equal(missing.signIn, "kept") + assert.match(missing.error, /agy CLI not found[\s\S]*Sign in to this account again/) + } + agy = f.executable + const found = await read() + assert.equal(found.error, undefined) + assert.equal(found.windows.length, 1) + await f.assertClean() +}) + +test("a failure held for one agy is not another agy's", async t => { + const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "connection refused" }) + let agy = f.executable + const clock = 1_000_000 + const read = createUsageReader(() => agy, { ...f.options, now: () => clock }) + assert.match((await read()).error, /network or proxy/) + f.env.TEST_MODE = "" + assert.match((await read()).error, /network or proxy/, "the same agy is held") + const other = path.join(path.dirname(f.executable), "agy2" + path.extname(f.executable)) + await fs.copyFile(f.executable, other) + await fs.chmod(other, 0o755) + agy = other + assert.equal((await read()).windows.length, 1) + await f.assertClean() +}) + const startupAuthLogs = [ "W1115 15:13:30.249469 10 cache.go:157] error getting token source: You are not logged into Antigravity.", "I1115 15:13:30.317328 1 server_oauth.go:226] OAuth: authenticated successfully", diff --git a/packages/agy-cli/usage.mjs b/packages/agy-cli/usage.mjs index 2734728..e9ff7a6 100644 --- a/packages/agy-cli/usage.mjs +++ b/packages/agy-cli/usage.mjs @@ -489,7 +489,7 @@ export async function fetchUsage(agy, { quota = readQuotaDirect, direct = false, } = {}) { - if (!agy) throw new UsageError("agy CLI not found. Install it and run `agy` once to sign in.") + if (!agy) throw new UsageError(NO_AGY) const deadline = Date.now() + timeout(timeoutMs) const directory = await fs.mkdtemp(path.join(tempRoot, "magpie-agy-usage-")) let pendingTreeKill = null @@ -600,6 +600,10 @@ function backoff(n) { return Math.min(BACKOFF_FIRST_MS * 2 ** Math.max(0, Math.min(n, 20) - 1), BACKOFF_MOST_MS) } +// what usage says while no agy is found: never held (createUsageReader), +// and in noAgy's words, so it says how magpie gets one +export const NO_AGY = "agy CLI not found. Sign in to this account again in magpie to have it installed, or install Antigravity CLI yourself." + const NEEDS_SIGN_IN = "Sign in again from this account's Sign in in magpie, or run `agy` in a terminal; magpie doesn't run agy for usage until then." // No completed-result cache: sequential refreshes must see account/allowance changes. @@ -614,7 +618,10 @@ const NEEDS_SIGN_IN = "Sign in again from this account's Sign in in magpie, or r // - an explicit authentication rejection, or an ended token hanging silently // or with sign-in talk, blocks further background runs for that credential. // Diagnostic-only output isn't evidence of a browser sign-in. -// - any other failure isn't run again for backoff(n). +// - any other failure isn't run again for backoff(n). No agy found is not +// held: finding it costs a few stat calls, and an agy installed since (a +// sign-in installs it; tmr11235 on X saw it) is used on the next read, +// not after hours of "not found" while its chats already run. export function createUsageReader(resolveAgy, options = {}) { const { signIn = () => storedSignIn(), now = () => Date.now(), ...fetchOptions } = options const pending = new Map() @@ -631,11 +638,14 @@ export function createUsageReader(resolveAgy, options = {}) { if (why) return expired(why) if (isDead(stored)) return expired("agy's sign-in no longer works") const key = stored?.state === "present" ? stored.fp : "unknown" - if (held && held.key === key && now() < held.until) { + const agy = resolveAgy() + if (!agy) return { windows: [], error: NO_AGY, signIn: "kept" } + // a failure held for another agy (gone, or another found since) isn't + // this one's + if (held && held.key === key && held.agy === agy && now() < held.until) { return { windows: [], error: held.error, signIn: held.auth ? "expired" : "kept" } } try { - const agy = resolveAgy() // an access token that has ended or ends within two minutes, with a // refresh token: read without running agy (fetchUsage's direct) const direct = stored?.state === "present" && stored.canRenew && stored.expiresAt > 0 && stored.expiresAt - now() < 2 * 60 * 1000 @@ -659,8 +669,8 @@ export function createUsageReader(resolveAgy, options = {}) { noteDead(stored) return expired("agy's sign-in no longer works") } - const n = held?.key === key ? held.n + 1 : 1 - held = { key, n, until: now() + backoff(n), error: message, auth } + const n = held?.key === key && held.agy === agy ? held.n + 1 : 1 + held = { key, agy, n, until: now() + backoff(n), error: message, auth } if (auth) saidExpired = true return { windows: [], error: message, signIn: auth ? "expired" : "kept" } }