From 1bd6d172c1b21f2f87ffc79daf63b2c57a15363d Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 14 Oct 2026 14:26:08 +0800 Subject: [PATCH] factory: a 413 is asked once more with older images left out, then said as Factory's byte limit (yetone/magpie#2082) Ziqi-Cui's Codex session on Opus 5.5 gathered nine screenshots, ~4.5 MB of data URLs, and Factory answered every request after with 413 "Request Entity Too Large". The plugin passed the 413 on as it came, which reads as the context window; it is Factory's limit on a body's bytes. On a 413 from Factory the plugin now sends the request once more with every image and file but the newest replaced, in place, by a line saying it was left out (droid 0.239.0 removes older images/PDFs from large requests the same way). Anthropic image/document blocks, Responses input_image/input_file, chat image_url/file and Gemini inlineData/fileData are found wherever they are, tool results included, so every tool call keeps its result; a Gemini function response's parts, which take inline data alone, drop the image instead. One retry, never more; none when there is nothing older to leave out. If the 413 stands, or nothing could be left out, the error (Anthropic's request_too_large, else invalid_request_error) gives Factory's words, says the limit is on the body's bytes and what was left out, and carries magpie's gateway 413 hint word for word (compact, or start a new session), so the gateway, finding it, doesn't add it twice and OpenCode users get it too. The words avoid what the gateway reads as a context overflow, so it stays a 413. The caller's own session and files are untouched: only the body sent to Factory changes, and only on the retry. Run: bun test in packages/factory (134 pass), bun scripts/check.mjs. Broken by hand: without the 413 branch, three of size.test.mjs's four tests fail. Not tried: a real Factory account (none here) or Factory's real limit, which neither droid's binary nor its changelog states; the fake upstream refuses over a chosen size. --- packages/factory/README.md | 10 +++ packages/factory/index.mjs | 99 ++++++++++++++++++++++++- packages/factory/size.test.mjs | 127 +++++++++++++++++++++++++++++++++ 3 files changed, 235 insertions(+), 1 deletion(-) create mode 100644 packages/factory/size.test.mjs diff --git a/packages/factory/README.md b/packages/factory/README.md index 357dec0..535e9e1 100644 --- a/packages/factory/README.md +++ b/packages/factory/README.md @@ -80,6 +80,16 @@ be refused it. auto is not included: droid picks it on the client side. +## Requests too large + +Factory refuses a request body over its size limit with 413 "Request +Entity Too Large". The limit is on bytes, not on the model's context, and +images reach it first. On a 413 the plugin sends the request once more with +every image and file but the newest replaced by a line saying it was left +out, each tool result kept beside its call, as droid does. If that is still +too large, or there was nothing to leave out, the error says it is +Factory's byte limit: compact the conversation or start a new one. + ## Use ```sh diff --git a/packages/factory/index.mjs b/packages/factory/index.mjs index dbbab37..fe2f1a1 100644 --- a/packages/factory/index.mjs +++ b/packages/factory/index.mjs @@ -462,6 +462,89 @@ function geminiBody(model, body) { return JSON.stringify(m) } +// ---- request size ------------------------------------------------------------- +// +// Factory answers a request body over its size limit with 413 "Request +// Entity Too Large": a limit on bytes, not on the model's context, which +// the images an agent's session gathers reach long before its tokens do +// (yetone/magpie#2082: nine screenshots, ~4.5 MB of data URLs, on Opus +// 5.5). droid 0.239.0 leaves older images and PDFs out of such a request. +// The plugin does the same once, on a 413: every image and file but the +// newest KEEP_ATTACHMENTS becomes a line saying it was left out, in place, +// so each tool result stays beside its call. Failing that, the 413 says +// what it is and what to do. + +const KEEP_ATTACHMENTS = 1 +const LEFT_OUT = "[An earlier image or file was left out of this request: it was over Factory's request size limit.]" +// what magpie's gateway adds to a 413 (internal/gateway/gateway.go, +// writeError), said here too for OpenCode; the gateway, finding it, adds +// it no second time +const TOO_LARGE_HINT = "This is a request-body byte limit, not the model's context: compact the conversation (/compact in Codex or Claude Code), or start a new one with a short summary; fewer images or smaller tool results also help." + +// dialectOf is which API's body a request to path carries, as attachments +// are found in it, or "" for one that has none to leave out. +function dialectOf(path) { + if (path.includes("/llm/a/") && path.endsWith("/messages")) return "anthropic" + if (path.endsWith("/responses")) return "responses" + if (path.endsWith("/chat/completions")) return "chat" + if (GEMINI_CALL.test(path) || path.endsWith("/llm/g/v1/generate")) return "gemini" + return "" +} + +const DIALECTS = { + anthropic: { list: "messages", is: (p) => p.type === "image" || p.type === "document", text: (p) => ({ type: "text", text: LEFT_OUT, ...(p.cache_control ? { cache_control: p.cache_control } : {}) }) }, + responses: { list: "input", is: (p) => p.type === "input_image" || p.type === "input_file", text: () => ({ type: "input_text", text: LEFT_OUT }) }, + chat: { list: "messages", is: (p) => p.type === "image_url" || p.type === "file", text: () => ({ type: "text", text: LEFT_OUT }) }, + gemini: { list: "contents", is: (p) => !!(p.inlineData || p.inline_data || p.fileData || p.file_data), text: () => ({ text: LEFT_OUT }) }, +} + +// leaveOutAttachments is body, a request to path, with every image and file +// but the newest KEEP_ATTACHMENTS left out, and how many were: null when +// there are none to leave out or the body can't be read. +function leaveOutAttachments(path, body) { + const d = DIALECTS[dialectOf(path)] + const text = d && bodyText(body) + if (!text) return null + let m + try { + m = JSON.parse(text) + } catch { + return null + } + if (!Array.isArray(m?.[d.list])) return null + // in the order they were sent: the array each is in, its place, and + // whether the array is a Gemini function response's parts, which take + // inline data alone + const found = [] + const walk = (v, key) => { + if (Array.isArray(v)) { + v.forEach((p, i) => { + if (p && typeof p === "object" && !Array.isArray(p) && d.is(p)) found.push({ list: v, i, drop: key === "functionResponse" }) + else walk(p, key) + }) + } else if (v && typeof v === "object") { + for (const [k, x] of Object.entries(v)) walk(x, k === "functionResponse" ? k : key) + } + } + walk(m[d.list], "") + const out = found.slice(0, Math.max(found.length - KEEP_ATTACHMENTS, 0)) + if (out.length === 0) return null + // from the last, so a part dropped doesn't move the places before it + for (const { list, i, drop } of out.reverse()) { + if (drop) list.splice(i, 1) + else list[i] = d.text(list[i]) + } + return { body: JSON.stringify(m), left: out.length } +} + +// tooLarge is what a 413 of Factory's says to the agent: Factory's own +// words, that the limit is on bytes, what the plugin left out, and the hint. +function tooLarge(text, left) { + const said = vendorError(text, "413") + const tried = left > 0 ? ` It was still too large with ${left} older image${left === 1 ? "" : "s"} or file${left === 1 ? "" : "s"} left out.` : "" + return `Factory refused the request as too large (${said}): it limits the size of a request's body in bytes.${tried} ${TOO_LARGE_HINT}` +} + // errorReply is an error as the API the request was for words one: // Anthropic's on /llm/a/, OpenAI's on the others. function errorReply(url, status, type, message, headers = new Headers()) { @@ -1547,9 +1630,23 @@ export const FactoryAuthPlugin = async ({ client }) => { let renewed = false const onRenew = () => (renewed = true) const answer = (res) => said(res, renewed ? "renewed" : "kept") + // a 413: once more with the older images left out, then the + // refusal said for what it is (leaveOutAttachments) + const smaller = async (res) => { + const path = new URL(url).pathname + const less = leaveOutAttachments(path, body) + if (less) { + await res.body?.cancel() + res = await send(input, init, less.body, onRenew) + if (res.status !== 413) return res + } + const anthropic = path.includes("/llm/a/") + return errorReply(url, 413, anthropic ? "request_too_large" : "invalid_request_error", tooLarge(await res.text(), less?.left ?? 0), new Headers(res.headers)) + } let res try { res = await send(input, init, body, onRenew) + if (res.status === 413) return answer(await smaller(res)) if (res.status !== 403) return answer(res) let text = await res.text() if (await mendOrg(res.status, text, onRenew).catch(() => false)) { @@ -1575,4 +1672,4 @@ export const FactoryAuthPlugin = async ({ client }) => { } // for tests -export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody } +export const _internal = { limitWindows, windowEnd, dollars, vendorError, CORE, droidBody, DROID_LINE, geminiBody, leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT } diff --git a/packages/factory/size.test.mjs b/packages/factory/size.test.mjs new file mode 100644 index 0000000..234cae1 --- /dev/null +++ b/packages/factory/size.test.mjs @@ -0,0 +1,127 @@ +// yetone/magpie#2082 (Ziqi-Cui): Codex on Opus 5.5 through the plugin +// gathered nine screenshots, ~4.5 MB of data URLs, and Factory answered +// every request after with 413 "Request Entity Too Large". It is Factory's +// limit on a body's bytes, not the model's context. On a 413 the plugin +// asks once more with every image but the newest left out, as droid 0.239.0 +// does, each tool result kept beside its call; failing that, it says what +// the 413 is and what to do. +import { afterEach, expect, test } from "bun:test" +import { FactoryAuthPlugin, _internal } from "./index.mjs" + +const { leaveOutAttachments, LEFT_OUT, TOO_LARGE_HINT } = _internal +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +// Factory refuses a body over limit bytes, as its edge does: plain text +async function loaded(limit) { + const seen = [] + globalThis.fetch = async (url, init) => { + seen.push({ url: String(url), ...init }) + if (String(init.body).length > limit) return new Response("Request Entity Too Large", { status: 413, headers: { "content-type": "text/plain" } }) + return new Response('event: message_stop\ndata: {"type":"message_stop"}\n\n', { headers: { "content-type": "text/event-stream" } }) + } + const auth = { type: "oauth", access: "factory-token", expires: Date.now() + 3_600_000, activeOrganizationId: "org_A" } + const hooks = await FactoryAuthPlugin({ client: { auth: { set: async () => {} } } }) + return { l: await hooks.auth.loader(async () => auth), seen } +} + +const png = (n) => ({ type: "image", source: { type: "base64", media_type: "image/png", data: "A".repeat(n) } }) + +// Codex's turns as magpie's gateway hands them to Factory's Messages: a +// screenshot from a tool, one pasted, and the newest from a tool again +const session = () => ({ + model: "claude-opus-5-5", + max_tokens: 1024, + stream: true, + messages: [ + { role: "user", content: [{ type: "text", text: "look" }, png(3000)] }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "view_image", input: { path: "/a.png" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: [png(3000)] }] }, + { role: "assistant", content: [{ type: "tool_use", id: "t2", name: "view_image", input: { path: "/b.png" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t2", content: [{ type: "text", text: "b.png" }, { ...png(3000), cache_control: { type: "ephemeral" } }] }] }, + ], +}) + +test("a 413 is asked once more with the older images left out, tool results kept beside their calls", async () => { + const { l, seen } = await loaded(5000) + const res = await l.fetch("https://api.factory.ai/api/llm/a/v1/messages", { method: "POST", headers: { "content-length": "99999" }, body: JSON.stringify(session()) }) + expect(res.status).toBe(200) + expect(seen.length).toBe(2) + const sent = JSON.parse(seen[1].body) + const want = session() + want.messages[0].content[1] = { type: "text", text: LEFT_OUT } + want.messages[2].content[0].content[0] = { type: "text", text: LEFT_OUT } + expect(sent.messages).toEqual(want.messages) + expect(seen[1].headers.get("content-length")).toBeNull() +}) + +test("a 413 still there with the older images left out says it is Factory's byte limit, and what to do", async () => { + const { l, seen } = await loaded(100) + const res = await l.fetch("https://api.factory.ai/api/llm/a/v1/messages", { method: "POST", body: JSON.stringify(session()) }) + expect(seen.length).toBe(2) + expect(res.status).toBe(413) + const e = await res.json() + expect(e.type).toBe("error") + expect(e.error.type).toBe("request_too_large") + expect(e.error.message).toContain("(413: Request Entity Too Large)") + expect(e.error.message).toContain("limits the size of a request's body in bytes") + expect(e.error.message).toContain("2 older images or files left out") + // magpie's gateway finds its own hint and doesn't add it again + expect(e.error.message).toContain(TOO_LARGE_HINT) + expect(e.error.message).not.toMatch(/context window|exceed/i) +}) + +test("a 413 with no older image to leave out is not asked again", async () => { + const { l, seen } = await loaded(10) + const res = await l.fetch("https://api.factory.ai/api/llm/o/v1/responses", { method: "POST", body: JSON.stringify({ model: "gpt-6-sol", input: [{ role: "user", content: [{ type: "input_text", text: "hi" }, { type: "input_image", image_url: "data:image/png;base64,AAAA" }] }] }) }) + expect(seen.length).toBe(1) + expect(res.status).toBe(413) + const e = await res.json() + expect(e.error.type).toBe("invalid_request_error") + expect(e.error.message).not.toContain("left out") + expect(e.error.message).toContain(TOO_LARGE_HINT) +}) + +test("Responses, chat completions and Gemini have their older images left out in their own words", () => { + const img = { type: "input_image", image_url: "data:image/png;base64,AAAA" } + const responses = { + input: [ + { role: "user", content: [{ type: "input_text", text: "a" }, img] }, + { type: "function_call", call_id: "c1", name: "view_image", arguments: "{}" }, + { type: "function_call_output", call_id: "c1", output: [img] }, + { role: "user", content: [img] }, + ], + } + const r = leaveOutAttachments("/api/llm/o/v1/responses", JSON.stringify(responses)) + expect(r.left).toBe(2) + const rs = JSON.parse(r.body) + expect(rs.input[0].content[1]).toEqual({ type: "input_text", text: LEFT_OUT }) + expect(rs.input[2]).toEqual({ type: "function_call_output", call_id: "c1", output: [{ type: "input_text", text: LEFT_OUT }] }) + expect(rs.input[3].content[0]).toEqual(img) + + const url = { type: "image_url", image_url: { url: "data:image/png;base64,AAAA" } } + const chat = { messages: [{ role: "user", content: [url, { type: "text", text: "x" }] }, { role: "user", content: [url] }] } + const c = JSON.parse(leaveOutAttachments("/api/llm/o/v1/chat/completions", JSON.stringify(chat)).body) + expect(c.messages[0].content).toEqual([{ type: "text", text: LEFT_OUT }, { type: "text", text: "x" }]) + expect(c.messages[1].content[0]).toEqual(url) + + const inline = { inlineData: { mimeType: "image/png", data: "AAAA" } } + const gemini = { + contents: [ + { role: "user", parts: [inline] }, + { role: "model", parts: [{ functionCall: { name: "view_image", args: {} } }] }, + { role: "user", parts: [{ functionResponse: { name: "view_image", response: {}, parts: [inline] } }] }, + { role: "user", parts: [inline] }, + ], + } + const g = JSON.parse(leaveOutAttachments("/api/llm/g/v1/models/gemini-4-argon:streamGenerateContent", JSON.stringify(gemini)).body) + expect(g.contents[0].parts).toEqual([{ text: LEFT_OUT }]) + // a function response's parts take inline data alone: the image goes, the response stays + expect(g.contents[2].parts).toEqual([{ functionResponse: { name: "view_image", response: {}, parts: [] } }]) + expect(g.contents[3].parts).toEqual([inline]) + + // one image, none to leave out; a body not JSON, or a route with none + expect(leaveOutAttachments("/api/llm/o/v1/chat/completions", JSON.stringify({ messages: [{ role: "user", content: [url] }] }))).toBeNull() + expect(leaveOutAttachments("/api/llm/a/v1/messages", "not json")).toBeNull() + expect(leaveOutAttachments("/api/llm/a/v1/messages/count_tokens", JSON.stringify(session()))).toBeNull() +})