From d933d70cf279d50fa6ff2769da8e06310fc98941 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:15:10 +0000 Subject: [PATCH 1/4] upstream agy-cli 0.1.157 (magpie-community/plugins@25b0979cdf9367c27a60be0aab3b2fe48e2f4458) --- README.en.md | 14 ++- README.md | 8 +- agy-cli.test.mjs | 1 + index.mjs | 246 +++++++++++++++++++++++++++++++------- package.json | 2 +- test/conversation-key.mjs | 12 ++ test/media-input.mjs | 236 ++++++++++++++++++++++++++++++++++++ test/repeat-batch.mjs | 77 ++++++++++++ test/smoke.mjs | 4 +- test/tool-schema.mjs | 177 ++++++++++++++++++++++++++- 10 files changed, 727 insertions(+), 50 deletions(-) create mode 100644 test/media-input.mjs diff --git a/README.en.md b/README.en.md index 7f6c7dd..9c82180 100644 --- a/README.en.md +++ b/README.en.md @@ -102,6 +102,14 @@ MCP server. The control port listens on loopback only, with a token per process. newer, because the ACP server has to advertise image support. An image a tool returns (a screenshot from `read`) goes to agy as a prompt image too: over MCP, agy would save it to a file the model can't open. +- **Video and audio input** (Gemini models): inline base64. agy's ACP prompt + carries neither, so each is written to `attachments/.` in the + session's folder and the model is asked to read it with agy's own + `view_file`, which hands Gemini the frames and the sound. Only a + conversation that carries one gets `view_file`; agy's tools stay off + otherwise. A video or audio URL, or one sent to a model other than Gemini, + gets HTTP 400. `count_tokens` counts a video or audio clip as one image, so + a long clip is undercounted. - **Tool calls**: parallel and consecutive calls both work. A tool that runs past 150 seconds first gets a "still running" placeholder; once the real result arrives, the same turn continues, and the client executes each call exactly once. @@ -413,7 +421,11 @@ since 11-14 Google's check reads past them. Reworded in the first user turn (the default), Claude Code's prompt is answered; in agy's session instructions (`AGY_BRIDGE_SYSTEM_APPEND=1`) it is still turned away. So a bare 429 there is reported as a 400 about the prompt, and in the user turn -as a rate limit the client can retry or another account can take. +as a rate limit the client can retry or another account can take. Either +way it ends the turn on the first try that got it: since agy 1.5.13 retries +it silently for minutes (eight tries over about two and a half), writing it +only to its log, so the plugin reads that log while the prompt runs instead +of waiting for agy to give up. DeepSeek Harness's paragraph on `@` paths ("Tokens prefixed with @ are paths…") goes reworded with the same meaning, as the Antigravity provider diff --git a/README.md b/README.md index cf07be1..2dce926 100644 --- a/README.md +++ b/README.md @@ -69,6 +69,11 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy - **图片输入**:支持内联 base64 的 PNG、JPEG、GIF、WebP。需要 agy 1.5.0 或更新版本, 因为图片能力要由 ACP 服务端声明。工具返回的图片(如 `read` 读到的截图)也作为提示里的 图片交给 agy:走 MCP 的话,agy 会把它存成文件,模型看不到。 +- **视频与音频输入**(Gemini 型号):支持内联 base64。agy 的 ACP 提示带不了这两种,所以 + 每个都写到会话目录的 `attachments/.<扩展名>`,再请模型用 agy 自己的 `view_file` + 读取,Gemini 由此拿到画面和声音。只有带着视频或音频的对话才有 `view_file`,其余时候 + agy 的工具都关着。视频或音频给的是 URL,或发给 Gemini 以外的模型时,返回 HTTP 400。 + `count_tokens` 把一段视频或音频按一张图片计数,长片段会少算。 - **工具调用**:支持并行和连续调用。运行超过 150 秒的工具会先收到 "still running" 的 占位响应,真正的结果送达后继续同一轮对话,每个调用只在客户端执行一次。 - **会话续接**:每轮结束后记录会话,工具循环进行中的每一步也记录。重启 Magpie 或插件后, @@ -287,7 +292,8 @@ Antigravity 对几行系统提示词(Claude Code 的计费行、Claude Agent S 和 pi 的身份句、oh-my-pi 的 RFC 2119 行)不论余量多少都回 429 "Resource has been exhausted"。插件在 agy 发出之前去掉计费那一行,其余几行换成同义的说法("built on the Claude Agent SDK by Anthropic"、"built on GPT-5"、"RFC 2119 key words: …"、"You're Hermes Agent / OpenCode / a coding agent running in the Codex CLI"、"running within pi"),和 Antigravity 提供商的做法一样(`cloak.mjs`)。Codex 的两句 GPT-5 行("You are Codex, a coding agent based on GPT-5"、"You are Codex, an agent based on GPT-5")出现在用户的轮次里(AGENTS.md、``)也会被拒,所以用户轮次里也换成 "built on GPT-5"。零宽空格已经没用:11-14 起 Google 的检查会忽略它们。改写后放在第一条用户消息里(默认做法),Claude Code 的提示词能正常回答;放在 agy 的会话指令里(`AGY_BRIDGE_SYSTEM_APPEND=1`)仍然被拒。所以后者回的 429 报成针对 -提示词的 400,前者报成限流,客户端可以重试,或交给别的账号。 +提示词的 400,前者报成限流,客户端可以重试,或交给别的账号。两种情况都在第一次被拒时就结束本轮:agy 1.5.13 +起会静默重试几分钟(约两分半内 8 次),只写在它的日志里,所以插件在提示词运行期间读这份日志,不再等 agy 放弃。 DeepSeek Harness 的 `@` 路径说明段("Tokens prefixed with @ are paths…")也和 Antigravity 提供商一样 换成同义的说法再发:原文照发时 `gemini-4-argon` 大多很快答完、不思考、只走一步(#1028)。 diff --git a/agy-cli.test.mjs b/agy-cli.test.mjs index 65b9607..d90b443 100644 --- a/agy-cli.test.mjs +++ b/agy-cli.test.mjs @@ -55,6 +55,7 @@ for (const [name, mocks] of [ ["park-reread.mjs", false], ["same-opening.mjs", false], ["claude-code-sessions.mjs", false], + ["media-input.mjs", false], ]) { test(`test/${name}`, () => { // bun's 5s default per test is a fixed wait these process-spawning tests diff --git a/index.mjs b/index.mjs index 96bbab7..459ff62 100644 --- a/index.mjs +++ b/index.mjs @@ -184,7 +184,9 @@ const ATTEMPT_LINE = /^⚠ API error \(attempt \d+\): ?(.*)$/ // quota is left. agy 1.5.9 retries it in the same turn with a banner each // time, and only ends the turn after its last retry: to the client the turn // hung (Lmohn39 on X, pi through agy-cli, 11-14). A banner with it ends the -// turn at once, as the 429 ending would. +// turn at once, as the 429 ending would. agy 1.5.13 and later retry it +// silently, saying so only in their log, and the log's line ends it +// (#watchRetries). const refused429 = (detail) => /code 429\b/i.test(detail) && /resource has been exhausted/i.test(detail) // agy writes this into the reply when the model's first call came back with // neither text nor tool calls, then calls the model again in the same turn. @@ -1887,14 +1889,19 @@ export function ideToolOf(toolCall) { return "" } -function agentDefinition() { +// media: the conversation carries a video or audio (stageMedia), which the +// model reads with agy's own view_file. Otherwise agy's tools stay off. +// view_file reads unasked what is under an --add-dir folder and agy's temp +// folder (anywhere else it asks, and the bridge denies): so a media session +// gets no --add-dir, and agy's temp folder is the session's workspace (#spawn). +function agentDefinition(media) { const lines = [ "---", `name: ${AGENT_NAME}`, "description: Bridges only client-declared tools", "mainAgent: true", "subagent: false", - "tools: []", + media ? "tools: [view_file]" : "tools: []", // Never expose the user's global MCP servers, skills or plugins. "inheritMcp: false", "inheritCustomizations: false", @@ -2563,6 +2570,7 @@ class Proc { this.home = currentHome() this.#assign(convKey, opts) this.workDir = opts.workDir + this.media = !!opts.media this.spareKey = null this.token = randomUUID() this.sessionId = null @@ -2689,7 +2697,7 @@ class Proc { } async #spawn() { - this.launchKey = await launchKey(this.agyPath, this.workDir) + this.launchKey = await launchKey(this.agyPath, this.workDir, this.media) await ensureControlServer() const bin = await ensureShimDir() sessions.set(this.token, this) @@ -2704,7 +2712,7 @@ class Proc { } const agentDir = path.join(this.workspace, ".agents", "agents", AGENT_NAME) await fs.promises.mkdir(agentDir, { recursive: true }) - await fs.promises.writeFile(path.join(agentDir, "agent.md"), agentDefinition(), { mode: 0o600 }) + await fs.promises.writeFile(path.join(agentDir, "agent.md"), agentDefinition(this.media), { mode: 0o600 }) this.logPath = path.join(this.workspace, "agy-acp.log") const args = [ @@ -2723,8 +2731,9 @@ class Proc { // 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) + // (plugins#1405). The model is still told where the tools run. Nor with + // media: view_file would read everything in it unasked. + if (this.workDir && !this.media && !holdsHome(this.workDir)) args.push("--add-dir", this.workDir) args.push(...await noDefaultCustomizationsArgs(this.agyPath)) args.push(...await telemetryArgs(this.agyPath)) const own = await geminiDirArgs(this.agyPath) @@ -2754,6 +2763,9 @@ class Proc { PATH: bin + path.delimiter + inheritedPath, AGY_BRIDGE_CONTROL_PORT: String(controlServer.address().port), AGY_BRIDGE_TOKEN: this.token, + // view_file reads agy's temp folder unasked: the workspace, not + // the one every other session's workspace is in + ...this.media ? { TMPDIR: this.workspace, TMP: this.workspace, TEMP: this.workspace } : {}, }, }) } catch (error) { @@ -3307,7 +3319,7 @@ class Proc { this.sessionPrompts++ if (turn.promptSentAt == null) turn.promptSentAt = Date.now() let result - const capacityWatch = this.#watchCapacity(turn) + const retryWatch = this.#watchRetries(turn) try { result = await this.conn.request("session/prompt", { sessionId: this.sessionId, @@ -3315,7 +3327,7 @@ class Proc { }) } finally { turn.promptInFlight = false - clearInterval(capacityWatch) + clearInterval(retryWatch) } if (promptNumber === 1) { // how long agy took to answer, beside the session row's start-up steps @@ -3471,17 +3483,34 @@ 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) { + // Reads the lines agy adds to its log while the prompt runs: since agy + // 1.5.13 its retries are silent (its changelog: "retries are now silent + // … the chat shows an error only when every retry fails"), so the bare 429 + // is no longer an attempt banner in the reply (refusedDetail) but only a + // log line, "Run: attempt 1 failed (RESOURCE_EXHAUSTED (code 429): + // Resource has been exhausted (e.g. check quota).), retrying in 4s", and + // agy tried 8 times over ~155s before its 429 ending (#1151's log): to the + // client, Claude Code and pi through agy-cli sat silent for minutes, then + // failed (lanmao on linux.do, herryhengAI on X, 11-22). The retry of a "no + // capacity" 503 (noCapacity) ends the turn only while nothing has reached + // the client, so a reply is never cut off for it. + #watchRetries(turn) { let reading = false + let from = turn.logOffset const quiet = () => !turn.done && turn.firstOutputAt == null && !turn.calls.length const timer = setInterval(async () => { - if (reading || !quiet()) return + if (reading || turn.done) return reading = true try { - const detail = await lastAgentError(this.logPath, turn.logOffset) - if (noCapacity(detail) && quiet()) this.capacityTurn(turn, detail) + const read = await logLines(this.logPath, from) + from = read.next + const details = agentErrorsIn(read.text) + const refused = details.find((detail) => refused429(detail)) + if (refused) this.refuseTurn(turn, refused) + else { + const busy = details.findLast((detail) => noCapacity(detail)) + if (busy && quiet()) this.capacityTurn(turn, busy) + } } finally { reading = false } @@ -3989,20 +4018,47 @@ async function logTail(file, offset) { } } -// agy writes the real upstream error only to its log; read what this turn added. -async function lastAgentError(file, offset) { - const text = await logTail(file, offset) - if (!text) return "" - let found = "" - for (const line of text.split("\n")) { +// The whole lines agy logged from offset (its last LOG_TAIL_BYTES at most), +// and the offset after them: a line still being written is read next time. +async function logLines(file, offset) { + try { + if ((await fs.promises.stat(file)).size <= offset) return { text: "", next: offset } + const handle = await fs.promises.open(file, "r") + try { + const size = (await handle.stat()).size + const start = Math.max(offset, size - LOG_TAIL_BYTES) + const buffer = Buffer.alloc(Math.max(0, size - start)) + await handle.read(buffer, 0, buffer.length, start) + const last = buffer.lastIndexOf(0x0a) + if (last < 0) return { text: "", next: offset } + return { text: buffer.subarray(0, last + 1).toString("utf8"), next: start + last + 1 } + } finally { + await handle.close() + } + } catch { + return { text: "", next: offset } + } +} + +// The upstream errors in text, agy's log, in the order agy logged them +function agentErrorsIn(text) { + const out = [] + for (const line of String(text || "").split("\n")) { const match = /\] (?:agent executor error|failed to construct executor|inference connection failed[^:]*): (.+)$/.exec(line) || /\] (?:Run|CallWithRetry): attempt \d+ failed \((.+)\), retrying in /.exec(line) - if (match) found = match[1] + if (!match) continue + let found = match[1] + const cut = found.lastIndexOf("generating and executing: ") + if (cut >= 0) found = found.slice(cut + "generating and executing: ".length) + found = found.trim().slice(0, 1000) + if (found) out.push(found) } - if (!found) return "" - const cut = found.lastIndexOf("generating and executing: ") - if (cut >= 0) found = found.slice(cut + "generating and executing: ".length) - return found.trim().slice(0, 1000) + return out +} + +// agy writes the real upstream error only to its log; read what this turn added. +async function lastAgentError(file, offset) { + return agentErrorsIn(await logTail(file, offset)).at(-1) || "" } // Where agy's three-line notice (the output cap's, a malformed call's) ends, @@ -4196,6 +4252,7 @@ function writeParked(proc, midTurn) { instructionsInSession: !!proc.instructionsInSession, workDir: proc.workDir, workspace: proc.workspace, + media: proc.media, ...midTurn ? { midTurn: true, count: proc.expectedMessages.length } : {}, at: Date.now(), }) @@ -4240,6 +4297,9 @@ function takeParked(convKey, opts, miss = {}) { saveParked() miss.reason = Date.now() - entry.at > RESUME_TTL_MS ? "expired" : (entry.workDir ?? null) !== (opts.workDir ?? null) ? "work_dir" + // agy resumes a session with the tools it was opened with, whatever the + // agent it runs now says: one opened without view_file can't read a video + : !!entry.media !== !!opts.media ? "media" : entry.instructionsHash !== digest(sentInstructionsIdentity(opts.instructions, legacy)) ? "instructions" : entry.userCloak !== USER_CLOAK ? "user_cloak" : entry.instructionsInSession !== (systemAppend() && !!opts.instructions) ? "instructions_place" @@ -4385,11 +4445,11 @@ function sparesOn() { } // Everything that decides how Proc starts agy for the current work. -async function launchKey(agyPath, workDir) { +async function launchKey(agyPath, workDir, media = false) { let mtime = 0 try { mtime = (await fs.promises.stat(agyPath)).mtimeMs } catch {} const own = await geminiDirArgs(agyPath) - return digest(JSON.stringify([currentHome(), agyPath, mtime, workDir || "", + return digest(JSON.stringify([currentHome(), agyPath, mtime, workDir || "", media, await noDefaultCustomizationsArgs(agyPath), await telemetryArgs(agyPath), own.args, childEnv(process.env)])) } @@ -4398,9 +4458,9 @@ function dropSpare(spare) { return spare.stop().catch(() => {}) } -async function takeSpare(agyPath, workDir) { +async function takeSpare(agyPath, workDir, media) { if (!spares.size || !sparesOn()) return null - const key = await launchKey(agyPath, workDir) + const key = await launchKey(agyPath, workDir, media) const spare = spares.get(key) if (!spare) return null spares.delete(key) @@ -4476,8 +4536,9 @@ async function acquireProc(agyPath, convKey, opts, isFreshConversation, forceNew // the new key (sorted, to avoid deadlock), then pick again inside those // locks. A process is re-keyed only when its current key is already held. let extra = null - const launch = !forceNew && isFreshConversation && freshToolless(opts) - ? await launchKey(agyPath, opts.workDir).catch(() => null) : null + // never a media request: the agy's folder still holds the clips it was sent + const launch = !forceNew && isFreshConversation && freshToolless(opts) && !opts.media + ? await launchKey(agyPath, opts.workDir, opts.media).catch(() => null) : null for (let attempt = 0; ; attempt++) { const keys = extra && extra !== convKey ? [convKey, extra] : [convKey] const outcome = await withAcquireLocks(keys, async () => { @@ -4581,7 +4642,8 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo // than the empty history, so matchesHistory turns the next one away. const retriedOpening = isFreshConversation && existing.failedOpening const compatible = !forceNew && !existing.dead && !existing.retiring && - existing.workDir === opts.workDir && sameInstructions(existing.instructions, opts.instructions) && + existing.workDir === opts.workDir && existing.media === opts.media && + sameInstructions(existing.instructions, opts.instructions) && (existing.matchesHistory(matchedHistory) || continuedFresh) if (compatible && (!(isFreshConversation && existing.hasSentFirstTurn) || continuedFresh || retriedOpening)) { if (continuedFresh) { @@ -4603,6 +4665,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo Array.isArray(matchedHistory) && !matchedHistory.length why = forceNew ? "forced" : existing.dead ? "dead" : existing.retiring ? "retiring" : existing.workDir !== opts.workDir ? "work_dir" : + existing.media !== opts.media ? "media" : !sameInstructions(existing.instructions, opts.instructions) ? "instructions" : newOpening ? "fresh_after_first" : !(existing.matchesHistory(matchedHistory) || continuedFresh) ? "history" : "fresh_after_first" @@ -4629,7 +4692,7 @@ async function acquireProcLocked(agyPath, convKey, opts, isFreshConversation, fo const parkMiss = { reason: isFreshConversation ? null : forceNew && !opts.resumeStep ? "forced" : null } const resume = isFreshConversation || (forceNew && !opts.resumeStep) ? null : takeParked(convKey, opts, parkMiss) // a spare runs in a folder of its own, and a resumed session needs its own - const spare = resume?.workspace ? null : await takeSpare(agyPath, opts.workDir) + const spare = resume?.workspace ? null : await takeSpare(agyPath, opts.workDir, opts.media) while (!spare && allProcs.size >= maxProcs()) { const idle = spares.values().next().value if (idle) { @@ -6105,6 +6168,8 @@ function historyBlock(block, ids) { } else if (block.type === "image") { const image = parseUserImage(block) value = { type: "image", mimeType: image.mimeType, sha256: digest(image.data) } + } else if (isMedia(block)) { + value = { type: block.type, mediaType: block.source.media_type, sha256: digest(mediaData(block)) } } else if (block.type === "tool_use") { const ordinal = ids.size + 1 ids.set(block.id, ordinal) @@ -6532,6 +6597,30 @@ function appendSchemaHint(node, hint) { } } +function plainSchemaMap(value) { + return value && typeof value === "object" && !Array.isArray(value) +} + +// agy rejects every extra key on an object whose properties map is missing +// or empty when additionalProperties is left out (plugins#1332). JSON Schema +// allows those keys. An explicit additionalProperties, a restrictive +// unevaluatedProperties, a non-empty properties map, and a non-empty +// patternProperties map stay as declared. +function emptyObjectIsOpen(node) { + const resolved = typeof node.type === "string" + ? node.type + : Array.isArray(node.type) + ? node.type.find((item) => item !== "null") || null + : null + const implicitObject = node.type === undefined && plainSchemaMap(node.properties) + if (resolved !== "object" && !implicitObject) return false + if (node.additionalProperties !== undefined) return false + if (node.unevaluatedProperties !== undefined && node.unevaluatedProperties !== true) return false + if (plainSchemaMap(node.patternProperties) && Object.keys(node.patternProperties).length > 0) return false + if (node.properties !== undefined && !plainSchemaMap(node.properties)) return false + if (plainSchemaMap(node.properties) && Object.keys(node.properties).length > 0) return false + return true +} // Sanitize JSON Schema constructs that agy's ACP -> Google Code Assist translator // converts into invalid Schema protos (e.g. union types leaving stale array/object @@ -6650,6 +6739,9 @@ function sanitizeInputSchema(schema) { // ECMA-262. Translate or drop those patterns here; tool-call arguments in // the response are plain JSON and do not need a reverse transform. sanitizePatternFields(out) + // After patterns: a map whose keys were all dropped is no longer a + // patternProperties object. Say the remaining empty object is open. + if (emptyObjectIsOpen(out)) out.additionalProperties = true return out } @@ -6708,6 +6800,10 @@ function blockText(block) { parseUserImage(block) return "[image]" } + if (isMedia(block)) { + mediaData(block) + return `[${block.type}]` + } if (block.type === "tool_result") { const inner = Array.isArray(block.content) ? block.content.map((part) => { @@ -6728,6 +6824,57 @@ function messageText(message) { return String(message.content ?? "") } +// A user's video or audio: magpie's Messages video block, and audio in the +// same shape. agy drops or refuses every way ACP has to attach one (an +// audio block, a resource or resource_link, @path); only its own view_file +// hands Gemini the media itself, so stageMedia leaves it in a file to read. +function isMedia(block) { + return block?.type === "video" || block?.type === "audio" +} + +function hasMedia(message) { + return Array.isArray(message.content) && message.content.some(isMedia) +} + +// of agy's models, only Gemini takes a video or audio +function takesMedia(modelId) { + return modelId.startsWith("gemini-") +} + +function mediaData(block) { + const source = block.source + if (source?.type !== "base64" || typeof source.data !== "string" || !source.data) { + throw new UnsupportedContent(`a ${block.type} source other than base64; provide inline ${block.type} data instead of a URL`) + } + return source.data +} + +// stageMedia is the message with each video or audio written to +// dir/attachments, named by its sha256 so a history that sends it every turn +// writes it once, and a note to read it in its place. Synchronous: an await +// before the turn starts would leave the process idle, to be evicted. +function stageMedia(message, dir) { + return hasMedia(message) + ? { ...message, content: message.content.map((block) => isMedia(block) ? stagedMedia(block, dir) : block) } + : message +} + +function stagedMedia(block, dir) { + const bytes = Buffer.from(mediaData(block), "base64") + const type = String(block.source.media_type || "").toLowerCase().split(";")[0].trim() + const sub = /^(?:video|audio)\/(?:x-)?([a-z0-9]{1,16})$/.exec(type)?.[1] + const ext = type === "audio/mpeg" ? "mp3" : sub === "quicktime" ? "mov" : sub || (block.type === "audio" ? "mp3" : "mp4") + const file = path.join(dir, "attachments", `${digest(bytes)}.${ext}`) + if (!fs.existsSync(file)) { + // whole or not at all: one cut short by a failed write would pass for it + fs.mkdirSync(path.dirname(file), { recursive: true }) + const part = `${file}.${process.pid}.${randomUUID().slice(0, 8)}.part` + fs.writeFileSync(part, bytes) + fs.renameSync(part, file) + } + return { type: "text", text: `[The user attached ${block.type === "video" ? "a video" : "an audio file"}: ${file}. Read it with your file reading tool before answering.]` } +} + function imageContent(block) { const source = block.source if (source?.type !== "base64") { @@ -8974,7 +9121,7 @@ function estimateInputTokens(body) { return } if (typeof value === "object") { - if (value.type === "image" && value.source?.type === "base64") { + if ((value.type === "image" || isMedia(value)) && value.source?.type === "base64") { images++ return } @@ -9210,18 +9357,22 @@ function withoutAnswered(messages, answered) { async function beginTurn(proc, history, body, callerWorkDir, model, selection, answered, grownTools = null) { const reminder = outputFormatReminder(body) - const flattened = proc.pendingFlattenedTurn + let flattened = proc.pendingFlattenedTurn proc.pendingFlattenedTurn = null const isFirstTurn = !proc.hasSentFirstTurn + // the prompt names each video or audio by its file; the session is still + // matched by body.messages + const messages = body.messages.map((message) => stageMedia(message, proc.workspace)) + if (flattened) flattened = stageMedia(flattened, proc.workspace) let baseParts let replay = null if (!isFirstTurn && proc.resumedStep) { proc.resumedStep = false - baseParts = renderResumedStepParts(body.messages.slice(history.length)) + baseParts = renderResumedStepParts(messages.slice(history.length)) } else if (!isFirstTurn) { baseParts = renderContinuedTurnParts(flattened - ? [flattened, ...body.messages.slice(1)] - : withoutAnswered(body.messages.slice(history.length), answered)) + ? [flattened, ...messages.slice(1)] + : withoutAnswered(messages.slice(history.length), answered)) // a step ended for tools loaded mid-turn: its results are in, so the // prompt says what can be called now and to go on if (grownTools?.length) baseParts = mergePromptParts([{ type: "text", text: grownToolsNote(grownTools) }], baseParts) @@ -9229,7 +9380,7 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a // A history bigger than one prompt goes in over several (seedHistory), // up to the model's window, where agy can take them. const budget = seedsHistory(proc.agentVersion) ? Math.max(maxInitialPromptBytes(), maxReplayBytes(model, selection?.model)) : maxInitialPromptBytes() - const initial = renderInitialPrompt(body, callerWorkDir, proc.instructionsInSession, + const initial = renderInitialPrompt({ ...body, messages }, callerWorkDir, proc.instructionsInSession, reminder.length ? promptTextBytes(reminder) + 2 : 0, budget) baseParts = initial.parts if (initial.stats.messages_before) replay = { ...initial.stats, prompt_bytes: promptTextBytes(baseParts), budget_bytes: budget } @@ -9267,14 +9418,14 @@ async function beginTurn(proc, history, body, callerWorkDir, model, selection, a throw new UnsupportedContent("image input with this agy ACP server; update to an image-capable agy version") } if (isFirstTurn) { - const rawEstimate = estimateInputTokens(body) + const rawEstimate = estimateInputTokens({ ...body, messages }) const sessionOverhead = (proc.instructionsInSession && body.system ? estimateInputTokens({ system: body.system, messages: [] }) : 0) + (Array.isArray(body.tools) && body.tools.length ? estimateTextTokens(JSON.stringify(body.tools)) : 0) const sentEstimate = Math.max(1, sessionOverhead + estimatePromptPartsTokens(contentParts) + seeds.reduce((sum, parts) => sum + estimatePromptPartsTokens(parts), 0)) const clipThreshold = Math.min(HISTORY_BLOCK_CLIP_BYTES, maxInitialPromptBytes()) - const promptClipped = utf8Bytes(JSON.stringify(body.messages)) > clipThreshold && + const promptClipped = utf8Bytes(JSON.stringify(messages)) > clipThreshold && rawEstimate > sentEstimate + 64 proc.omittedHistoryTokens = promptClipped ? rawEstimate - sentEstimate : 0 } @@ -9715,6 +9866,11 @@ export const AntigravityBridgePlugin = async () => { anotherAccountLists(agy, requestedModel)) { return jsonError(400, `agy bridge: model ${requestedModel} is unavailable to this agy account; another signed-in agy account lists it`) } + // agy runs the requested model when its session offers it (configModelSelection), else the resolved one + const media = body.messages.some(hasMedia) + if (media && !(takesMedia(requestedModel) && takesMedia(model))) { + return jsonError(400, `agy bridge: video or audio input to ${requestedModel} is not supported. Choose a Gemini model`, undefined, { noRetry: true }) + } const selection = { model: requestedModel, effort: requestedEffort(body, saidEffort) } // the key before the model line left it (0.1.142 and older) const legacyConvKey = (home ? `acct:${path.basename(home)}:` : "") + conversationKey(body, sessionScope, callerWorkDir || "", true) @@ -9750,7 +9906,8 @@ export const AntigravityBridgePlugin = async () => { const acquireOpts = { model, selection, tools, workDir, instructions, history: trailing.history, messages: body.messages, layout, nonstream: body.stream === false, reqId, convKey, legacyConvKey: legacyConvKey !== convKey ? legacyConvKey : "", - hasToolResults: resultBlocks.length > 0, userId: body.metadata?.user_id || "", sessionScope } + hasToolResults: resultBlocks.length > 0, userId: body.metadata?.user_id || "", sessionScope, + media } let answeredIds = null // tools the steered prompt names as callable now (grown mid-turn) let grownTools = null @@ -10022,6 +10179,7 @@ export const AntigravityBridgePlugin = async () => { } for (const model of catalog.models) { const imageModel = /^(?:gemini-|claude-)/.test(model.id) + const mediaModel = takesMedia(model.id) out[model.id] = { id: model.id, name: model.name, @@ -10029,7 +10187,7 @@ export const AntigravityBridgePlugin = async () => { limit: modelLimits(model.id), api: { id: model.id, url: "agy://local", npm: NPM_ANTHROPIC }, capabilities: { - ...(imageModel ? { attachment: true, input: { text: true, image: true }, output: { text: true } } : {}), + ...(imageModel ? { attachment: true, input: { text: true, image: true, ...(mediaModel ? { video: true, audio: true } : {}) }, output: { text: true } } : {}), ...(model.variants ? { reasoning: true } : {}), }, ...(model.variants ? { diff --git a/package.json b/package.json index a622173..8e13289 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.153", + "version": "0.1.157", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", diff --git a/test/conversation-key.mjs b/test/conversation-key.mjs index fbfdc60..cdd1538 100644 --- a/test/conversation-key.mjs +++ b/test/conversation-key.mjs @@ -776,6 +776,18 @@ test("historyKey keys a tool_result image by its hash, not its bytes", () => { assert.equal(key, historyKey(screenshotHistory(data))) }) +test("historyKey keys a user's video or audio by its hash, not its bytes", () => { + const clip = (type, data) => [{ role: "user", content: [ + { type, source: { type: "base64", media_type: `${type}/mp4`, data } }, { type: "text", text: "what is in it?" }] }] + for (const type of ["video", "audio"]) { + const data = "AAAAGGZ0eXBpc29t" + "A".repeat(200_000) + const key = historyKey(clip(type, data)) + assert.ok(key.length < 2_000, `key is ${key.length} chars`) + assert.notEqual(key, historyKey(clip(type, "AAAAGGZ0eXBpc29t" + "B".repeat(200_000)))) + assert.equal(key, historyKey(clip(type, data))) + } +}) + test("a turn lets go of each earlier request body once the next one arrives", () => { const proc = { estimatePromptTokens: () => 100 } const turn = new Turn(proc, [{ role: "user", content: "hi" }]) diff --git a/test/media-input.mjs b/test/media-input.mjs new file mode 100644 index 0000000..cda184e --- /dev/null +++ b/test/media-input.mjs @@ -0,0 +1,236 @@ +// A user's video or audio reaches Gemini through agy's own view_file: agy's +// ACP prompt carries neither, so the bridge writes each to a file in the +// session's folder and asks the model to read it there. view_file is the +// agent's tool only while the conversation carries one. + +import { test } from "node:test" +import assert from "node:assert/strict" +import { createHash } from "node:crypto" +import fs from "node:fs" +import path from "node:path" +import { BASE_MODEL_ROWS, baseBody, createBridgeKit, readSse, sleep, tick, usageTotal } from "./testkit.mjs" + +const MP4 = Buffer.concat([Buffer.from("000000186674797069736f6d", "hex"), Buffer.from("a video's bytes")]) +const MP3 = Buffer.concat([Buffer.from("494433", "hex"), Buffer.from("an audio's bytes")]) +const media = (type, bytes, mediaType) => ({ type, source: { type: "base64", media_type: mediaType, data: bytes.toString("base64") } }) +const sha256 = (bytes) => createHash("sha256").update(bytes).digest("hex") + +async function withKit(fn, options) { + const kit = await createBridgeKit(options) + try { + kit.defaultPrompt = async (agent) => { await agent.text("ok"); return { stopReason: "end_turn" } } + return await fn(kit) + } finally { + await kit.dispose() + } +} + +const prompts = (kit) => kit.acpLog.filter((entry) => entry.method === "session/prompt") +const promptText = (entry) => entry.params.prompt.map((part) => part.text ?? "").join("") +const workspaceOf = (kit, entry) => kit.acpSpawns[entry.spawn].cwd +const agentTools = (kit, entry) => /^tools: .*$/m.exec(fs.readFileSync( + path.join(workspaceOf(kit, entry), ".agents", "agents", "magpie-bridge", "agent.md"), "utf8"))[0] +const reply = async (response) => ({ role: "assistant", content: (await readSse(response)).content.map((block) => ({ type: "text", text: block.text })) }) + +test("a video and an audio go to agy as files in the session's folder, named by their sha256", async () => { + await withKit(async (kit) => { + const first = baseBody({ messages: [{ role: "user", content: [ + media("video", MP4, "video/mp4"), media("audio", MP3, "audio/mpeg"), { type: "text", text: "what is said?" }] }] }) + const answer = await reply(await kit.request(first)) + const sent = prompts(kit).at(-1) + const attachments = path.join(workspaceOf(kit, sent), "attachments") + const video = path.join(attachments, `${sha256(MP4)}.mp4`) + const audio = path.join(attachments, `${sha256(MP3)}.mp3`) + assert.deepEqual(sent.params.prompt.map((part) => part.type), ["text"]) + const text = promptText(sent) + assert.ok(text.includes(`[The user attached a video: ${video}. Read it with your file reading tool before answering.]`), text) + assert.ok(text.includes(`[The user attached an audio file: ${audio}. Read it with your file reading tool before answering.]`), text) + assert.ok(text.indexOf(video) < text.indexOf(audio) && text.indexOf(audio) < text.indexOf("what is said?")) + assert.ok(!text.includes(MP4.toString("base64"))) + assert.deepEqual(fs.readFileSync(video), MP4) + assert.deepEqual(fs.readFileSync(audio), MP3) + + // the history sends the video again: the same file, and the turn says only what is new + const next = { ...first, messages: [...first.messages, answer, { role: "user", content: "and the number?" }] } + await readSse(await kit.request(next)) + assert.equal(kit.acpSpawns.length, 1) + assert.equal(promptText(prompts(kit).at(-1)).includes("attached"), false) + assert.deepEqual(fs.readdirSync(attachments).sort(), [path.basename(video), path.basename(audio)].sort()) + }) +}) + +test("a file's extension comes from its media type, else mp4 for a video and mp3 for an audio", async () => { + await withKit(async (kit) => { + const cases = [["video", "video/quicktime", "mov"], ["audio", "audio/x-wav", "wav"], ["video", "video/webm; codecs=vp9", "webm"], + ["video", undefined, "mp4"], ["audio", "application/octet-stream", "mp3"]] + .map(([type, mediaType, ext], i) => ({ type, mediaType, ext, bytes: Buffer.from(`clip ${i}`) })) + await readSse(await kit.request(baseBody({ messages: [{ role: "user", content: [ + ...cases.map(({ type, bytes, mediaType }) => media(type, bytes, mediaType)), { type: "text", text: "compare them" }] }] }))) + const attachments = path.join(workspaceOf(kit, prompts(kit).at(-1)), "attachments") + assert.deepEqual(fs.readdirSync(attachments).sort(), cases.map(({ bytes, ext }) => `${sha256(bytes)}.${ext}`).sort()) + }) +}) + +test("view_file is agy's tool only in a conversation that carries a video or audio", async () => { + await withKit(async (kit) => { + const opening = baseBody({ messages: [{ role: "user", content: "hello" }] }) + const answer = await reply(await kit.request(opening)) + assert.equal(agentTools(kit, prompts(kit).at(-1)), "tools: []") + + // the conversation's first video: an agy whose agent has view_file, in + // a new session; a resumed one keeps the tools it was opened with + const withVideo = { ...opening, messages: [...opening.messages, answer, + { role: "user", content: [media("video", MP4, "video/mp4"), { type: "text", text: "what is in it?" }] }] } + await readSse(await kit.request(withVideo)) + assert.equal(kit.acpSpawns.length, 2) + assert.equal(agentTools(kit, prompts(kit).at(-1)), "tools: [view_file]") + assert.match(promptText(prompts(kit).at(-1)), /hello[\s\S]*The user attached a video/) + + // a request with no video never runs in an agy that has view_file + const stateless = (content) => baseBody({ stream: false, tools: [], messages: [{ role: "user", content }] }) + const described = await kit.request(stateless([media("audio", MP3, "audio/mpeg"), { type: "text", text: "transcribe" }])) + assert.equal(described.status, 200, await described.clone().text()) + assert.equal(agentTools(kit, prompts(kit).at(-1)), "tools: [view_file]") + const describedIn = prompts(kit).at(-1).spawn + const plain = await kit.request(stateless("write a title")) + assert.equal(plain.status, 200, await plain.clone().text()) + assert.equal(agentTools(kit, prompts(kit).at(-1)), "tools: []") + const again = await kit.request(stateless([media("video", MP4, "video/mp4"), { type: "text", text: "describe it" }])) + assert.equal(again.status, 200, await again.clone().text()) + assert.equal(agentTools(kit, prompts(kit).at(-1)), "tools: [view_file]") + // nor in one whose folder holds another conversation's clip + assert.notEqual(prompts(kit).at(-1).spawn, describedIn) + }, { sessionResume: true }) +}) + +// view_file reads unasked what is under an --add-dir folder and in agy's +// temp folder: a video must not open the caller's named folder, or /tmp +// with every other session's workspace in it, to the model +test("an agy for a video gets no --add-dir, and its temp folder is its workspace", async () => { + await withKit(async (kit) => { + const dir = path.join(kit.tmp, "project") + fs.mkdirSync(dir) + const ask = async (content) => { + await readSse(await kit.request(baseBody({ messages: [{ role: "user", content }] }), { headers: { "x-magpie-work-dir": dir } })) + return kit.acpSpawns[prompts(kit).at(-1).spawn] + } + const plain = await ask("hello") + const video = await ask([media("video", MP4, "video/mp4"), { type: "text", text: "what is in it?" }]) + assert.notEqual(plain, video) + assert.equal(plain.args[plain.args.indexOf("--add-dir") + 1], dir) + assert.equal(video.args.includes("--add-dir"), false) + assert.deepEqual([video.env.TMPDIR, video.env.TMP, video.env.TEMP], [video.cwd, video.cwd, video.cwd]) + assert.notEqual(plain.env.TMPDIR, plain.cwd) + }) +}) + +test("a flattened opening that grows by a video sends the new one as a file too", async () => { + await withKit(async (kit) => { + const opening = "Please look at the clip and say what happens.\nstep one" + const clip = Buffer.concat([MP4, Buffer.from(" and more")]) + const first = baseBody({ messages: [{ role: "user", content: [media("video", MP4, "video/mp4"), { type: "text", text: opening }] }] }) + const answer = (await reply(await kit.request(first))).content[0].text + await readSse(await kit.request(baseBody({ messages: [{ role: "user", content: [media("video", MP4, "video/mp4"), + { type: "text", text: `${opening}\n\nassistant: ${answer}\n\nstep two, a second clip` }, media("video", clip, "video/mp4")] }] }))) + // the same agy goes on with the opening's new part alone + assert.equal(kit.acpSpawns.length, 1) + const sent = prompts(kit).at(-1) + const file = path.join(workspaceOf(kit, sent), "attachments", `${sha256(clip)}.mp4`) + assert.equal(promptText(sent), `step two, a second clip[The user attached a video: ${file}. Read it with your file reading tool before answering.]`) + }) +}) + +test("a video conversation's files go with its agy, and its parked session resumes with view_file and the file again", async () => { + await withKit(async (kit) => { + const opening = baseBody({ messages: [{ role: "user", content: [media("video", MP4, "video/mp4"), { type: "text", text: "what is in it?" }] }] }) + const answer = await reply(await kit.request(opening)) + const first = prompts(kit).at(-1) + const video = path.join(workspaceOf(kit, first), "attachments", `${sha256(MP4)}.mp4`) + for (const proc of [...kit.module.__agyTestAllProcs]) await proc.stop() + assert.equal(fs.existsSync(path.dirname(video)), false) + + await readSse(await kit.request({ ...opening, messages: [...opening.messages, answer, { role: "user", content: "and the colour?" }] })) + assert.deepEqual(kit.acpLog.filter((entry) => entry.method === "session/resume").map((entry) => entry.params.sessionId), [first.sessionId]) + assert.equal(agentTools(kit, prompts(kit).at(-1)), "tools: [view_file]") + assert.deepEqual(fs.readFileSync(video), MP4) + }, { sessionResume: true }) +}) + +test("a session parked by a host from before video resumes for a conversation with none", async () => { + await withKit(async (kit) => { + const opening = baseBody({ messages: [{ role: "user", content: "hello" }] }) + const answer = await reply(await kit.request(opening)) + const first = prompts(kit).at(-1) + for (const proc of [...kit.module.__agyTestAllProcs]) await proc.stop() + // the old host parked the conversation's last turn: its entry has no media + const file = path.join(kit.env.XDG_STATE_HOME, "magpie-agy-bridge", "sessions.json") + const state = JSON.parse(fs.readFileSync(file, "utf8")) + for (const entry of state.entries) { delete entry.media; entry.at++ } + fs.writeFileSync(file, JSON.stringify(state)) + + await readSse(await kit.request({ ...opening, messages: [...opening.messages, answer, { role: "user", content: "and then?" }] })) + assert.deepEqual(kit.acpLog.filter((entry) => entry.method === "session/resume").map((entry) => entry.params.sessionId), [first.sessionId]) + }, { sessionResume: true }) +}) + +test("a spare agy, warmed without view_file, waits for a conversation with no video", async () => { + await withKit(async (kit) => { + await readSse(await kit.request(baseBody({ system: "one", messages: [{ role: "user", content: "hello" }] }))) + // spawn 1 is the spare + for (let i = 0; i < 2000 && kit.acpSpawns.length < 2; i++) await sleep(5) + assert.equal(kit.acpSpawns.length, 2) + + await readSse(await kit.request(baseBody({ system: "two", messages: [{ role: "user", content: [media("video", MP4, "video/mp4"), { type: "text", text: "what is in it?" }] }] }))) + assert.equal(prompts(kit).at(-1).spawn, 2) + assert.equal(agentTools(kit, prompts(kit).at(-1)), "tools: [view_file]") + await readSse(await kit.request(baseBody({ system: "three", messages: [{ role: "user", content: "hi" }] }))) + assert.equal(prompts(kit).at(-1).spawn, 1) + }, { env: { AGY_BRIDGE_SPARE: "1" } }) +}) + +test("a video by URL is refused before agy, and a video counts as an image does, in count_tokens and in a turn's usage", async () => { + await withKit(async (kit) => { + const byUrl = await kit.request(baseBody({ stream: false, messages: [{ role: "user", content: [ + { type: "video", source: { type: "url", url: "https://example.com/clip.mp4" } }, { type: "text", text: "what is in it?" }] }] })) + assert.equal(byUrl.status, 400) + assert.match(await byUrl.text(), /a video source other than base64/) + assert.equal(kit.acpSpawns.length, 0) + + const big = Buffer.alloc(300_000, 7) + const body = (type, mediaType) => baseBody({ tools: [], messages: [{ role: "user", content: [media(type, big, mediaType), { type: "text", text: "hi" }] }] }) + const counted = await kit.countTokens(body("video", "video/mp4")) + assert.equal(counted, await kit.countTokens(body("image", "image/png"))) + // the note in the video's place is no history cut from the prompt + assert.equal(usageTotal((await readSse(await kit.request(body("video", "video/mp4")))).usage), counted) + }) +}) + +// claude-haiku stands in for Gemini Flash, but agy runs Haiku itself when its session offers it +test("a video to a model other than Gemini is refused before agy", async () => { + await withKit(async (kit) => { + for (const model of ["claude-opus-5-5", "claude-haiku-4-5"]) { + const response = await kit.request(baseBody({ model: `agy-cli/${model}`, stream: false, messages: [{ role: "user", content: [ + media("video", MP4, "video/mp4"), { type: "text", text: "what is in it?" }] }] })) + assert.equal(response.status, 400) + assert.equal(response.headers.get("x-should-retry"), "false") + const body = await response.json() + assert.equal(body.error.type, "invalid_request_error") + assert.equal(body.error.message, `agy bridge: video or audio input to ${model} is not supported. Choose a Gemini model`) + } + assert.equal(kit.acpSpawns.length, 0) + }) +}) + +test("Gemini models take video and audio; Claude and GPT-OSS don't", async () => { + await withKit(async (kit) => { + await kit.models() + // the probe session says what agy offers + for (let i = 0; i < 20 && kit.children.size; i++) await sleep(10) + await tick() + const models = await kit.models() + assert.deepEqual(models["gemini-4-argon"].capabilities.input, { text: true, image: true, video: true, audio: true }) + assert.deepEqual(models["gemini-3.8-flash"].capabilities.input, { text: true, image: true, video: true, audio: true }) + assert.deepEqual(models["claude-opus-5-5"].capabilities.input, { text: true, image: true }) + assert.equal(models["gpt-oss-120b"].capabilities.input, undefined) + }, { offeredModels: BASE_MODEL_ROWS }) +}) diff --git a/test/repeat-batch.mjs b/test/repeat-batch.mjs index f96f780..05fa7d9 100644 --- a/test/repeat-batch.mjs +++ b/test/repeat-batch.mjs @@ -1827,6 +1827,83 @@ test("Lmohn39: a try that fails another way still waits for agy's next one", asy }) }) +// agy 1.5.13 made its retries silent ("retries are now silent … the chat +// shows an error only when every retry fails"): the bare 429 is no longer a +// banner in the reply but a line in agy's log, as #1151's log has it, and +// agy tried 8 times over ~155s before its ending. Claude Code and pi through +// agy-cli sat silent for minutes, then failed (lanmao on linux.do, +// herryhengAI on X, 11-22). The first such line ends the turn. +// how often the bridge reads agy's log (AGY_BRIDGE_CAPACITY_POLL_MS's default) +const RETRY_POLL_MS = 500 +const REFUSED_RETRY = (n) => `I1122 13:27:37.072566 6120 run.go:316] Run: attempt ${n} failed (RESOURCE_EXHAUSTED (code 429): Resource has been exhausted (e.g. check quota).), retrying in 4s\n` + +test("agy 1.5.13's silent retry of the bare 429 ends the turn at once, for Claude Code's and pi's prompts", async () => { + const PI = "You are a coding assistant running inside pi, a coding agent harness. Help users inspect files, run commands, and modify code." + const CLAUDE_CODE = "You are Claude Code, Anthropic's official CLI for Claude.\n\nHelp the user." + for (const [system, stream, before] of [ + [CLAUDE_CODE, true, ""], [CLAUDE_CODE, false, ""], [PI, true, ""], [PI, false, ""], + // the reply had begun when the next model call was refused + [CLAUDE_CODE, true, "Looking. "], + ]) { + await withKit({}, async (kit) => { + let tries = 0 + let ended = null + kit.defaultPrompt = async (agent) => { + tries++ + if (before) await agent.text(before) + // the log line agy writes while the line it goes on is half-written + const line = REFUSED_RETRY(1) + fs.appendFileSync(agyLogOf(kit), line.slice(0, 50)) + await sleep(RETRY_POLL_MS * 3) + fs.appendFileSync(agyLogOf(kit), line.slice(50)) + // agy waits, then tries again: here it gives up after 20s + ended = await Promise.race([agent.waitCancel().then(() => "cancelled"), sleep(20_000).then(() => "gave up")]) + return { stopReason: "end_turn" } + } + const started = Date.now() + const response = await kit.request(baseBody({ metadata: { user_id: `refused-retry-${stream}-${!!before}` }, system, + messages: [{ role: "user", content: "hello" }], stream })) + const text = await Promise.race([response.text(), sleep(8_000).then(() => "still waiting after 8s")]) + assert.ok(Date.now() - started < 8_000, `ended after ${Date.now() - started}ms, not at agy's give-up`) + assert.notEqual(ended, "gave up", "the reply didn't wait for agy to give up") + assert.equal(tries, 1) + const error = stream ? sseError(text) : JSON.parse(text).error + if (!stream) assert.equal(response.status, 429) + assert.equal(error.type, "rate_limit_error") + assert.match(error.message, /quota or rate limit reached: RESOURCE_EXHAUSTED \(code 429\): Resource has been exhausted.*not a quota/) + assert.ok(!text.includes("⚠"), "no banner reaches the client") + // the cloak reached the prompt agy was handed, with no setup + const sent = prompts(kit).join("") + assert.ok(sent.includes("")) + assert.ok(!/You are Claude Code, Anthropic's official CLI|coding assistant running inside pi/i.test(sent), sent.slice(0, 300)) + }) + } +}) + +test("a 429 retry logged before the prompt, or a retry of another error, doesn't end the turn", async () => { + await withKit({}, async (kit) => { + let first = true + kit.defaultPrompt = async (agent) => { + if (!first) { + fs.appendFileSync(agyLogOf(kit), "I1122 13:27:41.000000 6120 run.go:316] Run: attempt 1 failed (UNAVAILABLE (code 503): try again.), retrying in 4s\n") + await sleep(RETRY_POLL_MS * 4) + } + first = false + await agent.text("answer") + return { stopReason: "end_turn" } + } + const opening = await readSse(await kit.request(baseBody({ metadata: { user_id: "refused-before" }, + messages: [{ role: "user", content: "hello" }] }))) + assert.equal(opening.error, null) + // an earlier prompt's refused try, already in the log + fs.appendFileSync(agyLogOf(kit), REFUSED_RETRY(1)) + const parsed = await readSse(await kit.request(baseBody({ metadata: { user_id: "refused-before" }, + messages: [{ role: "user", content: "hello" }, { role: "assistant", content: "answer" }, { role: "user", content: "again" }] }))) + assert.equal(parsed.error, null) + assert.equal(replyText(parsed), "answer") + }) +}) + // ---------------------------------------------------------------- one opening, several models at once // magpie's "Test models" sends every model the same smallest request, four at a diff --git a/test/smoke.mjs b/test/smoke.mjs index 5bacf6c..342af5f 100644 --- a/test/smoke.mjs +++ b/test/smoke.mjs @@ -2516,13 +2516,13 @@ for (const location of ["inline", "system", "developer", "user"]) { check("request-path permissive items have a fixed depth of 8", bareDepth === 8, String(bareDepth)) - check("request-path expandToolSchema resolves $defs/$ref, lifts root oneOf object unions, preserves boolean additionalProperties, and leaves schema-less ToolSearch empty", + check("request-path expandToolSchema resolves $defs/$ref, lifts root oneOf object unions, preserves boolean additionalProperties, and leaves schema-less ToolSearch with no declared properties", initRefUnion?.inputSchema?.$defs === undefined && initRefUnion?.inputSchema?.oneOf === undefined && initRefUnion?.inputSchema?.additionalProperties === false && JSON.stringify(initRefUnion?.inputSchema?.properties?.method?.enum) === JSON.stringify(["click", "screenshot"]) && JSON.stringify(initRefUnion?.inputSchema?.properties?.params?.required) === JSON.stringify(["x", "y"]) && - JSON.stringify(initToolSearch?.inputSchema) === JSON.stringify({ type: "object", properties: {} }) && + JSON.stringify(initToolSearch?.inputSchema) === JSON.stringify({ type: "object", properties: {}, additionalProperties: true }) && !/gemini/i.test(JSON.stringify(initRefUnion?.inputSchema || {})), JSON.stringify({ refUnion: initRefUnion?.inputSchema, toolSearch: initToolSearch?.inputSchema })) diff --git a/test/tool-schema.mjs b/test/tool-schema.mjs index 09c4939..7ffa6f0 100644 --- a/test/tool-schema.mjs +++ b/test/tool-schema.mjs @@ -672,7 +672,7 @@ test("bridge request path delivers expanded schemas to MCP tools/list without in const cuaTool = mcpTools.find((t) => t.name === "cua_action") assert.ok(searchTool, "ToolSearch must be exposed over MCP tools/list") - assert.deepEqual(searchTool.inputSchema, { type: "object", properties: {} }) + assert.deepEqual(searchTool.inputSchema, { type: "object", properties: {}, additionalProperties: true }) assert.ok(cuaTool, "cua_action must be exposed over MCP tools/list") assert.equal(cuaTool.inputSchema.$defs, undefined) @@ -729,3 +729,178 @@ test("bridge tools/list keeps every tool of a catalog over agy's budget, within await kit.dispose() } }) + +// plugins#1332: agy treats an object with `properties: {}` (or no properties) +// and omitted additionalProperties as closed. JSON Schema allows those keys. +test("plugins#1332 open objects with empty or missing properties allow additional keys", () => { + const issue = { + type: "object", + properties: { + tool: { type: "string" }, + arguments: { + type: "object", + description: "Arguments matching the target tool schema", + properties: {}, + }, + }, + required: ["tool", "arguments"], + } + const expectedIssue = { + type: "object", + properties: { + tool: { type: "string" }, + arguments: { + type: "object", + description: "Arguments matching the target tool schema", + properties: {}, + additionalProperties: true, + }, + }, + required: ["tool", "arguments"], + } + assert.deepEqual(sanitizeInputSchema(issue), expectedIssue) + assert.deepEqual(fullPipeline(issue), expectedIssue) + assert.deepEqual(sanitizeInputSchema(sanitizeInputSchema(issue)), expectedIssue) + + const open = (schema) => sanitizeInputSchema(schema) + assert.deepEqual(open({ type: "object", properties: {} }), { + type: "object", properties: {}, additionalProperties: true, + }) + assert.deepEqual(open({ type: "object" }), { + type: "object", additionalProperties: true, + }) + assert.deepEqual(open({ properties: {} }), { + properties: {}, additionalProperties: true, + }) + assert.deepEqual(open({ type: ["object", "null"], properties: {} }), { + type: ["object", "null"], properties: {}, additionalProperties: true, + }) + assert.deepEqual(open({ type: ["object", "null"] }), { + type: ["object", "null"], additionalProperties: true, + }) + // An empty patternProperties map is already dropped; it does not keep the object closed. + assert.deepEqual(open({ type: "object", properties: {}, patternProperties: {} }), { + type: "object", properties: {}, additionalProperties: true, + }) + + const nested = open({ + type: "object", + additionalProperties: false, + properties: { + bag: { type: "object", properties: {} }, + list: { type: "array", items: { type: "object", properties: {} } }, + tuple: { type: "array", prefixItems: [{ properties: {} }] }, + either: { anyOf: [{ type: "object", properties: {} }, { type: "string" }] }, + one: { oneOf: [{ type: ["object", "null"], properties: {} }, { type: "integer" }] }, + all: { allOf: [{ type: "object", properties: {} }] }, + }, + $defs: { Bag: { type: "object", properties: {} } }, + }) + assert.equal(nested.additionalProperties, false) + assert.equal(nested.properties.bag.additionalProperties, true) + assert.equal(nested.properties.list.items.additionalProperties, true) + assert.equal(nested.properties.tuple.prefixItems[0].additionalProperties, true) + assert.equal(nested.properties.either.anyOf[0].additionalProperties, true) + assert.equal(nested.properties.either.anyOf[1].additionalProperties, undefined) + assert.equal(nested.properties.one.oneOf[0].additionalProperties, true) + assert.deepEqual(nested.properties.one.oneOf[0].type, ["object", "null"]) + assert.equal(nested.properties.all.allOf[0].additionalProperties, true) + assert.equal(nested.$defs.Bag.additionalProperties, true) + + const closed = open({ + type: "object", + properties: {}, + additionalProperties: false, + }) + assert.equal(closed.additionalProperties, false) + // unevaluatedProperties: false or a schema constrains extra keys; stamping + // additionalProperties: true would mark every property evaluated and bypass it. + const unevalClosed = open({ + type: "object", + properties: {}, + unevaluatedProperties: false, + }) + assert.equal(unevalClosed.additionalProperties, undefined) + assert.equal(unevalClosed.unevaluatedProperties, false) + assert.deepEqual( + fullPipeline({ type: "object", unevaluatedProperties: false }), + { type: "object", unevaluatedProperties: false }, + ) + const unevalSchema = open({ + type: "object", + unevaluatedProperties: { type: "string" }, + }) + assert.equal(unevalSchema.additionalProperties, undefined) + assert.deepEqual(unevalSchema.unevaluatedProperties, { type: "string" }) + const unevalOpen = open({ + type: "object", + properties: {}, + unevaluatedProperties: true, + }) + assert.equal(unevalOpen.additionalProperties, true) + assert.equal(unevalOpen.unevaluatedProperties, true) + const dict = open({ + type: "object", + properties: {}, + additionalProperties: { type: "string", minLength: 1 }, + }) + assert.deepEqual(dict.additionalProperties, { type: "string", minLength: 1 }) + const nestedDict = open({ + type: "object", + additionalProperties: { type: "object", properties: {} }, + }) + assert.deepEqual(nestedDict.additionalProperties, { + type: "object", properties: {}, additionalProperties: true, + }) + + const declared = open({ + type: "object", + properties: { command: { type: "string" } }, + required: ["command"], + }) + assert.equal(declared.additionalProperties, undefined) + assert.deepEqual(declared.required, ["command"]) + const patterned = open({ + type: "object", + patternProperties: { "^[a-z]+$": { type: "number" } }, + }) + assert.equal(patterned.additionalProperties, undefined) + assert.deepEqual(patterned.patternProperties, { "^[a-z]+$": { type: "number" } }) + const both = open({ + type: "object", + properties: { known: { type: "boolean" } }, + patternProperties: { "^x": { type: "object", properties: {} } }, + }) + assert.equal(both.additionalProperties, undefined) + assert.equal(both.properties.known.additionalProperties, undefined) + assert.equal(both.patternProperties["^x"].additionalProperties, true) + + // Every pattern key dropped: the object is no longer a pattern map. + // With no declared properties, the lifted `additionalProperties: false` + // would still be closed to agy, so the open-object rule applies. + const dropped = open({ + type: "object", + properties: {}, + additionalProperties: false, + patternProperties: { "^(?!x)": { type: "string" } }, + }) + assert.equal(dropped.patternProperties, undefined) + assert.equal(dropped.additionalProperties, true) + assert.match(dropped.description, /dropped patternProperties/) + const droppedWithFields = open({ + type: "object", + properties: { known: { type: "string" } }, + additionalProperties: false, + patternProperties: { "^(?!x)": { type: "number" } }, + }) + assert.equal(droppedWithFields.patternProperties, undefined) + assert.equal(droppedWithFields.additionalProperties, undefined) + assert.equal(droppedWithFields.properties.known.type, "string") + + assert.deepEqual(open({ type: "string" }), { type: "string" }) + assert.deepEqual(open({ type: "null", properties: {} }), { type: "null" }) + assert.deepEqual(open({ type: ["null"], properties: {} }), { type: ["null"], properties: {} }) + assert.deepEqual(open({ description: "any" }), { description: "any" }) + assert.equal(open(true), true) + assert.equal(open(false), false) +}) From 78f40358445e2c12ada3d47496d22111bf109818 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Sat, 28 Nov 2026 07:44:45 +0000 Subject: [PATCH 2/4] upstream agy-cli 0.1.159 (magpie-community/plugins@e98856a32b4dcf0239a8cfb3bdba26ae54182034) --- agy-cli.test.mjs | 1 + index.mjs | 97 ++++++++++++++++++++++++- opencode2.mjs | 18 ++++- package.json | 2 +- test/dropped-step.mjs | 163 ++++++++++++++++++++++++++++++++++++++++++ 5 files changed, 276 insertions(+), 5 deletions(-) create mode 100644 test/dropped-step.mjs diff --git a/agy-cli.test.mjs b/agy-cli.test.mjs index d90b443..7dd5008 100644 --- a/agy-cli.test.mjs +++ b/agy-cli.test.mjs @@ -29,6 +29,7 @@ for (const [name, mocks] of [ ["usage-settlement.mjs", false], ["steer-in-session.mjs", false], ["dropped-call.mjs", false], + ["dropped-step.mjs", false], ["repeat-batch.mjs", false], ["unmatched-results.mjs", false], ["conversation-key.mjs", false], diff --git a/index.mjs b/index.mjs index 459ff62..1d736b6 100644 --- a/index.mjs +++ b/index.mjs @@ -3752,6 +3752,31 @@ class Proc { return last } + // The step agy emitted last that a client dropped (plugins#1644): it merged + // a new message into the running step, so it never ran or stored the step's + // calls, and sent the session's history up to them again with only user + // text added. The step is only those calls, none answered or seen by the + // client, and they are every call the turn still waits for. Returns them, + // or null when anything differs (the caller keeps its guards and replay). + droppedNextStep(turn, messages) { + if (this.dead || this.stopping || this.retiring || this.historyInvalid || this.turn !== turn) return null + if (!turn || turn.done || turn.finalized || turn.attached || turn.steering || turn.cancelRequested) return null + const expected = this.expectedMessages + if (!Array.isArray(expected) || expected.length < 2 || !Array.isArray(messages)) return null + const step = expected.at(-1) + if (step?.role !== "assistant" || !Array.isArray(step.content)) return null + const uses = step.content.filter((block) => block?.type === "tool_use") + // a step that said something too is a reply the client never had: a fork + if (!uses.length || step.content.some((block) => block?.type !== "tool_use" && + block?.type !== "thinking" && block?.type !== "redacted_thinking")) return null + const calls = uses.map((block) => turn.calls.find((call) => call.id === block.id)) + if (calls.some((call) => !call || call.result || call.clientSeen || call.mcpResponded || call.deferred || + this.#selfPollCapped(turn, call))) return null + const pending = turn.calls.filter((call) => call.id && !call.result && !call.mcpResponded) + if (pending.length !== calls.length) return null + return appendedUserText(historyRows(expected.slice(0, -1)), historyRows(messages)) ? calls : null + } + #respondMcp(call, payload) { if (call.mcpResponded) return call.mcpResponded = true @@ -4924,6 +4949,28 @@ function droppedPendingCalls(turn, expected, base, history) { return historyKey(stripped) === historyKey(history) } +// The client's rows are the session's, tool results included, with only user +// text added after its last row: the step's tool results (plugins#1644). +function appendedUserText(want, got) { + if (!want.length || got.length !== want.length) return false + const n = want.length - 1 + if (stableJSON(want.slice(0, n)) !== stableJSON(got.slice(0, n))) return false + const a = want[n].content + const b = got[n].content + if (want[n].role !== "user" || got[n].role !== "user" || b.length < a.length) return false + if (!a.some((block) => block.type === "tool_result")) return false + const k = a.length - 1 + if (stableJSON(a.slice(0, k)) !== stableJSON(b.slice(0, k))) return false + let extra = b.slice(k + 1) + if (stableJSON(a[k]) !== stableJSON(b[k])) { + // the new text joins a text the results already ended with + if (a[k].type !== "text" || b[k].type !== "text" || !b[k].text.startsWith(a[k].text) || + !b[k].text.slice(a[k].text.length).trim()) return false + extra = [b[k], ...extra] + } + return extra.length > 0 && extra.every((block) => block.type === "text") +} + // Every tool_use of the turn's calls in messages has a tool_result after it. function carriedAnswered(messages, ids) { const open = new Set() @@ -4980,6 +5027,31 @@ async function keepDroppedTurn(proc, turn, opts) { } } +// A step the client dropped (droppedNextStep, plugins#1644) is answered as +// cancelled and the session goes on with the client's new message, as +// keepDroppedTurn does for #1231, instead of replaying the conversation into +// a new session with no cache. "kept", "failed" (the session is left +// behind; the caller replays) or null (not such a step). +async function keepDroppedStep(ctx) { + return withAcquireLock(ctx.convKey, async () => { + const { proc, turn } = ctx + if (pool.get(ctx.convKey) !== proc || proc.turn !== turn) return null + const calls = proc.droppedNextStep(turn, ctx.messages) + if (!calls || proc.workDir !== ctx.acquireOpts.workDir || + !sameInstructions(proc.instructions, ctx.acquireOpts.instructions)) return null + const kept = await keepDroppedTurn(proc, turn, ctx.acquireOpts) + logBridgeEvent(proc, turn, kept ? "kept" : "keep_failed", "dropped_step", ctx.acquireOpts, { calls: calls.length }) + if (kept) return "kept" + if (proc.turn === turn) await reclaimStaleTurn(proc, turn, SUPERSEDED_NOTE) + else { + proc.historyInvalid = true + dropFromPool(proc) + await proc.stop().catch(() => {}) + } + return "failed" + }) +} + async function reclaimStaleTurn(proc, turn, note = "agy bridge: stale tool turn closed") { turn.closeNote = note proc.retiring = true @@ -10013,7 +10085,18 @@ export const AntigravityBridgePlugin = async () => { // history replayed into a new one with no cache, once per // ToolSearch load (plugins#1371, _paper_hands on X). const grew = proc.toolsGrew(tools) - if (!prefillAfterResults && (interrupted || imageResult || grew) && historyMatches && proc.workDir === workDir && + // The step after these results that the client dropped, a new + // message in its place (plugins#1644): cancelled, the session + // goes on. + const droppedStep = !prefillAfterResults && !historyMatches + ? await keepDroppedStep({ convKey, proc, turn, messages: body.messages, acquireOpts }) + : null + if (droppedStep === "kept") { + keptSession = true + answeredIds = new Set(resultBlocks.map((block) => block.tool_use_id)) + } else if (droppedStep === "failed") { + acquireOpts.dropReason = "dropped_step" + } else if (!prefillAfterResults && (interrupted || imageResult || grew) && historyMatches && proc.workDir === workDir && sameInstructions(proc.instructions, instructions) && await proc.steerInSession(turn, rawResults, trailingMessages(body).history)) { keptSession = true @@ -10076,7 +10159,17 @@ export const AntigravityBridgePlugin = async () => { } } const held = pool.get(convKey) - if (held?.turn && !held.turn.cancelRequested) { + // results under ids the client renamed reach no live call, the + // step it dropped after them included (plugins#1644) + const droppedStep = !found.length && !prefillAfterResults && held?.turn && !held.turn.cancelRequested + ? await keepDroppedStep({ convKey, proc: held, turn: held.turn, messages: body.messages, acquireOpts }) + : null + if (droppedStep === "kept") { + keptSession = true + answeredIds = new Set(resultBlocks.map((block) => block.tool_use_id)) + } else if (droppedStep === "failed") { + acquireOpts.dropReason = "dropped_step" + } else if (held?.turn && !held.turn.cancelRequested) { // No live MCP call waits for these results, but the // conversation's session holds a turn. A turn streaming to // another request is busy for now (503, the client tries diff --git a/opencode2.mjs b/opencode2.mjs index b939308..05bc779 100644 --- a/opencode2.mjs +++ b/opencode2.mjs @@ -507,6 +507,14 @@ async function setupPlugin(ctx, fn, live) { // the account the list was last read for: a credential.updated that // leaves it as it was reads nothing again let readFor = null + // the last list each account's own read gave, by the account it was read + // for: a read that fails (a workspace config answering 503) keeps the + // list that same account last read rather than the bundled one, which + // brought back models its workspace hides (plugins#1642). Another + // account's list is never used, a read that gave an empty list is kept + // as empty, and the bundled list stands in only for an account whose + // list was never read. + const lists = new Map() const stateOf = async () => { const c = await ctx.integration.connection.active(authID).catch(() => undefined) const a = c ? await getAuth(authID) : undefined @@ -523,7 +531,8 @@ async function setupPlugin(ctx, fn, live) { const s = source.get(authID) const connection = await ctx.integration.connection.active(authID).catch(() => undefined) const a = connection ? await getAuth(authID) : undefined - readFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + const readingFor = connKey(connection) + "\0" + (a ? fingerprint(a) : "") + readFor = readingFor if (!a || listID !== authID || typeof hooks.provider?.models !== "function") { if (s.connection || s.models) { s.connection = undefined @@ -544,7 +553,12 @@ async function setupPlugin(ctx, fn, live) { return } s.connection = connection - s.models = got && typeof got === "object" ? Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) : null + if (got && typeof got === "object") { + s.models = Object.entries(got).map(([k, m]) => modelOf(authID, s.prov, k, record(m))) + lists.delete(readingFor) + lists.set(readingFor, s.models) + if (lists.size > 32) lists.delete(lists.keys().next().value) + } else s.models = lists.get(readingFor) ?? null await ctx.provider.reload() await ctx.model?.reload?.() } finally { diff --git a/package.json b/package.json index 8e13289..a8affb5 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.157", + "version": "0.1.159", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", diff --git a/test/dropped-step.mjs b/test/dropped-step.mjs new file mode 100644 index 0000000..425f7ab --- /dev/null +++ b/test/dropped-step.mjs @@ -0,0 +1,163 @@ +// #1644 (Sor85): a client that merges a new message into a running step drops +// the tool call agy had just emitted (B) without storing or running it, and +// sends A's result again with the new message after it. The live session +// answers B as cancelled and takes the new message as its next prompt, as +// #1231 does for a dropped call, instead of replaying the conversation into a +// new session (72K and 81K tokens with no cache in the report). + +import { test } from "node:test" +import assert from "node:assert/strict" +import { baseBody, continueWithToolResults, createBridgeKit, readSse } from "./testkit.mjs" + +globalThis.fetch = () => { throw new Error("offline fixture") } + +const sessions = (kit) => kit.acpLog.filter((entry) => entry.method === "session/new").length + +// The reporter's fixture: A, its result, then B emitted and its response ended. +async function atB(kit, { textBeforeB = "" } = {}) { + const seen = { prompts: [] } + kit.prompts.push(async (agent) => { + await agent.tool("Read", { path: "/fixture/a" }) + if (textBeforeB) await agent.text(textBeforeB) + seen.b = await agent.tool("Read", { path: "/fixture/b" }) + return { stopReason: "end_turn" } + }) + kit.defaultPrompt = async (agent) => { + seen.prompts.push(JSON.stringify(agent.prompt)) + await agent.text("fixture answer") + return { stopReason: "end_turn" } + } + const opening = baseBody() + const a = await readSse(await kit.request(opening)) + assert.equal(a.stopReason, "tool_use") + const original = continueWithToolResults(opening, a, () => "result A") + const b = await readSse(await kit.request(original)) + assert.equal(b.stopReason, "tool_use") + return { seen, a, b, original } +} + +async function withKit(fn) { + const kit = await createBridgeKit({ agentVersion: "1.5.18", sessionResume: true }) + try { return await fn(kit) } finally { await kit.dispose() } +} + +function goesOn(kit, seen, response, b) { + assert.equal(response.stopReason, "end_turn") + assert.equal(sessions(kit), 1, "the live session takes the new message, no replay") + assert.equal(kit.acpSpawns.length, 1) + // B was never run: agy hears it was cancelled, not A's result + assert.equal(seen.b?.result?.isError, true) + assert.match(seen.b.result.content[0].text, /not executed/) + assert.doesNotMatch(seen.b.result.content[0].text, /result A/) + // only the new message is prompted, not the history and not A's result again + assert.equal(seen.prompts.length, 1) + assert.ok(seen.prompts[0].includes("Use this new instruction.")) + assert.ok(!seen.prompts[0].includes("start the task"), "no replay of the history") + assert.ok(!seen.prompts[0].includes("result A"), "A's result went to agy once") + // B is not sent to the client again + assert.ok(!response.content.some((block) => block.type === "tool_use" && block.id === b.content.find((x) => x.type === "tool_use").id)) +} + +test("#1644 the reporter's identical retry still answers with the emitted B in one session", async () => { + await withKit(async (kit) => { + const { b, original } = await atB(kit) + const response = await readSse(await kit.request(structuredClone(original))) + assert.equal(sessions(kit), 1) + assert.deepEqual(response.content, b.content) + }) +}) + +test("#1644 A's result again with a new user message: B is cancelled and the session goes on", async () => { + await withKit(async (kit) => { + const { seen, b, original } = await atB(kit) + const retry = structuredClone(original) + retry.messages.push({ role: "user", content: "Use this new instruction." }) + const response = await readSse(await kit.request(retry)) + goesOn(kit, seen, response, b) + + // the session's history is now the client's: the next turn goes on in it + const next = structuredClone(retry) + next.messages.push({ role: "assistant", content: response.content.map((x) => ({ type: "text", text: x.text })) }, { role: "user", content: "and again" }) + const again = await readSse(await kit.request(next)) + assert.equal(again.stopReason, "end_turn") + assert.equal(sessions(kit), 1) + }) +}) + +test("#1644 the new instruction merged into the tool result's own message goes on the same way", async () => { + await withKit(async (kit) => { + const { seen, b, original } = await atB(kit) + const retry = structuredClone(original) + retry.messages.at(-1).content.push({ type: "text", text: "Use this new instruction." }) + const response = await readSse(await kit.request(retry)) + goesOn(kit, seen, response, b) + }) +}) + +test("#1644 with ids the client renamed (a Gemini client), the session goes on too", async () => { + await withKit(async (kit) => { + const { seen, b, original } = await atB(kit) + const retry = structuredClone(original) + const assistantA = retry.messages.at(-2) + const use = assistantA.content.find((x) => x.type === "tool_use") + const result = retry.messages.at(-1).content.find((x) => x.type === "tool_result") + use.id = "toolu_renamed_by_client" + result.tool_use_id = use.id + retry.messages.push({ role: "user", content: "Use this new instruction." }) + const response = await readSse(await kit.request(retry)) + goesOn(kit, seen, response, b) + }) +}) + +test("#1644 A's result changed beside the new message is still a conflict, never handed to B", async () => { + await withKit(async (kit) => { + const { seen, original } = await atB(kit) + const retry = structuredClone(original) + retry.messages.at(-1).content[0].content = "a different result A" + retry.messages.push({ role: "user", content: "Use this new instruction." }) + const res = await kit.request(retry) + assert.equal(res.status, 409) + await res.text() + assert.equal(seen.b, undefined, "B got no answer") + }) +}) + +test("#1644 a B step that said something first is a fork the client never had: replayed as before", async () => { + await withKit(async (kit) => { + const { original } = await atB(kit, { textBeforeB: "Now the second file." }) + const retry = structuredClone(original) + retry.messages.push({ role: "user", content: "Use this new instruction." }) + const response = await readSse(await kit.request(retry)) + assert.equal(response.stopReason, "end_turn") + assert.equal(sessions(kit), 2) + }) +}) + +test("#1644 a client that kept B and answers it with text after goes on as a steer, not a drop", async () => { + await withKit(async (kit) => { + const { seen, b, original } = await atB(kit) + const next = continueWithToolResults(original, b, () => "result B") + next.messages.at(-1).content.push({ type: "text", text: "Use this new instruction." }) + const response = await readSse(await kit.request(next)) + assert.equal(response.stopReason, "end_turn") + assert.equal(sessions(kit), 1) + assert.equal(seen.b?.result?.content?.[0]?.text, "result B") + }) +}) + +test("#1644 renamed ids with A's result changed are not taken as the dropped step", async () => { + await withKit(async (kit) => { + const { seen, original } = await atB(kit) + const retry = structuredClone(original) + const use = retry.messages.at(-2).content.find((x) => x.type === "tool_use") + const result = retry.messages.at(-1).content.find((x) => x.type === "tool_result") + use.id = "toolu_renamed_by_client" + result.tool_use_id = use.id + result.content = "a different result A" + retry.messages.push({ role: "user", content: "Use this new instruction." }) + const response = await readSse(await kit.request(retry)) + assert.equal(response.stopReason, "end_turn") + assert.equal(sessions(kit), 2, "replayed with the client's own result") + assert.doesNotMatch(seen.b?.result?.content?.[0]?.text ?? "", /not executed|result A/) + }) +}) From 5894d81adb869a4d05baec7b48d5af496e0de1a7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B4=94=E7=81=BF?= Date: Sat, 28 Nov 2026 20:11:22 +0800 Subject: [PATCH 3/4] upstream agy-cli 0.1.160 (magpie-community/plugins@7d85fba7304394edd6b97d87c03cfb37e00f7654) --- README.en.md | 10 ++++++++++ README.md | 3 ++- index.mjs | 12 +++++++++--- package.json | 2 +- test/web-search.mjs | 30 ++++++++++++++++++++++++++++++ 5 files changed, 52 insertions(+), 5 deletions(-) diff --git a/README.en.md b/README.en.md index 9c82180..9ef7afd 100644 --- a/README.en.md +++ b/README.en.md @@ -135,6 +135,16 @@ MCP server. The control port listens on loopback only, with a token per process. (SillyTavern presets, "continue"/"impersonate", bot frameworks) are served instead of rejected; the session ledger stays aligned across turns. See "Assistant prefill" below. +- **Web search**: the plugin gives Magpie's web search `agy-cli:agy` + (`magpie search add agy-cli`), through agy's own `search_web`: it opens an + agy session whose one tool is `search_web`, asks it for the query, reads the + summary and sources from the step output agy keeps, and cancels the turn, so + the model writes no answer. agy runs the search on Google's side; the plugin + never calls Google itself. Each result's title is its source's domain, its + link is Google's redirect (as agy gives it), and its text is what the summary + says citing that source. A search as an account uses that account's agy + sign-in. When `search_web` failed, never ran, or ran and left no source to + read, the search is an error that says which (since 0.1.160). - **Usage visibility**: Magpie shows the agy subscription usage windows. Each model's window (its pool's most used one) is what Magpie's routing weighs the account by for that model, so a routing group puts it by what it has left, diff --git a/README.md b/README.md index 2dce926..37c6245 100644 --- a/README.md +++ b/README.md @@ -92,7 +92,8 @@ agy 连接 `--ide-mcp-port` 时会运行 `nc 127.0.0.1 <端口>`。插件在 agy 从 agy 保存的这一步输出里读出摘要和来源,然后取消这一轮,模型不写回答。搜索由 agy 在 Google 那边完成,插件不直接请求 Google。每条结果的标题是来源的域名,链接是 Google 的 跳转地址(agy 给出的就是这样),正文是摘要里引用这个来源的句子。按账号搜索时,用的是 - 这个账号的 agy 登录。 + 这个账号的 agy 登录。`search_web` 失败、没有运行,或运行了但没留下可读的来源时, + 搜索返回错误并说明是哪一种(0.1.160 起)。 - **额度查看**:在 Magpie 里查看 agy 订阅的用量窗口。每个模型的窗口(它所在额度池用得最多的那个)也是 Magpie 路由给这个模型排账号的依据:路由组按剩余额度排它,额度池用完的模型会让给下一个成员。agy 的 `/usage` 报告不带账号套餐,所以不显示套餐。 ## 助手预填(assistant prefill) diff --git a/index.mjs b/index.mjs index 1d736b6..2fe9108 100644 --- a/index.mjs +++ b/index.mjs @@ -1128,11 +1128,17 @@ async function searchAsAccount(query, count, email, abort) { if (!output) await new Promise((resolve) => setTimeout(resolve, 100)) } if (how !== "ended") conn.notify("session/cancel", { sessionId }) - if (!output) { - const why = how === "failed" ? "agy's search_web failed" : "agy didn't search the web" + // a search that ran but left no source to read is said as that, not + // as no search: its step output had no "Sources:" (agy found none), or + // none of its lines read as one (plugins#1675) + const pages = output ? pagesOfSearchWeb(output, count) : [] + if (!pages.length) { + const why = how === "failed" ? "agy's search_web failed" + : how === "completed" || output ? "agy's search_web found no sources" + : "agy didn't search the web" throw new Error(stderr.trim() ? `${why}: ${stderr.trim().slice(-300)}` : why) } - return pagesOfSearchWeb(output, count) + return pages })()]) } finally { clearTimeout(timer) diff --git a/package.json b/package.json index a8affb5..272c5c6 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-agy-cli-auth", - "version": "0.1.159", + "version": "0.1.160", "description": "Magpie/OpenCode model provider that connects your local agy CLI through the Agent Client Protocol (agy acp), so Antigravity subscription models run through the real CLI", "type": "module", "main": "./opencode.mjs", diff --git a/test/web-search.mjs b/test/web-search.mjs index 29d79c9..3be7c3a 100644 --- a/test/web-search.mjs +++ b/test/web-search.mjs @@ -107,6 +107,36 @@ test("a turn that searched nothing is an error, not an empty list", async () => }) }) +// plugins#1675: a search_web that failed, or ran and left no source to +// read, is an error that says so, never pages without a source +test("a search_web that failed is an error that says so", async () => { + await withKit(async (kit) => { + kit.defaultPrompt = async (agent) => { + agent.update({ sessionUpdate: "tool_call", toolCallId: "c1", name: "search_web", args: { query: "q" }, status: "in_progress", kind: "search" }) + agent.update({ sessionUpdate: "tool_call_update", toolCallId: "c1", name: "search_web", status: "failed", kind: "search" }) + await agent.waitCancel() + return { stopReason: "cancelled" } + } + await assert.rejects(kit.plugin.search.agy.execute({ query: "x" }, {}), /agy's search_web failed/) + assert.ok(kit.acpLog.some((e) => e.method === "session/cancel")) + }) +}) + +test("a search_web that ran and left no source to read is an error that says so", async () => { + // no "Sources:" in the step output, and a "Sources:" none of whose lines + // reads as a source + const summary = OUTPUT.slice(0, OUTPUT.lastIndexOf("\nSources:\n") + 1) + for (const output of [summary, summary + "\nSources:\nnothing to read here\n"]) { + await withKit(async (kit) => { + searches(kit, output) + const error = await kit.plugin.search.agy.execute({ query: "x" }, {}).catch((e) => e) + assert.ok(error instanceof Error) + assert.match(error.message, /agy's search_web found no sources/) + assert.doesNotMatch(error.message, /didn't search/) + }) + } +}) + test("agy not signed in is the account refused, for magpie to rest", async () => { await withKit(async (kit) => { const error = await kit.plugin.search.agy.execute({ query: "x" }, {}).catch((e) => e) From ce9a336239d1384aa84dd3c575f32d773333fa57 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=B4=94=E7=81=BF?= Date: Sat, 28 Nov 2026 20:24:02 +0800 Subject: [PATCH 4/4] docs: video patch is now a converter onto upstream 0.1.155's media input Co-Authored-By: Claude Opus 5.5 --- .claude/skills/agy-cli-fork/SKILL.md | 19 +++++++++---------- FORK.md | 22 +++++++++++----------- fork/fork.sh | 2 +- 3 files changed, 21 insertions(+), 22 deletions(-) diff --git a/.claude/skills/agy-cli-fork/SKILL.md b/.claude/skills/agy-cli-fork/SKILL.md index 1f2bab6..6845d02 100644 --- a/.claude/skills/agy-cli-fork/SKILL.md +++ b/.claude/skills/agy-cli-fork/SKILL.md @@ -31,14 +31,12 @@ fork/fork.sh sync # 默认合并上游 main;也可以指定 ref:for 有冲突时: -- 补丁的标记是 `Video (local patch)`、`videoOn`、`mediaDir`、`videoizeBody`、`dropReadVideo`、`sniffVideo`、`privateAddress`,以及 `fetchVideo`、`videoBlock`。 -- 补丁一共挂在上游的 6 个位置: - 1. `import dns from "node:dns"` - 2. `FORWARD_THINKING` 后面的整段 helper - 3. `agentDefinition()` 里的 `tools:` 那一行 - 4. `#spawn` 里 `--add-dir` 那一行后面 - 5. `#onNotification` 开头那一行 - 6. fetch 里 `body = await videoizeBody(JSON.parse(raw))` +- 视频补丁(`Video (local patch)`)从 0.1.160 起只是一层转换,挂在 3 个位置: + 1. `import dns from "node:dns"`; + 2. `FORWARD_THINKING` 后面的整段 helper(`videoOn` 到 `videoizeBody`); + 3. fetch 里 `body = await videoizeBody(JSON.parse(raw))`。 + + 媒体落盘、`tools: [view_file]`、`--add-dir` 都是上游的,冲突时一律用上游的。`fork/patch-e2e.mjs` 的视频用例可以验证(`AGY_BRIDGE_VIDEO=0` 时它应该失败)。 - 重发接上原回合(`Retry attach (local patch)`),挂在五个位置: 1. `streamResponse` 前面的 `retryKey`、`retryResponse` 两个函数,以及 `streamResponse` 里给 `turn.retry` 赋值的那一行; 2. `makeAnthropicStream` 开头取 `const retry = turn.retry`; @@ -48,7 +46,7 @@ fork/fork.sh sync # 默认合并上游 main;也可以指定 ref:for `fork/patch-e2e.mjs` 的两个 retry 用例可以验证。容量不足改 503 的补丁上游 0.1.95 已自带,不再是我们的补丁;`patch-e2e.mjs` 里的 busy 用例留着当回归测试。 - 工具被拒后回空的修复(`Denied ending (local patch)`),挂在四个位置: - 1. `agentDefinition()` 末尾,`videoOn()` 时多加一行,说明 `read_file` 只能读媒体目录; + 1. `agentDefinition()` 末尾,`media` 时多加一行,说明 `view_file` 只能读附带的媒体; 2. `#onRequest` 的拒绝分支,在 `deniedPermissions++` 后面记下 `turn.denied`; 3. `Turn.emitText` 开头清掉 `this.denied`; 4. `#runTurn` 里 `turn.flushText()` 之后:`turn.denied` 还在、并且这期间没有新的客户端工具调用时,抛出 `AgentTurnError`。 @@ -60,7 +58,8 @@ fork/fork.sh sync # 默认合并上游 main;也可以指定 ref:for 3. 同一函数里,上游 `lineageVerdict` 那段之前插入的 `laneWanted` 分支,以及上游 `superseded` 事件后面的 `noteSuperseded`;`findLiveContinuedProc` 的条件多了 `key === convKey`,`why` 先取 `laneWhy`,`takeParked` 用 `key`; 4. `recoverStaleTurn` 里 `current` 按 `ctx.proc.convKey` 取,重放时带 `laneKey`; 5. fetch 里 Retry attach 的入口:在整组通道里找正在跑的那一轮; - 6. fetch 里 409 分支的 `held` 改用 `heldFor(convKey, acquireOpts, resultBlocks)`。 + 6. fetch 里 409 分支的 `held` 改用 `heldFor(convKey, acquireOpts, resultBlocks)`; + 7. `keepDroppedStep`(上游 0.1.158)里 `pool.get(proc.convKey)`,通道进程按自己的键存。 `fork/patch-e2e.mjs` 的四个 lanes 用例可以验证;设 `LANES_PROBE=1` 再跑这几个用例,它们应该失败(409、503、409),说明用例确实能抓到上游行为。上游测试经 `test/testkit.mjs` 跑,那里的环境变量是隔离的;分叉在 testkit 里放行了 `AGY_BRIDGE_VIDEO`、`AGY_BRIDGE_MAX_LANES`、`AGY_BRIDGE_THINKING_WHEN_DISABLED` 三个开关(用例自己的 `env` 优先),`fork/fork.sh test` 跑上游测试时把它们都设成上游行为。上游 0.1.106 的 `test/unmatched-results.mjs` 要求“对方正在出流时,对不上的工具结果回 503”,并行通道打开时这里会开通道重放(200),所以上游测试要在 `AGY_BRIDGE_MAX_LANES=1` 下跑。改 `test/testkit.mjs` 的那几行合并上游时可能冲突,按原样接回。 - thinking 关闭时照样转发思考(`Thinking when disabled (local patch)`),挂在三个位置: diff --git a/FORK.md b/FORK.md index 5cbcb9b..1ba2e75 100644 --- a/FORK.md +++ b/FORK.md @@ -4,10 +4,10 @@ 和上游相比多五处改动,都在 `index.mjs` 里(“容量不足报错改为 503”上游 0.1.95 已经自带,分叉里那份已删除): -1. **视频输入**:Gemini 能原生看视频,画面和声音都能处理。代码里搜 `Video (local patch)`。 +1. **视频输入(OpenAI 写法和链接)**:上游 0.1.155 起自带视频/音频输入,但只收 `video`/`audio` 块里的 base64,链接一律 400。补丁把 `image_url` 里的视频(`data:video/…` 或 http(s) 链接)和链接形式的 `video` 块转成上游的 base64 `video` 块,之后全走上游。代码里搜 `Video (local patch)`。 2. **重发的请求接上原来那一轮**:客户端等不到首字就断开,把同一份请求再发一遍,而原请求还在跑;或者原请求的回复(一次工具调用)在路上丢了。上游插件对这种重发返回错误(0.1.106 之前一律是 409 `no active MCP call matches these tool results`,0.1.106 起原请求还在出流时是 503),要等原来那一轮结束才变,而原请求照常跑完并计费,产出没人收。现在重发的请求会等原请求出结果,拿到同一份回复,用量记 0,不重复计费。原请求失败或被取消时,重发的请求收到 503,客户端再发一次就会重新跑。已经正常结束、没有待答工具调用的回复不走这条路,再发一遍仍然重新生成。带工具结果的请求、原请求已经结束时,交给上游 0.1.131 的 `replay_tool_step`(比对整份请求的摘要,回放同一个消息 id);本补丁只接原请求还在跑的重发,以及不带工具结果的请求丢了回复的重发。代码里搜 `Retry attach (local patch)`。 -3. **工具被拒后不再回空**:开放 `read_file` 以后,模型有时会拿它去读客户端机器上的路径,比如 ZCode 用户 Mac 上的 `~/.zcode/...`。这个工具在服务器上跑,读媒体目录以外的路径要先申请权限,插件会拒绝;agy 被拒后就直接结束这一轮。上游插件把这样的结束原样交给客户端,结果是空正文、没有工具调用,客户端看上去就是卡住不动。现在改成两处: - - agent 说明里写明 `read_file` 只能读附带的视频,其他文件用客户端的工具读。 +3. **工具被拒后不再回空**:带视频的会话开放 `view_file` 以后,模型有时会拿它去读客户端机器上的路径,比如 ZCode 用户 Mac 上的 `~/.zcode/...`。这个工具在服务器上跑,读会话目录以外的路径要先申请权限,插件会拒绝;agy 被拒后就直接结束这一轮。上游插件把这样的结束原样交给客户端,结果是空正文、没有工具调用,客户端看上去就是卡住不动。现在改成两处: + - 带视频的会话,agent 说明里写明 `view_file` 只能读附带的视频或音频,其他文件用客户端的工具读。 - 一轮在被拒的工具上结束、之后既没有正文也没有客户端工具调用时,返回 `api_error`,错误信息写明是哪个工具被拒、为什么被拒。 代码里搜 `Denied ending (local patch)`。 4. **同一对话的并行线各用各的 agy 进程**:插件按“user_id + system + 第一条消息”认对话,一个对话只有一个 agy 进程。有的客户端在同一个会话里同时跑两条线,比如 ZCode 带着整份主对话另跑一个有工具调用的后台任务,两条线这三样都一样。上游会让后到的那条抢掉对方挂着的工具轮,或者让它等对方出完流(503 `this conversation still has an unfinished response`);被抢的一方送回工具结果时,0.1.106 之前收到 409 `no active MCP call matches these tool results`;0.1.106 起改为重放,但会反过来抢掉对方挂着的那一轮,对方正在出流时则回 503。两条线来回互抢,每抢一次都要重放整份历史。现在: @@ -22,12 +22,13 @@ ## 为什么要绕一圈 -agy 1.5.9 的 ACP 不收视频:用 image 块发会报 `unsupported mimeType`,用 resource blob 发会被 `unsupported blob type` 丢掉。agy 自带的 `read_file` 却能把视频文件原生交给 Gemini。补丁的做法: +agy 的 ACP 不收视频(image 块报 `unsupported mimeType`,resource blob 被 `unsupported blob type` 丢掉),只有它自己读文件的工具能把视频原生交给 Gemini。上游 0.1.155 的做法:把 `video`/`audio` 块写到会话工作区的 `attachments/.`,prompt 里叫模型去读,只有带媒体的会话才有 `tools: [view_file]`,并且不加 `--add-dir`、把 TMPDIR 指到会话工作区,`view_file` 读不到别的目录。 + +补丁只在这之前做转换: 1. 客户端把视频当作图片发过来。OpenAI 协议写 `image_url`,值可以是 `data:video/mp4;base64,…`,也可以是 http(s) 链接。Magpie 会原样转成 `image` 块交给插件。 -2. 插件把视频写到 `~/.local/state/magpie-agy-bridge/media/.`,并在 prompt 里告诉模型“视频在这个路径,用 read_file 读”。 -3. agent 改成 `tools: [read_file]`,用 `--add-dir` 把 media 目录加进工作区。这样读文件不会弹权限请求。 -4. agy 读完时会发出 `tool_call completed`,插件收到后马上删掉自己写的文件。agy 会在 `brain/<会话>/.system_generated/logs/media/` 里留一份副本,多轮对话靠它继续。 +2. base64 的直接改成 `video` 块。链接先下载(只认识别得出的视频,或 `Content-Type: video/*`),缓存在 `~/.local/state/magpie-agy-bridge/media/`,同一个链接在后面的历史里再出现时读缓存,一小时没用的缓存在下次下载时清掉。 +3. 之后由上游写文件、开 `view_file`、拒绝非 Gemini 模型。 ## 用法 @@ -38,18 +39,17 @@ agy 1.5.9 的 ACP 不收视频:用 image 块发会报 `unsupported mimeType` | 环境变量 | 默认 | 作用 | |---|---|---| -| `AGY_BRIDGE_VIDEO` | 开启 | 设为 `0` 时退回上游行为(`tools: []`,不处理视频) | +| `AGY_BRIDGE_VIDEO` | 开启 | 设为 `0` 时退回上游行为(只收 `video`/`audio` 块的 base64) | | `AGY_BRIDGE_VIDEO_PRIVATE` | 关闭 | 设为 `1` 时允许下载内网或本机地址的视频链接。只在可信内网里用 | | `AGY_BRIDGE_MAX_LANES` | 3 | 一个对话最多同时用几个 agy 进程(并行通道)。设为 `1` 退回上游的一个对话一个进程 | | `AGY_BRIDGE_THINKING_WHEN_DISABLED` | 开启 | 请求写了 `thinking: {type: "disabled"}` 时仍转发思考。设为 `0` 退回上游行为(丢掉思考) | | `AGY_BRIDGE_DISABLED_EFFORT` | `low` | `thinking: {type: "disabled"}` 且没带 `output_config.effort` 时选的档位。设为 `0` 退回上游行为(模型默认档,通常是 high) | 限制: -- 单个视频最大 100 MB,这是 agy `read_file` 的上限。下载超时 120 秒,最多跟 3 次重定向。 +- 链接下载的视频最大 100 MB。下载超时 120 秒,最多跟 3 次重定向。 - 链接只允许 http(s),解析出的 IP 是内网、回环或链路本地地址时一律拒绝(400)。 - 下载前会检查一次 DNS,但检查完到真正下载之间如果 DNS 被改指(DNS rebinding),这种情况防不住。 -- 开启后,模型可以用 `read_file` 直接读 agy 工作区里的文件,包括客户端的项目目录。上游插件“只桥接客户端工具”的隔离因此变宽了。 -- agy 的副本插件不会清理。 +- 下载缓存插件按一小时清理;上游写在会话工作区的 `attachments/` 随会话走。 ## 安装 diff --git a/fork/fork.sh b/fork/fork.sh index 7bf9764..2bb453a 100755 --- a/fork/fork.sh +++ b/fork/fork.sh @@ -136,7 +136,7 @@ sync() { if ! git merge --no-edit upstream; then echo echo "合并有冲突(见上)。解决后 git add + git commit,再跑 fork/fork.sh test。" - echo "冲突里搜 videoOn / mediaDir / dropReadVideo / videoizeBody,就是我们的补丁。" + echo "冲突里搜 local patch,就是我们的补丁;位置见 .claude/skills/agy-cli-fork/SKILL.md 第 2 节。" exit 1 fi run_tests