From 1260b2ba40a2ebe8527e1e8e951b1016a680b58f Mon Sep 17 00:00:00 2001 From: yetone Date: Mon, 16 Nov 2026 01:46:53 +0800 Subject: [PATCH] devin 0.1.44: a long conversation Devin refuses is sent so it can take it a1pha1nthefog on X: a long session through Devin got "There is an issue with this request, please try a different model" on every turn, quota left, while a new session worked. On a real Devin account (claude-haiku-5-5 and others), Devin answers invalid_argument with that text to each of these, and each stays in the conversation: - a picture whose bytes aren't the type it is said to be (a PNG labelled image/jpeg or image/webp): now sent as the type its bytes are; - a user prompt of white space alone: no longer sent (both wires); - a thinking signature Devin didn't give (a fake one, or one from another Claude provider): the request goes again once without signatures; - a conversation past the window (2400KB of Go, ~1.01M tokens on a 1M window; 2350KB passed at 991,278): past half the window by a bytes/4 estimate, the refusal is a 400 "input is too long for the model's context", which magpie's gateway turns into prompt-too-long so the agent compacts. Not changed: up to 150 images, empty and image-only tool results, documents, redacted_thinking and Devin's own signatures across six Claude models all passed on the old code. Run at 7a3d33c7 on mote: HOME=$(mktemp -d) bun test, 8818 pass, 20 skip, 0 fail; bun scripts/check.mjs ok. long-session.test.mjs on origin/main's index.mjs: 5 of 7 red (the 2 green are the unchanged cases). Real account on the new code: mislabelled JPEG and WebP, a fake signature, one in a tool loop and a white-space user prompt all 200; 2400KB is 400 invalid_request_error "input is too long ... about 602459 tokens or more, for claude-haiku-5-5-low's window of 1000000". Not tried: the chat-completions path against the real account, models other than Claude, and which of the four the reporter hit. --- packages/devin/README.md | 11 ++ packages/devin/index.mjs | 112 +++++++++++++++++--- packages/devin/long-session.test.mjs | 152 +++++++++++++++++++++++++++ packages/devin/package.json | 2 +- 4 files changed, 262 insertions(+), 15 deletions(-) create mode 100644 packages/devin/long-session.test.mjs diff --git a/packages/devin/README.md b/packages/devin/README.md index db60cc8..6d6ec8b 100644 --- a/packages/devin/README.md +++ b/packages/devin/README.md @@ -95,6 +95,17 @@ The plugin's `fetch` handles this: before. - Failures keep their statuses: a refused token is a 401, a usage limit a 429, a prompt too long for the model a 400. +- Devin answers "There is an issue with this request, please try a + different model" to a long conversation it can't take, and every turn + after fails the same (since 0.1.44): + - A picture is sent as the type its bytes are (PNG, JPEG, GIF, WebP), + not the one it was said to be: Devin refuses a PNG labelled JPEG. + - A user message of white space alone isn't sent. + - Thinking signed somewhere Devin can't check is sent again once + without the signatures. + - Past half the model's window (about four bytes a token), the refusal + is a 400 "input is too long for the model's context", so the agent + compacts. - A reply with only metadata and usage is a 502, even when output tokens were counted. The plugin waits for actual content before opening a successful stream, so the gateway can try another channel. diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index ae76eff..70ac71e 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -1464,7 +1464,22 @@ function inlineImage(p) { if (p?.type !== "image_url") return null const u = typeof p.image_url === "string" ? p.image_url : p.image_url?.url ?? "" const d = /^data:([^,]*),(.*)$/s.exec(u) - return d && d[2] ? { data: d[2], type: d[1].replace(/;base64$/, "") || "image/png" } : null + return d && d[2] ? { data: d[2], type: imageType(d[2], d[1].replace(/;base64$/, "") || "image/png") } : null +} + +// imageType is the type an image's bytes (base64) are, by their first +// bytes, else the type it was said to be. Devin answers "There is an issue +// with this request, please try a different model" (invalid_argument) to +// a PNG said to be a JPEG or a WebP, on every Claude model, and the +// picture stays in the conversation, so every turn after fails the same: +// a tool that names a screenshot by its file's extension is enough. +function imageType(data, said) { + const b = Buffer.from(String(data).slice(0, 24), "base64") + if (b.length >= 8 && b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) return "image/png" + if (b.length >= 3 && b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return "image/jpeg" + if (b.length >= 6 && b.toString("latin1", 0, 4) === "GIF8") return "image/gif" + if (b.length >= 12 && b.toString("latin1", 0, 4) === "RIFF" && b.toString("latin1", 8, 12) === "WEBP") return "image/webp" + return said } // A chat's tool message holds text alone, so magpie's gateway (buildChat's @@ -1485,7 +1500,7 @@ function noted(text) { // build is the GetChatMessage request for a chat completion, to the model // uid. -function build(chat, uid, key) { +function build(chat, uid, key, opts = {}) { const claude = isClaude(uid) const msgs = [] let pending = [] // calls the last reply made, not yet answered @@ -1531,7 +1546,7 @@ function build(chat, uid, key) { const reasoning = claude ? "" : reasoningOf(m) // a Gemini reply goes back with its thought signature, as the // devin CLI sends it (thoughts) - const signed = thoughtFor(uid, calls, text) + const signed = opts.unsigned ? null : thoughtFor(uid, calls, text) const thinking = signed ? { text: reasoning, ...signed } : reasoning ? { text: reasoning } : null msgs.push({ role: ASSISTANT, text, calls, ...(thinking ? { thinking } : {}) }) // a copy: answering a call takes it off pending, never off the @@ -1576,7 +1591,9 @@ function build(chat, uid, key) { } } settleResults() - const text = texts.join("\n\n") + // words that are only white space are none: Devin turns a user prompt + // of them away (invalid_argument), as it does an empty one + const text = texts.join("\n\n").trim() ? texts.join("\n\n") : "" if (!text && !images.length) continue answer() msgs.push({ role: USER, text, images }) @@ -1650,9 +1667,32 @@ function encodeRequest(msgs, tools, chat, uid, key) { } const bytes = assemble([], chat.max || 128000) // the server holds max to the model's own pingOf.set(bytes, () => assemble([encodeMsg({ role: USER, text: "continue" })], 1)) + sentOf.set(bytes, { signed: msgs.some((m) => m.thinking?.signature), tokens: estimate(msgs, toolParts) }) return bytes } +// sentOf is what each request carried that its failure is read by: any +// signed thinking, and about how many tokens its prompt is (estimate) +const sentOf = new WeakMap() + +// estimate is about how many tokens msgs and the tools offered come to, +// a token counted as four bytes of text and an image as 1,600 tokens (a +// picture's base64 is no measure of its tokens): text runs under four +// bytes a token, code nearer three (Devin counted 991,278 tokens of +// 2,350,000 bytes of Go), so this is low, never high, and it is read +// against half the window (TOO_LONG_AT). +function estimate(msgs, toolParts) { + let bytes = 0 + let images = 0 + for (const m of msgs) { + bytes += Buffer.byteLength(m.text ?? "") + Buffer.byteLength(m.thinking?.text ?? "") + for (const c of m.calls ?? []) bytes += Buffer.byteLength(c.name ?? "") + Buffer.byteLength(c.args ?? "") + images += m.images?.length ?? 0 + } + for (const t of toolParts) bytes += t.length + return Math.ceil(bytes / 4) + images * 1600 +} + // pingOf is each request's keepalive ping, made when one is first sent const pingOf = new WeakMap() const keepalivePing = (bytes) => pingOf.get(bytes)?.() @@ -1752,7 +1792,7 @@ function failure(status, text) { if (low.includes("content policy")) return { status: 400, message: msg } if (low.includes("too long") || low.includes("context length") || low.includes("too many tokens")) return { status: 400, message: "input is too long for the model's context: " + msg } - if (code === "invalid_argument") return { status: 400, message: msg } + if (code === "invalid_argument") return { status: 400, message: msg, code } if (code === "unavailable") return { status: 503, message: msg } if (code) return { status: 502, message: msg } return { status, message: msg } @@ -1880,9 +1920,33 @@ const rpcHeaders = (key, body) => ({ "Content-Type": "application/connect+proto" // keep, when given, is the conversation's cache keepalive (keepaliveFor): // once the reply has finished, its pings are scheduled. +// +// Devin answers "There is an issue with this request, please try a +// different model" (invalid_argument) to a conversation past the model's +// window and to a thinking signature it didn't give (another vendor's +// Claude, or one a client changed), alike. Either stays in the +// conversation, so every turn after fails the same while a new session +// works (a1pha1nthefog on X). A request with signed thinking that is +// turned away is sent again once with no signature, its Claude thinking +// left out, as Anthropic takes a past turn's; one still turned away at +// half the model's window or more (TOO_LONG_AT) is told as too long, so +// the agent compacts the conversation rather than stopping. async function roundtrip({ key, server, families, keep }, chat, signal, wire = CHAT_WIRE) { const uid = variantFor(families, chat.model, wire.effort(chat)) - const msg = wire.build(chat, uid, key) + let msg = wire.build(chat, uid, key) + let r = await askOnce(key, server, msg, signal, uid) + if (r.code === "invalid_argument" && sentOf.get(msg)?.signed && !signal?.aborted) { + msg = wire.build(chat, uid, key, { unsigned: true }) + r = await askOnce(key, server, msg, signal, uid) + } + if (r.code === "invalid_argument") r = tooLongFor(r, sentOf.get(msg)?.tokens ?? 0, windowOf(families, uid), uid) + if (!r.it) return r + return { it: keep ? keptAfter(r.it, keep, { key, server, msg, sentAt: r.sentAt }) : r.it, uid } +} + +// askOnce sends one GetChatMessage, msg, and answers with its event iterator +// and when it was sent, or an error ({status, message, code}). +async function askOnce(key, server, msg, signal, uid) { const body = frame(msg) // when Devin was asked, which its cache's 5 minutes run from: the pings // are timed from it, not from the reply's end (plugins#626) @@ -1921,8 +1985,26 @@ async function roundtrip({ key, server, families, keep }, chat, signal, wire = C await fr.return?.() return head.value.error } - const it = prepend(head.value, source) - return { it: keep ? keptAfter(it, keep, { key, server, msg, sentAt }) : it, uid } + return { it: prepend(head.value, source), sentAt } +} + +// TOO_LONG_AT is how much of a model's window a request Devin turns away +// (invalid_argument) must be estimated at to be told as too long: the +// estimate runs low (estimate), and Devin says nothing of length. +const TOO_LONG_AT = 0.5 + +// tooLongFor is e, a request turned away, as too long for the model's +// window when it was estimated at TOO_LONG_AT of it or more; e otherwise. +function tooLongFor(e, tokens, window, uid) { + if (!window || tokens < window * TOO_LONG_AT) return e + return { status: 400, message: `input is too long for the model's context: about ${tokens} tokens or more, for ${uid}'s window of ${window} (Devin answered: ${e.message})` } +} + +// windowOf is the context window of the model uid, from the account's +// list or else the snapshot's; 0 when neither says. +function windowOf(families, uid) { + for (const fs of [families, SNAPSHOT_FAMILIES]) for (const f of fs ?? []) for (const m of f.models ?? []) if (m.id === uid && m.context) return m.context + return 0 } // complete answers a chat completion through GetChatMessage. @@ -2003,7 +2085,7 @@ const marked = (b) => !!(b && typeof b === "object" && b.cache_control && typeof function anthropicImage(b) { const s = b?.type === "image" ? b.source : null if (s?.type !== "base64" || !s.data) return null - return { data: s.data, type: s.media_type || "image/png" } + return { data: s.data, type: imageType(s.data, s.media_type || "image/png") } } // anthropicEffort is the effort a Messages request asks for, as magpie @@ -2026,7 +2108,7 @@ function anthropicEffort(req) { // (#566). Every boundary is kept, not only the marked ones: a mark moves // forward as the history grows, and the prompts it passed must stay as // they were sent for the cache to be read (yetone/magpie#3835). -function buildMessages(req, uid, key) { +function buildMessages(req, uid, key, opts = {}) { const claude = isClaude(uid) // Messages alternate roles; a client that sends two of one role in a row // means one turn @@ -2072,7 +2154,7 @@ function buildMessages(req, uid, key) { } else if (b?.type === "tool_use" && b.name) { calls.push({ id: inID(b.id), name: b.name, args: JSON.stringify(b.input ?? {}) }) mark ||= marked(b) - } else if (b?.type === "thinking" && claude && typeof b.signature === "string" && b.signature) { + } else if (b?.type === "thinking" && claude && !opts.unsigned && typeof b.signature === "string" && b.signature) { // Devin rejects a signed thought on an otherwise empty assistant prompt. // A gateway search can leave adjacent thoughts; keep the last one intact. const next = t.blocks[i + 1] @@ -2093,7 +2175,7 @@ function buildMessages(req, uid, key) { // a Gemini reply goes back with its thought signature, on the // prompt with its calls (or its last words), as the devin CLI sends // it (thoughts) - const signed = own.length ? thoughtFor(uid, calls, own.map((p) => p.text).join("")) : null + const signed = own.length && !opts.unsigned ? thoughtFor(uid, calls, own.map((p) => p.text).join("")) : null if (signed) { const p = own[own.length - 1] p.thinking = { text: p.thinking?.text ?? "", ...signed } @@ -2123,7 +2205,9 @@ function buildMessages(req, uid, key) { continue } if (b?.type === "text" && typeof b.text === "string") { - if (!b.text) { + // a block of white space alone is none: Devin turns a user prompt + // of it away (invalid_argument), as it does an empty one + if (!b.text.trim()) { if (marked(b) && words) words.cache = true continue } @@ -3312,4 +3396,4 @@ export async function DevinAuthPlugin({ client, magpie } = {}, options = {}) { } // for tests -export const _internal = { sigTypeOf, forgetSigTypes: () => sigTypes.clear(), forgetThoughts: () => thoughts.clear(), thoughtFor, keepaliveKey, keepaliveSettings, keepalivePing, scheduleKeepalive, stopKeepalive, stopAllKeepalive, keeping: () => [...keeps.keys()], useTimers: (t) => (timers = t ?? realTimers), KEEPALIVE, buildMessages, completeMessages, anthropicEffort, encodeMsg, parseFree, parsePrices, geminiSchema, freeIDs, outID, inID, objectRoot, seesImages, imagesFor, forgetSaid: () => said.clear(), parseModelConfigs, parseConfigFamilies, SNAPSHOT_IMAGES, withImages, forgetImages: () => (seen = null), effortOf, runtimeModel, configModel, live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readsHome, tierName, whoOfStatus, whoByKey, success, familiesFor, readCredentials, credentials, fields, frame, PB, events, frames, v2Chat, v2ToolParts, v2FileData, v2Effort, v2ResponseFormat, v2Usage, v2Auth, v2Credential, v2Models, devinLanguage, v2Setup, connKey } +export const _internal = { imageType, estimate, windowOf, TOO_LONG_AT, sigTypeOf, forgetSigTypes: () => sigTypes.clear(), forgetThoughts: () => thoughts.clear(), thoughtFor, keepaliveKey, keepaliveSettings, keepalivePing, scheduleKeepalive, stopKeepalive, stopAllKeepalive, keeping: () => [...keeps.keys()], useTimers: (t) => (timers = t ?? realTimers), KEEPALIVE, buildMessages, completeMessages, anthropicEffort, encodeMsg, parseFree, parsePrices, geminiSchema, freeIDs, outID, inID, objectRoot, seesImages, imagesFor, forgetSaid: () => said.clear(), parseModelConfigs, parseConfigFamilies, SNAPSHOT_IMAGES, withImages, forgetImages: () => (seen = null), effortOf, runtimeModel, configModel, live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readsHome, tierName, whoOfStatus, whoByKey, success, familiesFor, readCredentials, credentials, fields, frame, PB, events, frames, v2Chat, v2ToolParts, v2FileData, v2Effort, v2ResponseFormat, v2Usage, v2Auth, v2Credential, v2Models, devinLanguage, v2Setup, connKey } diff --git a/packages/devin/long-session.test.mjs b/packages/devin/long-session.test.mjs new file mode 100644 index 0000000..07fc945 --- /dev/null +++ b/packages/devin/long-session.test.mjs @@ -0,0 +1,152 @@ +// What a long conversation carries that Devin turns away with "There is an +// issue with this request, please try a different model" +// (invalid_argument), each seen on a real Devin account (2026-11-16, +// a1pha1nthefog on X): it stays in the conversation, so every turn after +// failed the same while a new session worked. A picture whose bytes aren't +// the type it is said to be, a user prompt of white space alone, a thinking +// signature Devin didn't give, and a conversation past the model's window. +import { afterEach, expect, test } from "bun:test" +import { gunzipSync } from "node:zlib" +import { _internal } from "./index.mjs" + +const { PB, frame, fields, buildMessages, build, completeMessages, familiesOf, SNAPSHOT } = _internal +const dec = new TextDecoder() +const enc = new TextEncoder() +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 13, 0x49, 0x48, 0x44, 0x52]).toString("base64") +const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 16, 0x4a, 0x46, 0x49, 0x46, 0, 1]).toString("base64") +const SIG = "EqQBCkgIBRABGAIiQL2xYzRvY0RzZWNyZXRzaWduYXR1cmU=" + +// prompts is each ChatMessagePrompt a request sends: its role, text, the +// types of its images and its thinking's signature +const prompts = (body) => + fields(body) + .filter((f) => f.num === 3 && f.wire === 2) + .map((f) => { + const p = { role: 0, text: "", images: [], signature: null } + for (const g of fields(f.data)) { + if (g.num === 2) p.role = g.n + else if (g.num === 3) p.text = dec.decode(g.data) + else if (g.num === 10) p.images.push(dec.decode(fields(g.data).find((h) => h.num === 2).data)) + else if (g.num === 12) p.signature = dec.decode(g.data) + } + return p + }) +const unframe = (body) => { + const b = new Uint8Array(body) + return b[0] & 1 ? new Uint8Array(gunzipSync(b.subarray(5))) : b.subarray(5) +} + +const end = (obj) => { + const b = enc.encode(JSON.stringify(obj)) + const out = new Uint8Array(5 + b.length) + out[0] = 2 + new DataView(out.buffer).setUint32(1, b.length) + out.set(b, 5) + return out +} +const refused = () => new Response(end({ error: { code: "invalid_argument", message: "There is an issue with this request, please try a different model." } })) +const answered = () => + new Response(new Blob([frame(new PB().str(3, "ok").done()), frame(new PB().varint(5, 1).bytes(7, new PB().varint(2, 10).varint(3, 1).done()).done()), end({})])) + +const ctx = { key: "k", server: "https://devin.test", families: familiesOf(SNAPSHOT) } +// sent is each request's prompts, as Devin is asked, each answered by +// replies in turn +const asking = (...replies) => { + const sent = [] + globalThis.fetch = async (_url, init) => { + sent.push(prompts(unframe(init.body))) + return replies[Math.min(sent.length, replies.length) - 1]() + } + return sent +} +const errOf = async (res) => JSON.parse(await res.text()).error.message + +test("a picture goes as the type its bytes are, whatever it is said to be", () => { + const img = (media_type, data) => ({ type: "image", source: { type: "base64", media_type, data } }) + const msg = buildMessages( + { + model: "claude-haiku-5-5", + tools: [{ name: "Read", input_schema: { type: "object", properties: {} } }], + messages: [ + { role: "user", content: [img("image/jpeg", PNG), { type: "text", text: "this" }] }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_1", name: "Read", input: {} }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_1", content: [img("image/webp", PNG), img("image/png", JPEG), img("image/png", "AAAA")] }] }, + ], + }, + "claude-haiku-5-5-low", + "k", + ) + expect(prompts(msg).flatMap((p) => p.images)).toEqual(["image/png", "image/png", "image/jpeg", "image/png"]) + const chat = build({ messages: [{ role: "user", content: [{ type: "text", text: "this" }, { type: "image_url", image_url: { url: "data:image/jpeg;base64," + PNG } }] }] }, "swe-2-high", "k") + expect(prompts(chat).flatMap((p) => p.images)).toEqual(["image/png"]) +}) + +test("a user prompt of white space alone is not sent", () => { + const msgs = [ + { role: "user", content: "hi" }, + { role: "assistant", content: "hello" }, + { role: "user", content: " \n" }, + ] + for (const p of [prompts(buildMessages({ messages: msgs }, "claude-haiku-5-5-low", "k")), prompts(build({ messages: msgs }, "swe-2-high", "k"))]) { + expect(p.some((x) => x.role === 1 && x.text && !x.text.trim())).toBe(false) + expect(p.at(-1).text).toBe("Please proceed with the task.") + } +}) + +const signed = { + model: "claude-haiku-5-5", + max_tokens: 64, + messages: [ + { role: "user", content: "hi" }, + { role: "assistant", content: [{ type: "thinking", thinking: "greet", signature: SIG }, { type: "text", text: "hello" }] }, + { role: "user", content: "say ok" }, + ], +} + +test("signed thinking Devin turns away is sent again once without its signature", async () => { + const sent = asking(refused, answered) + const res = await completeMessages(ctx, signed) + expect(res.status).toBe(200) + expect(sent.length).toBe(2) + expect(sent[0].some((p) => p.signature === SIG)).toBe(true) + expect(sent[1].some((p) => p.signature)).toBe(false) + expect(sent[1].map((p) => p.text)).toEqual(sent[0].map((p) => p.text)) +}) + +test("a request with no signed thinking is not sent again", async () => { + const sent = asking(refused, answered) + const res = await completeMessages(ctx, { ...signed, messages: [{ role: "user", content: "say ok" }] }) + expect(res.status).toBe(400) + expect(sent.length).toBe(1) + expect(await errOf(res)).toBe("There is an issue with this request, please try a different model.") +}) + +// claude-sonnet-4-6's window is 200,000 tokens; a token is estimated at +// four bytes +const filled = (bytes) => ({ model: "claude-sonnet-4-6", max_tokens: 64, messages: [{ role: "user", content: "x".repeat(bytes) }] }) + +test("turned away at half the window or more, it is too long for the model", async () => { + asking(refused) + const res = await completeMessages(ctx, filled(420_000)) + expect(res.status).toBe(400) + const msg = await errOf(res) + expect(msg).toStartWith("input is too long for the model's context: about 105") + expect(msg).toContain("claude-sonnet-4-6's window of 200000") +}) + +test("turned away well inside the window, it is said as Devin said it", async () => { + asking(refused) + const res = await completeMessages(ctx, filled(300_000)) + expect(res.status).toBe(400) + expect(await errOf(res)).toBe("There is an issue with this request, please try a different model.") +}) + +test("signed thinking still turned away without signatures, past half the window, is too long", async () => { + const sent = asking(refused, refused) + const res = await completeMessages(ctx, { ...signed, model: "claude-sonnet-4-6", messages: [{ role: "user", content: "x".repeat(420_000) }, ...signed.messages.slice(1)] }) + expect(sent.length).toBe(2) + expect(await errOf(res)).toStartWith("input is too long for the model's context") +}) diff --git a/packages/devin/package.json b/packages/devin/package.json index 801c21e..ddd6eb7 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.43", + "version": "0.1.44", "description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie", "type": "module", "main": "./index.mjs",