agy-cli 0.1.96: a resumed session runs in its own folder again, so agy's cache still hits
@chet030714 on X: Hermes through agy-cli started near 70% cache hits and
fell all day. agy's prompt cache follows the folder its process runs in.
Every agy the bridge started had a new mkdtemp folder, so a session
resumed after the 10-minute idle reclaim, an LRU eviction or a restart
replayed its whole history uncached, and the longer a conversation got,
the more each resume cost.
Measured with real agy 1.5.10 over ACP in a sandbox HOME (one session,
~24K tokens a turn): every turn in one process hit (cachedReadTokens
19,682 to 197,710). A resume in the same folder: 213,520 cached. In
another folder: 0 cached, 219,198 uncached. Only the process's folder
counts, not session/resume's cwd. The same folder after 13 minutes
idle, or removed and made again at the same path, still hits.
Now a parked session records its workspace, and a resume starts agy in
that folder (made again if it was removed), never in a spare's. Only a
magpie-agy-bridge-XXXXXX folder directly in the temp folder is taken
from the state file. A stopped agy leaves its folder when another
already runs there, and a resume waits for a removal in progress.
Run (at 63c2ff93 + this diff):
- mica, HOME=$(mktemp -d): packages/agy-cli `bun test`: 41 pass, 0 fail.
- The new test (usage-settlement.mjs, LRU resume runs in the session's
folder) on the old index.mjs, by hand: fails.
- The real bridge, index.mjs loaded with real agy in a sandbox HOME, two
turns with the process reclaimed between them (AGY_BRIDGE_IDLE_MS=5000):
old code, resumed turn 0 of 32,127 cached; this change, 29,681 of
32,018 cached.
Not tried: Windows and Linux with real agy. A resume from a park entry
written before this version still starts in a new folder, once.
This commit is contained in:
@@ -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.
|
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
|
- **Session resume**: each finished turn is recorded. After a Magpie or plugin
|
||||||
restart, the session continues through `session/resume` as long as the history
|
restart, the session continues through `session/resume` as long as the history
|
||||||
and instruction hashes still match. The state file stores session IDs and
|
and instruction hashes still match. agy's prompt cache follows the folder it
|
||||||
hashes, never message text.
|
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
|
- **Isolation**: your global MCP configuration is never read. Every agy process
|
||||||
runs with a temporary agent, and every permission request agy raises for its
|
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
|
own tools (shell, file edits, browser) is refused. A request for one of the
|
||||||
|
|||||||
@@ -63,7 +63,8 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy
|
|||||||
- **工具调用**:支持并行和连续调用。运行超过 150 秒的工具会先收到 "still running" 的
|
- **工具调用**:支持并行和连续调用。运行超过 150 秒的工具会先收到 "still running" 的
|
||||||
占位响应,真正的结果送达后继续同一轮对话,每个调用只在客户端执行一次。
|
占位响应,真正的结果送达后继续同一轮对话,每个调用只在客户端执行一次。
|
||||||
- **会话续接**:每轮结束后记录会话。重启 Magpie 或插件后,只要历史和指令的哈希一致,
|
- **会话续接**:每轮结束后记录会话。重启 Magpie 或插件后,只要历史和指令的哈希一致,
|
||||||
就用 `session/resume` 接上上下文。状态文件只存会话 ID 与哈希,不存消息原文。
|
就用 `session/resume` 接上上下文。agy 的提示缓存跟着它运行的目录走,所以接上的会话
|
||||||
|
回到原来的临时目录里运行,缓存照样命中。状态文件只存会话 ID、哈希和这个目录,不存消息原文。
|
||||||
- **隔离运行**:不读取你的全局 MCP 配置。每个 agy 进程使用临时 agent。agy 为它自己的
|
- **隔离运行**:不读取你的全局 MCP 配置。每个 agy 进程使用临时 agent。agy 为它自己的
|
||||||
工具发起的权限请求(shell、写文件、浏览器等)一律拒绝;客户端工具经桥接的 `ide-tools`
|
工具发起的权限请求(shell、写文件、浏览器等)一律拒绝;客户端工具经桥接的 `ide-tools`
|
||||||
调用时发起的请求放行一次,这些工具在客户端里运行,受客户端自己的权限管。真正的操作
|
调用时发起的请求放行一次,这些工具在客户端里运行,受客户端自己的权限管。真正的操作
|
||||||
|
|||||||
+47
-16
@@ -2071,7 +2071,7 @@ class Proc {
|
|||||||
this.resumed = false
|
this.resumed = false
|
||||||
this.child = null
|
this.child = null
|
||||||
this.conn = null
|
this.conn = null
|
||||||
this.workspace = null
|
this.workspace = this.resumeFrom?.workspace || null
|
||||||
this.logPath = null
|
this.logPath = null
|
||||||
this.lastUsed = Date.now()
|
this.lastUsed = Date.now()
|
||||||
this.dead = false
|
this.dead = false
|
||||||
@@ -2136,7 +2136,15 @@ class Proc {
|
|||||||
await ensureControlServer()
|
await ensureControlServer()
|
||||||
const bin = await ensureShimDir()
|
const bin = await ensureShimDir()
|
||||||
sessions.set(this.token, this)
|
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)
|
const agentDir = path.join(this.workspace, ".agents", "agents", AGENT_NAME)
|
||||||
await fs.promises.mkdir(agentDir, { recursive: true })
|
await fs.promises.mkdir(agentDir, { recursive: true })
|
||||||
await fs.promises.writeFile(path.join(agentDir, "agent.md"), agentDefinition(), { mode: 0o600 })
|
await fs.promises.writeFile(path.join(agentDir, "agent.md"), agentDefinition(), { mode: 0o600 })
|
||||||
@@ -3045,19 +3053,28 @@ class Proc {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
this.child = null
|
this.child = null
|
||||||
if (this.workspace) {
|
// A resumed session's agy starts again in this folder; never remove it
|
||||||
for (let attempt = 0; attempt < 4; attempt++) {
|
// from under one that already has.
|
||||||
try {
|
if (this.workspace && ![...allProcs].some((proc) => proc !== this && proc.workspace === this.workspace)) {
|
||||||
await fs.promises.rm(this.workspace, { recursive: true, force: true })
|
const removal = this.#removeWorkspace()
|
||||||
break
|
workspaceRemovals.set(this.workspace, removal)
|
||||||
} catch (error) {
|
await removal
|
||||||
if (attempt === 3 || !["EBUSY", "EPERM", "ENOTEMPTY"].includes(error?.code)) break
|
if (workspaceRemovals.get(this.workspace) === removal) workspaceRemovals.delete(this.workspace)
|
||||||
await new Promise((resolve) => setTimeout(resolve, 50 * (attempt + 1)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
allProcs.delete(this)
|
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) {
|
function stillRunningText(call) {
|
||||||
@@ -3351,12 +3368,22 @@ function park(proc) {
|
|||||||
userCloak: USER_CLOAK,
|
userCloak: USER_CLOAK,
|
||||||
instructionsInSession: !!proc.instructionsInSession,
|
instructionsInSession: !!proc.instructionsInSession,
|
||||||
workDir: proc.workDir,
|
workDir: proc.workDir,
|
||||||
|
workspace: proc.workspace,
|
||||||
at: Date.now(),
|
at: Date.now(),
|
||||||
})
|
})
|
||||||
while (parked.size > MAX_PARKED) parked.delete(parked.keys().next().value)
|
while (parked.size > MAX_PARKED) parked.delete(parked.keys().next().value)
|
||||||
saveParked()
|
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) {
|
function takeParked(convKey, opts) {
|
||||||
loadParked()
|
loadParked()
|
||||||
const entry = parked.get(convKey)
|
const entry = parked.get(convKey)
|
||||||
@@ -3368,7 +3395,8 @@ function takeParked(convKey, opts) {
|
|||||||
entry.instructionsHash !== digest(sentInstructionsIdentity(opts.instructions)) ||
|
entry.instructionsHash !== digest(sentInstructionsIdentity(opts.instructions)) ||
|
||||||
entry.userCloak !== USER_CLOAK || entry.instructionsInSession !== (systemAppend() && !!opts.instructions)) return null
|
entry.userCloak !== USER_CLOAK || entry.instructionsInSession !== (systemAppend() && !!opts.instructions)) return null
|
||||||
const incoming = digest(historyKey(opts.history))
|
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
|
// Sans-inputs resume needs the hashes written by current park(). Old
|
||||||
// entries without them still resume on an exact historyHash match only.
|
// entries without them still resume on an exact historyHash match only.
|
||||||
const incomingSans = digest(historyKey(stripToolUseInputs(opts.history)))
|
const incomingSans = digest(historyKey(stripToolUseInputs(opts.history)))
|
||||||
@@ -3376,7 +3404,7 @@ function takeParked(convKey, opts) {
|
|||||||
const idsOk = incomingIds != null && entry.toolUseIdentitiesHash === digest(incomingIds)
|
const idsOk = incomingIds != null && entry.toolUseIdentitiesHash === digest(incomingIds)
|
||||||
const sansOk = entry.historyHashSansInputs === incomingSans || entry.historyHash === incomingSans
|
const sansOk = entry.historyHashSansInputs === incomingSans || entry.historyHash === incomingSans
|
||||||
if (!idsOk || !sansOk) return null
|
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) {
|
async function retire(key, proc) {
|
||||||
@@ -3455,6 +3483,8 @@ setInterval(() => { evictIdle().catch(() => {}) }, 60_000).unref()
|
|||||||
// AGY_BRIDGE_SPARE=0 turns them off.
|
// AGY_BRIDGE_SPARE=0 turns them off.
|
||||||
const spares = new Map()
|
const spares = new Map()
|
||||||
const SPARE_MAX = 2
|
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() {
|
function sparesOn() {
|
||||||
return !/^(?:0|false|off|no|disabled)$/i.test(process.env.AGY_BRIDGE_SPARE || "")
|
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)
|
dropFromPool(existing)
|
||||||
await existing.stop().catch(() => {})
|
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()) {
|
while (!spare && allProcs.size >= maxProcs()) {
|
||||||
const idle = spares.values().next().value
|
const idle = spares.values().next().value
|
||||||
if (idle) {
|
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`)
|
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 })
|
const proc = spare ?? new Proc(agyPath, key, { ...opts, resume })
|
||||||
try {
|
try {
|
||||||
if (spare) await spare.adopt(key, { ...opts, resume })
|
if (spare) await spare.adopt(key, { ...opts, resume })
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "@magpie-community/opencode-agy-cli-auth",
|
"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",
|
"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",
|
"type": "module",
|
||||||
"main": "./opencode.mjs",
|
"main": "./opencode.mjs",
|
||||||
|
|||||||
@@ -555,7 +555,7 @@ export async function createBridgeKit(options = {}) {
|
|||||||
}
|
}
|
||||||
if (args[0] === "acp") {
|
if (args[0] === "acp") {
|
||||||
const child = new FakeChild(kit, file, args)
|
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)
|
new FakeAgy(kit, child, opts)
|
||||||
return child
|
return child
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -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 () => {
|
test("取消 prompt 把缓存比例校准为 0 后,下一回合工具步也不再把前缀估成读缓存", async () => {
|
||||||
await withKit({}, async (kit) => {
|
await withKit({}, async (kit) => {
|
||||||
const cancelled = { inputTokens: 5000, cachedReadTokens: 0, outputTokens: 3 }
|
const cancelled = { inputTokens: 5000, cachedReadTokens: 0, outputTokens: 3 }
|
||||||
|
|||||||
Reference in New Issue
Block a user