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
236 changes: 209 additions & 27 deletions index.mjs

Large diffs are not rendered by default.

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.181",
"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/)
})
})
60 changes: 50 additions & 10 deletions test/testkit.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -394,7 +394,7 @@ class FakeAgy {
return true
}
this.watchSocket = socket
this.kit.controlHandler(socket)
this.kit.connectControl(socket, this.env)
socket.emit("data", JSON.stringify({ token: this.token, kind: "watch" }) + "\n")
}

Expand All @@ -408,7 +408,7 @@ class FakeAgy {

control(message) {
const socket = new FakeSocket()
this.kit.controlHandler(socket)
this.kit.connectControl(socket, this.env)
socket.emit("data", JSON.stringify({ token: this.token, ...message }) + "\n")
return socket.reply
}
Expand Down Expand Up @@ -660,20 +660,60 @@ export async function createBridgeKit(options = {}) {
? callback(Object.assign(new Error("not found (test)"), { code: 44 }), "", "")
: callback(null, stored, ""))
}
const fakeServer = {
once() { return fakeServer },
on() { return fakeServer },
listen(_port, _host, callback) { setImmediate(callback); return fakeServer },
unref() { return fakeServer },
close() {},
address() { return { address: "127.0.0.1", family: "IPv4", port: 45999 } },
// The control server: each one the bridge makes listens on a port of
// its own (the first 45999), or the one it asks for unless a server or
// kit.busyPorts holds it. An agy's MCP server connects to the port in its
// environment, and reaches nothing once that server closed (#1766).
kit.controlServers = []
kit.busyPorts = new Set()
let nextPort = 45999
const listeningOn = (port) => kit.controlServers.find((server) => server.listening && server.port === port)
class FakeServer extends EventEmitter {
constructor(handler) {
super()
this.handler = handler
this.listening = false
this.port = 0
}
listen(port, _host, callback) {
setImmediate(() => {
if (port && (kit.busyPorts.has(port) || listeningOn(port))) {
this.emit("error", Object.assign(new Error(`listen EADDRINUSE: address already in use 127.0.0.1:${port}`), { code: "EADDRINUSE" }))
return
}
this.port = port || nextPort++
this.listening = true
kit.controlServers.push(this)
callback()
})
return this
}
unref() { return this }
close() {
if (!this.listening) return this
this.listening = false
setImmediate(() => this.emit("close"))
return this
}
address() { return this.listening ? { address: "127.0.0.1", family: "IPv4", port: this.port } : null }
}
// where the bridge's agy connect: the server on their port, or none
kit.connectControl = (socket, env) => {
const port = Number(env?.AGY_BRIDGE_CONTROL_PORT)
const server = port ? listeningOn(port) : kit.controlServers.findLast((item) => item.listening)
if (!server) {
setImmediate(() => socket.destroy())
return
}
server.handler(socket)
}
kit.controlServer = () => kit.controlServers.findLast((server) => server.listening) ?? null
const overrides = {
"node:child_process": { spawn, spawnSync, execFile },
"node:net": {
createServer(handler) {
kit.controlHandler = handler
return fakeServer
return new FakeServer(handler)
},
},
"node:os": { homedir: () => home, tmpdir: () => options.tmpdir ?? tmp },
Expand Down
22 changes: 16 additions & 6 deletions test/usage-settlement.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -1779,8 +1779,15 @@ test("SQLite 异常保护:超额失真行触发回退,EXCLUSIVE 锁库立即
`超额失真的 SQLite 行(90000)未被拦截,实际返回窗口=${usageTotal(responses[0].usage)}`)
})

// 子场景 2:数据库被 EXCLUSIVE 锁住(SQLITE_BUSY)时立即放弃轮询,不耗满 1000ms
await withKit({}, async (kit) => {
// 子场景 2:数据库被 EXCLUSIVE 锁住(SQLITE_BUSY)时立即放弃轮询。
// 不量首步用了多久(plugins#1765:负载下没轮询也要 653ms,旧的 500ms 线没有余量):
// 把轮询上限调到十分钟,锁一直持有到工具结果回来;只要锁住时还在轮询,首步就要等满
// 十分钟,下面 60s 的线两边都留足余量。
await withKit({ indexTransform: (source) => {
const pattern = /const STEP_USAGE_WAIT_MS = 1_000\n/
assert.match(source, pattern, "STEP_USAGE_WAIT_MS 改名或改值后这里要跟着改")
return source.replace(pattern, "const STEP_USAGE_WAIT_MS = 600_000\n")
} }, async (kit) => {
const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations")
fs.mkdirSync(convDir, { recursive: true })
let locker = null
Expand All @@ -1803,11 +1810,14 @@ test("SQLite 异常保护:超额失真行触发回退,EXCLUSIVE 锁库立即
})
try {
const body = baseBody()
const t0 = performance.now()
const toolResp = await readSse(await kit.request(body))
const toolElapsedMs = performance.now() - t0
let bound
const toolResp = await Promise.race([
kit.request(body).then(readSse),
new Promise((_, reject) => {
bound = setTimeout(() => reject(new Error("SQLITE_BUSY 时首步 60s 仍未返回:锁住的库还在被轮询")), 60_000)
}),
]).finally(() => clearTimeout(bound))
assert.equal(toolResp.stopReason, "tool_use")
assert.ok(toolElapsedMs < 500, `SQLITE_BUSY 时首步耗时 ${toolElapsedMs.toFixed(0)}ms,不应重复轮询阻塞至 1000ms`)
const finalResp = await readSse(await kit.request(continueWithToolResults(body, toolResp, () => "ok")))
assert.equal(finalResp.stopReason, "end_turn")
} finally {
Expand Down
Loading