diff --git a/packages/agy-cli/README.en.md b/packages/agy-cli/README.en.md index 848405b..b8b6ba9 100644 --- a/packages/agy-cli/README.en.md +++ b/packages/agy-cli/README.en.md @@ -85,9 +85,10 @@ MCP server. The control port listens on loopback only, with a token per process. ## Requirements -- The Antigravity CLI (`agy`) with the `acp` subcommand, signed in to a Google - account at least once from an interactive terminal. Text and tool calls have - been verified on 1.4.12 and 1.5.0; image input needs 1.5.0. +- The Antigravity CLI (`agy`) with the `acp` subcommand. Signing in from Magpie + needs agy 1.5.0 or later (`agy acp --login`); with an older one, run `agy` in + a terminal once to sign in. Text and tool calls have been verified on 1.4.12 + and 1.5.0; image input needs 1.5.0. - A Magpie build with OpenCode-style provider plugin support. Usage reporting was verified on Magpie 0.1.1599. - agy older than 1.4.12 is refused for sessions (see "Tool bridge"), and older @@ -114,13 +115,18 @@ The provider id is `agy-cli`, so models are named `agy-cli/`. The default concurrency is 16; change it under Concurrency on Magpie's Providers page (0 means no limit). -After installing, run `agy` once in a terminal to complete the Google sign-in. +After installing, sign in from Magpie; no terminal needed. ## Usage -1. Open Magpie's Providers page, find `agy-cli`, and click Sign in. The - plugin uses `agy models` to confirm the CLI works. Google credentials stay with - agy; the plugin never reads or stores them. +1. Open Magpie's Providers page, find `agy-cli`, and click Sign in. If agy is + signed in already, that's all. If not, the plugin runs agy's own Google + sign-in (`agy acp --login`): Magpie opens the sign-in page, and you paste the + 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. 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. @@ -196,8 +202,8 @@ off unless you turn it on. - **agy cannot be found**: set `AGY_PATH` to the executable, or make sure `agy` is on PATH. -- **Sign in fails, or agy reports a login problem**: run `agy` in a terminal and - finish the Google sign-in again. +- **Sign in fails, or agy reports a login problem**: click Sign in again, or run + `agy` in a terminal to sign in there. - **HTTP 503**: the pool is full. Raise `AGY_BRIDGE_MAX_PROCS` and the Providers page Concurrency, or reduce the number of simultaneous sessions. - **Usage shows "Limits not available" or a version error**: that window has no diff --git a/packages/agy-cli/README.md b/packages/agy-cli/README.md index bb85451..62c0464 100644 --- a/packages/agy-cli/README.md +++ b/packages/agy-cli/README.md @@ -63,7 +63,7 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy ## 环境要求 -- Antigravity CLI(`agy`),带 `acp` 子命令,并且在终端里交互登录过一次 Google 账号。 +- Antigravity CLI(`agy`),带 `acp` 子命令。在 Magpie 里登录需要 1.5.0 起的 agy(`agy acp --login`);更早的版本请先在终端运行一次 `agy` 登录。 文本与工具调用已在 1.4.12 和 1.5.0 上验证;图片输入需要 1.5.0。 - 支持 OpenCode 风格 provider 插件的 Magpie。额度查询已在 Magpie 0.1.1599 上验证。 - agy 版本低于 1.4.12 时,会话会被拒绝(见「工具桥接」);低于 1.1.11 时,额度查询也会被 @@ -83,12 +83,15 @@ magpie plugin add @magpie-community/opencode-agy-cli-auth 装好后 provider id 是 `agy-cli`,模型写成 `agy-cli/<模型>`。默认并发 16,可在 Magpie 的 Providers 页 Concurrency 里改(0 表示不限)。 -安装完成后,先在终端运行一次 `agy` 完成 Google 登录。 +安装完成后在 Magpie 里登录即可,不需要先开终端。 ## 使用 -1. 在 Magpie 的 Providers 页找到 `agy-cli` 并点击 Sign in。插件会用 `agy models` - 确认 CLI 可用。Google 凭据始终由 agy 自己保管,插件不读取、不保存。 +1. 在 Magpie 的 Providers 页找到 `agy-cli` 并点击 Sign in。agy 已经登录时直接完成; + 没登录时插件运行 agy 自己的 Google 登录(`agy acp --login`),Magpie 打开登录页, + 登录后把页面显示的授权码(或整个页面地址)粘贴回 Magpie。Magpie 在服务器或 Docker + 里也一样。登录的有效期是 15 分钟。Google 凭据始终由 agy 自己保管(系统钥匙串), + 插件不读取、不保存;agy 列出账号的模型(`agy models`)后才算登录成功。 2. 模型名写成 `agy-cli/<模型>`。agy 对同一模型不同思考等级给出的多个模型 ID, 在这里会合并成一个模型的多个变体,请求时再映射回对应的 agy ID。 3. 在客户端里选用这个模型即可。 @@ -152,7 +155,7 @@ agy 自己的系统提示词,只剩插件的一行工具说明和客户端的 ## 常见排查 - **找不到 agy**:设置 `AGY_PATH` 指向可执行文件,或确认 `agy` 在 PATH 里。 -- **Sign in 失败或 agy 报登录相关错误**:在终端运行一次 `agy`,重新完成 Google 登录。 +- **Sign in 失败或 agy 报登录相关错误**:再点一次 Sign in 重新登录,或在终端运行一次 `agy` 登录。 - **HTTP 503**:进程池满。提高 `AGY_BRIDGE_MAX_PROCS` 和 Providers 页的 Concurrency, 或者减少同时进行的会话。 - **额度显示 "Limits not available" 或报版本错误**:该窗口没有可测量的数据;版本错误则 diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index f3eb5d2..ca6959f 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -8,6 +8,7 @@ import os from "node:os" import path from "node:path" import { fileURLToPath } from "node:url" import { createUsageReader } from "./usage.mjs" +import { startLogin } from "./login.mjs" const PROVIDER_ID = "agy-cli" // Client tools reach the session through a private `nc` placed first on agy's @@ -213,6 +214,20 @@ async function listAgyModels(agyPath) { return out.length ? out : null } +// probeSignedIn is whether agy lists the signed-in account's models: an +// exit code alone can't say so, so a listing without one model in it is +// not signed in either. +async function probeSignedIn(agy) { + const probe = await execOnce(agy, ["models"], { timeoutMs: 15_000 }) + const listed = !probe.err && !probe.timedOut && probe.code === 0 && + probe.stdout.split("\n").some(line => /^\S+\s+\S/.test(line.trim())) + if (listed) return { ok: true } + const why = probe.timedOut + ? "`agy models` timed out after 15s" + : `\`agy models\` says: ${(probe.stderr || probe.stdout || "").trim().split(/\r?\n/).filter(Boolean).at(-1) || probe.err?.message || `exit ${probe.code}`}` + return { ok: false, why } +} + const EFFORT_ORDER = ["minimal", "low", "medium", "high", "xhigh", "max"] const MODEL_CATALOG_TTL_MS = 5 * 60 * 1000 const MODEL_CATALOG_FAST_WAIT_MS = 500 @@ -4003,28 +4018,38 @@ export const AntigravityBridgePlugin = async () => { usage: async () => readUsage(), methods: [ { - type: "api", - keyless: true, - label: "Sign in with the agy CLI", + // 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. + type: "oauth", + label: "Sign in with 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 — then run `agy` once to sign in.", + error: "agy CLI not found. Install Antigravity CLI first: https://antigravity.google/docs/cli", } } - const probe = await execOnce(agy, ["models"], { timeoutMs: 15_000 }) - if (probe.err || probe.code !== 0 || !probe.stdout.trim()) { - const why = probe.timedOut - ? "timed out after 15s" - : (probe.stderr || probe.stdout || "").trim() || probe.err?.message || "unknown error" - return { - type: "failed", - error: `agy at ${agy} is not signed in (${why}). Run \`agy\` in a terminal once to sign in to your Google account, then try again.`, - } + // signed in to agy already: nothing to open + 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 } + const probe = await probeSignedIn(agy) + if (!probe.ok) return { type: "failed", error: `agy signed in, but ${probe.why}` } + return { type: "success", key: "agy" } + }, } - return { type: "success", key: "agy" } }, }, ], diff --git a/packages/agy-cli/login.mjs b/packages/agy-cli/login.mjs new file mode 100644 index 0000000..28c3126 --- /dev/null +++ b/packages/agy-cli/login.mjs @@ -0,0 +1,129 @@ +import os from "node:os" +import { spawnAgy } from "./platform.mjs" + +// The Google sign-in, run by agy itself: `agy acp --login` (agy 1.5 and +// later, "ACP terminal auth") prints Google's sign-in link, then reads the +// code the page it lands on shows, or that page's whole address, from +// stdin. agy trades the code and keeps the token where it always does (the +// system keyring); the plugin never sees it. Nothing opens a browser here: +// magpie opens the link, on the machine the user is at, and takes the code +// in its own field, so this works with magpie on a server or in Docker too. + +// How long the link waits for its code before agy is stopped. A sign-in +// magpie gives up on reaches no plugin hook, so this is what ends it. +export const LOGIN_WAIT_MS = 15 * 60 * 1000 +// How long agy has to print the link, and to trade the code. +export const LOGIN_START_MS = 30_000 +export const LOGIN_FINISH_MS = 60_000 + +const SIGN_IN_LINK = /https:\/\/accounts\.google\.com\/[^\s"'<>]+/ + +let pending = null + +// lastLine is the last thing agy said, for an error. +function lastLine(text) { + const lines = String(text).split(/\r?\n/).map(line => line.trim()).filter(Boolean) + return lines.at(-1) ?? "" +} + +function stop(child) { + try { child.stdin?.end() } catch {} + try { child.kill() } catch {} +} + +// startLogin starts agy's sign-in and resolves with its link, or with why +// it couldn't start. A second sign-in ends the first's agy. +export function startLogin(agy, { waitMs = LOGIN_WAIT_MS, startMs = LOGIN_START_MS } = {}) { + if (pending) { + stop(pending) + pending = null + } + return new Promise((resolve) => { + let child + try { + child = spawnAgy(agy, ["acp", "--login"], { cwd: os.tmpdir(), stdio: ["pipe", "pipe", "pipe"] }) + } catch (err) { + resolve({ error: `couldn't run agy: ${err.message}` }) + return + } + pending = child + let out = "" + let settled = false + let exited = null + const waiters = [] + const settle = (value) => { + if (settled) return + settled = true + clearTimeout(startTimer) + resolve(value) + } + const startTimer = setTimeout(() => { + stop(child) + settle({ error: `agy didn't print a sign-in link within ${Math.round(startMs / 1000)}s${lastLine(out) ? ` (${lastLine(out)})` : ""}` }) + }, startMs) + const waitTimer = setTimeout(() => stop(child), waitMs) + waitTimer.unref?.() + const read = (data) => { + out += data + const link = SIGN_IN_LINK.exec(out)?.[0] + if (link) settle({ url: link, finish }) + } + child.stdout?.setEncoding("utf8") + child.stderr?.setEncoding("utf8") + child.stdout?.on("data", read) + child.stderr?.on("data", read) + child.stdin?.on("error", () => {}) + child.on("error", (err) => { + exited = { code: null, err } + for (const w of waiters.splice(0)) w() + settle({ error: `couldn't run agy: ${err.message}` }) + }) + child.on("close", (code) => { + clearTimeout(waitTimer) + if (pending === child) pending = null + exited = exited ?? { code } + for (const w of waiters.splice(0)) w() + // agy before 1.5 has no --login: it prints acp's usage and exits + if (/Usage:/.test(out) && !SIGN_IN_LINK.test(out)) { + settle({ error: "this agy can't sign in from magpie (it has no `agy acp --login`). Update it with `agy update`, or run `agy` in a terminal once to sign in, then try again." }) + } + settle({ error: `agy exited before printing a sign-in link${lastLine(out) ? `: ${lastLine(out)}` : ""}` }) + }) + + // finish hands agy the code (or the page's address) and waits for it + // to trade it. It says why when the sign-in didn't take. + async function finish(code, { signal, finishMs = LOGIN_FINISH_MS } = {}) { + const value = String(code ?? "").trim() + if (!value || /[\r\n]/.test(value)) { + stop(child) + return { error: "paste the code the sign-in page shows" } + } + if (exited) { + return { error: "this sign-in is over (its link waits 15 minutes); start it again" } + } + const before = out.length + const done = new Promise((resolve) => waiters.push(resolve)) + let timer + const late = new Promise((resolve) => { timer = setTimeout(() => resolve("late"), finishMs) }) + const onAbort = () => stop(child) + signal?.addEventListener?.("abort", onAbort, { once: true }) + try { + child.stdin.write(value + "\n") + const how = await Promise.race([done, late]) + if (how === "late") { + stop(child) + return { error: `agy didn't finish the sign-in within ${Math.round(finishMs / 1000)}s` } + } + } finally { + clearTimeout(timer) + signal?.removeEventListener?.("abort", onAbort) + } + if (exited.code === 0) return { ok: true, said: lastLine(out.slice(before)) } + const said = lastLine(out.slice(before)) || lastLine(out) + if (/invalid_grant/.test(said)) { + return { error: `Google turned the code away: it was mistyped, used already, or from another sign-in page. Start the sign-in again. (${said})` } + } + return { error: said || `agy exited with code ${exited.code}` } + } + }) +} diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 435152d..d3f4701 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.0", + "version": "0.1.1", "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", @@ -12,6 +12,7 @@ "opencode.mjs", "opencode2.mjs", "platform.mjs", + "login.mjs", "mcp-server.mjs", "usage.mjs", "README.md", diff --git a/packages/agy-cli/test/smoke.mjs b/packages/agy-cli/test/smoke.mjs index fe3445c..1bc91dc 100644 --- a/packages/agy-cli/test/smoke.mjs +++ b/packages/agy-cli/test/smoke.mjs @@ -63,6 +63,26 @@ if (argv.includes("/usage")) { }] } } }) process.exit(0) } +const signedOut = path.join(process.env.FAKE_AGY_STATE, "signed-out") +if (argv[0] === "acp" && argv.includes("--login")) { + log({ type: "login", update: process.env.AGY_CLI_DISABLE_AUTO_UPDATE }) + process.stdout.write("Open this link in a browser to log in with Google:\n\n https://accounts.google.com/o/oauth2/auth?client_id=test&redirect_uri=https%3A%2F%2Fantigravity.google%2Foauth-callback&response_type=code\n\nThen paste the authorization code, or the full URL of the page you land on, and press Enter:\n") + const line = await new Promise(resolve => readline.createInterface({ input: process.stdin }).once("line", resolve).once("close", () => resolve(""))) + 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 }) + process.stdout.write("Logged in as test@example.com.\n") + process.exit(0) + } + process.stderr.write('couldn\'t log in: token exchange failed: oauth2: "invalid_grant" "Bad Request"\n') + process.exit(1) +} +if (argv.includes("models") && fs.existsSync(signedOut)) { + log({ type: "models", update: process.env.AGY_CLI_DISABLE_AUTO_UPDATE, signedOut: true }) + process.stdout.write("Fetching available models...\n") + process.stderr.write("Error: Please sign in to view available models. Launch the CLI without arguments to sign in.\n") + process.exit(1) +} if (argv.includes("models")) { log({ type: "models", update: process.env.AGY_CLI_DISABLE_AUTO_UPDATE }) process.stdout.write("gemini-test-medium\tGemini Test (Medium)\ngemini-test-high\tGemini Test (High)\ngemini-test-low\tGemini Test (Low)\nclaude-test-medium\tClaude Test (Medium)\n") @@ -621,8 +641,43 @@ 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("authorize login probe still succeeds", result.type === "success" && result.key === "agy") + check("sign-in is agy's Google sign-in, an oauth way", plugin.auth.methods.length === 1 && plugin.auth.methods[0].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")) +} + +{ + // signed out: agy's own sign-in gives the link and takes the pasted code + const signedOut = path.join(stateDir, "signed-out") + fs.writeFileSync(signedOut, "") + const auth = plugin.auth.methods[0] + const a = await auth.authorize() + check("signed out, the sign-in opens Google's link agy printed", /^https:\/\/accounts\.google\.com\/o\/oauth2\/auth\?/.test(a.url ?? ""), JSON.stringify(a)) + check("signed out, the sign-in takes the code the page shows", a.method === "code" && typeof a.callback === "function") + check("agy's sign-in runs with auto update off", logs().filter(event => event.type === "login").at(-1)?.update === "true") + const bad = await a.callback("4/wrong-code") + check("a code Google turns away saves nothing", bad?.type === "failed" && /turned the code away/.test(bad.error ?? ""), JSON.stringify(bad)) + check("agy is handed the pasted code", logs().filter(event => event.type === "login-code").at(-1)?.code === "4/wrong-code") + check("still signed out after a turned-away code", fs.existsSync(signedOut)) + + const empty = await (await auth.authorize()).callback(" ") + check("an empty code saves nothing", empty?.type === "failed", JSON.stringify(empty)) + + const b = await auth.authorize() + const good = await b.callback("https://antigravity.google/oauth-callback?code=good-code&scope=x") + check("the page's whole address signs agy in", good?.type === "success" && good.key === "agy", JSON.stringify(good)) + check("signed in, agy lists models again", !fs.existsSync(signedOut)) + + // agy that says it signed in but still lists no models saves nothing + fs.writeFileSync(signedOut, "") + const c = await auth.authorize() + fs.writeFileSync(path.join(stateDir, "login-keeps-signed-out"), "") + const odd = await c.callback("good-code") + fs.rmSync(path.join(stateDir, "login-keeps-signed-out"), { force: true }) + check("agy saying it signed in while listing nothing saves nothing", odd?.type === "failed" && /agy models/.test(odd.error ?? ""), JSON.stringify(odd)) + fs.rmSync(signedOut, { force: true }) } async function launchedModel(body) { diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index 38c159f..398f210 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -31,6 +31,7 @@ export const REPO_DIR = path.dirname(path.dirname(fileURLToPath(import.meta.url) export const INDEX_FILE = process.env.AGY_BRIDGE_TEST_INDEX || path.join(REPO_DIR, "index.mjs") export const USAGE_FILE = path.join(REPO_DIR, "usage.mjs") export const PLATFORM_FILE = path.join(REPO_DIR, "platform.mjs") +export const LOGIN_FILE = path.join(REPO_DIR, "login.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 @@ -468,6 +469,7 @@ export async function createBridgeKit(options = {}) { const indexUrl = pathToFileURL(path.join(REPO_DIR, "index.mjs")).href const usageUrl = pathToFileURL(USAGE_FILE).href const platformUrl = pathToFileURL(PLATFORM_FILE).href + const loginUrl = pathToFileURL(LOGIN_FILE).href const linker = (specifier) => { const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER ? specifier @@ -476,6 +478,7 @@ export async function createBridgeKit(options = {}) { let module if (key === "./usage.mjs") module = sourceModule(USAGE_FILE, "", usageUrl) else if (key === "./platform.mjs") module = sourceModule(PLATFORM_FILE, "", platformUrl) + else if (key === "./login.mjs") module = sourceModule(LOGIN_FILE, "", loginUrl) else if (key.startsWith("node:")) module = builtinModule(key, overrides[key]) else throw new Error(`testkit: 未登记的依赖 ${specifier}`) cache.set(key, module)