From a064cf15e17e10573629b36db79fb06d49318133 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 3 Nov 2026 17:28:11 +0800 Subject: [PATCH] devin 0.1.35: Claude's thinking keeps its signature and goes back with it (#665) Vigilans (#665): GetChatMessage's reply carries the thinking's signature in delta_signature (10) and its type in delta_signature_type (21), and ChatMessagePrompt takes the thinking back in thinking (11), signature (12) and signature_type (18). The plugin read only delta_thinking (9), so /v1/messages answered thinking blocks with signature "", and the next request left the assistant's thinking out. Field numbers checked against devin2api's all-protos.proto (GetChatMessageResponse, ExaChatPb_ChatMessagePrompt) at e8547b6d. - events() yields {signature} for field 10 and {signatureType} for 21. - Messages, whole: the signature goes on the last thinking block. Stream: a signature_delta in the open thinking block, before its stop, as Anthropic streams it. Only when the request's model is Claude; another model's thinking stays unsigned, as before. - The type is kept by signature (the last 512) since a Messages block has no field for it; one not kept goes back as "anthropic", what Devin says for Claude. - buildMessages, to a Claude model: a signed thinking block goes back on the assistant prompt after it (its text, or the calls' prompt); a second one before any prompt gets an empty prompt of its own, and one after the text with calls following goes on the calls' prompt. Unsigned thinking, thinking to a model that isn't Claude, and a turn that only thought send nothing, as before. - The chat completion and Messages streams read past events they send nothing for: a pull that enqueues nothing isn't pulled again in Bun, and the Messages stream hung on one (seen in the new tests before the loop). Not changed: chat completions (and OpenCode 2's language model, which goes through them) have no field for a signature, so they carry the thinking text only, as before. thinking_redacted (reply 11, prompt 13) isn't read or sent. Run at this head on mote: - bun test packages/devin (HOME a temp dir): 199 pass, 0 fail. - repo root bun test: 5175 pass, 0 fail (15 skip); bun scripts/check.mjs ok. - thinking-signature.test.mjs on origin/main 311d628: the six tests of the signature (read, whole, stream, replay, two thinking blocks, type) red; the four "as before" tests pass. Not tried: a real Devin account (none in a sandbox); frames are built from the proto's field numbers, not captured bytes. --- packages/devin/index.mjs | 102 ++++++++++-- packages/devin/package.json | 2 +- packages/devin/thinking-signature.test.mjs | 181 +++++++++++++++++++++ 3 files changed, 274 insertions(+), 11 deletions(-) create mode 100644 packages/devin/thinking-signature.test.mjs diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index f03e1b4..8ffca6c 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -1630,9 +1630,30 @@ function encodeMsg(m) { // own: where the client put cache_control (#566) if (m.cache) b.bytes(8, new PB().varint(1, 1)) for (const p of m.images ?? []) b.bytes(10, new PB().str(1, p.data).str(2, p.type)) + // the signed thinking the reply had, sent back as Devin wrote it: + // thinking (11), signature (12) and signature_type (18) (plugins#665) + if (m.thinking?.signature) { + if (m.thinking.text) b.str(11, m.thinking.text) + b.str(12, m.thinking.signature) + if (m.thinking.type) b.str(18, m.thinking.type) + } return b.done() } +// sigTypes is each thinking signature's type (delta_signature_type) as +// Devin said it, by the signature, for the next request's thinking: a +// Messages thinking block has no field for it. The most recent are kept; +// one not kept is Anthropic's, which is what Devin says for Claude's. +const sigTypes = new Map() +const SIG_TYPES_KEPT = 512 +function rememberSigType(signature, type) { + if (!signature || !type) return + sigTypes.delete(signature) + sigTypes.set(signature, type) + if (sigTypes.size > SIG_TYPES_KEPT) sigTypes.delete(sigTypes.keys().next().value) +} +const sigTypeOf = (signature) => sigTypes.get(signature) ?? "anthropic" + // ---- the reply ----------------------------------------------------------------------- // statusText is a status as magpie's built-in words an error that says @@ -1699,6 +1720,13 @@ async function* events(it) { } else if (x.num === 9 && x.wire === 2 && x.data.length) { said += x.data.length yield { reasoning: dec.decode(x.data) } + } else if (x.num === 10 && x.wire === 2 && x.data.length) { + // delta_signature: the thinking's signature, Claude's opaque state + // to continue it from (plugins#665); no words of the reply + yield { signature: dec.decode(x.data) } + } else if (x.num === 21 && x.wire === 2 && x.data.length) { + // delta_signature_type: whose signature it is ("anthropic") + yield { signatureType: dec.decode(x.data) } } else if (x.num === 6 && x.wire === 2) { let id = "" let name = "" @@ -1811,7 +1839,7 @@ async function roundtrip({ key, server, families, keep }, chat, signal, wire = C return head.value.error } const it = prepend(head.value, source) - return { it: keep ? keptAfter(it, keep, { key, server, msg, sentAt }) : it } + return { it: keep ? keptAfter(it, keep, { key, server, msg, sentAt }) : it, uid } } // complete answers a chat completion through GetChatMessage. @@ -1850,7 +1878,11 @@ async function complete({ key, server, families, keep }, chat, signal) { began = true ctl.enqueue(chunk({ role: "assistant", content: "" })) } - const r = await it.next() + // a pull that sends nothing isn't pulled again: what a chat + // completion has no field for (a thinking signature) is passed over + let r + do r = await it.next() + while (!r.done && (r.value.signature || r.value.signatureType)) if (r.done) { ctl.enqueue(enc.encode("data: [DONE]\n\n")) return ctl.close() @@ -1912,6 +1944,7 @@ function anthropicEffort(req) { // 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) { + const claude = isClaude(uid) // Messages alternate roles; a client that sends two of one role in a row // means one turn const turns = [] @@ -1939,21 +1972,34 @@ function buildMessages(req, uid, key) { const own = [] const calls = [] let mark = false // a tool_use the client marked: the prompt with the calls ends there + // a signed thinking block, for the prompt that follows it: Claude's + // thinking goes back with its signature, which Anthropic wants on a + // tool loop's next turn (plugins#665). Unsigned thinking, and any to + // a model that isn't Claude, goes no further, as before. + let thought = null + const take = (p) => { + if (thought) [p.thinking, thought] = [thought, null] + return p + } for (const b of t.blocks) { if (b?.type === "text" && typeof b.text === "string") { - if (b.text) own.push({ role: ASSISTANT, text: b.text, calls: [], cache: marked(b) }) + if (b.text) own.push(take({ role: ASSISTANT, text: b.text, calls: [], cache: marked(b) })) else if (marked(b) && own.length) own[own.length - 1].cache = true } 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) { + // two in a row: the first has a prompt of its own + if (thought) own.push(take({ role: ASSISTANT, text: "", calls: [] })) + thought = { text: typeof b.thinking === "string" ? b.thinking : "", signature: b.signature, type: sigTypeOf(b.signature) } } - // thinking goes no further: Devin keeps none of a reply's } if (calls.length) { - if (!own.length) own.push({ role: ASSISTANT, text: "", calls: [] }) + if (!own.length || (thought && own[own.length - 1].thinking)) own.push({ role: ASSISTANT, text: "", calls: [] }) + take(own[own.length - 1]) own[own.length - 1].calls = calls own[own.length - 1].cache ||= mark - } + } else if (thought && own.length && !own[own.length - 1].thinking) take(own[own.length - 1]) if (!own.length) continue // a turn that only thought answer() msgs.push(...own) @@ -2057,6 +2103,9 @@ async function completeMessages({ key, server, families, keep }, req, signal) { if (!rt.it) return anthropicError(rt) const it = rt.it const id = "msg_" + randomBytes(12).toString("hex") + // a signature is sent on for Claude's thinking only: another model's + // thinking stays unsigned, as before, so no path sends it on as Claude's + const claude = isClaude(rt.uid) if (!req.stream) { const content = [] @@ -2070,10 +2119,17 @@ async function completeMessages({ key, server, families, keep }, req, signal) { return n } const args = [] + let sigType = "" for await (const e of it) { if (e.error) return anthropicError(e.error) if (e.text) block("text").text += e.text if (e.reasoning) block("thinking").thinking += e.reasoning + // the signature goes on the thinking it signs, the last one + if (e.signature && claude) { + const t = content.findLast((b) => b.type === "thinking") + if (t) t.signature += e.signature + } + if (e.signatureType) sigType = e.signatureType if (e.tool) { args[e.tool.index] = "" content.push({ type: "tool_use", id: e.tool.id, name: e.tool.name, input: {}, index: e.tool.index }) @@ -2090,6 +2146,7 @@ async function completeMessages({ key, server, families, keep }, req, signal) { } delete b.index } + for (const b of content) if (b.type === "thinking") rememberSigType(b.signature, sigType) return Response.json({ id, type: "message", role: "assistant", model: req.model, content, stop_reason: stop, stop_sequence: null, usage }, { headers: { "X-Magpie-Sign-In": "kept" } }) } @@ -2097,6 +2154,8 @@ async function completeMessages({ key, server, families, keep }, req, signal) { let began = false let index = -1 let open = "" // the kind of the block being sent: text, thinking or tool_use + let sig = "" // the signature of the thinking block last sent + let sigType = "" const stream = new ReadableStream({ async pull(ctl) { if (!began) { @@ -2104,6 +2163,7 @@ async function completeMessages({ key, server, families, keep }, req, signal) { ctl.enqueue(sse("message_start", { message: { id, type: "message", role: "assistant", model: req.model, content: [], stop_reason: null, stop_sequence: null, usage: anthropicUsage() } })) } const close = () => { + if (open === "thinking") rememberSigType(sig, sigType) if (open) ctl.enqueue(sse("content_block_stop", { index })) open = "" } @@ -2113,15 +2173,37 @@ async function completeMessages({ key, server, families, keep }, req, signal) { open = kind ctl.enqueue(sse("content_block_start", { index, content_block })) } - const r = await it.next() - if (r.done) return ctl.close() + // a pull that sends nothing isn't pulled again: the events that send + // nothing are read past here + let r + for (;;) { + r = await it.next() + if (r.done) return ctl.close() + const q = r.value + if (q.signatureType) { + sigType = q.signatureType + rememberSigType(sig, sigType) + continue + } + // a signature goes on Claude's thinking block, before its stop, as + // Anthropic streams it; one that comes once the block has closed + // has no block to go on + if (q.signature && !(open === "thinking" && claude)) continue + break + } const e = r.value if (e.text) { if (open !== "text") start("text", { type: "text", text: "" }) ctl.enqueue(sse("content_block_delta", { index, delta: { type: "text_delta", text: e.text } })) } else if (e.reasoning) { - if (open !== "thinking") start("thinking", { type: "thinking", thinking: "", signature: "" }) + if (open !== "thinking") { + start("thinking", { type: "thinking", thinking: "", signature: "" }) + sig = "" + } ctl.enqueue(sse("content_block_delta", { index, delta: { type: "thinking_delta", thinking: e.reasoning } })) + } else if (e.signature) { + sig += e.signature + ctl.enqueue(sse("content_block_delta", { index, delta: { type: "signature_delta", signature: e.signature } })) } else if (e.tool) start("tool_use", { type: "tool_use", id: e.tool.id, name: e.tool.name, input: {} }) else if (e.args) { if (open === "tool_use") ctl.enqueue(sse("content_block_delta", { index, delta: { type: "input_json_delta", partial_json: e.args.text } })) @@ -3117,4 +3199,4 @@ export async function DevinAuthPlugin({ client, magpie } = {}, options = {}) { } // for tests -export const _internal = { 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 = { sigTypeOf, forgetSigTypes: () => sigTypes.clear(), 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/package.json b/packages/devin/package.json index b690ab5..fa62111 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.34", + "version": "0.1.35", "description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/devin/thinking-signature.test.mjs b/packages/devin/thinking-signature.test.mjs new file mode 100644 index 0000000..d9b298d --- /dev/null +++ b/packages/devin/thinking-signature.test.mjs @@ -0,0 +1,181 @@ +// Claude's thinking through Devin keeps its signature (plugins#665, +// Vigilans). GetChatMessageResponse carries it in delta_signature (field +// 10) and its type in delta_signature_type (21), beside delta_thinking (9); +// ChatMessagePrompt takes the thinking back in thinking (11), signature +// (12) and signature_type (18). The field numbers are the ones in Devin's +// proto (devin2api's all-protos.proto: GetChatMessageResponse, +// ExaChatPb_ChatMessagePrompt); the frames below are built from them, not +// captured from Devin. +import { afterEach, expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +const { PB, frame, fields, buildMessages, completeMessages, build, events, familiesOf, SNAPSHOT } = _internal +const dec = new TextDecoder() +const enc = new TextEncoder() +const real = globalThis.fetch +afterEach(() => { + globalThis.fetch = real + _internal.forgetSigTypes?.() +}) + +const SIG = "EqQBCkgIBRABGAIiQL2xYzRvY0RzZWNyZXRzaWduYXR1cmU=" + +// tail is a Connect stream's end frame, {} +const tail = () => { + const end = enc.encode("{}") + const t = new Uint8Array(5 + end.length) + t[0] = 2 + new DataView(t.buffer).setUint32(1, end.length) + t.set(end, 5) + return t +} +// reply is Devin's answer: thinking, its signature split in two deltas +// (the second frame also says the type), then text and the finish +const reply = (type = "anthropic") => { + const usage = new PB().varint(2, 10).varint(3, 5).done() + return new Response( + new Blob([ + frame(new PB().str(9, "Let me think.").done()), + frame(new PB().str(10, SIG.slice(0, 20)).done()), + frame(new PB().str(10, SIG.slice(20)).str(21, type).done()), + frame(new PB().str(3, "Hello.").done()), + frame(new PB().varint(5, 1).bytes(7, usage).done()), + tail(), + ]), + ) +} +const ctx = { key: "k", server: "https://devin.test", families: familiesOf(SNAPSHOT) } +const req = (model, stream) => ({ model, max_tokens: 64, stream, thinking: { type: "adaptive" }, messages: [{ role: "user", content: "hi" }] }) + +// prompts is each ChatMessagePrompt a request sends: its role, text, +// calls, and the thinking it carries back +const prompts = (body) => + fields(body) + .filter((f) => f.num === 3 && f.wire === 2) + .map((f) => { + const p = { role: 0, text: "", calls: [], thinking: null, signature: null, type: 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 === 6) p.calls.push(dec.decode(fields(g.data).find((h) => h.num === 2).data)) + else if (g.num === 11) p.thinking = dec.decode(g.data) + else if (g.num === 12) p.signature = dec.decode(g.data) + else if (g.num === 18) p.type = dec.decode(g.data) + } + return p + }) + +test("the reply's signature and its type are read", async () => { + const got = [] + async function* fr() { + yield { data: new PB().str(9, "hm").str(10, SIG).str(21, "anthropic").done() } + yield { data: new PB().str(3, "ok").done() } + } + for await (const e of events(fr())) got.push(e) + expect(got.slice(0, 4)).toEqual([{ reasoning: "hm" }, { signature: SIG }, { signatureType: "anthropic" }, { text: "ok" }]) +}) + +test("a whole Messages reply's thinking carries Claude's signature", async () => { + globalThis.fetch = async () => reply() + const j = await (await completeMessages(ctx, req("claude-opus-5-5", false))).json() + expect(j.content).toEqual([ + { type: "thinking", thinking: "Let me think.", signature: SIG }, + { type: "text", text: "Hello." }, + ]) +}) + +test("a streamed Messages reply sends the signature before the thinking block stops", async () => { + globalThis.fetch = async () => reply() + const res = await completeMessages(ctx, req("claude-opus-5-5", true)) + const ev = (await res.text()).split("\n").filter((l) => l.startsWith("data: ")).map((l) => JSON.parse(l.slice(6))) + expect(ev.map((e) => e.type + (e.delta?.type ? ":" + e.delta.type : ""))).toEqual([ + "message_start", + "content_block_start", + "content_block_delta:thinking_delta", + "content_block_delta:signature_delta", + "content_block_delta:signature_delta", + "content_block_stop", + "content_block_start", + "content_block_delta:text_delta", + "content_block_stop", + "message_delta", + "message_stop", + ]) + expect(ev[1].content_block).toEqual({ type: "thinking", thinking: "", signature: "" }) + expect(ev[3].delta.signature + ev[4].delta.signature).toBe(SIG) + expect(ev[3].index).toBe(0) +}) + +test("another model's thinking stays unsigned, as before", async () => { + globalThis.fetch = async () => reply("openai") + const j = await (await completeMessages(ctx, req("deepseek-v4-flash", false))).json() + expect(j.content[0]).toEqual({ type: "thinking", thinking: "Let me think.", signature: "" }) + globalThis.fetch = async () => reply("openai") + const ev = (await (await completeMessages(ctx, req("deepseek-v4-flash", true))).text()).split("\n").filter((l) => l.startsWith("data: ")).map((l) => JSON.parse(l.slice(6))) + expect(ev.some((e) => e.delta?.type === "signature_delta")).toBe(false) +}) + +const history = (assistant) => ({ + model: "claude-opus-5-5", + messages: [ + { role: "user", content: "Read /a." }, + { role: "assistant", content: assistant }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_01", content: "A" }] }, + ], +}) +const use = { type: "tool_use", id: "toolu_01", name: "read_file", input: { path: "/a" } } + +test("the next request sends Claude's signed thinking back on the prompt that follows it", () => { + const ps = prompts(buildMessages(history([{ type: "thinking", thinking: "Read it first.", signature: SIG }, { type: "text", text: "Reading it." }, use]), "claude-opus-5-5", "k")) + const a = ps.find((p) => p.role === 2) + expect(a).toEqual({ role: 2, text: "Reading it.", calls: ["read_file"], thinking: "Read it first.", signature: SIG, type: "anthropic" }) + // with no text, the calls' prompt carries it + const only = prompts(buildMessages(history([{ type: "thinking", thinking: "t", signature: SIG }, use]), "claude-opus-5-5", "k")).find((p) => p.role === 2) + expect(only).toEqual({ role: 2, text: "", calls: ["read_file"], thinking: "t", signature: SIG, type: "anthropic" }) +}) + +test("thinking after the text goes on a prompt of its own ahead of the calls", () => { + const ps = prompts( + buildMessages( + history([{ type: "thinking", thinking: "one", signature: "s1" }, { type: "text", text: "Reading it." }, { type: "thinking", thinking: "two", signature: "s2" }, use]), + "claude-opus-5-5", + "k", + ), + ).filter((p) => p.role === 2) + expect(ps.map((p) => [p.text, p.calls, p.thinking, p.signature])).toEqual([ + ["Reading it.", [], "one", "s1"], + ["", ["read_file"], "two", "s2"], + ]) +}) + +test("the signature's type Devin said goes back with it", async () => { + globalThis.fetch = async () => reply("anthropic-bedrock") + const j = await (await completeMessages(ctx, req("claude-opus-5-5", false))).json() + expect(_internal.sigTypeOf?.(SIG)).toBe("anthropic-bedrock") + const a = prompts(buildMessages(history([...j.content, use]), "claude-opus-5-5", "k")).find((p) => p.role === 2) + expect([a.thinking, a.signature, a.type]).toEqual(["Let me think.", SIG, "anthropic-bedrock"]) +}) + +test("unsigned thinking, and thinking to another model, goes no further", () => { + const unsigned = prompts(buildMessages(history([{ type: "thinking", thinking: "t", signature: "" }, use]), "claude-opus-5-5", "k")).find((p) => p.role === 2) + expect([unsigned.thinking, unsigned.signature, unsigned.type]).toEqual([null, null, null]) + const other = prompts(buildMessages(history([{ type: "thinking", thinking: "t", signature: SIG }, use]), "deepseek-v4-flash-high", "k")).find((p) => p.role === 2) + expect([other.thinking, other.signature, other.type]).toEqual([null, null, null]) + // a turn that only thought still sends nothing of its own + const ps = prompts(buildMessages({ messages: [{ role: "user", content: "hi" }, { role: "assistant", content: [{ type: "thinking", thinking: "t", signature: SIG }] }] }, "claude-opus-5-5", "k")) + expect(ps.some((p) => p.role === 2)).toBe(false) +}) + +test("a chat completion's request is the same as before", () => { + const chat = { messages: [{ role: "user", content: "hi" }, { role: "assistant", content: "yo", reasoning_content: "t" }, { role: "user", content: "go" }] } + const ps = prompts(build(chat, "claude-opus-5-5", "k")) + expect(ps.every((p) => p.thinking === null && p.signature === null && p.type === null)).toBe(true) +}) + +test("a streamed chat completion passes the signature over and still ends", async () => { + globalThis.fetch = async () => reply() + const res = await _internal.complete(ctx, { model: "claude-opus-5-5", stream: true, messages: [{ role: "user", content: "hi" }] }) + const lines = (await res.text()).split("\n").filter((l) => l.startsWith("data: ")) + expect(lines[lines.length - 1]).toBe("data: [DONE]") + expect(lines.some((l) => l.includes(SIG.slice(0, 20)))).toBe(false) +})