diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index b7bb4c9..2162795 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -31,6 +31,7 @@ for (const [name, mocks] of [ ["conversation-key.mjs", false], ["windows-nc.mjs", false], ["spare.mjs", false], + ["tools-listed.mjs", false], ]) { test(`test/${name}`, () => { // bun's 5s default per test is a fixed wait these process-spawning tests diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index 8796f98..4358934 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -105,7 +105,10 @@ const SELF_POLL_LIMIT = positiveTimeout(process.env.AGY_BRIDGE_SELF_POLL_LIMIT, // SDK) stop their automatic retries instead of resending it. const NO_RETRY_HEADERS = { "x-should-retry": "false" } const SELF_POLL_NOTE = "agy bridge: gave up waiting for this tool: the client never returned a result for it; stop this turn" -const TOOL_LIST_WAIT_MS = 5_000 +// How long a session that declares tools waits for agy to list them from the +// ide-tools MCP server. One whose agy never does fails rather than running a +// turn the model sees none of the client's tools in (plugins#1239). +const TOOL_LIST_WAIT_MS = positiveTimeout(process.env.AGY_BRIDGE_TOOL_LIST_WAIT_MS, 20_000) const STDERR_TAIL = 32 * 1024 const CONTROL_LINE_LIMIT = 16 * 1024 * 1024 const ACP_LINE_LIMIT = 64 * 1024 * 1024 @@ -1110,6 +1113,20 @@ 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) { + 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`) + error.statusCode = 502 + error.code = "tools_not_loaded" + return error +} + class ConflictError extends Error { constructor(message, code) { super(message) @@ -1176,14 +1193,28 @@ async function ensureShimDir() { shimDir = undefined shimDirPromise = null } + // 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). + if (shimDirPromise && process.platform === "win32" && ncBuildFailure && shimDirOwned && + Date.now() - ncBuildFailedAt >= NC_BUILD_RETRY_MS) { + shimDirPromise = null + } if (shimDirPromise) return shimDirPromise shimDirPromise = (async () => { if (process.platform === "win32") { - const shared = await windowsNcDir().catch(() => null) + const shared = await windowsNcDir().catch((error) => { + ncBuildFailure = String(error?.message ?? error) + return null + }) if (shared) { + ncBuildFailure = "" shimDir = shared + shimDirOwned = false 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") { @@ -1208,6 +1239,11 @@ async function ensureShimDir() { const WINDOWS_NC_PREFIX = "magpie-agy-bridge-nc-" const WINDOWS_NC_BUILD_PREFIX = "magpie-agy-bridge-ncbuild-" const WINDOWS_NC_BUILD_TIMEOUT_MS = 120_000 +const NC_BUILD_RETRY_MS = 5 * 60 * 1000 +// Why the last nc.exe build didn't give one, "" when it did; it is named in +// the error of a session whose agy then never listed the client's tools. +let ncBuildFailure = "" +let ncBuildFailedAt = 0 // Each nc dir names the runtime that built it, so a build for a newer // mcp-server.mjs drops the same runtime's older ones at once: each holds a // whole Bun runtime (~115MB), and a week of plugin updates piles them up @@ -1228,7 +1264,10 @@ async function isFileWithBytes(file) { } async function windowsNcDir() { - if (!windowsNcBuild(process.execPath, MCP_SERVER_PATH, "nc.exe")) return null + if (!windowsNcBuild(process.execPath, MCP_SERVER_PATH, "nc.exe")) { + ncBuildFailure = `${path.win32.basename(String(process.execPath || ""))} is not Bun, which builds it` + return null + } const tmp = os.tmpdir() const source = await fs.promises.readFile(MCP_SERVER_PATH) const runtimeKey = createHash("sha256").update(String(process.execPath)).update("\0") @@ -1254,15 +1293,22 @@ async function windowsNcDir() { // A copy of it in an ASCII-only folder builds the same nc.exe. const base = [tmp, process.env.PUBLIC, process.env.ProgramData] .find(dir => dir && asciiPath(dir)) - if (!base) return null + if (!base) { + ncBuildFailure = "Bun is under a non-ASCII folder and there is no ASCII-only folder to copy it to" + return null + } copyBase = base copy = base === tmp ? build : await fs.promises.mkdtemp(path.join(base, WINDOWS_NC_BUILD_PREFIX)) runtime = path.join(copy, path.win32.basename(process.execPath)) await fs.promises.copyFile(process.execPath, runtime) } const spec = windowsNcBuild(runtime, MCP_SERVER_PATH, path.join(build, "nc.exe")) - const { err, code, timedOut } = await execOnce(spec.file, spec.args, { cwd: build, timeoutMs: WINDOWS_NC_BUILD_TIMEOUT_MS }) - if (err || timedOut || code !== 0 || !await isFileWithBytes(path.join(build, "nc.exe"))) return null + const { err, code, timedOut, stdout, stderr } = await execOnce(spec.file, spec.args, { cwd: build, timeoutMs: WINDOWS_NC_BUILD_TIMEOUT_MS }) + if (err || timedOut || code !== 0 || !await isFileWithBytes(path.join(build, "nc.exe"))) { + const said = String(stderr || stdout || err?.message || "").trim().split(/\r?\n/).filter(Boolean).slice(-2).join(" ") + ncBuildFailure = `bun build ${timedOut ? `timed out after ${WINDOWS_NC_BUILD_TIMEOUT_MS / 1000}s` : !err && code === 0 ? "wrote no nc.exe" : `exited with ${code ?? "an error"}`}${said ? `: ${said.slice(0, 300)}` : ""}` + return null + } await fs.promises.mkdir(dir, { recursive: true }) await fs.promises.writeFile(path.join(dir, WINDOWS_NC_RUNTIME_FILE), runtimeKey).catch(() => {}) try { @@ -2163,6 +2209,7 @@ class Proc { inAccount(this.home, () => noteOfferedModels(this.configOptions, session?.models)) if (this.model) await this.#setModel(this.model, this.selection, this.resumed) if (this.tools.length) await this.#waitForToolList(this.toolsVersion) + if (!this.toolsListed()) throw toolsUnlistedError(this.tools.length) } async #setConfig(config, value) { @@ -2257,6 +2304,14 @@ class Proc { socket.once("close", () => this.watchers.delete(socket)) } + // Whether agy has listed the catalog the client declares now. agy reads + // the tools from the ide-tools MCP server it starts through `nc`; when that + // never runs or never answers, the model sees only agy's own manage_task + // (plugins#1239). + toolsListed() { + return !this.tools.length || this.listedVersion >= this.toolsVersion + } + // Whether the client now declares a tool agy has not listed. agy checks a // call against the tools it listed before the prompt began, so a tool added // mid-turn (ToolSearch) stays unknown until the next session/prompt (#942). @@ -3506,12 +3561,16 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo existing.openingImages = openingImagesOf(first) } await existing.updateTools(opts.tools) - return { proc: existing, history: matchedHistory } + // agy never listed the tools this request declares (an agy started + // with none whose MCP server never connected): a new one may. + if (existing.toolsListed()) return { proc: existing, history: matchedHistory } + why = "tools_unlisted" + } else { + why = forceNew ? "forced" : existing.dead ? "dead" : existing.retiring ? "retiring" : + existing.workDir !== opts.workDir ? "work_dir" : + !sameInstructions(existing.instructions, opts.instructions) ? "instructions" : + !(existing.matchesHistory(matchedHistory) || continuedFresh) ? "history" : "fresh_after_first" } - why = forceNew ? "forced" : existing.dead ? "dead" : existing.retiring ? "retiring" : - existing.workDir !== opts.workDir ? "work_dir" : - !sameInstructions(existing.instructions, opts.instructions) ? "instructions" : - !(existing.matchesHistory(matchedHistory) || continuedFresh) ? "history" : "fresh_after_first" existing.retiring = true dropFromPool(existing) await existing.stop().catch(() => {}) diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 0cfb5c8..461f2f1 100644 --- a/packages/agy-cli/package.json +++ b/packages/agy-cli/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.88", + "version": "0.1.89", "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/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index e518ba8..8d3878a 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -226,7 +226,12 @@ class FakeAgy { // offeredModels may be a function of the agy's HOME: accounts on // different plans are offered different models (#1229). this.offered = () => typeof kit.offeredModels === "function" ? kit.offeredModels(this.env.HOME ?? "") : kit.offeredModels + // Whether this agy reaches the bridge's MCP server and lists the tools; + // listTools(env) false stands in for an `nc` agy never runs (nc.cmd + // under agy 1.5 on Windows, plugins#1239). + this.listsTools = () => typeof kit.listTools === "function" ? kit.listTools(this.env) : kit.listTools !== false child.onKill = () => { + this.watchSocket?.close() for (const waiter of this.cancelWaiters.splice(0)) waiter() } } @@ -271,7 +276,7 @@ class FakeAgy { this.send({ id, error: this.kit.sessionNewError }) } else if (method === "session/resume" && this.kit.sessionResume && params?.sessionId) { this.sessionId = params.sessionId - if (this.token) this.control({ kind: "list" }) + if (this.token && this.listsTools()) this.listAndWatch() const models = { currentModelId: this.kit.initialAgyModel } if (this.offered()) models.availableModels = this.offered().map(([modelId, name]) => ({ modelId, name })) this.respond(id, { sessionId: this.sessionId, models }) @@ -279,7 +284,7 @@ class FakeAgy { this.sessionId = `fake-session-${++this.kit.sessionSerial}` // Only the bridge's own processes carry a control token; the catalog's // model probe runs agy without one, as real agy does without --ide-mcp-port. - if (this.token) this.control({ kind: "list" }) + if (this.token && this.listsTools()) this.listAndWatch() const models = { currentModelId: this.kit.initialAgyModel } // What agy offers this client in the session; unset, the session names none. if (this.offered()) models.availableModels = this.offered().map(([modelId, name]) => ({ modelId, name })) @@ -324,6 +329,30 @@ class FakeAgy { this.send({ method: "session/update", params: { sessionId: this.sessionId, update } }) } + // As mcp-server.mjs does: list the tools, and keep a watch open that + // lists them again on each tools_changed the bridge pushes. + listAndWatch() { + this.list() + if (this.watchSocket || this.kit.watchTools === false) return + const socket = new FakeSocket() + socket.write = (data) => { + socket.written += data + if (String(data).includes("tools_changed") && !this.child.closed) setImmediate(() => this.list()) + return true + } + this.watchSocket = socket + this.kit.controlHandler(socket) + socket.emit("data", JSON.stringify({ token: this.token, kind: "watch" }) + "\n") + } + + // kit.listings records, per agy, the tool names each tools/list returned. + list() { + return this.control({ kind: "list" }).then((reply) => { + this.kit.listings.push({ spawn: this.spawnIndex, tools: (reply?.result?.tools || []).map((tool) => tool.name) }) + return reply + }) + } + control(message) { const socket = new FakeSocket() this.kit.controlHandler(socket) @@ -455,6 +484,9 @@ export async function createBridgeKit(options = {}) { initializeDelayMs: options.initializeDelayMs ?? 0, initialized: 0, sessionResume: options.sessionResume ?? false, + listTools: options.listTools ?? true, + watchTools: options.watchTools ?? true, + listings: [], agentVersion: options.agentVersion ?? "1.5.0", setModels: [], acpLog: [], diff --git a/packages/agy-cli/test/tools-listed.mjs b/packages/agy-cli/test/tools-listed.mjs new file mode 100644 index 0000000..38d018c --- /dev/null +++ b/packages/agy-cli/test/tools-listed.mjs @@ -0,0 +1,128 @@ +// plugins#1239: pi declared read, bash, edit and write, and the model saw +// only agy's own manage_task. agy reads a client's tools from the bridge's +// ide-tools MCP server, which it starts by running `nc`; when that never +// runs (agy 1.5 doesn't run the nc.cmd a failed nc.exe build leaves on +// Windows) or never answers, agy lists nothing and the turn went ahead +// without a single client tool. Now such a session fails and says why, a +// live agy that never listed the tools a request declares is replaced, and +// on Windows a failed nc.exe build is tried again. +// +// bun test ./tools-listed.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 FAST_WAIT = { AGY_BRIDGE_TOOL_LIST_WAIT_MS: "200" } +// The platform-neutral cases run as Linux on every OS; Windows has its own below. +const LINUX = { platform: "linux" } + +async function withKit(options, fn) { + const kit = await createBridgeKit({ ...options, env: { ...FAST_WAIT, ...(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 prompts = (kit) => kit.acpLog.filter((entry) => entry.method === "session/prompt") + +// pi's own tool names (the reporter's request), Anthropic shape +const PI_TOOLS = ["read", "bash", "edit", "write"].map((name) => ({ + name, + description: `pi's ${name}`, + input_schema: { type: "object", properties: { path: { type: "string" } }, required: ["path"] }, +})) + +test("a session whose agy never lists the request's tools fails and says why, with no turn run", async () => { + await withKit({ ...LINUX, listTools: false }, async (kit) => { + const response = await kit.request(baseBody({ tools: PI_TOOLS })) + const text = await response.text() + assert.equal(response.status, 502, text) + const error = JSON.parse(text).error + assert.match(error.message, /agy never loaded the request's 4 tools/) + assert.match(error.message, /`nc`/) + assert.equal(prompts(kit).length, 0, "a turn ran with none of the client's tools") + }) +}) + +test("a request with no tools still runs when agy lists none", async () => { + await withKit({ ...LINUX, listTools: false }, async (kit) => { + const parsed = await readSse(await kit.request(baseBody({ tools: [] }))) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) + assert.equal(parsed.stopReason, "end_turn") + }) +}) + +test("a live agy that never listed the tools a follow-up declares is replaced by one that does", async () => { + // agy started for a request with no tools; its MCP server keeps no watch, + // so a catalog the bridge swaps in is never listed again + await withKit({ ...LINUX, watchTools: false }, async (kit) => { + const first = baseBody({ tools: [], messages: [{ role: "user", content: "one" }] }) + assert.equal((await readSse(await kit.request(first))).stopReason, "end_turn") + const follow = baseBody({ + tools: [READ_TOOL], + messages: [{ role: "user", content: "one" }, { role: "assistant", content: "ok" }, { role: "user", content: "two" }], + }) + const parsed = await readSse(await kit.request(follow)) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) + const last = prompts(kit).at(-1) + assert.ok(kit.listings.some((listing) => listing.spawn === last.spawn && listing.tools.includes("Read")), + `the agy that ran the follow-up never listed Read: ${JSON.stringify(kit.listings)}`) + }) +}) + +test("a live agy that lists the swapped catalog keeps the conversation", async () => { + await withKit(LINUX, async (kit) => { + const first = baseBody({ tools: [], messages: [{ role: "user", content: "one" }] }) + assert.equal((await readSse(await kit.request(first))).stopReason, "end_turn") + const follow = baseBody({ + tools: [READ_TOOL], + messages: [{ role: "user", content: "one" }, { role: "assistant", content: "ok" }, { role: "user", content: "two" }], + }) + assert.equal((await readSse(await kit.request(follow))).stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, 1) + assert.ok(kit.listings.some((listing) => listing.tools.includes("Read"))) + }) +}) + +// Windows: agy 1.5 runs nc.exe from PATH and never nc.cmd. +const BUN = "C:\\Users\\Test\\magpie\\magpie-bun.exe" +const ncExeFirst = (env) => fs.existsSync(path.join(String(env.PATH).split(path.delimiter)[0], "nc.exe")) + +test("Windows: a failed nc.exe build is named in the error and tried again later", async () => { + let builds = 0 + const onSpawn = (file, args) => { + if (args[0] !== "build") return 0 + builds++ + if (builds === 1) return 1 + fs.writeFileSync(args[args.indexOf("--outfile") + 1], "MZ fake nc.exe") + return 0 + } + await withKit({ platform: "win32", execPath: BUN, versions: { ...process.versions, bun: "1.4.2" }, onSpawn, listTools: ncExeFirst }, async (kit) => { + const response = await kit.request(baseBody({ tools: PI_TOOLS, system: "first" })) + const text = await response.text() + assert.equal(response.status, 502, text) + const message = JSON.parse(text).error.message + assert.match(message, /nc\.exe, the program agy runs to reach them, could not be built \(bun build exited with 1/) + assert.match(message, /nc\.cmd/) + assert.equal(prompts(kit).length, 0) + + // Not again at once: a build that fails costs up to two minutes. + await kit.request(baseBody({ tools: PI_TOOLS, system: "second" })).then((r) => r.text()) + assert.equal(builds, 1) + + kit.clock.advance(5 * 60 * 1000) + const parsed = await readSse(await kit.request(baseBody({ tools: PI_TOOLS, system: "third" }))) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) + assert.equal(builds, 2) + assert.ok(kit.listings.some((listing) => listing.tools.includes("read"))) + }) +})