agy-cli 0.1.62: magpie's sign-in installs agy where there is none, and the plugin keeps that copy current (niuniu_8964 on X)

In magpie's Docker image there is no agy, so Sign in failed with "agy CLI
not found". The plugin now declares auth.cli (magpie 0.1.4246's hook,
engines.magpie raised to it): when agy isn't found, magpie's sign-in shows
"Installing Antigravity CLI…" and the plugin installs it the way Google's
install.sh does: the same manifest, the download checked against its
sha512, the antigravity binary taken out of the tarball, tried with
--version, then renamed into place. It goes into the data folder
($XDG_DATA_HOME/magpie-agy-cli/agy, ~/.local/share without it,
%LOCALAPPDATA% on Windows), which in the container is on /config, and is
searched last, so an agy the user installed wins. That copy is kept
current a minute after start and every 6 hours, only while it is the one
in use and not when AGY_CLI_DISABLE_AUTO_UPDATE is set.

Also: findAgy handed out a cached path to an agy removed since, so the
sign-in tried to spawn it (ENOENT) instead of installing it; and a write
loop left an error listener per wait (MaxListenersExceededWarning on the
260MB download).

Account code is unchanged.

Run, on mica: bun scripts/check.mjs ok; agy-cli bun test 34/34 under a
temp HOME (install.test.mjs: 10, against a local server). A6b red on the
old findAgy, green now.

Real use in magpie's Docker image (xiaomi-gpu, linux amd64), with magpie
0.1.4246's tree: `magpie plugin login agy-cli 1` and the browser UI's
POST /api/plugin-signin both installed agy 1.5.9 into
/config/data/magpie-agy-cli and went on to agy's Google link; it survived
a restart; agy.version set back to 1.5.0 was updated a minute after start.

