diff --git a/packages/agy-cli/README.en.md b/packages/agy-cli/README.en.md index b648361..bd656d0 100644 --- a/packages/agy-cli/README.en.md +++ b/packages/agy-cli/README.en.md @@ -92,8 +92,10 @@ MCP server. The control port listens on loopback only, with a token per process. arrives, the same turn continues, and the client executes each call exactly once. - **Session resume**: each finished turn is recorded. After a Magpie or plugin restart, the session continues through `session/resume` as long as the history - and instruction hashes still match. The state file stores session IDs and - hashes, never message text. + and instruction hashes still match. agy's prompt cache follows the folder it + runs in, so a resumed session runs in its own temporary folder again and its + cache still hits. The state file stores session IDs, hashes and that folder, + never message text. - **Isolation**: your global MCP configuration is never read. Every agy process runs with a temporary agent, and every permission request agy raises for its own tools (shell, file edits, browser) is refused. A request for one of the diff --git a/packages/agy-cli/README.md b/packages/agy-cli/README.md index 43aa468..d3bf995 100644 --- a/packages/agy-cli/README.md +++ b/packages/agy-cli/README.md @@ -63,7 +63,8 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy - **工具调用**:支持并行和连续调用。运行超过 150 秒的工具会先收到 "still running" 的 占位响应,真正的结果送达后继续同一轮对话,每个调用只在客户端执行一次。 - **会话续接**:每轮结束后记录会话。重启 Magpie 或插件后,只要历史和指令的哈希一致, - 就用 `session/resume` 接上上下文。状态文件只存会话 ID 与哈希,不存消息原文。 + 就用 `session/resume` 接上上下文。agy 的提示缓存跟着它运行的目录走,所以接上的会话 + 回到原来的临时目录里运行,缓存照样命中。状态文件只存会话 ID、哈希和这个目录,不存消息原文。 - **隔离运行**:不读取你的全局 MCP 配置。每个 agy 进程使用临时 agent。agy 为它自己的 工具发起的权限请求(shell、写文件、浏览器等)一律拒绝;客户端工具经桥接的 `ide-tools` 调用时发起的请求放行一次,这些工具在客户端里运行,受客户端自己的权限管。真正的操作 diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index 06537c4..8021063 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -2071,7 +2071,7 @@ class Proc { this.resumed = false this.child = null this.conn = null - this.workspace = null + this.workspace = this.resumeFrom?.workspace || null this.logPath = null this.lastUsed = Date.now() this.dead = false @@ -2136,7 +2136,15 @@ class Proc { await ensureControlServer() const bin = await ensureShimDir() sessions.set(this.token, this) - this.workspace = await fs.promises.mkdtemp(path.join(os.tmpdir(), "magpie-agy-bridge-")) + if (this.workspace) { + // agy's prompt cache follows the folder it runs in: a session resumed + // anywhere else replays its whole history uncached. It + // starts again in its own folder, made again if it was removed. + await workspaceRemovals.get(this.workspace)?.catch(() => {}) + await fs.promises.mkdir(this.workspace, { recursive: true, mode: 0o700 }) + } else { + this.workspace = await fs.promises.mkdtemp(path.join(os.tmpdir(), "magpie-agy-bridge-")) + } const agentDir = path.join(this.workspace, ".agents", "agents", AGENT_NAME) await fs.promises.mkdir(agentDir, { recursive: true }) await fs.promises.writeFile(path.join(agentDir, "agent.md"), agentDefinition(), { mode: 0o600 }) @@ -3045,19 +3053,28 @@ class Proc { } } this.child = null - if (this.workspace) { - for (let attempt = 0; attempt < 4; attempt++) { - try { - await fs.promises.rm(this.workspace, { recursive: true, force: true }) - break - } catch (error) { - if (attempt === 3 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) break - await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))) - } - } + // A resumed session's agy starts again in this folder; never remove it + // from under one that already has. + if (this.workspace && ![...allProcs].some((proc) => proc !== this && proc.workspace === this.workspace)) { + const removal = this.#removeWorkspace() + workspaceRemovals.set(this.workspace, removal) + await removal + if (workspaceRemovals.get(this.workspace) === removal) workspaceRemovals.delete(this.workspace) } allProcs.delete(this) } + + async #removeWorkspace() { + for (let attempt = 0; attempt < 4; attempt++) { + try { + await fs.promises.rm(this.workspace, { recursive: true, force: true }) + break + } catch (error) { + if (attempt === 3 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) break + await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1))) + } + } + } } function stillRunningText(call) { @@ -3351,12 +3368,22 @@ function park(proc) { userCloak: USER_CLOAK, instructionsInSession: !!proc.instructionsInSession, workDir: proc.workDir, + workspace: proc.workspace, at: Date.now(), }) while (parked.size > MAX_PARKED) parked.delete(parked.keys().next().value) saveParked() } +// Only a folder this bridge makes: the state file is never a way to run agy +// somewhere else. +function resumeWorkspace(workspace) { + if (typeof workspace !== "string" || !path.isAbsolute(workspace)) return null + const resolved = path.resolve(workspace) + if (path.dirname(resolved) !== path.resolve(os.tmpdir())) return null + return /^magpie-agy-bridge-[A-Za-z0-9]{6}$/.test(path.basename(resolved)) ? resolved : null +} + function takeParked(convKey, opts) { loadParked() const entry = parked.get(convKey) @@ -3368,7 +3395,8 @@ function takeParked(convKey, opts) { entry.instructionsHash !== digest(sentInstructionsIdentity(opts.instructions)) || entry.userCloak !== USER_CLOAK || entry.instructionsInSession !== (systemAppend() && !!opts.instructions)) return null const incoming = digest(historyKey(opts.history)) - if (entry.historyHash === incoming) return { sessionId: entry.sessionId, expectedMessages: opts.history } + const workspace = resumeWorkspace(entry.workspace) + if (entry.historyHash === incoming) return { sessionId: entry.sessionId, expectedMessages: opts.history, workspace } // Sans-inputs resume needs the hashes written by current park(). Old // entries without them still resume on an exact historyHash match only. const incomingSans = digest(historyKey(stripToolUseInputs(opts.history))) @@ -3376,7 +3404,7 @@ function takeParked(convKey, opts) { const idsOk = incomingIds != null && entry.toolUseIdentitiesHash === digest(incomingIds) const sansOk = entry.historyHashSansInputs === incomingSans || entry.historyHash === incomingSans if (!idsOk || !sansOk) return null - return { sessionId: entry.sessionId, expectedMessages: opts.history } + return { sessionId: entry.sessionId, expectedMessages: opts.history, workspace } } async function retire(key, proc) { @@ -3455,6 +3483,8 @@ setInterval(() => { evictIdle().catch(() => {}) }, 60_000).unref() // AGY_BRIDGE_SPARE=0 turns them off. const spares = new Map() const SPARE_MAX = 2 +// A stopped agy's folder being removed, by path, so one resumed into it waits. +const workspaceRemovals = new Map() function sparesOn() { return !/^(?:0|false|off|no|disabled)$/i.test(process.env.AGY_BRIDGE_SPARE || "") @@ -3667,7 +3697,9 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo dropFromPool(existing) await existing.stop().catch(() => {}) } - const spare = await takeSpare(agyPath, opts.workDir) + const resume = forceNew || isFreshConversation ? null : takeParked(convKey, opts) + // a spare runs in a folder of its own, and a resumed session needs its own + const spare = resume?.workspace ? null : await takeSpare(agyPath, opts.workDir) while (!spare && allProcs.size >= maxProcs()) { const idle = spares.values().next().value if (idle) { @@ -3678,7 +3710,6 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo throw new BusyError(`agy bridge: ${maxProcs()} agy processes are running and all have unfinished responses`) } } - const resume = forceNew || isFreshConversation ? null : takeParked(convKey, opts) const proc = spare ?? new Proc(agyPath, key, { ...opts, resume }) try { if (spare) await spare.adopt(key, { ...opts, resume }) diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index d2f146a..12caf80 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.95", + "version": "0.1.96", "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 4f4984b..8971a67 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -555,7 +555,7 @@ export async function createBridgeKit(options = {}) { } if (args[0] === "acp") { const child = new FakeChild(kit, file, args) - kit.acpSpawns.push({ file, args, env: opts.env, child }) + kit.acpSpawns.push({ file, args, env: opts.env, cwd: opts.cwd, child }) new FakeAgy(kit, child, opts) return child } diff --git a/packages/agy-cli/test/usage-settlement.mjs b/packages/agy-cli/test/usage-settlement.mjs index 1189918..59cd908 100644 --- a/packages/agy-cli/test/usage-settlement.mjs +++ b/packages/agy-cli/test/usage-settlement.mjs @@ -950,6 +950,42 @@ test("LRU 淘汰后,补默认字段的 follow-up 仍能 resume 原 session", a }) }) +test("LRU 淘汰后 resume 的 agy 跑在原 session 的目录里(agy 的缓存跟着目录走)", async () => { + await withKit({ env: { AGY_BRIDGE_MAX_PROCS: "1" }, sessionResume: true }, async (kit) => { + for (const text of ["a1", "b1", "a2", "b2", "a3"]) { + kit.prompts.push(async (agent) => { + await agent.text(text) + return { stopReason: "end_turn", usage: { inputTokens: 100, outputTokens: 1 } } + }) + } + const bodyA = baseBody({ messages: [{ role: "user", content: "conversation A" }] }) + const bodyB = baseBody({ messages: [{ role: "user", content: "conversation B" }] }) + const follow = (body, prior, reply, next) => ({ + ...body, + messages: [...prior, { role: "assistant", content: [{ type: "text", text: reply }] }, { role: "user", content: next }], + }) + await runTurn(kit, bodyA) + await runTurn(kit, bodyB) + const a2 = follow(bodyA, bodyA.messages, "a1", "more A") + await runTurn(kit, a2) + await runTurn(kit, follow(bodyB, bodyB.messages, "b1", "more B")) + await runTurn(kit, follow(bodyA, a2.messages, "a2", "and more A")) + assert.equal(kit.acpSpawns.length, 5, "每次换会话都应挤掉另一个 agy") + const resumes = kit.acpLog.filter((item) => item.method === "session/resume") + assert.equal(resumes.length, 3, "A、B、A 都应 resume,而不是新开 session") + const [a, b, aAgain, bAgain, aThird] = kit.acpSpawns.map((spawn) => spawn.cwd) + assert.ok(a && b && a !== b, "两个会话应各有自己的目录") + assert.equal(aAgain, a, "resume 的 agy 换了目录,agy 会整段不走缓存") + assert.equal(bAgain, b) + assert.equal(aThird, a) + for (const item of resumes) { + const spawn = kit.acpSpawns[item.spawn] + assert.equal(item.params.cwd, spawn?.cwd ?? item.params.cwd) + } + assert.ok(fs.existsSync(path.join(a, ".agents", "agents")), "目录被删后应重新建好") + }) +}) + test("取消 prompt 把缓存比例校准为 0 后,下一回合工具步也不再把前缀估成读缓存", async () => { await withKit({}, async (kit) => { const cancelled = { inputTokens: 5000, cachedReadTokens: 0, outputTokens: 3 }