Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions agy-cli.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,7 @@ for (const [name, mocks] of [
["account-scope.mjs", false],
["stateless-reuse.mjs", false],
["tools-listed.mjs", false],
["bridge-heal.mjs", false],
["slash-commands.mjs", false],
["concurrent-convs.mjs", false],
["masking-drift.mjs", false],
Expand Down
14 changes: 9 additions & 5 deletions default-agent.mjs
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
// Every agy session the plugin opens runs on agy's default agent. From agy
// 1.5.17 a session of a custom agent (--agent, .agents/agents/*) costs about
// four times the quota (google-antigravity/antigravity-cli#1890), and Google's
// answer is to drop --agent and give the instructions as rules. So a session's
// folder gets, in place of an agent.md:
// Every agy session the plugin opens runs on agy's default agent. It moved
// there when agy 1.5.17 charged a custom agent's session (--agent,
// .agents/agents/*) about four times the quota
// (google-antigravity/antigravity-cli#1890). Google reverted that charge on
// 2026-11-30, but the plugin stays on the default agent: it is the session
// agy itself opens, and with Antigravity accounts being disabled for terms
// violations (#1741) the session shape isn't changed until the owner rules on
// going back (#1777). Without --agent the instructions go in as rules, so a
// session's folder gets, in place of an agent.md:
// - AGENTS.md, the instructions: agy loads it as a workspace rule, also with
// --include-default-customizations=false (agy 1.5.19, measured).
// - .agents/skills.json excludes agy's bundled skills from the prompt index.
Expand Down
591 changes: 510 additions & 81 deletions index.mjs

Large diffs are not rendered by default.

43 changes: 15 additions & 28 deletions install.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -89,36 +89,30 @@ function checkReleaseVersion(version) {
if (tooOld) throw new Error(tooOld)
}

// 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)
})
// withOutput gives fill a write(chunk) for file that awaits the disk, and
// returns only once the handle has closed (a WriteStream's `finish` comes
// while the fd is still open for writing: ETXTBSY on Linux), failing if
// the write or the close does, after the partial file is closed.
async function withOutput(file, mode, fill) {
const handle = await fs.promises.open(file, "w", mode)
try {
await fill((chunk) => handle.writeFile(chunk))
} finally {
await handle.close()
}
}

// 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 {
await withOutput(file, 0o600, async (write) => {
for await (const chunk of res.body) {
hash.update(chunk)
if (!out.write(chunk)) await drained(out)
await write(chunk)
}
} finally {
out.end()
}
await wrote
})
return hash.digest("hex")
}

Expand Down Expand Up @@ -182,14 +176,7 @@ export async function untarMember(archive, name, file) {
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())))
}
await withOutput(file, 0o755, (write) => pass(size, write))
return true
}
await pass(size + pad, skip)
Expand Down
77 changes: 59 additions & 18 deletions install.test.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -8,8 +8,7 @@ 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 { agyPlatform, installAgy, installedVersion, untarMember, updateOwnAgy } from "./install.mjs"
import { agyCandidates, ownAgyPath } from "./platform.mjs"

const unix = process.platform !== "win32"
Expand Down Expand Up @@ -47,6 +46,31 @@ let manifest = null
let slow = false
let root

// failClose makes close() of the file install.mjs opens in dir with the
// given mode (0o600 the download, 0o755 the binary taken out of its
// archive) close for real, then fail with error: an installer that moved
// on before close() resolved installs a binary it never saw closed.
// It's restored after each test: fs.promises is one object.
function failClose(dir, mode, error) {
const real = fs.promises.open
const closed = []
fs.promises.open = async (file, flags, openMode) => {
const handle = await real(file, flags, openMode)
if (openMode !== mode || path.dirname(file) !== dir) return handle
const close = handle.close.bind(handle)
handle.close = async () => {
await close()
closed.push(file)
throw new Error(error)
}
return handle
}
return {
closed,
restore: () => { fs.promises.open = real },
}
}

