From 3781c50f521ddee34bb717fd98263b6b2bb99c5f Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 16 Nov 2026 15:04:00 +0800 Subject: [PATCH] agy-cli 0.1.76: a URL or text document goes to agy as text, not a 400 daoche_wuzui on X (magpie 0.1.4264): URL context through agy-cli failed with "a binary or URL document block in a user message (agy's ACP prompt accepts text and images only) is not supported". The bridge turned away every document that wasn't a text source. agy 1.5.9's initialize says promptCapabilities {image, embeddedContext}, and its binary has only messages.EmbeddedResource.InlineText: an embedded resource reaches the model as inline text, so a binary file can't be carried. What can, now is (documents.mjs): - a URL document (http/https): its URL, said to be unread, so the model fetches it with the client's tools instead of guessing; - a base64 document of a text type (text/*, JSON, XML): its decoded text, when it is valid UTF-8; - a PDF or other binary inside a tool_result (Claude Code's Read of a PDF): a note that it couldn't be attached and to extract its text with a tool, so the turn goes on instead of failing. Still refused, with what to do: a PDF attached to the user message ("paste the document's text, attach its pages as images, or let the agent read the file with a tool"), a Files API file_id (send it inline), a non-http URL. There is no PDF-to-text helper here or in magpie to extract it with. Neither note names agy, the bridge or magpie. Run at this tree (mica, HOME=$(mktemp -d)): packages/agy-cli bun test 37 pass 0 fail (new test/documents-unit.mjs, 15 checks); smoke ALL OK (381 checks); bun scripts/check.mjs agy-cli ok. Broken by hand: smoke with 0.1.75's index.mjs: 3 FAILURES (the URL/text document, the PDF 400's hint, the PDF in a tool_result). Not tried: a real agy model. The owner's agy account answers "This service has been disabled in this account for violation of Terms of Service", so the fix was checked against the fake agy only. The reporter's client isn't named in the tweet. --- packages/agy-cli/README.en.md | 7 +- packages/agy-cli/README.md | 5 +- packages/agy-cli/agy-cli.test.mjs | 6 ++ packages/agy-cli/documents.mjs | 84 ++++++++++++++++++++++++ packages/agy-cli/index.mjs | 28 +++----- packages/agy-cli/package.json | 1 + packages/agy-cli/test/documents-unit.mjs | 45 +++++++++++++ packages/agy-cli/test/smoke.mjs | 42 +++++++++++- packages/agy-cli/test/testkit.mjs | 3 + 9 files changed, 200 insertions(+), 21 deletions(-) create mode 100644 packages/agy-cli/documents.mjs create mode 100644 packages/agy-cli/test/documents-unit.mjs diff --git a/packages/agy-cli/README.en.md b/packages/agy-cli/README.en.md index ef322ef..a6cfc96 100644 --- a/packages/agy-cli/README.en.md +++ b/packages/agy-cli/README.en.md @@ -330,7 +330,12 @@ off unless you turn it on. measurable data. For a version error, upgrade agy to 1.1.11 or later. - **Image requests return HTTP 400**: the running agy does not advertise image support (1.5.0 or later is needed). Only inline base64 is accepted; image URLs - and binary documents such as PDFs are rejected. + are rejected. +- **Documents**: agy reads text and images only. A text document (plain text, + base64 text/JSON/XML) goes as its text, and a URL document goes as its URL, + for the model to fetch with a tool. A PDF read by a tool reaches the model as + a note to extract its text another way; a PDF attached to the message itself + gets HTTP 400 saying so. Paste its text or attach its pages as images instead. - **A reply contains "Agent execution terminated due to error."**: that is agy's in-band error marker. The plugin reads the real cause from agy's log and ends the turn with an error instead of passing the marker through as text. agy diff --git a/packages/agy-cli/README.md b/packages/agy-cli/README.md index 37b2b78..53cab83 100644 --- a/packages/agy-cli/README.md +++ b/packages/agy-cli/README.md @@ -237,7 +237,10 @@ agy 自己的系统提示词,只剩插件的一行工具说明和客户端的 - **额度显示 "Limits not available" 或报版本错误**:该窗口没有可测量的数据;版本错误则 把 agy 升级到 1.1.11 以上。 - **图片请求返回 HTTP 400**:当前 agy 没有声明图片能力(需要 1.5.0 以上)。另外只接受 - 内联 base64,URL 图片和 PDF 等二进制文档都会被拒绝。 + 内联 base64,URL 图片会被拒绝。 +- **文档**:agy 只读文字和图片。文本文档(纯文本,或 base64 的文本/JSON/XML)按文字发过去; + URL 文档发的是网址,由模型用工具去取。工具读到的 PDF 会变成一条说明,提示模型换个方式 + 提取文字;直接附在消息里的 PDF 返回 HTTP 400 并说明原因,请改为粘贴文字或把页面作为图片附上。 - **回复里出现 "Agent execution terminated due to error."**:这是 agy 的错误标记。插件会 从 agy 的日志中取出真实原因,并以错误结束本轮,不会当作正常回复输出。agy 1.5.8 的 "There was a network issue connecting to the server" 和 "Your AI credits balance is diff --git a/packages/agy-cli/agy-cli.test.mjs b/packages/agy-cli/agy-cli.test.mjs index 875dcb8..f96a9b4 100644 --- a/packages/agy-cli/agy-cli.test.mjs +++ b/packages/agy-cli/agy-cli.test.mjs @@ -58,3 +58,9 @@ test("test/array-items-unit.mjs", () => { expect(output).toMatch(/ALL OK/) expect(code).toBe(0) }, 70_000) + +test("test/documents-unit.mjs", () => { + const { code, output } = run([path.join(dir, "documents-unit.mjs")], 60_000) + expect(output).toMatch(/ALL OK/) + expect(code).toBe(0) +}, 70_000) diff --git a/packages/agy-cli/documents.mjs b/packages/agy-cli/documents.mjs new file mode 100644 index 0000000..31845e6 --- /dev/null +++ b/packages/agy-cli/documents.mjs @@ -0,0 +1,84 @@ +// An Anthropic document block, as text for agy's ACP prompt. agy takes text +// and images: an embedded resource reaches the model as its inline text +// only, so a PDF or other binary file can't be handed over as it is. +// +// - a text source, or a content list of text parts: the text; +// - a base64 source of a text type (text/*, JSON, XML): the decoded text; +// - a URL source: the URL, said to be unread, so the model can fetch it +// with a tool instead of guessing what it says (daoche_wuzui on X: a +// client's URL document turned the whole request away); +// - a binary file in a tool result (a client's file read of a PDF): a note +// that it couldn't be attached, so the model can read it another way +// instead of the whole turn failing. +// +// documentText returns null for what can't be carried: a binary file the +// user attached, and a file id from the Files API. The caller refuses it +// with documentRefusal's words. + +import { Buffer } from "node:buffer" +import { TextDecoder } from "node:util" + +const TEXT_TYPES = /^(?:text\/[\w.+-]+|application\/(?:[\w.+-]+\+)?(?:json|xml))$/ + +function decodeBase64Text(data) { + if (typeof data !== "string" || !/^[A-Za-z0-9+/\s]*={0,2}\s*$/.test(data)) return null + try { + return new TextDecoder("utf-8", { fatal: true }).decode(Buffer.from(data, "base64")) + } catch { + return null + } +} + +function mediaTypeOf(src) { + return String(src?.media_type || "").toLowerCase().split(";")[0].trim() +} + +function titleOf(block) { + return typeof block.title === "string" && block.title.trim() ? block.title.trim() : "" +} + +export function documentText(block, { inToolResult = false } = {}) { + if (block?.type !== "document") return "" + const title = titleOf(block) + const src = block.source + let text = null + if (src?.type === "text" && typeof src.data === "string") { + text = src.data + } else if (src?.type === "content") { + if (typeof src.content === "string") { + text = src.content + } else if (Array.isArray(src.content) && src.content.every((part) => part?.type === "text" && typeof part.text === "string")) { + text = src.content.map((part) => part.text).join("\n") + } + } else if (src?.type === "base64" && TEXT_TYPES.test(mediaTypeOf(src))) { + text = decodeBase64Text(src.data) + } else if (src?.type === "url" && typeof src.url === "string" && /^https?:\/\//i.test(src.url.trim())) { + const url = src.url.trim() + return `[document${title ? ": " + title : ""} at ${url}; its content is not attached here. Fetch the URL with a tool to read it.]` + } + if (text !== null) return title ? `[document: ${title}]\n${text}\n[end of document]` : text + if (inToolResult && src?.type === "base64") { + const kind = mediaTypeOf(src) === "application/pdf" ? "a PDF" : `a ${mediaTypeOf(src) || "binary"} file` + return `[document${title ? ": " + title : ""}: ${kind} that could not be attached here. Extract its text with a tool (pdftotext, say) to read it.]` + } + return null +} + +// documentRefusal says what was turned away and what the user can do. +export function documentRefusal(block) { + const src = block?.source + if (src?.type === "file") { + return { + what: "a document sent as a Files API file_id", + hint: "agy can't fetch it; send the document inline, as text or base64", + } + } + if (src?.type === "url") { + return { what: "a document URL other than http(s)", hint: "send an http(s) URL, or the document's text" } + } + const type = mediaTypeOf(src) + return { + what: `a ${type === "application/pdf" ? "PDF" : (type || "binary") + " file"} attached as a document`, + hint: "agy reads text and images, not PDFs or other files. Paste the document's text, attach its pages as images, or let the agent read the file with a tool", + } +} diff --git a/packages/agy-cli/index.mjs b/packages/agy-cli/index.mjs index aad7349..9ba5abd 100644 --- a/packages/agy-cli/index.mjs +++ b/packages/agy-cli/index.mjs @@ -15,6 +15,7 @@ import { startLogin } from "./login.mjs" import { accountsDir, currentHome, dropHome, homeIdOfAuth, homeOf, inAccount, newHome, tokenFile } from "./account.mjs" import { IMPORT_FROM, importedAccounts, tokenFileText } from "./import.mjs" import { AGY_MANUAL, installAgy, keepAgyCurrent } from "./install.mjs" +import { documentRefusal, documentText } from "./documents.mjs" import { ensureGeminiArrayItems } from "./array-items.mjs" import { expandToolSchema } from "./tool-schema.mjs" import { processExists } from "./proc.mjs" @@ -1011,8 +1012,8 @@ class ConflictError extends Error { } class UnsupportedContent extends Error { - constructor(what) { - super(`agy bridge: ${what} is not supported`) + constructor(what, hint) { + super(`agy bridge: ${what} is not supported${hint ? `. ${hint}` : ""}`) this.statusCode = 400 } } @@ -3599,24 +3600,14 @@ function parseUserImage(block) { return imageContent({ ...block, source: { ...block.source, media_type: mediaType === "image/jpg" ? "image/jpeg" : mediaType } }) } -function parseUserDocumentText(block) { +function parseUserDocumentText(block, inToolResult = false) { if (block?.type !== "document") return "" - const title = typeof block.title === "string" && block.title.trim() ? block.title.trim() : "" - const src = block.source - let text = null - if (src?.type === "text" && typeof src.data === "string") { - text = src.data - } else if (src?.type === "content") { - if (typeof src.content === "string") { - text = src.content - } else if (Array.isArray(src.content) && src.content.every((part) => part?.type === "text" && typeof part.text === "string")) { - text = src.content.map((part) => part.text).join("\n") - } - } + const text = documentText(block, { inToolResult }) if (text === null) { - throw new UnsupportedContent("a binary or URL document block in a user message (agy's ACP prompt accepts text and images only)") + const { what, hint } = documentRefusal(block) + throw new UnsupportedContent(what, hint) } - return title ? `[document: ${title}]\n${text}\n[end of document]` : text + return text } function parseSearchResultText(block) { @@ -4524,6 +4515,7 @@ function blockText(block) { const inner = Array.isArray(block.content) ? block.content.map((part) => { if (part?.type === "image") return "[image returned by tool]" + if (part?.type === "document") return parseUserDocumentText(part, true) return blockText(part) }).join("") : String(block.content ?? "") @@ -5185,7 +5177,7 @@ function toolResult(block) { if (part?.type === "tool_reference" && typeof part.tool_name === "string") { return { type: "text", text: `Loaded tool: ${part.tool_name}` } } - if (part?.type === "document") return { type: "text", text: parseUserDocumentText(part) } + 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 { diff --git a/packages/agy-cli/package.json b/packages/agy-cli/package.json index 9e38935..b7fda79 100644 --- a/packages/agy-cli/package.json +++ b/packages/agy-cli/package.json @@ -10,6 +10,7 @@ "files": [ "proc.mjs", "index.mjs", + "documents.mjs", "opencode.mjs", "opencode2.mjs", "platform.mjs", diff --git a/packages/agy-cli/test/documents-unit.mjs b/packages/agy-cli/test/documents-unit.mjs new file mode 100644 index 0000000..cb8611c --- /dev/null +++ b/packages/agy-cli/test/documents-unit.mjs @@ -0,0 +1,45 @@ +// Standalone checks for documents.mjs. Run with: +// node test/documents-unit.mjs +import { documentRefusal, documentText } from "../documents.mjs" + +let failed = 0 +function check(name, ok, detail) { + if (ok) { + console.log(`ok ${name}`) + return + } + failed++ + console.error(`FAIL ${name}${detail ? " :: " + detail : ""}`) +} + +const b64 = (s) => Buffer.from(s).toString("base64") +const doc = (source, title) => ({ type: "document", source, ...(title ? { title } : {}) }) +const pdf = doc({ type: "base64", media_type: "application/pdf", data: "JVBERi0xLjQK" }, "paper.pdf") + +check("a text source is its text", documentText(doc({ type: "text", media_type: "text/plain", data: "HELLO" })) === "HELLO") +check("a titled text source is framed", documentText(doc({ type: "text", data: "HELLO" }, "a.txt")) === "[document: a.txt]\nHELLO\n[end of document]") +check("a content list of text parts is joined", documentText(doc({ type: "content", content: [{ type: "text", text: "a" }, { type: "text", text: "b" }] })) === "a\nb") +check("a base64 text/plain source is decoded", documentText(doc({ type: "base64", media_type: "text/plain", data: b64("PLAIN ünïcode") })) === "PLAIN ünïcode") +check("a base64 JSON source is decoded", documentText(doc({ type: "base64", media_type: "application/json; charset=utf-8", data: b64('{"a":1}') })) === '{"a":1}') +check("a base64 text source that isn't UTF-8 is not passed as text", documentText(doc({ type: "base64", media_type: "text/plain", data: Buffer.from([0xff, 0xfe, 0x00]).toString("base64") })) === null) + +const url = documentText(doc({ type: "url", url: "https://example.com/spec.pdf" }, "spec")) +check("a URL source goes as its URL, said to be unread", url.includes("https://example.com/spec.pdf") && url.includes("spec") && url.includes("not attached"), url) +check("a URL source names neither agy nor the bridge", !/agy|bridge|magpie/i.test(url), url) +check("a URL source other than http(s) is refused", documentText(doc({ type: "url", url: "file:///etc/passwd" })) === null) + +check("a PDF the user attached is refused", documentText(pdf) === null) +const note = documentText(pdf, { inToolResult: true }) +check("a PDF inside a tool result is a note to read it another way", note.includes("paper.pdf") && note.includes("a PDF that could not be attached") && !note.includes("JVBERi0"), note) +check("the note names neither agy nor the bridge", !/agy|bridge|magpie/i.test(note), note) +check("a Files API file is refused, in a tool result too", documentText(doc({ type: "file", file_id: "file_1" }), { inToolResult: true }) === null) + +const refusal = documentRefusal(pdf) +check("a PDF's refusal says what the user can do", refusal.what.includes("PDF") && /Paste the document's text/.test(refusal.hint), JSON.stringify(refusal)) +check("a file id's refusal says to send it inline", /inline/.test(documentRefusal(doc({ type: "file", file_id: "f" })).hint)) + +if (failed) { + console.error(`${failed} FAILED`) + process.exit(1) +} +console.log("ALL OK") diff --git a/packages/agy-cli/test/smoke.mjs b/packages/agy-cli/test/smoke.mjs index 3bff32d..f104b6d 100644 --- a/packages/agy-cli/test/smoke.mjs +++ b/packages/agy-cli/test/smoke.mjs @@ -2190,6 +2190,22 @@ for (const location of ["inline", "system", "developer", "user"]) { readSteer.content.some(part => part.type === "image" && part.data === "cmVhZGltYWdl" && 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 + // document. agy can't take it, so the model is told so and the turn goes on. + const pdfReadFirst = { model, messages: [{ role: "user", content: "TOOL claude code read pdf" }], tools: [echoTool] } + const pdfReadEvents = (await readSSE(await callFetch(pdfReadFirst))).events + const pdfReadConv = inits().at(-1).convId + const pdfReadBefore = inits().length + const pdfReadResponse = await callFetch(continuation(pdfReadFirst, pdfReadEvents, [ + { type: "document", title: "paper.pdf", source: { type: "base64", media_type: "application/pdf", data: "JVBERi0xLjQK" } }, + ])) + const pdfReadFinal = (await readSSE(pdfReadResponse)).events + const pdfReadDelivered = JSON.stringify(logs().filter(event => event.type === "mcpResult" && event.convId === pdfReadConv).at(-1)?.result?.content || []) + check("a PDF inside a tool_result reaches agy as a note to read it another way, and the turn goes on", + pdfReadResponse.status === 200 && stopOf(pdfReadFinal) === "end_turn" && inits().length === pdfReadBefore && + pdfReadDelivered.includes("paper.pdf") && pdfReadDelivered.includes("a PDF that could not be attached") && + !pdfReadDelivered.includes("JVBERi0xLjQK"), pdfReadDelivered) + const searchTool = { name: "ToolSearch", description: "Search deferred tools", input_schema: { type: "object" } } const searchFirst = { model, messages: [{ role: "user", content: "TOOLSEARCHCALL load WebFetch" }], tools: [searchTool] } const searchEvents = (await readSSE(await callFetch(searchFirst))).events @@ -2448,7 +2464,31 @@ for (const location of ["inline", "system", "developer", "user"]) { content: [{ type: "document", source: { type: "base64", media_type: "application/pdf", data: "JVBERi0=" } }], }], }) - check("binary PDF document block returns HTTP 400", pdfRes.status === 400) + const pdfError = await pdfRes.json() + check("binary PDF document block returns HTTP 400 that says what to do", + pdfRes.status === 400 && /PDF attached as a document is not supported/.test(pdfError.error?.message) && + /Paste the document's text/.test(pdfError.error?.message), JSON.stringify(pdfError)) + + // A client's URL document (daoche_wuzui on X) and a base64 text file go + // to agy as text, instead of turning the request away. + const urlDocRes = await callFetch({ + model, + stream: false, + messages: [{ + role: "user", + content: [ + { type: "document", title: "spec", source: { type: "url", url: "https://example.com/spec.pdf" } }, + { type: "document", title: "notes.txt", source: { type: "base64", media_type: "text/plain", data: Buffer.from("NOTES_MARKER_77").toString("base64") } }, + { type: "text", text: "summarise the URL document" }, + ], + }], + }) + const urlDocBody = await urlDocRes.text() + const urlDocUser = lastOf("user") + check("a URL document goes as its URL, and a base64 text document as its text", + urlDocRes.status === 200 && urlDocUser.text.includes("https://example.com/spec.pdf") && + urlDocUser.text.includes("not attached") && urlDocUser.text.includes("NOTES_MARKER_77"), + JSON.stringify({ status: urlDocRes.status, body: urlDocBody, text: urlDocUser?.text })) const refusalRes = await callFetch({ model, stream: false, messages: [{ role: "user", content: "REFUSAL_CLEAN" }] }) const refusalMsg = await refusalRes.json() diff --git a/packages/agy-cli/test/testkit.mjs b/packages/agy-cli/test/testkit.mjs index bc842a5..62a0524 100644 --- a/packages/agy-cli/test/testkit.mjs +++ b/packages/agy-cli/test/testkit.mjs @@ -44,6 +44,7 @@ export const PROC_FILE = path.join(REPO_DIR, "proc.mjs") export const INSTALL_FILE = path.join(REPO_DIR, "install.mjs") export const ACCOUNT_FILE = path.join(REPO_DIR, "account.mjs") export const IMPORT_FILE = path.join(REPO_DIR, "import.mjs") +export const DOCUMENTS_FILE = path.join(REPO_DIR, "documents.mjs") export const MESSAGES_URL = "agy://local/v1/messages" export const COUNT_TOKENS_URL = "agy://local/v1/messages/count_tokens" export const CATALOG_TTL_MS = 5 * 60 * 1000 @@ -568,6 +569,7 @@ export async function createBridgeKit(options = {}) { const installUrl = pathToFileURL(INSTALL_FILE).href const accountUrl = pathToFileURL(ACCOUNT_FILE).href const importUrl = pathToFileURL(IMPORT_FILE).href + const documentsUrl = pathToFileURL(DOCUMENTS_FILE).href const linker = (specifier) => { const key = specifier.startsWith("node:") || specifier.startsWith("./") || specifier === RUNTIME_SPECIFIER ? specifier @@ -589,6 +591,7 @@ export async function createBridgeKit(options = {}) { else if (key === "./install.mjs") module = sourceModule(INSTALL_FILE, "", installUrl) else if (key === "./account.mjs") module = sourceModule(ACCOUNT_FILE, "", accountUrl) else if (key === "./import.mjs") module = sourceModule(IMPORT_FILE, "", importUrl) + else if (key === "./documents.mjs") module = sourceModule(DOCUMENTS_FILE, "", documentsUrl) else if (key.startsWith("node:")) module = builtinModule(key, overrides[key]) else throw new Error(`testkit: 未登记的依赖 ${specifier}`) cache.set(key, module)