diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index f154827..4e196b6 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -201,29 +201,62 @@ function findAgy() { } // agy loads the machine's own skills (~/.gemini/skills, ~/.agents/skills, …) -// into an ACP session even when the agent says inheritCustomizations: false. -// They share agy's 20,000-token customization budget with the client's tools, -// and over it agy drops the largest tools (plugins#1166). agy 1.5.9's acp -// takes --include-default-customizations=false to leave them out, but an -// agy without the flag refuses to start on it, so it is passed only when -// `agy acp --help` lists it. The answer is kept per binary (path, mtime, -// size), so an agy update asks again; a probe that failed is asked again. -const customizationFlag = new Map() -export function noDefaultCustomizationsArgs(agyPath) { +// and its global MCP servers into an ACP session even when the agent says +// inheritCustomizations: false. They share agy's 20,000-token customization +// budget with the client's tools, and over it agy drops the largest tools +// (plugins#1166). agy 1.5.9's acp takes --include-default-customizations=false, +// but on Windows it still loaded all 120 of a user's skills; --gemini-dir +// pointed at a folder of the bridge's own leaves them all out (the reporter +// ran it: no skills, every client tool listed). agy's Google sign-in is in +// the system keyring, not in that folder (signin.mjs), so it still applies. +// An agy without these flags refuses to start on them, so each is passed +// only when `agy acp --help` lists it. The answer is kept per binary (path, +// mtime, size), so an agy update asks again; a probe that failed is asked +// again. +const acpHelpText = new Map() +function acpHelp(agyPath) { let key = agyPath try { const st = fs.statSync(agyPath) key += `\0${st.mtimeMs}\0${st.size}` } catch {} - let probe = customizationFlag.get(key) + let probe = acpHelpText.get(key) if (!probe) { probe = execOnce(agyPath, ["acp", "--help"], { timeoutMs: 10_000 }).then(({ err, stdout, stderr, timedOut }) => { - if (err || timedOut) customizationFlag.delete(key) - return /--include-default-customizations\b/.test(stdout + stderr) + if (err || timedOut) acpHelpText.delete(key) + return stdout + stderr }) - customizationFlag.set(key, probe) + acpHelpText.set(key, probe) } - return probe.then((ok) => (ok ? ["--include-default-customizations=false"] : [])) + return probe +} + +export function noDefaultCustomizationsArgs(agyPath) { + return acpHelp(agyPath).then((help) => (/--include-default-customizations\b/.test(help) ? ["--include-default-customizations=false"] : [])) +} + +// The bridge's own agy folder, kept across restarts so agy finds a +// conversation again on session/resume. AGY_BRIDGE_GEMINI_DIR names another; +// "default" (or 0, off, …) leaves agy on its own ~/.gemini, skills and all. +export function bridgeGeminiDir(env = process.env) { + const named = env.AGY_BRIDGE_GEMINI_DIR || "" + if (/^(?:default|0|false|off|no|disabled)$/i.test(named)) return null + if (named) return path.resolve(named) + const base = env.XDG_STATE_HOME || path.join(os.homedir(), ".local", "state") + return path.join(base, "magpie-agy-bridge", "agy-home") +} + +// geminiDirArgs gives agy the bridge's own folder when its acp lists +// --gemini-dir and the folder can be made, else nothing (agy's ~/.gemini). +export async function geminiDirArgs(agyPath, env = process.env) { + const dir = bridgeGeminiDir(env) + if (!dir || !/--gemini[-_]dir\b/.test(await acpHelp(agyPath))) return { args: [], dir: null } + try { + await fs.promises.mkdir(dir, { recursive: true, mode: 0o700 }) + } catch { + return { args: [], dir: null } + } + return { args: ["--gemini-dir", dir], dir } } function execOnce(file, args, opts = {}) { @@ -1666,6 +1699,12 @@ class Proc { ] if (this.workDir) args.push("--add-dir", this.workDir) args.push(...await noDefaultCustomizationsArgs(this.agyPath)) + const own = await geminiDirArgs(this.agyPath) + args.push(...own.args) + // agy writes the conversation's steps under the folder it was given + this.conversationsDir = own.dir && !process.env.AGY_BRIDGE_CONVERSATIONS_DIR + ? path.join(own.dir, "antigravity-cli", "conversations") + : null try { const childEnv = { ...process.env } const inheritedPath = process.env.PATH || childEnv.Path || "" @@ -2067,7 +2106,9 @@ class Proc { if (model) await this.#setModel(model, selection) const stepUsageEnabled = this.stepUsageTrusted && !/^(?:0|false|off|no|disabled)$/i.test(process.env.AGY_BRIDGE_STEP_USAGE || "") - turn.stepsFile = stepUsageEnabled ? sessionDbPath(this.sessionId) : null + turn.stepsFile = stepUsageEnabled + ? sessionDbPath(this.sessionId, this.conversationsDir ? { AGY_BRIDGE_CONVERSATIONS_DIR: this.conversationsDir } : process.env) + : null turn.stepCursor = turn.stepsFile ? modelUsageCursor(turn.stepsFile) : null if (turn.stepsFile && turn.stepCursor === null) this.stepUsageTrusted = false // Content a cancelled turn never delivered still belongs to the session. diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 5f6b885..b7ddfa2 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.53", + "version": "0.1.54", "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/repeat-batch.mjs b/packages/agy-cli/test/repeat-batch.mjs index 08b42a4..1278c03 100644 --- a/packages/agy-cli/test/repeat-batch.mjs +++ b/packages/agy-cli/test/repeat-batch.mjs @@ -1042,6 +1042,36 @@ test("#1166: an agy without the flag is never given it, so it still starts", asy const reply = await readSse(await kit.request(baseBody({ metadata: { user_id: "custom-old" }, messages: [{ role: "user", content: "hello old" }] }))) assert.equal(reply.stopReason, "end_turn") assert.equal(kit.acpSpawns.length, 1) - assert.ok(!kit.acpSpawns[0].args.some((arg) => arg.startsWith("--include-default-customizations")), kit.acpSpawns[0].args.join(" ")) + assert.ok(!kit.acpSpawns[0].args.some((arg) => arg.startsWith("--include-default-customizations") || arg === "--gemini-dir"), kit.acpSpawns[0].args.join(" ")) + }) +}) + +const GEMINI_DIR_HELP = "Usage of acp:\n --gemini-dir\n \tPath where Gemini files are stored (default .gemini)\n --include-default-customizations\n \tInclude default customizations (default true)\n" + +test("#1166: an agy whose acp --help lists --gemini-dir runs in the bridge's own folder, kept across conversations", async () => { + await withKit({ acpHelp: GEMINI_DIR_HELP }, async (kit) => { + scriptedAgent(kit) + for (const user of ["home-a", "home-b"]) { + const reply = await readSse(await kit.request(baseBody({ metadata: { user_id: user }, messages: [{ role: "user", content: "hello " + user }] }))) + assert.equal(reply.stopReason, "end_turn") + } + const own = path.join(kit.env.XDG_STATE_HOME, "magpie-agy-bridge", "agy-home") + assert.equal(kit.acpSpawns.length, 2) + for (const spawn of kit.acpSpawns) { + const at = spawn.args.indexOf("--gemini-dir") + assert.ok(at >= 0 && spawn.args[at + 1] === own, spawn.args.join(" ")) + } + assert.ok(fs.statSync(own).isDirectory(), "the folder is made before agy starts") + assert.equal(kit.helpSpawns.length, 1, "acp --help is asked once for both flags") + }) +}) + +test("#1166: AGY_BRIDGE_GEMINI_DIR=default leaves agy on the machine's own folder", async () => { + await withKit({ acpHelp: GEMINI_DIR_HELP, env: { AGY_BRIDGE_GEMINI_DIR: "default" } }, async (kit) => { + scriptedAgent(kit) + const reply = await readSse(await kit.request(baseBody({ metadata: { user_id: "home-default" }, messages: [{ role: "user", content: "hello" }] }))) + assert.equal(reply.stopReason, "end_turn") + assert.ok(!kit.acpSpawns[0].args.includes("--gemini-dir"), kit.acpSpawns[0].args.join(" ")) + assert.ok(kit.acpSpawns[0].args.includes("--include-default-customizations=false")) }) }) diff --git a/packages/agy-cli/test/usage-settlement.mjs b/packages/agy-cli/test/usage-settlement.mjs index 3373878..1189918 100644 --- a/packages/agy-cli/test/usage-settlement.mjs +++ b/packages/agy-cli/test/usage-settlement.mjs @@ -2267,3 +2267,44 @@ test("同会话工具中途 steer:等待 tool_call_update 提交后再发 sess assert.equal(proc.stepUsageTrusted, false, "已进入生成输出的取消回合必须关闭 stepUsageTrusted") }) }) + +test("#1166: an agy given the bridge's own --gemini-dir has its steps read from there", { skip: !openSqlite }, async () => { + const varint = (n) => { const out = []; while (n > 127) { out.push((n & 127) | 128); n = Math.floor(n / 128) } out.push(n); return out } + const field = (n, bytes) => [n * 8 + 2, ...varint(bytes.length), ...bytes] + const genBlob = ({ input, output, read = 0 }) => new Uint8Array(field(1, field(4, [ + 0x10, ...varint(input), 0x18, ...varint(output), ...(read ? [0x28, ...varint(read)] : []), + ]))) + + await withKit({ acpHelp: " --gemini-dir\n \tPath where Gemini files are stored (default .gemini)\n" }, async (kit) => { + const own = path.join(kit.env.XDG_STATE_HOME, "magpie-agy-bridge", "agy-home") + const convDir = path.join(own, "antigravity-cli", "conversations") + // the machine's own folder holds a different count, which must not be read + const machineDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") + fs.mkdirSync(convDir, { recursive: true }) + fs.mkdirSync(machineDir, { recursive: true }) + kit.prompts.push(async (agent) => { + for (const dir of [convDir, machineDir]) { + const db = openSqlite(path.join(dir, `${agent.sessionId}.db`)) + try { + db.run("CREATE TABLE IF NOT EXISTS gen_metadata (idx INTEGER PRIMARY KEY, data BLOB)") + } finally { + db.close() + } + } + for (const [dir, input] of [[convDir, 1800], [machineDir, 9999]]) { + const db = openSqlite(path.join(dir, `${agent.sessionId}.db`)) + try { + db.run("INSERT INTO gen_metadata VALUES (1, ?)", genBlob({ input, read: 18_200, output: 32 })) + } finally { + db.close() + } + } + await agent.tool("Read", { path: "/step1.ts" }) + await agent.text("done reading") + return { stopReason: "end_turn", usage: { inputTokens: 3900, cachedReadTokens: 38_100, cachedWriteTokens: 0, outputTokens: 82, totalTokens: 3900 + 38_100 + 82 } } + }) + const { responses } = await runTurn(kit, baseBody()) + assert.ok(kit.acpSpawns[0].args.join(" ").includes(`--gemini-dir ${own}`), kit.acpSpawns[0].args.join(" ")) + assert.equal(responses[0].usage.input_tokens, 1800, JSON.stringify(responses[0].usage)) + }) +})