diff --git a/README.en.md b/README.en.md index 80f1cdf..7202bde 100644 --- a/README.en.md +++ b/README.en.md @@ -101,7 +101,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 @@ -282,6 +283,7 @@ account", which keeps its sign-in in a file. | `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_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 | diff --git a/README.md b/README.md index a51accd..8a63594 100644 --- a/README.md +++ b/README.md @@ -199,6 +199,7 @@ macOS 上,以 LaunchDaemon 方式运行的 Magpie 不在你的登录会话里 | `AGY_BRIDGE_EFFORT` | 未设置 | 强制思考等级:`minimal` / `low` / `medium` / `high` / `xhigh` / `max` | | `AGY_BRIDGE_MINIMAL_AGENT` | 关闭 | 设为 `1` 去掉 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` 关闭 | diff --git a/agy-cli.test.mjs b/agy-cli.test.mjs index b1bb08d..5edade3 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], @@ -36,6 +37,9 @@ for (const [name, mocks] of [ ["tools-listed.mjs", false], ["concurrent-convs.mjs", false], ["masking-drift.mjs", false], + ["spilled-output.mjs", false], + ["tool-result-prefill.mjs", false], + ["image-bytes.mjs", false], ]) { test(`test/${name}`, () => { // bun's 5s default per test is a fixed wait these process-spawning tests @@ -53,6 +57,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..cb96839 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" @@ -1324,7 +1324,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 } @@ -2480,7 +2483,18 @@ class Proc { "--log-file", this.logPath, "--ide-mcp-port", String(controlServer.address().port), ] - if (this.workDir) args.push("--add-dir", this.workDir) + // 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) if (videoOn()) { await fs.promises.mkdir(mediaDir(), { recursive: true, mode: 0o700 }) args.push("--add-dir", mediaDir()) @@ -2491,6 +2505,10 @@ class Proc { 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") @@ -3182,10 +3200,20 @@ 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}`) + 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. if (name === "run_command" && tool.inputSchema?.properties?.toolSummary && !Object.hasOwn(args, "toolSummary")) { args = { ...args, toolSummary: "Run command" } } + // 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 && call.name === name && stableJSON(call.arguments) === signature) @@ -4549,6 +4577,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() @@ -5478,8 +5525,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 +5566,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}$/ @@ -5685,7 +5769,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 +5786,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) { @@ -5912,7 +6001,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 @@ -6648,9 +6771,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 +6833,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") }) @@ -8238,11 +8362,14 @@ export const AntigravityBridgePlugin = async () => { const selection = { model: requestedModel, effort: requestedEffort(body) } const sessionScope = requestSessionScope(fetchInput, init) // 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) @@ -8308,7 +8435,7 @@ export const AntigravityBridgePlugin = async () => { 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,7 +8448,7 @@ 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. @@ -8333,7 +8460,7 @@ export const AntigravityBridgePlugin = async () => { // 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 +8469,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" diff --git a/package.json b/package.json index cdc8ce0..8387b6f 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.120", "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/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/compat.mjs b/test/compat.mjs index 79bd318..661849d 100644 --- a/test/compat.mjs +++ b/test/compat.mjs @@ -20,7 +20,7 @@ fs.writeFileSync(path.join(workspace, "bridge.mjs"), source + "\nexport { inspec const { inspectToolTurn, matchToolResults, historyKey, allProcs, toolCalls, renderInitialPromptParts, 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 }, 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/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/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/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..16bfe63 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -1092,14 +1092,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 +2179,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 +2199,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 +2210,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 +2220,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 +2362,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 +2698,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 +2710,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 +2723,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 +2734,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 +2876,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') } @@ -3133,6 +3138,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/usage.mjs b/test/usage.mjs index 9172fc0..453236c 100644 --- a/test/usage.mjs +++ b/test/usage.mjs @@ -1127,6 +1127,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..a41d520 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. @@ -561,10 +564,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" })