beforeAll(() => {
server = Bun.serve({
port: 0,
Expand Down Expand Up @@ -197,19 +221,36 @@ test.if(unix)("only the plugin's own copy is kept current, and not when the user
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)
})
// Both ways a release arrives (the binary inside its archive, or a raw
// file) are written through a handle whose close the installer awaits
// before the staged binary is run or renamed: a WriteStream's `finish`
// came first, and Linux won't exec a file still open for writing
// (ETXTBSY). A close that fails must fail the install, not be left
// behind it.
for (const [kind, mode] of [["archive", 0o755], ["raw", 0o600]]) {
test.if(unix)(`${kind}: a staged binary whose close fails isn't installed; the old one stays`, async () => {
const bin = path.join(root, "agy")
release("1.5.19")
await installAgy({ bin, platform: "linux_amd64" })
const before = fs.readFileSync(bin)
if (kind === "archive") release("1.5.20")
else {
const body = script("1.5.20")
files.set("/r/raw", body)
manifest = { version: "1.5.20", url: "/r/raw", sha512: sha(body) }
}
const failing = failClose(root, mode, "close: disk gone")
try {
await expect(installAgy({ bin, platform: "linux_amd64" })).rejects.toThrow("close: disk gone")
// closed for real (the fixture file), once, before the failure
expect(fs.readFileSync(bin).equals(before)).toBe(true)
expect(Bun.spawnSync([bin]).stdout.toString()).toContain("agy 1.5.19")
expect(installedVersion(bin)).toBe("1.5.19")
expect(fs.readdirSync(root).sort()).toEqual(["agy", "agy.version"])
expect(failing.closed.length).toBe(1)
expect(path.dirname(failing.closed[0])).toBe(root)
} finally {
failing.restore()
}
})
}
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-agy-cli-auth",
"version": "0.1.178",
"version": "0.1.185",
"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",
Expand Down
186 changes: 186 additions & 0 deletions test/bridge-heal.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,186 @@
// plugins#1766: after about an hour on macOS every agy-cli account failed
// with tools_not_loaded until magpie restarted. The bridge made its `nc`
// shim dir and its control server once for the host's life: with the dir
// gone ($TMPDIR cleaned) agy ran whatever `nc` came next in PATH, and a
// closed control server was handed to every later agy. Both are checked
// before each agy and request now and made again, in the same place where
// that is safe, so the next turn works without a restart.
//
// bun test ./bridge-heal.mjs

import { test } from "node:test"
import assert from "node:assert/strict"
import fs from "node:fs"
import path from "node:path"
import { READ_TOOL, baseBody, createBridgeKit, readSse } from "./testkit.mjs"

const LINUX = { platform: "linux" }

// As agy does: it runs `nc` from PATH, and only the bridge's own shim, there
// and executable, reaches the MCP server. Anything else lists nothing.
function shimFirst(env) {
const file = path.join(String(env.PATH).split(path.delimiter)[0], "nc")
try {
if (!fs.statSync(file).isFile() || !fs.statSync(file).size) return false
fs.accessSync(file, fs.constants.X_OK)
return true
} catch {
return false
}
}

async function withKit(options, fn) {
const kit = await createBridgeKit({
...LINUX, listTools: shimFirst, ...options,
env: { AGY_BRIDGE_TOOL_LIST_WAIT_MS: "200", ...(options.env || {}) },
})
kit.defaultPrompt = async (agent) => {
await agent.text("ok")
return { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 1 } }
}
try {
return await fn(kit)
} finally {
await kit.dispose()
}
}

const shimDirOf = (spawn) => String(spawn.env.PATH).split(path.delimiter)[0]
const portOf = (spawn) => Number(spawn.env.AGY_BRIDGE_CONTROL_PORT)
const conversation = (name, extra = {}) => baseBody({ tools: [READ_TOOL], system: name, messages: [{ role: "user", content: name }], ...extra })
const followUp = (name) => baseBody({
tools: [READ_TOOL], system: name,
messages: [{ role: "user", content: name }, { role: "assistant", content: "ok" }, { role: "user", content: "again" }],
})

async function ok(kit, body) {
const parsed = await readSse(await kit.request(body))
assert.equal(parsed.error, null, JSON.stringify(parsed.error))
assert.equal(parsed.stopReason, "end_turn")
return parsed
}

test("the shim dir taken between two turns is made again where it was, and the next turn lists the tools", async () => {
await withKit({}, async (kit) => {
await ok(kit, conversation("one"))
const dir = shimDirOf(kit.acpSpawns[0])
assert.ok(shimFirst(kit.acpSpawns[0].env), "the first agy never had the shim")
// what a temp cleaner does
fs.rmSync(dir, { recursive: true, force: true })

await ok(kit, conversation("two"))
assert.equal(kit.acpSpawns.length, 2)
assert.equal(shimDirOf(kit.acpSpawns[1]), dir, "the shim moved, leaving the agy already started on the old dir")
assert.ok(shimFirst(kit.acpSpawns[1].env))
assert.equal(fs.statSync(dir).mode & 0o777, 0o700)
assert.ok(kit.listings.some((listing) => listing.spawn === 1 && listing.tools.includes("Read")),
`the second agy never listed Read: ${JSON.stringify(kit.listings)}`)
})
})

test("a shim left without its execute bit is written again", { skip: process.platform === "win32" }, async () => {
await withKit({}, async (kit) => {
await ok(kit, conversation("one"))
const file = path.join(shimDirOf(kit.acpSpawns[0]), "nc")
fs.chmodSync(file, 0o600)
await ok(kit, conversation("two"))
assert.ok(shimFirst(kit.acpSpawns[1].env))
})
})

test("a shim dir someone else holds now is left for a new one, and an agy on the old one is not reused", async () => {
await withKit({}, async (kit) => {
await ok(kit, conversation("one"))
const dir = shimDirOf(kit.acpSpawns[0])
// the freed name taken by a dir anyone can write (Linux's shared /tmp)
fs.rmSync(dir, { recursive: true, force: true })
fs.mkdirSync(dir)
fs.chmodSync(dir, 0o777)
await ok(kit, followUp("one"))
assert.equal(kit.acpSpawns.length, 2, "the follow-up stayed on the agy whose `nc` reaches nothing")
const moved = shimDirOf(kit.acpSpawns[1])
assert.notEqual(moved, dir)
assert.ok(shimFirst(kit.acpSpawns[1].env))
assert.equal(fs.existsSync(path.join(dir, "nc")), false, "a shim was written into a dir others can write")
})
})

test("a control server that closed between two turns is made again on its port, and the live agy reaches it", async () => {
await withKit({}, async (kit) => {
await ok(kit, conversation("one"))
const port = portOf(kit.acpSpawns[0])
kit.controlServer().close()
await new Promise((resolve) => setImmediate(resolve))

// the live agy of "one" calls the bridge again on its own port
kit.prompts[1] = async (agent) => {
const reply = await agent.listTools()
assert.ok((reply?.result?.tools || []).some((tool) => tool.name === "Read"), `no tools: ${JSON.stringify(reply)}`)
await agent.text("ok")
return { stopReason: "end_turn" }
}
await ok(kit, followUp("one"))
assert.equal(kit.acpSpawns.length, 1)
assert.equal(kit.controlServer()?.port, port)

await ok(kit, conversation("two"))
assert.equal(portOf(kit.acpSpawns[1]), port)
assert.ok(kit.listings.some((listing) => listing.spawn === 1 && listing.tools.includes("Read")))
})
})

test("a control server whose port was taken meanwhile listens on another, and the agy on the old port is replaced", async () => {
await withKit({}, async (kit) => {
await ok(kit, conversation("one"))
const port = portOf(kit.acpSpawns[0])
kit.controlServer().close()
kit.busyPorts.add(port)
await new Promise((resolve) => setImmediate(resolve))

await ok(kit, followUp("one"))
assert.equal(kit.acpSpawns.length, 2, "the follow-up stayed on an agy whose port reaches nothing")
assert.notEqual(portOf(kit.acpSpawns[1]), port)
assert.equal(portOf(kit.acpSpawns[1]), kit.controlServer().port)
assert.ok(kit.listings.some((listing) => listing.spawn === 1 && listing.tools.includes("Read")))
})
})

test("tools_not_loaded from a shim gone as agy started says why, names the plugin's own shim, and the next try heals", async () => {
let taken = false
const listTools = (env) => {
if (!taken) {
taken = true
fs.rmSync(shimDirOf({ env }), { recursive: true, force: true })
kit.acpSpawns.at(-1).child.stderr.emit("data", "mcp: ide-tools: exited before answering\n")
}
return shimFirst(env)
}
let kit
await withKit({ listTools }, async (made) => {
kit = made
const response = await kit.request(conversation("one"))
const text = await response.text()
assert.equal(response.status, 502, text)
const message = JSON.parse(text).error.message
assert.match(message, /agy never loaded the request's 1 tool:/)
assert.match(message, /this plugin's own `nc` shim \(not a netcat installed on this computer\)/)
assert.match(message, /nc shim: missing/)
assert.match(message, /control port \d+: listening/)
assert.match(message, /made again, the next try uses it/)
assert.match(message, /agy stderr: mcp: ide-tools: exited before answering/)

await ok(kit, conversation("one"))
assert.ok(kit.listings.some((listing) => listing.tools.includes("Read")))
})
})

test("tools_not_loaded with the shim and the control server fine says so", async () => {
await withKit({ listTools: false }, async (kit) => {
const response = await kit.request(conversation("one"))
const text = await response.text()
assert.equal(response.status, 502, text)
const message = JSON.parse(text).error.message
assert.match(message, /nc shim: ok; its runtime: ok; MCP server: ok; control port \d+: listening; agy stderr: \(empty\)/)
assert.doesNotMatch(message, /made again/)
})
})
Loading