diff --git a/agy-cli.test.mjs b/agy-cli.test.mjs index bb2fa11..0e73f00 100644 --- a/agy-cli.test.mjs +++ b/agy-cli.test.mjs @@ -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], diff --git a/index.mjs b/index.mjs index f2ded9d..6dd356a 100644 --- a/index.mjs +++ b/index.mjs @@ -444,10 +444,20 @@ let cachedAgyPath let cachedAgySearchKey let controlServer let controlServerPromise +// The port the control server was last on: one made again asks for it +// first, so every agy already started with it reaches the new one (#1766). +let controlPort = 0 let shimDir // Only a shim dir this process made is removed at exit; the shared Windows nc.exe dir stays. let shimDirOwned = false let shimDirPromise +let lastShimDir +// A shim check in flight (checkShim), shared by everyone who asks meanwhile. +let shimCheck = null +// Counts each time the shim dir or the control port moved: an agy started +// before (Proc.bridgeEpoch) runs a `nc` that reaches nothing, so it is never +// handed another session (#1766). +let bridgeEpoch = 0 function positiveTimeout(value, fallback) { const parsed = Number(value) @@ -1849,17 +1859,51 @@ class BusyError extends Error { // agy never listed the client's tools from the bridge's ide-tools MCP // server, so a turn would have the model see none of them, only agy's own // manage_task (plugins#1239). It names the cause where one is known. -function toolsUnlistedError(count) { +function toolsUnlistedError(count, diagnosis = "") { const windows = process.platform === "win32" && shimDirOwned const why = windows ? `nc.exe, the program agy runs to reach them, could not be built (${ncBuildFailure || "unknown reason"}), and agy doesn't run the nc.cmd used instead` - : `the MCP server agy starts through \`nc\` to reach them didn't answer within ${Math.round(TOOL_LIST_WAIT_MS / 1000)}s` - const error = new Error(`agy bridge: agy never loaded the request's ${count} tool${count === 1 ? "" : "s"}: ${why}. The model would have seen none of them`) + : `the bridge's MCP server, which agy starts through this plugin's own \`nc\` shim (not a netcat installed on this computer), didn't answer within ${Math.round(TOOL_LIST_WAIT_MS / 1000)}s` + const error = new Error(`agy bridge: agy never loaded the request's ${count} tool${count === 1 ? "" : "s"}: ${why}. The model would have seen none of them${diagnosis ? ` (${diagnosis})` : ""}`) error.statusCode = 502 error.code = "tools_not_loaded" return error } +// What an agy that never listed the tools had to reach the bridge with, in +// a few words for the error and the log, and both made again where one was +// broken, so the next try needs no restart (#1766): the nc shim its PATH +// starts with, the runtime and the MCP server the shim runs, and the +// control port the server connects to. +async function toolsUnlistedDiagnosis(proc) { + const bin = proc?.bridgeBin || shimDir + const shim = bin ? await shimState(bin, proc?.bridgeBin ? proc.bridgeShimOwned : shimDirOwned) : "none" + // a built nc.exe (Windows) carries its runtime + const runtime = process.platform === "win32" && !shimDirOwned ? null : await isFileWithBytes(process.execPath) ? "ok" : "missing" + const server = await isFileWithBytes(MCP_SERVER_PATH) ? "ok" : "missing" + const port = proc?.controlPort || controlPort + const listening = !!(controlServer?.listening && controlPort === port) + const moved = !!proc && proc.bridgeEpoch !== bridgeEpoch + const broken = shim !== "ok" || !listening + let healed = false + if (broken) { + await checkBridge().catch(() => {}) + healed = !!controlServer?.listening && !!shimDir && await shimState(shimDir, shimDirOwned) === "ok" + } + const stderr = String(proc?.stderrTail || "").trim().replace(/\s+/g, " ").slice(-300) + logSessionEvent(proc, "tools_not_loaded", { + shim, runtime, server, control_listening: listening, moved, healed, + }, "tools_not_loaded") + return [ + `nc shim: ${shim}`, + ...runtime ? [`its runtime: ${runtime}`] : [], + `MCP server: ${server}`, + `control port${port ? ` ${port}` : ""}: ${listening ? "listening" : "closed"}`, + ...broken ? [healed ? "made again, the next try uses it" : "could not be made again"] : [], + `agy stderr: ${stderr || "(empty)"}`, + ].join("; ") +} + class ConflictError extends Error { constructor(message, code) { super(message) @@ -1951,11 +1995,7 @@ function shellQuote(value) { // earlier in agy's PATH runs the bridge's stdio MCP server instead, so the // connection is authenticated by the per-process token in its environment. async function ensureShimDir() { - // Another host's sweep can take a shared dir that sat unused for a week. - if (shimDir && !shimDirOwned && !await isFileWithBytes(path.join(shimDir, "nc.exe"))) { - shimDir = undefined - shimDirPromise = null - } + await checkShim() // agy 1.5 never runs nc.cmd, so a Windows host left on it after a failed // nc.exe build had no client tool in any session until it restarted. The // build is tried again once NC_BUILD_RETRY_MS has passed (plugins#1239). @@ -1974,27 +2014,123 @@ async function ensureShimDir() { ncBuildFailure = "" shimDir = shared shimDirOwned = false + noteShimDir(shared) return shared } ncBuildFailedAt = Date.now() if (shimDirOwned && shimDir) return shimDir } const dir = await fs.promises.mkdtemp(path.join(os.tmpdir(), "magpie-agy-bridge-bin-")) - if (process.platform === "win32") { - await fs.promises.writeFile(path.join(dir, "nc.cmd"), - windowsMcpShim(process.execPath, MCP_SERVER_PATH)) - } else { - await fs.promises.writeFile(path.join(dir, "nc"), - `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(MCP_SERVER_PATH)}\n`, { mode: 0o700 }) - } + await writeShim(dir) shimDir = dir shimDirOwned = true + noteShimDir(dir) return dir })() shimDirPromise.catch(() => { shimDirPromise = null }) return shimDirPromise } +function shimName(owned) { + return process.platform === "win32" ? (owned ? "nc.cmd" : "nc.exe") : "nc" +} + +// "ok", "missing" or "not executable": the shim in dir agy would run. +async function shimState(dir, owned) { + const file = path.join(dir, shimName(owned)) + if (!await isFileWithBytes(file)) return "missing" + if (process.platform === "win32") return "ok" + try { + await fs.promises.access(file, fs.constants.X_OK) + return "ok" + } catch { + return "not executable" + } +} + +// Through a temp file and a rename: a shim being written is never run half +// done, and one left without its execute bit is replaced whole. +async function writeShim(dir) { + const windows = process.platform === "win32" + const file = path.join(dir, shimName(true)) + const body = windows + ? windowsMcpShim(process.execPath, MCP_SERVER_PATH) + : `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(MCP_SERVER_PATH)}\n` + const temp = `${file}.${randomBytes(4).toString("hex")}.tmp` + try { + await fs.promises.writeFile(temp, body, { mode: 0o700, flag: "wx" }) + await fs.promises.rename(temp, file) + } catch (error) { + await fs.promises.rm(temp, { force: true }).catch(() => {}) + throw error + } +} + +// The shim dir made at the first agy is checked before each later one, and +// before a request goes to an agy already running: a temp cleaner (macOS +// clears $TMPDIR), or anything else, can take the dir or the shim from +// under a host that lives for days. agy then ran whatever `nc` came next in +// PATH, never reached the bridge, and every account's every session failed +// tools_not_loaded until magpie restarted (#1766). The shim is made again +// in the same dir, so the agy already started with it in their PATH reach +// the bridge again too; only a dir that isn't safely this user's any more +// (on Linux's shared /tmp anyone can take a freed name) is left for a new +// one, and the agy started on the old one are retired (bridgeEpoch). +function checkShim() { + shimCheck ??= (async () => { + const dir = shimDir + if (!dir) return + const owned = shimDirOwned + if (await shimState(dir, owned) === "ok" || dir !== shimDir) return + if (!owned) { + // Another host's sweep can take a shared dir that sat unused for a week. + shimDir = undefined + shimDirPromise = null + return + } + const restored = await restoreShimDir(dir).catch(() => false) + if (dir !== shimDir || restored) return + shimDir = undefined + shimDirPromise = null + })().finally(() => { shimCheck = null }) + return shimCheck +} + +// The owned shim dir made again where it was, when that is still safe: +// gone (made again here, 0700), or a real dir of this user's that no one +// else can write. false otherwise. +async function restoreShimDir(dir) { + try { + await fs.promises.mkdir(dir, { mode: 0o700 }) + } catch (error) { + if (error?.code !== "EEXIST") return false + } + const stat = await fs.promises.lstat(dir) + if (!stat.isDirectory()) return false + if (process.platform !== "win32") { + if (typeof process.getuid === "function" && stat.uid !== process.getuid()) return false + if (stat.mode & 0o077) return false + } + await writeShim(dir) + return await shimState(dir, true) === "ok" +} + +// Everything an agy needs to reach the bridge's MCP server, checked and made +// again where broken: the control server and the shim (#1766). +async function checkBridge() { + await ensureControlServer() + await checkShim() + // one that had to go is made now, not at the next agy only + if (!shimDir && lastShimDir) await ensureShimDir() +} + +// The shim dir an agy is started with, noted: one in another place than +// the last moves bridgeEpoch. +function noteShimDir(dir) { + if (lastShimDir && lastShimDir !== dir) bridgeEpoch++ + lastShimDir = dir +} + // Windows: a dir holding only nc.exe, a GUI-subsystem build of mcp-server.mjs // (see windowsNcBuild). It is named for the runtime and the server's source, so // every session and every later host reuses it. One no host has started for a @@ -2959,8 +3095,14 @@ class Proc { async #spawn() { this.launchKey = await launchKey(this.agyPath, this.workDir, this.media) - await ensureControlServer() + const port = await ensureControlServer() const bin = await ensureShimDir() + // what this agy reaches the bridge through (toolsUnlistedDiagnosis); + // one started before either moved is never handed a session (#1766) + this.controlPort = port + this.bridgeBin = bin + this.bridgeShimOwned = shimDirOwned + this.bridgeEpoch = bridgeEpoch sessions.set(this.token, this) this.workspaceOwner = randomUUID() if (this.workspace) { @@ -2997,7 +3139,7 @@ class Proc { const args = [ "acp", "--log-file", this.logPath, - "--ide-mcp-port", String(controlServer.address().port), + "--ide-mcp-port", String(port), ] if (allowAgyTools) args.push("--dangerously-skip-permissions") // Only the bridge's workspace supplies project customizations. The @@ -3026,7 +3168,7 @@ class Proc { ...childEnv, ...hookEnv, PATH: bin + path.delimiter + inheritedPath, - AGY_BRIDGE_CONTROL_PORT: String(controlServer.address().port), + AGY_BRIDGE_CONTROL_PORT: String(port), AGY_BRIDGE_TOKEN: this.token, // view_file reads agy's temp folder unasked: the workspace, not // the one every other session's workspace is in @@ -3169,7 +3311,7 @@ class Proc { if (this.model) await this.#setModel(this.model, this.selection, this.resumed) this.phases.set_model_ms = Date.now() - configured if (this.tools.length) await this.#waitForToolList(this.toolsVersion) - if (!this.toolsListed()) throw toolsUnlistedError(this.tools.length) + if (!this.toolsListed()) throw toolsUnlistedError(this.tools.length, await toolsUnlistedDiagnosis(this).catch(() => "")) } async #setConfig(config, value) { @@ -5283,7 +5425,7 @@ async function takeSpare(agyPath, workDir, media) { } catch { return null } - if (spare.dead || spare.stopping) { + if (spare.dead || spare.stopping || spare.bridgeEpoch !== bridgeEpoch) { await spare.stop().catch(() => {}) return null } @@ -5473,11 +5615,18 @@ function heldFor(convKey, opts, resultBlocks) { // Caller holds the conversation lock; recovery must not acquire it recursively. async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, forceNew = false, lockedKeys = new Set([convKey]), launch = null) { await evictIdle() +<<<<<<< HEAD // Parallel lanes (local patch) const lane = pickLane(convKey, opts) let existing = lane.proc let key = lane.key let laneWhy = existing === null && key !== convKey ? "lane" : null +======= + // the shim and the control server, made again if either went (#1766); + // an agy that can't reach them any more is not taken below (bridgeEpoch) + await checkBridge().catch(() => {}) + let existing = pool.get(convKey) +>>>>>>> upstream if (existing?.turn?.cancelRequested) { await Promise.race([existing.turn.settled, new Promise((resolve) => setTimeout(resolve, CANCEL_SETTLE_MS))]) } @@ -5565,7 +5714,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo // than the empty history, so matchesHistory turns the next one away. const retriedOpening = isFreshConversation && existing.failedOpening const compatible = !forceNew && !existing.dead && !existing.retiring && - existing.workDir === opts.workDir && existing.media === opts.media && + existing.bridgeEpoch === bridgeEpoch && existing.workDir === opts.workDir && existing.media === opts.media && sameInstructions(existing.instructions, opts.instructions) && (existing.matchesHistory(matchedHistory) || continuedFresh) if (compatible && (!(isFreshConversation && existing.hasSentFirstTurn) || continuedFresh || retriedOpening)) { @@ -5587,6 +5736,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo const newOpening = isFreshConversation && existing.hasSentFirstTurn && !continuedFresh && Array.isArray(matchedHistory) && !matchedHistory.length why = forceNew ? "forced" : existing.dead ? "dead" : existing.retiring ? "retiring" : + existing.bridgeEpoch !== bridgeEpoch ? "bridge_moved" : existing.workDir !== opts.workDir ? "work_dir" : existing.media !== opts.media ? "media" : !sameInstructions(existing.instructions, opts.instructions) ? "instructions" : @@ -6760,7 +6910,7 @@ function sameOpeningDonor(proc, launch, opts) { return !!proc && !proc.dead && !proc.stopping && !proc.retiring && !proc.turn && (proc.closable || proc.sessionPrompts === 1) && !proc.resumed && proc.hasSentFirstTurn && !!proc.sessionId && !proc.tools?.length && - proc.launchKey === launch && (proc.userId || "") === (opts.userId || "") && + proc.bridgeEpoch === bridgeEpoch && proc.launchKey === launch && (proc.userId || "") === (opts.userId || "") && (proc.sessionScope || "") === (opts.sessionScope || "") && proc.workDir === opts.workDir && process.env.AGY_BRIDGE_STATELESS_REUSE !== "0" } @@ -6784,7 +6934,7 @@ function findStatelessDonor(opts, launch) { function statelessDonor(proc, launch, userId, sessionScope, workDir) { return !!proc && proc.stateless && !proc.dead && !proc.stopping && !proc.retiring && !proc.turn && !proc.resumed && proc.hasSentFirstTurn && proc.sessionPrompts === 1 && !!proc.sessionId && - proc.launchKey === launch && (proc.userId || "") === userId && + proc.bridgeEpoch === bridgeEpoch && proc.launchKey === launch && (proc.userId || "") === userId && (proc.sessionScope || "") === sessionScope && proc.workDir === workDir } @@ -9550,18 +9700,50 @@ function workDirectory(directory) { return null } +// The control server every agy's MCP server connects to. One that closed or +// failed is made again, on the port it had when that is free: it was kept +// for the host's life, so a server gone for any reason left every later +// session without the client's tools until magpie restarted (#1766). function ensureControlServer() { + if (controlServerPromise && controlServer && !controlServer.listening) dropControlServer(controlServer) if (controlServerPromise) return controlServerPromise - controlServerPromise = new Promise((resolve, reject) => { + const want = controlPort + const promise = listenControl(want).catch((error) => { + if (want && error?.code === "EADDRINUSE") return listenControl(0) + throw error + }) + controlServerPromise = promise + promise.catch(() => { if (controlServerPromise === promise) controlServerPromise = null }) + return promise +} + +function listenControl(port) { + return new Promise((resolve, reject) => { const server = net.createServer((socket) => handleControlConnection(socket)) server.once("error", reject) - server.listen(0, "127.0.0.1", () => { + server.listen(port, "127.0.0.1", () => { + server.off("error", reject) + // An error once listening (no listener would end the host) or a + // close: the next agy or request makes it again. + server.on("error", () => { + dropControlServer(server) + try { server.close() } catch {} + }) + server.on("close", () => dropControlServer(server)) + const bound = server.address().port + if (controlPort && bound !== controlPort) bridgeEpoch++ + controlPort = bound controlServer = server server.unref() - resolve(server.address().port) + resolve(bound) }) }) - return controlServerPromise +} + +function dropControlServer(server) { + if (controlServer !== server) return + controlServer = undefined + controlServerPromise = null } function tokenMatches(left, right) { diff --git a/package.json b/package.json index bba5650..3764341 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/test/bridge-heal.mjs b/test/bridge-heal.mjs new file mode 100644 index 0000000..b0878dc --- /dev/null +++ b/test/bridge-heal.mjs @@ -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/) + }) +}) diff --git a/test/testkit.mjs b/test/testkit.mjs index 4756ac0..ddce999 100644 --- a/test/testkit.mjs +++ b/test/testkit.mjs @@ -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") } @@ -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 } @@ -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 }, diff --git a/test/usage-settlement.mjs b/test/usage-settlement.mjs index 18d97f9..1cfb237 100644 --- a/test/usage-settlement.mjs +++ b/test/usage-settlement.mjs @@ -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 @@ -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 { diff --git a/test/usage.mjs b/test/usage.mjs index 7ce3237..bc154c3 100644 --- a/test/usage.mjs +++ b/test/usage.mjs @@ -6,7 +6,7 @@ import fs from "node:fs/promises" import os from "node:os" import path from "node:path" import { test } from "node:test" -import { agyRefusal, createUsageReader, DUE_FOR_RENEWAL, fetchUsage, GATEWAY_NO_FOLDER, parseStatusLineQuota, parseUsageReport, STILL_READING, verifyLinkIn } from "../usage.mjs" +import { agyRefusal, createUsageReader, DUE_FOR_RENEWAL, retryIn, fetchUsage, GATEWAY_NO_FOLDER, parseStatusLineQuota, parseUsageReport, STILL_READING, verifyLinkIn } from "../usage.mjs" import { catalogRows, familiesInGroup, modelsInGroup, storeCatalogRows } from "../model-ids.mjs" import { inAccount } from "../account.mjs" import { forgetStoredSignIn } from "../signin.mjs" @@ -857,6 +857,96 @@ test("a failure held for one agy is not another agy's", async t => { await f.assertClean() }) +// agy updating itself writes a new binary at the same path. The update the +// reporter of plugins#1761 saw (1.5.17 to 1.5.20, the plugin and its host +// restarted minutes later) is this fake failing, slowly or not, and then +// replaced by one that answers. +async function updateInPlace(f) { + const next = f.executable + ".new" + const body = await fs.readFile(f.executable, "utf8") + await fs.writeFile(next, body + (process.platform === "win32" ? "rem 1.5.20\r\n" : "# 1.5.20\n"), { mode: 0o700 }) + await fs.rename(next, f.executable) +} + +test("an agy updated in place is read at once, not held for the old binary's failures (plugins#1761)", async t => { + for (const [mode, expected] of [["fail", /network or proxy/], ["version-hang", /didn't say its version/]]) { + const f = await fixture(t, { TEST_MODE: mode, TEST_ERROR: "connection refused" }) + let clock = 0 + const read = createUsageReader(() => f.executable, { ...f.options, timeoutMs: 3000, now: () => clock }) + const runs = async () => (await f.logs()).length + // the old binary fails twice in a row, so its hold has grown + assert.match((await read()).error, expected) + clock += 60 * 60 * 1000 + assert.match((await read()).error, expected) + const before = await runs() + f.env.TEST_MODE = "" + clock += 60 * 1000 + assert.match((await read()).error, expected, `${mode}: the same binary is held`) + assert.equal(await runs(), before) + await updateInPlace(f) + const result = await read() + assert.equal(result.error, undefined, `${mode}: ${result.error}`) + assert.equal(result.windows.length, 1) + assert.ok(await runs() > before) + await f.assertClean() + } +}) + +test("a new binary starts its own count: one failure after an update is held ten minutes, not the old binary's hours", async t => { + const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "unrecognized" }) + let clock = 0 + const read = createUsageReader(() => f.executable, { ...f.options, now: () => clock }) + const minute = 60 * 1000 + const runs = async () => (await f.logs()).filter(l => l.args[0] !== "--version").length + await read() + for (const wait of [10, 20, 40]) { + clock += wait * minute + await read() + } + assert.match((await read()).error, /again in 1\.3 hours\.$/) + await updateInPlace(f) + assert.match((await read()).error, /again in 10 minutes\.$/, "the updated binary fails once") + const before = await runs() + clock += 10 * minute + await read() + assert.equal(await runs(), before + 1, "read again ten minutes after its first failure") + await f.assertClean() +}) + +test("a first start that keeps running out of time is never held past ten minutes", async t => { + const f = await fixture(t, { TEST_MODE: "version-hang" }) + let clock = 0 + const read = createUsageReader(() => f.executable, { ...f.options, timeoutMs: 3000, now: () => clock }) + const minute = 60 * 1000 + const runs = async () => (await f.logs()).length + assert.match((await read()).error, /didn't say its version[\s\S]*magpie asks agy again in a minute\.$/) + for (const wait of [1, 2, 4, 8, 10, 10]) { + const before = await runs() + clock += wait * minute - 1000 + const held = await read() + assert.equal(await runs(), before, `run again before ${wait} minutes`) + assert.match(held.error, /magpie asks agy again in (?:a minute|\d+ minutes)\.$/) + clock += 1000 + const again = await read() + assert.equal(await runs(), before + 1, `not run again after ${wait} minutes`) + assert.match(again.error, /didn't say its version/) + } + await f.assertClean() +}) + +test("a held failure says when agy is asked again", async t => { + const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "connection refused" }) + let clock = 0 + const read = createUsageReader(() => f.executable, { ...f.options, now: () => clock }) + assert.match((await read()).error, /network or proxy[\s\S]* magpie asks agy again in 10 minutes\.$/) + clock += 4 * 60 * 1000 + 1 + assert.match((await read()).error, / magpie asks agy again in 6 minutes\.$/) + for (const [ms, said] of [[1, "a minute"], [60_000, "a minute"], [61_000, "2 minutes"], [59 * 60_000, "59 minutes"], [60 * 60_000, "an hour"], [90 * 60_000, "1.5 hours"], [6 * 60 * 60_000, "6 hours"]]) { + assert.equal(retryIn(ms), said, String(ms)) + } + await f.assertClean() +}) + const startupAuthLogs = [ "W1115 15:13:30.249469 10 cache.go:157] error getting token source: You are not logged into Antigravity.", "I1115 15:13:30.317328 1 server_oauth.go:226] OAuth: authenticated successfully", @@ -1382,7 +1472,7 @@ test("a read that runs out of time says so plainly, and is asked again a minute const result = await read() assert.deepEqual(result.windows, []) assert.equal(result.signIn, "kept") - assert.match(result.error, /agy's own usage read didn't finish in 3s[\s\S]*asked again in a minute[\s\S]*network or proxy/) + assert.match(result.error, /agy's own usage read didn't finish in 3s[\s\S]*network or proxy[\s\S]*magpie asks agy again in a minute\.$/) const runs = async () => (await f.logs()).filter(l => l.args[0] === "-p").length assert.equal(await runs(), 1) clock += 59_000 diff --git a/usage.mjs b/usage.mjs index 2cf99d1..d2dbdf6 100644 --- a/usage.mjs +++ b/usage.mjs @@ -687,7 +687,7 @@ export async function fetchUsage(agy, { version = await run(agy, ["--version"], options).catch((error) => { // not kind "timeout": --version needs no sign-in, so its hang is // never agy waiting on one - if (error?.kind === "timeout") throw new UsageError(`agy didn't say its version in ${limit / 1000}s (its first start after an update can take that long), so the quota wasn't read. It's asked again in a minute.`, { slow: true }) + if (error?.kind === "timeout") throw new UsageError(`agy didn't say its version in ${limit / 1000}s (its first start after an update can take that long), so the quota wasn't read.`, { slow: true }) throw error }) if (version.code !== 0) throw commandFailure(version.stderr) @@ -707,7 +707,7 @@ export async function fetchUsage(agy, { // start. It gets the whole deadline. const result = await run(agy, [...folderArgs, "-p", "/usage", "--output-format", "json", "--print-timeout", `${Math.max(1, Math.ceil((deadline - Date.now()) / 1000))}s`], options).catch((error) => { if (error?.kind !== "timeout") throw error - throw new UsageError(`agy's own usage read didn't finish in ${limit / 1000}s. agy asks Google about twelve times, one after another, before it has the quota, which takes longer behind a slow network or proxy. It's asked again in a minute; if this stays, check agy's network or proxy.`, { kind: "timeout", output: error.output }) + throw new UsageError(`agy's own usage read didn't finish in ${limit / 1000}s. agy asks Google about twelve times, one after another, before it has the quota, which takes longer behind a slow network or proxy. If this stays, check agy's network or proxy.`, { kind: "timeout", output: error.output }) }) if (folderArgs.length && result.code !== 0 && NO_GEMINI_DIR_FLAG.test(result.stderr + "\n" + result.stdout)) throw new UsageError(GATEWAY_NO_FOLDER) let report @@ -744,16 +744,30 @@ export async function fetchUsage(agy, { // A read that failed isn't run again for this long, doubled for each // failure in a row, up to BACKOFF_MOST: agy is a process of its own, and one // that fails every few minutes all day helps nobody. One that ran out of -// time is asked again sooner: a slow minute on the network (or agy's first -// start after an update) said "timed out" for ten (flmaximwang on -// plugins#1522), and a newly added account showed no quota for as long -// (Jayc1world on X). +// time is asked again sooner, and never held past BACKOFF_SLOW_MOST: a slow +// minute on the network (or agy's first start after an update) said "timed +// out" for ten (flmaximwang on plugins#1522), a newly added account showed +// no quota for as long (Jayc1world on X), and a slow first start must not +// grow into hours. const BACKOFF_FIRST_MS = 10 * 60 * 1000 const BACKOFF_SLOW_MS = 60 * 1000 +const BACKOFF_SLOW_MOST_MS = BACKOFF_FIRST_MS const BACKOFF_MOST_MS = 6 * 60 * 60 * 1000 function backoff(n, slow = false) { - return Math.min((slow ? BACKOFF_SLOW_MS : BACKOFF_FIRST_MS) * 2 ** Math.max(0, Math.min(n, 20) - 1), BACKOFF_MOST_MS) + return Math.min((slow ? BACKOFF_SLOW_MS : BACKOFF_FIRST_MS) * 2 ** Math.max(0, Math.min(n, 20) - 1), slow ? BACKOFF_SLOW_MOST_MS : BACKOFF_MOST_MS) +} + +// when a held failure is tried again, in the words its error ends with +export function retryIn(ms) { + const minutes = Math.max(1, Math.ceil(ms / 60_000)) + if (minutes < 60) return minutes === 1 ? "a minute" : `${minutes} minutes` + const hours = Math.round(minutes / 6) / 10 + return hours === 1 ? "an hour" : `${hours} hours` +} + +function heldError(held, at) { + return `${held.error} magpie asks agy again in ${retryIn(held.until - at)}.` } // what usage says while no agy is found: never held (createUsageReader), @@ -786,7 +800,10 @@ export const STILL_READING = "agy is still reading this account's quota (its own // - an explicit authentication rejection, or an ended token hanging silently // or with sign-in talk, blocks further background runs for that credential. // Diagnostic-only output isn't evidence of a browser sign-in. -// - any other failure isn't run again for backoff(n). No agy found is not +// - any other failure isn't run again for backoff(n), and says when it is +// (heldError). The hold is for one agy binary: an agy updated in place +// (same path, another size or modification time; plugins#1761) is read +// at once, and starts its count again. No agy found is not // held: finding it costs a few stat calls, and an agy installed since (a // sign-in installs it; tmr11235 on X saw it) is used on the next read, // not after hours of "not found" while its chats already run. @@ -811,7 +828,7 @@ export function createUsageReader(resolveAgy, options = {}) { return { windows: [], error: `${why}. ${NEEDS_SIGN_IN}`, signIn: "expired" } } // what a finished read says, worked out once for whoever takes it - const settle = (outcome, { agy, key, stored }) => { + const settle = (outcome, { agy, binary, key, stored }) => { if (!outcome.error) { const result = { ...structuredClone(outcome.result), signIn: saidExpired ? "renewed" : "kept" } held = null @@ -828,10 +845,11 @@ export function createUsageReader(resolveAgy, options = {}) { noteDead(stored) return expired("agy's sign-in no longer works") } - const n = held?.key === key && held.agy === agy ? held.n + 1 : 1 - held = { key, agy, n, until: now() + backoff(n, !auth && (error?.kind === "timeout" || error?.slow === true)), error: message, auth } + const n = held?.key === key && held.agy === agy && held.binary === binary ? held.n + 1 : 1 + const at = now() + held = { key, agy, binary, n, until: at + backoff(n, !auth && (error?.kind === "timeout" || error?.slow === true)), error: message, auth } if (auth) saidExpired = true - return { windows: [], error: message, signIn: auth ? "expired" : "kept" } + return { windows: [], error: heldError(held, at), signIn: auth ? "expired" : "kept" } } return async () => { const asked = Date.now() @@ -852,10 +870,12 @@ export function createUsageReader(resolveAgy, options = {}) { return reply } late = null - // a failure held for another agy (gone, or another found since) isn't - // this one's - if (held && held.key === key && held.agy === agy && now() < held.until) { - return { windows: [], error: held.error, signIn: held.auth ? "expired" : "kept" } + // a failure held for another agy (gone, another found since, or this + // one updated in place) isn't this one's + const binary = await binaryKey(agy) + const at = now() + if (held && held.key === key && held.agy === agy && held.binary === binary && at < held.until) { + return { windows: [], error: heldError(held, at), signIn: held.auth ? "expired" : "kept" } } let read = pending.get(agy) if (!read) { @@ -867,7 +887,7 @@ export function createUsageReader(resolveAgy, options = {}) { const entry = { waiting: 0 } entry.done = fetchUsage(agy, fetchOptions).then(result => ({ result }), error => ({ error })).then((outcome) => { if (pending.get(agy) === entry) pending.delete(agy) - const reply = settle(outcome, { agy, key, stored }) + const reply = settle(outcome, { agy, binary, key, stored }) // nobody waits for it any more: the next call takes it if (entry.waiting === 0 && !outcome.error) late = { key, agy, reply, at: now() } onSettled(reply)