diff --git a/packages/devin/README.md b/packages/devin/README.md index dbc62ed..db60cc8 100644 --- a/packages/devin/README.md +++ b/packages/devin/README.md @@ -86,6 +86,13 @@ The plugin's `fetch` handles this: #275): Devin turns a body past 10 MiB away with 413. - It turns the streamed reply back into a chat completion, streamed or not: text, reasoning, tool calls and usage. +- A Gemini model's reply goes back with its thought signature, as the CLI + sends it: on the prompt with the reply's calls (or its words), with + `signature_type` "gemini" and the model that wrote it (since 0.1.41). + Neither a chat completion nor a Messages `tool_use` carries one, so the + plugin keeps each reply's signature by its call ids for the next + request, in memory: after a restart, earlier turns go back unsigned, as + 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. - A reply with only metadata and usage is a 502, even when output tokens diff --git a/packages/devin/gemini-thought.test.mjs b/packages/devin/gemini-thought.test.mjs new file mode 100644 index 0000000..f62ad17 --- /dev/null +++ b/packages/devin/gemini-thought.test.mjs @@ -0,0 +1,131 @@ +// A Gemini reply goes back to Devin with its thought signature, as the +// devin CLI sends it: a reply from gemini-4-hydrogen carries one in +// delta_signature (10), typed "gemini" (21), and the CLI's next request +// has it on the prompt with the reply's call, in signature (12), +// signature_type (18) and the model that wrote it (22). Without it, +// Devin's Gemini models deep in a dsh tool loop answered with usage and +// nothing else (X, @liuzhengdong99, magpie 0.1.4146). +// testdata/gemini-tool-reply.bin is a real GetChatMessage reply from +// gemini-4-hydrogen-medium to the devin CLI (a call to exec), captured +// through WINDSURF_API_SERVER_URL; it has the bot id, response id and +// usage, no credentials. +import { afterEach, expect, test } from "bun:test" +import { readFile } from "node:fs/promises" +import { _internal } from "./index.mjs" + +const { PB, frame, fields, build, buildMessages, complete, completeMessages, familiesOf, SNAPSHOT } = _internal +const dec = new TextDecoder() +const real = globalThis.fetch +afterEach(() => { + globalThis.fetch = real + _internal.forgetThoughts?.() +}) + +const captured = await readFile(new URL("./testdata/gemini-tool-reply.bin", import.meta.url)) +const SIG = "AY89a1+u1EAPOiO7CmhB" +const CALL = "call_11646388125050983982" +const UID = "gemini-4-hydrogen-medium" +// Devin's list for the account that captured it has Gemini 4 Hydrogen, +// which the snapshot predates +const hydrogen = { uid: "gemini-4-hydrogen", label: "Gemini 4 Hydrogen", aliases: [], models: ["low", "medium", "high"].map((e) => ({ id: "gemini-4-hydrogen-" + e, name: "Gemini 4 Hydrogen " + e, context: 1048576, output: 65535 })) } +const families = [...familiesOf(SNAPSHOT), hydrogen] +const ctx = { key: "k", server: "https://devin.test", families } + +// prompts is each ChatMessagePrompt a request sends, with the thought it +// carries back +const prompts = (body) => + fields(body) + .filter((f) => f.num === 3 && f.wire === 2) + .map((f) => { + const p = { role: 0, calls: [], thinking: null, signature: null, type: null, model: null } + for (const g of fields(f.data)) { + if (g.num === 2) p.role = g.n + else if (g.num === 6) p.calls.push(dec.decode(fields(g.data).find((h) => h.num === 1).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) + else if (g.num === 22) p.model = dec.decode(g.data) + } + return p + }) + +// replyAndNext sends one request to the captured reply through the given +// wire, reads the reply whole, and builds the next request with the +// reply's call answered, to the model next +async function chatAndNext(stream, next = UID) { + globalThis.fetch = async () => new Response(captured) + const res = await complete(ctx, { model: "gemini-4-hydrogen", reasoning_effort: "medium", stream, messages: [{ role: "user", content: "cat calc.py" }] }) + expect(res.status).toBe(200) + let call + if (stream) { + for (const l of (await res.text()).split("\n")) { + const tc = l.startsWith("data: {") && JSON.parse(l.slice(6)).choices?.[0]?.delta?.tool_calls?.[0] + if (tc?.id) call = { id: tc.id, type: "function", function: { name: tc.function.name, arguments: '{"command":"cat calc.py"}' } } + } + } else call = (await res.json()).choices[0].message.tool_calls[0] + expect(call.id).toBe(CALL) + const messages = [ + { role: "user", content: "cat calc.py" }, + { role: "assistant", content: "", tool_calls: [call] }, + { role: "tool", tool_call_id: call.id, content: "def add(a,b): return a+b" }, + ] + return prompts(build({ model: "x", messages }, next, "k")) +} + +for (const stream of [false, true]) + test(`a chat completion's Gemini call goes back with its signature, as the CLI sends it (stream ${stream})`, async () => { + const ps = await chatAndNext(stream) + const a = ps.find((p) => p.calls.length) + expect(a.calls).toEqual([CALL]) + expect(a.signature?.startsWith(SIG)).toBe(true) + expect(a.type).toBe("gemini") + expect(a.model).toBe(UID) + // the prompts around it carry none + expect(ps.filter((p) => p.signature).length).toBe(1) + }) + +test("a Gemini signature goes back to Gemini only", async () => { + for (const next of ["swe-2-medium", "claude-opus-4-6"]) { + const ps = await chatAndNext(false, next) + expect(ps.some((p) => p.signature || p.type || p.model)).toBe(false) + } +}) + +test("a call the plugin never saw goes back as before, unsigned", () => { + const messages = [ + { role: "user", content: "hi" }, + { role: "assistant", content: "", tool_calls: [{ id: "call_1", type: "function", function: { name: "exec", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "call_1", content: "ok" }, + ] + expect(prompts(build({ model: "x", messages }, UID, "k")).some((p) => p.signature)).toBe(false) +}) + +for (const stream of [false, true]) + test(`a Messages Gemini tool_use goes back with its signature (stream ${stream})`, async () => { + globalThis.fetch = async () => new Response(captured) + const res = await completeMessages(ctx, { model: "gemini-4-hydrogen", max_tokens: 64, stream, output_config: { effort: "medium" }, messages: [{ role: "user", content: "cat calc.py" }] }) + expect(res.status).toBe(200) + let id + if (stream) id = /"id":"(call_[0-9]+)"/.exec(await res.text())[1] + else id = (await res.json()).content.find((b) => b.type === "tool_use").id + const messages = [ + { role: "user", content: "cat calc.py" }, + { role: "assistant", content: [{ type: "tool_use", id, name: "exec", input: { command: "cat calc.py" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: id, content: "def add(a,b): return a+b" }] }, + ] + const a = prompts(buildMessages({ model: "x", messages }, UID, "k")).find((p) => p.calls.length) + expect(a.signature?.startsWith(SIG)).toBe(true) + expect(a.type).toBe("gemini") + expect(a.model).toBe(UID) + }) + +test("a Gemini reply with only words goes back signed by its words", async () => { + const usage = new PB().varint(2, 10).varint(3, 5).done() + globalThis.fetch = async () => + new Response(new Blob([frame(new PB().str(3, "Hi there,").done()), frame(new PB().str(3, " friend!").str(10, "SIGTEXT").str(21, "gemini").done()), frame(new PB().varint(5, 1).bytes(7, usage).done())])) + const j = await (await complete(ctx, { model: "gemini-4-hydrogen", reasoning_effort: "medium", messages: [{ role: "user", content: "hi" }] })).json() + expect(j.choices[0].message.content).toBe("Hi there, friend!") + const messages = [{ role: "user", content: "hi" }, j.choices[0].message, { role: "user", content: "again" }] + const a = prompts(build({ model: "x", messages }, UID, "k")).find((p) => p.role === 2) + expect([a.signature, a.type, a.model]).toEqual(["SIGTEXT", "gemini", UID]) +}) diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index 00cac4d..b490a5b 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -1523,7 +1523,11 @@ function build(chat, uid, key) { // completion has no field for a signature, and Claude's thinking // goes back only signed (plugins#665), so Claude gets none, as before. const reasoning = claude ? "" : reasoningOf(m) - msgs.push({ role: ASSISTANT, text, calls, ...(reasoning ? { thinking: { text: reasoning } } : {}) }) + // a Gemini reply goes back with its thought signature, as the + // devin CLI sends it (thoughts) + const signed = 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 // reply that made it, which goes to Devin with every call it made pending = [...calls] @@ -1665,6 +1669,7 @@ function encodeMsg(m) { if (m.thinking?.signature) { b.str(12, m.thinking.signature) if (m.thinking.type) b.str(18, m.thinking.type) + if (m.thinking.model) b.str(22, m.thinking.model) } return b.done() } @@ -1683,6 +1688,37 @@ function rememberSigType(signature, type) { } const sigTypeOf = (signature) => sigTypes.get(signature) ?? "anthropic" +// thoughts is each Gemini reply's thought signature, by the reply's tool +// call ids (or, for a reply that made none, its text), for the request +// that sends the reply back. The devin CLI sends a Gemini reply back with +// its signature (12), its type "gemini" (18) and the model that wrote it +// (22); without them Devin's Gemini models, deep in a tool loop, answer +// with usage and nothing else (X, gemini-4-hydrogen in dsh). Neither a +// chat completion nor a Messages tool_use has a field for it, so it is +// kept here, as sigTypes are; the most recent are kept. +const thoughts = new Map() +const THOUGHTS_KEPT = 4096 +const isGemini = (uid) => /gemini/i.test(String(uid ?? "")) +const textKey = (text) => "text:" + createHash("sha256").update(String(text).replace(/\s+/g, "")).digest("base64url") +function rememberThought({ calls, text }, thought) { + const keys = calls.length ? calls : text ? [textKey(text)] : [] + for (const k of keys) { + thoughts.delete(k) + thoughts.set(k, thought) + if (thoughts.size > THOUGHTS_KEPT) thoughts.delete(thoughts.keys().next().value) + } +} +// thoughtFor is the signature kept for a reply sent back with these calls +// (Devin's ids) and text, to a Gemini model; null for none. +function thoughtFor(uid, calls, text) { + if (!isGemini(uid)) return null + for (const c of calls) { + const t = thoughts.get(c.id) + if (t) return t + } + return (!calls.length && text && thoughts.get(textKey(text))) || null +} + // ---- the reply ----------------------------------------------------------------------- // statusText is a status as magpie's built-in words an error that says @@ -1719,10 +1755,12 @@ function failure(status, text) { // events turns the reply's frames into chat completion pieces: text, // reasoning, each tool call opened with its id and name, its arguments in // pieces after, then the finish with the usage. -async function* events(it) { +async function* events(it, uid = "") { let tools = -1 let stop = 0 let said = 0 + // a Gemini reply's thought signature, to go back with it (thoughts) + const own = { calls: [], text: "", signature: "", type: "" } const usage = { input: 0, output: 0, cacheWrite: 0, cacheRead: 0 } for (;;) { let r @@ -1745,17 +1783,23 @@ async function* events(it) { for (const x of fields(f.data)) { if (x.num === 3 && x.wire === 2 && x.data.length) { said += x.data.length - yield { text: dec.decode(x.data) } + const text = dec.decode(x.data) + own.text += text + yield { text } } 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) } + const signature = dec.decode(x.data) + own.signature += signature + yield { signature } } 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) } + const signatureType = dec.decode(x.data) + own.type = signatureType + yield { signatureType } } else if (x.num === 6 && x.wire === 2) { let id = "" let name = "" @@ -1767,7 +1811,9 @@ async function* events(it) { } if (name) { tools++ - yield { tool: { index: tools, id: id ? outID(id) : "call_" + randomBytes(12).toString("hex"), name } } + const tool = { index: tools, id: id ? outID(id) : "call_" + randomBytes(12).toString("hex"), name } + own.calls.push(inID(tool.id)) + yield { tool } } if (args && tools >= 0) yield { args: { index: tools, text: args } } } else if (x.num === 5 && x.wire === 0) stop = x.n @@ -1786,6 +1832,8 @@ async function* events(it) { yield { error: { status: 502, message: "an empty reply (Devin returned no text, reasoning or tool call)" } } return } + if (own.signature && isGemini(uid) && (own.type || "gemini") === "gemini") + rememberThought(own, { signature: own.signature, type: own.type || "gemini", model: uid }) if (!usage.output) usage.output = Math.floor((said + 3) / 4) const prompt = usage.input + usage.cacheRead + usage.cacheWrite yield { @@ -1860,7 +1908,7 @@ async function roundtrip({ key, server, families, keep }, chat, signal, wire = C return e.status < 300 ? { status: 502, message: "an empty reply" } : e } // 先等到实际内容或错误,才能让网关在空回复时切换渠道。 - const source = events(prepend(first.value, fr)) + const source = events(prepend(first.value, fr), uid) const head = await source.next() if (head.done) return { status: 502, message: "an empty reply" } if (head.value.error) { @@ -2033,6 +2081,14 @@ function buildMessages(req, uid, key) { 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]) + // 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 + if (signed) { + const p = own[own.length - 1] + p.thinking = { text: p.thinking?.text ?? "", ...signed } + } if (!own.length) continue // a turn that only thought answer() msgs.push(...own) @@ -3244,4 +3300,4 @@ export async function DevinAuthPlugin({ client, magpie } = {}, options = {}) { } // for tests -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 } +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 } diff --git a/packages/devin/package.json b/packages/devin/package.json index db76630..6bf80da 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.40", + "version": "0.1.41", "description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/devin/testdata/gemini-tool-reply.bin b/packages/devin/testdata/gemini-tool-reply.bin new file mode 100644 index 0000000..8788389 Binary files /dev/null and b/packages/devin/testdata/gemini-tool-reply.bin differ