agy-cli 0.1.67: more than one Google account, each with its own usage

tongzhenbao on X wanted several accounts with their usage, as the old
built-in had. agy keeps one sign-in where it looks for it (the system
keyring's single "gemini"/"antigravity" entry), so the plugin was
single: true and its second sign-in way replaced the account.

Now the first account is agy's own, unchanged, and "Add another Google
account" signs another one in to an agy whose home is the account's
own (XDG_STATE_HOME/magpie-agy-bridge/accounts/<id>). Every agy run for
that account (sign-in, models, usage, requests) gets HOME (USERPROFILE
on Windows) there and SSH_CONNECTION set, which agy 1.5 reads as an SSH
session and so keeps the sign-in in .gemini/antigravity-cli/
antigravity-oauth-token under that home rather than the keyring. The
account's home is saved in its metadata (agyHome); the loader, usage and
models run its work in an AsyncLocalStorage scope that childEnv and the
stored sign-in read follow. Its conversations are keyed apart, and it
gets no --gemini-dir (its token is under its own .gemini). single: true
is gone, so each account has its own row and usage and rotates like
any other.

Checked by hand before writing it, with real agy and planted (expired)
tokens in sandbox homes: agy read the file token from the sandbox HOME
on macOS (mote) with SSH_CONNECTION set, on Windows (xiaomi-gpu) with
USERPROFILE set, and in WSL. The live keyring was never touched.

Run:
- packages/agy-cli `HOME=$(mktemp -d) bun test` on mote: 35 pass, 0 fail.
- bun scripts/check.mjs on mote: ok.
- test/smoke.mjs on Windows (win-run): ALL OK (369 checks).
- Broken by hand: the new smoke checks against the old index.mjs,
  signin.mjs and platform.mjs: 6 FAILURES (the method, single, the
  home, SSH_CONNECTION, the saved account, the failed home's cleanup).

Not tried: a real Google sign-in of a second account, so agy writing
the token file under SSH detection is known from file-mode users
(plugins#1165) rather than seen here. Signing an added account in
again makes a new home and leaves the old one (~800K). Every account
shares one model catalog.
This commit is contained in:
yetone
2026-11-15 23:51:00 +08:00
parent 8059af3148
commit e5cb9598c8
9 changed files with 286 additions and 69 deletions
+6 -4
View File
@@ -176,10 +176,12 @@ After installing, sign in from Magpie; no terminal needed.
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.
To add another Google account, click agy-cli's Add another account (or
Sign in) and pick "Add another Google account". The new account gets an
agy home of its own (under `~/.local/state/magpie-agy-bridge/accounts/`),
and agy keeps its sign-in in a file there, leaving the account in the
system keyring as it is. Each account has its own row and its own usage,
and is switched and rotated like any provider's accounts.
2. Refer to models as `agy-cli/<model>`. 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.
+4 -2
View File
@@ -124,8 +124,10 @@ magpie plugin add @magpie-community/opencode-agy-cli-auth
里也一样。登录的有效期是 15 分钟。Google 凭据始终由 agy 自己保管(系统钥匙串),
插件不保存;agy 列出账号的模型(`agy models`)后才算登录成功。账号在 Magpie 里以 agy
存的 Google 邮箱命名(只从钥匙串里读这一项)。
agy 只能登录一个 Google 账号,所以不能并列添加第二个。要换账号,点 Sign in 后选
「换一个 Google 账号」:agy 即使已经登录也会重新走 Google 登录,新账号替换旧账号。
要再加一个 Google 账号,点 agy-cli 的 Add another account(或 Sign in),选「添加另一个
Google 账号」。新账号有自己的 agy 主目录(`~/.local/state/magpie-agy-bridge/accounts/`
下),它的登录保存在那个目录里的文件中,不动系统钥匙串里原来那个账号。每个账号单独一行,
用量分开显示,可以像其他 provider 的账号一样切换和轮换。
2. 模型名写成 `agy-cli/<模型>`。agy 对同一模型不同思考等级给出的多个模型 ID,
在这里会合并成一个模型的多个变体,请求时再映射回对应的 agy ID。
3. 在客户端里选用这个模型即可。
+81
View File
@@ -0,0 +1,81 @@
import { AsyncLocalStorage } from "node:async_hooks"
import { randomBytes } from "node:crypto"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
// More than one Google account. agy keeps one sign-in where it looks for
// it: the system keyring (one entry, "gemini"/"antigravity"), or, where it
// uses none, the file .gemini/antigravity-cli/antigravity-oauth-token under
// its home folder. So the first account is agy's own, as it always was,
// and every other account gets a home folder of its own: its agy runs
// (sign-in, models, usage, requests) are started with HOME (USERPROFILE on
// Windows) there, and with SSH_CONNECTION set, which agy reads as "a
// session over SSH" and so keeps the sign-in in that file rather than in
// the keyring every account would share. agy 1.5 does so on macOS, Windows
// and Linux (WSL and no-D-Bus Linux use the file already).
//
// The account's home is in its saved sign-in (metadata.agyHome, a folder
// name under accountsDir), and the work done for it runs in accountScope,
// which childEnv (platform.mjs) and the stored sign-in's read (signin.mjs)
// follow.
export const accountScope = new AsyncLocalStorage()
const HOME_ID = /^[a-z0-9]{8,32}$/
// accountsDir is where the other accounts' homes are kept.
export function accountsDir(env = process.env) {
const base = env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state")
return path.join(base, "magpie-agy-bridge", "accounts")
}
// homeOf is the folder of the account home id names, or null when id
// isn't one (never a path out of accountsDir).
export function homeOf(id, env = process.env) {
return typeof id === "string" && HOME_ID.test(id) ? path.join(accountsDir(env), id) : null
}
// homeIdOfAuth is the home a saved sign-in names, "" for agy's own.
export function homeIdOfAuth(auth) {
const id = auth?.metadata?.agyHome
return typeof id === "string" && HOME_ID.test(id) ? id : ""
}
// currentHome is the home of the account the current work is for, null
// for agy's own.
export function currentHome() {
return accountScope.getStore()?.home ?? null
}
// inAccount runs fn for the account at home (null: agy's own).
export function inAccount(home, fn) {
return accountScope.run({ home: home || null }, fn)
}
export function tokenFile(home) {
return path.join(home, ".gemini", "antigravity-cli", "antigravity-oauth-token")
}
// accountEnv is what an agy for the account at home is started with.
export function accountEnv(home, platform = process.platform) {
return {
HOME: home,
...(platform === "win32" ? { USERPROFILE: home } : {}),
// agy keeps its sign-in in tokenFile(home), not the keyring
SSH_CONNECTION: "127.0.0.1 0 127.0.0.1 0",
}
}
// newHome makes a home for an account being added: { id, home }.
export function newHome(env = process.env) {
const id = randomBytes(8).toString("hex")
const home = homeOf(id, env)
fs.mkdirSync(home, { recursive: true, mode: 0o700 })
return { id, home }
}
export function dropHome(home) {
if (!home) return
try { fs.rmSync(home, { recursive: true, force: true }) } catch {}
}
+73 -33
View File
@@ -12,6 +12,7 @@ import { storeCatalogRows } from "./model-ids.mjs"
import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, storedEmail, storedSignInNow } from "./signin.mjs"
import { sanitizePatternFields } from "./re2-pattern.mjs"
import { startLogin } from "./login.mjs"
import { currentHome, dropHome, homeIdOfAuth, homeOf, inAccount, newHome } from "./account.mjs"
import { AGY_MANUAL, installAgy, keepAgyCurrent } from "./install.mjs"
import { ensureGeminiArrayItems } from "./array-items.mjs"
import { expandToolSchema } from "./tool-schema.mjs"
@@ -283,6 +284,9 @@ export function fileSignIn(home = os.homedir()) {
}
export async function geminiDirArgs(agyPath, env = process.env) {
// an account with a home of its own (account.mjs) keeps its sign-in in
// a file under that home's .gemini, which agy reads only as its own
if (currentHome()) return { args: [], dir: null }
const dir = bridgeGeminiDir(env)
if (!dir || (!env.AGY_BRIDGE_GEMINI_DIR && fileSignIn())) return { args: [], dir: null }
if (!/--gemini[-_]dir\b/.test(await acpHelp(agyPath))) return { args: [], dir: null }
@@ -1757,9 +1761,11 @@ class Proc {
const own = await geminiDirArgs(this.agyPath)
args.push(...own.args)
// agy writes the conversation's steps under the folder it was given
this.conversationsDir = own.dir && !process.env.AGY_BRIDGE_CONVERSATIONS_DIR
? path.join(own.dir, "antigravity-cli", "conversations")
: null
const home = currentHome()
this.conversationsDir = process.env.AGY_BRIDGE_CONVERSATIONS_DIR ? null
: own.dir ? path.join(own.dir, "antigravity-cli", "conversations")
: home ? path.join(home, ".gemini", "antigravity-cli", "conversations")
: null
try {
const childEnv = { ...process.env }
const inheritedPath = process.env.PATH || childEnv.Path || ""
@@ -5904,25 +5910,34 @@ function noAgy() {
}
// 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() {
// signed in to when its keyring (or token file) says (magpie shows the
// account by it, not as "API key"). An account with a home of its own
// (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()
return { type: "success", key: "agy", ...(email ? { metadata: { email } } : {}) }
const metadata = { ...(email ? { email } : {}), ...(homeId ? { agyHome: homeId } : {}) }
return { type: "success", key: homeId ? `agy:${homeId}` : "agy", ...(Object.keys(metadata).length ? { metadata } : {}) }
}
// 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 }
// page shows. account ({ id, home }) is a new account's own home: agy
// signs in there, and the home goes again when the sign-in fails.
async function googleSignIn(agy, account = null) {
const home = account?.home ?? null
const fail = (error) => {
if (account) dropHome(home)
return { type: "failed", error }
}
const login = await inAccount(home, () => startLogin(agy))
if (login.error) return fail(login.error)
return {
url: login.url,
instructions: "",
method: "code",
callback: async (code, opts = {}) => {
callback: (code, opts = {}) => inAccount(home, async () => {
const done = await login.finish(code, { signal: opts.signal })
if (done.error) return { type: "failed", error: done.error }
if (done.error) return fail(done.error)
// agy stored a new sign-in: read it again, and let what
// failed with the old one run again
forgetStoredSignIn({ dead: true })
@@ -5930,19 +5945,34 @@ async function googleSignIn(agy) {
// 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()
},
if (!probe.ok) return fail(`agy signed in, but ${probe.why}`)
return signedInAs(account?.id ?? "")
}),
}
}
// homeOfAuth is the home of the account a saved sign-in is, null for
// agy's own.
async function homeOfAuth(getAuth) {
let auth
try { auth = typeof getAuth === "function" ? await getAuth() : getAuth } catch {}
return homeOf(homeIdOfAuth(auth))
}
// One usage reader per account: each holds its own last report.
const usageReaders = new Map()
function readUsageOf(home) {
const key = home ?? ""
let read = usageReaders.get(key)
if (!read) usageReaders.set(key, (read = createUsageReader(findAgy)))
return inAccount(home, () => read())
}
export const AntigravityBridgePlugin = async () => {
const readUsage = createUsageReader(findAgy)
keepAgyCurrent(findAgy)
return {
auth: {
provider: PROVIDER_ID,
single: true,
// Magpie's hook for the CLI a plugin runs through: a sign-in on a
// machine without agy (magpie in Docker) installs it first, into the
// plugin's own folder (install.mjs). OpenCode ignores it.
@@ -5957,7 +5987,7 @@ export const AntigravityBridgePlugin = async () => {
},
},
// Magpie's usage hook; OpenCode ignores this extension. agy owns auth.
usage: async () => readUsage(),
usage: async (getAuth) => readUsageOf(await homeOfAuth(getAuth)),
methods: [
{
// agy's own Google sign-in (`agy acp --login`): magpie opens its
@@ -5978,26 +6008,35 @@ export const AntigravityBridgePlugin = async () => {
},
},
{
// 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).
// Another Google account beside the first: agy signs in to it in
// a home of its own (account.mjs), so the one agy has stays.
// Always a new sign-in, even while agy 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 つだけ)" },
label: "Add another Google account",
labels: { zh: "添加另一个 Google 账号", "zh-TW": "新增另一個 Google 帳號", ja: "別の Google アカウントを追加" },
authorize: async () => {
const agy = findAgy()
if (!agy) return noAgy()
return googleSignIn(agy)
let account
try {
account = newHome()
} catch (error) {
return { type: "failed", error: `couldn't make a folder for the account: ${error.message}` }
}
return googleSignIn(agy, account)
},
},
],
loader: async () => {
loader: async (getAuth) => {
// the account's own home, null for agy's own sign-in: every agy
// its requests run is started there
const home = await homeOfAuth(getAuth)
return {
baseURL: "agy://local",
apiKey: "agy",
fetch: async (fetchInput, init = {}) => {
fetch: (fetchInput, init = {}) => inAccount(home, async () => {
const requestUrl = typeof fetchInput === "string"
? fetchInput
: fetchInput instanceof URL
@@ -6048,7 +6087,8 @@ export const AntigravityBridgePlugin = async () => {
body = { ...canonicalBody(body), model: requestedModel }
const model = resolveAgyModel(await loadModelCatalog(agy), requestedModel, body)
const selection = { model: requestedModel, effort: requestedEffort(body) }
const convKey = conversationKey(body)
// an account's conversations are its own: its agy has them
const convKey = (home ? `acct:${path.basename(home)}:` : "") + conversationKey(body)
const trailing = trailingMessages(body)
const isFresh = trailing.history.length === 0
const resultBlocks = extractToolResults(body)
@@ -6213,7 +6253,7 @@ export const AntigravityBridgePlugin = async () => {
} catch (error) {
return jsonError(error.statusCode ?? 502, error.message, error.code, { noRetry: error.noRetry })
}
},
}),
}
},
},
@@ -6223,7 +6263,7 @@ export const AntigravityBridgePlugin = async () => {
// Not an OpenCode hook: the adapter in opencode2.mjs reads the list
// once more when this background work ends.
warming: () => catalogWarming(),
models: async () => {
models: async (_given, ctx) => inAccount(await homeOfAuth(ctx?.auth), async () => {
const agy = findAgy()
// Never force a refresh here: Magpie times models() out after about two seconds.
const catalog = await loadModelCatalog(agy, { probeOffered: true })
@@ -6255,7 +6295,7 @@ export const AntigravityBridgePlugin = async () => {
}
}
return out
},
}),
},
}
}
+2 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-agy-cli-auth",
"version": "0.1.66",
"version": "0.1.67",
"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",
@@ -20,6 +20,7 @@
"usage.mjs",
"model-ids.mjs",
"signin.mjs",
"account.mjs",
"README.md",
"README.en.md",
"LICENSE",
+5 -2
View File
@@ -1,5 +1,6 @@
import { spawn } from "node:child_process"
import path from "node:path"
import { accountEnv, currentHome } from "./account.mjs"
export function agyCandidates(env, home, platform = process.platform) {
const windows = platform === "win32"
@@ -86,11 +87,13 @@ export function agySpawnSpec(file, args, platform = process.platform, env = proc
// AGY_CLI_DISABLE_AUTO_UPDATE (in the parent's environment or the caller's)
// is kept as written. Only when nobody set it do the plugin's children run
// with auto-update off, so a pool of ACP processes doesn't update the binary
// under each other; the user's own `agy` runs keep updating.
// under each other; the user's own `agy` runs keep updating. Work for an
// account with a home of its own (account.mjs) runs agy in that home.
export function childEnv(parent = process.env, extra = {}, platform = process.platform) {
const env = {}
const names = new Map()
for (const source of [parent, extra]) {
const home = currentHome()
for (const source of [parent, extra, home ? accountEnv(home, platform) : null]) {
for (const [key, value] of Object.entries(source || {})) {
if (value === undefined) continue
// Windows treats env names case-insensitively; keep the caller's PATH.
+35 -15
View File
@@ -1,5 +1,7 @@
import { execFile } from "node:child_process"
import { createHash } from "node:crypto"
import fs from "node:fs"
import { currentHome, tokenFile } from "./account.mjs"
// What agy's own sign-in looks like on this computer, read without running
// agy. agy keeps its Google token in the system keyring through go-keyring,
@@ -119,7 +121,16 @@ export function emailOf(raw) {
// 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 } = {}) {
async function readStoredValue({ platform = process.platform, exec = run, env = process.env, home = currentHome() } = {}) {
// an account with a home of its own (account.mjs): agy keeps its
// sign-in in a file there, the same JSON
if (home) {
try {
return { raw: await fs.promises.readFile(tokenFile(home), "utf8") }
} catch (error) {
return { state: error?.code === "ENOENT" ? "missing" : "unknown" }
}
}
// 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
@@ -182,32 +193,42 @@ export function isDead(s) {
return s?.state === "present" && dead.has(s.fp)
}
let cached = null
let reading = null
// The last read and the read under way, per account home ("" for agy's
// own sign-in).
const reads = new Map()
function readsOf(home) {
const key = home ?? ""
let r = reads.get(key)
if (!r) reads.set(key, (r = { cached: null, reading: null }))
return r
}
// storedSignIn is readStoredSignIn, shared for CACHE_MS and while one read
// is under way.
export async function storedSignIn({ read = readStoredSignIn, fresh = false } = {}) {
if (!fresh && cached && Date.now() - cached.at < CACHE_MS) return cached.value
if (!reading) {
const r = Promise.resolve().then(() => read()).catch(() => ({ state: "unknown" })).then((value) => {
if (reading === r) {
cached = { at: Date.now(), value }
reading = null
const r = readsOf(currentHome())
if (!fresh && r.cached && Date.now() - r.cached.at < CACHE_MS) return r.cached.value
if (!r.reading) {
const p = Promise.resolve().then(() => read()).catch(() => ({ state: "unknown" })).then((value) => {
if (r.reading === p) {
r.cached = { at: Date.now(), value }
r.reading = null
}
return value
})
reading = r
r.reading = p
}
return reading
return r.reading
}
// storedSignInNow is the last read without waiting for one (null before
// the first), starting a new read when it is old: a request isn't held up
// by a keyring read (on Windows, PowerShell).
export function storedSignInNow({ read = readStoredSignIn } = {}) {
if (!cached || Date.now() - cached.at >= CACHE_MS) storedSignIn({ read }).catch(() => {})
return cached?.value ?? null
const r = readsOf(currentHome())
if (!r.cached || Date.now() - r.cached.at >= CACHE_MS) storedSignIn({ read }).catch(() => {})
return r.cached?.value ?? null
}
// backgroundBlocked is why agy must not be run for work nobody asked for
@@ -220,7 +241,6 @@ export async function backgroundBlocked(opts) {
// forgetStoredSignIn drops the cached read (after a sign-in, and in tests).
export function forgetStoredSignIn({ dead: clearDead = false } = {}) {
cached = null
reading = null
reads.delete(currentHome() ?? "")
if (clearDead) dead.clear()
}
+77 -12
View File
@@ -45,11 +45,15 @@ function windowsAclPrivate(file) {
fs.writeFileSync(fakeAgy, String.raw`
import { spawn } from "node:child_process"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import readline from "node:readline"
const argv = process.argv.slice(2)
const log = value => fs.appendFileSync(process.env.FAKE_AGY_LOG, JSON.stringify(value) + "\n")
// where agy's home is (HOME, USERPROFILE on Windows) and whether it keeps
// its sign-in in a file there (SSH_CONNECTION: agy reads it as SSH)
const where = { home: os.homedir(), ssh: process.env.SSH_CONNECTION ?? null }
const log = value => fs.appendFileSync(process.env.FAKE_AGY_LOG, JSON.stringify({ ...where, ...value }) + "\n")
const send = value => process.stdout.write(JSON.stringify(value) + "\n")
if (argv.includes("--version")) {
@@ -71,6 +75,15 @@ if (argv[0] === "acp" && argv.includes("--login")) {
log({ type: "login-code", code: line })
if (/^(good-code|https:\/\/antigravity\.google\/oauth-callback\?code=good-code(&.*)?)$/.test(line.trim())) {
if (!fs.existsSync(path.join(process.env.FAKE_AGY_STATE, "login-keeps-signed-out"))) fs.rmSync(signedOut, { force: true })
// agy with no keyring to use keeps the sign-in in a file in its home
if (process.env.FAKE_AGY_FILE_EMAIL && where.ssh) {
const dir = path.join(where.home, ".gemini", "antigravity-cli")
fs.mkdirSync(dir, { recursive: true })
fs.writeFileSync(path.join(dir, "antigravity-oauth-token"), JSON.stringify({
token: { access_token: "ya29.fake", token_type: "Bearer", refresh_token: "1//fake", expiry: "2099-01-01T00:00:00Z" },
auth_method: "consumer", id_token_email: process.env.FAKE_AGY_FILE_EMAIL,
}))
}
process.stdout.write("Logged in as test@example.com.\n")
process.exit(0)
}
@@ -753,7 +766,7 @@ 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, and a way to switch accounts", plugin.auth.methods.length === 2 && plugin.auth.methods.every(m => m.type === "oauth"))
check("sign-in is agy's Google sign-in, an oauth way, and a way to add another account", 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")
@@ -761,16 +774,68 @@ const legacyModel = "agy-cli/gemini-test-low"
}
{
// 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))
// tongzhenbao on X: more than one account, each with its own usage, as
// the old plugin had. agy keeps one sign-in where it looks for it, so the
// second way signs another Google account in to an agy whose home is the
// account's own, beside agy's own sign-in. It opens Google's link even
// while agy is signed in (Archivemylife on X: "Sign in again" changed
// nothing).
const savedState = process.env.XDG_STATE_HOME
const xdg = path.join(stateDir, "xdg-state")
process.env.XDG_STATE_HOME = xdg
process.env.FAKE_AGY_FILE_EMAIL = "second@example.com"
try {
const adder = plugin.auth.methods[1]
check("the second way adds another Google account", adder.type === "oauth" && /another Google account/.test(adder.label) && !/one\)/.test(adder.label), adder.label)
check("more than one account may be signed in", plugin.auth.single !== true)
const before = logs().filter(event => event.type === "login").length
const a = await adder.authorize()
check("signed in already, adding an account still opens Google's link", /^https:\/\/accounts\.google\.com\//.test(a.url ?? "") && a.method === "code", JSON.stringify(a))
const login = logs().filter(event => event.type === "login")
check("adding an account runs agy's own sign-in", login.length === before + 1)
const accounts = path.join(xdg, "magpie-agy-bridge", "accounts")
const home = login.at(-1)?.home ?? ""
check("the added account's agy signs in with a home of its own", path.dirname(home) === accounts, home)
check("the added account's agy keeps its sign-in in a file there, not the keyring", login.at(-1)?.ssh === "127.0.0.1 0 127.0.0.1 0", login.at(-1)?.ssh)
const good = await a.callback("good-code")
check("the added account is saved beside agy's own, named by its Google account",
good?.type === "success" && good.key !== "agy" && good.metadata?.email === "second@example.com" && good.metadata?.agyHome === path.basename(home), JSON.stringify(good))
const second = { type: "api", key: good?.key, metadata: good?.metadata }
const usageBefore = logs().filter(event => event.type === "usage").length
const usage = await plugin.auth.usage(async () => second, {})
const usageRuns = logs().filter(event => event.type === "usage").slice(usageBefore)
check("the added account's usage is its own agy's", usage.windows?.length > 0 && usageRuns.length === 1 && usageRuns[0].home === home && !!usageRuns[0].ssh, JSON.stringify(usageRuns))
const secondLoader = await plugin.auth.loader(async () => second)
const initsBefore = inits().length
await readSSE(await secondLoader.fetch("agy://local/messages", {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ model, messages: [{ role: "user", content: "the second account " + Date.now() }] }),
}))
const secondInit = inits().slice(initsBefore).find(event => event.args.includes("--agent"))
check("the added account's requests run agy in its home", secondInit?.home === home && !!secondInit.ssh && !secondInit.args.includes("--gemini-dir"), JSON.stringify(secondInit && { home: secondInit.home, ssh: secondInit.ssh, args: secondInit.args }))
const firstBefore = inits().length
await readSSE(await callFetch({ model, messages: [{ role: "user", content: "the first account " + Date.now() }] }))
const firstInit = inits().slice(firstBefore).find(event => event.args.includes("--agent"))
check("agy's own account still runs in the user's home", firstInit?.home === os.homedir() && firstInit.ssh !== "127.0.0.1 0 127.0.0.1 0", JSON.stringify(firstInit && { home: firstInit.home, ssh: firstInit.ssh }))
const firstUsageBefore = logs().filter(event => event.type === "usage").length
await plugin.auth.usage(async () => ({ key: "agy" }), {})
const firstUsage = logs().filter(event => event.type === "usage").slice(firstUsageBefore)
check("agy's own account's usage is read in the user's home", firstUsage.length === 1 && firstUsage[0].home === os.homedir(), JSON.stringify(firstUsage))
// a sign-in that fails leaves no home behind
const c = await adder.authorize()
const failedHome = logs().filter(event => event.type === "login").at(-1)?.home ?? ""
const bad = await c.callback("4/wrong-code")
check("a failed added sign-in saves nothing and leaves no home", bad?.type === "failed" && failedHome !== home && !fs.existsSync(failedHome), JSON.stringify(bad))
} finally {
delete process.env.FAKE_AGY_FILE_EMAIL
if (savedState === undefined) delete process.env.XDG_STATE_HOME
else process.env.XDG_STATE_HOME = savedState
}
}
{
+3
View File
@@ -41,6 +41,7 @@ export const SIGNIN_FILE = path.join(REPO_DIR, "signin.mjs")
export const TOOL_SCHEMA_FILE = path.join(REPO_DIR, "tool-schema.mjs")
export const TOOL_BUDGET_FILE = path.join(REPO_DIR, "tool-budget.mjs")
export const INSTALL_FILE = path.join(REPO_DIR, "install.mjs")
export const ACCOUNT_FILE = path.join(REPO_DIR, "account.mjs")
export const MESSAGES_URL = "agy://local/v1/messages"
export const COUNT_TOKENS_URL = "agy://local/v1/messages/count_tokens"
export const CATALOG_TTL_MS = 5 * 60 * 1000
@@ -547,6 +548,7 @@ export async function createBridgeKit(options = {}) {
const toolSchemaUrl = pathToFileURL(TOOL_SCHEMA_FILE).href
const toolBudgetUrl = pathToFileURL(TOOL_BUDGET_FILE).href
const installUrl = pathToFileURL(INSTALL_FILE).href
const accountUrl = pathToFileURL(ACCOUNT_FILE).href
const linker = (specifier) => {
const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER
? specifier
@@ -565,6 +567,7 @@ export async function createBridgeKit(options = {}) {
else if (key === "./tool-schema.mjs") module = sourceModule(TOOL_SCHEMA_FILE, "", toolSchemaUrl)
else if (key === "./tool-budget.mjs") module = sourceModule(TOOL_BUDGET_FILE, "", toolBudgetUrl)
else if (key === "./install.mjs") module = sourceModule(INSTALL_FILE, "", installUrl)
else if (key === "./account.mjs") module = sourceModule(ACCOUNT_FILE, "", accountUrl)
else if (key.startsWith("node:")) module = builtinModule(key, overrides[key])
else throw new Error(`testkit: 未登记的依赖 ${specifier}`)
cache.set(key, module)