Not tried: finishing the Google sign-in in the container, a real install
on macOS, Windows or musl.
This commit is contained in:
yetone
2026-11-15 14:55:10 +08:00
parent b6a996478f
commit b840915abc
9 changed files with 605 additions and 15 deletions
+18 -6
View File
@@ -33,8 +33,9 @@ channel: Antigravity's models over ACP. The differences:
- **What runs**: Antigravity ACP downloads Google's ACP server
(`agy_acp_server.par`, about 400 MB) and rides the Antigravity IDE's sign-in.
This plugin downloads nothing; it runs the `agy` CLI you installed and signed
in to yourself (`agy acp`).
This plugin runs the `agy` CLI (`agy acp`): your own when you have one, and
when the machine has none, signing in from Magpie installs one the way
Google's own installer does (see "Requirements").
- **Sessions**: Antigravity ACP opens a new session per request and carries the
history as context. This plugin keeps a pool of agy processes, reuses one agy
session for one conversation, and picks it up again with `session/resume`
@@ -122,7 +123,14 @@ turn); the models a client gets remain agy's decision.
## Requirements
- The Antigravity CLI (`agy`) with the `acp` subcommand. Signing in from Magpie
- The Antigravity CLI (`agy`) with the `acp` subcommand. On a machine without
agy (Magpie's Docker container, say), Sign in in Magpie 0.1.4246 or later
installs it first: downloaded from where Google's install script gets it,
checked against its sha512, and kept in the data folder
(`$XDG_DATA_HOME/magpie-agy-cli/agy`, else `~/.local/share/magpie-agy-cli/agy`;
`%LOCALAPPDATA%\magpie-agy-cli\agy.exe` on Windows). In the container that
folder is on the /config volume, so it survives a restart. An agy you
installed yourself comes first. 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.
@@ -137,7 +145,10 @@ turn); the models a client gets remain agy's decision.
affected and update as usual. If you set `AGY_CLI_DISABLE_AUTO_UPDATE`
yourself (`false` included), the plugin passes your value on as written. If
you use agy only through this plugin, run `agy` in a terminal now and then so
it updates: an old version stands out too.
it updates: an old version stands out too. The copy the plugin installed is
kept current by the plugin: checked a minute after it starts and every 6
hours after, and a new version is downloaded, checked and tried before it
replaces the old one. Not when you set `AGY_CLI_DISABLE_AUTO_UPDATE`.
## Install
@@ -281,8 +292,9 @@ off unless you turn it on.
## Troubleshooting
- **agy cannot be found**: set `AGY_PATH` to the executable, or make sure `agy`
is on PATH.
- **agy cannot be found**: click Sign in in Magpie to have it installed (Magpie
0.1.4246 or later), set `AGY_PATH` to the executable, or make sure `agy` is
on PATH.
- **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
+12 -5
View File
@@ -25,8 +25,8 @@ OpenCode、Claude Code 等客户端经由 Magpie 调用 agy 向本插件开放
两者的区别:
- **运行的程序**:Antigravity ACP 自己下载 Google 的 ACP 服务端(`agy_acp_server.par`,
约 400 MB),依赖 Antigravity IDE 的登录。本插件不下载任何东西,运行你自己装好、自己
登录过的 `agy` CLI(`agy acp`)。
约 400 MB),依赖 Antigravity IDE 的登录。本插件运行 `agy` CLI(`agy acp`):用你自己装好的;
机器上没有时,在 Magpie 里登录会按 Google 官方安装脚本的方式装一份(见「环境要求」)。
- **会话**:Antigravity ACP 每个请求开一个新会话,把历史当作上下文带上。本插件维护一个
agy 进程池,同一段对话复用同一个 agy 会话,重启后用 `session/resume` 接上;只有接不上时
才在字节预算内重放历史。
@@ -88,7 +88,11 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy
## 环境要求
- Antigravity CLI(`agy`),带 `acp` 子命令。在 Magpie 里登录需要 1.5.0 起的 agy(`agy acp --login`);更早的版本请先在终端运行一次 `agy` 登录。
- Antigravity CLI(`agy`),带 `acp` 子命令。机器上没有 agy 时(比如 Magpie 的 Docker 容器里),
Magpie 0.1.4246 起在 Magpie 里点 Sign in 会先装好它:从 Google 官方安装脚本用的同一个地址下载、
校验 sha512,放在数据目录里(`$XDG_DATA_HOME/magpie-agy-cli/agy`,没设时是
`~/.local/share/magpie-agy-cli/agy`;Windows 是 `%LOCALAPPDATA%\magpie-agy-cli\agy.exe`)。
容器的数据目录在 /config 卷里,重启后还在。你自己装的 agy 优先。在 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 时,额度查询也会被
@@ -96,7 +100,9 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy
- **自动更新**:插件启动的 agy 进程默认带 `AGY_CLI_DISABLE_AUTO_UPDATE=true`,免得进程池里的
多个进程同时更新同一个可执行文件。你自己在终端里运行的 agy 不受影响,照常更新。你自己设置了
`AGY_CLI_DISABLE_AUTO_UPDATE`(包括设为 `false`)时,插件原样使用你的值。只通过本插件使用
agy 的话,请定期在终端里运行一次 `agy` 让它更新:版本过旧本身也更显眼。
agy 的话,请定期在终端里运行一次 `agy` 让它更新:版本过旧本身也更显眼。插件自己装的那份由插件
保持最新:启动一分钟后查一次,之后每 6 小时查一次,有新版就下载、校验、试运行后替换;你设置了
`AGY_CLI_DISABLE_AUTO_UPDATE` 时不更新。
## 安装
@@ -204,7 +210,8 @@ agy 自己的系统提示词,只剩插件的一行工具说明和客户端的
## 常见排查
- **找不到 agy**:设置 `AGY_PATH` 指向可执行文件,或确认 `agy` 在 PATH 里。
- **找不到 agy**:在 Magpie 里点 Sign in 让它装一份(需要 Magpie 0.1.4246 起),或设置 `AGY_PATH`
指向可执行文件,或确认 `agy` 在 PATH 里。
- **Sign in 失败或 agy 报登录相关错误**:再点一次 Sign in 重新登录,或在终端运行一次 `agy` 登录。
- **HTTP 503**:进程池满。提高 `AGY_BRIDGE_MAX_PROCS` 和 Providers 页的 Concurrency,
或者减少同时进行的会话。
+27 -3
View File
@@ -11,6 +11,7 @@ import { createUsageReader } from "./usage.mjs"
import { backgroundBlocked, cannotSignIn, forgetStoredSignIn, storedEmail, storedSignInNow } from "./signin.mjs"
import { sanitizePatternFields } from "./re2-pattern.mjs"
import { startLogin } from "./login.mjs"
import { AGY_MANUAL, installAgy, keepAgyCurrent } from "./install.mjs"
import { ensureGeminiArrayItems } from "./array-items.mjs"
import { expandToolSchema } from "./tool-schema.mjs"
import { fitTools } from "./tool-budget.mjs"
@@ -197,8 +198,15 @@ function findAgy() {
// LOCALAPPDATA, home): a cached path from an old environment may be gone.
const home = os.homedir()
const env = process.env
const searchKey = JSON.stringify([env.AGY_PATH, env.PATH, env.Path, env.LOCALAPPDATA, home])
if (cachedAgyPath && cachedAgySearchKey === searchKey) return cachedAgyPath
const searchKey = JSON.stringify([env.AGY_PATH, env.PATH, env.Path, env.LOCALAPPDATA, env.XDG_DATA_HOME, home])
// and whenever the path found is gone: an agy removed while magpie ran
// is installed again by the next sign-in, not spawned where it was
if (cachedAgyPath && cachedAgySearchKey === searchKey) {
try {
fs.accessSync(cachedAgyPath, fs.constants.X_OK)
return cachedAgyPath
} catch {}
}
cachedAgyPath = null
cachedAgySearchKey = searchKey
const candidates = agyCandidates(env, home)
@@ -5872,8 +5880,10 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a
return proc.startTurn(contentParts, body.messages, model, selection)
}
// A magpie that installs a plugin's CLI (auth.cli) installs agy before it
// gets here; an older one, or OpenCode, doesn't.
function noAgy() {
return { type: "failed", error: "agy CLI not found. Install Antigravity CLI first: https://antigravity.google/docs/cli" }
return { type: "failed", error: `agy CLI not found. Update magpie and sign in again to have it installed, or install Antigravity CLI yourself: ${AGY_MANUAL}` }
}
// signedInAs is the sign-in's result, named by the Google account agy is
@@ -5911,10 +5921,24 @@ async function googleSignIn(agy) {
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.
cli: {
name: "Antigravity CLI",
manual: AGY_MANUAL,
installed: async () => findAgy() !== null,
install: async ({ signal } = {}) => {
if (findAgy()) return
await installAgy({ signal })
if (!findAgy()) throw new Error("agy was installed, but the plugin can't run it")
},
},
// Magpie's usage hook; OpenCode ignores this extension. agy owns auth.
usage: async () => readUsage(),
methods: [
+308
View File
@@ -0,0 +1,308 @@
// Installs agy where the machine has none, as Antigravity's own installer
// does (https://antigravity.google/cli/install.sh, install.ps1): the
// platform's manifest names the version, the download and its sha512; a
// Unix download is a tar.gz holding the binary as `antigravity`, a Windows
// one the exe itself. magpie's sign-in runs it (auth.cli) when agy isn't
// there, so a magpie in a container, which has no shell to run the
// installer in, gets agy too (niuniu_8964 on X). It goes into the plugin's
// own folder (ownAgyPath), which only this file writes, and keepAgyCurrent
// keeps that copy at the manifest's version. Not done: `agy install`, which
// the official installer runs to put agy on the user's PATH; the plugin
// finds its copy itself.
import { spawn } from "node:child_process"
import { createHash, randomBytes } from "node:crypto"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { createGunzip } from "node:zlib"
import { childEnv, ownAgyPath } from "./platform.mjs"
const MANIFESTS = "https://antigravity-cli-auto-updater-974169037036.us-central1.run.app/manifests/"
export const AGY_MANUAL = process.platform === "win32"
? "irm https://antigravity.google/cli/install.ps1 | iex"
: "curl -fsSL https://antigravity.google/cli/install.sh | bash"
const KEEP_FIRST_MS = 60_000
const KEEP_EVERY_MS = 6 * 60 * 60 * 1000
// manifestBase is where the manifests are read; AGY_BRIDGE_INSTALL_BASE
// points it elsewhere (the tests' own server).
function manifestBase(env = process.env) {
const base = (env.AGY_BRIDGE_INSTALL_BASE || "").trim()
return base ? base.replace(/\/?$/, "/") : MANIFESTS
}
function muslLinux() {
for (const lib of ["/lib/libc.musl-x86_64.so.1", "/lib/libc.musl-aarch64.so.1"]) {
if (fs.existsSync(lib)) return true
}
try {
// Bun and Node say which glibc they run on; a musl build says none
const header = process.report?.getReport?.()?.header
if (header && !header.glibcVersionRuntime) return true
} catch {}
return false
}
// agyPlatform is the installer's name for this machine, null for one
// Antigravity builds nothing for here (Android's Termux needs its own
// installer).
export function agyPlatform(platform = process.platform, arch = process.arch, musl = platform === "linux" && muslLinux()) {
const cpu = { x64: "amd64", arm64: "arm64" }[arch]
if (!cpu) return null
if (platform === "linux") return `linux_${cpu}${musl ? "_musl" : ""}`
if (platform === "darwin") return `darwin_${cpu}`
if (platform === "win32") return `windows_${cpu}`
return null
}
function ownPath() {
return ownAgyPath(process.env, os.homedir())
}
function versionFile(bin) {
return bin + ".version"
}
export async function readManifest(platform = agyPlatform(), { signal } = {}) {
if (!platform) throw new Error(`Antigravity CLI has no build for ${process.platform} ${process.arch}`)
const url = manifestBase() + platform + ".json"
let res
try {
res = await fetch(url, { signal })
} catch (error) {
if (signal?.aborted) throw error
throw new Error(`couldn't reach Antigravity's release server: ${error?.message || error}`)
}
if (!res.ok) throw new Error(`Antigravity's release server answered ${res.status} for ${platform}`)
const m = await res.json().catch(() => null)
if (!m || typeof m.url !== "string" || !/^https?:\/\//.test(m.url) || !/^[0-9a-f]{128}$/i.test(String(m.sha512 || ""))) {
throw new Error("Antigravity's release manifest isn't one")
}
return { version: String(m.version || ""), url: m.url, sha512: String(m.sha512).toLowerCase(), platform }
}
// drained waits for a full stream to take more, and leaves no listener
// behind: one per wait piled up past Node's limit of 10 on a 260MB agy.
export function drained(out) {
return new Promise((resolve, reject) => {
const done = (error) => {
out.off("drain", done)
out.off("error", done)
error ? reject(error) : resolve()
}
out.on("drain", done)
out.on("error", done)
})
}
// download writes url to file, hashing as it goes, and returns the sha512.
async function download(url, file, signal) {
const res = await fetch(url, { signal })
if (!res.ok || !res.body) throw new Error(`downloading agy failed: ${res.status}`)
const hash = createHash("sha512")
const out = fs.createWriteStream(file, { mode: 0o600 })
const wrote = new Promise((resolve, reject) => { out.on("finish", resolve); out.on("error", reject) })
try {
for await (const chunk of res.body) {
hash.update(chunk)
if (!out.write(chunk)) await drained(out)
}
} finally {
out.end()
}
await wrote
return hash.digest("hex")
}
// untarMember copies the regular file named name out of a .tar.gz into
// file (mode 755), and says whether it was there. A tar entry is a
// 512-byte header and its data padded to 512; a GNU long name ("L") or a
// pax header ("x") names the entry after it.
export async function untarMember(archive, name, file) {
const gz = fs.createReadStream(archive).pipe(createGunzip())
const it = gz[Symbol.asyncIterator]()
let buf = Buffer.alloc(0)
const fill = async (n) => {
while (buf.length < n) {
const r = await it.next()
if (r.done) return false
buf = buf.length ? Buffer.concat([buf, r.value]) : r.value
}
return true
}
// pass hands the next n bytes to fn a chunk at a time
const pass = async (n, fn) => {
while (n > 0) {
if (!buf.length) {
const r = await it.next()
if (r.done) throw new Error("the agy download is cut short")
buf = r.value
}
const k = Math.min(n, buf.length)
await fn(buf.subarray(0, k))
buf = buf.subarray(k)
n -= k
}
}
const skip = () => {}
let longName = null
try {
for (;;) {
if (!(await fill(512))) return false
const header = buf.subarray(0, 512)
buf = buf.subarray(512)
if (header.every((b) => b === 0)) continue
const field = (at, len) => header.subarray(at, at + len).toString("utf8").replace(/\0.*$/s, "")
const size = parseInt(field(124, 12).trim() || "0", 8)
if (!Number.isFinite(size) || size < 0) throw new Error("the agy download isn't a tar archive")
const pad = (512 - (size % 512)) % 512
const type = field(156, 1) || "0"
if (type === "L" || type === "x") {
if (size > 1 << 20) throw new Error("the agy download isn't a tar archive")
const parts = []
await pass(size, (c) => { parts.push(Buffer.from(c)) })
await pass(pad, skip)
const text = Buffer.concat(parts).toString("utf8")
if (type === "L") longName = text.replace(/\0.*$/s, "")
else {
const m = /(?:^|\n)\d+ path=([^\n]*)\n/.exec(text)
if (m) longName = m[1]
}
continue
}
const prefix = field(345, 155)
const entry = (longName ?? (prefix ? prefix + "/" + field(0, 100) : field(0, 100))).replace(/^\.\//, "")
longName = null
if ((type === "0" || type === "7") && entry === name) {
const out = fs.createWriteStream(file, { mode: 0o755 })
try {
await pass(size, async (c) => {
if (!out.write(c)) await drained(out)
})
} finally {
await new Promise((resolve, reject) => out.end((error) => (error ? reject(error) : resolve())))
}
return true
}
await pass(size + pad, skip)
}
} finally {
gz.destroy()
}
}
function run(file, args, { timeoutMs = 30_000 } = {}) {
return new Promise((resolve) => {
let output = ""
let child
try {
child = spawn(file, args, { env: childEnv(process.env), stdio: ["ignore", "pipe", "pipe"], windowsHide: true })
} catch (error) {
resolve({ code: -1, output: String(error?.message || error) })
return
}
const timer = setTimeout(() => child.kill(), timeoutMs)
child.stdout.on("data", (d) => { output += d })
child.stderr.on("data", (d) => { output += d })
child.on("error", (error) => { clearTimeout(timer); resolve({ code: -1, output: String(error?.message || error) }) })
child.on("close", (code) => { clearTimeout(timer); resolve({ code, output }) })
})
}
function lastLine(text) {
return String(text).trim().split(/\r?\n/).filter(Boolean).pop() || ""
}
// installAgy puts the manifest's agy at bin (the plugin's own copy unless
// a test says otherwise): downloaded, checked against the manifest's
// sha512, taken out of its archive, run once with --version, then renamed
// over the old copy, so a running agy and a second install racing this one
// each see a whole binary. It returns the version installed.
export async function installAgy({ signal, bin = ownPath(), platform = agyPlatform(), manifest } = {}) {
const m = manifest || (await readManifest(platform, { signal }))
const windows = (platform || "").startsWith("windows_")
const dir = path.dirname(bin)
fs.mkdirSync(dir, { recursive: true })
const tag = randomBytes(6).toString("hex")
const payload = path.join(dir, `.download-${tag}`)
const staged = path.join(dir, `.agy-${tag}${windows ? ".exe" : ""}`)
try {
const sum = await download(m.url, payload, signal)
if (sum !== m.sha512) throw new Error("the agy download doesn't match the checksum Antigravity's manifest gives; nothing was installed")
if (/\.tar\.gz(?:$|\?)/.test(m.url)) {
if (!(await untarMember(payload, "antigravity", staged))) throw new Error("the agy download has no agy in it")
} else {
fs.renameSync(payload, staged)
}
if (!windows) fs.chmodSync(staged, 0o755)
if (signal?.aborted) throw new DOMException("the install was cancelled", "AbortError")
const check = await run(staged, ["--version"])
if (check.code !== 0) throw new Error(`the downloaded agy doesn't run here (${lastLine(check.output) || `exit ${check.code}`})`)
if (windows && fs.existsSync(bin)) {
// a running exe can't be replaced on Windows, but it can be moved
try { fs.renameSync(bin, path.join(dir, `.old-${tag}.exe`)) } catch {}
}
fs.renameSync(staged, bin)
try { fs.writeFileSync(versionFile(bin), m.version + "\n") } catch {}
return m.version
} finally {
for (const f of [payload, staged]) {
try { fs.rmSync(f, { force: true }) } catch {}
}
sweepOld(dir)
}
}
// sweepOld removes the Windows copies an update moved aside, once nothing
// runs them.
function sweepOld(dir) {
try {
for (const name of fs.readdirSync(dir)) {
if (/^\.old-[0-9a-f]+\.exe$/.test(name)) {
try { fs.rmSync(path.join(dir, name), { force: true }) } catch {}
}
}
} catch {}
}
// installedVersion is the version the plugin's copy at bin is, "" when
// unknown.
export function installedVersion(bin = ownPath()) {
try {
return fs.readFileSync(versionFile(bin), "utf8").trim()
} catch {
return ""
}
}
// updateOwnAgy brings the plugin's copy to the manifest's version. It
// leaves alone an agy the plugin didn't install (the user's own updates
// itself), a machine where the plugin's copy isn't the one used, and a
// user who turned agy's updates off (AGY_CLI_DISABLE_AUTO_UPDATE).
export async function updateOwnAgy({ signal, bin = ownPath(), used, platform = agyPlatform(), env = process.env } = {}) {
if (Object.keys(env).some((k) => k.toUpperCase() === "AGY_CLI_DISABLE_AUTO_UPDATE")) return "off"
if (!fs.existsSync(bin)) return "none"
if (used && path.resolve(used) !== path.resolve(bin)) return "not used"
const m = await readManifest(platform, { signal })
if (m.version && m.version === installedVersion(bin)) return "current"
await installAgy({ signal, bin, platform, manifest: m })
return "updated"
}
let keeping = false
// keepAgyCurrent checks for a newer agy a minute after the plugin starts
// and every six hours after, as magpie keeps its own Claude Code current.
export function keepAgyCurrent(findAgy) {
if (keeping) return
keeping = true
const tick = async () => {
try {
const was = await updateOwnAgy({ used: findAgy() })
if (was === "updated") console.error(`agy-cli: updated its agy to ${installedVersion()}`)
} catch (error) {
console.error(`agy-cli: couldn't update its agy: ${error?.message || error}`)
}
setTimeout(tick, KEEP_EVERY_MS).unref?.()
}
setTimeout(tick, KEEP_FIRST_MS).unref?.()
}
+201
View File
@@ -0,0 +1,201 @@
// install.mjs installs agy where the machine has none (magpie's sign-in
// runs it, niuniu_8964 on X: agy-cli in magpie's container) and keeps its
// own copy current. A local server stands in for Antigravity's manifests
// and downloads; nothing here reaches the network.
import { afterAll, beforeAll, beforeEach, expect, test } from "bun:test"
import { createHash } from "node:crypto"
import fs from "node:fs"
import os from "node:os"
import path from "node:path"
import { gzipSync } from "node:zlib"
import { EventEmitter } from "node:events"
import { agyPlatform, drained, installAgy, installedVersion, untarMember, updateOwnAgy } from "./install.mjs"
import { agyCandidates, ownAgyPath } from "./platform.mjs"
const unix = process.platform !== "win32"
// tar builds a ustar archive of [name, bytes, type?] entries.
function tar(entries) {
const blocks = []
for (const [name, data, type = "0"] of entries) {
const header = Buffer.alloc(512)
header.write(name.slice(0, 100), 0)
header.write("0000755\0", 100)
header.write("0000000\0", 108)
header.write("0000000\0", 116)
header.write(data.length.toString(8).padStart(11, "0") + "\0", 124)
header.write("00000000000\0", 136)
header.write(" ", 148)
header.write(type, 156)
header.write("ustar\0", 257)
header.write("00", 263)
let sum = 0
for (const b of header) sum += b
header.write(sum.toString(8).padStart(6, "0") + "\0 ", 148)
blocks.push(header, data, Buffer.alloc((512 - (data.length % 512)) % 512))
}
blocks.push(Buffer.alloc(1024))
return gzipSync(Buffer.concat(blocks))
}
const script = (version) => Buffer.from(`#!/bin/sh\necho "agy ${version}"\n`)
const sha = (b) => createHash("sha512").update(b).digest("hex")
let server
const files = new Map() // path → body
let manifest = null
let slow = false
let root
beforeAll(() => {
server = Bun.serve({
port: 0,
async fetch(req) {
const url = new URL(req.url)
if (url.pathname.startsWith("/manifests/")) {
return manifest ? Response.json({ ...manifest, url: `http://127.0.0.1:${server.port}${manifest.url}` }) : new Response("no", { status: 404 })
}
const body = files.get(url.pathname)
if (!body) return new Response("no", { status: 404 })
if (slow) {
return new Response(new ReadableStream({
async pull(c) {
await Bun.sleep(50)
c.enqueue(new Uint8Array(1024))
},
}))
}
return new Response(body)
},
})
process.env.AGY_BRIDGE_INSTALL_BASE = `http://127.0.0.1:${server.port}/manifests/`
})
afterAll(() => {
server.stop(true)
delete process.env.AGY_BRIDGE_INSTALL_BASE
})
beforeEach(() => {
root = fs.mkdtempSync(path.join(os.tmpdir(), "agy-install-"))
files.clear()
manifest = null
slow = false
})
function release(version, entries) {
const body = tar(entries ?? [["antigravity", script(version)]])
files.set(`/r/${version}.tar.gz`, body)
manifest = { version, url: `/r/${version}.tar.gz`, sha512: sha(body) }
}
test("each machine is named as Antigravity's installer names it", () => {
expect(agyPlatform("linux", "x64", false)).toBe("linux_amd64")
expect(agyPlatform("linux", "arm64", true)).toBe("linux_arm64_musl")
expect(agyPlatform("darwin", "arm64")).toBe("darwin_arm64")
expect(agyPlatform("win32", "x64")).toBe("windows_amd64")
expect(agyPlatform("linux", "ia32", false)).toBe(null)
expect(agyPlatform("android", "arm64", false)).toBe(null)
})
test("the plugin's own agy is in its own data folder, found after the user's", () => {
expect(ownAgyPath({ XDG_DATA_HOME: "/config/data" }, "/config/home", "linux")).toBe("/config/data/magpie-agy-cli/agy")
expect(ownAgyPath({}, "/home/u", "linux")).toBe("/home/u/.local/share/magpie-agy-cli/agy")
expect(ownAgyPath({ XDG_DATA_HOME: "relative" }, "/home/u", "linux")).toBe("/home/u/.local/share/magpie-agy-cli/agy")
expect(ownAgyPath({ LOCALAPPDATA: "C:\\Users\\u\\AppData\\Local" }, "C:\\Users\\u", "win32")).toBe("C:\\Users\\u\\AppData\\Local\\magpie-agy-cli\\agy.exe")
const c = agyCandidates({ PATH: "/usr/bin", XDG_DATA_HOME: "/config/data" }, "/config/home", "linux")
expect(c.at(-1)).toBe("/config/data/magpie-agy-cli/agy")
expect(c[0]).toBe("/usr/bin/agy")
})
test("agy is taken out of its archive, past a long name and a ./ prefix", async () => {
const archive = path.join(root, "a.tar.gz")
const long = "x".repeat(150)
fs.writeFileSync(archive, tar([
["././@LongLink", Buffer.from(long + "\0"), "L"],
["short", Buffer.from("not this one")],
["README", Buffer.alloc(700, 65)],
["./antigravity", Buffer.alloc(5000, 7)],
]))
const out = path.join(root, "agy")
expect(await untarMember(archive, "antigravity", out)).toBe(true)
expect(fs.readFileSync(out).equals(Buffer.alloc(5000, 7))).toBe(true)
expect(await untarMember(archive, "nothere", path.join(root, "none"))).toBe(false)
expect(fs.existsSync(path.join(root, "none"))).toBe(false)
})
test.if(unix)("installs the manifest's agy, checked and runnable, leaving nothing else", async () => {
release("1.5.9")
const bin = path.join(root, "data", "magpie-agy-cli", "agy")
expect(await installAgy({ bin, platform: "linux_amd64" })).toBe("1.5.9")
expect(fs.statSync(bin).mode & 0o111).not.toBe(0)
expect(Bun.spawnSync([bin]).stdout.toString()).toContain("agy 1.5.9")
expect(installedVersion(bin)).toBe("1.5.9")
expect(fs.readdirSync(path.dirname(bin)).sort()).toEqual(["agy", "agy.version"])
})
test.if(unix)("a download that isn't the manifest's is never installed", async () => {
release("1.5.9")
manifest.sha512 = sha(Buffer.from("something else"))
const bin = path.join(root, "agy")
await expect(installAgy({ bin, platform: "linux_amd64" })).rejects.toThrow(/checksum/)
expect(fs.readdirSync(root)).toEqual([])
})
test.if(unix)("an agy that doesn't run here isn't put in place of one that does", async () => {
release("1.5.9")
const bin = path.join(root, "agy")
await installAgy({ bin, platform: "linux_amd64" })
release("1.6.0", [["antigravity", Buffer.from("#!/bin/sh\necho 'cannot execute: required file not found' >&2\nexit 126\n")]])
await expect(installAgy({ bin, platform: "linux_amd64" })).rejects.toThrow(/doesn't run here \(cannot execute/)
expect(Bun.spawnSync([bin]).stdout.toString()).toContain("agy 1.5.9")
expect(installedVersion(bin)).toBe("1.5.9")
})
test.if(unix)("a manifest the server won't give says so", async () => {
await expect(installAgy({ bin: path.join(root, "agy"), platform: "linux_amd64" })).rejects.toThrow(/answered 404/)
})
test.if(unix)("an install given up stops its download and leaves nothing", async () => {
release("1.5.9")
slow = true
const bin = path.join(root, "agy")
const ctl = new AbortController()
const done = installAgy({ bin, platform: "linux_amd64", signal: ctl.signal })
await Bun.sleep(200)
ctl.abort()
await expect(done).rejects.toThrow()
expect(fs.readdirSync(root)).toEqual([])
})
test.if(unix)("only the plugin's own copy is kept current, and not when the user turned updates off", async () => {
const bin = path.join(root, "agy")
release("1.5.9")
expect(await updateOwnAgy({ bin, platform: "linux_amd64", env: {} })).toBe("none")
await installAgy({ bin, platform: "linux_amd64" })
expect(await updateOwnAgy({ bin, platform: "linux_amd64", env: {} })).toBe("current")
release("1.6.0")
expect(await updateOwnAgy({ bin, platform: "linux_amd64", env: { AGY_CLI_DISABLE_AUTO_UPDATE: "true" } })).toBe("off")
expect(await updateOwnAgy({ bin, platform: "linux_amd64", env: {}, used: "/usr/local/bin/agy" })).toBe("not used")
expect(installedVersion(bin)).toBe("1.5.9")
expect(await updateOwnAgy({ bin, platform: "linux_amd64", env: {}, used: bin })).toBe("updated")
expect(Bun.spawnSync([bin]).stdout.toString()).toContain("agy 1.6.0")
expect(installedVersion(bin)).toBe("1.6.0")
})
test("waiting on a full stream leaves no listener behind", async () => {
// a 260MB agy waits thousands of times; each wait used to leave an
// error listener (MaxListenersExceededWarning in magpie's container)
const out = new EventEmitter()
for (let i = 0; i < 20; i++) {
const wait = drained(out)
out.emit("drain")
await wait
}
expect(out.listenerCount("error")).toBe(0)
expect(out.listenerCount("drain")).toBe(0)
const failed = drained(out)
out.emit("error", new Error("disk full"))
await expect(failed).rejects.toThrow("disk full")
expect(out.listenerCount("drain")).toBe(0)
})
+5 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-agy-cli-auth",
"version": "0.1.61",
"version": "0.1.62",
"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",
"install.mjs",
"login.mjs",
"mcp-server.mjs",
"step-usage.mjs",
@@ -44,6 +45,9 @@
"scripts": {
"test": "bun test"
},
"engines": {
"magpie": ">=0.1.4246"
},
"magpie": {
"maxConcurrency": 16
}
+17
View File
@@ -17,9 +17,26 @@ export function agyCandidates(env, home, platform = process.platform) {
paths.join(home, ".gemini", "bin"),
] : [paths.join(home, ".local", "bin"), paths.join(home, ".gemini", "bin"), "/usr/local/bin", "/opt/homebrew/bin"]
for (const directory of directories) candidates.push(...names.map(name => paths.join(directory, name)))
// the copy the plugin installed itself (install.mjs), last: an agy the
// user installed wins
candidates.push(ownAgyPath(env, home, platform))
return candidates
}
// Where the plugin installs agy when the machine has none (install.mjs):
// a folder of its own under the user's data folder, never one an agy the
// user installed is in, so it never writes over theirs. In magpie's Docker
// image XDG_DATA_HOME is /config/data, on the volume, so it outlives the
// container.
export function ownAgyPath(env, home, platform = process.platform) {
if (platform === "win32") {
const local = env.LOCALAPPDATA || path.win32.join(home, "AppData", "Local")
return path.win32.join(local, "magpie-agy-cli", "agy.exe")
}
const data = env.XDG_DATA_HOME && path.posix.isAbsolute(env.XDG_DATA_HOME) ? env.XDG_DATA_HOME : path.posix.join(home, ".local", "share")
return path.posix.join(data, "magpie-agy-cli", "agy")
}
// The cmd.exe escaping algorithm is adapted from node-cross-spawn:
// https://github.com/moxystudio/node-cross-spawn/blob/master/lib/util/escape.js
// Copyright (c) 2018 Made With MOXY Lda
+14
View File
@@ -130,6 +130,20 @@ test("A6: findAgy searches again when PATH changes instead of keeping the first
})
})
test("A6b: an agy removed after it was found is not found again", async () => {
// magpie's sign-in asks whether agy is there and installs it when not;
// a cached path to a removed agy answered yes and the sign-in failed
// with ENOENT spawning it (magpie's container, 11-15)
await withKit({ agyPath: null }, async (kit) => {
const findAgy = kit.module.__agyTestFindAgy
const agy = kit.makeFakeAgy("gone")
kit.env.PATH = path.dirname(agy)
assert.equal(findAgy(), agy)
fs.rmSync(agy)
assert.equal(findAgy(), null, "the removed agy's cached path was handed out")
})
})
// ------------------------------------------------ A7 no-progress repeat limit
async function pendingToolTurn(kit, body) {
+3
View File
@@ -39,6 +39,7 @@ export const STEP_USAGE_FILE = path.join(REPO_DIR, "step-usage.mjs")
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 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
@@ -543,6 +544,7 @@ export async function createBridgeKit(options = {}) {
const signinUrl = pathToFileURL(SIGNIN_FILE).href
const toolSchemaUrl = pathToFileURL(TOOL_SCHEMA_FILE).href
const toolBudgetUrl = pathToFileURL(TOOL_BUDGET_FILE).href
const installUrl = pathToFileURL(INSTALL_FILE).href
const linker = (specifier) => {
const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER
? specifier
@@ -559,6 +561,7 @@ export async function createBridgeKit(options = {}) {
else if (key === "./signin.mjs") module = sourceModule(SIGNIN_FILE, "", signinUrl)
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.startsWith("node:")) module = builtinModule(key, overrides[key])
else throw new Error(`testkit: 未登记的依赖 ${specifier}`)
cache.set(key, module)