From 80d3a00ee3794bd721709e5e7babfc7771509f85 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 12 Nov 2026 17:38:20 +0800 Subject: [PATCH] agy-cli 0.1.24: no console window or leftover conhost on Windows (#1047) agy dials --ide-mcp-port by running `nc` from PATH, and on Windows the bridge's nc was nc.cmd: cmd.exe running mcp-server.mjs, two console programs. When agy starts a console program with a console of its own (CREATE_NEW_CONSOLE, or CREATE_NO_WINDOW), each dial gets a window or a conhost.exe. Each session also made its own bin dir, and a host that exited left its parked agy's cmd/bun children and its workspace dirs behind. - Under Bun (magpie's runtime), nc is now a GUI-subsystem nc.exe that Bun builds from mcp-server.mjs on the user's own machine (`bun build --compile --windows-hide-console`, ~0.3s on the test box). A GUI exe gets no console under any creation flags, and it still talks over the stdio pipes agy hands it. Nothing prebuilt ships. It lives in %TEMP%\magpie-agy-bridge-nc-, so every session and every later host reuses one build. A dir no host has used for a week, or a half-done build dir older than an hour, is swept. If the build fails, or the runtime isn't Bun (e.g. opencode.exe), nc.cmd is used as before. - At exit on Windows one `taskkill /T /F` ends every live agy with its tree (cmd, nc). The workspace rm retries while the just-killed processes let go of their cwd. Only a shim dir this host made is removed; the shared nc.exe dir stays. Run on Windows 11 (build 26200, xiaomi-gpu), Bun 1.4.2. A fake agy (Go) answers ACP and dials `nc 127.0.0.1 ` 3 times per session, with CreationFlags none, CREATE_NO_WINDOW or CREATE_NEW_CONSOLE. 4 sessions per run, all 12 dials answered in every run below. conhost counts are those under the host after 4 sessions, while agy is parked: old, none: 5 conhost; agy 4, cmd 4, bun 4; 4 workspace dirs leaked old, nowindow: 9 conhost (+2 per session); same leak old, newconsole: 9 conhost (+2 per session); same leak new, none / nowindow / newconsole: 5 conhost (the parked agy's own); agy 4, nc.exe 4, no cmd, no bun; one magpie-agy-bridge-nc- dir, nothing else left in TEMP after exit new, idle eviction (3s): back to 1 conhost, no agy/nc left new, host hard-killed: no agy/nc left; the 4 workspace dirs stay (no code runs after a hard kill; the same on old, which also leaks its bin dir) old, DETACHED_PROCESS: the dial never answers (agy start times out), so that isn't what the reported agy does. The system-wide conhost count was 1 before and after every run. Tests: test/windows-nc.mjs (6 tests, on any OS through the kit's platform, execPath and versions overrides): the build command, the shared dir built once and reused by a later host, no nc.cmd, the nc.cmd fallback, the one-run tree kill at exit and which dirs it removes. Run at this tree on mica (Bun 1.4.2, temp HOME): bun test packages/agy-cli 15 pass 0 fail; bun scripts/check.mjs exit 0. On the Windows box: 14 pass, 1 fail. The red is smoke.mjs's "no call to the loaded tool reaches agy's validator in the old prompt". It fails the same way at origin/main 8768126 on the same box, and is filed as #973. Broken by hand, each red in windows-nc.mjs: never using nc.exe (2 red), a build without --windows-hide-console (2), a rebuild per host (1), SIGKILL per child instead of the taskkill tree (1), removing the shared dir at exit (1). Not tried: a real agy on Windows (it isn't installed on the box, and was not downloaded); whether a window is visible (ssh runs in session 0, where none is, so conhosts were counted instead); the reporter's build 26300. A host killed hard can still leave an agy that ignores stdin EOF: only a job object around the plugin host (magpie's internal/plugin/host.go starts it with a plain cmd.Start) would end it. Reported-by: Tericerice --- packages/agy-cli/agy-cli.test.mjs | 1 + packages/agy-cli/index.mjs | 118 ++++++++++++++++++++-- packages/agy-cli/package.json | 2 +- packages/agy-cli/platform.mjs | 21 ++++ packages/agy-cli/test/testkit.mjs | 18 +++- packages/agy-cli/test/windows-nc.mjs | 145 +++++++++++++++++++++++++++ 6 files changed, 292 insertions(+), 13 deletions(-) create mode 100644 packages/agy-cli/test/windows-nc.mjs diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index 5628b28..d0ff25c 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -24,6 +24,7 @@ for (const [name, mocks] of [ ["usage-settlement.mjs", false], ["repeat-batch.mjs", false], ["conversation-key.mjs", false], + ["windows-nc.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 3fbfcae..cc56d25 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -1,5 +1,5 @@ -import { agyCandidates, spawnAgy, windowsMcpShim } from "./platform.mjs" -import { spawn } from "node:child_process" +import { agyCandidates, spawnAgy, windowsMcpShim, windowsNcBuild, windowsTreeKill } from "./platform.mjs" +import { spawn, spawnSync } from "node:child_process" import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto" import { once } from "node:events" import fs from "node:fs" @@ -127,6 +127,8 @@ let cachedAgySearchKey let controlServer let controlServerPromise 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 function positiveTimeout(value, fallback) { @@ -667,9 +669,21 @@ function shellQuote(value) { // agy connects to --ide-mcp-port by running `nc host port`. A private `nc` // 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. -function ensureShimDir() { +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 + } if (shimDirPromise) return shimDirPromise shimDirPromise = (async () => { + if (process.platform === "win32") { + const shared = await windowsNcDir().catch(() => null) + if (shared) { + shimDir = shared + return shared + } + } 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"), @@ -679,12 +693,80 @@ function ensureShimDir() { `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(MCP_SERVER_PATH)}\n`, { mode: 0o700 }) } shimDir = dir + shimDirOwned = true return dir })() shimDirPromise.catch(() => { shimDirPromise = null }) return shimDirPromise } +// 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 +// week is swept. null when the runtime can't build it. +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 + +async function isFileWithBytes(file) { + try { + const stat = await fs.promises.stat(file) + return stat.isFile() && stat.size > 0 + } catch { + return false + } +} + +async function windowsNcDir() { + if (!windowsNcBuild(process.execPath, MCP_SERVER_PATH, "nc.exe")) return null + const tmp = os.tmpdir() + const source = await fs.promises.readFile(MCP_SERVER_PATH) + const key = createHash("sha256").update(String(process.execPath)).update("\0") + .update(String(process.versions?.bun || "")).update("\0").update(source).digest("hex").slice(0, 16) + const dir = path.join(tmp, WINDOWS_NC_PREFIX + key) + const exe = path.join(dir, "nc.exe") + if (await isFileWithBytes(exe)) { + const now = new Date() + await fs.promises.utimes(exe, now, now).catch(() => {}) + return dir + } + const build = await fs.promises.mkdtemp(path.join(tmp, WINDOWS_NC_BUILD_PREFIX)) + try { + const spec = windowsNcBuild(process.execPath, 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 + await fs.promises.mkdir(dir, { recursive: true }) + try { + await fs.promises.rename(path.join(build, "nc.exe"), exe) + } catch (error) { + // Another host built it at the same time; theirs is as good. + if (!await isFileWithBytes(exe)) throw error + } + } finally { + fs.promises.rm(build, { recursive: true, force: true }).catch(() => {}) + } + sweepWindowsNcDirs(tmp, path.basename(dir)).catch(() => {}) + return dir +} + +// A build no host has started for a week (an older runtime or server), or a +// build dir a killed host left half done. An nc.exe still running is locked, +// so its dir stays until a later sweep. +async function sweepWindowsNcDirs(tmp, keep) { + const now = Date.now() + for (const name of await fs.promises.readdir(tmp)) { + const shared = name.startsWith(WINDOWS_NC_PREFIX) && /^[0-9a-f]{16}$/.test(name.slice(WINDOWS_NC_PREFIX.length)) + const build = name.startsWith(WINDOWS_NC_BUILD_PREFIX) + if (name === keep || (!shared && !build)) continue + const file = path.join(tmp, name) + try { + const stat = await fs.promises.stat(shared ? path.join(file, "nc.exe") : file).catch(() => fs.promises.stat(file)) + if (now - stat.mtimeMs < (shared ? 7 * 24 : 1) * 60 * 60 * 1000) continue + await fs.promises.rm(file, { recursive: true, force: true }) + } catch {} + } +} + function agentDefinition() { const lines = [ "---", @@ -5221,17 +5303,35 @@ function jsonError(status, message, code, { extra, headers, noRetry = false } = ) } -process.once("exit", () => { +// On Windows child.kill() ends agy alone and leaves the cmd.exe and nc it +// started, so one taskkill /T ends every tree before the workspaces go. +function reapOnExit() { + const windows = process.platform === "win32" + const pids = [] for (const proc of allProcs) { - try { proc.child?.kill("SIGKILL") } catch {} - if (proc.workspace) { - try { fs.rmSync(proc.workspace, { recursive: true, force: true }) } catch {} + const child = proc.child + if (!child || child.exitCode !== null || child.signalCode !== null) continue + if (windows && child.pid) pids.push(child.pid) + else { + try { child.kill("SIGKILL") } catch {} } } - if (shimDir) { + const kill = windows ? windowsTreeKill(pids) : null + if (kill) { + try { spawnSync(kill.file, kill.args, { stdio: "ignore", windowsHide: true, timeout: 10_000 }) } catch {} + } + for (const proc of allProcs) { + // A process that just ended can hold its cwd (the workspace) for a moment. + if (proc.workspace) { + try { fs.rmSync(proc.workspace, { recursive: true, force: true, maxRetries: windows ? 10 : 0, retryDelay: 50 }) } catch {} + } + } + if (shimDir && shimDirOwned) { try { fs.rmSync(shimDir, { recursive: true, force: true }) } catch {} } -}) +} + +process.once("exit", reapOnExit) export { sanitizeInputSchema } export default { id: PROVIDER_ID, server: AntigravityBridgePlugin } diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 696aa55..1d60422 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.23", + "version": "0.1.24", "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/platform.mjs b/packages/agy-cli/platform.mjs index b5f74cf..636290f 100644 --- a/packages/agy-cli/platform.mjs +++ b/packages/agy-cli/platform.mjs @@ -102,3 +102,24 @@ export function windowsMcpShim(executable, server) { } return `@echo off\r\nsetlocal DisableDelayedExpansion\r\n${quote(executable)} ${quote(server)}\r\n` } + +// agy dials --ide-mcp-port by running `nc` from PATH. On Windows a console +// program started that way can be handed a console of its own, and nc.cmd +// always runs in cmd.exe, a console program: each dial then flashes a window +// and leaves a conhost.exe behind (#1047). A GUI-subsystem nc.exe never gets +// a console, whatever creation flags agy uses, and still talks over the +// stdio pipes agy hands it. Bun builds it from mcp-server.mjs on the user's +// own machine; nothing prebuilt ships. Another runtime gets null, and the +// caller falls back to nc.cmd. +export function windowsNcBuild(runtime, server, outfile, versions = process.versions) { + if (!versions?.bun || !/^bun(?:\.exe)?$/i.test(path.win32.basename(String(runtime || "")))) return null + return { file: runtime, args: ["build", "--compile", "--windows-hide-console", server, "--outfile", outfile] } +} + +// One taskkill run that ends each agy and everything it started (cmd.exe, +// nc); null when there is nothing to end. +export function windowsTreeKill(pids) { + const live = [...new Set(pids)].filter(pid => Number.isInteger(pid) && pid > 0) + if (!live.length) return null + return { file: "taskkill", args: ["/T", "/F", ...live.flatMap(pid => ["/PID", String(pid)])] } +} diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index 43fc62d..67df4d3 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -45,7 +45,7 @@ const RUNTIME_NAMES = ["Date", "setTimeout", "clearTimeout", "setInterval", "cle const RUNTIME_PRELUDE = `import { ${RUNTIME_NAMES.join(", ")} } from ${JSON.stringify(RUNTIME_SPECIFIER)};\n` const TEST_EXPORTS = "\nexport { Turn as __agyTestTurn, allProcs as __agyTestAllProcs, pool as __agyTestPool, " + "execOnce as __agyTestExecOnce, findAgy as __agyTestFindAgy, canonicalBody as __agyTestCanonicalBody, " + - "conversationKey as __agyTestConversationKey, renderInitialPromptParts as __agyTestRenderInitialPromptParts };\n" + "conversationKey as __agyTestConversationKey, renderInitialPromptParts as __agyTestRenderInitialPromptParts, reapOnExit as __agyTestReapOnExit };\n" const IDENTIFIER_RE = /^[A-Za-z_$][\w$]*$/ if (typeof vm.SourceTextModule !== "function" || typeof vm.SyntheticModule !== "function") { @@ -410,6 +410,8 @@ export async function createBridgeKit(options = {}) { children: new Set(), modelsSpawns: [], acpSpawns: [], + otherSpawns: [], + spawnSyncs: [], modelsBehavior: options.modelsBehavior ?? { stdout: modelsOutput(BASE_MODEL_ROWS) }, prompts: [], promptSerial: 0, @@ -444,6 +446,10 @@ export async function createBridgeKit(options = {}) { const fakeProcess = new Proxy(process, { get(target, property) { if (property === "env") return kit.env + // Windows paths (nc.exe, taskkill) run on any test machine. + if (property === "platform" && options.platform) return options.platform + if (property === "execPath" && options.execPath) return options.execPath + if (property === "versions" && options.versions) return options.versions const value = Reflect.get(target, property, target) return typeof value === "function" ? value.bind(target) : value }, @@ -456,10 +462,16 @@ export async function createBridgeKit(options = {}) { new FakeAgy(kit, child, opts) return child } + kit.otherSpawns.push({ file, args, opts }) const child = new FakeChild(kit, file, args) - child.finish(0) + const code = options.onSpawn ? options.onSpawn(file, args, opts) : 0 + child.finish(code ?? 0) return child } + const spawnSync = (file, args = [], opts = {}) => { + kit.spawnSyncs.push({ file, args, opts }) + return { status: 0, signal: null, stdout: "", stderr: "", pid: 0, output: [] } + } const fakeServer = { once() { return fakeServer }, on() { return fakeServer }, @@ -469,7 +481,7 @@ export async function createBridgeKit(options = {}) { address() { return { address: "127.0.0.1", family: "IPv4", port: 45999 } }, } const overrides = { - "node:child_process": { spawn }, + "node:child_process": { spawn, spawnSync }, "node:net": { createServer(handler) { kit.controlHandler = handler diff --git a/packages/agy-cli/test/windows-nc.mjs b/packages/agy-cli/test/windows-nc.mjs new file mode 100644 index 0000000..2937624 --- /dev/null +++ b/packages/agy-cli/test/windows-nc.mjs @@ -0,0 +1,145 @@ +// #1047: on Windows agy's nc dials run a GUI-subsystem nc.exe that Bun builds +// once and every session and later host reuses, never nc.cmd (cmd.exe, a +// console program that can be handed a window and a conhost per dial). At +// exit every agy is ended with its tree, and its workspace is removed. +import assert from "node:assert/strict" +import fs from "node:fs" +import path from "node:path" +import { test } from "node:test" +import { windowsNcBuild, windowsTreeKill } from "../platform.mjs" +import { baseBody, createBridgeKit, readSse } from "./testkit.mjs" + +function workDir(kit, name) { + const dir = path.join(kit.tmp, name) + fs.mkdirSync(dir, { recursive: true }) + return dir +} + +const BUN = "C:\\Users\\Test\\magpie\\bun.exe" +const body = (text) => baseBody({ model: "agy-cli/gemini-4-argon", tools: [], messages: [{ role: "user", content: text }] }) + +function buildsOf(kit) { + return kit.otherSpawns.filter(({ args }) => args[0] === "build") +} + +// Stands in for `bun build --compile`: writes the --outfile it was asked for. +function writeOutfile(file, args) { + if (args[0] !== "build") return 0 + fs.writeFileSync(args[args.indexOf("--outfile") + 1], "MZ fake nc.exe") + return 0 +} + +async function windowsKit(options = {}) { + const kit = await createBridgeKit({ platform: "win32", execPath: BUN, versions: { ...process.versions, bun: "1.4.2" }, onSpawn: writeOutfile, ...options }) + kit.defaultPrompt = async (agent) => { + await agent.text("ok") + return { stopReason: "end_turn", usage: { inputTokens: 10, outputTokens: 1 } } + } + return kit +} + +async function turn(kit, text, workDir) { + const parsed = await readSse(await kit.request(body(text), workDir ? { headers: { "x-magpie-work-dir": workDir } } : {})) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) + assert.equal(parsed.stopReason, "end_turn") +} + +function agyPathDir(kit, index = -1) { + const env = kit.acpSpawns.at(index).env + return String(env.PATH).split(path.delimiter)[0] +} + +test("windowsNcBuild compiles a hidden-console exe under Bun only", () => { + assert.deepEqual(windowsNcBuild(BUN, "C:\\p\\mcp-server.mjs", "C:\\t\\nc.exe", { bun: "1.4.2" }), { + file: BUN, + args: ["build", "--compile", "--windows-hide-console", "C:\\p\\mcp-server.mjs", "--outfile", "C:\\t\\nc.exe"], + }) + assert.equal(windowsNcBuild("C:\\opencode\\opencode.exe", "s", "o", { bun: "1.4.2" }), null) + assert.equal(windowsNcBuild("C:\\node\\node.exe", "s", "o", { node: "22.0.0" }), null) + assert.equal(windowsNcBuild(BUN, "s", "o", { node: "22.0.0" }), null) +}) + +test("windowsTreeKill ends every agy with its tree in one run", () => { + assert.deepEqual(windowsTreeKill([12, 34, 12, 0, undefined, -1]), { file: "taskkill", args: ["/T", "/F", "/PID", "12", "/PID", "34"] }) + assert.equal(windowsTreeKill([undefined]), null) +}) + +test("Windows sessions dial a shared nc.exe built once, never nc.cmd", async () => { + const kit = await windowsKit() + try { + await turn(kit, "one", workDir(kit, "w1")) + await turn(kit, "two", workDir(kit, "w2")) + assert.equal(kit.acpSpawns.length, 2) + const builds = buildsOf(kit) + assert.equal(builds.length, 1) + assert.equal(builds[0].file, BUN) + assert.ok(builds[0].args.includes("--windows-hide-console")) + const dir = agyPathDir(kit, 0) + assert.match(path.basename(dir), /^magpie-agy-bridge-nc-[0-9a-f]{16}$/) + assert.equal(agyPathDir(kit, 1), dir) + assert.deepEqual(fs.readdirSync(dir), ["nc.exe"]) + assert.ok(!fs.readdirSync(kit.tmp).some((name) => name.startsWith("magpie-agy-bridge-bin-") || name.startsWith("magpie-agy-bridge-ncbuild-"))) + + // A later host with the same runtime and server reuses the exe. + const later = await windowsKit() + try { + fs.cpSync(dir, path.join(later.tmp, path.basename(dir)), { recursive: true }) + await turn(later, "three") + assert.equal(buildsOf(later).length, 0) + assert.equal(path.basename(agyPathDir(later)), path.basename(dir)) + } finally { + await later.dispose() + } + } finally { + await kit.dispose() + } +}) + +test("Windows falls back to nc.cmd when the runtime can't build nc.exe", async () => { + for (const options of [{ execPath: "C:\\opencode\\opencode.exe", versions: { ...process.versions, bun: undefined } }, { onSpawn: () => 1 }]) { + const kit = await windowsKit(options) + try { + await turn(kit, "hi") + const dir = agyPathDir(kit) + assert.match(path.basename(dir), /^magpie-agy-bridge-bin-/) + assert.deepEqual(fs.readdirSync(dir), ["nc.cmd"]) + assert.ok(!fs.readdirSync(kit.tmp).some((name) => name.startsWith("magpie-agy-bridge-nc"))) + } finally { + await kit.dispose() + } + } +}) + +test("at exit on Windows every live agy's tree is ended and the workspaces removed; the shared nc.exe stays", async () => { + const kit = await windowsKit() + try { + await turn(kit, "one", workDir(kit, "w1")) + await turn(kit, "two", workDir(kit, "w2")) + const procs = [...kit.module.__agyTestAllProcs] + assert.equal(procs.length, 2) + procs.forEach((proc, index) => { proc.child.pid = 4100 + index }) + const workspaces = procs.map((proc) => proc.workspace) + const dir = agyPathDir(kit) + kit.module.__agyTestReapOnExit() + const kills = kit.spawnSyncs.filter(({ file }) => file === "taskkill") + assert.equal(kills.length, 1) + assert.deepEqual(kills[0].args, ["/T", "/F", "/PID", "4100", "/PID", "4101"]) + assert.equal(kills[0].opts.windowsHide, true) + for (const workspace of workspaces) assert.ok(!fs.existsSync(workspace), workspace) + assert.ok(fs.existsSync(path.join(dir, "nc.exe"))) + } finally { + await kit.dispose() + } +}) + +test("at exit a shim dir this host made is removed", async () => { + const kit = await windowsKit({ onSpawn: () => 1 }) + try { + await turn(kit, "hi") + const dir = agyPathDir(kit) + kit.module.__agyTestReapOnExit() + assert.ok(!fs.existsSync(dir)) + } finally { + await kit.dispose() + } +})