diff --git a/README.en.md b/README.en.md index 80f1cdf..50e29a7 100644 --- a/README.en.md +++ b/README.en.md @@ -42,7 +42,9 @@ channel: Antigravity's models over ACP. The differences: history as context. This plugin keeps a pool of agy processes, reuses one agy session for one conversation, and picks it up again with `session/resume` after a restart; only when that fails does it replay the history, within a - byte budget. + byte budget. When magpie's image-slim swaps an earlier image for its + placeholder (on Codex, a whole view_image output for one line of text), or + magpie leaves one out to fit a size or image limit, the session holds. - **Tool calls**: Antigravity ACP ends the turn with the call as the reply's `tool_calls`. This plugin feeds the client's result back into the same agy turn (see "Tool bridge" below). @@ -101,7 +103,8 @@ MCP server. The control port listens on loopback only, with a token per process. own tools (shell, file edits, browser) is refused. A request for one of the client's tools on the bridge's `ide-tools` server is allowed once, since that tool runs in the client under the client's own permissions. Real actions - happen on the client side. + happen on the client side. Set `AGY_BRIDGE_ALLOW_AGY_TOOLS=1` to instead start + agy with `--dangerously-skip-permissions` and let its own tools through. - **Assistant prefill**: requests that end with a text-only assistant message (SillyTavern presets, "continue"/"impersonate", bot frameworks) are served instead of rejected; the session ledger stays aligned across turns. See @@ -280,8 +283,9 @@ account", which keeps its sign-in in a file. | `AGY_BRIDGE_MAX_PROCS` | 16 | Maximum number of agy processes in the pool | | `AGY_BRIDGE_THINKING` | on | Set to `0` to stop forwarding thought summaries | | `AGY_BRIDGE_EFFORT` | unset | Force a thinking level: `minimal`, `low`, `medium`, `high`, `xhigh` or `max` | -| `AGY_BRIDGE_MINIMAL_AGENT` | off | Set to `1` to drop agy's own prompt components; see "Minimal agent" below | +| `AGY_BRIDGE_MINIMAL_AGENT` | off | **⚠️ Ban risk, not recommended.** Set to `1` to drop agy's own prompt components, so requests upstream no longer look like the official agy client's; a user reported their account banned within hours of turning it on. See "Minimal agent" below | | `AGY_BRIDGE_TELEMETRY` | off (agy reports nothing) | The bridge starts agy with `--disable-telemetry` when agy's `acp --help` lists it; set to `1` to keep agy's own reporting | +| `AGY_BRIDGE_ALLOW_AGY_TOOLS` | off | Set to `1` to start every `agy acp` with `--dangerously-skip-permissions`, so agy's own tools (shell, file edits, browser) auto-approve instead of the bridge refusing each `session/request_permission`. Client `ide-tools` still run under the client's own permissions. agy's tools run on the computer magpie runs on, with your user's rights, for every request that reaches this provider: a client on another machine, or anyone holding a gateway key, can run commands there. Leave off unless only you use it | | `AGY_BRIDGE_SYSTEM_APPEND` | off | Set to `1` to append the client's system prompt to agy's own instead of putting it in the first prompt; see below | | `AGY_BRIDGE_IDLE_MS` | 600000 | How long a process may sit idle before it is reclaimed; the session can still resume | | `AGY_BRIDGE_SPARE` | on | Keeps one spare agy per account, started but with no session and no request sent, so a new conversation skips agy's start; set to `0` to turn it off | @@ -301,6 +305,15 @@ account", which keeps its sign-in in a file. ## Minimal agent (`AGY_BRIDGE_MINIMAL_AGENT=1`) +> **⚠️ Ban risk, not recommended.** With it on, requests go upstream without +> agy's own system prompt, so they no longer look like the official agy +> client's, and the point of this plugin is that requests are sent by the +> official client and look like it. A user reported their account was banned +> within hours of turning it on. That is one report, not proof of cause, but +> treat the risk as real. While it is on, the plugin prints the same warning to its +> log, once a process. If you turned it on, unset it to go back to the +> default. + By default agy runs every request with its own system prompt, and the client's system prompt goes as `` at the start of the first prompt. Antigravity answers a bare 429 to a growing set of @@ -345,8 +358,8 @@ request that goes upstream then has none of agy's own system prompt, only the plugin's one-line tool note and the client's system prompt (sent in one of the two ways above). The original author measured about 8,400 input tokens per model call with agy's prompt and about 500 without. The cost is -that upstream no longer sees agy's own request shape, which is why it is -off unless you turn it on. +that upstream no longer sees agy's own request shape, a ban risk (see the +top of this section), which is why it is off and not recommended. ## Troubleshooting diff --git a/README.md b/README.md index a51accd..26ab91c 100644 --- a/README.md +++ b/README.md @@ -29,7 +29,8 @@ OpenCode、Claude Code 等客户端经由 Magpie 调用 agy 向本插件开放 机器上没有时,在 Magpie 里登录会按 Google 官方安装脚本的方式装一份(见「环境要求」)。 - **会话**:Antigravity ACP 每个请求开一个新会话,把历史当作上下文带上。本插件维护一个 agy 进程池,同一段对话复用同一个 agy 会话,重启后用 `session/resume` 接上;只有接不上时 - 才在字节预算内重放历史。 + 才在字节预算内重放历史。magpie 的 image-slim 把较早的图片换成占位文字(Codex 上是整段 + view_image 结果换成一行字),或 magpie 为满足大小、图片数上限省去较早的图片时,会话照常复用。 - **工具调用**:Antigravity ACP 把工具调用作为回复的 `tool_calls` 结束这一轮。本插件把 客户端的结果送回同一轮 agy 对话(见下文「工具桥接」)。 - **额度**:本插件读 agy 自己的 `/usage` 报告;Antigravity ACP 读每次回复带的配额。 @@ -197,8 +198,9 @@ macOS 上,以 LaunchDaemon 方式运行的 Magpie 不在你的登录会话里 | `AGY_BRIDGE_MAX_PROCS` | 16 | agy 进程池上限 | | `AGY_BRIDGE_THINKING` | 开启 | 设为 `0` 关闭思考摘要 | | `AGY_BRIDGE_EFFORT` | 未设置 | 强制思考等级:`minimal` / `low` / `medium` / `high` / `xhigh` / `max` | -| `AGY_BRIDGE_MINIMAL_AGENT` | 关闭 | 设为 `1` 去掉 agy 自带的提示组件,见下文「精简 agent」 | +| `AGY_BRIDGE_MINIMAL_AGENT` | 关闭 | **⚠️ 有封号风险,不建议开启。** 设为 `1` 去掉 agy 自带的提示组件,发往上游的请求就和官方 agy 客户端的不一样了;有用户反馈开启几个小时后账号被封。见下文「精简 agent」 | | `AGY_BRIDGE_TELEMETRY` | 关闭(agy 不上报) | 插件启动 agy 时带上 `--disable-telemetry`(agy 的 `acp --help` 没这个开关就带不上);设成 `1` 保留 agy 自己的上报 | +| `AGY_BRIDGE_ALLOW_AGY_TOOLS` | 关闭 | 设为 `1` 让每个 `agy acp` 带 `--dangerously-skip-permissions` 启动,agy 自带的工具(shell、改文件、浏览器)自动放行,不再由 bridge 逐个拒绝 `session/request_permission`。客户端 `ide-tools` 仍在客户端自己的权限下运行。agy 的工具在 magpie 所在的电脑上以你的用户权限运行,凡是到达这个 provider 的请求都能用:另一台机器上的客户端、或持有网关密钥的任何人,都能在这台电脑上执行命令。只有你自己用时才打开 | | `AGY_BRIDGE_SYSTEM_APPEND` | 关闭 | 设为 `1` 把客户端的系统提示词附加到 agy 自己的系统提示词后面,而不是放进第一条提示词,见下文 | | `AGY_BRIDGE_IDLE_MS` | 600000 | 进程空闲多久后回收(会话仍可续接) | | `AGY_BRIDGE_SPARE` | 开启 | 每个账号预先启动一个备用 agy(只启动、不建会话,不发任何请求),新对话直接用它,省掉 agy 的启动时间;设为 `0` 关闭 | @@ -218,6 +220,11 @@ macOS 上,以 LaunchDaemon 方式运行的 Magpie 不在你的登录会话里 ## 精简 agent(`AGY_BRIDGE_MINIMAL_AGENT=1`) +> **⚠️ 有封号风险,不建议开启。** 开启后,发往上游的请求不再带 agy 自己的系统提示词,和官方 +> agy 客户端发出的请求不一样了;而这个插件的意义正在于请求由官方客户端发出、看起来就是官方客户端。 +> 有用户反馈开启后几个小时账号就被封了。这只是一例反馈,不能证明就是它导致的,但请把这个风险当真。 +> 开启时插件会在日志里打印一行同样的警告(每个进程一次)。已经开了的话,去掉这个变量即可恢复默认。 + 默认情况下,agy 用它自己的系统提示词跑每个请求,客户端的系统提示词作为 `` 放在第一条提示词开头。Antigravity 对附加在 agy 系统提示词 后面的越来越多 agent 的提示词直接回 429(11-15 起包括 Claude Code 的 "You are an interactive @@ -242,7 +249,7 @@ DeepSeek Harness 的第一句 "You are an AI agent powered by DeepSeek Harness." 设为 `1` 后,临时 agent 带上 `excludeDefaultComponents: true`:发往上游的请求里不再有 agy 自己的系统提示词,只剩插件的一行工具说明和客户端的系统提示词(同样以上面两种方式之一 发送)。原作者实测每次模型调用的输入从约 8,400 token 降到约 500 token。代价是上游看到的 -不再是 agy 自己的请求形态,所以默认关闭,由你自行决定是否开启。 +不再是 agy 自己的请求形态,有封号风险(见本节开头),所以默认关闭,不建议开启。 ## 常见排查 diff --git a/agy-cli.test.mjs b/agy-cli.test.mjs index b1bb08d..c71be22 100644 --- a/agy-cli.test.mjs +++ b/agy-cli.test.mjs @@ -24,6 +24,7 @@ for (const [name, mocks] of [ ["step-usage.mjs", false], ["tool-schema.mjs", false], ["tool-summary.mjs", false], + ["call-mcp-tool.mjs", false], ["usage-settlement.mjs", false], ["steer-in-session.mjs", false], ["dropped-call.mjs", false], @@ -32,10 +33,18 @@ for (const [name, mocks] of [ ["conversation-key.mjs", false], ["windows-nc.mjs", false], ["spare.mjs", false], + ["account-scope.mjs", false], ["stateless-reuse.mjs", false], ["tools-listed.mjs", false], ["concurrent-convs.mjs", false], ["masking-drift.mjs", false], + ["spilled-output.mjs", false], + ["tool-result-prefill.mjs", false], + ["tool-step-retry.mjs", false], + ["image-bytes.mjs", false], + ["dsh-replay-state.mjs", false], + ["duplicate-result-notice.mjs", false], + ["image-slim.mjs", false], ]) { test(`test/${name}`, () => { // bun's 5s default per test is a fixed wait these process-spawning tests @@ -53,6 +62,12 @@ test("test/re2-pattern-unit.mjs", () => { expect(code).toBe(0) }, 70_000) +test("test/image-signature-unit.mjs", () => { + const { code, output } = run([path.join(dir, "image-signature-unit.mjs")], 60_000) + expect(output).toMatch(/ALL OK/) + expect(code).toBe(0) +}, 70_000) + test("test/smoke.mjs against a fake agy", () => { const { code, output } = run([path.join(dir, "smoke.mjs")], 240_000) expect(output).toMatch(/ALL OK \(\d+ checks\)/) diff --git a/index.mjs b/index.mjs index 72fc3d2..4ba2e36 100644 --- a/index.mjs +++ b/index.mjs @@ -1,4 +1,4 @@ -import { agyCandidates, childEnv, spawnAgy, windowsMcpShim, windowsNcBuild, windowsTreeKill } from "./platform.mjs" +import { agyCandidates, childEnv, holdsHome, spawnAgy, windowsMcpShim, windowsNcBuild, windowsTreeKill } from "./platform.mjs" import { spawn, spawnSync } from "node:child_process" import { createHash, createHmac, randomBytes, randomUUID, timingSafeEqual } from "node:crypto" import { once } from "node:events" @@ -162,6 +162,15 @@ const DISABLED_CORE = AGENT_ERROR_CORES[6] // again. It is a 503 overloaded_error: the model's, not the account's, so // the account is not rested as a 429 would rest it. const BUSY_CORE = "⚠ Our servers are experiencing high traffic right now" +// Before that ending, agy retries the 503 inside the turn for minutes, with +// nothing streamed: only its log says "Run: attempt 1 failed (transport error +// (Unavailable, HTTP 503): No capacity available for model … on the server +// …), retrying in 4s". A 1 to 2 minute wait before the first token, past a +// client's patience (Hermes cancels at 30s), and nothing behind magpie tried +// another account (plugins#1541). The first such line, before anything was +// streamed, ends the turn as the same overloaded 503. +const noCapacity = (detail) => /\bNo capacity available for model\b/i.test(detail || "") +const CAPACITY_POLL_MS = Math.max(50, Number(process.env.AGY_BRIDGE_CAPACITY_POLL_MS) || 500) const BUSY_MARKER = "\n" + BUSY_CORE // agy 1.5.8 writes each failed attempt of a model call into the reply as one // line, then tries again in the same turn (#1136). The line is agy's. @@ -216,8 +225,21 @@ const HOLD_MAX = Math.max( ) - 1 // Opt-in. The minimal agent drops agy's own prompt components (~8,400 input // tokens a model call, against ~500 without them), so the request goes upstream -// with the client's system prompt in their place. +// with the client's system prompt in their place. Not recommended: the +// request no longer looks like the official agy client's, and a user reported +// their account banned within hours of turning it on (limengy88811922 on X). const minimalAgent = () => process.env.AGY_BRIDGE_MINIMAL_AGENT === "1" +const MINIMAL_AGENT_WARNING = "AGY_BRIDGE_MINIMAL_AGENT=1 is on: requests go upstream without agy's own system prompt, so they no longer look like the official agy client's. A user reported their account banned within hours of turning it on. Not recommended; unset it to go back." +// Once per process, though the module may be loaded more than once in it. +const MINIMAL_WARNED = Symbol.for("magpie-community.agy-cli.minimal-agent-warned") +function warnMinimalAgent() { + if (globalThis[MINIMAL_WARNED]) return + globalThis[MINIMAL_WARNED] = true + // A JSON row like the bridge's other stderr lines; AGY_BRIDGE_EVENTS=0 + // doesn't silence it. + const row = { event: "agy_bridge_warning", ts: Date.now(), warning: MINIMAL_AGENT_WARNING } + try { process.stderr.write("[agy-bridge] " + JSON.stringify(row) + "\n") } catch {} +} // Opt-in. agy's ACP server offers to append the client's system prompt to // its own (session instructions), and Antigravity sends that upstream as // part of the system instruction, where Google's check turns away a widening @@ -1127,6 +1149,38 @@ function saveCatalog(agyPath, change) { } catch {} } +// Whether another account of this agy lists model, by the lists models.json +// keeps for each (offered, when a session said, else listed). A family +// alias for a model this account lacks swapped it for another model with a +// 200, claude-sonnet-5-5 served as claude-sonnet-4-6, while the account +// that has it was never asked (plugins#1542). +function anotherAccountLists(agyPath, model) { + if (!agyPath || !model) return false + const base = model.replace(/-\d{8}$/, "") + const bare = base.replace(/-(?:minimal|low|medium|high|xhigh|max)$/i, "") + try { + const data = JSON.parse(fs.readFileSync(modelCatalogFile(), "utf8")) + if (data?.version !== 1 || !data.byAgy || typeof data.byAgy !== "object") return false + const mine = catalogKey(agyPath) + for (const [key, entry] of Object.entries(data.byAgy)) { + if (key === mine || (key !== agyPath && !key.startsWith(agyPath + "#"))) continue + // an account removed since leaves its entry behind, not its home + const id = key === agyPath ? "" : key.slice(agyPath.length + 1) + if (id && !fs.existsSync(path.join(accountsDir(), id))) continue + if (!Number.isFinite(entry?.at) || Date.now() - entry.at > SAVED_CATALOG_MAX_AGE_MS) continue + const rows = Array.isArray(entry.offered) && entry.offered.length ? entry.offered : entry.list + if (!Array.isArray(rows)) continue + for (const row of rows) { + const rowId = typeof row?.id === "string" ? row.id : "" + if (!rowId) continue + const family = row.effort && rowId.endsWith("-" + row.effort) ? rowId.slice(0, -row.effort.length - 1) : rowId + if (rowId === base || family === base || family === bare) return true + } + } + } catch {} + return false +} + function startingModelCatalog(agyPath) { const saved = readSavedCatalog(agyPath) if (!saved) return fallbackModelCatalog(agyPath, { replace: true }) @@ -1264,6 +1318,7 @@ function normalizeEffort(value) { return EFFORT_ORDER.includes(direct) ? direct : "" } +<<<<<<< HEAD // Thinking when disabled (local patch). agy has no level that turns thinking // off, and upstream leaves the effort unset on disabled, so the model ran at // the family's default level (high where there is one): the longest thinking @@ -1282,12 +1337,35 @@ function requestedEffort(body) { if (forced) return forced const thinking = body.thinking?.type if (thinking === "disabled") return disabledEffort(body) // Thinking when disabled (local patch) +======= +// The level the request names. magpie says the effort the client asked for in +// X-Magpie-Effort (said): its Anthropic body carries only a thinking budget, +// held under max_tokens, or no thinking at all when max_tokens is small, so a +// level read from the budget put reasoning_effort "high" at max_tokens 4000 on +// -low, and "low" at max_tokens 1500 on the family's default high +// (plugins#1540). What magpie says comes first; the budget is the last guess. +function namedEffort(body, said = "") { + const forced = normalizeEffort(process.env.AGY_BRIDGE_EFFORT) + if (forced) return forced + const thinking = body.thinking?.type + if (thinking === "disabled") return "" + const told = normalizeEffort(said) + if (told) return told +>>>>>>> upstream const generic = [body.reasoning_effort, body.reasoningEffort, body.reasoning?.effort, body.generationConfig?.thinkingConfig?.thinkingLevel].map(normalizeEffort).find(Boolean) if (generic) return generic if (thinking !== "enabled" && thinking !== "adaptive") return "" - const direct = normalizeEffort(body.output_config?.effort) - if (direct) return direct + return normalizeEffort(body.output_config?.effort) +} + +function requestedEffort(body, said = "") { + return namedEffort(body, said) || budgetEffort(body) +} + +function budgetEffort(body) { + const thinking = body.thinking?.type + if (thinking !== "enabled" && thinking !== "adaptive") return "" const budget = Number(body.thinking?.budget_tokens) if (!Number.isFinite(budget) || budget <= 0) return "" if (budget <= 4096) return "low" @@ -1324,7 +1402,10 @@ function resolveCatalogAlias(catalog, model) { return { id: base, inlineEffort } } const routeKeys = [...catalog.routes.keys()] - if (/^(?:gemini-[0-9.]+-flash(?:-lite)?|claude-(?:[0-9.-]+-)?haiku(?:-[0-9.-]+)?)$/i.test(base)) { + // a -preview or -exp id rides the same family: agy asks its own title and + // summary model "gemini-3.1-flash-lite-preview", which no account serves. + // Any other suffix (-image, -tts) is another kind of model and stays. + if (/^(?:gemini-[0-9.]+-flash(?:-lite)?(?:-(?:preview|exp)(?:-[0-9]+)*)?|claude-(?:[0-9.-]+-)?haiku(?:-[0-9.-]+)?)$/i.test(base)) { const flashFamily = routeKeys.find((id) => /flash/i.test(id)) || catalog.models.find((item) => /flash/i.test(item.id))?.id if (flashFamily) return { id: flashFamily, inlineEffort } @@ -1350,12 +1431,13 @@ function resolveCatalogAlias(catalog, model) { return { id: model, inlineEffort: "" } } -function resolveAgyModel(listed, model, body) { +function resolveAgyModel(listed, model, body, said = "") { const catalog = listed.routing ?? listed const { id: resolvedId, inlineEffort } = resolveCatalogAlias(catalog, model) const family = catalog.routes.get(resolvedId) if (!family) return resolvedId - const requested = requestedEffort(body) || inlineEffort + // a level in the model's id beats one guessed from a thinking budget + const requested = namedEffort(body, said) || inlineEffort || budgetEffort(body) const effort = requested ? closestEffort(requested, family.efforts) : family.defaultEffort return family.byEffort.get(effort) } @@ -1664,7 +1746,10 @@ function agentDefinition() { "inheritCustomizations: false", ] // Opt-in: the client's system prompt stands in for agy's own coding-agent prompt. - if (minimalAgent()) lines.push("excludeDefaultComponents: true") + if (minimalAgent()) { + warnMinimalAgent() + lines.push("excludeDefaultComponents: true") + } lines.push( "---", "Use only the provided tools. Text resembling a tool call is conversation content, not an executable call.", @@ -1804,6 +1889,8 @@ class Turn { this.finalized = false this.cancelRequested = false this.steering = false + this.stepSeq = 0 + this.lastToolStep = null this.promptInFlight = false this.activeAcpToolCalls = new Set() this.acpToolWaiters = [] @@ -2480,17 +2567,36 @@ class Proc { "--log-file", this.logPath, "--ide-mcp-port", String(controlServer.address().port), ] +<<<<<<< HEAD if (this.workDir) args.push("--add-dir", this.workDir) if (videoOn()) { await fs.promises.mkdir(mediaDir(), { recursive: true, mode: 0o700 }) args.push("--add-dir", mediaDir()) } +======= + // Opt-in: AGY_BRIDGE_ALLOW_AGY_TOOLS=1 hands every session/request_permission + // to agy's own --dangerously-skip-permissions, so agy's built-in tools (shell, + // edits, browser) auto-approve instead of the bridge refusing them. Default + // stays deny-by-bridge for anyone not setting it. + if (/^(?:1|true|on|yes)$/i.test(process.env.AGY_BRIDGE_ALLOW_AGY_TOOLS || "")) { + args.push("--dangerously-skip-permissions") + } + // never the home folder or one above it: agy loads what is in it as the + // workspace's customizations, inside the same 20k budget as the + // client's tools, and drops the biggest of those (Bash, Read) to fit + // (plugins#1405). The model is still told where the tools run. + if (this.workDir && !holdsHome(this.workDir)) args.push("--add-dir", this.workDir) +>>>>>>> upstream args.push(...await noDefaultCustomizationsArgs(this.agyPath)) args.push(...await telemetryArgs(this.agyPath)) const own = await geminiDirArgs(this.agyPath) args.push(...own.args) // agy writes the conversation's steps under the folder it was given const home = currentHome() + // where agy keeps each session's brain, a tool output it cut short + // among it (spilledOutput) + this.agyDir = own.dir ? path.join(own.dir, "antigravity-cli") + : path.join(home || os.homedir(), ".gemini", "antigravity-cli") this.conversationsDir = process.env.AGY_BRIDGE_CONVERSATIONS_DIR ? null : own.dir ? path.join(own.dir, "antigravity-cli", "conversations") : home ? path.join(home, ".gemini", "antigravity-cli", "conversations") @@ -2870,6 +2976,9 @@ class Proc { if (historyKey(expectedStripped) === historyKey(actualStripped) || sameHistoryUpToMasking(expectedStripped, actualStripped)) return true } + // magpie's image-slim swaps an earlier image for its placeholder text; agy + // has that image already, so the history it has is otherwise as it was. + if (sameHistoryUpToImages(this.expectedMessages, messages)) return true // A client that compacts its own context (billion-context in DeepSeek // Harness) folds earlier messages into a summary the live session never // saw. agy still holds those messages whole, so the session holds as long @@ -2921,6 +3030,7 @@ class Proc { // distinct from the bridge's toolu_ IDs, so snapshot all in-flight ACP IDs. const pendingAcpIds = deliveringLiveMcp ? new Set(turn.activeAcpToolCalls) : new Set() turn.steering = true + turn.lastToolStep = null try { this.continueWith(results) } catch { @@ -2984,6 +3094,7 @@ class Proc { this.sessionPrompts++ if (turn.promptSentAt == null) turn.promptSentAt = Date.now() let result + const capacityWatch = this.#watchCapacity(turn) try { result = await this.conn.request("session/prompt", { sessionId: this.sessionId, @@ -2991,6 +3102,7 @@ class Proc { }) } finally { turn.promptInFlight = false + clearInterval(capacityWatch) } if (promptNumber === 1) { // how long agy took to answer, beside the session row's start-up steps @@ -3148,6 +3260,36 @@ class Proc { // A try Antigravity answered with the bare 429 ends the turn now, with the // same error as agy's own 429 ending, instead of after agy's retries: the // process goes, as on a timeout, since agy is still retrying in it. + // Reads agy's log while nothing has reached the client, for the retry of + // a "no capacity" 503 (noCapacity). + #watchCapacity(turn) { + let reading = false + const quiet = () => !turn.done && turn.firstOutputAt == null && !turn.calls.length + const timer = setInterval(async () => { + if (reading || !quiet()) return + reading = true + try { + const detail = await lastAgentError(this.logPath, turn.logOffset) + if (noCapacity(detail) && quiet()) this.capacityTurn(turn, detail) + } finally { + reading = false + } + }, CAPACITY_POLL_MS) + timer.unref?.() + return timer + } + + capacityTurn(turn, detail) { + if (this.turn !== turn || turn.done) return + logSessionEvent(this, this.sessionReason ?? null, { + waited_ms: turn.promptSentAt != null ? Date.now() - turn.promptSentAt : null, + detail, + }, "no_capacity") + turn.fail(new AgentTurnError(`agy bridge: Antigravity has no capacity for this model now: ${detail}`, "overloaded_error")) + dropFromPool(this) + this.stop().catch(() => {}) + } + refuseTurn(turn, detail) { if (this.turn !== turn || turn.done) return turn.fail(this.#formatAgentError(detail)) @@ -3182,9 +3324,24 @@ class Proc { if (!args || typeof args !== "object" || Array.isArray(args)) throw new Error("agy bridge: invalid tool arguments") const tool = this.tools.find((item) => item.name === name) if (!tool) throw new Error(`agy bridge: undeclared tool ${name}`) - // agy consumes its internal toolSummary instead of forwarding it to MCP. - if (name === "run_command" && tool.inputSchema?.properties?.toolSummary && !Object.hasOwn(args, "toolSummary")) { - args = { ...args, toolSummary: "Run command" } + const spilled = spilledOutput(this.agyDir, name, args) + if (spilled) { + socket.end(JSON.stringify({ result: spilled }) + "\n") + return null + } + // agy consumes its internal toolSummary instead of forwarding it to MCP, so + // a call it makes reaches us without one. The client (an outer agy) declared + // the field required on the tool, so put a value back before handing the + // call on. We dropped the incoming toolSummary from every tool's required + // list above, so this restore is for every tool whose schema declares it, + // not run_command alone. + if (tool.inputSchema?.properties?.toolSummary && !Object.hasOwn(args, "toolSummary")) { + args = { ...args, toolSummary: name === "run_command" ? "Run command" : name } + } + // Outer agy expects call_mcp_tool.Arguments as a JSON object for jsontext.Value, + // while Gemini schema translation exposes Arguments as type:"string" inside ACP. + if (name === "call_mcp_tool") { + args = unwrapCallMcpArguments(args) } const signature = stableJSON(args) const running = turn.calls.find((call) => call.deferred && !call.lateDelivered && @@ -3199,6 +3356,7 @@ class Proc { ready: true, socket, result: null, + rawResultKey: null, deferred: false, lateDelivered: false, deadline: null, @@ -3289,15 +3447,15 @@ class Proc { const unique = new Map() for (const item of results) { const id = item.block.tool_use_id - const serialized = JSON.stringify(item.result) + const rawKey = item.rawKey ?? JSON.stringify(item.result) const previous = unique.get(id) - if ((previous && JSON.stringify(previous.result) !== serialized) || - (item.call.result && JSON.stringify(item.call.result) !== serialized)) { + const storedKey = item.call.rawResultKey ?? (item.call.result ? JSON.stringify(item.call.result) : null) + if ((previous && previous.rawKey !== rawKey) || (storedKey !== null && storedKey !== rawKey)) { const error = new Error(`agy bridge: conflicting duplicate result for ${id}`) error.statusCode = 409 throw error } - if (!previous) unique.set(id, item) + if (!previous) unique.set(id, item.rawKey === rawKey ? item : { ...item, rawKey }) } return unique } @@ -3306,21 +3464,49 @@ class Proc { const turn = this.turn if (!turn || turn.finalized) throw new BusyError("agy bridge: no response is waiting for these tool results") turn.touchClient() - for (const { call, result } of this.validateResults(results).values()) { + let delivered = 0 + for (const { call, result, rawKey } of this.validateResults(results).values()) { clearTimeout(call.deadline) if (call.deferred) { if (!call.result) { call.result = result + call.rawResultKey = rawKey + delivered++ this.#deliverLate(turn, call) } continue } if (call.mcpResponded || !call.ready || turn.done) continue call.result = result + call.rawResultKey = rawKey + delivered++ this.#respondMcp(call, { result }) } + if (delivered > 0) { + turn.lastToolStep = null + turn.stepSeq++ + } turn.arm() this.lastUsed = Date.now() + return delivered + } + + canReplayLastToolStep(turn, req) { + const last = turn?.lastToolStep + if (!last) return null + if (this.dead || this.stopping || this.retiring || this.turn !== turn) return null + if (turn.done || turn.finalized || turn.attached || turn.steering || turn.cancelRequested) return null + if (staleTurnVerdict(this, turn).stale) return null + if (!Array.isArray(this.expectedMessages) || this.expectedMessages.length !== last.expectedLength) return null + if (!sameSessionScope(this, req.sessionScope)) return null + if (!Array.isArray(last.emittedCalls) || !last.emittedCalls.length) return null + for (const call of last.emittedCalls) { + if (call.result || call.clientSeen) return null + if (call.mcpResponded && (!call.deferred || call.lateDelivered)) return null + if (this.#selfPollCapped(turn, call)) return null + } + if (!sameCallIds(req.matches, last.callIds) || !req.requestDigest || req.requestDigest !== last.requestDigest) return null + return last } #respondMcp(call, payload) { @@ -3339,6 +3525,7 @@ class Proc { } turn.cancelledMcpSockets.clear() turn.steering = false + turn.lastToolStep = null if (turn.stepsFile && turn.promptCount > 0 && !turn.stepUsageReconciled) { this.stepUsageTrusted = false } @@ -4476,11 +4663,15 @@ function replayHistoryProblem(body, resultBlocks) { async function keepDroppedTurn(proc, turn, opts) { if (proc.toolsGrew(opts.tools) || proc.workDir !== opts.workDir || !sameInstructions(proc.instructions, opts.instructions)) return false - const results = turn.calls.filter((call) => call.id && !call.result && !call.mcpResponded).map((call) => ({ - block: { tool_use_id: call.id }, - call, - result: { content: [{ type: "text", text: DROPPED_NOTE }], isError: true }, - })) + const results = turn.calls.filter((call) => call.id && !call.result && !call.mcpResponded).map((call) => { + const result = { content: [{ type: "text", text: DROPPED_NOTE }], isError: true } + return { + block: { tool_use_id: call.id }, + call, + result, + rawKey: JSON.stringify(result), + } + }) try { return await proc.steerInSession(turn, results, opts.history) } catch { @@ -4549,6 +4740,25 @@ function stableJSON(value) { : item) } +/** + * Parse a JSON-object string in call_mcp_tool.Arguments back into an object, + * leaving malformed or non-object values untouched. + */ +function unwrapCallMcpArguments(args) { + if (!args || typeof args.Arguments !== "string") return args + const raw = args.Arguments.trim() + if (!raw) return args + try { + const parsed = JSON.parse(raw) + if (parsed !== null && typeof parsed === "object" && !Array.isArray(parsed)) { + return { ...args, Arguments: parsed } + } + } catch { + // Keep the raw string so upstream schema/tool errors stay visible. + } + return args +} + function parseUserImage(block) { if (block?.type !== "image") return null const mediaType = String(block.source?.media_type || "").toLowerCase() @@ -4611,7 +4821,8 @@ function renderServerAssistantBlock(block) { } const MAGPIE_PLACEHOLDER_NOTICE = "Values written like {{NAME_ab12cd34}} are placeholders for real values. Use them exactly as written, in replies and in tool calls alike: they are filled in with the real values before anything runs. Don't ask to verify them, and don't replace them with examples." -const MAGPIE_PLACEHOLDER_NOTICE_RE = /(?:^|\n\n)Values written like \{\{NAME_ab12cd34\}\} are placeholders for real values\. Use them exactly as written, in replies and in tool calls alike: they are filled in with the real values before anything runs\. Don't ask to verify them, and don't replace them with examples\.(?=\s|$)/g +const MAGPIE_PLACEHOLDER_NOTICE_BODY = "Values written like \\{\\{NAME_ab12cd34\\}\\} are placeholders for real values\\. Use them exactly as written, in replies and in tool calls alike: they are filled in with the real values before anything runs\\. Don't ask to verify them, and don't replace them with examples\\." +const MAGPIE_PLACEHOLDER_NOTICE_RE = new RegExp(`(?:^|\\n\\n)(?:\\s*${MAGPIE_PLACEHOLDER_NOTICE_BODY}\\s*<\\/system-reminder>|${MAGPIE_PLACEHOLDER_NOTICE_BODY})(?=\\s|$)`, "g") function stripMagpiePlaceholderNotice(text) { if (typeof text !== "string" || !text.includes("{{NAME_ab12cd34}}")) return text @@ -4755,7 +4966,7 @@ function stripAgentClockLines(text) { // System prompt and session instructions: billing headers plus known agent // clock lines. User text is never passed through this helper. function stripVolatileSystem(text) { - return stripAgentClockLines(stripBillingHeader(text)) + return stripMagpiePlaceholderNotice(stripAgentClockLines(stripBillingHeader(text))) } function instructionsIdentity(text) { @@ -5099,6 +5310,7 @@ function findLiveContinuedProc(opts) { let tied = false for (const proc of pool.values()) { if (proc.dead || proc.retiring || proc.turn) continue + if (!sameAccount(proc)) continue if ((proc.userId || "") !== userId) continue if ((proc.sessionScope || "") !== sessionScope) continue if (proc.workDir !== opts.workDir) continue @@ -5379,6 +5591,70 @@ function sameHistoryUpToMasking(expected, actual) { return sameUpToMasking(historyRows(expected), historyRows(actual)) } +// What magpie's image-slim middleware writes where it took out an image the +// model has already seen: a text block, or on Codex a whole view_image output +// set to it as a plain string. +const IMAGE_SLIM_RE = /^\[\d+(?:\.\d+)? MB image left out here: [\s\S]*\]$/ +// magpie's gateway writes these where it leaves out an earlier image itself: +// under a provider's byte cap (body_cap.go imageLeftOut), a model's image cap +// (image_cap.go imageOverCap), or an image the request carries again later +// (imageShownLater). agy has seen each of those images too. +const MAGPIE_IMAGE_PLACEHOLDERS = new Set([ + "[An earlier image was left out here to keep this request under its size limit.]", + "[An earlier image was omitted here to keep this request within the model's image limit.]", + "[This image is omitted here; the same image appears again later in this conversation.]", +]) + +function isImagePlaceholder(text) { + if (typeof text !== "string") return false + const trimmed = text.trim() + return IMAGE_SLIM_RE.test(trimmed) || MAGPIE_IMAGE_PLACEHOLDERS.has(trimmed) +} + +function isImageSlot(block) { + return block?.type === "image" || (block?.type === "text" && isImagePlaceholder(block.text)) +} + +// How many images a message has where they were, each counted as an image or +// as the placeholder that stands for it, tool results' included. +function imageSlots(message) { + if (!Array.isArray(message?.content)) return isImagePlaceholder(message?.content) ? 1 : 0 + let n = 0 + for (const block of message.content) { + if (isImageSlot(block)) n++ + else if (block?.type === "tool_result") { + if (typeof block.content === "string") n += isImagePlaceholder(block.content) ? 1 : 0 + else if (Array.isArray(block.content)) n += block.content.filter(isImageSlot).length + } + } + return n +} + +function withoutImages(messages) { + const kept = (block) => !isImageSlot(block) + const resultContent = (content) => typeof content === "string" + ? (isImagePlaceholder(content) ? [] : content) + : content.filter(kept) + return messages.map((message) => !Array.isArray(message?.content) ? message : { + ...message, + content: message.content.filter(kept).map((block) => block?.type === "tool_result" && + (Array.isArray(block.content) || typeof block.content === "string") + ? { ...block, content: resultContent(block.content) } + : block), + }) +} + +// The same history but for images swapped for placeholders. Each message +// keeps as many images-or-placeholders as it had, so an image added to or +// taken out of an earlier message is still a changed history. +function sameHistoryUpToImages(expected, actual) { + if (!Array.isArray(expected) || !Array.isArray(actual) || expected.length !== actual.length) return false + if (expected.some((message, i) => imageSlots(message) !== imageSlots(actual[i]))) return false + const a = withoutImages(expected) + const b = withoutImages(actual) + return historyKey(a) === historyKey(b) || sameHistoryUpToMasking(a, b) +} + // One block as the history key reads it, or null for a block the key // leaves out (thinking, tool catalog changes). ids numbers tool calls in // order, so a client's ids of its own key the same. @@ -5478,8 +5754,9 @@ function assistantTextOf(message) { // run: runStart = first message of the trailing text-only assistant run, // boundary = history split point (after the last assistant message before the // run, the session ledger's newest entry). Returns null when the request does -// not end with a text-only assistant run. Known limits: a request combining a -// live tool_result with a prefill tail is rejected in validateBody; a run with +// not end with a text-only assistant run. A tool_result with a prefill tail +// (magpie going on from a reply cut after a tool round, plugins#1512) is +// replayed into a fresh session. Known limits: a run with // no user message before it (contiguous assistant tail, e.g. a client re-sending // a completed reply with a prefill appended) puts the whole run in the tail, so // that one turn degrades to a fresh session (safe, self-healing). @@ -5518,6 +5795,42 @@ function lastAssistantCalls(messages) { ? message.content.filter(block => block.type === "tool_use") : []) } +// agy cuts a tool result over its size short, saves the whole of it as +// /brain//.system_generated/steps//output.txt and +// has the model read that file. With magpie on a server (Docker) and the +// client on another machine, the client's Read of that path fails: the +// file is only where agy runs (Dani Ariyanto on Discord). So a read-type +// tool whose one path is such a file is answered here, from the file, and +// never reaches the client; null for any other call. Lines are numbered, +// from offset (a line number) for at most limit lines when the call says. +const SPILLED = /^brain[\\/][^\\/]+[\\/]\.system_generated[\\/]steps[\\/][^\\/]+[\\/]output\.txt$/ + +export function spilledOutput(agyDir, name, args) { + if (!agyDir || !/read|view/i.test(name) || !args || typeof args !== "object") return null + const paths = Object.values(args).filter((value) => typeof value === "string" && path.isAbsolute(value)) + if (paths.length !== 1 || !SPILLED.test(path.relative(agyDir, path.resolve(paths[0])))) return null + let text + try { + // a link out of agy's folder is not followed + const real = fs.realpathSync(paths[0]) + if (!SPILLED.test(path.relative(fs.realpathSync(agyDir), real))) return null + text = fs.readFileSync(real, "utf8") + } catch { + return null + } + const number = (key) => { + const value = Number(args[key]) + return Number.isFinite(value) && value > 0 ? Math.floor(value) : 0 + } + const lines = text.split("\n") + if (lines.length > 1 && lines[lines.length - 1] === "") lines.pop() + const from = Math.max(1, number("offset")) + const to = number("limit") ? Math.min(lines.length, from - 1 + number("limit")) : lines.length + const out = [] + for (let n = from; n <= to; n++) out.push(`${String(n).padStart(6)}\t${lines[n - 1]}`) + return { content: [{ type: "text", text: out.join("\n") }], isError: false } +} + // A bridge call's id, as #handleMcpCall makes it. const BRIDGE_CALL_ID = /^toolu_[0-9a-f]{24}$/ @@ -5593,8 +5906,58 @@ function foldSplitCalls(body) { return changed ? { ...body, messages: out } : body } +// Claude Code's AgentSummary: the sub-agent's own conversation, sent again +// while it works with its last user message ending in the ask for a few +// words of progress ("Describe your most recent action in 3-5 words. Do not +// use tools."), as magpie's agentSummaryAsk tells it. Only a sub-agent's +// (x-magpie-subagent) is one. In the worker's scope +// it was the worker's conversation, whose response was still running: seven +// 503 "already has an active response" over ~34s, each try retried +// (plugins#1545). It gets a scope of its own, beside the worker's. +const AGENT_SUMMARY_SCOPE = "\nagent-summary" + +function agentSummaryAsk(body) { + const last = body?.messages?.at(-1) + if (last?.role !== "user") return false + const part = typeof last.content === "string" ? { type: "text", text: last.content } : last.content?.at?.(-1) + if (part?.type !== "text" || typeof part.text !== "string") return false + const ask = part.text.trim() + return ask.startsWith("Describe your ") && ask.includes(" in 3-5 words") +} + +// An agy runs under one account's sign-in (Proc.home), so a request of +// another account never goes on in it, not even when its opening or tool +// ids match: it would be answered with that account's credentials and +// quota, and its 429 would rest this account too (Archivemylife on X: +// two Google accounts used up and reset together). +function sameAccount(proc) { + return !!proc && (proc.home ?? null) === (currentHome() ?? null) +} + function sameSessionScope(proc, sessionScope = "") { - return (proc?.sessionScope || "") === sessionScope + return sameAccount(proc) && (proc?.sessionScope || "") === sessionScope +} + +function sameCallIds(matches, callIds) { + return Array.isArray(callIds) && matches.length === callIds.length && + matches.every((item, i) => item.block.tool_use_id === callIds[i]) +} + +function toolStepRequestDigest({ trailing, matches, results, workDir, instructions, tools, model, wireModel, effort, forwardThinking, outputFormat }) { + return digest(stableJSON({ + history: historyKey(trailing.history), + tail: historyKey(trailing.messages), + callIds: matches.map((m) => m.block.tool_use_id), + results: results.map((r) => [r.block.tool_use_id, r.result]), + workDir, + instructions, + tools: stableJSON(tools), + model, + wireModel, + effort, + forwardThinking, + outputFormat, + })) } function matchToolResults(body, blocks, sessionScope = "") { @@ -5674,6 +6037,13 @@ function sameInstructions(a, b) { return instructionsIdentity(a) === instructionsIdentity(b) } +function requestHeader(fetchInput, init, name) { + const headers = new Headers( + init?.headers ?? (fetchInput instanceof Request ? fetchInput.headers : undefined) ?? {}, + ) + return headers.get(name)?.trim() || "" +} + // The model is not part of the key: agy switches models inside a live session. function requestSessionScope(fetchInput, init) { const headers = new Headers( @@ -5685,7 +6055,12 @@ function requestSessionScope(fetchInput, init) { return session || subagent ? `${session}\n${subagent}` : "" } -function conversationKey(rawBody, sessionScope = "") { +// workDir: the directory the client names for this conversation. Two chats +// whose opening is identical (DSH opens every session with the same +// approval-policy notice) but run in different folders are different +// conversations; without it they share one agy session and each one's +// request is refused while the other's response runs. +function conversationKey(rawBody, sessionScope = "", workDir = "") { const body = canonicalBody(rawBody) const system = historyKey([{ role: "system", content: compactIdentity(stripVolatileSystem(systemText(body))) }]) const first = body.messages?.[0] @@ -5697,7 +6072,7 @@ function conversationKey(rawBody, sessionScope = "") { const firstText = first ? historyKey([first]) : "" const userId = body.metadata?.user_id || "" const discriminator = sessionScope ? `${userId}\n${sessionScope}` : userId - const source = discriminator + "\n" + system + "\n===\n" + firstText + const source = discriminator + "\n" + system + "\n===\n" + firstText + (workDir ? "\n@@@\n" + workDir : "") return createHash("sha256").update(source).digest("hex") } function appendSchemaHint(node, hint) { @@ -5849,9 +6224,14 @@ function normalizeTools(body) { throw new UnsupportedContent(`an invalid schema for tool ${tool.name}`) } const inputSchema = ensureGeminiArrayItems(sanitizeInputSchema(expandToolSchema(rawSchema))) - // agy adds its own required toolSummary to MCP tools. A duplicate makes - // the resulting JSON Schema invalid before the agent can start. - if (tool.name === "run_command" && Array.isArray(inputSchema.required)) { + // agy adds its own required toolSummary to every tool it loads (run_command + // and the MCP tools alike). When the client already lists toolSummary as + // required — e.g. an outer agy injected it before forwarding the tool here — + // agy re-adds it and the duplicate ('allOf' /required items 0 and 1 equal) + // makes the JSON Schema invalid, so the toolbox fails to build. Drop the + // incoming toolSummary from every tool's required list so agy adds exactly + // one, as it does for a tool it sees fresh. + if (Array.isArray(inputSchema.required)) { inputSchema.required = inputSchema.required.filter((key) => key !== "toolSummary") } tools.push({ @@ -5912,7 +6292,41 @@ function imageContent(block) { source.data.length % 4 !== 0 || /[^A-Za-z0-9+/]/.test(source.data.replace(/={1,2}$/, ""))) { throw new UnsupportedContent("invalid base64 image data") } - return { type: "image", data: source.data, mimeType: source.media_type } + // Gemini answers "Unable to process input image" for base64 that is valid + // but no image (a truncated capture, a tool's stub, a text file labelled + // image/png). An image sent as another of the four types (a JPEG labelled + // image/png, common in screenshot tools) goes as what it is. + const mimeType = imageTypeOf(source.data) + if (!mimeType) { + const decoded = Buffer.from(source.data.slice(0, 16), "base64") + const note = decoded.length === 0 ? "empty" : `not an image (first bytes: ${decoded.subarray(0, 8).toString("hex")})` + throw new UnsupportedContent(`an image whose data is ${note}`) + } + return { type: "image", data: source.data, mimeType } +} + +// imageTypeOf is the image type base64 data's first bytes say, of the four +// Gemini takes, or null. WebP is RIFF....WEBP; the others are their file +// signatures. Only the head is decoded. +export function imageTypeOf(data) { + const buf = typeof data === "string" ? Buffer.from(data.slice(0, 16), "base64") : data + if (!buf || buf.length < 4) return null + if (buf.length >= 8 && + buf[0] === 0x89 && buf[1] === 0x50 && buf[2] === 0x4e && buf[3] === 0x47 && + buf[4] === 0x0d && buf[5] === 0x0a && buf[6] === 0x1a && buf[7] === 0x0a) return "image/png" + if (buf[0] === 0xff && buf[1] === 0xd8 && buf[2] === 0xff) return "image/jpeg" + if (buf.length >= 6 && + buf[0] === 0x47 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x38 && + (buf[4] === 0x37 || buf[4] === 0x39) && buf[5] === 0x61) return "image/gif" + if (buf.length >= 12 && + buf[0] === 0x52 && buf[1] === 0x49 && buf[2] === 0x46 && buf[3] === 0x46 && + buf[8] === 0x57 && buf[9] === 0x45 && buf[10] === 0x42 && buf[11] === 0x50) return "image/webp" + return null +} + +// hasImageSignature is the data's magic bytes matching the type it was sent as. +export function hasImageSignature(buf, mimeType) { + return !!mimeType && imageTypeOf(buf) === mimeType } // Keep text adjacent to its images, including when an old conversation has to @@ -6049,12 +6463,44 @@ function renderTurnMessage(message) { return out.join("\n\n") } -function renderTurnMessageParts(message) { - if (message.role !== "user" || !Array.isArray(message.content)) { - let text = renderTurnMessage(message) +function renderTurnMessageSegments(message) { + if (message.role !== "user") { + const blocks = Array.isArray(message.content) ? message.content : [message.content] + const reminders = [] + const queuedParts = [] + for (const block of blocks) { + const raw = blockText(block) + const trimmed = raw.trim() + if (!trimmed) continue + const queued = extractQueuedPrompt(trimmed) + if (queued !== null) { + if (queued) queuedParts.push(queued) + } else { + reminders.push(raw) + } + } + const out = [] // a system or developer message later in the chat is system text too - if (message.role === "system" || message.role === "developer") text = outgoing(text) - return text === "" ? [] : [{ type: "text", text }] + const format = (text) => (message.role === "system" || message.role === "developer" ? outgoing(text) : text) + const joinedReminders = reminders.join("").trim() + if (joinedReminders) { + const wrapped = /^]*)?>[\s\S]*<\/system-reminder(?:\s[^>]*)?>$/.test(joinedReminders) + ? joinedReminders + : `\n${joinedReminders}\n` + const text = format(wrapped) + if (text) out.push({ type: "text", text, kind: "meta" }) + } + for (const queued of queuedParts) { + const text = format(queued) + if (!text) continue + if (out.length) out.push({ type: "text", text: "\n\n", kind: "meta" }) + out.push({ type: "text", text, kind: isMetaOnlyUserText(queued) ? "meta" : "user" }) + } + return out + } + if (!Array.isArray(message.content)) { + const text = renderTurnMessage(message) + return text === "" ? [] : [{ type: "text", text, kind: isMetaOnlyUserText(text) ? "meta" : "user" }] } const parts = [] let afterToolResult = false @@ -6063,37 +6509,52 @@ function renderTurnMessageParts(message) { parts.push(parseUserImage(block)) afterToolResult = false } else if (block?.type === "tool_result") { - appendPrompt(parts, `[tool result${block.tool_use_id ? " id=" + block.tool_use_id : ""}]\n`) + const toolParts = [] + appendPrompt(toolParts, `[tool result${block.tool_use_id ? " id=" + block.tool_use_id : ""}]\n`) const result = toolResult(block) - for (const part of result.content) appendPrompt(parts, [part]) - appendPrompt(parts, "\n[end of tool result]") + for (const part of result.content) appendPrompt(toolParts, [part]) + appendPrompt(toolParts, "\n[end of tool result]") + for (const part of toolParts) { + parts.push(part.type === "text" ? { type: "text", text: part.text, kind: "tool" } : part) + } afterToolResult = true } else { const raw = blockText(block) const queued = block?.type === "text" ? extractQueuedPrompt(raw) : null const rendered = queued !== null ? queued : raw - appendPrompt(parts, rendered && afterToolResult && !rendered.startsWith("\n") ? "\n\n" + rendered : rendered) - if (rendered) afterToolResult = false + const text = rendered && afterToolResult && !rendered.startsWith("\n") ? "\n\n" + rendered : rendered + if (text) { + parts.push({ type: "text", text, kind: isMetaOnlyUserText(rendered) ? "meta" : "user" }) + afterToolResult = false + } } } - return toPromptParts(parts) + return parts } -function renderTurnMessagesParts(messages) { +function renderTurnMessageParts(message) { + return toPromptParts(renderTurnMessageSegments(message)) +} + +function renderTurnMessagesSegments(messages) { // A trailing assistant prefill run renders as a continuation carrier rather // than the system-reminder treatment (see prefillRun above). const run = prefillTailEnabled() && messages.length ? prefillRun(messages) : null const prefillStart = run ? run.runStart : -1 const groups = messages.map((message, index) => prefillStart >= 0 && index >= prefillStart - ? renderPrefillCarrierParts(message) - : renderTurnMessageParts(message)).filter((group) => group.length > 0) + ? renderPrefillCarrierParts(message).map((part) => (part.type === "text" ? { ...part, kind: "user" } : part)) + : renderTurnMessageSegments(message)).filter((group) => group.length > 0) const out = [] for (let i = 0; i < groups.length; i++) { - if (i > 0) out.push({ type: "text", text: "\n\n" }) + if (i > 0) out.push({ type: "text", text: "\n\n", kind: "meta" }) out.push(...groups[i]) } - return toPromptParts(out) + return out +} + +function renderTurnMessagesParts(messages) { + return toPromptParts(renderTurnMessagesSegments(messages)) } // agy's ACP server cuts a prompt at 128 KiB and appends "", @@ -6137,15 +6598,26 @@ function utf8Prefix(text, bytes) { function clipMiddle(text, limit, keep = Math.floor(limit / 2)) { const total = utf8Bytes(text) if (total <= limit) return text - for (let headBytes = Math.min(keep, limit), tries = 0; tries < 8; tries++) { + if (limit <= 0) return "" + const maxMarker = utf8Bytes(`\n[... ${total} bytes omitted ...]\n`) + if (limit <= maxMarker) return utf8Prefix(text, limit) + let bodyBudget = Math.min(limit - maxMarker, keep * 2) + for (let tries = 0; tries < 8 && bodyBudget > 0; tries++) { + const headBytes = Math.min(keep, Math.floor(bodyBudget / 2)) + const tailBytes = Math.min(keep, bodyBudget - headBytes) const head = utf8Prefix(text, headBytes) - const tailStart = utf8Prefix(text, total - Math.max(0, Math.min(keep, limit - headBytes))).length + const tailStart = utf8Prefix(text, Math.max(0, total - tailBytes)).length const tail = text.slice(Math.max(tailStart, head.length)) - const marker = `\n[... ${total - utf8Bytes(head) - utf8Bytes(tail)} bytes omitted ...]\n` + const omitted = total - utf8Bytes(head) - utf8Bytes(tail) + if (omitted <= 0) { + bodyBudget = Math.max(0, bodyBudget - 4) + continue + } + const marker = `\n[... ${omitted} bytes omitted ...]\n` const clipped = head + marker + tail - if (utf8Bytes(clipped) <= limit) return clipped - keep = Math.floor(keep * 0.75) - headBytes = Math.min(keep, limit) + const over = utf8Bytes(clipped) - limit + if (over <= 0) return clipped + bodyBudget = Math.max(0, bodyBudget - over) } return utf8Prefix(text, limit) } @@ -6168,8 +6640,8 @@ function headTail(text) { // What the user wrote is clipped only past `userLimit`, which the caller sets // well above a tool result's: a request often states what to do in the middle // of a long paste, and tool output gives way first (plugins#1401). -function clipHistoryMessage(message, userLimit = HISTORY_BLOCK_CLIP_BYTES) { - const clipText = (text) => message.role === "user" && userLimit > HISTORY_BLOCK_CLIP_BYTES && !isMetaOnlyUserText(text) +function clipHistoryMessage(message, userLimit = HISTORY_BLOCK_CLIP_BYTES, preserveMeta = false) { + const clipText = (text) => message.role === "user" && userLimit > HISTORY_BLOCK_CLIP_BYTES && (preserveMeta || !isMetaOnlyUserText(text)) ? clipMiddle(text, userLimit) : clipHistoryText(text) if (typeof message.content === "string") return { ...message, content: clipText(message.content) } @@ -6224,6 +6696,42 @@ function clipPartsToBytes(parts, limit) { return out } +// Shrinks segments to fit `limit` bytes: meta reminders and +// trailing system messages yield first, then tool results, and user text last +// so a short user message sandwiched between post-compact reminders and a +// trailing system block is not sliced out of the middle. +function clipTurnSegments(segments, limit) { + const out = segments.map((part) => ({ ...part })) + if (promptTextBytes(out) <= limit) return out + for (const kind of ["meta", "tool", "user"]) { + const excess = promptTextBytes(out) - limit + if (excess <= 0) return out + const tier = out.filter((part) => part.type === "text" && part.kind === kind) + if (!tier.length) continue + const sizes = tier.map((part) => utf8Bytes(part.text)) + const tierBytes = sizes.reduce((sum, size) => sum + size, 0) + if (tierBytes <= 0) continue + const tierBudget = Math.max(0, tierBytes - excess) + let rem = tierBudget + let cap = 0 + const sorted = [...sizes].sort((a, b) => a - b) + for (let i = 0; i < sorted.length; i++) { + const share = Math.floor(rem / (sorted.length - i)) + if (sorted[i] <= share) { + rem -= sorted[i] + } else { + cap = share + break + } + } + for (let i = 0; i < tier.length; i++) { + if (sizes[i] <= cap) continue + tier[i].text = cap <= 0 ? "" : clipMiddle(tier[i].text, cap) + } + } + return promptTextBytes(out) <= limit ? out : clipPartsToBytes(out, limit) +} + // Claude Code's and DeepSeek Harness's own user-role notes: reminders, context // notices, local command output, interrupt markers, clock and runtime-context // snapshots, repeat-tool warnings and mode switches. A user message of these @@ -6241,6 +6749,152 @@ const DSH_TMUX_RE = /(?:^|\r?\n)tmux location \(turn \d+\):\r?\nsession [^\r\n]* const DSH_JOB_RE = /(?:^|\r?\n)background job \S+ \([^\r\n]*\) finished [^\r\n]*/g const DSH_MODEL_NOTE_RE = /(?:^|\r?\n)\[model changed: assistant turns above this point were generated by [^\r\n]*\]/g const DSH_NOTE_RES = [DSH_TIME_CONTEXT_RE, DSH_REPEAT_TOOL_RE, DSH_PLAN_MODE_RE, DSH_TMUX_RE, DSH_JOB_RE, DSH_MODEL_NOTE_RE] +const AVAILABLE_SKILLS_OPEN = "" +const AVAILABLE_SKILLS_CLOSE = "" +const WORKSPACE_BUDGET_LINE_RE = /^Workspace instruction budget \d+ bytes: [^\r\n]+(?:\r?\n+|$)/ +const WORKSPACE_INSTRUCTIONS_PREFIX = "The following workspace instructions may be relevant to your work." +const REPLACEMENT_BASELINE_PREFIX = "This complete workspace instruction baseline replaces all earlier workspace instruction baselines." +const EMPTY_WORKSPACE_INSTRUCTIONS_PREFIX = "No workspace instructions are currently active." +const COMPACT_WORKSPACE_INSTRUCTIONS_PREFIX = "Workspace instructions were omitted or truncated to fit the configured byte budget." +const BASELINE_INSTRUCTION_PATH_RE = /(?:^|\r?\n)Instructions from:\s*([^\r\n]+)/g +const INSTRUCTION_CHANGE_FIRST_LINE_RE = /^(?:Updated instructions from|Additional instructions from|Instructions removed):\s*([^\r\n]+)/ +const INSTRUCTION_CHANGE_PATH_RE = /(?:^|\r?\n)(?:Updated instructions from|Additional instructions from|Instructions removed):\s*([^\r\n]+)/g +const SESSION_INFO_PREFIX = "The following information describes your current session" + +function matchPaths(text, re) { + const paths = [] + for (const match of text.matchAll(re)) { + const file = match[1]?.trim() + if (file) paths.push(file) + } + return paths +} + +// Extract closed inner blocks linearly (via indexOf in +// replaceClosedSystemReminders) only when the surrounding text is meta-only, +// so user-pasted logs/tests quoting those tags are never treated as state. +function extractMetaRemindersFromText(text) { + if (typeof text !== "string" || !asciiLower(text).includes(" { + const gt = block.indexOf(">") + const close = asciiLower(block).lastIndexOf("") + if (gt !== -1 && close > gt) blocks.push(block.slice(gt + 1, close).trim()) + return "" + }).trim() + if (!blocks.length) return [] + if (rest && !isMetaOnlyUserText(rest)) return [] + return blocks +} + +function extractMessageMetaReminders(message, perBlock = false) { + if (message?.role !== "user" || isToolResultMessage(message)) return [] + if (typeof message.content === "string") return extractMetaRemindersFromText(message.content) + if (!Array.isArray(message.content)) return [] + if (!perBlock) { + if (message.content.some((block) => block?.type === "image")) return [] + return extractMetaRemindersFromText(messageText(message)) + } + const blocks = [] + for (const block of message.content) { + const text = blockText(block) + if (text) blocks.push(...extractMetaRemindersFromText(text)) + } + return blocks +} + +// Classify a meta-only emitted by @deepseek-ai/dsh-agent-instructions: +// baselines (initial, replacement, empty replacement, or compact budget fallback) +// and reconciliation change batches (Updated / Additional / Instructions removed). +function parseWorkspaceInstructionReminder(inner) { + const body = inner.replace(WORKSPACE_BUDGET_LINE_RE, "").trimStart() + const hadBudget = body.length !== inner.length + if ( + body.startsWith(WORKSPACE_INSTRUCTIONS_PREFIX) || + body.startsWith(REPLACEMENT_BASELINE_PREFIX) || + body.startsWith(EMPTY_WORKSPACE_INSTRUCTIONS_PREFIX) + ) { + return { kind: "baseline", paths: matchPaths(body, BASELINE_INSTRUCTION_PATH_RE) } + } + const afterCompact = body.startsWith(COMPACT_WORKSPACE_INSTRUCTIONS_PREFIX) + ? body.slice(COMPACT_WORKSPACE_INSTRUCTIONS_PREFIX.length).trimStart() + : body + const hadCompact = afterCompact.length !== body.length + if (INSTRUCTION_CHANGE_FIRST_LINE_RE.test(afterCompact)) { + return { kind: "changes", paths: matchPaths(afterCompact, INSTRUCTION_CHANGE_PATH_RE) } + } + if ((hadBudget || hadCompact) && /^Instructions from:\s*[^\r\n]+/.test(afterCompact)) { + return { kind: "baseline", paths: matchPaths(afterCompact, BASELINE_INSTRUCTION_PATH_RE) } + } + return null +} + +function isSessionInfoReminder(inner) { + if (DSH_RUNTIME_SNAPSHOT_RE.test(inner)) return true + if (!inner.startsWith(SESSION_INFO_PREFIX)) return false + const next = inner[SESSION_INFO_PREFIX.length] + return next === "." || next === ":" +} + +function isAvailableSkillsReminder(inner) { + if (parseWorkspaceInstructionReminder(inner) || isSessionInfoReminder(inner)) return false + const open = inner.indexOf(AVAILABLE_SKILLS_OPEN) + return open !== -1 && inner.indexOf(AVAILABLE_SKILLS_CLOSE, open + AVAILABLE_SKILLS_OPEN.length) !== -1 +} + +// Stateful user-role messages (DeepSeek Harness sends +// workspace instructions, session context, and as separate +// meta-only user messages after messages[0], replacing them only on change). +function sessionStateIndices(history, current) { + const currentBlocks = current.flatMap((msg) => extractMessageMetaReminders(msg, true)) + const historyBlocks = history.map((msg) => extractMessageMetaReminders(msg, false)) + const priority = [] + if (!currentBlocks.some(isAvailableSkillsReminder)) { + for (let i = history.length - 1; i >= 0; i--) { + if (historyBlocks[i].some(isAvailableSkillsReminder)) { + priority.push(i) + break + } + } + } + const currentWs = currentBlocks.map(parseWorkspaceInstructionReminder).filter(Boolean) + if (!currentWs.some((item) => item.kind === "baseline")) { + const historyWs = historyBlocks.map((blocks) => blocks.map(parseWorkspaceInstructionReminder).filter(Boolean)) + let wsIdx = -1 + for (let i = history.length - 1; i >= 0; i--) { + if (historyWs[i].some((item) => item.kind === "baseline")) { + wsIdx = i + break + } + } + const seenPaths = new Set(currentWs.flatMap((item) => item.kind === "changes" ? item.paths : [])) + const changeIdxs = [] + for (let i = history.length - 1; i > wsIdx; i--) { + const paths = historyWs[i].flatMap((item) => item.kind === "changes" ? item.paths : []) + if (paths.some((p) => !seenPaths.has(p))) { + paths.forEach((p) => seenPaths.add(p)) + changeIdxs.push(i) + } + } + priority.push(...changeIdxs) + if (wsIdx >= 0) { + const baselinePaths = historyWs[wsIdx].flatMap((item) => item.paths) + if (!baselinePaths.length || baselinePaths.some((p) => !seenPaths.has(p))) { + priority.push(wsIdx) + } + } + } + if (!currentBlocks.some(isSessionInfoReminder)) { + for (let i = history.length - 1; i >= 0; i--) { + if (historyBlocks[i].some(isSessionInfoReminder)) { + priority.push(i) + break + } + } + } + const unique = [...new Set(priority)] + return { priority: unique, set: new Set(unique) } +} // DSH's own notes in a user text, apart from what the user wrote. Beside a // live tool_result they are context for the model, never the user steering @@ -6436,22 +7090,22 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve if (system.trim()) appendPrompt(head, `\n${outgoing(system)}\n\n`) if (callerWorkDir) appendPrompt(head, `\n${workDirNote(callerWorkDir)}\n\n`) } - const currentParts = renderTurnMessagesParts(current) + const currentSegments = renderTurnMessagesSegments(current) // A fresh conversation needs no wrapper; it would only add tokens. - if (!head.length && !history.length) return { parts: clipPartsToBytes(currentParts, budget), stats: replayStats(history, [], [], []) } + if (!head.length && !history.length) return { parts: toPromptParts(clipTurnSegments(currentSegments, budget)), stats: replayStats(history, [], [], []) } const historyOpen = history.length ? "\n" : "" const historyClose = history.length ? HISTORY_RECORD_NOTE + "\n\n" : "" const turnOpen = "\n" const turnClose = "\n" const frame = utf8Bytes(historyOpen + historyClose + turnOpen + turnClose) // Mandatory segments first: instructions, the frame and the current turn. - // An oversized current turn keeps its head and tail; instructions shrink - // only when they alone would not leave the current turn any room. + // An oversized current turn clips meta/system reminders before user text; + // instructions shrink only when they alone would not leave the turn room. let headParts = head - let turn = currentParts + let turn = currentSegments if (promptTextBytes(headParts) + frame + promptTextBytes(turn) > budget) { const forTurn = Math.max(0, budget - frame - promptTextBytes(headParts)) - turn = clipPartsToBytes(turn, Math.max(forTurn, Math.min(promptTextBytes(turn), Math.floor((budget - frame) / 2)))) + turn = clipTurnSegments(turn, Math.max(forTurn, Math.min(promptTextBytes(turn), Math.floor((budget - frame) / 2)))) headParts = clipPartsToBytes(headParts, Math.max(0, budget - frame - promptTextBytes(turn))) } const render = (message) => { @@ -6474,7 +7128,7 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve short = promptTextBytes(headParts) + promptTextBytes(turn) + historyWant - available } if (short > 0 && promptTextBytes(turn) > Math.floor(available * REPLAY_TURN_SHARE)) { - turn = clipPartsToBytes(turn, Math.max(Math.floor(available * REPLAY_TURN_SHARE), promptTextBytes(turn) - short)) + turn = clipTurnSegments(turn, Math.max(Math.floor(available * REPLAY_TURN_SHARE), promptTextBytes(turn) - short)) } let room = budget - frame - promptTextBytes(headParts) - promptTextBytes(turn) const overRoom = (list) => list.reduce((sum, entry) => sum + entry.bytes, 0) > room @@ -6482,8 +7136,10 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve // blocks clipped first (#1055). let entries = raw let keptIndices = entries.map((_, i) => i) + const sessionState = overRoom(entries) ? sessionStateIndices(history, current) : { priority: [], set: new Set() } if (overRoom(entries)) { - entries = history.map((message) => render(clipHistoryMessage(message, Math.max(HISTORY_BLOCK_CLIP_BYTES, Math.floor(room / 3))))) + const 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 let showOpeningDone = false @@ -6545,7 +7201,28 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve ? Math.min(PINNED_USER_TASKS_BYTES - PINNED_USER_TASK_CLIP_BYTES + pinFirstBytes, Math.floor(room / (pinFirstBytes > PINNED_USER_TASK_CLIP_BYTES ? 3 : 4))) : 0 - let left = room - keptSliceBytes(keep, entries.length, entries, noteBytes) - pinReserve + const baseKeepBytes = keptSliceBytes(keep, entries.length, entries, noteBytes) + const tailFloor = entries.length > 0 && !keep.includes(entries.length - 1) + ? Math.min(entries.at(-1).bytes, Math.floor(room / 4)) + : 0 + const desiredStateCap = Math.floor(room / 2) + let desiredStateReserve = 0 + for (const idx of sessionState.priority) { + if (keep.includes(idx)) continue + const cost = entries[idx].bytes + noteBytes + if (desiredStateReserve + cost <= desiredStateCap) desiredStateReserve += cost + } + const stateReserveCap = Math.min( + desiredStateCap, + Math.max(0, room - baseKeepBytes - pinReserve - tailFloor), + ) + let stateReserve = 0 + for (const idx of sessionState.priority) { + if (keep.includes(idx)) continue + const cost = entries[idx].bytes + noteBytes + if (stateReserve + cost <= stateReserveCap) stateReserve += cost + } + let left = room - baseKeepBytes - pinReserve - stateReserve const floor = keep.length ? keep.at(-1) : -1 let { tail, left: remainingLeft } = fillHistoryTail(entries, floor, left, noteBytes) const lastIdx = entries.length - 1 @@ -6555,8 +7232,10 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve entries[0].bytes > Math.floor((room - noteBytes) / 2) && remainingLeft < Math.min(entries[lastIdx].bytes, Math.floor((room - noteBytes) / 2))) { const reservedLast = Math.min(entries[lastIdx].bytes, Math.floor((room - noteBytes) / 2)) - entries[0] = clipHistoryEntry(entries[0], Math.max(2048, room - noteBytes - reservedLast)) - left = room - keptSliceBytes(keep, entries.length, entries, noteBytes) + const stateCapAfterClip = Math.min(desiredStateReserve, Math.max(0, room - noteBytes - reservedLast - 2048)) + entries[0] = clipHistoryEntry(entries[0], Math.max(2048, room - noteBytes - reservedLast - stateCapAfterClip)) + stateReserve = stateCapAfterClip + left = room - keptSliceBytes(keep, entries.length, entries, noteBytes) - stateReserve ;({ tail, left: remainingLeft } = fillHistoryTail(entries, floor, left, noteBytes)) } if (tail.length === 0 && !keep.includes(lastIdx)) { @@ -6568,18 +7247,24 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve } } } + const combinedFits = (nextKeep) => + keptSliceBytes([...new Set([...nextKeep, ...tail])].sort((x, y) => x - y), entries.length, entries, noteBytes) <= room + for (const idx of sessionState.priority) { + if (keep.includes(idx) || tail.includes(idx)) continue + const nextKeep = [...keep, idx].sort((x, y) => x - y) + if (combinedFits(nextKeep)) keep = nextKeep + } if (pinReserve) { let pinned = 0 let pinnedBytes = 0 for (let idx = (tail.length ? tail[0] : entries.length) - 1; idx > 0 && pinned < PINNED_USER_TASKS_MAX; idx--) { - if (keep.includes(idx) || !isUserTask(history[idx])) continue + if (keep.includes(idx) || tail.includes(idx) || !isUserTask(history[idx])) continue const saved = entries[idx] // 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) const nextKeep = [...keep, idx].sort((x, y) => x - y) - if (pinnedBytes + entries[idx].bytes <= pinReserve && - keptSliceBytes([...nextKeep, ...tail], entries.length, entries, noteBytes) <= room) { + if (pinnedBytes + entries[idx].bytes <= pinReserve && combinedFits(nextKeep)) { keep = nextKeep pinned++ pinnedBytes += entries[idx].bytes @@ -6592,16 +7277,17 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve // 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. - if (inToolLoop && floor > 0) { - for (let idx = floor - 1; idx > 0; idx--) { - if (keep.includes(idx)) continue - const nextKeep = [...keep, idx].sort((x, y) => x - y) - if (keptSliceBytes([...nextKeep, ...tail], entries.length, entries, noteBytes) > room) break - keep = nextKeep - } + // newest first. Unused stateReserve is reclaimed the same way. + const fillStart = inToolLoop + ? floor - 1 + : (stateReserve > 0 ? (tail.length ? tail[0] : entries.length) - 1 : 0) + for (let idx = fillStart; idx > 0; idx--) { + if (keep.includes(idx) || tail.includes(idx)) continue + const nextKeep = [...keep, idx].sort((x, y) => x - y) + if (!combinedFits(nextKeep)) break + keep = nextKeep } - keptIndices = [...keep, ...tail] + keptIndices = [...new Set([...keep, ...tail])].sort((x, y) => x - y) kept = [] let next = 0 for (const i of keptIndices) { @@ -6623,14 +7309,14 @@ function renderInitialPrompt(body, callerWorkDir, instructionsInSession, reserve appendPrompt(out, historyClose) } appendPrompt(out, turnOpen) - appendPrompt(out, turn) + appendPrompt(out, toPromptParts(turn)) appendPrompt(out, turnClose) const stats = { ...replayStats(history, raw, keptIndices.map((i) => entries[i]), keptIndices), head_bytes: promptTextBytes(headParts), head_clipped: promptTextBytes(headParts) < promptTextBytes(head), turn_bytes: promptTextBytes(turn), - turn_clipped: promptTextBytes(turn) < promptTextBytes(currentParts), + turn_clipped: promptTextBytes(turn) < promptTextBytes(currentSegments), } return { parts: promptTextBytes(out) <= budget ? out : clipPartsToBytes(out, budget), stats } } @@ -6648,9 +7334,6 @@ function validateBody(body) { // A text-only assistant tail is a client-side prefill (see prefillRun). const prefillTail = prefillTailEnabled() && lastRole === "assistant" && assistantTextOf(body.messages.at(-1)) !== null const validTailRole = lastRole === "user" || lastRole === "system" || lastRole === "developer" || prefillTail - if (prefillTail && extractToolResults(body).length) { - throw new UnsupportedContent("a request combining a live tool_result with an assistant prefill tail") - } if (!validTailRole || (!extractToolResults(body).length && !trailing.messages.some((message) => message.role === "user") && !trailing.history.length)) { throw new UnsupportedContent(prefillTail @@ -6713,11 +7396,15 @@ function toolResult(block) { if (part?.type === "document") return { type: "text", text: parseUserDocumentText(part, true) } if (part?.type === "search_result") return { type: "text", text: parseSearchResultText(part) } if (part?.type === "image" && part.source?.type === "base64" && part.source.data) { - return { - type: "image", - data: part.source.data, - mimeType: part.source.media_type || "application/octet-stream", + // a tool's image goes through agy only as PNG/JPEG/GIF/WebP, as the + // type its bytes say; anything else Gemini refuses 400 "Unable to + // process input image", so a bad capture becomes a text note. + const mt = imageTypeOf(part.source.data) + if (!mt) { + const declared = String(part.source.media_type || "").toLowerCase() || "no media type" + return { type: "text", text: `[tool returned an image that could not be read (${declared}, ${Math.floor(part.source.data.length * 3 / 4)} bytes)]` } } + return { type: "image", data: part.source.data, mimeType: mt } } throw new UnsupportedContent("this tool_result content") }) @@ -6849,12 +7536,12 @@ function inspectToolTurn(results, body) { rawText = dsh.rest } } - if (!seenResult && message.role === "user" && rawText.trim()) { + const text = stripMagpiePlaceholderNotice(rawText) + if (!seenResult && message.role === "user" && text.trim()) { // A user can steer a pending tool turn from either side of a tool_result. // Replay the instruction as a user prompt, never as an MCP tool response. userSteered = true } - const text = stripMagpiePlaceholderNotice(rawText) if (text !== rawText && !notices.includes(MAGPIE_PLACEHOLDER_NOTICE)) { notices.push(MAGPIE_PLACEHOLDER_NOTICE) } @@ -7395,6 +8082,7 @@ function thinkingSignature(sessionId, thinking) { createHmac("sha256", THINKING_KEY).update(String(sessionId) + "\n" + thinking).digest("base64url") } +<<<<<<< HEAD // Thinking when disabled (local patch). A gateway adds thinking: {type: // "disabled"} to requests that never mentioned thinking, but agy can't turn // thinking off: it has no such level (disabledEffort picks the lowest), and @@ -7414,6 +8102,13 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist const responseContent = [] const forwardThinking = FORWARD_THINKING && (body.thinking?.type !== "disabled" || thinkingWhenDisabled()) // Thinking when disabled (local patch) +======= +function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.registerResponse(body), toolResultStep = null) { + const encoder = new TextEncoder() + const responseContent = [] + const emittedCalls = [] + const forwardThinking = FORWARD_THINKING && body.thinking?.type !== "disabled" +>>>>>>> upstream let blockIndex = 0 let open = null let pingTimer = null @@ -7483,6 +8178,7 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist send("content_block_stop", { type: "content_block_stop", index: blockIndex }) blockIndex++ responseContent.push({ type: "tool_use", id: call.id, name: call.name, input: call.arguments }) + emittedCalls.push(call) } const detach = () => { finished = true @@ -7582,7 +8278,24 @@ function makeAnthropicStream(proc, turn, body, msgId, signal, step = turn.regist if (finished) return stopMessage("tool_use", usage, false, step.usageKind === "agy_model_call") proc.recordAssistantResponse(turn, responseContent) +<<<<<<< HEAD if (retry) retry.reply = { content: responseContent, stopReason: "tool_use" } // Retry attach (local patch) +======= + if (toolResultStep && emittedCalls.length > 0 && proc.turn === turn && + !proc.dead && !proc.stopping && !proc.retiring && + !turn.done && !turn.finalized && !turn.cancelRequested && + turn.stepSeq === toolResultStep.stepSeq && Array.isArray(proc.expectedMessages)) { + turn.lastToolStep = { + callIds: toolResultStep.callIds, + requestDigest: toolResultStep.requestDigest, + expectedLength: proc.expectedMessages.length, + msgId, + wireModel: toolResultStep.wireModel, + emittedCalls, + content: structuredClone(responseContent), + } + } +>>>>>>> upstream detach() controller.close() return @@ -7782,6 +8495,7 @@ async function jsonResponseFromStream(stream, fallbackModel, fallbackId) { }) } +<<<<<<< HEAD // Retry attach (local patch). A client that gave up waiting for the first // byte sends the same request again while the first one still runs, or after // its reply (a tool call) was lost on the way. That request was a 409 until @@ -7840,20 +8554,111 @@ function retryResponse(retry, body) { } function streamResponse(proc, turn, body, signal) { +======= +const SSE_HEADERS = { + "Content-Type": "text/event-stream", + "Cache-Control": "no-cache", + "Connection": "keep-alive", +} + +function streamResponse(proc, turn, body, signal, toolResultStep = null) { +>>>>>>> upstream turn.attach() turn.retry = { key: retryKey(body), reply: null, waiters: [] } // Retry attach (local patch) const step = turn.registerResponse(body) const msgId = "msg_" + randomUUID().replace(/-/g, "").slice(0, 24) - const stream = makeAnthropicStream(proc, turn, body, msgId, signal, step) + const stream = makeAnthropicStream(proc, turn, body, msgId, signal, step, toolResultStep) if (body.stream === false) return jsonResponseFromStream(stream, body.model, msgId) return new Response(stream, { status: 200, - headers: { - "Content-Type": "text/event-stream", - "Cache-Control": "no-cache", - "Connection": "keep-alive", + headers: SSE_HEADERS, + }) +} + +function replayToolStepResponse(last, body) { + const encoder = new TextEncoder() + const content = structuredClone(last.content) + const stream = new ReadableStream({ + start(controller) { + const send = (event, data) => controller.enqueue(encoder.encode(sseEvent(event, data))) + send("message_start", { + type: "message_start", + message: { + id: last.msgId, + type: "message", + role: "assistant", + model: last.wireModel, + content: [], + stop_reason: null, + stop_sequence: null, + usage: { input_tokens: 0, output_tokens: 0 }, + }, + }) + let index = 0 + for (const block of content) { + if (block.type === "text") { + send("content_block_start", { + type: "content_block_start", + index, + content_block: { type: "text", text: "" }, + }) + if (block.text) { + send("content_block_delta", { + type: "content_block_delta", + index, + delta: { type: "text_delta", text: block.text }, + }) + } + send("content_block_stop", { type: "content_block_stop", index }) + index++ + } else if (block.type === "thinking") { + send("content_block_start", { + type: "content_block_start", + index, + content_block: { type: "thinking", thinking: "" }, + }) + if (block.thinking) { + send("content_block_delta", { + type: "content_block_delta", + index, + delta: { type: "thinking_delta", thinking: block.thinking }, + }) + } + if (block.signature) { + send("content_block_delta", { + type: "content_block_delta", + index, + delta: { type: "signature_delta", signature: block.signature }, + }) + } + send("content_block_stop", { type: "content_block_stop", index }) + index++ + } else if (block.type === "tool_use") { + send("content_block_start", { + type: "content_block_start", + index, + content_block: { type: "tool_use", id: block.id, name: block.name, input: {} }, + }) + send("content_block_delta", { + type: "content_block_delta", + index, + delta: { type: "input_json_delta", partial_json: JSON.stringify(block.input ?? {}) }, + }) + send("content_block_stop", { type: "content_block_stop", index }) + index++ + } + } + send("message_delta", { + type: "message_delta", + delta: { stop_reason: "tool_use", stop_sequence: null }, + usage: { input_tokens: 0, output_tokens: 0 }, + }) + send("message_stop", { type: "message_stop" }) + controller.close() }, }) + if (body.stream === false) return jsonResponseFromStream(stream, last.wireModel, last.msgId) + return new Response(stream, { status: 200, headers: SSE_HEADERS }) } // Tool results a kept session already holds (answered to its live MCP calls @@ -8234,15 +9039,27 @@ export const AntigravityBridgePlugin = async () => { const layout = requestLayout(body) body = { ...foldSplitCalls(canonicalBody(body)), model: requestedModel } if (isOrchestrator(requestedModel)) return jsonError(400, orchestratorRefusal(requestedModel), undefined, { noRetry: true }) - const model = resolveAgyModel(await loadModelCatalog(agy), requestedModel, body) - const selection = { model: requestedModel, effort: requestedEffort(body) } - const sessionScope = requestSessionScope(fetchInput, init) + const saidEffort = requestHeader(fetchInput, init, "x-magpie-effort") + const listed = await loadModelCatalog(agy) + const model = resolveAgyModel(listed, requestedModel, body, saidEffort) + // a family alias stands in for a model only no account has + const aliasOf = resolveCatalogAlias(listed.routing ?? listed, requestedModel).id + if (aliasOf !== requestedModel && !requestedModel.startsWith(aliasOf + "-") && + anotherAccountLists(agy, requestedModel)) { + return jsonError(400, `agy bridge: model ${requestedModel} is unavailable to this agy account; another signed-in agy account lists it`) + } + const selection = { model: requestedModel, effort: requestedEffort(body, saidEffort) } + const sessionScope = requestSessionScope(fetchInput, init) + + (requestHeader(fetchInput, init, "x-magpie-subagent") && agentSummaryAsk(body) ? AGENT_SUMMARY_SCOPE : "") // an account's conversations are its own: its agy has them - const convKey = (home ? `acct:${path.basename(home)}:` : "") + conversationKey(body, sessionScope) + const callerWorkDir = namedWorkDirectory(body, init) + const convKey = (home ? `acct:${path.basename(home)}:` : "") + conversationKey(body, sessionScope, callerWorkDir || "") const trailing = trailingMessages(body) const isFresh = trailing.history.length === 0 const resultBlocks = extractToolResults(body) - const callerWorkDir = namedWorkDirectory(body, init) + // magpie going on from a reply its stream cut after a tool round: + // the round's results, then what the reply had said (plugins#1512) + const prefillAfterResults = resultBlocks.length > 0 && prefillTailEnabled() && !!prefillRun(body.messages) const workDir = workDirectory(callerWorkDir) const instructions = sessionInstructions(body, callerWorkDir) @@ -8300,15 +9117,24 @@ export const AntigravityBridgePlugin = async () => { if (proc.turn !== turn) return jsonError(409, "agy bridge: the tool response has already completed") if (turn.attached) throw new BusyError("agy bridge: this conversation already has an active response") if (turn.steering) throw new BusyError("agy bridge: this conversation is already steering this tool turn") - const rawResults = matches.map(({ block, match }) => ({ - block, - call: match.call, - result: toolResult(block), - })) + // Notices appended by inspectToolTurn belong in call.result for + // agy, while duplicate checks compare the raw tool_result (#1475). + const rawResults = matches.map(({ block, match }) => { + const result = toolResult(block) + return { + block, + call: match.call, + result, + rawKey: JSON.stringify(result), + } + }) + const directIdsMatch = matches.every((item) => item.match?.call?.id === item.block.tool_use_id) + // An identical retry passes: its results are the ones already + // committed, compared raw (#1475). proc.validateResults(rawResults) let interrupted = isInterruptedToolTurn(body) let results = rawResults - if (!interrupted) { + if (!interrupted && !prefillAfterResults) { try { const inspected = inspectToolTurn(rawResults, body) results = inspected.results @@ -8321,19 +9147,50 @@ export const AntigravityBridgePlugin = async () => { } } } - if (!interrupted) proc.validateResults(results) + if (!interrupted && !prefillAfterResults) proc.validateResults(results) // An image over MCP reaches agy's model as a path it can't // read, so a result with one takes the steer's way: the call // gets the text, the next prompt the image. const imageResult = proc.supportsImages && results.some((item) => resultHasImage(item.result)) - const directIdsMatch = matches.every((item) => item.match?.call?.id === item.block.tool_use_id) + const forwardThinking = FORWARD_THINKING && body.thinking?.type !== "disabled" + let requestDigest = null + if (!prefillAfterResults && !interrupted && !imageResult && directIdsMatch) { + try { + const outputFormat = stableJSON(outputFormatReminder(body)) + requestDigest = toolStepRequestDigest({ + trailing, + matches, + results, + workDir, + instructions, + tools, + model, + wireModel: body.model, + effort: selection.effort, + forwardThinking, + outputFormat, + }) + } catch { + requestDigest = null + } + } const historyMatches = directIdsMatch - ? proc.matchesPendingTurnHistory(turn, trailingMessages(body).history) - : proc.matchesHistory(trailingMessages(body).history) + ? proc.matchesPendingTurnHistory(turn, trailing.history) + : proc.matchesHistory(trailing.history) + if (!historyMatches && !prefillAfterResults && !interrupted && !imageResult && directIdsMatch) { + const replay = proc.canReplayLastToolStep(turn, { sessionScope, matches, requestDigest }) + if (replay) { + turn.touchClient() + turn.arm() + proc.lastUsed = Date.now() + logBridgeEvent(proc, turn, "replay_tool_step", "idempotent_retry", acquireOpts, { calls: replay.emittedCalls.length }) + return replayToolStepResponse(replay, body) + } + } // A steer keeps the live session, so agy's prompt cache holds: the // calls are answered with their real results, the step is // cancelled, and the steer goes in as the next prompt. - if ((interrupted || imageResult) && historyMatches && !proc.toolsGrew(tools) && proc.workDir === workDir && + if (!prefillAfterResults && (interrupted || imageResult) && historyMatches && !proc.toolsGrew(tools) && proc.workDir === workDir && sameInstructions(proc.instructions, instructions) && await proc.steerInSession(turn, rawResults, trailingMessages(body).history)) { keptSession = true @@ -8342,12 +9199,15 @@ export const AntigravityBridgePlugin = async () => { .filter((item) => !item.call.deferred || item.call.lateDelivered) .map((item) => item.block.tool_use_id), ) - } else if (interrupted || imageResult || !historyMatches || proc.toolsGrew(tools) || + } else if (prefillAfterResults || interrupted || imageResult || !historyMatches || proc.toolsGrew(tools) || proc.workDir !== workDir || !sameInstructions(proc.instructions, instructions)) { // A changed context, a tool catalog that grew, or a // user-interrupted tool turn needs a new session. Replay the // real results without resolving the old process's calls. - const dropReason = interrupted ? "interrupted" + // A reply going on from its own text can't be steered into + // the live step: it is replayed into a fresh session. + const dropReason = prefillAfterResults ? "prefill" + : interrupted ? "interrupted" : imageResult ? "image_result" : !historyMatches ? "history_mismatch" : proc.toolsGrew(tools) ? "tools_grew" @@ -8370,14 +9230,25 @@ export const AntigravityBridgePlugin = async () => { proc.abandonTurn(turn) await proc.stop() } else { + let toolResultStep = null if (!proc.dead && !turn.done) { // A tool catalog that lost or changed tools applies to the // rest of this turn; a model change applies from the next prompt. await proc.updateTools(tools) - proc.continueWith(results) - proc.recordToolResults(turn, body.messages) + const delivered = proc.continueWith(results) + if (delivered > 0) { + proc.recordToolResults(turn, body.messages) + if (directIdsMatch && requestDigest) { + toolResultStep = { + stepSeq: turn.stepSeq, + callIds: matches.map((item) => item.block.tool_use_id), + requestDigest, + wireModel: body.model, + } + } + } } - return streamResponse(proc, turn, body, init.signal) + return streamResponse(proc, turn, body, init.signal, toolResultStep) } } const held = heldFor(convKey, acquireOpts, resultBlocks) // Parallel lanes (local patch) diff --git a/package.json b/package.json index cdc8ce0..49726fd 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.116", + "version": "0.1.134", "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/platform.mjs b/platform.mjs index 384cae5..af1e206 100644 --- a/platform.mjs +++ b/platform.mjs @@ -1,7 +1,17 @@ import { spawn } from "node:child_process" +import os from "node:os" import path from "node:path" import { accountEnv, currentHome } from "./account.mjs" +// holdsHome says whether dir is the user's home folder or a folder above +// it ("/", "C:\Users"); on Windows case aside, as the system ignores it. +export function holdsHome(dir, home = os.homedir(), platform = process.platform) { + if (!dir || !home) return false + const paths = platform === "win32" ? path.win32 : path.posix + const rel = paths.relative(paths.resolve(dir), paths.resolve(home)) + return rel === "" || (!rel.startsWith("..") && !paths.isAbsolute(rel)) +} + export function agyCandidates(env, home, platform = process.platform) { const windows = platform === "win32" const paths = windows ? path.win32 : path.posix diff --git a/signin.mjs b/signin.mjs index 2e80991..178fc65 100644 --- a/signin.mjs +++ b/signin.mjs @@ -255,6 +255,15 @@ async function readStoredValue({ platform = process.platform, exec = run, env = // go-keyring on Windows stores the value's bytes as they are (UTF-8) return { raw: Buffer.from(out.slice(3), "base64").toString("utf8") } } + // Linux and the rest: with no keyring to reach (Docker, a NAS, a + // headless box) agy keeps its sign-in in the same file an account's own + // home has (#1502). No file says nothing: it may be in a keyring. + const own = env.HOME || (env === process.env ? os.homedir() : "") + if (own) { + try { + return { raw: await fs.promises.readFile(tokenFile(own), "utf8") } + } catch {} + } return { state: "unknown" } } diff --git a/test/account-scope.mjs b/test/account-scope.mjs new file mode 100644 index 0000000..1050de7 --- /dev/null +++ b/test/account-scope.mjs @@ -0,0 +1,96 @@ +// An agy runs under one account's sign-in, so one account's request never +// goes on in another account's agy (Archivemylife on X: two Google accounts, +// each added with "Add another Google account", were used up and reset +// together). Before, a request of account B whose flattened opening went on +// from account A's conversation, or whose tool ids were A's pending calls, +// was answered in A's agy: with A's credentials, A's quota and A's 429. +// +// bun test ./account-scope.mjs + +import { test } from "node:test" +import assert from "node:assert/strict" +import { MESSAGES_URL, baseBody, continueWithToolResults, createBridgeKit, readSse } from "./testkit.mjs" + +async function withKit(fn) { + const kit = await createBridgeKit({}) + try { return await fn(kit) } finally { await kit.dispose() } +} + +function promptText(entry) { + return (entry.params?.prompt || []).map((part) => (part.type === "text" ? part.text : "")).join("") +} + +// "TOOL" asks for one Read and goes on once its result is in; a replayed +// round answers "replayed"; anything else is answered with the spawn's number. +function script(kit) { + kit.defaultPrompt = async (agent) => { + const text = promptText({ params: { prompt: agent.prompt } }) + const current = text.includes("") ? text.slice(text.lastIndexOf("")) : text + if (current.includes("B RESULT")) { + await agent.text("replayed") + return { stopReason: "end_turn" } + } + if (current.includes("TOOL")) { + await agent.tool("Read", { path: "/repo/a.txt" }) + await agent.text("after tool") + return { stopReason: "end_turn" } + } + await agent.text("done") + return { stopReason: "end_turn" } + } +} + +const prompts = (kit) => kit.acpLog.filter((entry) => entry.method === "session/prompt") +const homeOf = (kit, spawn) => kit.acpSpawns[spawn].env.HOME ?? "" + +async function accountB(kit) { + return kit.plugin.auth.loader(async () => ({ type: "oauth", metadata: { agyHome: "accountb1" } })) +} + +const OPENING = "Please review the following project files and propose a short fix.\nstep one" +const GROWN = OPENING + "\n\nassistant: done\n\nstep two is longer than four chars" + +test("a continued opening goes on in its own account's agy only", async () => { + await withKit(async (kit) => { + script(kit) + await readSse(await kit.request(baseBody({ messages: [{ role: "user", content: OPENING }] }))) + assert.equal(prompts(kit).length, 1) + assert.equal(prompts(kit)[0].spawn, 0) + const b = await accountB(kit) + const response = await b.fetch(MESSAGES_URL, { method: "POST", + body: JSON.stringify(baseBody({ messages: [{ role: "user", content: GROWN }] })) }) + await readSse(response) + const second = prompts(kit).at(-1) + assert.notEqual(second.spawn, 0, "account B's request went on in account A's agy") + assert.match(homeOf(kit, second.spawn), /accountb1$/) + assert.notEqual(homeOf(kit, second.spawn), homeOf(kit, 0)) + }) +}) + +test("the same account's continued opening still goes on in its live agy", async () => { + await withKit(async (kit) => { + script(kit) + await readSse(await kit.request(baseBody({ messages: [{ role: "user", content: OPENING }] }))) + await readSse(await kit.request(baseBody({ messages: [{ role: "user", content: GROWN }] }))) + assert.equal(kit.acpSpawns.length, 1) + assert.deepEqual(prompts(kit).map((entry) => entry.spawn), [0, 0]) + }) +}) + +test("another account's tool results never feed this account's pending call", async () => { + await withKit(async (kit) => { + script(kit) + const body = baseBody({ messages: [{ role: "user", content: "TOOL start" }] }) + const first = await readSse(await kit.request(body)) + assert.equal(first.stopReason, "tool_use") + const b = await accountB(kit) + const response = await b.fetch(MESSAGES_URL, { method: "POST", + body: JSON.stringify(continueWithToolResults(body, first, () => "B RESULT")) }) + const parsed = await readSse(response) + assert.equal(parsed.content.find((block) => block.type === "text")?.text, "replayed", + "account B's results resolved account A's call") + const last = prompts(kit).at(-1) + assert.notEqual(last.spawn, 0) + assert.match(homeOf(kit, last.spawn), /accountb1$/) + }) +}) diff --git a/test/call-mcp-tool.mjs b/test/call-mcp-tool.mjs new file mode 100644 index 0000000..c948129 --- /dev/null +++ b/test/call-mcp-tool.mjs @@ -0,0 +1,104 @@ +import { test } from "node:test" +import assert from "node:assert/strict" +import { baseBody, createBridgeKit, readSse } from "./testkit.mjs" + +const USAGE = { inputTokens: 100, cachedReadTokens: 0, cachedWriteTokens: 0, outputTokens: 5, totalTokens: 105 } + +const CALL_MCP_TOOL_SCHEMA = { + type: "object", + properties: { + ServerName: { type: "string" }, + ToolName: { type: "string" }, + Arguments: { type: "string" }, + }, + required: ["ServerName", "ToolName", "Arguments"], +} + +async function callToolOnce(toolName, inputSchema, args) { + const kit = await createBridgeKit() + try { + kit.prompts.push(async (agent) => { + await agent.tool(toolName, args) + }) + const body = baseBody({ tools: [{ name: toolName, input_schema: inputSchema }] }) + const result = await readSse(await kit.request(body)) + return result.content.find((item) => item.type === "tool_use") + } finally { + await kit.dispose() + } +} + +test("call_mcp_tool unwraps a JSON-object Arguments string and keeps the live session on tool_result", async () => { + const kit = await createBridgeKit() + try { + let forwardedResult + kit.prompts.push(async (agent) => { + forwardedResult = await agent.tool("call_mcp_tool", { + ServerName: "magpie", + ToolName: "amd-doc-search__vivado_doc_search", + Arguments: ' {"query":"Vivado synthesis","limit":2} ', + }) + await agent.text("done") + return { stopReason: "end_turn", usage: USAGE } + }) + + const body = baseBody({ tools: [{ name: "call_mcp_tool", input_schema: CALL_MCP_TOOL_SCHEMA }] }) + const firstRes = await kit.request(body) + assert.equal(firstRes.status, 200) + const first = await readSse(firstRes) + assert.equal(first.stopReason, "tool_use") + const call = first.content.find((item) => item.type === "tool_use") + assert.deepEqual(call.input, { + ServerName: "magpie", + ToolName: "amd-doc-search__vivado_doc_search", + Arguments: { query: "Vivado synthesis", limit: 2 }, + }) + + const nextBody = { + ...body, + messages: [ + ...body.messages, + { role: "assistant", content: [call] }, + { + role: "user", + content: [{ type: "tool_result", tool_use_id: call.id, content: "DOC #UG901" }], + }, + ], + } + const secondRes = await kit.request(nextBody) + assert.equal(secondRes.status, 200, await (secondRes.status === 200 ? "" : secondRes.text())) + const second = await readSse(secondRes) + assert.equal(second.stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, 1, "tool_result continues the live ACP session without replay") + assert.equal(forwardedResult?.result?.content?.[0]?.text, "DOC #UG901") + } finally { + await kit.dispose() + } +}) + +test("call_mcp_tool preserves already-object Arguments and leaves non-object or invalid strings intact", async () => { + const objCall = await callToolOnce("call_mcp_tool", CALL_MCP_TOOL_SCHEMA, { + ServerName: "calc", + ToolName: "eval", + Arguments: { expression: "1+1" }, + }) + assert.deepEqual(objCall.input.Arguments, { expression: "1+1" }) + + for (const raw of ["", " ", "null", "123", '"text"', "[1,2]", "{bad json"]) { + const call = await callToolOnce("call_mcp_tool", CALL_MCP_TOOL_SCHEMA, { + ServerName: "calc", + ToolName: "eval", + Arguments: raw, + }) + assert.equal(call.input.Arguments, raw) + } +}) + +test("unrelated tools with a string Arguments property are not unwrapped", async () => { + const call = await callToolOnce("custom_tool", CALL_MCP_TOOL_SCHEMA, { + ServerName: "magpie", + ToolName: "x", + Arguments: '{"a":1}', + }) + assert.equal(call.input.Arguments, '{"a":1}') +}) diff --git a/test/catalog.mjs b/test/catalog.mjs index d6d7c07..66e2b6f 100644 --- a/test/catalog.mjs +++ b/test/catalog.mjs @@ -749,6 +749,43 @@ test("Orchestrator 不列出,点名它的请求得 400 并指向它实际会 }) }) +// plugins#1542: on an account without Claude 5.5, the sonnet family alias +// served claude-sonnet-5-5 as claude-sonnet-4-6 with a 200, while another +// signed-in account lists 5.5. That account is asked, not a stand-in. +test("a family alias doesn't stand in for a model another signed-in account lists", async () => { + await withKit({ modelsBehavior: { stdout: modelsOutput(ORCH_ROWS) }, offeredModels: ORCH_ROWS }, async (kit) => { + await kit.models() + await settle(kit) + await kit.models() + const ask = async (label) => { + const response = await kit.request(baseBody({ model: "agy-cli/claude-sonnet-5-5", messages: [{ role: "user", content: label }] })) + return { status: response.status, text: await response.text() } + } + 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) + const other = { + at: Date.now(), + list: [{ id: "claude-sonnet-5-5-high", name: "Claude Sonnet 5.5 (High)", effort: "high" }, { id: "claude-sonnet-5-5-low", name: "Claude Sonnet 5.5 (Low)", effort: "low" }], + } + // an account removed since: its entry stays, its home is gone + data.byAgy[`${own}#abcdef0123456789`] = other + fs.writeFileSync(file, JSON.stringify(data)) + const gone = await ask("removed account") + assert.equal(gone.status, 200, gone.text) + + fs.mkdirSync(path.join(kit.env.XDG_STATE_HOME, "magpie-agy-bridge", "accounts", "abcdef0123456789"), { recursive: true }) + const spawned = kit.children.size + const listed = await ask("another account") + assert.equal(listed.status, 400, listed.text) + assert.match(JSON.parse(listed.text).error.message, /claude-sonnet-5-5 is unavailable to this agy account; another signed-in agy account lists it/) + assert.equal(kit.children.size, spawned, "no agy was started for it") + + const plain = await kit.request(baseBody({ model: "agy-cli/claude-sonnet-4-6", messages: [{ role: "user", content: "own model" }] })) + assert.equal(plain.status, 200) + }) +}) + test("各家族 limit 正确,未知动态型号不猜成 1M", async () => { const expected = { "gemini-4-argon": { context: 1048576, output: 65536 }, diff --git a/test/compat.mjs b/test/compat.mjs index 79bd318..cffa548 100644 --- a/test/compat.mjs +++ b/test/compat.mjs @@ -16,11 +16,11 @@ const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "agy-compat-test-")) const entry = new URL("../index.mjs", import.meta.url) let source = fs.readFileSync(entry, "utf8") source = source.replace(/from "(\.\/[^"\n]+)"/g, (_, target) => `from ${JSON.stringify(new URL(target, entry).href)}`) -fs.writeFileSync(path.join(workspace, "bridge.mjs"), source + "\nexport { inspectToolTurn, matchToolResults, historyKey, allProcs, toolCalls, renderInitialPromptParts, withStateLock, execOnce };\n") -const { inspectToolTurn, matchToolResults, historyKey, allProcs, toolCalls, renderInitialPromptParts, withStateLock, execOnce } = await import(pathToFileURL(path.join(workspace, "bridge.mjs")).href) +fs.writeFileSync(path.join(workspace, "bridge.mjs"), source + "\nexport { inspectToolTurn, matchToolResults, historyKey, allProcs, toolCalls, renderInitialPromptParts, clipMiddle, withStateLock, execOnce };\n") +const { inspectToolTurn, matchToolResults, historyKey, allProcs, toolCalls, renderInitialPromptParts, clipMiddle, withStateLock, execOnce } = await import(pathToFileURL(path.join(workspace, "bridge.mjs")).href) after(() => fs.rmSync(workspace, { recursive: true, force: true })) -const image = { type: "image", source: { type: "base64", media_type: "image/png", data: "aW1hZ2VB" } } +const image = { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgoAAAANaW1hZ2VB" } } const result = (id, name, text) => ({ block: { type: "tool_result", tool_use_id: id, content: text }, call: { id, name }, @@ -272,3 +272,110 @@ test("text that names a notice tag it never closes is routed by its writer, not // a notice that opens and is cut short is still turned away assert.throws(() => inspectToolTurn([call], bodyFor([call.block, { type: "text", text: "cut short" }])), /text beside a live tool_result/) }) + +test("clipMiddle stays close to limit instead of dropping 25% on marker overflow", () => { + const utf8Len = text => Buffer.byteLength(text, "utf8") + const text = "HEAD_MARK " + "a".repeat(107_000) + " TAIL_MARK" + const limit = 106_000 + const clipped = clipMiddle(text, limit) + assert.ok(utf8Len(clipped) <= limit, `clipped size ${utf8Len(clipped)} exceeded limit ${limit}`) + assert.ok(utf8Len(clipped) >= limit - 64, `clipped size ${utf8Len(clipped)} lost too much of budget ${limit}`) + assert.ok(clipped.startsWith("HEAD_MARK ") && clipped.endsWith(" TAIL_MARK")) + assert.match(clipped, /\[\.\.\. \d+ bytes omitted \.\.\.\]/) + + // Multi-byte UTF-8 boundary stays within limit without splitting characters. + const multi = "首部" + "中".repeat(4000) + "尾部" + const multiLimit = 9000 + const multiClipped = clipMiddle(multi, multiLimit) + assert.ok(utf8Len(multiClipped) <= multiLimit) + assert.ok(utf8Len(multiClipped) >= multiLimit - 64) + assert.ok(multiClipped.startsWith("首部") && multiClipped.endsWith("尾部")) +}) + +test("current_turn clipping trims meta reminders and trailing system blocks before user text", () => { + const utf8Len = text => Buffer.byteLength(text, "utf8") + const userPrompt = "Please update the sidebar layout and proceed with the refactor." + const body = { + system: "System instructions. " + "s".repeat(7000), + messages: [ + { role: "user", content: "Previous conversation summary. " + "h".repeat(14_000) }, + { role: "assistant", content: [{ type: "text", text: "Preview is ready. " + "a".repeat(2400) }] }, + { + role: "user", + content: [ + { type: "text", text: "\nResult of calling the Read tool:\n" + "f".repeat(22_000) + "\n" }, + { type: "text", text: "\nResult of calling the Read tool:\n" + "g".repeat(22_000) + "\n" }, + { type: "text", text: "\nProject instructions:\n" + "p".repeat(20_000) + "\n" }, + { type: "text", text: "local command" }, + { type: "text", text: "Compacted" }, + { type: "text", text: userPrompt }, + ], + }, + { role: "system", content: [{ type: "text", text: "Deferred tools and skills:\n" + "d".repeat(42_000) }] }, + ], + } + const prompt = renderInitialPromptParts(body, "/workspace/demo", false).map(part => part.text || "").join("") + assert.ok(utf8Len(prompt) <= 112 * 1024, `prompt size ${utf8Len(prompt)} exceeded 112 KiB`) + assert.ok(prompt.includes(userPrompt), "sandwiched user prompt must survive clipping") + assert.ok(prompt.endsWith("\n")) + + // Extreme meta bloat (>260 KiB) still keeps the short user prompt verbatim. + const extreme = { + ...body, + messages: [ + body.messages[0], + body.messages[1], + { + role: "user", + content: [ + { type: "text", text: "\n" + "r".repeat(100_000) + "\n" }, + { type: "text", text: "\n" + "q".repeat(100_000) + "\n" }, + { type: "text", text: userPrompt }, + ], + }, + { role: "system", content: [{ type: "text", text: "Trailing system catalog:\n" + "z".repeat(60_000) }] }, + ], + } + const extremePrompt = renderInitialPromptParts(extreme, "/workspace/demo", false).map(part => part.text || "").join("") + assert.ok(utf8Len(extremePrompt) <= 112 * 1024, `extreme prompt size ${utf8Len(extremePrompt)} exceeded 112 KiB`) + assert.ok(extremePrompt.includes(userPrompt), "user prompt must survive extreme meta/system bloat") + + // Fresh turn without head or history also protects user text over reminders. + const fresh = { + messages: [ + { + role: "user", + content: [ + { type: "text", text: "\n" + "m".repeat(80_000) + "\n" }, + { type: "text", text: userPrompt }, + ], + }, + { role: "system", content: [{ type: "text", text: "Environment:\n" + "e".repeat(60_000) }] }, + ], + } + const freshPrompt = renderInitialPromptParts(fresh, null, true).map(part => part.text || "").join("") + assert.ok(utf8Len(freshPrompt) <= 112 * 1024) + assert.ok(freshPrompt.includes(userPrompt), "user prompt must survive clipping on a fresh turn") +}) + + +test("current_turn clipping takes reminders first even when the user's own text is the largest part", () => { + // A pasted log larger than the reminders beside it: clipping the largest + // part first would cut the user's text and keep the reminders whole. + const userText = "USER_START " + "u".repeat(80_000) + " USER_END" + const body = { + messages: [ + { + role: "user", + content: [ + { type: "text", text: "\n" + "m".repeat(50_000) + "\n" }, + { type: "text", text: userText }, + ], + }, + ], + } + const prompt = renderInitialPromptParts(body, null, true).map(part => part.text || "").join("") + assert.ok(Buffer.byteLength(prompt, "utf8") <= 112 * 1024) + assert.ok(prompt.includes(userText), "the user's text must stay whole while reminders can still give way") + assert.match(prompt, /\[\.\.\. \d+ bytes omitted \.\.\.\]/) +}) diff --git a/test/concurrent-convs.mjs b/test/concurrent-convs.mjs index 6da3792..2026acc 100644 --- a/test/concurrent-convs.mjs +++ b/test/concurrent-convs.mjs @@ -241,3 +241,56 @@ test("an earlier message really changed still starts a new session, masked value const { drops } = await runMasked({ conversations: 1, steer: false, edit: true }) assert.deepEqual(drops.map((row) => row.reason), ["history_mismatch"], JSON.stringify(drops)) }) +// DSH opens every session with the same notice ("The user changed the +// approval policy ...") before the user's own request, and names the +// session's folder after it. Two sessions in two folders had one key (system +// and first message alike), shared one agy, and each one's request was +// refused with 503 "this conversation still has an unfinished response" +// while the other's response ran. The folder is part of the key. +test("two DSH sessions with the same opening notice in different folders get their own agy", async () => { + const fs = await import("node:fs") + const os = await import("node:os") + const path = await import("node:path") + const dirs = ["A", "B"].map((name) => fs.mkdtempSync(path.join(os.tmpdir(), `agy-dsh-${name}-`))) + const stderr = captureStderr() + const kit = await createBridgeKit({}) + try { + kit.defaultPrompt = async (agent) => { + const text = (agent.prompt || []).map((p) => p.text || "").join("") + return stepper(text.includes("TASK-A") ? "a" : "b", 2)(agent) + } + const notice = { role: "user", content: [{ type: "text", text: 'The user changed the approval policy from "ask the user for approval" to "never ask the user for approval".' }] } + const convs = ["A", "B"].map((name, i) => ({ + name, + body: baseBody({ metadata: { user_id: "dsh-main" }, messages: [ + notice, + { role: "user", content: `Current working directory: "${dirs[i]}".\nTASK-${name} read everything` }, + ] }), + parsed: null, + })) + const advance = async (conv) => { + if (conv.parsed) { + const call = conv.parsed.content.find((block) => block.type === "tool_use") + assert.ok(call, `${conv.name}: ${JSON.stringify(conv.parsed)}`) + conv.body = { ...conv.body, messages: [ + ...conv.body.messages, + { role: "assistant", content: [call] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: call.id, content: `ok ${call.id}` }] }, + ] } + } + const response = await kit.request(conv.body) + assert.equal(response.status, 200, `${conv.name}: ${response.status} ${response.status === 200 ? "" : await response.clone().text()}`) + conv.parsed = await readSse(response) + } + for (let i = 0; i <= 2; i++) await Promise.all(convs.map(advance)) + for (const conv of convs) assert.equal(conv.parsed.stopReason, "end_turn", `${conv.name}: ${JSON.stringify(conv.parsed)}`) + } finally { + await kit.dispose() + stderr.restore() + for (const dir of dirs) fs.rmSync(dir, { recursive: true, force: true }) + } + const drops = stderr.lines.filter((row) => row.action === "drop_live") + assert.deepEqual(drops, [], JSON.stringify(drops)) + const opened = stderr.lines.filter((row) => row.action === "session_new") + assert.equal(opened.length, 2, JSON.stringify(opened)) +}) diff --git a/test/conversation-key.mjs b/test/conversation-key.mjs index e23a11f..fbfdc60 100644 --- a/test/conversation-key.mjs +++ b/test/conversation-key.mjs @@ -768,11 +768,11 @@ function screenshotHistory(data) { } test("historyKey keys a tool_result image by its hash, not its bytes", () => { - const data = "A".repeat(200_000) + const data = "iVBORw0KGgoAAAAN" + "A".repeat(200_000) const key = historyKey(screenshotHistory(data)) assert.ok(key.length < 2_000, `key is ${key.length} chars`) assert.ok(!key.includes("AAAAAAAAAAAAAAAA")) - assert.notEqual(key, historyKey(screenshotHistory("B".repeat(200_000)))) + assert.notEqual(key, historyKey(screenshotHistory("iVBORw0KGgoAAAAN" + "B".repeat(200_000)))) assert.equal(key, historyKey(screenshotHistory(data))) }) diff --git a/test/dsh-replay-state.mjs b/test/dsh-replay-state.mjs new file mode 100644 index 0000000..dc18e34 --- /dev/null +++ b/test/dsh-replay-state.mjs @@ -0,0 +1,448 @@ +import assert from "node:assert/strict" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { pathToFileURL } from "node:url" +import { after, test } from "node:test" + +// Expose renderInitialPrompt from an isolated copy without adding production exports. +const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "agy-dsh-state-test-")) +const entry = new URL("../index.mjs", import.meta.url) +let source = fs.readFileSync(entry, "utf8") +source = source.replace(/from "(\.\/[^"\n]+)"/g, (_, target) => `from ${JSON.stringify(new URL(target, entry).href)}`) +fs.writeFileSync(path.join(workspace, "bridge.mjs"), source + "\nexport { renderInitialPrompt };\n") +const { renderInitialPrompt } = await import(pathToFileURL(path.join(workspace, "bridge.mjs")).href) +after(() => fs.rmSync(workspace, { recursive: true, force: true })) + +const joinText = ({ parts }) => parts.map((p) => p.text || "").join("") +const LIMIT = 112 * 1024 + +// Verbatim reminder builders matching DeepSeek Harness (@deepseek-ai/dsh-agent-instructions, +// @deepseek-ai/dsh-tool-skill, and @deepseek-ai/dsh-agent-loop). +const AGENT_INSTRUCTIONS_INTRO = + "The following workspace instructions may be relevant to your work. Use them as guidance when applicable. More specific instructions take precedence over broader ones. They do not override system, developer, or direct user instructions." +const REPLACEMENT_BASELINE_INTRO = + "This complete workspace instruction baseline replaces all earlier workspace instruction baselines. " + + AGENT_INSTRUCTIONS_INTRO +const EMPTY_REPLACEMENT_INTRO = + "This complete workspace instruction baseline replaces all earlier workspace instruction baselines. No workspace instructions are currently active." +const COMPACT_INTRO = + "Workspace instructions were omitted or truncated to fit the configured byte budget." +const ADDITIONAL_GUIDANCE = + "Use them as guidance when relevant; more specific instructions take precedence. They do not override system, developer, or direct user instructions." + +const reminderMsg = (body) => ({ + role: "user", + content: [{ type: "text", text: `\n${body}\n` }], +}) + +const baselineMsg = (files, { replace = false, budgetLine = "", compact = false } = {}) => { + const intro = compact + ? COMPACT_INTRO + : replace + ? (files.length === 0 ? EMPTY_REPLACEMENT_INTRO : REPLACEMENT_BASELINE_INTRO) + : AGENT_INSTRUCTIONS_INTRO + const sections = files.map(({ path: filePath, content }) => `Instructions from: ${filePath}\n\n${content}`) + return reminderMsg([budgetLine, intro, ...sections].filter(Boolean).join("\n\n")) +} + +const changesMsg = (changes, { budgetLine = "", compact = false } = {}) => { + const sections = changes.map((c) => { + if (c.action === "add") { + const applicability = c.scope === "user-global" + ? "These user-global instructions apply to all work." + : `These instructions apply to work under \`${c.scope}\`.` + return `Additional instructions from: ${c.path}\n\n${applicability} ${ADDITIONAL_GUIDANCE}\n\n${c.content}` + } + if (c.action === "remove") { + return `Instructions removed: ${c.path}\n\nThe previously loaded instructions from this file no longer apply.` + } + return [ + `Updated instructions from: ${c.path}`, + "", + "This file changed after it was loaded. Use the following content instead of the previously loaded instructions from this file.", + "", + c.content, + ].join("\n") + }) + return reminderMsg([budgetLine, compact ? COMPACT_INTRO : "", ...sections].filter(Boolean).join("\n\n")) +} + +const skillCatalogMsg = (entries, { update = false } = {}) => { + const header = update + ? "The available skill catalog changed. This complete catalog replaces every earlier available-skills list in this session:" + : "A skill is a reusable set of task-specific instructions. The following skills are available in this session:" + const footer = update + ? "Use only names in this replacement catalog. If the user names a listed skill, or the task clearly matches its description, call the `skill` tool with the exact name before acting." + : "If the user names a skill, or the task clearly matches a skill's description, call the `skill` tool with the exact skill name before taking task actions. Load all applicable skills, then follow their full instructions. This catalog contains summaries only; do not infer or follow a skill's instructions until it has been loaded." + const lines = entries.map(([name, desc]) => `- \`${name}\`: ${desc}`) + return reminderMsg([ + header, + "", + "", + ...lines, + "", + "", + footer, + "A user may also invoke a skill directly; its block then appears in this conversation. Follow it, and do not call the `skill` tool again for that skill.", + ].join("\n")) +} + +const sessionInfoMsg = (body, { update = false } = {}) => { + const intro = update + ? "The following information describes your current session. It replaces earlier versions of this context, including any retained in conversation summaries." + : "The following information describes your current session:" + return reminderMsg(`${intro}\n\n${body}`) +} + +const clearedRuntimeContextMsg = () => + reminderMsg("Current runtime context: none. Earlier runtime-context snapshots no longer apply.") + +const pushFillerTurns = (messages, count = 40, size = 2500) => { + for (let i = 0; i < count; i++) { + messages.push({ role: "user", content: [{ type: "text", text: `turn ${i} ` + "x".repeat(size) }] }) + messages.push({ role: "assistant", content: [{ type: "text", text: `reply ${i} ` + "y".repeat(size) }] }) + } +} + +test("preserves latest , updated instructions, and updated session info across >112 KiB replay", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "Initialize project plan" }] }, + baselineMsg([ + { path: "~/.dsh/AGENTS.md", content: "Old global rule v1" }, + ]), + sessionInfoMsg('Current working directory: "/repo".'), + skillCatalogMsg([["old-skill", "stale skill"]]), + { role: "assistant", content: [{ type: "text", text: "Acknowledged." }] }, + changesMsg([ + { + action: "update", + path: "~/.dsh/AGENTS.md", + content: "New global rule v2 (even if docs mention )", + }, + ]), + sessionInfoMsg('Current working directory: "/repo/packages/api".', { update: true }), + skillCatalogMsg([["lark-doc", "Feishu doc skill"]], { update: true }), + ] + + pushFillerTurns(messages) + messages.push({ role: "user", content: [{ type: "text", text: "Read this Feishu doc and update the code" }] }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/repo/packages/api", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(text.includes("`lark-doc`: Feishu doc skill")) + assert.ok(!text.includes("`old-skill`: stale skill")) + assert.ok(text.includes("New global rule v2")) + assert.ok(!text.includes("Old global rule v1")) + assert.ok(text.includes('Current working directory: "/repo/packages/api".')) + assert.ok(!text.includes('Current working directory: "/repo".')) + assert.ok(text.includes("Read this Feishu doc and update the code")) +}) + +test("replacement baseline supersedes earlier baseline and earlier change batches", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "Start in repo A" }] }, + baselineMsg([ + { path: "~/.dsh/AGENTS.md", content: "STALE_BASELINE_GLOBAL" }, + { path: "AGENTS.md", content: "STALE_BASELINE_REPO_A" }, + ]), + { role: "assistant", content: [{ type: "text", text: "Working in repo A." }] }, + changesMsg([ + { action: "add", path: "legacy/AGENTS.md", scope: "legacy", content: "STALE_PRE_REPLACEMENT_ADD" }, + ]), + { role: "assistant", content: [{ type: "text", text: "Switching workspace root." }] }, + baselineMsg( + [ + { path: "~/.dsh/AGENTS.md", content: "ACTIVE_REPLACEMENT_GLOBAL" }, + { path: "packages/web/AGENTS.md", content: "ACTIVE_REPLACEMENT_WEB" }, + ], + { replace: true }, + ), + changesMsg([ + { action: "add", path: "packages/web/ui/AGENTS.md", scope: "packages/web/ui", content: "ACTIVE_POST_REPLACEMENT_ADD" }, + ]), + ] + + pushFillerTurns(messages) + messages.push({ role: "user", content: [{ type: "text", text: "Update the web UI button" }] }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/repo/packages/web", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(text.includes("ACTIVE_REPLACEMENT_GLOBAL")) + assert.ok(text.includes("ACTIVE_REPLACEMENT_WEB")) + assert.ok(text.includes("ACTIVE_POST_REPLACEMENT_ADD")) + assert.ok(!text.includes("STALE_BASELINE_GLOBAL")) + assert.ok(!text.includes("STALE_BASELINE_REPO_A")) + assert.ok(!text.includes("STALE_PRE_REPLACEMENT_ADD")) +}) + +test("empty replacement baseline drops stale initial baseline instead of pinning it", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "Start session with instructions" }] }, + baselineMsg([ + { path: "~/.dsh/AGENTS.md", content: "STALE_INITIAL_RULE" }, + ]), + { role: "assistant", content: [{ type: "text", text: "Loaded initial instructions." }] }, + changesMsg([ + { action: "add", path: "sub/AGENTS.md", scope: "sub", content: "STALE_ADDED_RULE" }, + ]), + baselineMsg([], { replace: true }), + ] + + pushFillerTurns(messages) + messages.push({ role: "user", content: [{ type: "text", text: "Continue without workspace instructions" }] }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/tmp/clean", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(text.includes("No workspace instructions are currently active.")) + assert.ok(!text.includes("STALE_INITIAL_RULE")) + assert.ok(!text.includes("STALE_ADDED_RULE")) + + // Standalone empty replacement text (without the preceding sentence) and + // replacement baseline arriving in must drop stale history too. + const standalone = [ + { role: "user", content: [{ type: "text", text: "Start" }] }, + baselineMsg([{ path: "~/.dsh/AGENTS.md", content: "STALE_STANDALONE_RULE" }]), + reminderMsg("No workspace instructions are currently active."), + ] + pushFillerTurns(standalone) + standalone.push({ role: "user", content: [{ type: "text", text: "Continue" }] }) + const standaloneText = joinText(renderInitialPrompt({ system: "You are DSH.", messages: standalone }, "/tmp/clean", false, 0)) + assert.ok(Buffer.byteLength(standaloneText, "utf8") <= LIMIT) + assert.ok(standaloneText.includes("No workspace instructions are currently active.")) + assert.ok(!standaloneText.includes("STALE_STANDALONE_RULE")) + + const inCurrent = [ + { role: "user", content: [{ type: "text", text: "Start" }] }, + baselineMsg([{ path: "~/.dsh/AGENTS.md", content: "STALE_BEFORE_CURRENT_REPLACEMENT" }]), + ] + pushFillerTurns(inCurrent) + inCurrent.push(baselineMsg([], { replace: true })) + inCurrent.push({ role: "user", content: [{ type: "text", text: "Continue" }] }) + const inCurrentText = joinText(renderInitialPrompt({ system: "You are DSH.", messages: inCurrent }, "/tmp/clean", false, 0)) + assert.ok(Buffer.byteLength(inCurrentText, "utf8") <= LIMIT) + assert.ok(inCurrentText.includes("No workspace instructions are currently active.")) + assert.ok(!inCurrentText.includes("STALE_BEFORE_CURRENT_REPLACEMENT")) +}) + +test("handles multi-file change batches with Updated, Additional, and Instructions removed", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "Work across monorepo packages" }] }, + baselineMsg([ + { path: "~/.dsh/AGENTS.md", content: "GLOBAL_V1" }, + { path: "AGENTS.md", content: "ROOT_V1" }, + ]), + { role: "assistant", content: [{ type: "text", text: "Ready." }] }, + // Batch 1: updates global + root AND adds pkg/a + pkg/b in a single reminder. + changesMsg([ + { action: "update", path: "~/.dsh/AGENTS.md", content: "GLOBAL_V2" }, + { action: "update", path: "AGENTS.md", content: "ROOT_V2_ACTIVE" }, + { action: "add", path: "pkg/a/AGENTS.md", scope: "pkg/a", content: "PKG_A_ACTIVE" }, + { action: "add", path: "pkg/b/AGENTS.md", scope: "pkg/b", content: "PKG_B_SHOULD_DROP" }, + ]), + // Batch 2: updates global again and removes pkg/b, plus adds pkg/c which is later removed alone. + changesMsg([ + { action: "add", path: "pkg/c/AGENTS.md", scope: "pkg/c", content: "PKG_C_SHOULD_DROP" }, + ]), + changesMsg([ + { action: "update", path: "~/.dsh/AGENTS.md", content: "GLOBAL_V3_ACTIVE" }, + { action: "remove", path: "pkg/b/AGENTS.md" }, + { action: "remove", path: "pkg/c/AGENTS.md" }, + ]), + ] + + pushFillerTurns(messages) + messages.push({ role: "user", content: [{ type: "text", text: "Check rules across packages" }] }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/repo", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + // Both baseline files were superseded by Batch 1 -> stale baseline dropped. + assert.ok(!text.includes("GLOBAL_V1")) + assert.ok(!text.includes("ROOT_V1")) + // Batch 1 stays because ROOT_V2_ACTIVE and PKG_A_ACTIVE were not superseded later. + assert.ok(text.includes("ROOT_V2_ACTIVE")) + assert.ok(text.includes("PKG_A_ACTIVE")) + // Batch 2 (solo add of pkg/c) was fully superseded by removal in Batch 3 -> dropped. + assert.ok(!text.includes("PKG_C_SHOULD_DROP")) + // Batch 3 stays for GLOBAL_V3_ACTIVE and removal notices for pkg/b & pkg/c. + assert.ok(text.includes("GLOBAL_V3_ACTIVE")) + assert.ok(text.includes("Instructions removed: pkg/b/AGENTS.md")) + assert.ok(text.includes("Instructions removed: pkg/c/AGENTS.md")) +}) + +test("recognizes budget-prefixed baselines, compact baselines, and budget-prefixed change batches", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "Start under tight instruction budget" }] }, + baselineMsg( + [{ path: "AGENTS.md", content: "BUDGET_BASELINE_V1" }], + { budgetLine: "Workspace instruction budget 16384 bytes: omitted ~/.dsh/AGENTS.md; truncated AGENTS.md from 20000 to 15000 bytes" }, + ), + { role: "assistant", content: [{ type: "text", text: "Understood." }] }, + changesMsg( + [ + { action: "add", path: "pkg/x/AGENTS.md", scope: "pkg/x", content: "BUDGET_ADDED_PKG_X" }, + ], + { budgetLine: "Workspace instruction budget 4096 bytes: truncated pkg/x/AGENTS.md from 8000 to 3600 bytes" }, + ), + ] + + pushFillerTurns(messages) + messages.push({ role: "user", content: [{ type: "text", text: "Apply budget-clipped rules" }] }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/repo", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(text.includes("BUDGET_BASELINE_V1")) + assert.ok(text.includes("BUDGET_ADDED_PKG_X")) + + // Also verify compact budget fallback baseline is superseded cleanly when replaced. + const compactMsgs = [ + { role: "user", content: [{ type: "text", text: "Start tiny budget" }] }, + baselineMsg( + [{ path: "AGENTS.md", content: "COMPACT_BASELINE_V1" }], + { + budgetLine: "Workspace instruction budget 512 bytes: omitted ~/.dsh/AGENTS.md; truncated AGENTS.md from 4000 to 200 bytes", + compact: true, + }, + ), + changesMsg( + [{ action: "update", path: "AGENTS.md", content: "COMPACT_UPDATE_V2" }], + { + budgetLine: "Workspace instruction budget 512 bytes: truncated AGENTS.md from 4000 to 200 bytes", + compact: true, + }, + ), + ] + pushFillerTurns(compactMsgs) + compactMsgs.push({ role: "user", content: [{ type: "text", text: "Continue" }] }) + + const compactText = joinText(renderInitialPrompt({ system: "You are DSH.", messages: compactMsgs }, "/repo", false, 0)) + assert.ok(Buffer.byteLength(compactText, "utf8") <= LIMIT) + assert.ok(compactText.includes("COMPACT_UPDATE_V2")) + assert.ok(!compactText.includes("COMPACT_BASELINE_V1")) +}) + +test("cleared runtime context supersedes earlier session info snapshot", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "Check runtime context" }] }, + sessionInfoMsg('Current working directory: "/old/sandbox".'), + { role: "assistant", content: [{ type: "text", text: "Noted." }] }, + clearedRuntimeContextMsg(), + ] + + pushFillerTurns(messages) + messages.push({ role: "user", content: [{ type: "text", text: "Proceed" }] }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/repo", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(text.includes("Current runtime context: none. Earlier runtime-context snapshots no longer apply.")) + assert.ok(!text.includes('Current working directory: "/old/sandbox".')) +}) + +test("ignores user-pasted quotes in both history and current turn", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "Start investigation" }] }, + skillCatalogMsg([["real-skill", "genuine"]]), + { role: "assistant", content: [{ type: "text", text: "Understood." }] }, + ] + pushFillerTurns(messages) + messages.push({ + role: "user", + content: [{ + type: "text", + text: "Sample log snippet:\n\n\n- `fake-skill`: quoted\n\n", + }], + }) + messages.push({ role: "assistant", content: [{ type: "text", text: "Noted " + "z".repeat(1500) }] }) + messages.push({ + role: "user", + content: [{ + type: "text", + text: "Even if I quote - `quoted`, use the real skill", + }], + }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/repo", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(text.includes("`real-skill`: genuine")) +}) + +test("does not anchor pasted or backtrack on unclosed tags in non-DSH sessions", () => { + const messages = [ + { + role: "user", + content: [{ + type: "text", + text: "\nContents of /repo/CLAUDE.md:\nKeep diffs minimal.\n\n\nImplement refactor.", + }], + }, + ] + for (let i = 0; i < 40; i++) { + messages.push({ role: "assistant", content: [{ type: "text", text: `step ${i} ` + "a".repeat(2400) }] }) + messages.push({ role: "user", content: [{ type: "text", text: `next ${i} ` + "u".repeat(2400) }] }) + } + messages.splice(5, 0, { + role: "user", + content: [{ type: "text", text: "".repeat(2000) + "".repeat(500) }], + }) + messages.splice(10, 0, { + role: "user", + content: [{ + type: "text", + text: "Pasted fixture:\n```xml\n\n\n- `pasted-only`: ignore\n\n\n```", + }], + }) + messages.push({ role: "user", content: [{ type: "text", text: "Summarize the refactor" }] }) + + const t0 = performance.now() + const text = joinText(renderInitialPrompt({ system: "You are Claude Code.", messages }, "/repo", false, 0)) + const elapsed = performance.now() - t0 + + assert.ok(elapsed < 500, `expected linear-time scan, took ${elapsed.toFixed(1)} ms`) + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(!text.includes("`pasted-only`: ignore")) +}) + +test("keeps latest assistant reply under combined pinReserve and stateReserve on short nudge", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "Build feature " + "h".repeat(8000) }] }, + baselineMsg([{ path: "~/.dsh/AGENTS.md", content: "R".repeat(18000) }]), + skillCatalogMsg([["lark-doc", "S".repeat(14000)]]), + ] + pushFillerTurns(messages, 35, 2400) + messages.push({ role: "user", content: [{ type: "text", text: "Update handler and add validation " + "q".repeat(12000) }] }) + messages.push({ role: "assistant", content: [{ type: "text", text: "CRITICAL_LAST_ASSISTANT_REPLY " + "k".repeat(8000) }] }) + messages.push({ role: "user", content: [{ type: "text", text: "continue" }] }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/repo", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(text.includes("CRITICAL_LAST_ASSISTANT_REPLY")) + assert.ok(text.includes("`lark-doc`:")) +}) + +test("preserves latest reply and when history[0] is oversized", () => { + const messages = [ + { role: "user", content: [{ type: "text", text: "HUGE_OPENING " + "O".repeat(65000) }] }, + skillCatalogMsg([["megrez-db-map", "db lookup"]]), + ] + for (let i = 0; i < 20; i++) { + messages.push({ role: "assistant", content: [{ type: "text", text: `mid ${i} ` + "d".repeat(3000) }] }) + messages.push({ role: "user", content: [{ type: "text", text: `u ${i} ` + "e".repeat(3000) }] }) + } + messages.push({ role: "assistant", content: [{ type: "text", text: "FINAL_ASSISTANT_TURN " + "F".repeat(18000) }] }) + messages.push({ role: "user", content: [{ type: "text", text: "Inspect the student table schema" }] }) + + const text = joinText(renderInitialPrompt({ system: "You are DSH.", messages }, "/repo", false, 0)) + + assert.ok(Buffer.byteLength(text, "utf8") <= LIMIT) + assert.ok(text.includes("HUGE_OPENING")) + assert.ok(text.includes("FINAL_ASSISTANT_TURN")) + assert.ok(text.includes("`megrez-db-map`: db lookup")) +}) diff --git a/test/duplicate-result-notice.mjs b/test/duplicate-result-notice.mjs new file mode 100644 index 0000000..c608cb9 --- /dev/null +++ b/test/duplicate-result-notice.mjs @@ -0,0 +1,239 @@ +// inspectToolTurn appends protocol notices (such as ) to a +// tool result's content before continueWith stores call.result. When the same +// raw tool_result is replayed while the turn is still open (a multi-step tool +// turn, a retry, or Claude Code auto-compaction), duplicate validation must +// compare the canonical raw tool_result rather than the notice-enriched copy +// (#1475). + +import { test } from "node:test" +import assert from "node:assert/strict" +import { baseBody, continueWithToolResults, createBridgeKit, readSse, sleep } from "./testkit.mjs" + +function promptText(params) { + return (params?.prompt || []).map((part) => (part.type === "text" ? part.text : "")).join("") +} + +test("replaying an unchanged tool_result after system notices were appended passes validation and delivers once", async () => { + const kit = await createBridgeKit({}) + try { + const delivered = [] + kit.defaultPrompt = async (agent) => { + const r1 = await agent.tool("Read", { path: "/one" }) + delivered.push(r1) + const r2 = await agent.tool("Read", { path: "/two" }) + delivered.push(r2) + await agent.text(`done:${r2?.result?.content?.map((p) => p.text).join("|") || ""}`) + return { stopReason: "end_turn" } + } + + const firstBody = baseBody({ messages: [{ role: "user", content: "two steps" }] }) + const first = await readSse(await kit.request(firstBody)) + assert.equal(first.stopReason, "tool_use") + const call1 = first.content.find((b) => b.type === "tool_use") + + const secondBody = continueWithToolResults(firstBody, first, () => "step-one") + secondBody.messages.at(-1).content.push({ + type: "text", + text: "\nFirst notice\n", + }) + const second = await readSse(await kit.request(secondBody)) + assert.equal(second.stopReason, "tool_use") + const call2 = second.content.find((b) => b.type === "tool_use") + assert.equal(delivered.length, 1) + const firstTexts = delivered[0]?.result?.content?.map((p) => p.text) || [] + assert.deepEqual(firstTexts, ["step-one", "\nFirst notice\n"]) + + const changedContent = continueWithToolResults(firstBody, first, () => "changed-result") + const conflict1 = await kit.request(changedContent) + assert.equal(conflict1.status, 409) + assert.match((await conflict1.json())?.error?.message || "", /conflicting duplicate result/) + + const changedError = continueWithToolResults(firstBody, first, () => "step-one") + changedError.messages.at(-1).content[0].is_error = true + const conflict2 = await kit.request(changedError) + assert.equal(conflict2.status, 409) + + const thirdBody = { + ...secondBody, + messages: [ + ...secondBody.messages, + { role: "assistant", content: second.content }, + { + role: "user", + content: [ + { type: "tool_result", tool_use_id: call1.id, content: "step-one" }, + { type: "tool_result", tool_use_id: call2.id, content: "step-two" }, + { type: "text", text: "\nSecond notice\n" }, + ], + }, + ], + } + const thirdRes = await kit.request(thirdBody) + assert.equal(thirdRes.status, 200, thirdRes.status !== 200 ? await thirdRes.text() : "") + const third = await readSse(thirdRes) + assert.equal(third.stopReason, "end_turn") + assert.equal(delivered.length, 2, "first MCP call is not delivered a second time") + assert.equal(kit.acpSpawns.length, 1) + const secondTexts = delivered[1]?.result?.content?.map((p) => p.text) || [] + assert.deepEqual(secondTexts, ["step-two", "\nSecond notice\n"]) + } finally { + await kit.dispose() + } +}) + +test("auto-compaction replaying an unchanged tool_result with system notices does not return 409", async () => { + const kit = await createBridgeKit({}) + try { + kit.defaultPrompt = async (agent) => { + const text = promptText({ prompt: agent.prompt }) + if (text.includes("SUMMARIZE_COMPACT")) { + await agent.text("compact summary") + return { stopReason: "end_turn" } + } + await agent.tool("Read", { path: "/one" }) + await agent.tool("Read", { path: "/two" }) + await agent.text("done") + return { stopReason: "end_turn" } + } + + const headers = { "x-magpie-session": "compact-session-1475" } + const firstBody = baseBody({ messages: [{ role: "user", content: "start work" }] }) + const first = await readSse(await kit.request(firstBody, { headers })) + const call1 = first.content.find((b) => b.type === "tool_use") + + const secondBody = continueWithToolResults(firstBody, first, () => "step-one") + secondBody.messages.at(-1).content.push({ + type: "text", + text: "\nHook context\n", + }) + const second = await readSse(await kit.request(secondBody, { headers })) + assert.equal(second.stopReason, "tool_use") + + const compactBody = baseBody({ + system: "You are summarizing the conversation.", + messages: [ + ...firstBody.messages, + { role: "assistant", content: first.content }, + { + role: "user", + content: [ + { type: "tool_result", tool_use_id: call1.id, content: "step-one" }, + { type: "text", text: "\nHook context\n" }, + { type: "text", text: "SUMMARIZE_COMPACT now" }, + ], + }, + ], + }) + const compactRes = await kit.request(compactBody, { headers }) + assert.equal(compactRes.status, 200, compactRes.status !== 200 ? await compactRes.text() : "") + const compact = await readSse(compactRes) + assert.equal(compact.stopReason, "end_turn") + assert.ok(compact.content.some((b) => b.text?.includes("compact summary"))) + } finally { + await kit.dispose() + } +}) + +test("same-batch equal tool_result blocks followed by a notice deliver once and retain the notice", async () => { + const kit = await createBridgeKit({}) + try { + const delivered = [] + kit.defaultPrompt = async (agent) => { + delivered.push(await agent.tool("Read", { path: "/dup" })) + await agent.text("finished") + return { stopReason: "end_turn" } + } + + const firstBody = baseBody({ messages: [{ role: "user", content: "same batch dup" }] }) + const first = await readSse(await kit.request(firstBody)) + const call = first.content.find((b) => b.type === "tool_use") + + const next = { + ...firstBody, + messages: [ + ...firstBody.messages, + { role: "assistant", content: first.content }, + { + role: "user", + content: [ + { type: "tool_result", tool_use_id: call.id, content: "same-value" }, + { type: "tool_result", tool_use_id: call.id, content: "same-value" }, + { type: "text", text: "\nRetained notice\n" }, + ], + }, + ], + } + const res = await kit.request(next) + assert.equal(res.status, 200) + const done = await readSse(res) + assert.equal(done.stopReason, "end_turn") + assert.equal(delivered.length, 1) + assert.deepEqual( + delivered[0]?.result?.content?.map((p) => p.text), + ["same-value", "\nRetained notice\n"], + ) + } finally { + await kit.dispose() + } +}) + +test("deferred tool_result enriched with a notice compares by raw key on replay", async () => { + const kit = await createBridgeKit({ env: { AGY_BRIDGE_IDE_CALL_DEADLINE_MS: "40" } }) + try { + let firstPromptDone = false + let latePromptText = "" + kit.prompts.push(async (agent) => { + await agent.tool("Read", { path: "/slow" }) + firstPromptDone = true + return { stopReason: "end_turn" } + }) + kit.prompts.push(async (agent) => { + latePromptText = promptText({ prompt: agent.prompt }) + await agent.tool("Read", { path: "/after-late" }) + await agent.text("after late done") + return { stopReason: "end_turn" } + }) + + const firstBody = baseBody({ messages: [{ role: "user", content: "deferred notice" }] }) + const first = await readSse(await kit.request(firstBody)) + const call1 = first.content.find((b) => b.type === "tool_use") + for (let i = 0; i < 200 && !firstPromptDone; i++) await sleep(5) + assert.ok(firstPromptDone) + await sleep(20) + + const secondBody = continueWithToolResults(firstBody, first, () => "late-one") + secondBody.messages.at(-1).content.push({ + type: "text", + text: "\nDeferred notice\n", + }) + const second = await readSse(await kit.request(secondBody)) + assert.equal(second.stopReason, "tool_use") + assert.match(latePromptText, /late-one/) + assert.match(latePromptText, /Deferred notice/) + const call2 = second.content.find((b) => b.type === "tool_use") + + const conflict = await kit.request(continueWithToolResults(firstBody, first, () => "late-changed")) + assert.equal(conflict.status, 409) + + const thirdBody = { + ...secondBody, + messages: [ + ...secondBody.messages, + { role: "assistant", content: second.content }, + { + role: "user", + content: [ + { type: "tool_result", tool_use_id: call1.id, content: "late-one" }, + { type: "tool_result", tool_use_id: call2.id, content: "step-two" }, + ], + }, + ], + } + const thirdRes = await kit.request(thirdBody) + assert.equal(thirdRes.status, 200, thirdRes.status !== 200 ? await thirdRes.text() : "") + const third = await readSse(thirdRes) + assert.equal(third.stopReason, "end_turn") + } finally { + await kit.dispose() + } +}) diff --git a/test/image-bytes.mjs b/test/image-bytes.mjs new file mode 100644 index 0000000..0178680 --- /dev/null +++ b/test/image-bytes.mjs @@ -0,0 +1,86 @@ +// plugins#1527 (Pisces233): an image whose base64 is valid but whose bytes +// are no image reached Gemini, which answered 400 "Unable to process input +// image" as the reply's text. An image whose bytes are another of the four +// types than it was labelled (a JPEG sent as image/png) goes as what it is. + +import { test } from "node:test" +import assert from "node:assert/strict" +import { baseBody, continueWithToolResults, createBridgeKit, readSse } from "./testkit.mjs" + +const b64 = (hex, tail = "") => Buffer.concat([Buffer.from(hex, "hex"), Buffer.from(tail)]).toString("base64") +const JPEG = b64("ffd8ffe000104a4649460001", "jpeg body") +const PNG = b64("89504e470d0a1a0a0000000d49484452", "png body") +const TEXT = Buffer.from("hello, a text file labelled image/png").toString("base64") +const image = (data, mediaType = "image/png") => ({ type: "image", source: { type: "base64", media_type: mediaType, data } }) + +async function withKit(fn) { + const kit = await createBridgeKit({ promptImages: true }) + try { + return await fn(kit) + } finally { + await kit.dispose() + } +} + +const promptImages = (kit) => (kit.acpLog.filter((entry) => entry.method === "session/prompt").at(-1)?.params?.prompt || []) + .filter((part) => part.type === "image") + +test("a user's JPEG labelled image/png goes as image/jpeg", async () => { + await withKit(async (kit) => { + kit.defaultPrompt = async (agent) => { await agent.text("a cat"); return { stopReason: "end_turn" } } + const response = await kit.request(baseBody({ stream: false, messages: [{ role: "user", content: [image(JPEG), { type: "text", text: "what is it" }] }] })) + assert.equal(response.status, 200, await response.clone().text()) + assert.deepEqual(promptImages(kit).map((part) => [part.mimeType, part.data]), [["image/jpeg", JPEG]]) + }) +}) + +test("a user's image whose bytes are no image is refused before agy", async () => { + await withKit(async (kit) => { + for (const data of [TEXT, "AAAA"]) { + const response = await kit.request(baseBody({ stream: false, messages: [{ role: "user", content: [image(data), { type: "text", text: "what is it" }] }] })) + const text = await response.text() + assert.equal(response.status, 400, text) + assert.match(text, /not an image/) + } + assert.equal(kit.acpLog.filter((entry) => entry.method === "session/prompt").length, 0) + }) +}) + +test("a tool's images go to agy as their bytes say, and one that is no image becomes a note", async () => { + await withKit(async (kit) => { + let reply + kit.defaultPrompt = async (agent) => { + if (reply) { await agent.text("done"); return { stopReason: "end_turn" } } + reply = await agent.tool("Read", { path: "/repo/shot.png" }) + await agent.text("seen") + return { stopReason: "end_turn" } + } + const body = baseBody({ messages: [{ role: "user", content: "look at shot.png" }] }) + const first = await readSse(await kit.request(body)) + assert.equal(first.stopReason, "tool_use") + const next = continueWithToolResults(body, first, () => [image(JPEG), image(PNG, "image/jpeg"), image(TEXT), image("AAAA", "image/webp")]) + const result = await readSse(await kit.request(next)) + assert.ok(!result.error, JSON.stringify(result.error)) + // agy takes a tool's images in the next prompt (IMAGE_FOLLOWS) + const sent = kit.acpLog.filter((entry) => entry.method === "session/prompt").flatMap((entry) => entry.params.prompt || []) + assert.deepEqual(sent.filter((part) => part.type === "image").map((part) => part.mimeType), ["image/jpeg", "image/png"]) + const content = reply.result.content + const notes = content.filter((part) => part.type === "text" && /could not be read/.test(part.text)).map((part) => part.text) + assert.equal(notes.length, 2, JSON.stringify(content)) + assert.match(notes[0], /image\/png/) + assert.match(notes[1], /image\/webp/) + }) +}) + +test("a -preview flash id goes to the account's flash model; an -image one does not", async () => { + await withKit(async (kit) => { + kit.defaultPrompt = async (agent) => { await agent.text("ok"); return { stopReason: "end_turn" } } + const preview = await kit.request(baseBody({ stream: false, model: "agy-cli/gemini-3.1-flash-lite-preview" })) + assert.equal(preview.status, 200, await preview.clone().text()) + const flash = kit.setModels.at(-1) + assert.match(flash ?? "", /^gemini-[0-9.]+-flash-(?:low|high)$/) + const before = kit.setModels.length + await (await kit.request(baseBody({ stream: false, model: "agy-cli/gemini-3.1-flash-image" }))).text() + assert.ok(!kit.setModels.slice(before).includes(flash), JSON.stringify(kit.setModels.slice(before))) + }) +}) diff --git a/test/image-signature-unit.mjs b/test/image-signature-unit.mjs new file mode 100644 index 0000000..44f3f18 --- /dev/null +++ b/test/image-signature-unit.mjs @@ -0,0 +1,41 @@ +// Standalone checks for the image magic-byte guard. Run with: +// node test/image-signature-unit.mjs +import { hasImageSignature } from "../index.mjs" + +let failed = 0 +function check(name, ok, detail) { + if (ok) { + console.log(`ok ${name}`) + return + } + failed++ + console.error(`FAIL ${name}${detail ? " :: " + detail : ""}`) +} + +// A 1x1 PNG header, and real JPEG/GIF/WebP signatures. +const png = Buffer.from("89504e470d0a1a0a0000000d4948445200000001000000010802000000907753de", "hex") +const jpeg = Buffer.from("ffd8ffe000104a4649460001", "hex") +const gif = Buffer.from("47494638396101000100", "hex") +const webp = Buffer.from("524946461a0000005745425056503820", "hex") +const notImage = Buffer.from("AAAA", "base64") +const text = Buffer.from("hello, this is a text file labelled image/png") + +check("PNG signature accepted", hasImageSignature(png, "image/png")) +check("JPEG signature accepted", hasImageSignature(jpeg, "image/jpeg")) +check("GIF89a signature accepted", hasImageSignature(gif, "image/gif")) +check("WebP RIFF....WEBP accepted", hasImageSignature(webp, "image/webp")) + +check("base64 'AAAA' is not an image", !hasImageSignature(notImage, "image/png")) +check("text labelled image/png rejected", !hasImageSignature(text, "image/png")) +check("PNG bytes as image/jpeg rejected", !hasImageSignature(png, "image/jpeg")) +check("PNG bytes as image/gif rejected", !hasImageSignature(png, "image/gif")) +check("empty buffer rejected", !hasImageSignature(Buffer.alloc(0), "image/png")) +check("tiny buffer rejected", !hasImageSignature(Buffer.from([0x89, 0x50]), "image/png")) +check("unknown media type rejected", !hasImageSignature(png, "image/bmp")) +check("null rejected", !hasImageSignature(null, "image/png")) + +if (failed) { + console.error(`\n${failed} check(s) failed`) + process.exit(1) +} +console.log("\nALL OK") diff --git a/test/image-slim.mjs b/test/image-slim.mjs new file mode 100644 index 0000000..6962fb4 --- /dev/null +++ b/test/image-slim.mjs @@ -0,0 +1,64 @@ +import assert from "node:assert/strict" +import fs from "node:fs" +import os from "node:os" +import path from "node:path" +import { pathToFileURL } from "node:url" +import { after, test } from "node:test" + +// Expose private seams from an isolated copy, without adding production exports. +const workspace = fs.mkdtempSync(path.join(os.tmpdir(), "agy-image-slim-test-")) +const entry = new URL("../index.mjs", import.meta.url) +let source = fs.readFileSync(entry, "utf8") +source = source.replace(/from "(\.\/[^"\n]+)"/g, (_, target) => `from ${JSON.stringify(new URL(target, entry).href)}`) +fs.writeFileSync(path.join(workspace, "bridge.mjs"), source + "\nexport { sameHistoryUpToImages };\n") +const { sameHistoryUpToImages } = await import(pathToFileURL(path.join(workspace, "bridge.mjs")).href) +after(() => fs.rmSync(workspace, { recursive: true, force: true })) + +const U = (content) => ({ role: "user", content }) +const A = (content) => ({ role: "assistant", content }) +const image = (data = "aW1hZ2VB") => ({ type: "image", source: { type: "base64", media_type: "image/png", data } }) +const text = (value) => ({ type: "text", text: value }) +const call = (id) => ({ type: "tool_use", id, name: "view_image", input: { path: `/tmp/${id}.png` } }) +const result = (id, content) => ({ type: "tool_result", tool_use_id: id, content }) + +// What magpie's image-slim middleware writes where it took out an image the +// model has already seen. +const SLIM = "[1.42 MB image left out here: a view_image result, already seen earlier in this conversation. Rely on what you already said about it. It is the file /tmp/a.png; call view_image on that path if you need to look at it again.]" + +test("an earlier image image-slim swapped for its placeholder is the same history", () => { + const expected = [U("look at it"), A([call("a")]), U([result("a", [text("saved /tmp/a.png"), image()])]), A([text("the button is misaligned")])] + const slimmed = [expected[0], expected[1], U([result("a", [text("saved /tmp/a.png"), text(SLIM)])]), expected[3]] + assert.equal(sameHistoryUpToImages(expected, slimmed), true) + const changed = [expected[0], expected[1], U([result("a", [text("saved /tmp/OTHER.png"), text(SLIM)])]), expected[3]] + assert.equal(sameHistoryUpToImages(expected, changed), false, "a changed text is still a changed history") +}) + +test("on Codex image-slim swaps a whole view_image output for its placeholder as a plain string", () => { + const expected = [U("look at it"), A([call("a")]), U([result("a", [image()])]), A([text("the button is misaligned")])] + const slimmed = [expected[0], expected[1], U([result("a", SLIM)]), expected[3]] + assert.equal(sameHistoryUpToImages(expected, slimmed), true) + const other = [expected[0], expected[1], U([result("a", "some other output")]), expected[3]] + assert.equal(sameHistoryUpToImages(expected, other), false, "a real string result is still a changed history") +}) + +test("magpie's own placeholders for an earlier image keep the history the same", () => { + const expected = [U("look at it"), A([call("a")]), U([result("a", [image()])]), A([text("the button is misaligned")]), U("and now?")] + for (const placeholder of [ + "[An earlier image was left out here to keep this request under its size limit.]", + "[An earlier image was omitted here to keep this request within the model's image limit.]", + "[This image is omitted here; the same image appears again later in this conversation.]", + ]) { + const swapped = [expected[0], expected[1], U([result("a", [text(placeholder)])]), expected[3], expected[4]] + assert.equal(sameHistoryUpToImages(expected, swapped), true, placeholder) + } +}) + +test("an image added to or taken out of an earlier message is still a changed history", () => { + const expected = [U([text("look at it"), image()]), A([text("a cat")]), U("and now?")] + const added = [U([text("look at it"), image(), image("aW1hZ2VC")]), expected[1], expected[2]] + assert.equal(sameHistoryUpToImages(expected, added), false, "an extra image") + const removed = [U([text("look at it")]), expected[1], expected[2]] + assert.equal(sameHistoryUpToImages(expected, removed), false, "an image gone with no placeholder") + const placeholderOnly = [U([text("look at it"), text(SLIM)]), expected[1], expected[2]] + assert.equal(sameHistoryUpToImages(expected, placeholderOnly), true, "the image swapped for its placeholder") +}) diff --git a/test/masking-drift.mjs b/test/masking-drift.mjs index 9759f20..1854246 100644 --- a/test/masking-drift.mjs +++ b/test/masking-drift.mjs @@ -358,3 +358,104 @@ test("session_new for a changed history says where, as the history key reads it, stderr.restore() } }) + +const PLACEHOLDER_NOTE = "Values written like {{NAME_ab12cd34}} are placeholders for real values. Use them exactly as written, in replies and in tool calls alike: they are filled in with the real values before anything runs. Don't ask to verify them, and don't replace them with examples." +const WRAPPED_PLACEHOLDER_NOTE = `\n${PLACEHOLDER_NOTE}\n` + +test("wrapped placeholder note appearing and disappearing keeps the live session", async () => { + // Simulates Responses -> Anthropic translation of Magpie's developer placeholder note: + // steps 0..1 unmasked; step 2 masking starts and appends the wrapped note to message[2]; + // step 3 masking turns off and the wrapped note disappears. + const { drops } = await run({ + mask: (text, step) => step === 2 ? text.replaceAll("Alice Johnson", "{{NAME_a2b3c4d5}}") : text, + extra: (messages, i) => i !== 2 ? messages : messages.map((message, index) => index !== 2 ? message + : { ...message, content: [...message.content, { type: "text", text: WRAPPED_PLACEHOLDER_NOTE }] }), + }) + assert.deepEqual(drops, [], JSON.stringify(drops)) +}) + +test("placeholder note appearing and disappearing in system prompt keeps the live session", async () => { + const stderr = captureStderr() + const kit = await createBridgeKit({}) + try { + kit.defaultPrompt = async (agent) => { + await agent.tool("Read", { path: "/repo/a.txt" }) + await agent.tool("Read", { path: "/repo/b.txt" }) + await agent.text("all done") + return { stopReason: "end_turn" } + } + const baseSystem = "You are a test agent." + const opening = baseBody({ system: baseSystem, messages: [{ role: "user", content: "read a and b" }] }) + const step1 = await readSse(await kit.request(opening)) + assert.equal(step1.stopReason, "tool_use") + const call1 = step1.content.find((b) => b.type === "tool_use") + + // Step 2: masking adds the placeholder note to system. + const req1 = baseBody({ + system: `${baseSystem}\n\n${PLACEHOLDER_NOTE}`, + messages: [ + ...opening.messages, + { role: "assistant", content: step1.content }, + { role: "user", content: [{ type: "tool_result", tool_use_id: call1.id, content: "ok" }] }, + ], + }) + const step2 = await readSse(await kit.request(req1)) + assert.equal(step2.stopReason, "tool_use") + const call2 = step2.content.find((b) => b.type === "tool_use") + + // Step 3: masking turns off and the note disappears from system. + const req2 = baseBody({ + system: baseSystem, + messages: [ + ...req1.messages, + { role: "assistant", content: step2.content }, + { role: "user", content: [{ type: "tool_result", tool_use_id: call2.id, content: "ok2" }] }, + ], + }) + const done = await readSse(await kit.request(req2)) + assert.equal(done.stopReason, "end_turn") + const drops = stderr.lines.filter((row) => row.action === "drop_live") + assert.deepEqual(drops, [], JSON.stringify(drops)) + assert.equal(kit.acpLog.filter((entry) => entry.method === "session/new").length, 1) + } finally { + await kit.dispose() + stderr.restore() + } +}) + +test("wrapped placeholder note before tool_result does not trigger user steer", async () => { + const stderr = captureStderr() + const kit = await createBridgeKit({}) + try { + kit.defaultPrompt = async (agent) => { + await agent.tool("Read", { path: "/repo/a.txt" }) + await agent.text("done") + return { stopReason: "end_turn" } + } + const opening = baseBody({ messages: [{ role: "user", content: "read a" }] }) + const step1 = await readSse(await kit.request(opening)) + assert.equal(step1.stopReason, "tool_use") + const call1 = step1.content.find((b) => b.type === "tool_use") + + const req1 = baseBody({ + messages: [ + ...opening.messages, + { role: "assistant", content: step1.content }, + { + role: "user", + content: [ + { type: "text", text: WRAPPED_PLACEHOLDER_NOTE }, + { type: "tool_result", tool_use_id: call1.id, content: "ok" }, + ], + }, + ], + }) + const done = await readSse(await kit.request(req1)) + assert.equal(done.stopReason, "end_turn") + assert.equal(kit.acpLog.filter((entry) => entry.method === "session/new").length, 1) + assert.equal(kit.acpLog.filter((entry) => entry.method === "session/prompt").length, 1) + } finally { + await kit.dispose() + stderr.restore() + } +}) diff --git a/test/platform.mjs b/test/platform.mjs index 9fe6378..9cf453d 100644 --- a/test/platform.mjs +++ b/test/platform.mjs @@ -2,7 +2,24 @@ import assert from "node:assert/strict" import childProcess from "node:child_process" import { syncBuiltinESMExports } from "node:module" import { test } from "node:test" -import { agyCandidates, agySpawnSpec, childEnv, spawnAgy, windowsMcpShim } from "../platform.mjs" +import { agyCandidates, agySpawnSpec, childEnv, holdsHome, spawnAgy, windowsMcpShim } from "../platform.mjs" + +// plugins#1405 (Danco): agy loads the home folder's contents as the +// workspace's customizations and drops the client's biggest tools to fit +test("the home folder and those above it are never added to agy's workspace", () => { + assert.equal(holdsHome("/Users/me", "/Users/me", "darwin"), true) + assert.equal(holdsHome("/Users/me/", "/Users/me", "darwin"), true) + assert.equal(holdsHome("/Users", "/Users/me", "darwin"), true) + assert.equal(holdsHome("/", "/home/me", "linux"), true) + assert.equal(holdsHome("/Users/me/project", "/Users/me", "darwin"), false) + assert.equal(holdsHome("/Users/meow", "/Users/me", "darwin"), false) + assert.equal(holdsHome("/tmp/x", "/Users/me", "darwin"), false) + assert.equal(holdsHome("c:\\users\\me", "C:\\Users\\Me", "win32"), true) + assert.equal(holdsHome("C:\\", "C:\\Users\\Me", "win32"), true) + assert.equal(holdsHome("D:\\", "C:\\Users\\Me", "win32"), false) + assert.equal(holdsHome("C:\\Users\\Me\\code", "C:\\Users\\Me", "win32"), false) + assert.equal(holdsHome("", "/Users/me", "darwin"), false) +}) test("Windows discovery considers exe/cmd/bat, Path and LOCALAPPDATA", () => { const candidates = agyCandidates({ Path: 'C:\\Program Files\\agy;D:\\tools', LOCALAPPDATA: 'C:\\Users\\Test\\AppData\\Local' }, 'C:\\Users\\Test', 'win32') diff --git a/test/prefill.mjs b/test/prefill.mjs index 5814302..d391cde 100644 --- a/test/prefill.mjs +++ b/test/prefill.mjs @@ -73,10 +73,8 @@ test("validateBody serves a prefill tail and rejects the unsupported shapes", () validateBody({ messages: [U("1"), A("p1"), A("r1"), U("2"), A("p2")] }) assert.throws(() => validateBody({ messages: [A("r"), A("p")] }), /no user turn to continue from/) assert.throws(() => validateBody({ messages: [U("1"), toolUseTail()] }), /not from the user or a tool-result/) - assert.throws( - () => validateBody({ messages: [U("1"), A("r1"), { role: "user", content: [{ type: "tool_result", tool_use_id: "call_a", content: "done" }] }, A("p")] }), - /tool_result with an assistant prefill/, - ) + // magpie going on from a reply cut after a tool round (plugins#1512) + validateBody({ messages: [U("1"), toolUseTail(), { role: "user", content: [{ type: "tool_result", tool_use_id: "call_a", content: "done" }] }, A("p")] }) }) test("a trailing prefill run renders as a continuation carrier, not a system reminder", () => { diff --git a/test/repeat-batch.mjs b/test/repeat-batch.mjs index f5fbdbf..7377c16 100644 --- a/test/repeat-batch.mjs +++ b/test/repeat-batch.mjs @@ -1565,6 +1565,58 @@ test("agy's high-traffic ending fails the turn as an overloaded 503, not a rate } }) +// plugins#1541: before that ending agy retries the 503 for minutes, saying +// so only in its log. The first retry line ends the turn, so magpie can ask +// another account at once. +const CAPACITY_RETRY = "I1125 13:34:23.878000 6120 run.go:88] Run: attempt 1 failed (transport error (Unavailable, HTTP 503): No capacity available for model gemini-4-hydrogen-low on the server), retrying in 4s\n" + +test("agy's silent no-capacity retry ends the turn as an overloaded 503 before anything is streamed", async () => { + for (const stream of [false, true]) { + await withKit({}, async (kit) => { + // how agy's turn ended: cancelled by the bridge, or by its own give-up + let ended = null + kit.defaultPrompt = async (agent) => { + fs.appendFileSync(agyLogOf(kit), CAPACITY_RETRY) + ended = await Promise.race([agent.waitCancel().then(() => "cancelled"), + new Promise((resolve) => setTimeout(() => resolve("gave up"), 20000).unref())]) + return { stopReason: "end_turn" } + } + const started = Date.now() + const response = await kit.request(baseBody({ metadata: { user_id: `capacity-${stream}` }, + messages: [{ role: "user", content: "hello" }], stream })) + if (stream) { + const error = sseError(await response.text()) + assert.equal(error.type, "overloaded_error") + assert.notEqual(error.noRetry, true) + assert.match(error.message, /no capacity for this model now: .*No capacity available for model gemini-4-hydrogen-low/) + } else { + const body = await response.json() + assert.equal(response.status, 503) + assert.equal(body.error.type, "overloaded_error") + } + assert.ok(Date.now() - started < 10000, `ended after ${Date.now() - started}ms, not at agy's next retry`) + assert.notEqual(ended, "gave up", "the reply didn't wait for agy to give up") + }) + } +}) + +test("a no-capacity retry after the reply began leaves the turn to agy", async () => { + await withKit({}, async (kit) => { + kit.defaultPrompt = async (agent) => { + await agent.text("Working on it. ") + fs.appendFileSync(agyLogOf(kit), CAPACITY_RETRY) + await new Promise((resolve) => setTimeout(resolve, 1500)) + await agent.text("Done.") + return { stopReason: "end_turn" } + } + const response = await kit.request(baseBody({ metadata: { user_id: "capacity-late" }, + messages: [{ role: "user", content: "hello" }], stream: false })) + const body = await response.json() + assert.equal(response.status, 200) + assert.equal(replyText(body), "Working on it. Done.") + }) +}) + test("agy's high-traffic ending fails a non-stream request as an HTTP 503", async () => { await withKit({}, async (kit) => { markerAgent(kit, ["Let me look", BUSY.slice(0, 30), BUSY.slice(30)]) @@ -2022,6 +2074,83 @@ test("forked session or subagent carrying an ancestor tool_use does not hit conf }) }) +// plugins#1545: Claude Code's AgentSummary sends the sub-agent's own +// conversation again, its tool result and the ask for a few words, while the +// worker's response still runs. In the worker's scope it got 503 "already +// has an active response" seven times over. +const SUMMARY_ASK = "Describe your most recent action in 3-5 words. Do not use tools." + +test("an AgentSummary beside a running worker is answered in a scope of its own", async () => { + await withKit({}, async (kit) => { + let release + const gate = new Promise((resolve) => { release = resolve }) + let workerReading = null + const reading = new Promise((resolve) => { workerReading = resolve }) + kit.defaultPrompt = async (agent) => { + const text = promptText({ prompt: agent.prompt }) + if (text.includes(SUMMARY_ASK)) { + await agent.text("Reading the shared file") + return { stopReason: "end_turn" } + } + const result = await agent.tool("Read", { path: "/shared" }) + workerReading() + await gate + await agent.text(`worker got:${result?.result?.content?.[0]?.text || ""}`) + return { stopReason: "end_turn" } + } + const headers = { "x-magpie-session": "claude:worker-1545", "x-magpie-subagent": "task-1" } + const opening = baseBody({ system: "worker system", messages: [{ role: "user", content: "WORK on it" }] }) + const turn1 = await readSse(await kit.request(opening, { headers })) + assert.equal(turn1.stopReason, "tool_use") + const resumed = continueWithToolResults(opening, turn1, () => "file body") + const workerDone = kit.request(resumed, { headers }).then(readSse) + await reading + const last = resumed.messages.at(-1) + const summary = { ...resumed, messages: [...resumed.messages.slice(0, -1), + { ...last, content: [...last.content, { type: "text", text: SUMMARY_ASK }] }] } + const summaryResponse = await kit.request(summary, { headers }) + assert.equal(summaryResponse.status, 200, await summaryResponse.clone().text()) + const parsed = await readSse(summaryResponse) + assert.ok(parsed.content.some((block) => block.text?.includes("Reading the shared file")), JSON.stringify(parsed.content)) + release() + const worker = await workerDone + assert.equal(worker.stopReason, "end_turn") + assert.ok(worker.content.some((block) => block.text?.includes("worker got:file body")), JSON.stringify(worker.content)) + }) +}) + +test("a tool result whose text is the summary ask stays the worker's", async () => { + await withKit({}, async (kit) => { + kit.defaultPrompt = async (agent) => { + const result = await agent.tool("Read", { path: "/shared" }) + await agent.text(`worker got:${result?.result?.content?.[0]?.text || ""}`) + return { stopReason: "end_turn" } + } + const headers = { "x-magpie-session": "claude:worker-1545b", "x-magpie-subagent": "task-2" } + const opening = baseBody({ system: "worker system", messages: [{ role: "user", content: "WORK on it" }] }) + const turn1 = await readSse(await kit.request(opening, { headers })) + const spawned = kit.acpSpawns.length + const done = await readSse(await kit.request(continueWithToolResults(opening, turn1, () => SUMMARY_ASK), { headers })) + assert.equal(done.stopReason, "end_turn") + assert.ok(done.content.some((block) => block.text?.includes(`worker got:${SUMMARY_ASK}`))) + assert.equal(kit.acpSpawns.length, spawned, "the result went to the worker's live session") + }) +}) + +test("the summary ask from a main session, not a sub-agent, stays in its session", async () => { + await withKit({}, async (kit) => { + scriptedAgent(kit, { "hello": "hi", "Describe your": "Said hello" }) + const headers = { "x-magpie-session": "claude:main-1545" } + const first = baseBody({ system: "main system", messages: [{ role: "user", content: "hello" }] }) + const done1 = await readSse(await kit.request(first, { headers })) + const spawned = kit.acpSpawns.length + const next = { ...first, messages: [...first.messages, { role: "assistant", content: done1.content }, { role: "user", content: SUMMARY_ASK }] } + const done2 = await readSse(await kit.request(next, { headers })) + assert.equal(done2.stopReason, "end_turn") + assert.equal(kit.acpSpawns.length, spawned, "kept the main session") + }) +}) + test("forked subagent arriving before parent answers its pending tool call leaves parent's call intact", async () => { await withKit({}, async (kit) => { kit.defaultPrompt = async (agent) => { diff --git a/test/signin.mjs b/test/signin.mjs index d244c4f..fc92954 100644 --- a/test/signin.mjs +++ b/test/signin.mjs @@ -1,6 +1,6 @@ import assert from "node:assert/strict" import { test } from "node:test" -import { backgroundBlocked, cannotSignIn, emailOf, forgetStoredSignIn, heldByAnother, isDead, noteDead, parseStored, readStoredSignIn, signedInEmail, storedEmail, storedSignIn, storedSignInNow } from "../signin.mjs" +import { backgroundBlocked, cannotSignIn, emailOf, forgetStoredSignIn, heldByAnother, isDead, noteDead, parseStored, readStoredSignIn, signedInEmail, storedEmail, storedSignIn, storedSignInNow, storedToken } from "../signin.mjs" const NOW = Date.parse("2026-11-13T00:00:00Z") const stored = (token, extra = {}) => JSON.stringify({ token, auth_method: "consumer", id_token_email: "someone@example.com", ...extra }) @@ -180,3 +180,25 @@ test("storedEmail is the Google account agy's keyring is signed in to, on macOS assert.equal(await storedEmail({ platform: "win32", exec: mac(0, "OK " + Buffer.from(value).toString("base64") + "\r\n"), env: {} }), "someone@example.com") assert.equal(await storedEmail({ platform: "darwin", exec: mac(0, b64(value)), env: { AGY_BRIDGE_STORED_SIGNIN: "skip" } }), "") }) + +test("Linux: agy's own sign-in is read from its token file, and no file concludes nothing (#1502)", async () => { + const fs = await import("node:fs") + const os = await import("node:os") + const path = await import("node:path") + const home = fs.mkdtempSync(path.join(os.tmpdir(), "agy-linux-")) + try { + const exec = async () => { throw new Error("no keyring tool is run on Linux") } + assert.equal((await readStoredSignIn({ platform: "linux", exec, env: { HOME: home } })).state, "unknown") + const value = stored({ access_token: "a", refresh_token: "r", expiry: "2026-11-12T00:00:00Z" }) + const file = path.join(home, ".gemini", "antigravity-cli", "antigravity-oauth-token") + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.writeFileSync(file, value) + const s = await readStoredSignIn({ platform: "linux", exec, now: NOW, env: { HOME: home } }) + assert.equal(s.state, "present") + assert.equal(s.canRenew, true) + assert.equal((await storedToken({ platform: "linux", exec, env: { HOME: home } }))?.token?.refresh_token, "r") + assert.equal(await storedEmail({ platform: "linux", exec, env: { HOME: home } }), "someone@example.com") + } finally { + fs.rmSync(home, { recursive: true, force: true }) + } +}) diff --git a/test/smoke.mjs b/test/smoke.mjs index a41b19d..850bb94 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -15,6 +15,16 @@ const stateDir = fs.mkdtempSync(path.join(os.tmpdir(), "fake-agy-state-")) const originalAutoUpdate = process.env.AGY_CLI_DISABLE_AUTO_UPDATE delete process.env.AGY_CLI_DISABLE_AUTO_UPDATE delete process.env.AGY_BRIDGE_MINIMAL_AGENT +// Every ban-risk warning the bridge prints, from the first import on: none +// while AGY_BRIDGE_MINIMAL_AGENT is off, one in the process once it is on. +const minimalWarnings = [] +{ + const write = process.stderr.write + process.stderr.write = function (chunk, ...args) { + if (String(chunk).includes('"event":"agy_bridge_warning"') && String(chunk).includes("AGY_BRIDGE_MINIMAL_AGENT")) minimalWarnings.push(String(chunk)) + return write.call(this, chunk, ...args) + } +} process.env.FAKE_AGY_LOG = logPath process.env.FAKE_AGY_STATE = stateDir const bridgeStateFile = path.join(stateDir, "bridge-sessions.json") @@ -939,6 +949,13 @@ async function launchedModel(body) { check("high thinking budget selects high", await launchedModel({ model, thinking: { type: "enabled", budget_tokens: 24000 }, messages: [{ role: "user", content: "MODEL high effort" }] }) === "gemini-test-high") check("output effort without thinking keeps the default", await launchedModel({ model, output_config: { effort: "low" }, messages: [{ role: "user", content: "MODEL title request" }] }) === "gemini-test-high") check("legacy effort ids pass through unchanged", await launchedModel({ model: legacyModel, thinking: { type: "enabled", budget_tokens: 10000 }, messages: [{ role: "user", content: "MODEL legacy id" }] }) === "gemini-test-low") + // plugins#1540: magpie says the client's effort in X-Magpie-Effort; its + // Anthropic body has only a budget held under max_tokens, or no thinking. + const told = async (effort, body) => { await readSSE(await callFetch(body, { "X-Magpie-Effort": effort })); return lastOf("user")?.model } + check("magpie's effort header beats a thinking budget held under max_tokens", await told("high", { model, thinking: { type: "enabled", budget_tokens: 3000 }, messages: [{ role: "user", content: "MODEL told high" }] }) === "gemini-test-high") + check("magpie's effort header counts with no thinking in the body", await told("low", { model, messages: [{ role: "user", content: "MODEL told low" }] }) === "gemini-test-low") + check("a level in an alias's id beats one guessed from a thinking budget", await launchedModel({ model: "agy-cli/gemini-3.5-pro-medium", thinking: { type: "enabled", budget_tokens: 30000 }, messages: [{ role: "user", content: "MODEL alias medium" }] }) === "gemini-test-medium") + check("thinking turned off still beats magpie's effort header", await told("low", { model, thinking: { type: "disabled" }, messages: [{ role: "user", content: "MODEL told off" }] }) === "gemini-test-high") check("single-effort model requests pass through unchanged", await launchedModel({ model: "agy-cli/claude-test-medium", thinking: { type: "enabled", budget_tokens: 4096 }, messages: [{ role: "user", content: "MODEL singleton" }] }) === "claude-test-medium") check("modern sessions select models and levels through ACP config options", logs().some(event => event.type === "setConfig" && event.configId === "model") && logs().some(event => event.type === "setConfig" && event.configId === "thought_level" && event.value === "low")) const offered = await plugin.provider.models() @@ -1092,14 +1109,19 @@ async function launchedModel(body) { check("UTF-8 split inside a code point preserves text", textOf(events).includes("中文😀"), textOf(events)) } +// a project folder of its own: os.tmpdir() holds HOME where HOME is a +// mktemp folder (CI's), and a folder above home is never added (plugins#1405) +const project = fs.mkdtempSync(path.join(os.tmpdir(), "agy-smoke-project-")) for (const [name, system, headers, expectedDir, named] of [ - ["local prompt", `Working directory: ${os.tmpdir()}`, {}, path.resolve(os.tmpdir()), os.tmpdir()], + ["local prompt", `Working directory: ${project}`, {}, path.resolve(project), project], ["remote prompt", "/remote-mac/project", {}, null, "/remote-mac/project"], - ["header precedence", "Current working directory: /remote-mac/project", { "x-magpie-work-dir": encodeURIComponent(os.tmpdir()) }, path.resolve(os.tmpdir()), os.tmpdir()], + ["header precedence", "Current working directory: /remote-mac/project", { "x-magpie-work-dir": encodeURIComponent(project) }, path.resolve(project), project], ["relative prompt", "Primary working directory: relative-project", {}, null, "relative-project"], + // plugins#1405 (Danco): the home folder is told, never added + ["home folder prompt", `Working directory: ${os.homedir()}`, {}, null, os.homedir()], // yetone/magpie#7223 (sevenqcx): DSH quotes the directory and ends the // sentence after the closing quote - ["quoted prompt ending a sentence", `Current working directory: "${os.tmpdir()}".`, {}, path.resolve(os.tmpdir()), os.tmpdir()], + ["quoted prompt ending a sentence", `Current working directory: "${project}".`, {}, path.resolve(project), project], ]) { const body = { model, system, messages: [{ role: "user", content: `environment ${name}` }] } const final = (await readSSE(await callFetch(body, headers))).events @@ -2174,7 +2196,7 @@ for (const location of ["inline", "system", "developer", "user"]) { const convId = inits().at(-1).convId const before = inits().length const second = continuation(first, events, [ - { type: "image", source: { type: "base64", media_type: "image/png", data: "AAAA" } }, + { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgoAAAANAAAA" } }, ]) second.messages.at(-1).content.push( { type: "text", text: "[Image: original 3423x1834, displayed at 2000x1072. Multiply coordinates by 1.71 to map to original image.]" }, @@ -2194,7 +2216,7 @@ for (const location of ["inline", "system", "developer", "user"]) { !content.some(part => part.type === "image") && content.some(part => part.text === IMAGE_FOLLOWS) && steer.convId === convId && - steer.content.some(part => part.type === "image" && part.data === "AAAA") && + steer.content.some(part => part.type === "image" && part.data === "iVBORw0KGgoAAAANAAAA") && steer.text.includes("Multiply coordinates by 1.71") && steer.text.includes("worker-1"), JSON.stringify({ content, steer: steer.content })) @@ -2205,7 +2227,7 @@ for (const location of ["inline", "system", "developer", "user"]) { const readBefore = inits().length const readSecond = continuation(readFirst, readEvents, [ { type: "text", text: "Image read successfully" }, - { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "cmVhZGltYWdl" } }, + { type: "image", source: { type: "base64", media_type: "image/jpeg", data: "/9j/4AAQSkZJRgABcmVhZGltYWdl" } }, ]) const readResponse = await callFetch(readSecond) const readFinal = (await readSSE(readResponse)).events @@ -2215,7 +2237,7 @@ for (const location of ["inline", "system", "developer", "user"]) { readResponse.status === 200 && stopOf(readFinal) === "end_turn" && inits().length === readBefore && JSON.stringify(readDelivered) === JSON.stringify([{ type: "text", text: "Image read successfully" }, { type: "text", text: IMAGE_FOLLOWS }]) && readSteer.convId === readConv && readSteer.images === 1 && - readSteer.content.some(part => part.type === "image" && part.data === "cmVhZGltYWdl" && part.mimeType === "image/jpeg") && + readSteer.content.some(part => part.type === "image" && part.data === "/9j/4AAQSkZJRgABcmVhZGltYWdl" && part.mimeType === "image/jpeg") && !readSteer.text.includes("Image read successfully"), JSON.stringify({ readDelivered, steer: readSteer.content })) // Claude Code's Read of a PDF: the tool_result holds the file as a base64 @@ -2357,7 +2379,7 @@ for (const location of ["inline", "system", "developer", "user"]) { role: "user", content: [ { type: "text", text: "Hello token counter 中文" }, - { type: "image", source: { type: "base64", media_type: "image/png", data: "A".repeat(4000) } }, + { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgoAAAAN" + "A".repeat(3984) } }, ], }], }), @@ -2693,7 +2715,7 @@ for (const location of ["inline", "system", "developer", "user"]) { const resultBlock = imgSecond.messages.at(-1).content[0] imgSecond.messages.at(-1).content = [ { type: "text", text: "look at this" }, - { type: "image", source: { type: "base64", media_type: "image/png", data: "cmVwbGF5aW1hZ2U=" } }, + { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgoAAAANcmVwbGF5aW1hZ2U=" } }, resultBlock, ] const imgRes = await callFetch(imgSecond) @@ -2705,7 +2727,7 @@ for (const location of ["inline", "system", "developer", "user"]) { imgReplay.convId === imgOld && inits().length === imgBefore && imgReplay.text.includes("look at this") && !imgReplay.text.includes("MIXED_IMAGE_RESULT") && mcpResultText(imgOld).includes("MIXED_IMAGE_RESULT") && - imgReplay.content.some(part => part.type === "image" && part.data === "cmVwbGF5aW1hZ2U="), + imgReplay.content.some(part => part.type === "image" && part.data === "iVBORw0KGgoAAAANcmVwbGF5aW1hZ2U="), `status=${imgRes.status}`) } @@ -2718,7 +2740,7 @@ for (const location of ["inline", "system", "developer", "user"]) { const imgSecond = continuation(imgFirst, imgEvents, "ONLY_IMAGE_RESULT") const resultBlock = imgSecond.messages.at(-1).content[0] imgSecond.messages.at(-1).content = [ - { type: "image", source: { type: "base64", media_type: "image/png", data: "b25seWltYWdl" } }, + { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBORw0KGgoAAAANb25seWltYWdl" } }, resultBlock, ] const imgRes = await callFetch(imgSecond) @@ -2729,7 +2751,7 @@ for (const location of ["inline", "system", "developer", "user"]) { imgRes.status === 200 && stopOf(imgFinal) === "end_turn" && imgReplay.convId === imgOld && inits().length === imgBefore && !imgReplay.text.includes("ONLY_IMAGE_RESULT") && mcpResultText(imgOld).includes("ONLY_IMAGE_RESULT") && - imgReplay.content.some(part => part.type === "image" && part.data === "b25seWltYWdl"), + imgReplay.content.some(part => part.type === "image" && part.data === "iVBORw0KGgoAAAANb25seWltYWdl"), `status=${imgRes.status}`) } @@ -2871,12 +2893,12 @@ for (const location of ["inline", "system", "developer", "user"]) { { const first = { model, messages: [{ role: 'user', content: 'ESCCALL replay tool image regression' }], tools: [echoTool] } const events = (await readSSE(await callFetch(first))).events - const second = continuation(first, events, [{ type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'cmVwbGF5aW1hZ2U=' } }]) + const second = continuation(first, events, [{ type: 'image', source: { type: 'base64', media_type: 'image/png', data: 'iVBORw0KGgoAAAANcmVwbGF5aW1hZ2U=' } }]) second.messages.at(-1).content.push({ type: 'text', text: 'The user sent a new message while you were working:\nInspect that returned image' }) const response = await callFetch(second) if (response.status === 200) await readSSE(response) else await response.text() - check('fresh replay retains image bytes inside a tool_result', response.status === 200 && lastOf('user').content.some(part => part.type === 'image' && part.data === 'cmVwbGF5aW1hZ2U=')) + check('fresh replay retains image bytes inside a tool_result', response.status === 200 && lastOf('user').content.some(part => part.type === 'image' && part.data === 'iVBORw0KGgoAAAANcmVwbGF5aW1hZ2U=')) if (response.status !== 200) await drive(first, events, 'cleanup replay image') } @@ -3106,16 +3128,24 @@ for (const location of ["inline", "system", "developer", "user"]) { { // AGY_BRIDGE_MINIMAL_AGENT=1 drops agy's own prompt components, for a session started after it is set. + check("no ban-risk warning while AGY_BRIDGE_MINIMAL_AGENT is off", minimalWarnings.length === 0, minimalWarnings.join("")) const before = inits().length process.env.AGY_BRIDGE_MINIMAL_AGENT = "1" try { - const response = await callFetch({ model, messages: [{ role: "user", content: "minimal agent opt-in " + Date.now() }] }) - await readSSE(response) + // two sessions: the warning is still printed once (limengy88811922 on X) + for (const n of [1, 2]) { + const response = await callFetch({ model, messages: [{ role: "user", content: `minimal agent opt-in ${n} ` + Date.now() }] }) + await readSSE(response) + } } finally { delete process.env.AGY_BRIDGE_MINIMAL_AGENT } + const minimal = inits().slice(before).filter(event => event.agentConfig?.includes("excludeDefaultComponents: true")) const init = inits().slice(before).at(-1) check("AGY_BRIDGE_MINIMAL_AGENT=1 turns on the minimal agent", !!init && init.agentConfig.includes("excludeDefaultComponents: true"), init?.agentConfig) + check("AGY_BRIDGE_MINIMAL_AGENT=1 prints its ban-risk warning once for two sessions", minimal.length >= 2 && minimalWarnings.length === 1 + && /no longer look like the official agy client's/.test(minimalWarnings[0]) && /banned/.test(minimalWarnings[0]) && /Not recommended/.test(minimalWarnings[0]), + `${minimal.length} minimal sessions; ${minimalWarnings.join("")}`) } { @@ -3133,6 +3163,7 @@ else process.env.AGY_CLI_DISABLE_AUTO_UPDATE = originalAutoUpdate try { fs.rmSync(here, { recursive: true, force: true }) } catch {} try { fs.rmSync(stateDir, { recursive: true, force: true }) } catch {} +try { fs.rmSync(project, { recursive: true, force: true }) } catch {} console.log(failures === 0 ? `\nALL OK (${checks} checks)` : `\n${failures} FAILURES (${checks} checks)`) process.exit(failures === 0 ? 0 : 1) diff --git a/test/spilled-output.mjs b/test/spilled-output.mjs new file mode 100644 index 0000000..253932c --- /dev/null +++ b/test/spilled-output.mjs @@ -0,0 +1,97 @@ +import { test } from "node:test" +import assert from "node:assert/strict" +import fs from "node:fs" +import path from "node:path" +import { baseBody, createBridgeKit, readSse } from "./testkit.mjs" + +// agy cut a tool result short and saved the whole of it in its own folder, +// where the client (on another machine than magpie in Docker, Dani Ariyanto +// on Discord) can't read it: the bridge answers that read itself. +function spill(agyDir, text, session = "s1", step = "4") { + const file = path.join(agyDir, "brain", session, ".system_generated", "steps", step, "output.txt") + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.writeFileSync(file, text) + return file +} + +async function readThrough(kit, args) { + let reply + kit.prompts.push(async (agent) => { + const [proc] = [...kit.module.__agyTestAllProcs] + reply = await agent.tool("Read", args(proc.agyDir)) + if (reply?.result) await agent.text("read it") + }) + const result = await readSse(await kit.request(baseBody())) + return { reply, result } +} + +test("a read of agy's own saved output is answered by the bridge, never sent to the client", async () => { + const kit = await createBridgeKit() + try { + const { reply, result } = await readThrough(kit, (dir) => ({ path: spill(dir, "alpha\nbeta\ngamma\n") })) + assert.equal(reply.result.isError, false) + assert.equal(reply.result.content[0].text, " 1\talpha\n 2\tbeta\n 3\tgamma") + assert.equal(result.content.find((item) => item.type === "tool_use"), undefined) + assert.equal(result.content.find((item) => item.type === "text")?.text, "read it") + } finally { + await kit.dispose() + } +}) + +test("offset and limit pick the lines of a saved output", async () => { + const kit = await createBridgeKit() + try { + const lines = Array.from({ length: 10 }, (_, i) => `line ${i + 1}`).join("\n") + const { reply } = await readThrough(kit, (dir) => ({ file_path: spill(dir, lines), offset: 4, limit: 2 })) + assert.equal(reply.result.content[0].text, " 4\tline 4\n 5\tline 5") + } finally { + await kit.dispose() + } +}) + +test("any other file, or a link out of agy's folder, still goes to the client", async () => { + for (const place of ["outside", "link", "not a step"]) { + const kit = await createBridgeKit() + try { + const { reply, result } = await readThrough(kit, (dir) => { + if (place === "outside") return { path: spill(path.join(kit.tmp, "elsewhere"), "x") } + if (place === "not a step") { + const file = path.join(dir, "brain", "s1", "notes.txt") + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.writeFileSync(file, "x") + return { path: file } + } + const target = path.join(kit.tmp, "secret.txt") + fs.writeFileSync(target, "secret") + const file = path.join(dir, "brain", "s1", ".system_generated", "steps", "4", "output.txt") + fs.mkdirSync(path.dirname(file), { recursive: true }) + fs.symlinkSync(target, file) + return { path: file } + }) + assert.equal(reply, undefined, `${place}: answered by the bridge`) + const call = result.content.find((item) => item.type === "tool_use") + assert.ok(call, `${place}: not sent to the client`) + assert.equal(call.name, "Read") + } finally { + await kit.dispose() + } + } +}) + +test("a tool that isn't a read is never answered from the saved output", async () => { + const kit = await createBridgeKit() + try { + const { result } = await (async () => { + let reply + kit.prompts.push(async (agent) => { + const [proc] = [...kit.module.__agyTestAllProcs] + reply = await agent.tool("Bash", { command: spill(proc.agyDir, "x") }) + }) + const body = baseBody({ tools: [{ name: "Bash", input_schema: { type: "object", properties: { command: { type: "string" } }, required: ["command"] } }] }) + return { reply, result: await readSse(await kit.request(body)) } + })() + assert.equal(result.content.find((item) => item.type === "tool_use")?.name, "Bash") + } finally { + await kit.dispose() + } +}) diff --git a/test/tool-result-prefill.mjs b/test/tool-result-prefill.mjs new file mode 100644 index 0000000..554dce5 --- /dev/null +++ b/test/tool-result-prefill.mjs @@ -0,0 +1,87 @@ +// plugins#1512 (deimos6677): a reply cut after a tool round (agy silent +// past TURN_TIMEOUT_MS, a stream that broke) is asked again by magpie, +// going on from what it had said: the round's tool_result, then the +// reply's text as an assistant prefill. The bridge refused that shape +// with a 400 no client retries, and the agent's turn ended there. + +import { test } from "node:test" +import assert from "node:assert/strict" +import { baseBody, continueWithToolResults, createBridgeKit, readSse } from "./testkit.mjs" + +function promptText(entry) { + return (entry?.params?.prompt || []).map((part) => (part.type === "text" ? part.text : "")).join("") +} + +function captureStderr() { + const lines = [] + const original = process.stderr.write + process.stderr.write = function write(chunk, ...rest) { + const text = String(chunk) + if (text.startsWith("[agy-bridge] ")) { + lines.push(JSON.parse(text.slice("[agy-bridge] ".length))) + return true + } + return original.call(this, chunk, ...rest) + } + return { lines, restore: () => { process.stderr.write = original } } +} + +function script(kit) { + kit.defaultPrompt = async (agent) => { + const text = (agent.prompt || []).map((part) => (part.type === "text" ? part.text : "")).join("") + if (text.includes("FILE BODY")) { + await agent.text(" and it says hello.") + return { stopReason: "end_turn" } + } + await agent.tool("Read", { path: "/repo/a.txt" }) + await agent.text("after tool") + return { stopReason: "end_turn" } + } +} + +const READ_ROUND = [ + { role: "user", content: "read a.txt" }, + { role: "assistant", content: [{ type: "text", text: "Reading it." }, { type: "tool_use", id: "toolu_cut1", name: "Read", input: { path: "/repo/a.txt" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_cut1", content: "FILE BODY: hello" }] }, + { role: "assistant", content: "I read the file" }, +] + +test("a tool round whose session is gone, then a prefill tail, is replayed and goes on from the prefill", async () => { + const kit = await createBridgeKit({}) + try { + script(kit) + const response = await kit.request(baseBody({ messages: READ_ROUND })) + assert.equal(response.status, 200, await response.clone().text()) + const result = await readSse(response) + assert.ok(!result.error, JSON.stringify(result.error)) + assert.match(result.content.find((block) => block.type === "text")?.text ?? "", /it says hello/) + const sent = promptText(kit.acpLog.filter((entry) => entry.method === "session/prompt").at(-1)) + assert.match(sent, /FILE BODY: hello/) + assert.match(sent, /I read the file/) + } finally { + await kit.dispose() + } +}) + +test("a live tool round answered with a prefill tail drops the live session and replays it", async () => { + const kit = await createBridgeKit({}) + const err = captureStderr() + try { + script(kit) + const body = baseBody({ messages: [{ role: "user", content: "read a.txt" }] }) + const first = await readSse(await kit.request(body)) + assert.equal(first.stopReason, "tool_use") + const next = continueWithToolResults(body, first, () => "FILE BODY: hello") + next.messages.push({ role: "assistant", content: "I read the file" }) + const response = await kit.request(next) + assert.equal(response.status, 200, await response.clone().text()) + const result = await readSse(response) + assert.ok(!result.error, JSON.stringify(result.error)) + assert.match(result.content.find((block) => block.type === "text")?.text ?? "", /it says hello/) + assert.ok(err.lines.some((line) => line.event === "agy_bridge_tool_state" && line.action === "drop_live" && line.reason === "prefill"), + JSON.stringify(err.lines.map((line) => [line.event, line.action, line.reason]))) + } finally { + err.restore() + await kit.dispose() + } +}) diff --git a/test/tool-step-retry.mjs b/test/tool-step-retry.mjs new file mode 100644 index 0000000..f28417f --- /dev/null +++ b/test/tool-step-retry.mjs @@ -0,0 +1,187 @@ +// Identical tool_result retry after the bridge already emitted the next +// tool_use step (e.g. response lost in flight and client timed out at 300s): +// replay the emitted tool_use step instead of dropping the live session on +// history_mismatch (expected_history = history + 2, first_diff = missing_actual). + +import { test } from "node:test" +import assert from "node:assert/strict" +import { baseBody, continueWithToolResults, createBridgeKit, readSse } from "./testkit.mjs" + +function captureStderr() { + const lines = [] + const original = process.stderr.write + process.stderr.write = function write(chunk, ...rest) { + const text = String(chunk) + if (text.startsWith("[agy-bridge] ")) { + lines.push(JSON.parse(text.slice("[agy-bridge] ".length))) + return true + } + return original.call(this, chunk, ...rest) + } + return { lines, restore: () => { process.stderr.write = original } } +} + +function messageIdOf(parsed) { + return parsed.events.find((entry) => entry.event === "message_start")?.data?.message?.id +} + +function toolText(res) { + return (res?.result?.content || res?.content || []).map((part) => (part.type === "text" ? part.text : "")).join("") +} + +function twoStepScript(kit) { + kit.defaultPrompt = async (agent) => { + const first = await agent.tool("Read", { path: "/repo/a.txt" }) + const second = await agent.tool("Read", { path: "/repo/b.txt" }) + await agent.text(`done:${toolText(first)}:${toolText(second)}`) + return { stopReason: "end_turn" } + } +} + +test("identical tool_result retry replays the emitted next tool_use step without dropping the live session", async () => { + const kit = await createBridgeKit({}) + const err = captureStderr() + try { + twoStepScript(kit) + const opening = baseBody({ messages: [{ role: "user", content: "read a and b" }] }) + const step1 = await readSse(await kit.request(opening)) + assert.equal(step1.stopReason, "tool_use") + + const req1 = continueWithToolResults(opening, step1, () => "AAA") + const step2 = await readSse(await kit.request(req1)) + assert.equal(step2.stopReason, "tool_use") + const call2 = step2.content.find((block) => block.type === "tool_use") + assert.ok(call2) + + // Client never received step2 (e.g. timed out after 300s) and resends req1 identically. + const retryRes = await kit.request(structuredClone(req1)) + assert.equal(retryRes.status, 200, await retryRes.clone().text()) + const replayed = await readSse(retryRes) + assert.equal(replayed.stopReason, "tool_use") + assert.deepEqual(replayed.content, step2.content) + assert.equal(messageIdOf(replayed), messageIdOf(step2)) + + assert.ok( + err.lines.some((line) => line.event === "agy_bridge_tool_state" && line.action === "replay_tool_step" && line.reason === "idempotent_retry"), + JSON.stringify(err.lines.map((line) => [line.event, line.action, line.reason])), + ) + assert.ok( + !err.lines.some((line) => line.action === "drop_live"), + JSON.stringify(err.lines.filter((line) => line.action === "drop_live")), + ) + assert.equal(kit.acpLog.filter((entry) => entry.method === "session/new").length, 1) + + // Answering the replayed call finishes on the same live session. + const req2 = continueWithToolResults(req1, replayed, () => "BBB") + const done = await readSse(await kit.request(req2)) + assert.equal(done.stopReason, "end_turn") + assert.match(done.content.find((block) => block.type === "text")?.text ?? "", /done:AAA:BBB/) + assert.equal(kit.acpLog.filter((entry) => entry.method === "session/new").length, 1) + } finally { + err.restore() + await kit.dispose() + } +}) + +test("identical retry with companion text spliced by inspectToolTurn replays instead of 409", async () => { + const kit = await createBridgeKit({}) + try { + twoStepScript(kit) + const opening = baseBody({ messages: [{ role: "user", content: "read a and b" }] }) + const step1 = await readSse(await kit.request(opening)) + assert.equal(step1.stopReason, "tool_use") + + const req1 = continueWithToolResults(opening, step1, () => "AAA") + req1.messages.at(-1).content.push({ type: "text", text: "keep going" }) + const step2 = await readSse(await kit.request(req1)) + assert.equal(step2.stopReason, "tool_use") + + const retryRes = await kit.request(structuredClone(req1)) + assert.equal(retryRes.status, 200, await retryRes.clone().text()) + const replayed = await readSse(retryRes) + assert.deepEqual(replayed.content, step2.content) + } finally { + await kit.dispose() + } +}) + +test("non-streaming identical retry returns the replayed JSON response", async () => { + const kit = await createBridgeKit({}) + try { + twoStepScript(kit) + const opening = baseBody({ messages: [{ role: "user", content: "read a and b" }] }) + const step1 = await readSse(await kit.request(opening)) + const req1 = continueWithToolResults(opening, step1, () => "AAA") + const step2 = await readSse(await kit.request(req1)) + + const retryReq = structuredClone(req1) + retryReq.stream = false + const retryRes = await kit.request(retryReq) + assert.equal(retryRes.status, 200, await retryRes.clone().text()) + const json = await retryRes.json() + assert.equal(json.id, messageIdOf(step2)) + assert.equal(json.stop_reason, "tool_use") + assert.deepEqual(json.content, step2.content) + } finally { + await kit.dispose() + } +}) + +test("changed request or prefill tail does not replay the cached step", async () => { + const kit = await createBridgeKit({}) + const err = captureStderr() + try { + twoStepScript(kit) + const opening = baseBody({ messages: [{ role: "user", content: "read a and b" }] }) + const step1 = await readSse(await kit.request(opening)) + const req1 = continueWithToolResults(opening, step1, () => "AAA") + const step2 = await readSse(await kit.request(req1)) + assert.equal(step2.stopReason, "tool_use") + + // Conflicting duplicate tool_result still returns 409. + const conflict = structuredClone(req1) + conflict.messages.at(-1).content[0].content = "CHANGED" + const conflictRes = await kit.request(conflict) + assert.equal(conflictRes.status, 409) + + // Changing the tool catalog invalidates the digest and drops the live session. + const grown = structuredClone(req1) + grown.tools = [...grown.tools, { name: "Write", description: "write", input_schema: { type: "object", properties: {} } }] + const grownRes = await kit.request(grown) + assert.equal(grownRes.status, 200, await grownRes.clone().text()) + await readSse(grownRes) + assert.ok( + err.lines.some((line) => line.event === "agy_bridge_tool_state" && line.action === "drop_live" && line.reason === "history_mismatch"), + JSON.stringify(err.lines.map((line) => [line.event, line.action, line.reason])), + ) + } finally { + err.restore() + await kit.dispose() + } +}) + +test("prefill tail after tool_result keeps 0.1.120 drop_live/prefill behavior", async () => { + const kit = await createBridgeKit({}) + const err = captureStderr() + try { + twoStepScript(kit) + const opening = baseBody({ messages: [{ role: "user", content: "read a and b" }] }) + const step1 = await readSse(await kit.request(opening)) + const req1 = continueWithToolResults(opening, step1, () => "AAA") + const step2 = await readSse(await kit.request(req1)) + assert.equal(step2.stopReason, "tool_use") + + const prefill = structuredClone(req1) + prefill.messages.push({ role: "assistant", content: "partial reply" }) + const prefillRes = await kit.request(prefill) + assert.equal(prefillRes.status, 200, await prefillRes.clone().text()) + await readSse(prefillRes) + assert.ok( + err.lines.some((line) => line.event === "agy_bridge_tool_state" && line.action === "drop_live" && line.reason === "prefill"), + JSON.stringify(err.lines.map((line) => [line.event, line.action, line.reason])), + ) + } finally { + err.restore() + await kit.dispose() + } +}) diff --git a/test/tool-summary.mjs b/test/tool-summary.mjs index 503cd72..e95d172 100644 --- a/test/tool-summary.mjs +++ b/test/tool-summary.mjs @@ -2,22 +2,25 @@ import { test } from "node:test" import assert from "node:assert/strict" import { baseBody, createBridgeKit, readSse } from "./testkit.mjs" -async function callRunCommand(inputSchema, args) { +async function callTool(name, inputSchema, args) { const kit = await createBridgeKit() try { let listed kit.prompts.push(async (agent) => { listed = await agent.listTools() - await agent.tool("run_command", args) + await agent.tool(name, args) }) - const body = baseBody({ tools: [{ name: "run_command", input_schema: inputSchema }] }) + const body = baseBody({ tools: [{ name, input_schema: inputSchema }] }) const result = await readSse(await kit.request(body)) - return { schema: listed.result.tools[0].inputSchema, call: result.content.find((item) => item.type === "tool_use") } + const tool = listed.result.tools.find((item) => item.name === name) + return { schema: tool.inputSchema, call: result.content.find((item) => item.type === "tool_use") } } finally { await kit.dispose() } } +const callRunCommand = (inputSchema, args) => callTool("run_command", inputSchema, args) + test("run_command avoids agy's toolSummary collision and restores the argument for the client", async () => { const schema = { type: "object", @@ -44,3 +47,47 @@ test("run_command keeps supplied summaries and does not add one to unrelated sch }, { command: "pwd" }) assert.deepEqual(withoutSummary.call.input, { command: "pwd" }) }) + +// #visamzh on X (0.1.120): an MCP tool the outer agy forwards already lists +// toolSummary as required, so agy's own toolSummary duplicated it and the +// toolbox failed to build with "'allOf' failed • at '/required': items at 0 +// and 1 are equal". The collision guard must cover every tool, not run_command. +test("an MCP tool with an injected toolSummary does not duplicate agy's own", async () => { + const name = "mcp_ide-tools_mcp_magpie-artifacts_publish_artifact" + const schema = { + type: "object", + properties: { + id: { type: "string" }, + type: { type: "string" }, + title: { type: "string" }, + content: { type: "string" }, + // The original publish_artifact schema has no toolSummary; the terminal + // agy adds this property and the required entry before forwarding it. + toolSummary: { type: "string" }, + }, + required: ["id", "type", "title", "content", "toolSummary"], + additionalProperties: false, + } + const result = await callTool(name, schema, { + id: "a1", type: "markdown", title: "Hello", content: "# Hi", + }) + // toolSummary is stripped from required, so agy adds exactly one and the + // schema stays valid (no "items 0 and 1 are equal"). + assert.deepEqual(result.schema.required, ["id", "type", "title", "content"]) + assert.ok(!result.schema.required.includes("toolSummary")) + // On the return path the client's required field is filled back in. + assert.deepEqual(result.call.input, { + id: "a1", type: "markdown", title: "Hello", content: "# Hi", toolSummary: name, + }) +}) + +test("an MCP tool keeps a summary the model supplied", async () => { + const name = "mcp_magpie-artifacts_publish_artifact" + const schema = { + type: "object", + properties: { id: { type: "string" }, toolSummary: { type: "string" } }, + required: ["id", "toolSummary"], + } + const supplied = await callTool(name, schema, { id: "a2", toolSummary: "Publish the doc" }) + assert.equal(supplied.call.input.toolSummary, "Publish the doc") +}) diff --git a/test/usage.mjs b/test/usage.mjs index 9172fc0..63fe8be 100644 --- a/test/usage.mjs +++ b/test/usage.mjs @@ -642,7 +642,9 @@ test("only concurrent refreshes share work, and callers cannot mutate each other results[0].windows[0].used = 99 assert.equal(results[1].windows[0].used, 25) await read() - assert.equal((await f.logs()).length, 4) + // the next refresh reads quota again; agy's --version answer is kept for + // its binary (plugins#1544) + assert.deepEqual((await f.logs()).map((call) => call.args[0]), ["--version", "-p", "-p"]) await f.assertClean() }) @@ -892,6 +894,19 @@ test("invalid and oversized stdout/stderr reports fail within the output budget" } }) +// plugins#1544: agy --version took 5 to 17 seconds on a one-CPU Linux host, +// and the quota read was given up at 3 seconds, before it could start. +test("a slow agy --version can finish within the usage deadline, and is asked once", async t => { + const f = await fixture(t, { TEST_START_DELAY_MS: "4000" }) + const result = await fetchUsage(f.executable, { ...f.options, first: true, quota: async () => SUMMARY }) + assert.equal(result.windows.length, 2) + assert.deepEqual((await f.logs()).map(call => call.args), [["--version"]]) + const again = await fetchUsage(f.executable, { ...f.options, first: true, quota: async () => SUMMARY }) + assert.equal(again.windows.length, 2) + assert.deepEqual((await f.logs()).map(call => call.args), [["--version"]], "the same binary isn't asked its version again") + await f.assertClean() +}) + test("version/report hangs time out, terminate the process, and leave no workspace", async t => { for (const mode of ["version-hang", "hang"]) { const f = await fixture(t, { TEST_MODE: mode }) @@ -1127,6 +1142,28 @@ test("a stored sign-in with time left is read directly first, so a slow agy -p d await f.assertClean() }) +// plugins#1522: a direct read that can't connect hung until the deadline, +// and agy -p, run after it with a second left, timed the card out. +test("a direct read that hangs leaves agy -p the time it needs", async t => { + const f = await fixture(t) + const deadlines = [] + const quota = async o => { + deadlines.push(o.deadline - Date.now()) + await new Promise(r => setTimeout(r, Math.max(0, o.deadline - Date.now()))) + throw new Error("The operation timed out.") + } + const stored = { state: "present", fp: "live", canRenew: true, expiresAt: Date.now() + 10 * 60_000, expired: false } + const read = createUsageReader(() => f.executable, { ...f.options, timeoutMs: 9000, quota, signIn: async () => stored }) + const result = await read() + assert.equal(result.error, undefined) + assert.equal(result.windows.length, 1) + assert.equal(deadlines.length, 1) + assert.ok(deadlines[0] <= 5000, `the direct read had ${deadlines[0]}ms`) + const p = (await f.logs()).find(l => l.args[0] === "-p") + assert.ok(Number(p.args.at(-1).replace(/s$/, "")) >= 3, `agy -p had ${p.args.at(-1)}`) + await f.assertClean() +}) + test("a direct read that can't answer goes through agy -p, and agy's answer stands", async t => { const f = await fixture(t) let asked = 0 diff --git a/usage.mjs b/usage.mjs index 317b078..45bc7f6 100644 --- a/usage.mjs +++ b/usage.mjs @@ -9,6 +9,9 @@ import { cannotSignIn, isDead, noteDead, storedSignIn, storedToken } from "./sig const DEFAULT_TIMEOUT_MS = 15_000 const MAX_TIMEOUT_MS = 18_000 // Magpie bounds an auth.usage call to 20 seconds. const MAX_OUTPUT_BYTES = 1024 * 1024 +// The direct read made before agy -p (fetchUsage's first) takes about 1.5 +// seconds; agy -p, 5 to 10. The first gets this long, agy -p the rest. +const FIRST_READ_MS = 5_000 // kind: "auth" (agy says it needs a sign-in), "timeout" (output: what agy // had printed by then, never shown), "cancel", or none. @@ -260,6 +263,20 @@ function timeout(value) { return Number.isFinite(n) && n > 0 ? Math.min(n, MAX_TIMEOUT_MS) : DEFAULT_TIMEOUT_MS } +// What agy --version said, by the binary that said it: its real path, size +// and modification time, so an updated agy is asked again. +const versionCache = new Map() + +async function binaryKey(file) { + try { + const real = await fs.realpath(file) + const st = await fs.stat(real) + return `${real}\0${st.size}\0${st.mtimeMs}` + } catch { + return "" + } +} + function run(file, args, { cwd, env, deadline, signal, maxOutputBytes, onTreeKill }) { return new Promise((resolve, reject) => { let child @@ -525,13 +542,21 @@ export async function fetchUsage(agy, { BROWSER: path.join(directory, process.platform === "win32" ? "open.cmd" : "open"), }) const options = { cwd: directory, env: childEnv, deadline, signal, maxOutputBytes, onTreeKill: p => { pendingTreeKill = p } } - // --version needs no sign-in, so its hang is never read as one - const version = await run(agy, ["--version"], { ...options, deadline: Math.min(deadline, Date.now() + 3000) }).catch((error) => { - if (error?.kind === "timeout") throw new UsageError(error.message) - throw error - }) - if (version.code !== 0) throw commandFailure(version.stderr) - if (!supportedVersion(version.stdout)) throw new UsageError("agy usage reports require a verified agy version 1.1.11 or later. Update the CLI.") + // --version needs no sign-in, so its hang is never read as one. It gets + // the whole deadline, and its answer is kept for the binary it came from: + // a 266 MB agy on a one-CPU Linux host takes 5 to 17 seconds just to say + // its version (plugins#1544), which left no time for the quota read. + const binary = await binaryKey(agy) + let version = binary && versionCache.get(binary) + if (!version) { + version = await run(agy, ["--version"], options).catch((error) => { + if (error?.kind === "timeout") throw new UsageError(error.message) + throw error + }) + if (version.code !== 0) throw commandFailure(version.stderr) + if (!supportedVersion(version.stdout)) throw new UsageError("agy usage reports require a verified agy version 1.1.11 or later. Update the CLI.") + if (binary) versionCache.set(binary, { code: 0, stdout: version.stdout, stderr: "" }) + } // agy's access token has ended (or is about to): agy renews it when it // runs, and when that renewal fails, even for a moment (DNS at startup, // a slow keyring), agy starts its own Google sign-in, which on Windows @@ -561,10 +586,15 @@ export async function fetchUsage(agy, { // seconds. When they can't answer (a sign-in that can't be read, a // refusal, a reply with no quota), agy -p is asked as before, in the // time left, and its answer (a refusal, a sign-in agy asks for) stands. + // + // It gets FIRST_READ_MS of the deadline, not all of it: a read that + // can't connect (a proxy down, a network that drops Google) hung until + // the deadline and left agy -p a second, so the card said "timed out" + // when agy -p alone would have answered (plugins#1522). let firstFailed = "" if (first) { try { - const data = await quota({ env, version: version.stdout.trim(), deadline, signal }) + const data = await quota({ env, version: version.stdout.trim(), deadline: Math.min(deadline, Date.now() + FIRST_READ_MS), signal }) return parseUsageReport({ status: "SUCCESS", command: { name: "usage", data } }) } catch (error) { if (signal?.aborted) throw new UsageError("agy usage query was cancelled.", { kind: "cancel" })