diff --git a/.claude/skills/agy-cli-fork/SKILL.md b/.claude/skills/agy-cli-fork/SKILL.md index 33d7684..2dfd5fd 100644 --- a/.claude/skills/agy-cli-fork/SKILL.md +++ b/.claude/skills/agy-cli-fork/SKILL.md @@ -45,15 +45,10 @@ fork/fork.sh sync # 默认合并上游 main;也可以指定 ref:for 5. fetch 里 `let keptSession = false` 后面、匹配工具结果之前的入口判断。 `fork/patch-e2e.mjs` 的两个 retry 用例可以验证。容量不足改 503 的补丁上游 0.1.95 已自带,不再是我们的补丁;`patch-e2e.mjs` 里的 busy 用例留着当回归测试。 -- 工具被拒后回空的修复(`Denied ending (local patch)`),挂在三个位置(0.1.161 起上游改用默认 agent,`bridgeAgentFiles` 的说明已写明 agy 自带工具关闭、带媒体时只开 read_file,原来加在 agent 说明里的那行删了): - 1. `#onRequest` 的拒绝分支,在 `deniedPermissions++` 后面记下 `turn.denied`; - 2. `Turn.emitText` 开头清掉 `this.denied`; - 3. `#runTurn` 里 `turn.flushText()` 之后:`turn.denied` 还在、并且这期间没有新的客户端工具调用时,抛出 `AgentTurnError`。 - - `fork/patch-e2e.mjs` 的两个 denied 用例可以验证这几处接得对不对。 +- 工具被拒后回空的修复(`Denied ending`)0.1.186 起已退役,用上游 0.1.182 的 `noteDenied()`/`TOOL_OFF_PROMPT`;合并时 `#onRequest` 拒绝分支一律用上游的。 - 并行通道(`Parallel lanes (local patch)`),挂在六个位置: 1. `acquireProcLocked` 前面的整段 helper(`LANE_TAG` 到 `heldFor`); - 2. `acquireProcLocked` 开头用 `pickLane` 取 `existing` 和 `key`(原来是 `pool.get(convKey)`,`key` 原来在后面才 `let key = convKey`,那一行已删); + 2. `acquireProcLocked` 开头(上游 0.1.181 的 `await checkBridge()` 之后)用 `pickLane` 取 `existing` 和 `key`(原来是 `pool.get(convKey)`,`key` 原来在后面才 `let key = convKey`,那一行已删); 3. 同一函数里,上游 `lineageVerdict` 那段之前插入的 `laneWanted` 分支,以及上游 `superseded` 事件后面的 `noteSuperseded`;`findLiveContinuedProc` 的条件多了 `key === convKey`,`why` 先取 `laneWhy`,`takeParked` 用 `key`; 4. `takeParked(key, …)` 用通道的键;0.1.163 的 `parkRebase` 要求 `proc.convKey === convKey`,通道进程上不做 rebase、按旧办法整段重放; 4b. `recoverStaleTurn` 里 `current` 按 `ctx.proc.convKey` 取,重放时带 `laneKey`; @@ -102,7 +97,7 @@ fork/fork.sh release `fork/swap-agy-cli.sh <新spec>` 在容器里以 abc 身份运行,它会: - 备份插件配置,rm 旧来源,add 新来源。add 失败时自动把旧来源装回去。 -- 检查四项:来源对不对、登录状态和换之前是否一致、四处补丁是否都在(按 Video、Retry attach、Denied ending、Parallel lanes、Thinking when disabled、Chat routing 六种标记数)、插件进程是否重启(最多等 60 秒)。 +- 检查四项:来源对不对、登录状态和换之前是否一致、四处补丁是否都在(按 Video、Retry attach、Parallel lanes、Thinking when disabled、Chat routing 五种标记数)、插件进程是否重启(最多等 60 秒)。 - 任何一项不符就以非 0 退出。 ```sh diff --git a/FORK.md b/FORK.md index 615eea7..8ddf624 100644 --- a/FORK.md +++ b/FORK.md @@ -2,14 +2,11 @@ 本仓库 fork 自 [magpie-community/plugins](https://github.com/magpie-community/plugins) 的 `packages/agy-cli`,npm 包名是 `@magpie-community/opencode-agy-cli-auth`。上游的 LICENSE(MIT)和 NOTICE.md 原样保留。 -和上游相比多六处改动,都在 `index.mjs` 里(“容量不足报错改为 503”上游 0.1.95 已经自带,分叉里那份已删除): +和上游相比多五处改动,都在 `index.mjs` 里(“容量不足报错改为 503”上游 0.1.95 已经自带、“工具被拒后不再回空”上游 0.1.182 已经自带,分叉里那两份已删除): 1. **视频和图片链接(OpenAI 写法)**:上游 0.1.155 起自带视频/音频输入,但只收 `video`/`audio` 块里的 base64;图片也只收 base64,链接一律 400(agy 本身不收图片链接)。补丁把 `image_url` 里的视频(`data:video/…` 或 http(s) 链接)、图片链接,以及 Magpie 从部分 `/v1/responses` 写法原样留下的 `image_url` / `input_image` 块,下载或解码后转成上游的 base64 `image`/`video` 块,之后全走上游。链接下载禁止内网地址,最大 100 MB,缓存一小时。代码里搜 `Video (local patch)`。 -2. **重发的请求接上原来那一轮**:客户端等不到首字就断开,把同一份请求再发一遍,而原请求还在跑;或者原请求的回复(一次工具调用)在路上丢了。上游插件对这种重发返回错误(0.1.106 之前一律是 409 `no active MCP call matches these tool results`,0.1.106 起原请求还在出流时是 503),要等原来那一轮结束才变,而原请求照常跑完并计费,产出没人收。现在重发的请求会等原请求出结果,拿到同一份回复,用量记 0,不重复计费。原请求失败或被取消时,重发的请求收到 503,客户端再发一次就会重新跑。已经正常结束、没有待答工具调用的回复不走这条路,再发一遍仍然重新生成。带工具结果的请求、原请求已经结束时,交给上游 0.1.131 的 `replay_tool_step`(比对整份请求的摘要,回放同一个消息 id);本补丁只接原请求还在跑的重发,以及不带工具结果的请求丢了回复的重发。代码里搜 `Retry attach (local patch)`。 -3. **工具被拒后不再回空**:带视频的会话开放 agy 的读文件工具以后,模型有时会拿它去读客户端机器上的路径,比如 ZCode 用户 Mac 上的 `~/.zcode/...`。这个工具在服务器上跑,读会话目录以外的路径要先申请权限,插件会拒绝;agy 被拒后就直接结束这一轮。上游插件把这样的结束原样交给客户端,结果是空正文、没有工具调用,客户端看上去就是卡住不动。现在改成两处: - - (上游 0.1.161 起自带)会话说明写明 agy 自带工具都关着,带媒体时只开 `read_file` 读附带的文件。 - - 一轮在被拒的工具上结束、之后既没有正文也没有客户端工具调用时,返回 `api_error`,错误信息写明是哪个工具被拒、为什么被拒。 - 代码里搜 `Denied ending (local patch)`。 +2. **重发的请求接上原来那一轮**:客户端等不到首字就断开,把同一份请求再发一遍,而原请求还在跑;或者原请求的回复(一次工具调用)在路上丢了。上游插件对这种重发返回错误(0.1.106 之前一律是 409 `no active MCP call matches these tool results`,0.1.106 起原请求还在出流时是 503),要等原来那一轮结束才变,而原请求照常跑完并计费,产出没人收。现在重发的请求会等原请求出结果,拿到同一份回复,用量记 0,不重复计费。原请求失败或被取消时,重发的请求收到 503,客户端再发一次就会重新跑。已经正常结束、没有待答工具调用的回复不走这条路,再发一遍仍然重新生成。带工具结果的请求、原请求已经结束时,交给上游 0.1.131 的 `replay_tool_step`(比对整份请求的摘要,回放同一个消息 id);本补丁只接原请求还在跑的重发,以及不带工具结果的请求丢了回复的重发。代码里搜 `R3. **工具被拒后不再回空**(已退役):上游 0.1.182(#1805)自带:agy 自带工具被拒后这一轮既没正文也没工具调用时,先带说明重问一次(`TOOL_OFF_PROMPT`),再空才报错。分叉原来的 `Denied ending (local patch)` 是直接报错,而且排在上游重问之前,会把上游的重问截掉,所以 0.1.186 合并时删了。编号留着,免得别处引用对不上。 +nied ending (local patch)`。 4. **同一对话的并行线各用各的 agy 进程**:插件按“user_id + system + 第一条消息”认对话,一个对话只有一个 agy 进程。有的客户端在同一个会话里同时跑两条线,比如 ZCode 带着整份主对话另跑一个有工具调用的后台任务,两条线这三样都一样。上游会让后到的那条抢掉对方挂着的工具轮,或者让它等对方出完流(503 `this conversation still has an unfinished response`);被抢的一方送回工具结果时,0.1.106 之前收到 409 `no active MCP call matches these tool results`;0.1.106 起改为重放,但会反过来抢掉对方挂着的那一轮,对方正在出流时则回 503。两条线来回互抢,每抢一次都要重放整份历史。现在: - 对方正在出流时,新来的另一条线(不带对方的工具调用)直接另开一个进程(一条“通道”),不等也不抢; - 对方挂着工具轮、没在出流时,仍按上游的规则抢占;被抢的那一轮的工具结果回来时,不抢回对方、也不回 503,而是开一条通道用请求里的历史重放,并把这个对话记为“并行”; diff --git a/README.en.md b/README.en.md index ac035f7..0a741a6 100644 --- a/README.en.md +++ b/README.en.md @@ -340,6 +340,11 @@ then comes from what agy acp offers (plugins#1602). With no tier, the account shows agy's refusal and no numbers. On Windows, where the plugin has no terminal to give agy, the refusal stays. +A usage call with `printOnly` (what magpie sends for the one reading it makes +when you ask for it) runs `agy -p /usage` and nothing else: the refusal +stands, and neither agy acp nor agy's terminal UI is started for it +(plugins#1824). + While Antigravity's app has its gateway on (`gateway.enabled` in `~/.gemini/config/config.json`, as when magpie takes over Antigravity), agy reads the same file and goes to that gateway instead of your Google account, diff --git a/README.md b/README.md index 829132d..f1bc6c6 100644 --- a/README.md +++ b/README.md @@ -221,6 +221,9 @@ agy 因地区拒绝 `/usage`("not currently available in your location")时 (plugins#1602)。没有档位时,账号显示 agy 的拒绝原因,不显示数字。Windows 上插件没有终端可给 agy, 仍显示拒绝。 +带 `printOnly` 的额度查询(Magpie 在你手动读取时发出的那一次)只运行 `agy -p /usage`:拒绝原样显示, +不为它启动 agy acp,也不启动 agy 的终端界面(plugins#1824)。 + Antigravity 应用的网关打开时(`~/.gemini/config/config.json` 里 `gateway.enabled`,例如 Magpie 接管了 Antigravity),agy 读同一个文件,会走网关而不是你的 Google 账号,`/usage` 只得到 `groups: []`。从 0.1.148 起,插件启动的每个 agy(对话和额度)都用不带网关的目录:登录在系统钥匙串里时 diff --git a/agy-cli.test.mjs b/agy-cli.test.mjs index bb2fa11..0e73f00 100644 --- a/agy-cli.test.mjs +++ b/agy-cli.test.mjs @@ -41,6 +41,7 @@ for (const [name, mocks] of [ ["account-scope.mjs", false], ["stateless-reuse.mjs", false], ["tools-listed.mjs", false], + ["bridge-heal.mjs", false], ["slash-commands.mjs", false], ["concurrent-convs.mjs", false], ["masking-drift.mjs", false], diff --git a/default-agent.mjs b/default-agent.mjs index 49fd58f..fbf0e12 100644 --- a/default-agent.mjs +++ b/default-agent.mjs @@ -1,8 +1,12 @@ -// Every agy session the plugin opens runs on agy's default agent. From agy -// 1.5.17 a session of a custom agent (--agent, .agents/agents/*) costs about -// four times the quota (google-antigravity/antigravity-cli#1890), and Google's -// answer is to drop --agent and give the instructions as rules. So a session's -// folder gets, in place of an agent.md: +// Every agy session the plugin opens runs on agy's default agent. It moved +// there when agy 1.5.17 charged a custom agent's session (--agent, +// .agents/agents/*) about four times the quota +// (google-antigravity/antigravity-cli#1890). Google reverted that charge on +// 2026-11-30, but the plugin stays on the default agent: it is the session +// agy itself opens, and with Antigravity accounts being disabled for terms +// violations (#1741) the session shape isn't changed until the owner rules on +// going back (#1777). Without --agent the instructions go in as rules, so a +// session's folder gets, in place of an agent.md: // - AGENTS.md, the instructions: agy loads it as a workspace rule, also with // --include-default-customizations=false (agy 1.5.19, measured). // - .agents/skills.json excludes agy's bundled skills from the prompt index. diff --git a/fork/patch-e2e.mjs b/fork/patch-e2e.mjs index 4f95006..ec81502 100644 --- a/fork/patch-e2e.mjs +++ b/fork/patch-e2e.mjs @@ -149,53 +149,6 @@ test("the image model stays out of provider.models unless AGY_BRIDGE_IMAGE_MODEL }, { agyPath: null, env: { AGY_BRIDGE_IMAGE_MODEL: "1" } }) }) -// agy asks the client to allow its own read_file on a path outside the media -// folder (a client path), as agy 1.5.10 does; returns the bridge's answer. -async function askReadFile(kit, agent, file) { - const { child } = kit.acpSpawns[kit.acpLog.findLast((e) => e.method === "session/prompt").spawn] - const answered = new Promise((resolve) => { - const own = child.onStdin - child.onStdin = (chunk) => { - own(chunk) - for (const line of String(chunk).split("\n")) if (line.includes('"id":"perm"')) resolve(JSON.parse(line)) - } - }) - child.stdout.emit("data", JSON.stringify({ jsonrpc: "2.0", id: "perm", method: "session/request_permission", params: { - sessionId: agent.sessionId, - toolCall: { toolCallId: "call_rf", title: `Read ${file}`, kind: "read" }, - options: [{ optionId: "allow", name: "Allow", kind: "allow_once" }, { optionId: "deny", name: "Deny", kind: "reject_once" }], - } }) + "\n") - return (await answered).result -} - -test("a turn agy ends at its own denied read_file fails with the reason, not an empty reply", async () => { - await withKit(async (kit) => { - kit.defaultPrompt = async (agent) => { - const answer = await askReadFile(kit, agent, "/Users/someone/video_dl/video.mp4") - assert.equal(answer.outcome.optionId, "deny") - return { stopReason: "end_turn" } - } - const text = await (await kit.request(baseBody({ metadata: { user_id: "denied" }, messages: [{ role: "user", content: "look at /Users/someone/video_dl/video.mp4" }] }))).text() - const error = sseError(text) - assert.equal(error.type, "api_error") - assert.match(error.message, /agy's own tool \(Read \/Users\/someone\/video_dl\/video\.mp4\).*denied/) - assert.ok(!text.includes("text_delta")) - }) -}) - -test("a denied read_file the model answers after is a normal reply", async () => { - await withKit(async (kit) => { - kit.defaultPrompt = async (agent) => { - await askReadFile(kit, agent, "/Users/someone/notes.md") - await agent.text("I can't open that here.") - return { stopReason: "end_turn" } - } - const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "denied-then-text" }, messages: [{ role: "user", content: "read /Users/someone/notes.md" }] }))) - assert.equal(parsed.error, null) - assert.equal(parsed.content.filter((b) => b.type === "text").map((b) => b.text).join(""), "I can't open that here.") - }) -}) - // Retry attach (local patch) const toolRound = (body, parsed, result) => ({ ...body, messages: [...body.messages, { role: "assistant", content: parsed.content.filter((b) => b.type === "tool_use").map((b) => ({ type: "tool_use", id: b.id, name: b.name, input: b.input })) }, diff --git a/fork/swap-agy-cli.sh b/fork/swap-agy-cli.sh index afdf69b..c1d7039 100755 --- a/fork/swap-agy-cli.sh +++ b/fork/swap-agy-cli.sh @@ -38,7 +38,7 @@ fi now=$(spec) after=$(state) # distinct patch markers present (one per patch, however many lines carry it) -p=$(grep -o -e "Video (local patch)" -e "Retry attach (local patch)" -e "Denied ending (local patch)" -e "Parallel lanes (local patch)" -e "Thinking when disabled (local patch)" -e "Chat routing (local patch)" \ +p=$(grep -o -e "Video (local patch)" -e "Retry attach (local patch)" -e "Parallel lanes (local patch)" -e "Thinking when disabled (local patch)" -e "Chat routing (local patch)" \ "$C/plugins/node_modules/@magpie-community/opencode-agy-cli-auth/index.mjs" | sort -u | wc -l | tr -d " ") h="" for _ in $(seq 1 60); do @@ -48,4 +48,4 @@ for _ in $(seq 1 60); do done echo "$old -> $now | $before -> $after | patches=$p | plugin host $h0 -> $h | backup $B" -[ "$now" = "$NEW" ] && [ "$after" = "$before" ] && [ "$p" = 6 ] && [ -n "$h" ] && [ "$h" != "$h0" ] || exit 7 +[ "$now" = "$NEW" ] && [ "$after" = "$before" ] && [ "$p" = 5 ] && [ -n "$h" ] && [ "$h" != "$h0" ] || exit 7 diff --git a/index.mjs b/index.mjs index f2ded9d..6b53cb5 100644 --- a/index.mjs +++ b/index.mjs @@ -2,6 +2,7 @@ import { agyCandidates, childEnv, spawnAgy, windowsMcpShim, windowsNcBuild, wind import { spawn, spawnSync } from "node:child_process" import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto" import { once } from "node:events" +import { isDeepStrictEqual } from "node:util" import fs from "node:fs" import net from "node:net" import dns from "node:dns" @@ -200,6 +201,16 @@ const RETRY_CORE = RETRY_MARKER.trim() // the whole context, and a reply still empty after that is an error the // next account answers. The words go upstream, so they name nobody. const EMPTY_REPLY_PROMPT = "Your last reply was empty. Continue: make the tool call you were about to make, or give your answer." +// The same ask after a call to one of agy's own tools was turned away +// (plugins#1805): a read_file outside the session's folder is asked of the +// bridge as a permission, which it refuses, and agy tells the model the +// user denied it and not to get at it another way. Asked to go on with +// EMPTY_REPLY_PROMPT alone, the model told the user it had no access to +// their project and asked for it. This says what happened instead, in +// words that go upstream too, so they name nobody. +const TOOL_OFF_PROMPT = "Your last reply was empty. The built-in tool you called is turned off in this session, so that call did not run. " + + "This is not the user refusing access to the project, and there is no need to ask for workspace access or permission. " + + "Continue with the tools you were given: make the tool call you need with one of them, or give your answer." // agy's own output-cap retry reaches the reply as three lines of its own: // what happened, its instruction to continue, and the retries left. The // model's answer goes on after them in the same turn, so the notice is agy's @@ -444,10 +455,20 @@ let cachedAgyPath let cachedAgySearchKey let controlServer let controlServerPromise +// The port the control server was last on: one made again asks for it +// first, so every agy already started with it reaches the new one (#1766). +let controlPort = 0 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 +let lastShimDir +// A shim check in flight (checkShim), shared by everyone who asks meanwhile. +let shimCheck = null +// Counts each time the shim dir or the control port moved: an agy started +// before (Proc.bridgeEpoch) runs a `nc` that reaches nothing, so it is never +// handed another session (#1766). +let bridgeEpoch = 0 function positiveTimeout(value, fallback) { const parsed = Number(value) @@ -884,9 +905,13 @@ const MODEL_CATALOG_RETRY_MS = 5_000 // offer is stale and asked again. 60 minutes: the offer changes rarely, // and a probe is a fresh agy acp spawn per account, so re-probing on the // catalog's 5-minute cadence would spawn far more often than the job -// needs. A re-probe triggered by a request for a model the offer doesn't -// list is a possible follow-up, not done here. +// needs. A request for a model the offer lacks while `agy models` lists it +// asks again sooner (recheckOffer, plugins#1804). const OFFERED_TTL_MS = 60 * 60 * 1000 +// How often a request may ask agy acp again for its account's offer: the +// offer lacks the model asked for while `agy models` lists it and another +// account's list has it, which would turn the request away (plugins#1804). +const OFFER_RECHECK_MS = 5 * 60 * 1000 // What is learnt of the models is each account's own (#1229): accounts on // different plans list and are offered different models, so one account's @@ -910,6 +935,8 @@ const OFFERED_TTL_MS = 60 * 60 * 1000 // shenggxhz (X, 11-17) moved from Pro to Ultra and kept the Pro account's // offer, which filtered Gemini 4 out of Ultra's listing. // - offeredProbePromise, offeredProbeAt, offeredGen: the probe below. +// - offerRecheckAt: when a request last asked the offer again +// (recheckOffer). const modelStates = new Map() function ms() { @@ -928,6 +955,7 @@ function ms() { offeredProbePromise: null, offeredProbeAt: null, offeredGen: 0, + offerRecheckAt: null, } modelStates.set(home, state) } @@ -945,13 +973,36 @@ function offeredModelsOf(configOptions, models) { return out } -function noteOfferedModels(configOptions, models) { +function offeredFamily(id) { + return String(id).replace(/-\d{8}$/, "").replace(/-(?:minimal|low|medium|high|xhigh|max)$/i, "") +} + +// update: the offer comes from a session's config_option_update, not from +// a session agy just opened. +function noteOfferedModels(configOptions, models, { update = false } = {}) { const offered = offeredModelsOf(configOptions, models) if (!offered.length) return - ms().offeredStale = false - ms().offeredAt = Date.now() const names = new Map(offered.map(model => [model.id, typeof model.name === "string" && model.name ? model.name : model.id])) const key = [...names.keys()].sort().join("\n") + // An update mid-session that drops models the offer had isn't believed + // (plugins#1804): an offer short of Gemini 4 Neon and Carbon was saved + // while agy's calls to its service failed (loadCodeAssist: EOF) and + // served for the offer's hour, so requests for them were turned away, + // and a host restarted in that hour froze it into magpie's list. The + // offer is asked again instead; a freshly opened session's is believed, + // as a plan that loses models shows there (a short one is asked again + // by recheckOffer). An update names models by family (gemini-4-neon, + // where an opened session's offer also has gemini-4-neon-high), so what + // is lost is a family. + if (update && ms().acpOfferedModels) { + const families = new Set([...names.keys()].map(offeredFamily)) + if ([...ms().acpOfferedModels.keys()].some(id => !families.has(offeredFamily(id)))) { + ms().offeredStale = true + return + } + } + ms().offeredStale = false + ms().offeredAt = Date.now() if (key === ms().acpOfferedKey) return ms().acpOfferedModels = names ms().acpOfferedKey = key @@ -989,6 +1040,7 @@ function forgetOffered() { ms().offeredAt = 0 ms().offeredProbePromise = null ms().offeredProbeAt = null + ms().offerRecheckAt = null ms().offeredGen++ } @@ -1087,6 +1139,21 @@ function probeOfferedOnce(agyPath) { return probe } +// recheckOffer asks agy acp again what this account offers, for a request +// whose model the offer lacks while `agy models` lists it (plugins#1804). +// At most once in OFFER_RECHECK_MS for an account, past the probes' own +// retry gate; a probe that fails leaves the offer stale, which is unknown. +async function recheckOffer(agyPath) { + const now = Date.now() + if (ms().offerRecheckAt !== null && now - ms().offerRecheckAt < OFFER_RECHECK_MS) return + ms().offerRecheckAt = now + if (!ms().offeredProbePromise) { + ms().offeredStale = true + ms().offeredProbeAt = null + } + await briefly(probeOfferedOnce(agyPath), OFFERED_PROBE_TIMEOUT_MS) +} + // Web search, as agy itself searches (Kayphoon, magpie#7632): a session on // agy's default agent whose tool gate lets only agy's own search_web // through (default-agent.mjs), asked for the query. @@ -1849,17 +1916,51 @@ 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) { +function toolsUnlistedError(count, diagnosis = "") { 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`) + : `the bridge's MCP server, which agy starts through this plugin's own \`nc\` shim (not a netcat installed on this computer), 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${diagnosis ? ` (${diagnosis})` : ""}`) error.statusCode = 502 error.code = "tools_not_loaded" return error } +// What an agy that never listed the tools had to reach the bridge with, in +// a few words for the error and the log, and both made again where one was +// broken, so the next try needs no restart (#1766): the nc shim its PATH +// starts with, the runtime and the MCP server the shim runs, and the +// control port the server connects to. +async function toolsUnlistedDiagnosis(proc) { + const bin = proc?.bridgeBin || shimDir + const shim = bin ? await shimState(bin, proc?.bridgeBin ? proc.bridgeShimOwned : shimDirOwned) : "none" + // a built nc.exe (Windows) carries its runtime + const runtime = process.platform === "win32" && !shimDirOwned ? null : await isFileWithBytes(process.execPath) ? "ok" : "missing" + const server = await isFileWithBytes(MCP_SERVER_PATH) ? "ok" : "missing" + const port = proc?.controlPort || controlPort + const listening = !!(controlServer?.listening && controlPort === port) + const moved = !!proc && proc.bridgeEpoch !== bridgeEpoch + const broken = shim !== "ok" || !listening + let healed = false + if (broken) { + await checkBridge().catch(() => {}) + healed = !!controlServer?.listening && !!shimDir && await shimState(shimDir, shimDirOwned) === "ok" + } + const stderr = String(proc?.stderrTail || "").trim().replace(/\s+/g, " ").slice(-300) + logSessionEvent(proc, "tools_not_loaded", { + shim, runtime, server, control_listening: listening, moved, healed, + }, "tools_not_loaded") + return [ + `nc shim: ${shim}`, + ...runtime ? [`its runtime: ${runtime}`] : [], + `MCP server: ${server}`, + `control port${port ? ` ${port}` : ""}: ${listening ? "listening" : "closed"}`, + ...broken ? [healed ? "made again, the next try uses it" : "could not be made again"] : [], + `agy stderr: ${stderr || "(empty)"}`, + ].join("; ") +} + class ConflictError extends Error { constructor(message, code) { super(message) @@ -1951,11 +2052,7 @@ function shellQuote(value) { // 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. 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 - } + await checkShim() // 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). @@ -1974,27 +2071,123 @@ async function ensureShimDir() { ncBuildFailure = "" shimDir = shared shimDirOwned = false + noteShimDir(shared) 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") { - await fs.promises.writeFile(path.join(dir, "nc.cmd"), - windowsMcpShim(process.execPath, MCP_SERVER_PATH)) - } else { - await fs.promises.writeFile(path.join(dir, "nc"), - `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(MCP_SERVER_PATH)}\n`, { mode: 0o700 }) - } + await writeShim(dir) shimDir = dir shimDirOwned = true + noteShimDir(dir) return dir })() shimDirPromise.catch(() => { shimDirPromise = null }) return shimDirPromise } +function shimName(owned) { + return process.platform === "win32" ? (owned ? "nc.cmd" : "nc.exe") : "nc" +} + +// "ok", "missing" or "not executable": the shim in dir agy would run. +async function shimState(dir, owned) { + const file = path.join(dir, shimName(owned)) + if (!await isFileWithBytes(file)) return "missing" + if (process.platform === "win32") return "ok" + try { + await fs.promises.access(file, fs.constants.X_OK) + return "ok" + } catch { + return "not executable" + } +} + +// Through a temp file and a rename: a shim being written is never run half +// done, and one left without its execute bit is replaced whole. +async function writeShim(dir) { + const windows = process.platform === "win32" + const file = path.join(dir, shimName(true)) + const body = windows + ? windowsMcpShim(process.execPath, MCP_SERVER_PATH) + : `#!/bin/sh\nexec ${shellQuote(process.execPath)} ${shellQuote(MCP_SERVER_PATH)}\n` + const temp = `${file}.${randomBytes(4).toString("hex")}.tmp` + try { + await fs.promises.writeFile(temp, body, { mode: 0o700, flag: "wx" }) + await fs.promises.rename(temp, file) + } catch (error) { + await fs.promises.rm(temp, { force: true }).catch(() => {}) + throw error + } +} + +// The shim dir made at the first agy is checked before each later one, and +// before a request goes to an agy already running: a temp cleaner (macOS +// clears $TMPDIR), or anything else, can take the dir or the shim from +// under a host that lives for days. agy then ran whatever `nc` came next in +// PATH, never reached the bridge, and every account's every session failed +// tools_not_loaded until magpie restarted (#1766). The shim is made again +// in the same dir, so the agy already started with it in their PATH reach +// the bridge again too; only a dir that isn't safely this user's any more +// (on Linux's shared /tmp anyone can take a freed name) is left for a new +// one, and the agy started on the old one are retired (bridgeEpoch). +function checkShim() { + shimCheck ??= (async () => { + const dir = shimDir + if (!dir) return + const owned = shimDirOwned + if (await shimState(dir, owned) === "ok" || dir !== shimDir) return + if (!owned) { + // Another host's sweep can take a shared dir that sat unused for a week. + shimDir = undefined + shimDirPromise = null + return + } + const restored = await restoreShimDir(dir).catch(() => false) + if (dir !== shimDir || restored) return + shimDir = undefined + shimDirPromise = null + })().finally(() => { shimCheck = null }) + return shimCheck +} + +// The owned shim dir made again where it was, when that is still safe: +// gone (made again here, 0700), or a real dir of this user's that no one +// else can write. false otherwise. +async function restoreShimDir(dir) { + try { + await fs.promises.mkdir(dir, { mode: 0o700 }) + } catch (error) { + if (error?.code !== "EEXIST") return false + } + const stat = await fs.promises.lstat(dir) + if (!stat.isDirectory()) return false + if (process.platform !== "win32") { + if (typeof process.getuid === "function" && stat.uid !== process.getuid()) return false + if (stat.mode & 0o077) return false + } + await writeShim(dir) + return await shimState(dir, true) === "ok" +} + +// Everything an agy needs to reach the bridge's MCP server, checked and made +// again where broken: the control server and the shim (#1766). +async function checkBridge() { + await ensureControlServer() + await checkShim() + // one that had to go is made now, not at the next agy only + if (!shimDir && lastShimDir) await ensureShimDir() +} + +// The shim dir an agy is started with, noted: one in another place than +// the last moves bridgeEpoch. +function noteShimDir(dir) { + if (lastShimDir && lastShimDir !== dir) bridgeEpoch++ + lastShimDir = dir +} + // 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 @@ -2291,6 +2484,10 @@ class Turn { this.thoughtSinceCall = false this.invalidOutput = false this.invalidOutputSeen = false + // a call to agy's own tool was turned away (its permission refused, or + // the tool gate's hook): since the last client tool call, and at all + this.deniedSinceCall = false + this.deniedSeen = false this.emptyAsked = false this.refusedDetail = "" this.agentErrorCore = "" @@ -2629,7 +2826,6 @@ class Turn { emitText(text) { if (!text) return - this.denied = null // Denied ending (local patch): the model went on if (text.trim()) this.saidSinceCall = true this.textTail = text.slice(-1) this.push({ type: "text", text }) @@ -2664,12 +2860,18 @@ class Turn { } // The model ended its reply having thought, or after agy's empty-output - // retry, with no text and no tool call since the last one. A bare empty - // ending (no thinking either) is left as it is: that is a reply. + // retry, or after a call to agy's own tool was turned away, with no text + // and no tool call since the last one. A bare empty ending (no thinking + // either) is left as it is: that is a reply. One after a call turned + // away is agy ending the turn on it (plugins#1464, #1805). emptyEnding(stopReason) { if (this.steering || this.saidSinceCall) return false if (stopReason != null && stopReason !== "end_turn") return false - return this.thoughtSinceCall || this.invalidOutput + return this.thoughtSinceCall || this.invalidOutput || this.deniedSinceCall + } + + noteDenied() { + this.deniedSinceCall = this.deniedSeen = true } flushText() { @@ -2721,6 +2923,7 @@ class Turn { if (wasActive && update.status === "failed" && typeof update.rawOutput === "string" && update.rawOutput.startsWith("tool call denied by pre-tool hook: ")) { this.proc.deniedHooks++ + this.noteDenied() logBridgeEvent(this.proc, this, "tool_denied", "pre_tool_hook", {}, { denied_hooks: this.proc.deniedHooks, denied_permissions: this.proc.deniedPermissions, }) @@ -2959,8 +3162,14 @@ class Proc { async #spawn() { this.launchKey = await launchKey(this.agyPath, this.workDir, this.media) - await ensureControlServer() + const port = await ensureControlServer() const bin = await ensureShimDir() + // what this agy reaches the bridge through (toolsUnlistedDiagnosis); + // one started before either moved is never handed a session (#1766) + this.controlPort = port + this.bridgeBin = bin + this.bridgeShimOwned = shimDirOwned + this.bridgeEpoch = bridgeEpoch sessions.set(this.token, this) this.workspaceOwner = randomUUID() if (this.workspace) { @@ -2997,7 +3206,7 @@ class Proc { const args = [ "acp", "--log-file", this.logPath, - "--ide-mcp-port", String(controlServer.address().port), + "--ide-mcp-port", String(port), ] if (allowAgyTools) args.push("--dangerously-skip-permissions") // Only the bridge's workspace supplies project customizations. The @@ -3026,7 +3235,7 @@ class Proc { ...childEnv, ...hookEnv, PATH: bin + path.delimiter + inheritedPath, - AGY_BRIDGE_CONTROL_PORT: String(controlServer.address().port), + AGY_BRIDGE_CONTROL_PORT: String(port), AGY_BRIDGE_TOKEN: this.token, // view_file reads agy's temp folder unasked: the workspace, not // the one every other session's workspace is in @@ -3169,7 +3378,7 @@ class Proc { if (this.model) await this.#setModel(this.model, this.selection, this.resumed) this.phases.set_model_ms = Date.now() - configured if (this.tools.length) await this.#waitForToolList(this.toolsVersion) - if (!this.toolsListed()) throw toolsUnlistedError(this.tools.length) + if (!this.toolsListed()) throw toolsUnlistedError(this.tools.length, await toolsUnlistedDiagnosis(this).catch(() => "")) } async #setConfig(config, value) { @@ -3321,8 +3530,7 @@ class Proc { if (allow) return { outcome: { outcome: "selected", optionId: allow.optionId } } } this.deniedPermissions++ - // Denied ending (local patch): what was denied, in case agy ends the turn on it - if (this.turn) this.turn.denied = { what: String(params?.toolCall?.title || params?.toolCall?.kind || "a tool").slice(0, 200), calls: this.turn.calls.length } + if (!this.seeding && this.turn && !this.turn.done) this.turn.noteDenied() const reject = (params?.options || []).find((option) => option?.kind === "reject_once") || (params?.options || []).find((option) => option?.kind === "reject_always") return reject @@ -3348,7 +3556,7 @@ class Proc { if (params.update?.sessionUpdate === "config_option_update" && Array.isArray(params.update.configOptions)) { this.configOptions = params.update.configOptions this.currentSelectionKey = null - inAccount(this.home, () => noteOfferedModels(this.configOptions)) + inAccount(this.home, () => noteOfferedModels(this.configOptions, undefined, { update: true })) this.turn?.logWatch?.onUpdate() return } @@ -3446,9 +3654,7 @@ class Proc { matchesHistory(messages) { if (this.historyInvalid) return false if (this.expectedMessages == null) return !this.turn && !this.hasSentFirstTurn - const expectedKey = historyKey(this.expectedMessages) - const actualKey = historyKey(messages) - if (expectedKey === actualKey) return true + if (sameHistory(this.expectedMessages, messages)) return true // magpie's masking can mask a text the session already has differently // on a later request: the local model that missed it under load (the // rules masked it alone) reads it for a later one, and a value in an @@ -3479,7 +3685,7 @@ class Proc { if (sameToolUseIdentities(this.expectedMessages, messages)) { const expectedStripped = stripToolUseInputs(this.expectedMessages) const actualStripped = stripToolUseInputs(messages) - if (historyKey(expectedStripped) === historyKey(actualStripped) || + if (sameHistory(expectedStripped, actualStripped) || sameHistoryUpToMasking(expectedStripped, actualStripped)) return true } // magpie's image-slim swaps an earlier image for its placeholder text; agy @@ -3505,7 +3711,7 @@ class Proc { while (split > 0 && history[split - 1].role === "assistant") split-- let expectedSplit = this.expectedMessages.length while (expectedSplit > 0 && this.expectedMessages[expectedSplit - 1].role === "assistant") expectedSplit-- - if (historyKey(this.expectedMessages.slice(0, expectedSplit)) !== historyKey(history.slice(0, split))) return false + if (!sameHistory(this.expectedMessages.slice(0, expectedSplit), history.slice(0, split))) return false const actualAssistant = history.slice(split) const expectedAssistant = this.expectedMessages.slice(expectedSplit) const actualCalls = lastAssistantCalls(actualAssistant) @@ -3515,7 +3721,7 @@ class Proc { !call.id || call.id !== expectedCalls[index].id || call.name !== expectedCalls[index].name)) { return false } - return historyKey(stripToolUseInputs(expectedAssistant)) === historyKey(stripToolUseInputs(actualAssistant)) + return sameHistory(stripToolUseInputs(expectedAssistant), stripToolUseInputs(actualAssistant)) } // Answers the pending calls with the results the client sent, waits for agy @@ -3665,26 +3871,22 @@ class Proc { if (detail) throw this.#formatAgentError(detail) } turn.flushText() - // Denied ending (local patch): agy ended the turn at a tool the bridge - // denied (its own view_file on a client path), with no text or client - // call after it. An empty reply reads to the client as a hang. - if (turn.denied && turn.calls.length === turn.denied.calls) { - throw new AgentTurnError(`agy bridge: the model called agy's own tool (${turn.denied.what}), which runs on the server, not on the client; the bridge denied it and agy ended the turn without a reply. Ask again: the client's own tools read its files.`) - } // agy ended the turn without waiting for a long-running client tool: // deliver its real result in a follow-up prompt of the same response. const late = turn.calls.filter((call) => call.deferred && !call.lateDelivered) if (!late.length && turn.emptyEnding(result?.stopReason)) { if (!turn.emptyAsked) { turn.emptyAsked = true - turn.thoughtSinceCall = turn.invalidOutput = false + const denied = turn.deniedSinceCall + turn.thoughtSinceCall = turn.invalidOutput = turn.deniedSinceCall = false turn.arm() - promptParts = [{ type: "text", text: EMPTY_REPLY_PROMPT }] + promptParts = [{ type: "text", text: denied ? TOOL_OFF_PROMPT : EMPTY_REPLY_PROMPT }] lateCalls = null continue } throw new AgentTurnError("agy bridge: the model ended its reply twice with no text and no tool call" + (turn.invalidOutputSeen ? " (agy: Model produced invalid output)" : "") + + (turn.deniedSeen ? " after a call to one of agy's own tools was turned away" : "") + "; send the request again, or try another model") } if (!late.length) { @@ -4022,7 +4224,7 @@ class Proc { clientSeen: false, } turn.flushText() - turn.saidSinceCall = turn.thoughtSinceCall = turn.invalidOutput = turn.emptyAsked = false + turn.saidSinceCall = turn.thoughtSinceCall = turn.invalidOutput = turn.deniedSinceCall = turn.emptyAsked = false turn.calls.push(call) toolCalls.set(call.id, { proc: this, turn, call }) socket.once("close", () => { @@ -4877,8 +5079,8 @@ function writeParked(proc, midTurn, rebase = null) { parked.set(proc.convKey, { key: proc.convKey, sessionId: proc.sessionId, - historyHash: digest(historyKey(held)), - historyHashSansInputs: digest(historyKey(stripToolUseInputs(held))), + historyHash: historyDigest(held), + historyHashSansInputs: historyDigest(stripToolUseInputs(held)), toolUseIdentitiesHash: digest(toolUseIdentitiesKey(held) ?? ""), instructionsHash: digest(sentInstructionsIdentity(proc.instructions)), userCloak: USER_CLOAK, @@ -5143,10 +5345,10 @@ function takeParked(convKey, opts, miss = {}) { } function sameParkedHistory(entry, history) { - if (entry.historyHash === digest(historyKey(history))) return true + if (entry.historyHash === historyDigest(history)) return true // 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(history))) + const incomingSans = historyDigest(stripToolUseInputs(history)) const incomingIds = toolUseIdentitiesKey(history) const idsOk = incomingIds != null && entry.toolUseIdentitiesHash === digest(incomingIds) const sansOk = entry.historyHashSansInputs === incomingSans || entry.historyHash === incomingSans @@ -5283,7 +5485,7 @@ async function takeSpare(agyPath, workDir, media) { } catch { return null } - if (spare.dead || spare.stopping) { + if (spare.dead || spare.stopping || spare.bridgeEpoch !== bridgeEpoch) { await spare.stop().catch(() => {}) return null } @@ -5473,6 +5675,9 @@ function heldFor(convKey, opts, resultBlocks) { // Caller holds the conversation lock; recovery must not acquire it recursively. async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, forceNew = false, lockedKeys = new Set([convKey]), launch = null) { await evictIdle() + // the shim and the control server, made again if either went (#1766); + // an agy that can't reach them any more is not taken below (bridgeEpoch) + await checkBridge().catch(() => {}) // Parallel lanes (local patch) const lane = pickLane(convKey, opts) let existing = lane.proc @@ -5565,7 +5770,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo // than the empty history, so matchesHistory turns the next one away. const retriedOpening = isFreshConversation && existing.failedOpening const compatible = !forceNew && !existing.dead && !existing.retiring && - existing.workDir === opts.workDir && existing.media === opts.media && + existing.bridgeEpoch === bridgeEpoch && existing.workDir === opts.workDir && existing.media === opts.media && sameInstructions(existing.instructions, opts.instructions) && (existing.matchesHistory(matchedHistory) || continuedFresh) if (compatible && (!(isFreshConversation && existing.hasSentFirstTurn) || continuedFresh || retriedOpening)) { @@ -5587,6 +5792,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo const newOpening = isFreshConversation && existing.hasSentFirstTurn && !continuedFresh && Array.isArray(matchedHistory) && !matchedHistory.length why = forceNew ? "forced" : existing.dead ? "dead" : existing.retiring ? "retiring" : + existing.bridgeEpoch !== bridgeEpoch ? "bridge_moved" : existing.workDir !== opts.workDir ? "work_dir" : existing.media !== opts.media ? "media" : !sameInstructions(existing.instructions, opts.instructions) ? "instructions" : @@ -5815,7 +6021,7 @@ function lineageVerdict(proc, turn, opts) { // history, not the trailing (#1208). The round is settled on the client's // side: the turn is left behind, and the replay carries those results. if (carried && carriedAnswered(opts.messages, ids)) return "answered" - if (history.length < base.length || historyKey(history.slice(0, base.length)) !== historyKey(base)) { + if (history.length < base.length || !sameHistory(history.slice(0, base.length), base)) { // The client no longer continues this turn's base: it was shortened or its // prefix was rewritten (a compaction summary). A plain new request has left // the detached tool wait behind; one carrying its tool_use is still a conflict. @@ -5825,7 +6031,7 @@ function lineageVerdict(proc, turn, opts) { const expected = proc.expectedMessages const recorded = Array.isArray(expected) && expected.length > base.length && history.length >= expected.length && - historyKey(history.slice(0, expected.length)) === historyKey(expected) + sameHistory(history.slice(0, expected.length), expected) // A renamed call with edited arguments still belongs to the old response. // Keep upstream's 409 and its live owner intact rather than replaying it as // a sibling conversation just because its inputs no longer compare equal. @@ -5835,7 +6041,7 @@ function lineageVerdict(proc, turn, opts) { })) if (!carried && !recorded && Array.isArray(expected) && expected.length > base.length && history.length === expected.length && - historyKey(withoutInputs(history)) === historyKey(withoutInputs(expected))) return null + sameHistory(withoutInputs(history), withoutInputs(expected))) return null // Codex keeps the text of a reply it interrupts (a sub-agent's message at a // sampling boundary) but drops the reply's tool calls, then sends on (#1231). // The client's history is this session's with only the pending calls taken @@ -5862,7 +6068,7 @@ function droppedPendingCalls(turn, expected, base, history) { const last = stripped.at(-1) if (last?.role !== "assistant" || !last.content.some((block) => block?.type === "text" && block.text?.trim())) return false if (stripped.slice(base.length).some((message) => Array.isArray(message.content) && !message.content.length)) return false - return historyKey(stripped) === historyKey(history) + return sameHistory(stripped, history) } // The client's rows are the session's, tool results included, with only user @@ -6184,9 +6390,9 @@ function compactedEarlierHistory(expected, actual) { const tail = actual.slice(last + 1) if (!tail.length || tail.length > expected.length) return false const mine = expected.slice(expected.length - tail.length) - if (historyKey(mine) === historyKey(tail)) return true + if (sameHistory(mine, tail)) return true return sameToolUseIdentities(mine, tail) && - historyKey(stripToolUseInputs(mine)) === historyKey(stripToolUseInputs(tail)) + sameHistory(stripToolUseInputs(mine), stripToolUseInputs(tail)) } // Whether actual is expected but for text that was there for one request @@ -6760,7 +6966,7 @@ function sameOpeningDonor(proc, launch, opts) { return !!proc && !proc.dead && !proc.stopping && !proc.retiring && !proc.turn && (proc.closable || proc.sessionPrompts === 1) && !proc.resumed && proc.hasSentFirstTurn && !!proc.sessionId && !proc.tools?.length && - proc.launchKey === launch && (proc.userId || "") === (opts.userId || "") && + proc.bridgeEpoch === bridgeEpoch && proc.launchKey === launch && (proc.userId || "") === (opts.userId || "") && (proc.sessionScope || "") === (opts.sessionScope || "") && proc.workDir === opts.workDir && process.env.AGY_BRIDGE_STATELESS_REUSE !== "0" } @@ -6784,7 +6990,7 @@ function findStatelessDonor(opts, launch) { function statelessDonor(proc, launch, userId, sessionScope, workDir) { return !!proc && proc.stateless && !proc.dead && !proc.stopping && !proc.retiring && !proc.turn && !proc.resumed && proc.hasSentFirstTurn && proc.sessionPrompts === 1 && !!proc.sessionId && - proc.launchKey === launch && (proc.userId || "") === userId && + proc.bridgeEpoch === bridgeEpoch && proc.launchKey === launch && (proc.userId || "") === userId && (proc.sessionScope || "") === sessionScope && proc.workDir === workDir } @@ -7185,28 +7391,64 @@ function historyBlock(block, ids) { // The history as the key reads it: one row for each run of messages of one // role, its texts joined and trimmed. -function historyRows(messages) { - const rows = [] +function* historyRowStream(messages) { + let row + const finish = (r) => { + r.content = r.content.filter(block => block.type !== "text" || (block.text = block.text.trim()) !== "") + return r.content.length > 0 + } const ids = new Map() for (const message of messages) { const blocks = Array.isArray(message.content) ? message.content : [{ type: "text", text: message.content ?? "" }] for (const block of blocks) { const value = historyBlock(block, ids) if (!value) continue - let row = rows.at(-1) if (!row || row.role !== message.role) { + if (row && finish(row)) yield row row = { role: message.role, content: [] } - rows.push(row) } const last = row.content.at(-1) if (last?.type === "text" && value.type === "text") last.text += value.text else row.content.push(value) } } - for (const row of rows) { - row.content = row.content.filter(block => block.type !== "text" || (block.text = block.text.trim()) !== "") + if (row && finish(row)) yield row +} + +function historyRows(messages) { + return Array.from(historyRowStream(messages)) +} + +// Compare one normalized row at a time. JSON equality is the fallback for +// blocks with equivalent wire representations (e.g. omitted undefined fields). +function sameHistory(expected, actual) { + const other = historyRowStream(actual) + for (const row of historyRowStream(expected)) { + const next = other.next() + if (next.done || row.role !== next.value.role || row.content.length !== next.value.content.length) return false + for (let i = 0; i < row.content.length; i++) { + const a = row.content[i], b = next.value.content[i] + if (!isDeepStrictEqual(a, b) && stableJSON(a) !== stableJSON(b)) return false + } + } + return other.next().done +} + +// Preserve the digest already on disk. stableJSON sorts "content" before +// "role", and omits an undefined role, exactly as these fragments do. +function historyDigest(messages) { + const hash = createHash("sha256").update("[") + let first = true + for (const row of historyRowStream(messages)) { + hash.update(first ? '{"content":[' : ',{"content":[') + first = false + for (let i = 0; i < row.content.length; i++) { + if (i) hash.update(",") + hash.update(stableJSON(row.content[i]) ?? "null") + } + hash.update(row.role === undefined ? "]}" : '],"role":' + stableJSON(row.role) + "}") } - return rows.filter(row => row.content.length) + return hash.update("]").digest("hex") } function historyKey(messages) { @@ -7978,8 +8220,10 @@ function sessionInstructions(body, callerWorkDir) { return parts.join("\n\n") } -const QUEUED_PROMPT_PREFIX_RE = /^(?:The user sent (?:a new message while you were working|the following message)|The [^\r\n]+ plugin sent a message while you were working):\n([\s\S]*)$/ -const QUEUED_PROMPT_SUFFIX_RE = /\n\n(?:This is how Claude Code surfaces (?:messages the user sends|prompts [^\r\n]+ submits) mid-turn[\s\S]*|IMPORTANT: After completing your current task, you MUST address the user's message above\. Do not ignore it\.|Please address this message and continue with your tasks\.)\s*$/ +const USER_INTERRUPTION_PREFIX = "(?:The user sent (?:a new message while you were working|the following message)|The [^\\r\\n]+ plugin sent a message while you were working):" +const USER_INTERRUPTION_RE = new RegExp(USER_INTERRUPTION_PREFIX) +const QUEUED_PROMPT_PREFIX_RE = new RegExp(`^${USER_INTERRUPTION_PREFIX}(?:\\r?\\n|[ \\t]+)([\\s\\S]*)$`) +const QUEUED_PROMPT_SUFFIX_RE = /\r?\n\r?\n(?:This is how Claude Code surfaces (?:messages the user sends|prompts [^\r\n]+ submits) mid-turn[\s\S]*|IMPORTANT: After completing your current task, you MUST address the user's message above\. Do not ignore it\.|Please address this message and continue with your tasks\.)\s*$/ function extractQueuedPrompt(raw) { if (typeof raw !== "string") return null @@ -7987,7 +8231,7 @@ function extractQueuedPrompt(raw) { const hadPlaceholder = cleanedRaw !== raw let trimmed = cleanedRaw.trim() const reminder = /^]*)?>([\s\S]*)<\/system-reminder(?:\s[^>]*)?>$/.exec(trimmed) - if (reminder) trimmed = reminder[1].trim() + if (reminder && !asciiLower(reminder[1]).includes(" block?.type === "tool_result") } +// Mid-turn user prompts absorbed beside a tool_result (Claude Code queues +// user/plugin messages as text blocks inside the next tool_result message). +// Non-steer companions (DSH notes, skill instructions, hook output, plain +// system-reminders, or quotes inside a tool_result body) return []. +function extractQueuedUserTexts(message) { + if (message?.role !== "user" || !isToolResultMessage(message) || !Array.isArray(message.content)) return [] + const out = [] + for (const block of message.content) { + if (block?.type !== "text" || typeof block.text !== "string") continue + const direct = extractQueuedPrompt(block.text) + if (direct !== null) { + if (!isMetaOnlyUserText(direct)) out.push(direct) + continue + } + if (!asciiLower(block.text).includes(" 0 +} + +// Render only the queued mid-turn prompt(s) carried beside a tool_result so +// a trimmed replay can keep the steer without dragging an oversized (and +// otherwise omitted) tool_result into the budget. +function renderQueuedSteerEntry(message, userLimit = HISTORY_BLOCK_CLIP_BYTES) { + const texts = extractQueuedUserTexts(message) + if (!texts.length) return null + const clipped = userLimit > HISTORY_BLOCK_CLIP_BYTES + ? texts.map((text) => clipMiddle(text, userLimit)) + : texts.map(clipHistoryText) + const parts = [{ type: "text", text: `Human: ${clipped.join("\n\n")}\n` }] + return { parts, bytes: promptTextBytes(parts) } +} + // Bytes of a user message's own text, without the meta notes around it. function userTextBytes(message) { if (typeof message?.content === "string") return isMetaOnlyUserText(message.content) ? 0 : utf8Bytes(message.content) if (!Array.isArray(message?.content)) return 0 + if (isToolResultMessage(message)) { + return extractQueuedUserTexts(message).reduce((sum, text) => sum + utf8Bytes(text), 0) + } return message.content.reduce((sum, block) => { const text = blockText(block) return sum + (text && !isMetaOnlyUserText(text) ? utf8Bytes(text) : 0) }, 0) } -// A user message with no tool result and something the user wrote or attached. +// A user message with something the user wrote or attached, including a +// mid-turn user steer absorbed beside a tool_result. function isUserTask(message) { if (message?.role !== "user") return false if (typeof message.content === "string") return !isMetaOnlyUserText(message.content) - if (!Array.isArray(message.content) || isToolResultMessage(message)) return false + if (!Array.isArray(message.content)) return false + if (isToolResultMessage(message)) return hasQueuedUserSteer(message) if (message.content.some((block) => block?.type === "image")) return true return message.content.some((block) => !isMetaOnlyUserText(blockText(block))) } @@ -8690,6 +8985,12 @@ function lastCompletedTurnEnd(history) { // least one message in it is a user task; null when the run is meta-only. function userTurnRun(history, index) { if (index < 0 || index >= history.length) return null + if (isToolResultMessage(history[index])) { + if (!hasQueuedUserSteer(history[index])) return null + // Index 0 is already kept as the opening anchor, matching the loop below. + const list = index === 0 ? [] : [index] + return { all: list, tasks: list, rest: [] } + } let start = index while (start > 0 && history[start - 1].role !== "assistant" && !isToolResultMessage(history[start - 1])) start-- let end = index + 1 @@ -8854,9 +9155,10 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve // blocks clipped first (#1055). let entries = raw let keptIndices = entries.map((_, i) => i) + let blockLimit = HISTORY_BLOCK_CLIP_BYTES const sessionState = overRoom(entries) ? sessionStateIndices(history, current) : { priority: [], set: new Set() } if (overRoom(entries)) { - const blockLimit = Math.max(HISTORY_BLOCK_CLIP_BYTES, Math.floor(room / 3)) + blockLimit = Math.max(HISTORY_BLOCK_CLIP_BYTES, Math.floor(room / 3)) entries = history.map((message, i) => render(clipHistoryMessage(message, blockLimit, sessionState.set.has(i)))) } let kept = entries @@ -8881,12 +9183,27 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve if (entries.length && keptSliceBytes([0], entries.length, entries, noteBytes) <= room) { keep.push(0) } + const steerCache = new Map() + const steerEntryFor = (idx) => { + if (!steerCache.has(idx)) steerCache.set(idx, renderQueuedSteerEntry(history[idx], blockLimit)) + return steerCache.get(idx) + } + const swappedSteers = new Map() // Mid tool loop, the user's prompt run that started it says what the loop is // for (plus any later user steer run): keep it after the anchor, with a note // for each gap (#1053, #1055). if (inToolLoop) { const runs = [loopOpeningRun(history, loopStart), latestLoopTaskRun(history, loopStart)].filter(Boolean) - const whole = [...new Set([...keep, ...runs.flatMap((run) => run.all)])].sort((a, b) => a - b) + const runIndices = [...new Set(runs.flatMap((run) => run.all))] + for (const idx of runIndices) { + if (keep.includes(idx)) continue + const steerEntry = steerEntryFor(idx) + if (steerEntry) { + swappedSteers.set(idx, entries[idx]) + entries[idx] = steerEntry + } + } + const whole = [...new Set([...keep, ...runIndices])].sort((a, b) => a - b) if (whole.length > keep.length && keptSliceBytes(whole, entries.length, entries, noteBytes) <= room) { keep = whole } else { @@ -8897,6 +9214,12 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve if (keptSliceBytes(nextKeep, entries.length, entries, noteBytes) <= room) keep = nextKeep } } + for (const [idx, full] of swappedSteers) { + if (!keep.includes(idx)) { + entries[idx] = full + swappedSteers.delete(idx) + } + } } // A short follow-up ("快点", "继续") as the newest request carries no // task of its own; it points back at one an earlier turn asked for. @@ -8914,7 +9237,10 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve for (let i = entries.length - 1; i > 0 && pinTarget < 0; i--) { if (!keep.includes(i) && isUserTask(history[i])) pinTarget = i } - const pinFirstBytes = Math.max(PINNED_USER_TASK_CLIP_BYTES, pinTarget > 0 ? entries[pinTarget].bytes : 0) + const pinFirstBytes = Math.max( + PINNED_USER_TASK_CLIP_BYTES, + pinTarget > 0 ? (steerEntryFor(pinTarget)?.bytes ?? entries[pinTarget].bytes) : 0, + ) const pinReserve = newestBytes >= 0 && newestBytes <= NUDGE_MAX_BYTES ? Math.min(PINNED_USER_TASKS_BYTES - PINNED_USER_TASK_CLIP_BYTES + pinFirstBytes, Math.floor(room / (pinFirstBytes > PINNED_USER_TASK_CLIP_BYTES ? 3 : 4))) @@ -8978,28 +9304,54 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve for (let idx = (tail.length ? tail[0] : entries.length) - 1; idx > 0 && pinned < PINNED_USER_TASKS_MAX; idx--) { if (keep.includes(idx) || tail.includes(idx) || !isUserTask(history[idx])) continue const saved = entries[idx] + const steer = steerEntryFor(idx) + const base = steer ?? saved // the first (newest) pin may take what the reserve has left; older ones are clipped const limit = pinned ? PINNED_USER_TASK_CLIP_BYTES : Math.max(PINNED_USER_TASK_CLIP_BYTES, pinReserve - pinnedBytes) - if (saved.bytes > limit) entries[idx] = clipHistoryEntry(saved, limit) + entries[idx] = base.bytes > limit ? clipHistoryEntry(base, limit) : base const nextKeep = [...keep, idx].sort((x, y) => x - y) if (pinnedBytes + entries[idx].bytes <= pinReserve && combinedFits(nextKeep)) { keep = nextKeep pinned++ pinnedBytes += entries[idx].bytes + if (steer) swappedSteers.set(idx, saved) } else { entries[idx] = saved } } } + // If a pinned mixed tool_result+steer entry (from either the tool-loop + // run or pinReserve) sits right against the kept tail with no gap and its + // full entry still fits, restore the tool_result. + for (const [idx, full] of swappedSteers) { + if (idx !== entries.length - 1 && (!tail.length || idx !== tail[0] - 1)) continue + const steerOnly = entries[idx] + entries[idx] = full + if (combinedFits(keep)) swappedSteers.delete(idx) + else entries[idx] = steerOnly + } // Mid tool loop the tail stops at the task that opened the loop, so the // turns before it got only their user tasks: a 500 KB history kept 10 KB, // and the model, with nothing of what it had just read or done, read // and checked it all again (plugins#1401). They get the room left over, // newest first. Unused stateReserve is reclaimed the same way. + // Any steer-only entry encountered during backfill tries to restore its + // full tool_result first so steer-only stays a fallback for tight budgets + // rather than dropping a newer result while backfilling older ones. const fillStart = inToolLoop - ? floor - 1 + ? floor : (stateReserve > 0 ? (tail.length ? tail[0] : entries.length) - 1 : 0) for (let idx = fillStart; idx > 0; idx--) { + if (swappedSteers.has(idx)) { + const steerOnly = entries[idx] + entries[idx] = swappedSteers.get(idx) + if (combinedFits(keep)) { + swappedSteers.delete(idx) + continue + } + entries[idx] = steerOnly + break + } if (keep.includes(idx) || tail.includes(idx)) continue const nextKeep = [...keep, idx].sort((x, y) => x - y) if (!combinedFits(nextKeep)) break @@ -9286,7 +9638,7 @@ function inspectToolTurn(results, body) { let resultIndex = -1 const stoppedByHookOrUser = out.some((item) => item.result?.isError && /^(?:The user doesn't want to proceed with this tool use\.|User rejected tool use\b|Operation stopped by hook\b|Execution stopped by hook\b|Blocked by PreToolUse hook\b|Hook PreToolUse:\S+ denied\b|API Error: Request was aborted\.|\[Request interrupted by user\b)/.test(resultText(item.result).trim())) - const userInterruption = /(?:The user sent (?:a new message while you were working|the following message)|The [^\r\n]+ plugin sent a message while you were working):/ + const userInterruption = USER_INTERRUPTION_RE const nonUserSourceNotice = /^\[MESSAGE FROM NON-USER SOURCE - NOT USER INPUT\]\s*\n/ const skillCompanion = /^\s*(?:Base directory for this skill:|ARGUMENTS:|Skill arguments:) / const imageCompanion = /^\[Image(?: source)?: [^\r\n]+\]$/ @@ -9550,18 +9902,50 @@ function workDirectory(directory) { return null } +// The control server every agy's MCP server connects to. One that closed or +// failed is made again, on the port it had when that is free: it was kept +// for the host's life, so a server gone for any reason left every later +// session without the client's tools until magpie restarted (#1766). function ensureControlServer() { + if (controlServerPromise && controlServer && !controlServer.listening) dropControlServer(controlServer) if (controlServerPromise) return controlServerPromise - controlServerPromise = new Promise((resolve, reject) => { + const want = controlPort + const promise = listenControl(want).catch((error) => { + if (want && error?.code === "EADDRINUSE") return listenControl(0) + throw error + }) + controlServerPromise = promise + promise.catch(() => { if (controlServerPromise === promise) controlServerPromise = null }) + return promise +} + +function listenControl(port) { + return new Promise((resolve, reject) => { const server = net.createServer((socket) => handleControlConnection(socket)) server.once("error", reject) - server.listen(0, "127.0.0.1", () => { + server.listen(port, "127.0.0.1", () => { + server.off("error", reject) + // An error once listening (no listener would end the host) or a + // close: the next agy or request makes it again. + server.on("error", () => { + dropControlServer(server) + try { server.close() } catch {} + }) + server.on("close", () => dropControlServer(server)) + const bound = server.address().port + if (controlPort && bound !== controlPort) bridgeEpoch++ + controlPort = bound controlServer = server server.unref() - resolve(server.address().port) + resolve(bound) }) }) - return controlServerPromise +} + +function dropControlServer(server) { + if (controlServer !== server) return + controlServer = undefined + controlServerPromise = null } function tokenMatches(left, right) { @@ -10607,13 +10991,24 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a const sentEstimate = Math.max(1, sessionOverhead + estimatePromptPartsTokens(contentParts) + seeds.reduce((sum, parts) => sum + estimatePromptPartsTokens(parts), 0)) const clipThreshold = Math.min(HISTORY_BLOCK_CLIP_BYTES, maxInitialPromptBytes()) - const promptClipped = utf8Bytes(JSON.stringify(messages)) > clipThreshold && - rawEstimate > sentEstimate + 64 + const promptClipped = rawEstimate > sentEstimate + 64 && + messagesExceedBytes(messages, clipThreshold) proc.omittedHistoryTokens = promptClipped ? rawEstimate - sentEstimate : 0 } return proc.startTurn(contentParts, body.messages, model, selection, seeds) } +// Only a threshold is needed here. Stringifying all the history again +// doubles the body at its peak and can exceed the JS runtime's string size. +function messagesExceedBytes(messages, limit) { + let bytes = 1 + for (const message of messages) { + bytes += 1 + utf8Bytes(JSON.stringify(message)) + if (bytes > limit) return true + } + return Math.max(bytes, 2) > limit +} + // A magpie that installs a plugin's CLI (auth.cli) installs agy before it // gets here; an older one, or OpenCode, doesn't. function noAgy() { @@ -10819,7 +11214,8 @@ const usageReaders = new Map() // The accounts of agy's own told agy holds another (by email, lower case): // a read once agy holds them again says the sign-in works. const toldNotHeld = new Set() -function readUsageOf(home, email = "") { +// printOnly: agy -p /usage alone (usage.mjs's fetchUsage) +function readUsageOf(home, email = "", printOnly = false) { const key = home ?? "" let read = usageReaders.get(key) if (!read) usageReaders.set(key, (read = createUsageReader(findAgy, { geminiDir: usageGeminiDir }))) @@ -10830,12 +11226,12 @@ function readUsageOf(home, email = "") { // out of reach, or agy's sign-in can't say whose it is (#1599): read // with the sign-in kept for it, when there is one const kept = stored?.state === "unreachable" || ownerUnknown(stored) ? keptFor(email) : null - if (kept) return readUsageOf(kept) + if (kept) return readUsageOf(kept, "", printOnly) if (ownerUnknown(stored) && anotherOwn(email)) return { windows: [], error: unknownOwnerError(email), signIn: "expired" } if (heldByAnother(stored, email)) { // kept while agy held it: read with its own sign-in const kept = keptFor(email) - const result = kept ? await readUsageOf(kept) : null + const result = kept ? await readUsageOf(kept, "", printOnly) : null if (result && result.signIn !== "expired") { return toldNotHeld.delete(email.toLowerCase()) && result.signIn === "kept" ? { ...result, signIn: "renewed" } : result } @@ -10848,7 +11244,7 @@ function readUsageOf(home, email = "") { // windows map its own models even when usage runs before models(). const agy = findAgy() if (agy) useAgyPath(agy) - const result = await read() + const result = await read({ printOnly }) if (email && !result.error && toldNotHeld.delete(email.toLowerCase()) && result.signIn === "kept") { return { ...result, signIn: "renewed" } } @@ -10880,12 +11276,14 @@ export const AntigravityBridgePlugin = async () => { }, }, // Magpie's usage hook; OpenCode ignores this extension. agy owns auth. - usage: async (getAuth) => { + // printOnly (magpie's reading the user asked for): agy -p /usage + // alone, never agy acp or agy's TUI in its place + usage: async (getAuth, _provider, { printOnly = false } = {}) => { const { home, email, given } = await accountOfAuth(getAuth) // saved without its email, beside another account of agy's own: // whose agy's sign-in is can't be told for it (#1599) if (given && !home && !email && anotherOwn("")) return { windows: [], error: unknownOwnerError(""), signIn: "expired" } - return readUsageOf(home, email) + return readUsageOf(home, email, printOnly === true) }, // magpie's "Import accounts from a file…" (OpenCode ignores it): the // retired Antigravity plugin's sign-ins, which magpie's Move hands over @@ -11044,8 +11442,8 @@ export const AntigravityBridgePlugin = async () => { }) } const saidEffort = requestHeader(fetchInput, init, "x-magpie-effort") - const listed = await loadModelCatalog(agy) - const model = resolveAgyModel(listed, requestedModel, body, saidEffort) + let listed = await loadModelCatalog(agy) + let model = resolveAgyModel(listed, requestedModel, body, saidEffort) // a family alias stands in for a model only no account has, and an // unaliased model missing from this account's fresh catalog fails // fast before spawning agy when another signed-in account lists it (#1542) @@ -11053,11 +11451,24 @@ export const AntigravityBridgePlugin = async () => { const aliasOf = resolveCatalogAlias(routing, requestedModel).id const aliased = aliasOf !== requestedModel && !requestedModel.startsWith(aliasOf + "-") const current = ms().cachedModelCatalog - const liveOffer = Boolean(ms().acpOfferedModels && !ms().offeredStale) const liveList = !current.isFallback && current.fetchedAt > 0 && Date.now() - current.fetchedAt < MODEL_CATALOG_TTL_MS - const knownCatalog = liveOffer ? listed : liveList ? routing : null - const missingHere = aliased || (knownCatalog !== null && !catalogHasModel(knownCatalog, requestedModel)) + const offerLacks = () => Boolean(ms().acpOfferedModels && !ms().offeredStale) && !catalogHasModel(listed, requestedModel) + const missing = () => aliased || offerLacks() || + (!(ms().acpOfferedModels && !ms().offeredStale) && liveList && !catalogHasModel(listed.routing ?? listed, requestedModel)) + let missingHere = missing() + // what agy acp offered may be short of what it offers now + // (plugins#1804): a model `agy models` lists for this account + // has its offer asked again before the request is turned away. + // An offer that couldn't be read is unknown, and the request + // goes on by the listing. + if (missingHere && !aliased && offerLacks() && catalogHasModel(routing, requestedModel) && + anotherAccountLists(agy, requestedModel)) { + await recheckOffer(agy) + listed = catalogOf(ms().cachedModelCatalog) + model = resolveAgyModel(listed, requestedModel, body, saidEffort) + missingHere = missing() + } if (missingHere && anotherAccountLists(agy, requestedModel)) { return jsonError(400, `agy bridge: model ${requestedModel} is unavailable to this agy account; another signed-in agy account lists it`) } @@ -11459,7 +11870,12 @@ export const AntigravityBridgePlugin = async () => { // asked what it offers. magpie keeps the list it had and the // user's picks with it; a cold host's short list dropped every // other pick (Archivemylife on X: the picks didn't stick). - if (ms().cachedModelCatalog.isFallback || (!ms().acpOfferedModels && (ms().modelCatalogRefreshPromise || ms().offeredProbePromise))) { + // So is an offer from before (saved by an earlier run, past its + // hour, or put in doubt by a session's update) while agy acp is + // asked again: a host restarted froze a short saved offer into + // magpie's list though the probe had the full one seconds later + // (plugins#1804). + if (ms().cachedModelCatalog.isFallback || ((!ms().acpOfferedModels || ms().offeredStale) && (ms().modelCatalogRefreshPromise || ms().offeredProbePromise))) { out[Symbol.for("magpie.fellBack")] = true } for (const model of catalog.models) { diff --git a/install.mjs b/install.mjs index 46e1464..c47c395 100644 --- a/install.mjs +++ b/install.mjs @@ -89,18 +89,17 @@ function checkReleaseVersion(version) { if (tooOld) throw new Error(tooOld) } -// drained waits for a full stream to take more, and leaves no listener -// behind: one per wait piled up past Node's limit of 10 on a 260MB agy. -export function drained(out) { - return new Promise((resolve, reject) => { - const done = (error) => { - out.off("drain", done) - out.off("error", done) - error ? reject(error) : resolve() - } - out.on("drain", done) - out.on("error", done) - }) +// withOutput gives fill a write(chunk) for file that awaits the disk, and +// returns only once the handle has closed (a WriteStream's `finish` comes +// while the fd is still open for writing: ETXTBSY on Linux), failing if +// the write or the close does, after the partial file is closed. +async function withOutput(file, mode, fill) { + const handle = await fs.promises.open(file, "w", mode) + try { + await fill((chunk) => handle.writeFile(chunk)) + } finally { + await handle.close() + } } // download writes url to file, hashing as it goes, and returns the sha512. @@ -108,17 +107,12 @@ async function download(url, file, signal) { const res = await fetch(url, { signal }) if (!res.ok || !res.body) throw new Error(`downloading agy failed: ${res.status}`) const hash = createHash("sha512") - const out = fs.createWriteStream(file, { mode: 0o600 }) - const wrote = new Promise((resolve, reject) => { out.on("finish", resolve); out.on("error", reject) }) - try { + await withOutput(file, 0o600, async (write) => { for await (const chunk of res.body) { hash.update(chunk) - if (!out.write(chunk)) await drained(out) + await write(chunk) } - } finally { - out.end() - } - await wrote + }) return hash.digest("hex") } @@ -182,14 +176,7 @@ export async function untarMember(archive, name, file) { const entry = (longName ?? (prefix ? prefix + "/" + field(0, 100) : field(0, 100))).replace(/^\.\//, "") longName = null if ((type === "0" || type === "7") && entry === name) { - const out = fs.createWriteStream(file, { mode: 0o755 }) - try { - await pass(size, async (c) => { - if (!out.write(c)) await drained(out) - }) - } finally { - await new Promise((resolve, reject) => out.end((error) => (error ? reject(error) : resolve()))) - } + await withOutput(file, 0o755, (write) => pass(size, write)) return true } await pass(size + pad, skip) diff --git a/install.test.mjs b/install.test.mjs index d8f96e1..c9e4f86 100644 --- a/install.test.mjs +++ b/install.test.mjs @@ -8,8 +8,7 @@ import fs from "node:fs" import os from "node:os" import path from "node:path" import { gzipSync } from "node:zlib" -import { EventEmitter } from "node:events" -import { agyPlatform, drained, installAgy, installedVersion, untarMember, updateOwnAgy } from "./install.mjs" +import { agyPlatform, installAgy, installedVersion, untarMember, updateOwnAgy } from "./install.mjs" import { agyCandidates, ownAgyPath } from "./platform.mjs" const unix = process.platform !== "win32" @@ -47,6 +46,31 @@ let manifest = null let slow = false let root +// failClose makes close() of the file install.mjs opens in dir with the +// given mode (0o600 the download, 0o755 the binary taken out of its +// archive) close for real, then fail with error: an installer that moved +// on before close() resolved installs a binary it never saw closed. +// It's restored after each test: fs.promises is one object. +function failClose(dir, mode, error) { + const real = fs.promises.open + const closed = [] + fs.promises.open = async (file, flags, openMode) => { + const handle = await real(file, flags, openMode) + if (openMode !== mode || path.dirname(file) !== dir) return handle + const close = handle.close.bind(handle) + handle.close = async () => { + await close() + closed.push(file) + throw new Error(error) + } + return handle + } + return { + closed, + restore: () => { fs.promises.open = real }, + } +} + beforeAll(() => { server = Bun.serve({ port: 0, @@ -197,19 +221,36 @@ test.if(unix)("only the plugin's own copy is kept current, and not when the user expect(installedVersion(bin)).toBe("1.6.0") }) -test("waiting on a full stream leaves no listener behind", async () => { - // a 260MB agy waits thousands of times; each wait used to leave an - // error listener (MaxListenersExceededWarning in magpie's container) - const out = new EventEmitter() - for (let i = 0; i < 20; i++) { - const wait = drained(out) - out.emit("drain") - await wait - } - expect(out.listenerCount("error")).toBe(0) - expect(out.listenerCount("drain")).toBe(0) - const failed = drained(out) - out.emit("error", new Error("disk full")) - await expect(failed).rejects.toThrow("disk full") - expect(out.listenerCount("drain")).toBe(0) -}) +// Both ways a release arrives (the binary inside its archive, or a raw +// file) are written through a handle whose close the installer awaits +// before the staged binary is run or renamed: a WriteStream's `finish` +// came first, and Linux won't exec a file still open for writing +// (ETXTBSY). A close that fails must fail the install, not be left +// behind it. +for (const [kind, mode] of [["archive", 0o755], ["raw", 0o600]]) { + test.if(unix)(`${kind}: a staged binary whose close fails isn't installed; the old one stays`, async () => { + const bin = path.join(root, "agy") + release("1.5.19") + await installAgy({ bin, platform: "linux_amd64" }) + const before = fs.readFileSync(bin) + if (kind === "archive") release("1.5.20") + else { + const body = script("1.5.20") + files.set("/r/raw", body) + manifest = { version: "1.5.20", url: "/r/raw", sha512: sha(body) } + } + const failing = failClose(root, mode, "close: disk gone") + try { + await expect(installAgy({ bin, platform: "linux_amd64" })).rejects.toThrow("close: disk gone") + // closed for real (the fixture file), once, before the failure + expect(fs.readFileSync(bin).equals(before)).toBe(true) + expect(Bun.spawnSync([bin]).stdout.toString()).toContain("agy 1.5.19") + expect(installedVersion(bin)).toBe("1.5.19") + expect(fs.readdirSync(root).sort()).toEqual(["agy", "agy.version"]) + expect(failing.closed.length).toBe(1) + expect(path.dirname(failing.closed[0])).toBe(root) + } finally { + failing.restore() + } + }) +} diff --git a/package.json b/package.json index bba5650..ae76255 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.178", + "version": "0.1.186", "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/test/bridge-heal.mjs b/test/bridge-heal.mjs new file mode 100644 index 0000000..b0878dc --- /dev/null +++ b/test/bridge-heal.mjs @@ -0,0 +1,186 @@ +// plugins#1766: after about an hour on macOS every agy-cli account failed +// with tools_not_loaded until magpie restarted. The bridge made its `nc` +// shim dir and its control server once for the host's life: with the dir +// gone ($TMPDIR cleaned) agy ran whatever `nc` came next in PATH, and a +// closed control server was handed to every later agy. Both are checked +// before each agy and request now and made again, in the same place where +// that is safe, so the next turn works without a restart. +// +// bun test ./bridge-heal.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 LINUX = { platform: "linux" } + +// As agy does: it runs `nc` from PATH, and only the bridge's own shim, there +// and executable, reaches the MCP server. Anything else lists nothing. +function shimFirst(env) { + const file = path.join(String(env.PATH).split(path.delimiter)[0], "nc") + try { + if (!fs.statSync(file).isFile() || !fs.statSync(file).size) return false + fs.accessSync(file, fs.constants.X_OK) + return true + } catch { + return false + } +} + +async function withKit(options, fn) { + const kit = await createBridgeKit({ + ...LINUX, listTools: shimFirst, ...options, + env: { AGY_BRIDGE_TOOL_LIST_WAIT_MS: "200", ...(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 shimDirOf = (spawn) => String(spawn.env.PATH).split(path.delimiter)[0] +const portOf = (spawn) => Number(spawn.env.AGY_BRIDGE_CONTROL_PORT) +const conversation = (name, extra = {}) => baseBody({ tools: [READ_TOOL], system: name, messages: [{ role: "user", content: name }], ...extra }) +const followUp = (name) => baseBody({ + tools: [READ_TOOL], system: name, + messages: [{ role: "user", content: name }, { role: "assistant", content: "ok" }, { role: "user", content: "again" }], +}) + +async function ok(kit, body) { + const parsed = await readSse(await kit.request(body)) + assert.equal(parsed.error, null, JSON.stringify(parsed.error)) + assert.equal(parsed.stopReason, "end_turn") + return parsed +} + +test("the shim dir taken between two turns is made again where it was, and the next turn lists the tools", async () => { + await withKit({}, async (kit) => { + await ok(kit, conversation("one")) + const dir = shimDirOf(kit.acpSpawns[0]) + assert.ok(shimFirst(kit.acpSpawns[0].env), "the first agy never had the shim") + // what a temp cleaner does + fs.rmSync(dir, { recursive: true, force: true }) + + await ok(kit, conversation("two")) + assert.equal(kit.acpSpawns.length, 2) + assert.equal(shimDirOf(kit.acpSpawns[1]), dir, "the shim moved, leaving the agy already started on the old dir") + assert.ok(shimFirst(kit.acpSpawns[1].env)) + assert.equal(fs.statSync(dir).mode & 0o777, 0o700) + assert.ok(kit.listings.some((listing) => listing.spawn === 1 && listing.tools.includes("Read")), + `the second agy never listed Read: ${JSON.stringify(kit.listings)}`) + }) +}) + +test("a shim left without its execute bit is written again", { skip: process.platform === "win32" }, async () => { + await withKit({}, async (kit) => { + await ok(kit, conversation("one")) + const file = path.join(shimDirOf(kit.acpSpawns[0]), "nc") + fs.chmodSync(file, 0o600) + await ok(kit, conversation("two")) + assert.ok(shimFirst(kit.acpSpawns[1].env)) + }) +}) + +test("a shim dir someone else holds now is left for a new one, and an agy on the old one is not reused", async () => { + await withKit({}, async (kit) => { + await ok(kit, conversation("one")) + const dir = shimDirOf(kit.acpSpawns[0]) + // the freed name taken by a dir anyone can write (Linux's shared /tmp) + fs.rmSync(dir, { recursive: true, force: true }) + fs.mkdirSync(dir) + fs.chmodSync(dir, 0o777) + await ok(kit, followUp("one")) + assert.equal(kit.acpSpawns.length, 2, "the follow-up stayed on the agy whose `nc` reaches nothing") + const moved = shimDirOf(kit.acpSpawns[1]) + assert.notEqual(moved, dir) + assert.ok(shimFirst(kit.acpSpawns[1].env)) + assert.equal(fs.existsSync(path.join(dir, "nc")), false, "a shim was written into a dir others can write") + }) +}) + +test("a control server that closed between two turns is made again on its port, and the live agy reaches it", async () => { + await withKit({}, async (kit) => { + await ok(kit, conversation("one")) + const port = portOf(kit.acpSpawns[0]) + kit.controlServer().close() + await new Promise((resolve) => setImmediate(resolve)) + + // the live agy of "one" calls the bridge again on its own port + kit.prompts[1] = async (agent) => { + const reply = await agent.listTools() + assert.ok((reply?.result?.tools || []).some((tool) => tool.name === "Read"), `no tools: ${JSON.stringify(reply)}`) + await agent.text("ok") + return { stopReason: "end_turn" } + } + await ok(kit, followUp("one")) + assert.equal(kit.acpSpawns.length, 1) + assert.equal(kit.controlServer()?.port, port) + + await ok(kit, conversation("two")) + assert.equal(portOf(kit.acpSpawns[1]), port) + assert.ok(kit.listings.some((listing) => listing.spawn === 1 && listing.tools.includes("Read"))) + }) +}) + +test("a control server whose port was taken meanwhile listens on another, and the agy on the old port is replaced", async () => { + await withKit({}, async (kit) => { + await ok(kit, conversation("one")) + const port = portOf(kit.acpSpawns[0]) + kit.controlServer().close() + kit.busyPorts.add(port) + await new Promise((resolve) => setImmediate(resolve)) + + await ok(kit, followUp("one")) + assert.equal(kit.acpSpawns.length, 2, "the follow-up stayed on an agy whose port reaches nothing") + assert.notEqual(portOf(kit.acpSpawns[1]), port) + assert.equal(portOf(kit.acpSpawns[1]), kit.controlServer().port) + assert.ok(kit.listings.some((listing) => listing.spawn === 1 && listing.tools.includes("Read"))) + }) +}) + +test("tools_not_loaded from a shim gone as agy started says why, names the plugin's own shim, and the next try heals", async () => { + let taken = false + const listTools = (env) => { + if (!taken) { + taken = true + fs.rmSync(shimDirOf({ env }), { recursive: true, force: true }) + kit.acpSpawns.at(-1).child.stderr.emit("data", "mcp: ide-tools: exited before answering\n") + } + return shimFirst(env) + } + let kit + await withKit({ listTools }, async (made) => { + kit = made + const response = await kit.request(conversation("one")) + const text = await response.text() + assert.equal(response.status, 502, text) + const message = JSON.parse(text).error.message + assert.match(message, /agy never loaded the request's 1 tool:/) + assert.match(message, /this plugin's own `nc` shim \(not a netcat installed on this computer\)/) + assert.match(message, /nc shim: missing/) + assert.match(message, /control port \d+: listening/) + assert.match(message, /made again, the next try uses it/) + assert.match(message, /agy stderr: mcp: ide-tools: exited before answering/) + + await ok(kit, conversation("one")) + assert.ok(kit.listings.some((listing) => listing.tools.includes("Read"))) + }) +}) + +test("tools_not_loaded with the shim and the control server fine says so", async () => { + await withKit({ listTools: false }, async (kit) => { + const response = await kit.request(conversation("one")) + const text = await response.text() + assert.equal(response.status, 502, text) + const message = JSON.parse(text).error.message + assert.match(message, /nc shim: ok; its runtime: ok; MCP server: ok; control port \d+: listening; agy stderr: \(empty\)/) + assert.doesNotMatch(message, /made again/) + }) +}) diff --git a/test/catalog.mjs b/test/catalog.mjs index 2ef7394..727f578 100644 --- a/test/catalog.mjs +++ b/test/catalog.mjs @@ -196,6 +196,44 @@ test("an account of agy's own that agy no longer holds shows no other account's } }) +// plugins#1824: magpie reads agy's usage only when the user asks, and then +// through agy -p /usage alone (printOnly). An account agy -p calls +// ineligible keeps the refusal: neither agy acp nor agy's TUI is started +// for the quota, as they are for a read that doesn't ask so. +test("a printOnly usage read runs agy -p /usage alone, never agy acp or agy's TUI", async () => { + const keyring = "go-keyring-base64:" + Buffer.from(JSON.stringify({ + token: { access_token: "ya29.a", refresh_token: "1//r", expiry: "0001-01-01T00:00:00Z" }, + auth_method: "consumer", id_token_email: "a@example.com", + })).toString("base64") + "\n" + const refusal = JSON.stringify({ status: "ERROR", response: "", error: "Eligibility check failed: Your current account is not eligible for Gemini Code Assist for individuals because it is not currently available in your location." }) + const a = { type: "oauth", key: "agy", metadata: { email: "a@example.com" } } + const net = noFetch() + try { + for (const printOnly of [true, false]) { + const runs = [] + const options = { platform: "darwin", storedSignIn: keyring, modelsBehavior: DYNAMIC_OK } + options.onSpawn = (_file, args) => { + runs.push(args[0]) + if (args[0] === "--version") return { code: 0, stdout: "1.5.19\n" } + if (args[0] === "-p") return { code: 1, stdout: refusal + "\n" } + return 1 + } + await withKit(options, async (kit) => { + const u = await kit.plugin.auth.usage(async () => a, {}, printOnly ? { printOnly } : undefined) + assert.match(u.error, /not eligible/, JSON.stringify(u)) + assert.deepEqual(runs.filter(r => r !== "--help"), ["--version", "-p"]) + const acp = kit.acpSpawns.filter(s => !s.args.includes("--help")).length + if (printOnly) assert.equal(acp, 0, "a printOnly read started agy acp") + else assert.ok(acp > 0, "the read that may fall back never started agy acp: this test proves nothing") + await settle(kit) + }) + } + assert.deepEqual(net.fetched, [], "usage asked Google itself") + } finally { + net.restore() + } +}) + // ownsh1p on X again (为什么不能两个都显示额度呢): an account of agy's own // that agy held once keeps its own sign-in, so when agy holds another its // card reads its own quota, and its requests run agy with its own sign-in, @@ -1136,6 +1174,129 @@ test("unaliased models missing from this account fail fast without spawning agy }) }) +// plugins#1804 (holEeast979): four Pro accounts all offered Gemini 4 Neon +// and Carbon. One account's saved offer lost them while agy's calls to its +// service failed, and requests for gemini-4-carbon were turned away with +// "another signed-in agy account lists it" for the offer's hour, though +// `agy models` and a fresh agy acp session on it listed both. +const PRO_1804 = [ + ["gemini-4-neon-high", "Gemini 4 Neon (High)"], ["gemini-4-neon-low", "Gemini 4 Neon (Low)"], + ["gemini-4-carbon-high", "Gemini 4 Carbon (High)"], ["gemini-4-carbon-low", "Gemini 4 Carbon (Low)"], + ["gemini-4-hydrogen-high", "Gemini 4 Hydrogen (High)"], ["gemini-4-hydrogen-low", "Gemini 4 Hydrogen (Low)"], + ["claude-sonnet-4-6", "Claude Sonnet 4.6"], +] +const PRO_1804_SHORT = PRO_1804.filter(([id]) => !/^gemini-4-(?:neon|carbon)/.test(id)) + +function seedProPeer(kit) { + const file = path.join(kit.env.XDG_STATE_HOME, "magpie-agy-bridge", "models.json") + const data = JSON.parse(fs.readFileSync(file, "utf8")) + const own = Object.keys(data.byAgy).find(key => !key.includes("#")) + fs.mkdirSync(path.join(kit.env.XDG_STATE_HOME, "magpie-agy-bridge", "accounts", "abcdef0123456789"), { recursive: true }) + data.byAgy[`${own}#abcdef0123456789`] = { + at: kit.clock.now(), + list: PRO_1804.map(([id, name]) => ({ id, name, ...(/-(high|low)$/.exec(id) ? { effort: /-(high|low)$/.exec(id)[1] } : {}) })), + offered: PRO_1804.map(([id, name]) => ({ id, name })), + } + fs.writeFileSync(file, JSON.stringify(data)) + return { file, own } +} + +function modelSelect(ids) { + return [{ id: "model", name: "Model", category: "model", type: "select", currentValue: ids[0], options: ids.map(value => ({ value, name: value })) }] +} + +async function ask(kit, model) { + const response = await kit.request(baseBody({ model: `agy-cli/${model}`, messages: [{ role: "user", content: model }] })) + return { status: response.status, text: await response.text() } +} + +test("a session's update that loses models doesn't overwrite the account's offer (plugins#1804)", async () => { + await withKit({ modelsBehavior: { stdout: modelsOutput(PRO_1804) }, offeredModels: PRO_1804 }, async (kit) => { + await kit.models() + await warmed(kit) + await kit.models() + const { file, own } = seedProPeer(kit) + let update = null + kit.defaultPrompt = async (agent) => { + if (update) agent.update({ sessionUpdate: "config_option_update", configOptions: modelSelect(update) }) + await agent.text("ok") + return { stopReason: "end_turn" } + } + // the same families by their bare names: believed, as before + update = ["gemini-4-neon", "gemini-4-carbon", "gemini-4-hydrogen", "claude-sonnet-4-6"] + { const own = await ask(kit, "gemini-4-hydrogen"); assert.equal(own.status, 200, own.text) } + assert.deepEqual(JSON.parse(fs.readFileSync(file, "utf8")).byAgy[own].offered.map(m => m.id).sort(), [...update].sort()) + // Neon and Carbon gone mid-session: not saved, and not turned away + update = ["gemini-4-hydrogen", "claude-sonnet-4-6"] + { const own = await ask(kit, "gemini-4-hydrogen"); assert.equal(own.status, 200, own.text) } + const saved = JSON.parse(fs.readFileSync(file, "utf8")).byAgy[own].offered.map(m => m.id) + assert.ok(saved.some(id => id.startsWith("gemini-4-carbon")) && saved.some(id => id.startsWith("gemini-4-neon")), saved.join(",")) + // asked again: the next listing probes agy acp before the hour is up + // (the request's own agy stays open, so this waits on the plugin's + // warming, not on every child) + update = null + const probes = kit.acpSpawns.filter(spawn => spawn.args.length === 1).length + kit.clock.advance(60_000) + await kit.models() + await kit.plugin.provider.warming?.() + await settle(kit) + assert.equal(kit.acpSpawns.filter(spawn => spawn.args.length === 1).length, probes + 1, "the offer in doubt wasn't asked again") + assert.ok((await kit.models())["gemini-4-carbon"]) + const carbon = await ask(kit, "gemini-4-carbon") + assert.equal(carbon.status, 200, carbon.text) + }) +}) + +test("a model the offer lacks but agy models lists has the offer asked again before it is turned away (plugins#1804)", async () => { + let offer = PRO_1804_SHORT + await withKit({ modelsBehavior: { stdout: modelsOutput(PRO_1804) }, offeredModels: () => offer }, async (kit) => { + await kit.models() + await warmed(kit) + await kit.models() + seedProPeer(kit) + const probes = () => kit.acpSpawns.filter(spawn => spawn.args.length === 1).length + // the offer was short; agy acp offers Carbon again now + offer = PRO_1804 + let before = probes() + const carbon = await ask(kit, "gemini-4-carbon") + assert.equal(carbon.status, 200, carbon.text) + assert.equal(probes(), before + 1, "asked agy acp once") + + // short again (a session opened on the account says so): within five + // minutes it isn't asked again, and the request is turned away + offer = PRO_1804_SHORT + { const own = await ask(kit, "gemini-4-hydrogen"); assert.equal(own.status, 200, own.text) } + before = probes() + const soon = await ask(kit, "gemini-4-carbon") + assert.equal(soon.status, 400, soon.text) + assert.match(JSON.parse(soon.text).error.message, /unavailable to this agy account; another signed-in agy account lists it/) + assert.equal(probes(), before, "asked again within five minutes") + + // after five minutes it is asked again, and still short: turned away + kit.clock.advance(5 * 60_000) + before = probes() + const later = await ask(kit, "gemini-4-neon") + assert.equal(later.status, 400, later.text) + assert.equal(probes(), before + 1) + }) +}) + +test("a saved offer in doubt is marked fell back while agy acp is asked again (plugins#1804)", async () => { + await withKit({ modelsBehavior: { stdout: modelsOutput(PRO_1804) }, offeredModels: PRO_1804 }, async (kit) => { + await kit.models() + await warmed(kit) + assert.equal((await kit.models())[FELL_BACK], undefined) + // the offer's hour is up and the probe takes its time + kit.sessionNewDelayMs = 1_500 + kit.clock.advance(OFFERED_TTL_MS) + const stale = await kit.models() + assert.ok(kit.children.size > 0, "no probe running") + assert.equal(stale[FELL_BACK], true, "an offer past its hour, served while agy acp is asked, wasn't marked fell back") + await warmed(kit) + assert.equal((await kit.models())[FELL_BACK], undefined) + }) +}) + test("unaliased fail-fast uses fresh agy models before ACP probe and does not reject on stale or fallback catalogs", async () => { const proRows = [ ["gemini-4-hydrogen-high", "Gemini 4 Hydrogen (High)"], diff --git a/test/park-reread.mjs b/test/park-reread.mjs index 42fb850..61cbf31 100644 --- a/test/park-reread.mjs +++ b/test/park-reread.mjs @@ -1,4 +1,5 @@ import assert from "node:assert/strict" +import { createHash } from "node:crypto" import fs from "node:fs" import os from "node:os" import path from "node:path" @@ -132,3 +133,127 @@ test("the earliest conversation is still resumable after parking 40 conversation assert.equal(entries().length, 40) }) }) + +test("matching a long live history does not serialize all its rows at once", async () => { + // Count individual stringify results inside the bridge's isolated VM. + const kit = await createBridgeKit({ indexTransform: source => source + ` + export function measureHistoryMatch(expected, actual) { + const stringify = JSON.stringify + let largest = 0 + try { + JSON.stringify = (...args) => { + const s = stringify(...args) + largest = Math.max(largest, s?.length || 0) + return s + } + const matches = Proc.prototype.matchesHistory.call({ expectedMessages: expected }, actual) + return { matches, largest } + } finally { + JSON.stringify = stringify + } + }` }) + try { + const text = "x".repeat(32 * 1024) + const rows = Array.from({ length: 128 }, (_, i) => ({ + role: i % 2 ? "assistant" : "user", content: text + i, + })) + const { matches, largest } = kit.module.measureHistoryMatch(rows, structuredClone(rows)) + assert.ok(matches) + assert.ok(largest < 2 * text.length, `materialized a ${largest}-character string for 128 rows`) + } finally { + await kit.dispose() + } +}) + +test("parked history digests keep the previous canonical JSON format", async () => { + await withSharedState(async (start, entries) => { + const kit = await start() + const text = 'quotes " and newline\n羽' + await complete(kit, opening(text), FIRST_REPLY) + const rows = [ [ "user", text ], [ "assistant", FIRST_REPLY ] ].map(([role, value]) => ({ + content: [{ text: value, type: "text" }], role, + })) + const oldDigest = createHash("sha256").update(JSON.stringify(rows)).digest("hex") + assert.equal(entries()[0].historyHash, oldDigest) + assert.equal(entries()[0].historyHashSansInputs, oldDigest) + }) +}) + +test("sameHistory and historyDigest agree with historyKey across shape and length cases", async () => { + const kit = await createBridgeKit({ + indexTransform: (source) => source + "\nexport { sameHistory, historyKey, historyDigest }\n", + }) + try { + const base = [ + { role: "user", content: "first question" }, + { role: "assistant", content: [{ type: "text", text: "first answer" }] }, + { role: "user", content: "second question" }, + { role: "assistant", content: [{ type: "text", text: "second answer" }] }, + ] + const cases = [ + ["equal history", base, structuredClone(base), true], + [ + "same content with roles swapped", + [{ role: "user", content: "x" }, { role: "assistant", content: "y" }], + [{ role: "assistant", content: "x" }, { role: "user", content: "y" }], + false, + ], + ["null role differs from missing role", [{ role: null, content: "x" }], [{ content: "x" }], false], + [ + "middle edit", + base, + [base[0], { role: "assistant", content: [{ type: "text", text: "edited answer" }] }, base[2], base[3]], + false, + ], + ["shorter history", base, base.slice(0, 2), false], + ["longer history", base, [...base, { role: "user", content: "extra trailing turn" }], false], + [ + "fork", + base, + [...base.slice(0, 3), { role: "assistant", content: [{ type: "text", text: "different branch" }] }], + false, + ], + [ + "same-role run split in two", + [{ role: "user", content: "hello world" }, { role: "assistant", content: "ok" }], + [{ role: "user", content: "hello " }, { role: "user", content: "world" }, { role: "assistant", content: "ok" }], + true, + ], + ["whitespace-only trailing row", base, [...base, { role: "user", content: " \n\t " }], true], + ["whitespace-only row alone matches empty", [{ role: "user", content: " \n\t " }], [], true], + [ + "whitespace-only role switch splits same-role run", + [{ role: "user", content: "hello" }, { role: "assistant", content: " " }, { role: "user", content: "world" }], + [{ role: "user", content: "hello" }, { role: "user", content: "world" }], + false, + ], + [ + "tool_use and tool_result with renumbered ids and undefined field", + [ + { role: "assistant", content: [{ type: "tool_use", id: "call_a", name: "Read", input: { path: "a.js" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "call_a", content: "ok" }] }, + ], + [ + { role: "assistant", content: [{ type: "tool_use", id: "call_b", name: "Read", input: { path: "a.js", extra: undefined } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "call_b", content: "ok" }] }, + ], + true, + ], + ] + for (const [name, expected, actual, want] of cases) { + const got = kit.module.sameHistory(expected, actual) + const oracle = kit.module.historyKey(expected) === kit.module.historyKey(actual) + assert.equal(got, oracle, `${name}: sameHistory disagreed with historyKey`) + assert.equal(got, want, `${name}: unexpected match result`) + for (const msgs of [expected, actual]) { + assert.equal( + kit.module.historyDigest(msgs), + createHash("sha256").update(kit.module.historyKey(msgs)).digest("hex"), + `${name}: historyDigest disagreed with historyKey`, + ) + } + } + } finally { + await kit.dispose() + } +}) diff --git a/test/repeat-batch.mjs b/test/repeat-batch.mjs index b045461..644fecc 100644 --- a/test/repeat-batch.mjs +++ b/test/repeat-batch.mjs @@ -1031,6 +1031,322 @@ test("A16: under a tight budget, a mid-loop user steer beats an opening meta com }) }) +test("A16: mid tool loop keeps a queued user steer carried beside a tool_result", async () => { + const steerVariants = [ + [ + "claude-mid-turn", + "The user sent a new message while you were working:\nMID LOOP STEER: keep backward-compatible exports\n\nThis is how Claude Code surfaces messages the user sends mid-turn — within the running turn, often alongside the next tool result, rather than as a separate conversation turn. Address the message above as you continue this turn.", + ], + [ + "following-message", + "The user sent the following message:\nMID LOOP STEER: keep backward-compatible exports\n\nPlease address this message and continue with your tasks.", + ], + [ + "plugin-mid-turn", + "The review plugin sent a message while you were working:\nMID LOOP STEER: keep backward-compatible exports", + ], + [ + "reminder-wrapped", + "\nThe user sent a new message while you were working:\nMID LOOP STEER: keep backward-compatible exports\n", + ], + ] + const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail` + for (const [label, steerBlock] of steerVariants) { + await withSinglePromptKit({}, async (kit) => { + scriptedAgent(kit) + const messages = [ + { role: "user", content: "ANCHOR opening request" }, + { role: "assistant", content: "ANCHOR reply" }, + { role: "user", content: "LOOP OPENER: refactor group router" }, + ] + for (let index = 0; index < 4; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qsa_${index}`, name: "Read", input: { path: `/repo/a${index}.txt` } }] }) + const content = [{ type: "tool_result", tool_use_id: `toolu_qsa_${index}`, content: big(`qsa-${index}`) }] + if (index === 3) content.push({ type: "text", text: steerBlock }) + messages.push({ role: "user", content }) + } + for (let index = 0; index < 14; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qsb_${index}`, name: "Read", input: { path: `/repo/b${index}.txt` } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_qsb_${index}`, content: big(`qsb-${index}`) }] }) + } + messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_qs_last", name: "Read", input: { path: "/repo/last.txt" } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_qs_last", content: "LAST RESULT" }] }) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: `queued-steer-${label}` }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 112 * 1024, `${label}: initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("Human: LOOP OPENER: refactor group router"), `${label}: loop opener is kept`) + assert.ok(prompt.includes("MID LOOP STEER: keep backward-compatible exports"), `${label}: queued steer beside tool_result is kept`) + assert.ok(prompt.indexOf("LOOP OPENER") < prompt.indexOf("MID LOOP STEER"), `${label}: steer stays after opener`) + assert.ok(prompt.includes("qsa-3 head") && prompt.includes("qsa-3 tail"), `${label}: steer row's tool_result is restored before older backfill`) + assert.ok(!prompt.includes("qsa-1 tail"), `${label}: older qsa-1 gives way so newer qsa-3 is kept`) + assert.ok(prompt.includes("qsb-13 tail"), `${label}: newest tail steps stay intact`) + assert.ok(prompt.includes("LAST RESULT"), `${label}: current turn result is kept`) + }) + } +}) + +test("A16: mid tool loop falls back to steer-only when the steer row's tool_result does not fit remaining room", async () => { + await withSinglePromptKit({}, async (kit) => { + scriptedAgent(kit) + const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail` + const medium = (label) => `${label} head ` + "tail filler line with words. ".repeat(100) + ` ${label} tail` + // Long steer (> NUDGE_MAX_BYTES = 280) leaves pinReserve = 0, and ~3 KiB + // tail steps fill within ~3 KiB of the 112 KiB budget so qso-3's ~8 KiB + // clipped tool_result cannot fit in the leftover room. + const longSteer = ("MID LOOP STEER: keep backward-compatible exports across every caller, preserve existing error shapes and status codes, do not rename public symbols in the router package, and make sure every downstream consumer keeps working without any breaking contract change " + "details ".repeat(15)).trim() + const messages = [ + { role: "user", content: "ANCHOR opening request" }, + { role: "assistant", content: "ANCHOR reply" }, + { role: "user", content: "LOOP OPENER: refactor group router" }, + ] + for (let index = 0; index < 4; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qso_${index}`, name: "Read", input: { path: `/repo/o${index}.txt` } }] }) + const content = [{ type: "tool_result", tool_use_id: `toolu_qso_${index}`, content: big(`qso-${index}`) }] + if (index === 3) { + content.push({ + type: "text", + text: `The user sent a new message while you were working:\n${longSteer}\n\nThis is how Claude Code surfaces messages the user sends mid-turn — within the running turn, often alongside the next tool result, rather than as a separate conversation turn. Address the message above as you continue this turn.`, + }) + } + messages.push({ role: "user", content }) + } + for (let index = 0; index < 42; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qsob_${index}`, name: "Read", input: { path: `/repo/ob${index}.txt` } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_qsob_${index}`, content: medium(`qsob-${index}`) }] }) + } + messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_qso_last", name: "Read", input: { path: "/repo/last.txt" } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_qso_last", content: "LAST RESULT" }] }) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "queued-steer-overflow" }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 112 * 1024, `initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("Human: LOOP OPENER: refactor group router"), "loop opener is kept") + assert.ok(prompt.includes(`Human: ${longSteer}`), "falls back to unwrapped steer-only when full tool_result does not fit") + assert.ok(!prompt.includes("This is how Claude Code surfaces"), "queued prompt wrapper is unwrapped in steer-only fallback") + assert.ok(!prompt.includes("qso-3 head"), "unfitting tool_result beside the steer is omitted") + assert.ok(!prompt.includes("/repo/o3.txt") && !prompt.includes("qso-2 tail"), "older steps are not backfilled behind an unfitting newer steer result") + assert.ok(prompt.includes("qsob-41 tail"), "newest tail steps stay intact") + assert.ok(prompt.includes("LAST RESULT"), "current turn result is kept") + }) +}) + +test("A16: a recent queued steer beside a tool_result keeps its tool_result and backfills recent steps before it", async () => { + await withSinglePromptKit({}, async (kit) => { + scriptedAgent(kit) + const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail` + const messages = [ + { role: "user", content: "ANCHOR opening request" }, + { role: "assistant", content: "ANCHOR reply" }, + { role: "user", content: "LOOP OPENER: refactor group router" }, + ] + for (let index = 0; index < 16; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qtail_${index}`, name: "Read", input: { path: `/repo/t${index}.txt` } }] }) + const content = [{ type: "tool_result", tool_use_id: `toolu_qtail_${index}`, content: big(`qtail-${index}`) }] + if (index === 15) { + content.push({ + type: "text", + text: "The user sent a new message while you were working:\nRECENT STEER: also check edge cases\n\nThis is how Claude Code surfaces messages the user sends mid-turn — within the running turn, often alongside the next tool result, rather than as a separate conversation turn. Address the message above as you continue this turn.", + }) + } + messages.push({ role: "user", content }) + } + messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_qtail_last", name: "Read", input: { path: "/repo/last.txt" } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_qtail_last", content: "LAST RESULT" }] }) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "recent-queued-steer" }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 112 * 1024, `initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("Human: LOOP OPENER: refactor group router"), "loop opener is kept") + assert.ok(prompt.includes("RECENT STEER: also check edge cases"), "recent queued steer is kept") + assert.ok(prompt.includes("qtail-15 tail"), "contiguous tool_result beside recent steer is restored") + assert.ok(prompt.includes("qtail-14 tail"), "recent steps immediately before the steer are backfilled") + assert.ok(prompt.includes("LAST RESULT"), "current turn result is kept") + }) +}) + +test("A16: under a tight budget, a queued steer beside an oversized tool_result beats an opening meta companion", async () => { + await withSinglePromptKit({ AGY_BRIDGE_MAX_PROMPT_BYTES: String(8 * 1024) }, async (kit) => { + scriptedAgent(kit) + const bigReminder = "" + "r".repeat(4200) + "" + const steer = "MID LOOP STEER: keep backward-compatible exports " + "s".repeat(900) + const messages = [ + { role: "user", content: "ANCHOR opening request" }, + { role: "assistant", content: "ANCHOR reply" }, + { role: "user", content: "LOOP OPENER: refactor group router" }, + { role: "user", content: bigReminder }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_qts_0", name: "Read", input: { path: "/repo/0.txt" } }] }, + { + role: "user", + content: [ + { type: "tool_result", tool_use_id: "toolu_qts_0", content: "z".repeat(4000) }, + { + type: "text", + text: `The user sent a new message while you were working:\n${steer}\n\nThis is how Claude Code surfaces messages the user sends mid-turn — within the running turn, often alongside the next tool result, rather than as a separate conversation turn. Address the message above as you continue this turn.`, + }, + ], + }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_qts_last", name: "Read", input: { path: "/repo/last.txt" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_qts_last", content: "y".repeat(3000) + " LAST RESULT" }] }, + ] + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "tight-queued-steer" }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 8 * 1024, `initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("Human: LOOP OPENER: refactor group router"), "loop opener is kept") + assert.ok(prompt.includes("Human: MID LOOP STEER: keep backward-compatible exports"), "queued steer beats opening reminder") + assert.ok(!prompt.includes("This is how Claude Code surfaces"), "queued prompt wrapper is unwrapped in tight-budget fallback") + assert.ok(!prompt.includes(bigReminder), "oversized opening reminder gave way to fit the steer") + assert.ok(!prompt.includes("z".repeat(200)), "oversized tool_result beside the steer was dropped to fit the tight budget") + assert.ok(prompt.includes("LAST RESULT")) + }) +}) + +test("A16: a trimmed replay after a short follow-up pins an earlier queued steer carried beside a tool_result", async () => { + await withSinglePromptKit({}, async (kit) => { + scriptedAgent(kit) + const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail` + const messages = [ + { role: "user", content: "ANCHOR opening request" }, + { role: "assistant", content: "ANCHOR reply" }, + { role: "user", content: "TURN 2 OPENER: inspect routing table" }, + ] + for (let index = 0; index < 4; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qpa_${index}`, name: "Read", input: { path: `/repo/pa${index}.txt` } }] }) + const content = [{ type: "tool_result", tool_use_id: `toolu_qpa_${index}`, content: big(`qpa-${index}`) }] + if (index === 3) { + content.push({ + type: "text", + text: "The user sent a new message while you were working:\nQUEUED TASK: preserve exact error codes on retry\n\nThis is how Claude Code surfaces messages the user sends mid-turn — within the running turn, often alongside the next tool result, rather than as a separate conversation turn. Address the message above as you continue this turn.", + }) + } + messages.push({ role: "user", content }) + } + for (let index = 0; index < 14; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qpb_${index}`, name: "Read", input: { path: `/repo/pb${index}.txt` } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_qpb_${index}`, content: big(`qpb-${index}`) }] }) + } + messages.push({ role: "assistant", content: "Paused after checking the routing table." }) + messages.push({ role: "user", content: "继续" }) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "queued-nudge-pin" }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 112 * 1024, `initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("Human: QUEUED TASK: preserve exact error codes on retry"), "earlier queued steer is pinned for short follow-up") + assert.ok(!prompt.includes("qpa-3 head"), "oversized tool_result beside the pinned steer is not dragged in") + assert.ok(prompt.includes("继续")) + }) +}) + +test("A16: a pinReserve-pinned queued steer contiguous with the kept tail restores its tool_result when it fits", async () => { + await withSinglePromptKit({}, async (kit) => { + scriptedAgent(kit) + const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail` + const messages = [ + { role: "user", content: "ANCHOR opening request" }, + { role: "assistant", content: "ANCHOR reply" }, + { role: "user", content: "TURN 2 OPENER: inspect routing table" }, + ] + for (let index = 0; index < 8; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qca_${index}`, name: "Read", input: { path: `/repo/ca${index}.txt` } }] }) + const content = [{ type: "tool_result", tool_use_id: `toolu_qca_${index}`, content: big(`qca-${index}`) }] + if (index === 7) { + content.push({ + type: "text", + text: "The user sent a new message while you were working:\nCONTIGUOUS PIN STEER: keep exact status codes\n\nThis is how Claude Code surfaces messages the user sends mid-turn — within the running turn, often alongside the next tool result, rather than as a separate conversation turn. Address the message above as you continue this turn.", + }) + } + messages.push({ role: "user", content }) + } + // 11 clipped tail steps (~93 KiB) fit in room - pinReserve (~94 KiB) so + // tail[0] lands right after qca-7; pinReserve pins qca-7 as steer-only + // and the contiguous-tail restore loop restores its full tool_result. + for (let index = 0; index < 11; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_qcb_${index}`, name: "Read", input: { path: `/repo/cb${index}.txt` } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_qcb_${index}`, content: big(`qcb-${index}`) }] }) + } + messages.push({ role: "assistant", content: "Paused after checking the routing table." }) + messages.push({ role: "user", content: "继续" }) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "queued-nudge-contiguous" }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 112 * 1024, `initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("CONTIGUOUS PIN STEER: keep exact status codes"), "contiguous pinReserve steer is kept") + assert.ok(prompt.includes("qca-7 head") && prompt.includes("qca-7 tail"), "contiguous tool_result beside pinReserve steer is restored") + assert.ok(prompt.includes("qcb-0 head"), "tail starts right after the pinned steer with no gap") + assert.ok(prompt.includes("继续")) + }) +}) + +test("A16: non-steer companions beside a tool_result are not pinned as mid-loop steers", async () => { + const nonSteerCases = [ + [ + "dsh-time", + "Time sampled while preparing turn 19, step 5: 2026-11-13T15:35:00Z", + [{ type: "text", text: "Time sampled while preparing turn 19, step 5: 2026-11-13T15:35:00Z\nElapsed since the preceding step context: 10m 2s." }], + null, + ], + [ + "skill-companion", + "SKILL_BODY_MARKER", + [ + { type: "text", text: "(Re-invocation of /demo-skill — the skill instructions were previously loaded; the arguments or dynamic output below are new.)\n" }, + { type: "text", text: "Base directory for this skill: /repo/skills/demo\n\nSKILL_BODY_MARKER: docs may quote The user sent a new message while you were working: literally." }, + ], + null, + ], + [ + "hook-output", + "HOOK_CONTEXT_MARKER", + [{ type: "text", text: "PostToolUse hook additional context: HOOK_CONTEXT_MARKER" }], + null, + ], + [ + "system-reminder", + "REMINDER_DATE_MARKER", + [{ type: "text", text: "\nREMINDER_DATE_MARKER: The date has changed.\n" }], + null, + ], + [ + "tool-result-body-quote", + "FILE_BODY_QUOTE_MARKER", + [], + "The user sent a new message while you were working:\nFILE_BODY_QUOTE_MARKER\n", + ], + ] + const big = (label) => `${label} head ` + "tool output line with some words. ".repeat(560) + ` ${label} tail` + for (const [label, forbiddenMarker, extraBlocks, resultPrefix] of nonSteerCases) { + await withSinglePromptKit({}, async (kit) => { + scriptedAgent(kit) + const messages = [ + { role: "user", content: "ANCHOR opening request" }, + { role: "assistant", content: "ANCHOR reply" }, + { role: "user", content: "LOOP OPENER: refactor group router" }, + ] + for (let index = 0; index < 4; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_nsa_${index}`, name: "Read", input: { path: `/repo/na${index}.txt` } }] }) + const resultBody = (index === 3 && resultPrefix ? resultPrefix : "") + big(`nsa-${index}`) + const content = [{ type: "tool_result", tool_use_id: `toolu_nsa_${index}`, content: resultBody }] + if (index === 3) content.push(...extraBlocks) + messages.push({ role: "user", content }) + } + for (let index = 0; index < 14; index++) { + messages.push({ role: "assistant", content: [{ type: "tool_use", id: `toolu_nsb_${index}`, name: "Read", input: { path: `/repo/nb${index}.txt` } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: `toolu_nsb_${index}`, content: big(`nsb-${index}`) }] }) + } + messages.push({ role: "assistant", content: [{ type: "tool_use", id: "toolu_ns_last", name: "Read", input: { path: "/repo/last.txt" } }] }) + messages.push({ role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_ns_last", content: "LAST RESULT" }] }) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: `non-steer-${label}` }, messages }))) + assert.equal(parsed.stopReason, "end_turn") + const prompt = prompts(kit).at(-1) + assert.ok(bytes(prompt) <= 112 * 1024, `${label}: initial prompt is ${bytes(prompt)} bytes`) + assert.ok(prompt.includes("Human: LOOP OPENER: refactor group router"), `${label}: loop opener is kept`) + assert.ok(!prompt.includes(forbiddenMarker), `${label}: non-steer companion must not be pinned as a mid-loop steer`) + assert.ok(prompt.includes("LAST RESULT"), `${label}: current turn result is kept`) + }) + } +}) + // #896: agy reports the run to its vendor unless it is told not to; the flag // is passed only to an agy whose own acp --help lists it. const TELEMETRY_HELP = "Usage of acp:\n --disable-telemetry\n \tdisable telemetry (default false)\n" @@ -1171,6 +1487,106 @@ test("an empty ending is asked again in the same session, and its answer is the } }) +// plugins#1805 (berwinjoule): a read_file outside the session's folder is +// asked of the bridge as a permission, which it refuses; agy tells the model +// the user denied it, and the model ended its reply on that. Asked again +// with the plain empty-reply words, it told the user it had no access to +// the project. After a refused call the words say the tool is off here. +const TURNED_AWAY = [ + ["a refused permission", async (agent) => { + const outcome = await agent.requestPermission({ toolCallId: "rf", title: "read_file(/home/u/other/notes.md)", kind: "read", + rawInput: { AbsolutePath: "/home/u/other/notes.md" } }) + assert.equal(outcome?.result?.outcome?.outcome, "selected") + assert.equal(outcome.result.outcome.optionId, "deny") + await agent.thought("the user denied permission, so I should not circumvent it") + }], + ["the tool gate's hook", async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "hk", name: "run_command", status: "in_progress" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "hk", status: "failed", + rawOutput: "tool call denied by pre-tool hook: run_command is turned off in this session. Use only the tools you were given." }) + await agent.thought("I can't run that") + }], + ["a refusal with nothing after it", async (agent) => { + await agent.requestPermission({ toolCallId: "rf", title: "read_file(/etc/hosts)", kind: "read" }) + }], +] + +test("an empty ending after a refused built-in tool is asked again with words that say the tool is off", async () => { + for (const [name, turnAway] of TURNED_AWAY) { + await withKit({}, async (kit) => { + kit.defaultPrompt = async (agent) => { + if (promptText({ prompt: agent.prompt }).includes("Your last reply was empty")) { + await agent.text("answered with the tools given") + return { stopReason: "end_turn" } + } + await turnAway(agent) + return { stopReason: "end_turn" } + } + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "turned-away" }, + messages: [{ role: "user", content: "read my notes" }] }))) + assert.equal(parsed.error, null, name) + assert.equal(replyText(parsed).trim(), "answered with the tools given", name) + const sent = prompts(kit) + assert.equal(sent.length, 2, `${name}: asked once more`) + assert.match(sent[1], /turned off in this session/, name) + assert.match(sent[1], /not the user refusing/, name) + assert.match(sent[1], /no need to ask for workspace access/, name) + assert.match(sent[1], /tools you were given/, name) + // these words go upstream: they name neither magpie nor the vendor, + // nor the parts of the bridge that turned the call away + assert.ok(!/magpie|agy|antigravity|google|gemini|bridge|ide-tools|tool.gate|hook|mcp|plugin/i.test(sent[1]), `${name}: ${sent[1]}`) + }) + } +}) + +test("an empty ending with no refused call is asked again with the plain words", async () => { + await withKit({}, async (kit) => { + kit.defaultPrompt = async (agent) => { + if (promptText({ prompt: agent.prompt }).includes("Your last reply was empty")) { + await agent.text("ok") + return { stopReason: "end_turn" } + } + await agent.thought("the next step is to read the file") + return { stopReason: "end_turn" } + } + await readSse(await kit.request(baseBody({ metadata: { user_id: "plain-empty" }, + messages: [{ role: "user", content: "fix the bug" }] }))) + const sent = prompts(kit) + assert.equal(sent.length, 2) + assert.doesNotMatch(sent[1], /turned off/) + }) +}) + +test("a refused call that the model answered in text is a reply, not asked again", async () => { + await withKit({}, async (kit) => { + kit.defaultPrompt = async (agent) => { + await agent.requestPermission({ toolCallId: "rf", title: "read_file(/etc/hosts)", kind: "read" }) + await agent.text("I'll answer without that file.") + return { stopReason: "end_turn" } + } + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "refused-then-said" }, + messages: [{ role: "user", content: "read it" }] }))) + assert.equal(parsed.error, null) + assert.equal(prompts(kit).length, 1) + }) +}) + +test("still empty after a refused call is an error that says a tool was turned away", async () => { + await withKit({}, async (kit) => { + kit.defaultPrompt = async (agent) => { + await agent.requestPermission({ toolCallId: "rf", title: "read_file(/etc/hosts)", kind: "read" }) + await agent.thought("denied") + return { stopReason: "end_turn" } + } + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "refused-twice" }, + messages: [{ role: "user", content: "read it" }] }))) + assert.ok(parsed.error) + assert.match(parsed.error.message, /no text and no tool call/) + assert.match(parsed.error.message, /turned away/) + assert.equal(prompts(kit).length, 2) + }) +}) + test("an ending still empty after asking again is an error, and the session is kept", async () => { await withKit({}, async (kit) => { let empty = true diff --git a/test/testkit.mjs b/test/testkit.mjs index 4756ac0..ddce999 100644 --- a/test/testkit.mjs +++ b/test/testkit.mjs @@ -394,7 +394,7 @@ class FakeAgy { return true } this.watchSocket = socket - this.kit.controlHandler(socket) + this.kit.connectControl(socket, this.env) socket.emit("data", JSON.stringify({ token: this.token, kind: "watch" }) + "\n") } @@ -408,7 +408,7 @@ class FakeAgy { control(message) { const socket = new FakeSocket() - this.kit.controlHandler(socket) + this.kit.connectControl(socket, this.env) socket.emit("data", JSON.stringify({ token: this.token, ...message }) + "\n") return socket.reply } @@ -660,20 +660,60 @@ export async function createBridgeKit(options = {}) { ? callback(Object.assign(new Error("not found (test)"), { code: 44 }), "", "") : callback(null, stored, "")) } - const fakeServer = { - once() { return fakeServer }, - on() { return fakeServer }, - listen(_port, _host, callback) { setImmediate(callback); return fakeServer }, - unref() { return fakeServer }, - close() {}, - address() { return { address: "127.0.0.1", family: "IPv4", port: 45999 } }, + // The control server: each one the bridge makes listens on a port of + // its own (the first 45999), or the one it asks for unless a server or + // kit.busyPorts holds it. An agy's MCP server connects to the port in its + // environment, and reaches nothing once that server closed (#1766). + kit.controlServers = [] + kit.busyPorts = new Set() + let nextPort = 45999 + const listeningOn = (port) => kit.controlServers.find((server) => server.listening && server.port === port) + class FakeServer extends EventEmitter { + constructor(handler) { + super() + this.handler = handler + this.listening = false + this.port = 0 + } + listen(port, _host, callback) { + setImmediate(() => { + if (port && (kit.busyPorts.has(port) || listeningOn(port))) { + this.emit("error", Object.assign(new Error(`listen EADDRINUSE: address already in use 127.0.0.1:${port}`), { code: "EADDRINUSE" })) + return + } + this.port = port || nextPort++ + this.listening = true + kit.controlServers.push(this) + callback() + }) + return this + } + unref() { return this } + close() { + if (!this.listening) return this + this.listening = false + setImmediate(() => this.emit("close")) + return this + } + address() { return this.listening ? { address: "127.0.0.1", family: "IPv4", port: this.port } : null } + } + // where the bridge's agy connect: the server on their port, or none + kit.connectControl = (socket, env) => { + const port = Number(env?.AGY_BRIDGE_CONTROL_PORT) + const server = port ? listeningOn(port) : kit.controlServers.findLast((item) => item.listening) + if (!server) { + setImmediate(() => socket.destroy()) + return + } + server.handler(socket) } + kit.controlServer = () => kit.controlServers.findLast((server) => server.listening) ?? null const overrides = { "node:child_process": { spawn, spawnSync, execFile }, "node:net": { createServer(handler) { kit.controlHandler = handler - return fakeServer + return new FakeServer(handler) }, }, "node:os": { homedir: () => home, tmpdir: () => options.tmpdir ?? tmp }, diff --git a/test/usage-settlement.mjs b/test/usage-settlement.mjs index 18d97f9..1cfb237 100644 --- a/test/usage-settlement.mjs +++ b/test/usage-settlement.mjs @@ -1779,8 +1779,15 @@ test("SQLite 异常保护:超额失真行触发回退,EXCLUSIVE 锁库立即 `超额失真的 SQLite 行(90000)未被拦截,实际返回窗口=${usageTotal(responses[0].usage)}`) }) - // 子场景 2:数据库被 EXCLUSIVE 锁住(SQLITE_BUSY)时立即放弃轮询,不耗满 1000ms - await withKit({}, async (kit) => { + // 子场景 2:数据库被 EXCLUSIVE 锁住(SQLITE_BUSY)时立即放弃轮询。 + // 不量首步用了多久(plugins#1765:负载下没轮询也要 653ms,旧的 500ms 线没有余量): + // 把轮询上限调到十分钟,锁一直持有到工具结果回来;只要锁住时还在轮询,首步就要等满 + // 十分钟,下面 60s 的线两边都留足余量。 + await withKit({ indexTransform: (source) => { + const pattern = /const STEP_USAGE_WAIT_MS = 1_000\n/ + assert.match(source, pattern, "STEP_USAGE_WAIT_MS 改名或改值后这里要跟着改") + return source.replace(pattern, "const STEP_USAGE_WAIT_MS = 600_000\n") + } }, async (kit) => { const convDir = path.join(kit.home, ".gemini", "antigravity-cli", "conversations") fs.mkdirSync(convDir, { recursive: true }) let locker = null @@ -1803,11 +1810,14 @@ test("SQLite 异常保护:超额失真行触发回退,EXCLUSIVE 锁库立即 }) try { const body = baseBody() - const t0 = performance.now() - const toolResp = await readSse(await kit.request(body)) - const toolElapsedMs = performance.now() - t0 + let bound + const toolResp = await Promise.race([ + kit.request(body).then(readSse), + new Promise((_, reject) => { + bound = setTimeout(() => reject(new Error("SQLITE_BUSY 时首步 60s 仍未返回:锁住的库还在被轮询")), 60_000) + }), + ]).finally(() => clearTimeout(bound)) assert.equal(toolResp.stopReason, "tool_use") - assert.ok(toolElapsedMs < 500, `SQLITE_BUSY 时首步耗时 ${toolElapsedMs.toFixed(0)}ms,不应重复轮询阻塞至 1000ms`) const finalResp = await readSse(await kit.request(continueWithToolResults(body, toolResp, () => "ok"))) assert.equal(finalResp.stopReason, "end_turn") } finally { diff --git a/test/usage.mjs b/test/usage.mjs index 7ce3237..60e2f9b 100644 --- a/test/usage.mjs +++ b/test/usage.mjs @@ -6,7 +6,7 @@ import fs from "node:fs/promises" import os from "node:os" import path from "node:path" import { test } from "node:test" -import { agyRefusal, createUsageReader, DUE_FOR_RENEWAL, fetchUsage, GATEWAY_NO_FOLDER, parseStatusLineQuota, parseUsageReport, STILL_READING, verifyLinkIn } from "../usage.mjs" +import { agyRefusal, createUsageReader, DUE_FOR_RENEWAL, retryIn, fetchUsage, GATEWAY_NO_FOLDER, parseStatusLineQuota, parseUsageReport, STILL_READING, verifyLinkIn } from "../usage.mjs" import { catalogRows, familiesInGroup, modelsInGroup, storeCatalogRows } from "../model-ids.mjs" import { inAccount } from "../account.mjs" import { forgetStoredSignIn } from "../signin.mjs" @@ -857,6 +857,96 @@ test("a failure held for one agy is not another agy's", async t => { await f.assertClean() }) +// agy updating itself writes a new binary at the same path. The update the +// reporter of plugins#1761 saw (1.5.17 to 1.5.20, the plugin and its host +// restarted minutes later) is this fake failing, slowly or not, and then +// replaced by one that answers. +async function updateInPlace(f) { + const next = f.executable + ".new" + const body = await fs.readFile(f.executable, "utf8") + await fs.writeFile(next, body + (process.platform === "win32" ? "rem 1.5.20\r\n" : "# 1.5.20\n"), { mode: 0o700 }) + await fs.rename(next, f.executable) +} + +test("an agy updated in place is read at once, not held for the old binary's failures (plugins#1761)", async t => { + for (const [mode, expected] of [["fail", /network or proxy/], ["version-hang", /didn't say its version/]]) { + const f = await fixture(t, { TEST_MODE: mode, TEST_ERROR: "connection refused" }) + let clock = 0 + const read = createUsageReader(() => f.executable, { ...f.options, timeoutMs: 3000, now: () => clock }) + const runs = async () => (await f.logs()).length + // the old binary fails twice in a row, so its hold has grown + assert.match((await read()).error, expected) + clock += 60 * 60 * 1000 + assert.match((await read()).error, expected) + const before = await runs() + f.env.TEST_MODE = "" + clock += 60 * 1000 + assert.match((await read()).error, expected, `${mode}: the same binary is held`) + assert.equal(await runs(), before) + await updateInPlace(f) + const result = await read() + assert.equal(result.error, undefined, `${mode}: ${result.error}`) + assert.equal(result.windows.length, 1) + assert.ok(await runs() > before) + await f.assertClean() + } +}) + +test("a new binary starts its own count: one failure after an update is held ten minutes, not the old binary's hours", async t => { + const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "unrecognized" }) + let clock = 0 + const read = createUsageReader(() => f.executable, { ...f.options, now: () => clock }) + const minute = 60 * 1000 + const runs = async () => (await f.logs()).filter(l => l.args[0] !== "--version").length + await read() + for (const wait of [10, 20, 40]) { + clock += wait * minute + await read() + } + assert.match((await read()).error, /again in 1\.3 hours\.$/) + await updateInPlace(f) + assert.match((await read()).error, /again in 10 minutes\.$/, "the updated binary fails once") + const before = await runs() + clock += 10 * minute + await read() + assert.equal(await runs(), before + 1, "read again ten minutes after its first failure") + await f.assertClean() +}) + +test("a first start that keeps running out of time is never held past ten minutes", async t => { + const f = await fixture(t, { TEST_MODE: "version-hang" }) + let clock = 0 + const read = createUsageReader(() => f.executable, { ...f.options, timeoutMs: 3000, now: () => clock }) + const minute = 60 * 1000 + const runs = async () => (await f.logs()).length + assert.match((await read()).error, /didn't say its version[\s\S]*magpie asks agy again in a minute\.$/) + for (const wait of [1, 2, 4, 8, 10, 10]) { + const before = await runs() + clock += wait * minute - 1000 + const held = await read() + assert.equal(await runs(), before, `run again before ${wait} minutes`) + assert.match(held.error, /magpie asks agy again in (?:a minute|\d+ minutes)\.$/) + clock += 1000 + const again = await read() + assert.equal(await runs(), before + 1, `not run again after ${wait} minutes`) + assert.match(again.error, /didn't say its version/) + } + await f.assertClean() +}) + +test("a held failure says when agy is asked again", async t => { + const f = await fixture(t, { TEST_MODE: "fail", TEST_ERROR: "connection refused" }) + let clock = 0 + const read = createUsageReader(() => f.executable, { ...f.options, now: () => clock }) + assert.match((await read()).error, /network or proxy[\s\S]* magpie asks agy again in 10 minutes\.$/) + clock += 4 * 60 * 1000 + 1 + assert.match((await read()).error, / magpie asks agy again in 6 minutes\.$/) + for (const [ms, said] of [[1, "a minute"], [60_000, "a minute"], [61_000, "2 minutes"], [59 * 60_000, "59 minutes"], [60 * 60_000, "an hour"], [90 * 60_000, "1.5 hours"], [6 * 60 * 60_000, "6 hours"]]) { + assert.equal(retryIn(ms), said, String(ms)) + } + await f.assertClean() +}) + const startupAuthLogs = [ "W1115 15:13:30.249469 10 cache.go:157] error getting token source: You are not logged into Antigravity.", "I1115 15:13:30.317328 1 server_oauth.go:226] OAuth: authenticated successfully", @@ -1274,6 +1364,44 @@ test("an account agy acp names no tier for keeps the refusal, and agy's TUI is n await f.assertClean() }) +// plugins#1824: the reading magpie makes when the user asks is agy -p /usage +// alone. The eligibility refusal stands, with no agy acp and no TUI run. +test("printOnly keeps agy -p's eligibility refusal and starts neither agy acp nor agy's TUI", { skip: !PTY }, async t => { + const f = await fixture(t, { TEST_MODE: "eligibility", TEST_TIER: PRO_TIER, TEST_QUOTA: JSON.stringify(STATUS_QUOTA), TEST_VERSION: "1.5.19" }) + await assert.rejects(fetchUsage(f.executable, { ...f.options, timeoutMs: 20_000, printOnly: true }), /not eligible for Antigravity/) + const logs = await f.logs() + assert.deepEqual(logs.filter(l => l.args).map(l => l.args[0]), ["--version", "-p"]) + assert.ok(!logs.some(l => l.acp || l.settings)) + await f.assertClean() +}) + +// a printOnly call never takes what a read that could fall back read with +// nobody waiting, nor joins such a read under way: it runs agy -p itself +test("a printOnly call of the reader neither joins nor takes a read that could fall back", async t => { + // the agy -p runs so far, n at least once they have started + const runs = async () => (await f.logs().catch(() => [])).filter(l => l.args?.[0] === "-p").length + const prints = async (n) => { + for (let i = 0; i < 100 && await runs() < n; i++) await new Promise(r => setTimeout(r, 30)) + return runs() + } + const f = await fixture(t, { TEST_MODE: "delay", TEST_REPORT_DELAY_MS: "300" }) + const read = createUsageReader(() => f.executable, { ...f.options, waitMs: 50 }) + // under way: a printOnly call runs agy -p of its own + assert.equal((await read()).error, STILL_READING) + assert.equal((await read({ printOnly: true })).error, STILL_READING) + assert.equal(await prints(2), 2, "the printOnly call joined a read that could fall back") + await new Promise(r => setTimeout(r, 600)) + // read with nobody waiting: a printOnly call doesn't take it + const again = createUsageReader(() => f.executable, { ...f.options, waitMs: 50 }) + assert.equal((await again()).error, STILL_READING) + assert.equal(await prints(3), 3) + await new Promise(r => setTimeout(r, 600)) + assert.equal((await again({ printOnly: true })).error, STILL_READING, "the printOnly call took a read that could fall back") + assert.equal(await prints(4), 4) + await new Promise(r => setTimeout(r, 600)) + await f.assertClean() +}) + test("a tier with no quota in the statusLine keeps the refusal, and agy is stopped at the deadline", { skip: !PTY }, async t => { const f = await fixture(t, { TEST_MODE: "eligibility", TEST_TIER: PRO_TIER }) await assert.rejects(fetchUsage(f.executable, { ...f.options, timeoutMs: 3_000 }), /not eligible for Antigravity/) @@ -1382,7 +1510,7 @@ test("a read that runs out of time says so plainly, and is asked again a minute const result = await read() assert.deepEqual(result.windows, []) assert.equal(result.signIn, "kept") - assert.match(result.error, /agy's own usage read didn't finish in 3s[\s\S]*asked again in a minute[\s\S]*network or proxy/) + assert.match(result.error, /agy's own usage read didn't finish in 3s[\s\S]*network or proxy[\s\S]*magpie asks agy again in a minute\.$/) const runs = async () => (await f.logs()).filter(l => l.args[0] === "-p").length assert.equal(await runs(), 1) clock += 59_000 diff --git a/test/windows-nc.mjs b/test/windows-nc.mjs index 363be9b..7d0e18c 100644 --- a/test/windows-nc.mjs +++ b/test/windows-nc.mjs @@ -19,6 +19,18 @@ function workDir(kit, name) { const BUN = "C:\\Users\\Test\\magpie\\bun.exe" const body = (text) => baseBody({ model: "agy-cli/gemini-4-argon", tools: [], messages: [{ role: "user", content: text }] }) +const NCBUILD = "magpie-agy-bridge-ncbuild-" + +// A build's dir (and the runtime's ASCII copy) and the older nc dirs are +// removed without the turn waiting for them (#1608): gone soon, not at +// once. gone waits, by the clock and up to ms, for every name in dir +// starting with prefix to go, and gives the ones left. +async function gone(dir, prefix, ms = 5000) { + const left = () => fs.readdirSync(dir).filter((name) => name.startsWith(prefix)) + for (const end = Date.now() + ms; left().length && Date.now() < end; ) await new Promise((resolve) => setTimeout(resolve, 5)) + return left() +} + function buildsOf(kit) { return kit.otherSpawns.filter(({ args }) => args[0] === "build") } @@ -86,7 +98,8 @@ test("Windows sessions dial a shared nc.exe built once, never nc.cmd", async () assert.match(path.basename(dir), /^magpie-agy-bridge-nc-[0-9a-f]{16}$/) assert.equal(agyPathDir(kit, 1), dir) assert.deepEqual(fs.readdirSync(dir).sort(), ["nc.exe", "runtime"]) - assert.ok(!fs.readdirSync(kit.tmp).some((name) => name.startsWith("magpie-agy-bridge-bin-") || name.startsWith("magpie-agy-bridge-ncbuild-"))) + assert.ok(!fs.readdirSync(kit.tmp).some((name) => name.startsWith("magpie-agy-bridge-bin-"))) + assert.deepEqual(await gone(kit.tmp, NCBUILD), []) // A later host with the same runtime and server reuses the exe. const later = await windowsKit() @@ -136,10 +149,12 @@ test("a runtime under a non-ASCII folder builds nc.exe from an ASCII copy", asyn const dir = agyPathDir(kit) assert.match(path.basename(dir), /^magpie-agy-bridge-nc-[0-9a-f]{16}$/) assert.deepEqual(fs.readdirSync(dir).sort(), ["nc.exe", "runtime"]) - // The copy goes with the build dir. - for (let i = 0; i < 1000 && fs.existsSync(builds[0].file); i++) await new Promise(resolve => setImmediate(resolve)) + // The copy goes with its build dir. + const copyDir = path.dirname(builds[0].file) + assert.ok(path.basename(copyDir).startsWith(NCBUILD)) + assert.deepEqual(await gone(path.dirname(copyDir), NCBUILD), []) assert.equal(fs.existsSync(builds[0].file), false) - assert.ok(!fs.readdirSync(kit.tmp).some((name) => name.startsWith("magpie-agy-bridge-ncbuild-"))) + assert.deepEqual(await gone(kit.tmp, NCBUILD), []) } finally { await kit.dispose() fs.rmSync(outside, { recursive: true, force: true }) @@ -175,8 +190,7 @@ test("a new nc.exe build removes this runtime's older nc dirs and keeps others", await turn(kit, "two") assert.equal(buildsOf(kit).length, 1) const current = agyPathDir(kit) - for (let i = 0; i < 1000 && fs.existsSync(older); i++) await new Promise(resolve => setImmediate(resolve)) - assert.equal(fs.existsSync(older), false, "this runtime's older nc dir stayed") + assert.deepEqual(await gone(kit.tmp, path.basename(older)), [], "this runtime's older nc dir stayed") assert.ok(fs.existsSync(path.join(foreign, "nc.exe")), "another runtime's nc dir was removed") assert.ok(fs.existsSync(path.join(legacy, "nc.exe")), "an unmarked nc dir was removed before its week") assert.ok(fs.existsSync(path.join(current, "nc.exe"))) @@ -193,7 +207,9 @@ test("Windows falls back to nc.cmd when the runtime can't build nc.exe", async ( 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"))) + // no nc dir is made, and the failed build's dir goes + assert.ok(!fs.readdirSync(kit.tmp).some((name) => name.startsWith("magpie-agy-bridge-nc-"))) + assert.deepEqual(await gone(kit.tmp, NCBUILD), []) } finally { await kit.dispose() } diff --git a/usage.mjs b/usage.mjs index 2cf99d1..7d6baa3 100644 --- a/usage.mjs +++ b/usage.mjs @@ -639,6 +639,11 @@ export async function fetchUsage(agy, { // the folder agy reads in place of ~/.gemini when the app's gateway is on // there: { gateway, dir } (index.mjs's usageGeminiDir) geminiDir = async () => ({ gateway: false, dir: null }), + // agy -p /usage alone: an eligibility refusal stands, and neither agy acp + // nor agy's TUI (servedQuota) is started for it. magpie asks so for the + // one reading it makes, when the user asks for it: agy's own /usage, run + // headless, and nothing else (plugins#1824) + printOnly = false, } = {}) { if (!agy) throw new UsageError(NO_AGY) const folder = await geminiDir(agy) @@ -687,7 +692,7 @@ export async function fetchUsage(agy, { version = await run(agy, ["--version"], options).catch((error) => { // not kind "timeout": --version needs no sign-in, so its hang is // never agy waiting on one - if (error?.kind === "timeout") throw new UsageError(`agy didn't say its version in ${limit / 1000}s (its first start after an update can take that long), so the quota wasn't read. It's asked again in a minute.`, { slow: true }) + if (error?.kind === "timeout") throw new UsageError(`agy didn't say its version in ${limit / 1000}s (its first start after an update can take that long), so the quota wasn't read.`, { slow: true }) throw error }) if (version.code !== 0) throw commandFailure(version.stderr) @@ -707,7 +712,7 @@ export async function fetchUsage(agy, { // start. It gets the whole deadline. const result = await run(agy, [...folderArgs, "-p", "/usage", "--output-format", "json", "--print-timeout", `${Math.max(1, Math.ceil((deadline - Date.now()) / 1000))}s`], options).catch((error) => { if (error?.kind !== "timeout") throw error - throw new UsageError(`agy's own usage read didn't finish in ${limit / 1000}s. agy asks Google about twelve times, one after another, before it has the quota, which takes longer behind a slow network or proxy. It's asked again in a minute; if this stays, check agy's network or proxy.`, { kind: "timeout", output: error.output }) + throw new UsageError(`agy's own usage read didn't finish in ${limit / 1000}s. agy asks Google about twelve times, one after another, before it has the quota, which takes longer behind a slow network or proxy. If this stays, check agy's network or proxy.`, { kind: "timeout", output: error.output }) }) if (folderArgs.length && result.code !== 0 && NO_GEMINI_DIR_FLAG.test(result.stderr + "\n" + result.stdout)) throw new UsageError(GATEWAY_NO_FOLDER) let report @@ -718,7 +723,7 @@ export async function fetchUsage(agy, { ? text(report.error) || text(report.response) : result.stderr + "\n" + result.stdout const failure = commandFailure(said) - if (failure.ineligible) { + if (failure.ineligible && !printOnly) { const served = await servedQuota(agy, folder, options) if (served) return served } @@ -744,16 +749,30 @@ export async function fetchUsage(agy, { // A read that failed isn't run again for this long, doubled for each // failure in a row, up to BACKOFF_MOST: agy is a process of its own, and one // that fails every few minutes all day helps nobody. One that ran out of -// time is asked again sooner: a slow minute on the network (or agy's first -// start after an update) said "timed out" for ten (flmaximwang on -// plugins#1522), and a newly added account showed no quota for as long -// (Jayc1world on X). +// time is asked again sooner, and never held past BACKOFF_SLOW_MOST: a slow +// minute on the network (or agy's first start after an update) said "timed +// out" for ten (flmaximwang on plugins#1522), a newly added account showed +// no quota for as long (Jayc1world on X), and a slow first start must not +// grow into hours. const BACKOFF_FIRST_MS = 10 * 60 * 1000 const BACKOFF_SLOW_MS = 60 * 1000 +const BACKOFF_SLOW_MOST_MS = BACKOFF_FIRST_MS const BACKOFF_MOST_MS = 6 * 60 * 60 * 1000 function backoff(n, slow = false) { - return Math.min((slow ? BACKOFF_SLOW_MS : BACKOFF_FIRST_MS) * 2 ** Math.max(0, Math.min(n, 20) - 1), BACKOFF_MOST_MS) + return Math.min((slow ? BACKOFF_SLOW_MS : BACKOFF_FIRST_MS) * 2 ** Math.max(0, Math.min(n, 20) - 1), slow ? BACKOFF_SLOW_MOST_MS : BACKOFF_MOST_MS) +} + +// when a held failure is tried again, in the words its error ends with +export function retryIn(ms) { + const minutes = Math.max(1, Math.ceil(ms / 60_000)) + if (minutes < 60) return minutes === 1 ? "a minute" : `${minutes} minutes` + const hours = Math.round(minutes / 6) / 10 + return hours === 1 ? "an hour" : `${hours} hours` +} + +function heldError(held, at) { + return `${held.error} magpie asks agy again in ${retryIn(held.until - at)}.` } // what usage says while no agy is found: never held (createUsageReader), @@ -786,7 +805,10 @@ export const STILL_READING = "agy is still reading this account's quota (its own // - an explicit authentication rejection, or an ended token hanging silently // or with sign-in talk, blocks further background runs for that credential. // Diagnostic-only output isn't evidence of a browser sign-in. -// - any other failure isn't run again for backoff(n). No agy found is not +// - any other failure isn't run again for backoff(n), and says when it is +// (heldError). The hold is for one agy binary: an agy updated in place +// (same path, another size or modification time; plugins#1761) is read +// at once, and starts its count again. No agy found is not // held: finding it costs a few stat calls, and an agy installed since (a // sign-in installs it; tmr11235 on X saw it) is used on the next read, // not after hours of "not found" while its chats already run. @@ -811,7 +833,7 @@ export function createUsageReader(resolveAgy, options = {}) { return { windows: [], error: `${why}. ${NEEDS_SIGN_IN}`, signIn: "expired" } } // what a finished read says, worked out once for whoever takes it - const settle = (outcome, { agy, key, stored }) => { + const settle = (outcome, { agy, binary, key, stored }) => { if (!outcome.error) { const result = { ...structuredClone(outcome.result), signIn: saidExpired ? "renewed" : "kept" } held = null @@ -828,12 +850,15 @@ export function createUsageReader(resolveAgy, options = {}) { noteDead(stored) return expired("agy's sign-in no longer works") } - const n = held?.key === key && held.agy === agy ? held.n + 1 : 1 - held = { key, agy, n, until: now() + backoff(n, !auth && (error?.kind === "timeout" || error?.slow === true)), error: message, auth } + const n = held?.key === key && held.agy === agy && held.binary === binary ? held.n + 1 : 1 + const at = now() + held = { key, agy, binary, n, until: at + backoff(n, !auth && (error?.kind === "timeout" || error?.slow === true)), error: message, auth } if (auth) saidExpired = true - return { windows: [], error: message, signIn: auth ? "expired" : "kept" } + return { windows: [], error: heldError(held, at), signIn: auth ? "expired" : "kept" } } - return async () => { + // printOnly: agy -p /usage alone (fetchUsage); such a call never joins + // or takes a read that could have gone on to agy acp or agy's TUI + return async ({ printOnly = false } = {}) => { const asked = Date.now() let stored try { stored = await signIn() } catch { stored = { state: "unknown" } } @@ -846,18 +871,21 @@ export function createUsageReader(resolveAgy, options = {}) { const agy = resolveAgy() if (!agy) return { windows: [], error: NO_AGY, signIn: "kept" } // read while nobody waited: this call's answer, once - if (late && late.key === key && late.agy === agy && now() - late.at < LATE_KEPT_MS) { + if (late && late.key === key && late.agy === agy && (late.printOnly || !printOnly) && now() - late.at < LATE_KEPT_MS) { const { reply } = late late = null return reply } late = null - // a failure held for another agy (gone, or another found since) isn't - // this one's - if (held && held.key === key && held.agy === agy && now() < held.until) { - return { windows: [], error: held.error, signIn: held.auth ? "expired" : "kept" } + // a failure held for another agy (gone, another found since, or this + // one updated in place) isn't this one's + const binary = await binaryKey(agy) + const at = now() + if (held && held.key === key && held.agy === agy && held.binary === binary && at < held.until) { + return { windows: [], error: heldError(held, at), signIn: held.auth ? "expired" : "kept" } } - let read = pending.get(agy) + const reading = printOnly ? agy + "\0print" : agy + let read = pending.get(reading) if (!read) { // an access token that has ended or ends within two minutes, with a // refresh token: agy isn't run (plugins#1234, above) @@ -865,15 +893,15 @@ export function createUsageReader(resolveAgy, options = {}) { return { windows: [], error: DUE_FOR_RENEWAL, signIn: "kept" } } const entry = { waiting: 0 } - entry.done = fetchUsage(agy, fetchOptions).then(result => ({ result }), error => ({ error })).then((outcome) => { - if (pending.get(agy) === entry) pending.delete(agy) - const reply = settle(outcome, { agy, key, stored }) + entry.done = fetchUsage(agy, { ...fetchOptions, printOnly }).then(result => ({ result }), error => ({ error })).then((outcome) => { + if (pending.get(reading) === entry) pending.delete(reading) + const reply = settle(outcome, { agy, binary, key, stored }) // nobody waits for it any more: the next call takes it - if (entry.waiting === 0 && !outcome.error) late = { key, agy, reply, at: now() } + if (entry.waiting === 0 && !outcome.error) late = { key, agy, reply, printOnly, at: now() } onSettled(reply) return reply }) - pending.set(agy, entry) + pending.set(reading, entry) read = entry } read.waiting++