From 44bfefb7a7336c7364b230922b75e9d1a0e3a36d Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 17 Nov 2026 02:50:13 +0800 Subject: [PATCH] agy-cli 0.1.84: an ended access token is renewed by the plugin for usage, so agy never opens a sign-in (#1234) qiankun229 traced it in agy's own logs (#1234): at Windows startup the background usage read ran `agy -p /usage` with an ended access token and a refresh token. agy's silent renewal failed for a moment (a 10s keyring timeout, or "no such host" for oauth2.googleapis.com before the network was up) and agy fell back to an interactive Google sign-in, which opens the browser through ShellExecuteW past the BROWSER/PATH shims. The next read renewed the same token fine. The stored-sign-in precheck passes such a token, since it can be renewed. - createUsageReader: when the stored access token has ended or ends within two minutes and has a refresh token, fetchUsage reads with `direct`: it runs `agy --version` only (no sign-in) and reads the quota the way agy does (readQuotaDirect, loadCodeAssist then retrieveUserQuotaSummary, with agy's User-Agent), renewing the token in memory. agy's stored sign-in is never written. `agy -p` isn't run. - A failed renewal is a failed read: it backs off as before and keeps the sign-in. A network error says to check the network or proxy. - Google answering the refresh with invalid_grant (400/401) is kind "auth": the account reads as signed out ("Sign in again") and nothing runs for that sign-in again until another is stored. - A token with time left still goes through agy -p, as before. Tests: three tests that leaned on an ended token only to get agy to run now use a token whose end isn't said (as the existing "refreshing" test does); what they check is unchanged. Run (mote, HOME=$(mktemp -d)): - test/usage.mjs (AGY_BRIDGE_STORED_SIGNIN=skip node --test): 41 pass. - bun test agy-cli.test.mjs: 20 pass, 0 fail. - bun scripts/check.mjs agy-cli: ok. Broken by hand: origin/main's usage.mjs with the new tests: the three new tests fail (agy -p ran for an ended token; no backoff/network message; invalid_grant not auth), 38 pass. Not tried: Windows with a real ended token and the network down at startup (no agy account here: the local one answers 403); the requests are the ones the region-refusal path has made since 0.1.7x. --- packages/agy-cli/package.json | 2 +- packages/agy-cli/test/usage.mjs | 89 +++++++++++++++++++++++++++++++-- packages/agy-cli/usage.mjs | 31 +++++++++++- 3 files changed, 117 insertions(+), 5 deletions(-) diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index a9205be..5295492 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.83", + "version": "0.1.84", "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/test/usage.mjs b/packages/agy-cli/test/usage.mjs index 780c59d..181b613 100644 --- a/packages/agy-cli/test/usage.mjs +++ b/packages/agy-cli/test/usage.mjs @@ -716,7 +716,7 @@ test("never runs agy while it has no stored sign-in, or one that ended with noth let stored = { state: "missing" } const read = createUsageReader(() => f.executable, { ...f.options, signIn: async () => stored }) assert.equal((await read()).signIn, "expired") - stored = { state: "present", fp: "b", canRenew: true, expiresAt: 1, expired: true } + stored = { state: "present", fp: "b", canRenew: true, expiresAt: 0, expired: false } const back = await read() assert.equal(back.windows.length, 1) assert.equal(back.signIn, "renewed") @@ -729,7 +729,7 @@ test("a sign-in agy failed on isn't run again in the background until another is t.after(() => forgetStoredSignIn({ dead: true })) const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "You are not logged in. Please sign in." }) let clock = 0 - let stored = { state: "present", fp: "old", canRenew: true, expiresAt: 1, expired: true } + let stored = { state: "present", fp: "old", canRenew: true, expiresAt: 0, expired: false } const read = createUsageReader(() => f.executable, { ...f.options, now: () => clock, signIn: async () => stored }) assert.equal((await read()).signIn, "expired") const runs = (await f.logs()).length @@ -750,7 +750,7 @@ test("a hung sign-in with an ended token is never restarted until the credential forgetStoredSignIn({ dead: true }) t.after(() => forgetStoredSignIn({ dead: true })) const f = await fixture(t, { TEST_MODE: "hang", TEST_ERROR: output }) - let stored = { state: "present", fp: "hung", canRenew: true, expiresAt: 1, expired: true } + let stored = { state: "present", fp: "hung", canRenew: true, expired: true } let clock = 0 const read = createUsageReader(() => f.executable, { ...f.options, timeoutMs: 3000, now: () => clock, signIn: async () => stored }) assert.equal((await read()).signIn, "expired") @@ -957,6 +957,89 @@ test("a direct read that fails leaves the region refusal standing: unknown, neve } }) +// plugins#1234 (qiankun229): agy run for usage with an ended access token +// renews it first, and when that failed for a moment (a DNS miss at +// Windows startup, a 10s keyring timeout) it opened Google's sign-in in the +// browser. With such a token agy -p isn't run: the quota is read directly. +test("an ended or ending access token with a refresh token is read without running agy -p", async t => { + for (const ends of [1, 1_000_000 + 60_000]) { + const f = await fixture(t, { TEST_VERSION: "1.5.9" }) + const asked = [] + const quota = async o => { asked.push(o.version); return SUMMARY } + const stored = { state: "present", fp: "ended", canRenew: true, expiresAt: ends, expired: ends === 1 } + const read = createUsageReader(() => f.executable, { ...f.options, quota, now: () => 1_000_000, signIn: async () => stored }) + const result = await read() + assert.equal(result.error, undefined) + assert.equal(result.signIn, "kept") + assert.equal(result.windows.length, 2) + assert.deepEqual(asked, ["1.5.9"]) + assert.deepEqual((await f.logs()).map(l => l.args[0]), ["--version"]) + await f.assertClean() + } + // a token with time left still goes through agy + const f = await fixture(t) + let asked = 0 + const stored = { state: "present", fp: "live", canRenew: true, expiresAt: 1_000_000 + 10 * 60_000, expired: false } + const read = createUsageReader(() => f.executable, { ...f.options, quota: async () => { asked++; return SUMMARY }, now: () => 1_000_000, signIn: async () => stored }) + assert.equal((await read()).windows.length, 1) + assert.equal(asked, 0) + assert.deepEqual((await f.logs()).map(l => l.args[0]), ["--version", "-p"]) +}) + +test("a renewal that fails for a moment backs off and keeps the sign-in; one Google refuses asks for a new sign-in", async t => { + forgetStoredSignIn({ dead: true }) + t.after(() => forgetStoredSignIn({ dead: true })) + const f = await fixture(t) + let clock = 1_000_000 + let fail = () => { throw new TypeError("fetch failed: getaddrinfo ENOTFOUND oauth2.googleapis.com") } + let asked = 0 + const quota = async () => { asked++; return fail() } + const stored = { state: "present", fp: "blip", canRenew: true, expiresAt: 1, expired: true } + const read = createUsageReader(() => f.executable, { ...f.options, quota, now: () => clock, signIn: async () => stored }) + const first = await read() + assert.equal(first.signIn, "kept") + assert.match(first.error, /network or proxy/) + assert.equal((await read()).signIn, "kept") + assert.equal(asked, 1, "held until the backoff ends") + clock += 10 * 60 * 1000 + fail = () => SUMMARY + const back = await read() + assert.equal(back.windows.length, 2) + assert.equal(back.signIn, "kept") + assert.ok((await f.logs()).every(l => l.args[0] === "--version"), "agy -p never ran") + // Google refusing the refresh token: the sign-in is over, and nothing runs for it again + const refused = { ...stored, fp: "revoked" } + const api = async () => new Response(JSON.stringify({ error: "invalid_grant", error_description: "Token has been expired or revoked." }), { status: 400 }) + const ended = structuredClone(STORED) + ended.token.expiry = new Date(Date.now() - 60_000).toISOString() + const read2 = createUsageReader(() => f.executable, { + ...f.options, now: () => clock, signIn: async () => refused, + quota: o => readQuotaDirect({ ...o, stored: async () => ended, fetch: api }), + }) + const over = await read2() + assert.equal(over.signIn, "expired") + assert.match(over.error, /Sign in again/) + clock += 7 * 60 * 60 * 1000 + assert.equal((await read2()).signIn, "expired") + await f.assertClean() +}) + +test("the direct read's renewal: invalid_grant is a sign-in that no longer works, anything else a failed read", async t => { + const ended = structuredClone(STORED) + ended.token.expiry = new Date(Date.now() - 60_000).toISOString() + for (const [status, body, kind] of [ + [400, { error: "invalid_grant" }, "auth"], + [401, { error: "invalid_grant" }, "auth"], + [400, { error: "invalid_request" }, ""], + [503, { error: "backendError" }, ""], + [500, "not json", ""], + ]) { + const fetchFn = async () => new Response(typeof body === "string" ? body : JSON.stringify(body), { status }) + await assert.rejects(readQuotaDirect({ env: {}, version: "1.5.9", deadline: Date.now() + 5000, stored: async () => ended, fetch: fetchFn }), + e => e.kind === kind && /sign-in/.test(e.message), `${status} ${JSON.stringify(body)}`) + } +}) + test("only a region refusal reads the quota directly", async t => { for (const error of [ "Eligibility check failed: EOF", diff --git a/packages/agy-cli/usage.mjs b/packages/agy-cli/usage.mjs index ff301ad..a285bb7 100644 --- a/packages/agy-cli/usage.mjs +++ b/packages/agy-cli/usage.mjs @@ -395,6 +395,11 @@ export async function readQuotaDirect({ let fresh try { fresh = JSON.parse(await res.text()) } catch {} access = res.ok ? text(fresh?.access_token) : "" + // Google's answer for a refresh token it no longer takes: only a new + // sign-in mends it + if (!access && (res.status === 400 || res.status === 401) && fresh?.error === "invalid_grant") { + throw new UsageError("agy's stored sign-in no longer works.", { kind: "auth" }) + } if (!access) throw new UsageError("agy's stored sign-in couldn't be renewed.") } const base = (text(env.CLOUD_CODE_URL) || CODE_ASSIST).replace(/\/+$/, "") @@ -422,6 +427,7 @@ export async function fetchUsage(agy, { signal, tempRoot = os.tmpdir(), quota = readQuotaDirect, + direct = false, } = {}) { if (!agy) throw new UsageError("agy CLI not found. Install it and run `agy` once to sign in.") const deadline = Date.now() + timeout(timeoutMs) @@ -459,6 +465,23 @@ 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.") + // agy's access token has ended (or is about to): agy renews it when it + // runs, and when that renewal fails, even for a moment (DNS at startup, + // a slow keyring), agy starts its own Google sign-in, which on Windows + // opens the browser past every shim (plugins#1234). So the quota is + // read the way agy reads it, renewing the token in memory, and agy -p + // isn't run: a failed renewal is a failed read, never a sign-in. + if (direct) { + 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" }) + if (error instanceof UsageError) throw error + throw new UsageError("agy's stored sign-in couldn't be renewed. Check the network or proxy.") + } + return parseUsageReport({ status: "SUCCESS", command: { name: "usage", data } }) + } 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) let report try { report = JSON.parse(result.stdout) } catch {} @@ -523,6 +546,9 @@ const NEEDS_SIGN_IN = "Sign in again from this account's Sign in in magpie, or r // there is none, or it has ended with nothing to renew it: the read says // the sign-in has expired (signIn "expired"), which magpie shows on the // account, and nothing starts a Google sign-in in the background. +// - while its access token has ended with a refresh token to renew it, agy +// -p isn't run either: the quota is read directly (fetchUsage's direct), +// so a renewal that fails for a moment can't start one (plugins#1234). // - 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. @@ -548,8 +574,11 @@ export function createUsageReader(resolveAgy, options = {}) { } 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 if (!pending.has(agy)) { - const query = fetchUsage(agy, fetchOptions).finally(() => { + const query = fetchUsage(agy, { ...fetchOptions, direct }).finally(() => { if (pending.get(agy) === query) pending.delete(agy) }) pending.set(agy, query)