From e4c825b5544d99a688d92ed32e688ae5f768e731 Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 15 Nov 2026 13:55:42 +0800 Subject: [PATCH] agy-cli 0.1.61: picks stick, and a second Google account can be signed in MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Archivemylife on X: "没法sign in第二个账号,点击sign in again后过一会就 恢复原状,没有任何报错" and "配置后报存提示成功,再打开还是全部都启用". Picks: while agy's model list wasn't known yet (agy missing, signed out, or the probe still running), the models hook served the static or Gemini-only catalog as if it were the real list. magpie relisted on that, dropped the user's picks that weren't in it, and the editor came back with every model on. The hook now marks such a list with Symbol.for("magpie.fellBack"), so the host keeps the last good list and the picks. Second account: "Sign in again" with agy already signed in succeeded at once with the stored sign-in, so nothing changed and nothing said why. agy holds one Google account in its keyring. A second method, "Switch to another Google account (agy holds one)" / "换一个 Google 账号(agy 只能 登录一个)", always runs agy's Google login, which replaces the stored account. The sign-in result carries the stored id_token_email, so the account is named by its email instead of "API key", and a switch shows. READMEs say agy keeps one account. magpie needs no change: it already keeps the last good list for a list marked fell back, and shows a method picker for two methods. Run: - packages/agy-cli bun test (HOME=mktemp -d): 24 pass, 0 fail. - test/smoke.mjs (AGY_BRIDGE_STORED_SIGNIN=skip): all ok. - Red on the old index.mjs/signin.mjs with the new tests: signin red (emailOf missing), catalog 3 fail (the three new tests), smoke BAD on the two-methods check. - Plugins root bun test (HOME=mktemp -d) on Linux (wsl-run, magpie-desktop) at this tree: 8754 pass, 19 skip, 0 fail. - Real magpie GUI in a sandbox HOME with this plugin installed: picked two models, deleted the plugin's models.json and killed the plugin host, POST /api/provider/models: before, count 2 and the pick dropped; after, count 5, the pick kept, nothing delisted. "重新登录" shows both methods in en and zh, no page errors, and the account is named by its gmail address. Not tried: signing a real second Google account in (it would change the live agy keyring), Windows and Linux agy. --- packages/agy-cli/README.en.md | 9 ++- packages/agy-cli/README.md | 5 +- packages/agy-cli/index.mjs | 97 +++++++++++++++++++++---------- packages/agy-cli/package.json | 2 +- packages/agy-cli/signin.mjs | 52 +++++++++++++---- packages/agy-cli/test/catalog.mjs | 51 ++++++++++++++++ packages/agy-cli/test/signin.mjs | 19 +++++- packages/agy-cli/test/smoke.mjs | 15 ++++- 8 files changed, 204 insertions(+), 46 deletions(-) diff --git a/packages/agy-cli/README.en.md b/packages/agy-cli/README.en.md index 17c5576..66b67f5 100644 --- a/packages/agy-cli/README.en.md +++ b/packages/agy-cli/README.en.md @@ -162,8 +162,13 @@ After installing, sign in from Magpie; no terminal needed. code the page shows (or the page's whole address) back into Magpie. This works with Magpie on a server or in Docker too. The sign-in waits 15 minutes. Google credentials stay with agy (in the system keyring); the - plugin never reads or stores them, and counts the sign-in as done only once - `agy models` lists the account's models. + plugin never stores them, and counts the sign-in as done only once + `agy models` lists the account's models. Magpie names the account by the + Google email agy stored (the one thing read from the keyring for it). + agy holds one Google account, so a second one can't be added beside it. To + change accounts, click Sign in and pick "Switch to another Google account": + agy runs its Google sign-in even while signed in, and the new account + replaces the old one. 2. Refer to models as `agy-cli/`. When agy lists separate model IDs for different thinking levels, they are grouped here as variants of one model, and each request is mapped back to the matching agy ID. diff --git a/packages/agy-cli/README.md b/packages/agy-cli/README.md index ef56043..b9eab9f 100644 --- a/packages/agy-cli/README.md +++ b/packages/agy-cli/README.md @@ -116,7 +116,10 @@ magpie plugin add @magpie-community/opencode-agy-cli-auth 没登录时插件运行 agy 自己的 Google 登录(`agy acp --login`),Magpie 打开登录页, 登录后把页面显示的授权码(或整个页面地址)粘贴回 Magpie。Magpie 在服务器或 Docker 里也一样。登录的有效期是 15 分钟。Google 凭据始终由 agy 自己保管(系统钥匙串), - 插件不读取、不保存;agy 列出账号的模型(`agy models`)后才算登录成功。 + 插件不保存;agy 列出账号的模型(`agy models`)后才算登录成功。账号在 Magpie 里以 agy + 存的 Google 邮箱命名(只从钥匙串里读这一项)。 + agy 只能登录一个 Google 账号,所以不能并列添加第二个。要换账号,点 Sign in 后选 + 「换一个 Google 账号」:agy 即使已经登录也会重新走 Google 登录,新账号替换旧账号。 2. 模型名写成 `agy-cli/<模型>`。agy 对同一模型不同思考等级给出的多个模型 ID, 在这里会合并成一个模型的多个变体,请求时再映射回对应的 agy ID。 3. 在客户端里选用这个模型即可。 diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index f763c46..adab8e1 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -8,7 +8,7 @@ import os from "node:os" import path from "node:path" import { fileURLToPath } from "node:url" import { createUsageReader } from "./usage.mjs" -import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, storedSignInNow } from "./signin.mjs" +import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, storedEmail, storedSignInNow } from "./signin.mjs" import { sanitizePatternFields } from "./re2-pattern.mjs" import { startLogin } from "./login.mjs" import { ensureGeminiArrayItems } from "./array-items.mjs" @@ -5872,6 +5872,43 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a return proc.startTurn(contentParts, body.messages, model, selection) } +function noAgy() { + return { type: "failed", error: "agy CLI not found. Install Antigravity CLI first: https://antigravity.google/docs/cli" } +} + +// signedInAs is the sign-in's result, named by the Google account agy is +// signed in to when its keyring says (magpie shows the account by it, +// not as "API key"). +async function signedInAs() { + const email = await storedEmail() + return { type: "success", key: "agy", ...(email ? { metadata: { email } } : {}) } +} + +// googleSignIn runs agy's own Google sign-in: its link, then the code the +// page shows. +async function googleSignIn(agy) { + const login = await startLogin(agy) + if (login.error) return { type: "failed", error: login.error } + return { + url: login.url, + instructions: "", + method: "code", + callback: async (code, opts = {}) => { + const done = await login.finish(code, { signal: opts.signal }) + if (done.error) return { type: "failed", error: done.error } + // agy stored a new sign-in: read it again, and let what + // failed with the old one run again + forgetStoredSignIn({ dead: true }) + // A new account: what agy offered the last one, or refused + // before the sign-in, is asked again. + forgetOffered() + const probe = await probeSignedIn(agy) + if (!probe.ok) return { type: "failed", error: `agy signed in, but ${probe.why}` } + return signedInAs() + }, + } +} + export const AntigravityBridgePlugin = async () => { const readUsage = createUsageReader(findAgy) return { @@ -5885,41 +5922,33 @@ export const AntigravityBridgePlugin = async () => { // agy's own Google sign-in (`agy acp --login`): magpie opens its // link and takes the code the page shows. agy keeps the token; // the plugin's account is only "agy", saved once agy says the - // sign-in took and lists the account's models. + // sign-in took and lists the account's models. Signed in to agy + // already, nothing opens: the account agy has is the one saved. type: "oauth", label: "Sign in with Google", + labels: { zh: "使用 Google 登录", "zh-TW": "使用 Google 登入", ja: "Google でサインイン" }, authorize: async () => { const agy = findAgy() - if (!agy) { - return { - type: "failed", - error: "agy CLI not found. Install Antigravity CLI first: https://antigravity.google/docs/cli", - } - } - // signed in to agy already: nothing to open + if (!agy) return noAgy() if ((await probeSignedIn(agy)).ok) { - return { url: "", instructions: "", method: "auto", callback: async () => ({ type: "success", key: "agy" }) } - } - const login = await startLogin(agy) - if (login.error) return { type: "failed", error: login.error } - return { - url: login.url, - instructions: "", - method: "code", - callback: async (code, opts = {}) => { - const done = await login.finish(code, { signal: opts.signal }) - if (done.error) return { type: "failed", error: done.error } - // agy stored a new sign-in: read it again, and let what - // failed with the old one run again - forgetStoredSignIn({ dead: true }) - // A new account: what agy offered the last one, or refused - // before the sign-in, is asked again. - forgetOffered() - const probe = await probeSignedIn(agy) - if (!probe.ok) return { type: "failed", error: `agy signed in, but ${probe.why}` } - return { type: "success", key: "agy" } - }, + return { url: "", instructions: "", method: "auto", callback: async () => signedInAs() } } + return googleSignIn(agy) + }, + }, + { + // agy keeps one Google account (the system keyring's), so a + // second account isn't added beside the first: this signs agy in + // to another one in its place, even while it is signed in. The + // first way, signed in already, ends at once with nothing changed + // (Archivemylife on X: "Sign in again" did nothing). + type: "oauth", + label: "Switch to another Google account (agy holds one)", + labels: { zh: "换一个 Google 账号(agy 只能登录一个)", "zh-TW": "換一個 Google 帳號(agy 只能登入一個)", ja: "別の Google アカウントに切り替える(agy は 1 つだけ)" }, + authorize: async () => { + const agy = findAgy() + if (!agy) return noAgy() + return googleSignIn(agy) }, }, ], @@ -6158,6 +6187,14 @@ export const AntigravityBridgePlugin = async () => { // Never force a refresh here: Magpie times models() out after about two seconds. const catalog = await loadModelCatalog(agy, { probeOffered: true }) const out = {} + // Not the account's list yet: the static one (no agy, signed out, + // or agy hasn't answered), or Gemini alone while agy acp is still + // asked what it offers. magpie keeps the list it had and the + // user's picks with it; a cold host's short list dropped every + // other pick (Archivemylife on X: the picks didn't stick). + if (cachedModelCatalog.isFallback || (!acpOfferedModels && (modelCatalogRefreshPromise || offeredProbePromise))) { + out[Symbol.for("magpie.fellBack")] = true + } for (const model of catalog.models) { const imageModel = /^(?:gemini-|claude-)/.test(model.id) out[model.id] = { diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index edc274b..03d8ef0 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.60", + "version": "0.1.61", "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 fef644d..1c95aa4 100644 --- a/packages/agy-cli/signin.mjs +++ b/packages/agy-cli/signin.mjs @@ -78,18 +78,25 @@ function run(file, args) { }) } -// parseStored is what a stored value says, "unknown" when it isn't the -// shape agy writes. -export function parseStored(raw, now = Date.now()) { +// decodeStored is a stored value's JSON as go-keyring wrote it, or null +// when it isn't that. +function decodeStored(raw) { let value = String(raw ?? "").trim() - const fp = createHash("sha256").update(value).digest("hex").slice(0, 32) if (value.startsWith("go-keyring-base64:")) { value = Buffer.from(value.slice("go-keyring-base64:".length), "base64").toString("utf8") } else if (value.startsWith("go-keyring-encoded:")) { value = Buffer.from(value.slice("go-keyring-encoded:".length), "hex").toString("utf8") } - let stored - try { stored = JSON.parse(value) } catch { return { state: "unknown" } } + try { return JSON.parse(value) } catch { return null } +} + +// parseStored is what a stored value says, "unknown" when it isn't the +// shape agy writes. It says nothing of who: the account's email isn't kept +// with the cached read (storedEmail reads it when a sign-in names it). +export function parseStored(raw, now = Date.now()) { + const fp = createHash("sha256").update(String(raw ?? "").trim()).digest("hex").slice(0, 32) + const stored = decodeStored(raw) + if (!stored) return { state: "unknown" } // a Gemini API key needs no Google sign-in if (typeof stored?.api_key === "string" && stored.api_key !== "") return { state: "unknown" } const token = stored?.token @@ -103,8 +110,16 @@ export function parseStored(raw, now = Date.now()) { return { state: "present", fp, canRenew, expiresAt, expired: expiresAt > 0 && now >= expiresAt } } -// readStoredSignIn reads agy's stored sign-in on this computer. -export async function readStoredSignIn({ platform = process.platform, exec = run, now = Date.now(), env = process.env } = {}) { +// emailOf is the Google account a stored value is signed in to, "" when +// it doesn't say. +export function emailOf(raw) { + const email = decodeStored(raw)?.id_token_email + return typeof email === "string" ? email.trim().slice(0, 200) : "" +} + +// readStoredValue reads agy's keyring value on this computer: { raw }, or +// { state } when there is none ("missing") or it can't be read ("unknown"). +async function readStoredValue({ platform = process.platform, exec = run, env = process.env } = {}) { // tests, and setups this reading doesn't fit, turn it off if (env.AGY_BRIDGE_STORED_SIGNIN === "skip") return { state: "unknown" } // agy signs in with these instead of a stored Google sign-in @@ -114,7 +129,7 @@ export async function readStoredSignIn({ platform = process.platform, exec = run // 44: errSecItemNotFound if (r.code === 44) return { state: "missing" } if (r.code !== 0) return { state: "unknown" } - return parseStored(r.stdout, now) + return { raw: r.stdout } } if (platform === "win32") { const r = await exec("powershell.exe", ["-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", WINDOWS_SCRIPT]) @@ -124,11 +139,28 @@ export async function readStoredSignIn({ platform = process.platform, exec = run if (out === "MISSING") return { state: "missing" } if (!out.startsWith("OK ")) return { state: "unknown" } // go-keyring on Windows stores the value's bytes as they are (UTF-8) - return parseStored(Buffer.from(out.slice(3), "base64").toString("utf8"), now) + return { raw: Buffer.from(out.slice(3), "base64").toString("utf8") } } return { state: "unknown" } } +// readStoredSignIn reads agy's stored sign-in on this computer. +export async function readStoredSignIn({ now = Date.now(), ...opts } = {}) { + const v = await readStoredValue(opts) + return "raw" in v ? parseStored(v.raw, now) : v +} + +// 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) { + try { + const v = await readStoredValue(opts) + return "raw" in v ? emailOf(v.raw) : "" + } catch { + return "" + } +} + // 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/catalog.mjs b/packages/agy-cli/test/catalog.mjs index 65151f8..b0b4dd6 100644 --- a/packages/agy-cli/test/catalog.mjs +++ b/packages/agy-cli/test/catalog.mjs @@ -545,3 +545,54 @@ test("慢刷新与失败刷新都不会挂住 Node 退出(独立子进程实 assert.ok(report.a > 0 && report.b > 0) assert.ok(wall < 8_000, `子进程 ${wall}ms 才退出,疑似被定时器挂住`) }) + +// Archivemylife on X: picks saved in magpie were gone on the next open. A +// cold host served the static list (or Gemini alone, before agy acp said +// what it offers) as if it were the account's, and magpie set aside every +// pick it didn't name. Such a list says it fell back, so magpie keeps the +// one it had; the account's own list doesn't. +const FELL_BACK = Symbol.for("magpie.fellBack") + +test("静态目录与探测前只有 Gemini 的目录都标为 fell back,账号自己的目录不标", async () => { + await withKit({ agyPath: null }, async (kit) => { + assert.equal((await kit.models())[FELL_BACK], true, "没有 agy 的静态目录没标 fell back") + }) + await withKit({ platform: "darwin", storedSignIn: "missing", modelsBehavior: DYNAMIC_OK }, async (kit) => { + assert.equal((await kit.models())[FELL_BACK], true, "没登录的静态目录没标 fell back") + await warmed(kit) + }) + await withKit(SLOW_AGY, async (kit) => { + const first = await kit.models() + assertFallbackPresent(first) + assert.equal(first[FELL_BACK], true, "冷启动的静态目录没标 fell back") + await warmed(kit) + const listed = await kit.models() + assertClaudeListed(listed, "热身后的 models()") + assert.equal(listed[FELL_BACK], undefined, "账号自己的目录标成了 fell back") + }) +}) + +test("agy models 答了、探测还没答时只有 Gemini 的目录标 fell back", async () => { + await withKit({ modelsBehavior: DYNAMIC_OK, sessionNewDelayMs: SLOW_MS, offeredModels: OFFERED_CLAUDE }, async (kit) => { + const first = await kit.models() + assert.ok(!Object.keys(first).some(id => id.startsWith("claude-")), Object.keys(first).join(",")) + assert.equal(first[FELL_BACK], true, "探测前只有 Gemini 的目录没标 fell back") + await warmed(kit) + const listed = await kit.models() + assertClaudeListed(listed, "探测后的 models()") + assert.equal(listed[FELL_BACK], undefined) + }) +}) + +test("已登录时登录结果用 agy 存的 Google 账号命名,而不是一个 API key", async () => { + const value = "go-keyring-base64:" + Buffer.from(JSON.stringify({ token: { access_token: "a", refresh_token: "r", expiry: "2020-01-01T00:00:00Z" }, id_token_email: "second@example.com" })).toString("base64") + await withKit({ platform: "darwin", storedSignIn: value + "\n", modelsBehavior: DYNAMIC_OK }, async (kit) => { + const started = await kit.plugin.auth.methods[0].authorize() + assert.equal(started.method, "auto") + const done = await started.callback() + assert.equal(done.type, "success") + assert.equal(done.key, "agy") + assert.deepEqual(done.metadata, { email: "second@example.com" }) + await warmed(kit) + }) +}) diff --git a/packages/agy-cli/test/signin.mjs b/packages/agy-cli/test/signin.mjs index ddd731e..8d973c8 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, forgetStoredSignIn, isDead, noteDead, parseStored, readStoredSignIn, storedSignIn, storedSignInNow } from "../signin.mjs" +import { backgroundBlocked, cannotSignIn, emailOf, forgetStoredSignIn, isDead, noteDead, parseStored, readStoredSignIn, 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 }) @@ -102,3 +102,20 @@ test("storedSignInNow answers from the last read without waiting, and reads agai assert.equal(reads, 1) forgetStoredSignIn({ dead: true }) }) + +// 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. +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") + assert.equal(emailOf(value), "someone@example.com") + assert.equal(emailOf(stored({ access_token: "a" }, { id_token_email: undefined })), "") + assert.equal(emailOf("garbage"), "") + const mac = (code, stdout = "") => async () => ({ code, stdout }) + assert.equal(await storedEmail({ platform: "darwin", exec: mac(0, b64(value) + "\n"), env: {} }), "someone@example.com") + assert.equal(await storedEmail({ platform: "darwin", exec: mac(44), env: {} }), "") + assert.equal(await storedEmail({ platform: "darwin", exec: async () => { throw new Error("no security") }, env: {} }), "") + assert.equal(await storedEmail({ platform: "win32", exec: mac(0, "OK " + Buffer.from(value).toString("base64") + "\r\n"), env: {} }), "someone@example.com") + assert.equal(await storedEmail({ platform: "darwin", exec: mac(0, b64(value)), env: { AGY_BRIDGE_STORED_SIGNIN: "skip" } }), "") +}) diff --git a/packages/agy-cli/test/smoke.mjs b/packages/agy-cli/test/smoke.mjs index 256347b..15176f1 100644 --- a/packages/agy-cli/test/smoke.mjs +++ b/packages/agy-cli/test/smoke.mjs @@ -753,13 +753,26 @@ const legacyModel = "agy-cli/gemini-test-low" const before = logs().filter(event => event.type === "models").length const result = await plugin.auth.methods[0].authorize() const probes = logs().filter(event => event.type === "models").slice(before) - check("sign-in is agy's Google sign-in, an oauth way", plugin.auth.methods.length === 1 && plugin.auth.methods[0].type === "oauth") + check("sign-in is agy's Google sign-in, an oauth way, and a way to switch accounts", plugin.auth.methods.length === 2 && plugin.auth.methods.every(m => m.type === "oauth")) check("signed in to agy already, the sign-in opens nothing", result.url === "" && result.method === "auto") check("signed in to agy already, the sign-in saves agy", (await result.callback())?.type === "success") check("authorize login probe disables auto update", probes.length === 1 && probes[0].update === "true") check("signed in already, agy's sign-in isn't started", !logs().some(event => event.type === "login")) } +{ + // Archivemylife on X: signed in already, "Sign in again" changed nothing. + // agy holds one Google account; the second way signs it in to another in + // its place, even while it is signed in. + const switcher = plugin.auth.methods[1] + const before = logs().filter(event => event.type === "login").length + const a = await switcher.authorize() + check("signed in already, switching accounts still opens Google's link", /^https:\/\/accounts\.google\.com\//.test(a.url ?? "") && a.method === "code", JSON.stringify(a)) + check("switching accounts runs agy's own sign-in", logs().filter(event => event.type === "login").length === before + 1) + const good = await a.callback("good-code") + check("the other account's sign-in saves agy", good?.type === "success" && good.key === "agy", JSON.stringify(good)) +} + { // signed out: agy's own sign-in gives the link and takes the pasted code const signedOut = path.join(stateDir, "signed-out")