diff --git a/packages/devin/README.md b/packages/devin/README.md index 6e77252..7a104ac 100644 --- a/packages/devin/README.md +++ b/packages/devin/README.md @@ -50,8 +50,10 @@ The plugin's `fetch` handles this: are sent as the tools' own. - A tool call the conversation never answered is answered with "Tool use was interrupted and did not produce a result." - - Images must be inline (`data:` URLs); images in tool results are - dropped. + - Images must be inline (`data:` URLs). The images a tool returned go + with its result, as magpie's built-in sends them: a tool message's own + `image_url` parts, and the ones magpie's gateway puts in the user + message after the results ("[From the result of …]"). - It turns the streamed reply back into a chat completion, streamed or not: text, reasoning, tool calls and usage. - Failures keep their statuses: a refused token is a 401, a usage limit a diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index 8f6663c..a5a494d 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -1334,6 +1334,32 @@ function formatText(f) { return "Respond with a single JSON value and nothing else, matching this JSON schema:\n" + JSON.stringify(schema) + "." } +// inlineImage is an image_url part as Devin takes an image, its bytes and +// type, or null for one that carries no bytes: Devin takes no URL, and +// magpie's built-in sends only an image with its bytes (inlineImages). +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 +} + +// A chat's tool message holds text alone, so magpie's gateway (buildChat's +// seeLater) sends the images a tool returned in the user message after the +// results: each result's text ends saying how many follow (NOTE), and its +// images are headed FROM " (tool call ):]" or FROM +// "tool call :]", ahead of the user's own words and images. +const FROM = "[From the result of " +const NOTE = /(?:\n\n)?\[The tool returned (an image; it|(\d+) images; they) follows? in the next message\.\]$/ + +// noted is how many images a result's text says follow it, and its text +// without saying so. +function noted(text) { + const m = NOTE.exec(text) + if (!m) return { n: 0, text } + return { n: m[2] ? Number(m[2]) : 1, text: text.slice(0, m.index) } +} + // build is the GetChatMessage request for a chat completion, to the model // uid. function build(chat, uid, key) { @@ -1344,11 +1370,30 @@ function build(chat, uid, key) { pending = [] } const system = [] + // the results just sent, by the call id the chat gave each, for the + // images that follow them in the user message after + const results = new Map() + const resultFor = (text) => { + if (typeof text !== "string" || !text.startsWith(FROM)) return null + for (const [id, r] of results) if (r.said.n > r.seen && (text === `${FROM}tool call ${id}:]` || text.endsWith(` (tool call ${id}):]`))) return r + return null + } + // settleResults gives each result just sent its text: without the note + // that its images follow when every one went back with it, and "(no + // output)" for none, as the built-in words it + const settleResults = () => { + for (const r of results.values()) { + if (r.said.n > 0 && r.seen === r.said.n) r.msg.text = r.said.text + r.msg.text ||= "(no output)" + } + results.clear() + } for (const m of joinSplitCalls(chat.messages ?? [])) { if (m.role === "system" || m.role === "developer") { system.push(textOf(m.content)) continue } + if (m.role !== "tool" && m.role !== "user") settleResults() if (m.role === "assistant") { const calls = (m.tool_calls ?? []).map((c) => ({ id: inID(c.id), name: c.function?.name, args: argsOf(c.function?.arguments) })) const text = typeof m.content === "string" ? m.content : Array.isArray(m.content) ? m.content.filter((p) => p?.type === "text" && p.text).map((p) => p.text).join("\n\n") : "" @@ -1364,8 +1409,10 @@ function build(chat, uid, key) { // only a call just made is answered, and only once const i = pending.findIndex((c) => c.id === inID(m.tool_call_id)) if (i >= 0) { - let out = textOf(m.content) || "(no output)" - msgs.push({ role: TOOL, callID: pending[i].id, text: out }) + const images = Array.isArray(m.content) ? m.content.map(inlineImage).filter(Boolean) : [] + const msg = { role: TOOL, callID: pending[i].id, text: textOf(m.content), images } + msgs.push(msg) + results.set(m.tool_call_id, { msg, said: noted(msg.text), seen: 0 }) pending.splice(i, 1) } continue @@ -1375,20 +1422,32 @@ function build(chat, uid, key) { const images = [] if (typeof m.content === "string") { if (m.content) texts.push(m.content) - } else + } else { + // the images a tool returned, which a chat's tool message can't + // hold, go back with the result that returned them, as magpie's + // built-in sends them (inlineImages): a tool message's images + // (field 10) and not a user message of their own + let to = null // the result the images that follow are of, until it has the number it said for (const p of m.content ?? []) { - if (p?.type === "text" && p.text) texts.push(p.text) - else if (p?.type === "image_url") { - const u = typeof p.image_url === "string" ? p.image_url : p.image_url?.url ?? "" - const d = /^data:([^,]*),(.*)$/s.exec(u) - if (d && d[2]) images.push({ data: d[2], type: d[1].replace(/;base64$/, "") || "image/png" }) + if (p?.type === "text") { + to = results.size ? resultFor(p.text) : null + if (!to && p.text) texts.push(p.text) + } else if (p?.type === "image_url") { + const im = inlineImage(p) + if (to) { + if (im) to.msg.images.push(im) + if (++to.seen === to.said.n) to = null + } else if (im) images.push(im) } } + } + settleResults() const text = texts.join("\n\n") if (!text && !images.length) continue answer() msgs.push({ role: USER, text, images }) } + settleResults() answer() // Devin has no field for the answer's format: it is told in words, at // the end of the instructions, as magpie's built-in tells it (inSystem) diff --git a/packages/devin/package.json b/packages/devin/package.json index ec213ae..d04bd8a 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.19", + "version": "0.1.20", "description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/devin/testdata/chat-tool-image.json b/packages/devin/testdata/chat-tool-image.json new file mode 100644 index 0000000..51afc6a --- /dev/null +++ b/packages/devin/testdata/chat-tool-image.json @@ -0,0 +1 @@ +{"messages":[{"content":"使用computer use截图当前屏幕看下","role":"user"},{"role":"assistant","tool_calls":[{"function":{"arguments":"{\"path\":\"/tmp/magpie_icon.png\"}","name":"view_image"},"id":"call_view1","type":"function"}]},{"content":"[The tool returned an image; it follows in the next message.]","role":"tool","tool_call_id":"call_view1"},{"content":[{"text":"[From the result of view_image (tool call call_view1):]","type":"text"},{"image_url":{"url":"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="},"type":"image_url"}],"role":"user"}],"model":"swe-2","stream":true,"stream_options":{"include_usage":true}} \ No newline at end of file diff --git a/packages/devin/testdata/chat-tool-images-two.json b/packages/devin/testdata/chat-tool-images-two.json new file mode 100644 index 0000000..3028966 --- /dev/null +++ b/packages/devin/testdata/chat-tool-images-two.json @@ -0,0 +1 @@ +{"max_tokens":10,"messages":[{"content":"shot","role":"user"},{"role":"assistant","tool_calls":[{"function":{"arguments":"{\"p\":\"a.png\"}","name":"Read"},"id":"toolu_1","type":"function"},{"function":{"arguments":"{\"p\":\"b.png\"}","name":"Read"},"id":"toolu_2","type":"function"}]},{"content":"two pics\n\n[The tool returned 2 images; they follow in the next message.]","role":"tool","tool_call_id":"toolu_1"},{"content":"plain","role":"tool","tool_call_id":"toolu_2"},{"content":[{"text":"[From the result of Read (tool call toolu_1):]","type":"text"},{"image_url":{"url":"data:image/png;base64,AAAA"},"type":"image_url"},{"image_url":{"url":"data:image/jpeg;base64,BBBB"},"type":"image_url"},{"image_url":{"url":"data:image/gif;base64,CCCC"},"type":"image_url"},{"text":"what are these?","type":"text"}],"role":"user"}],"model":"swe-2","stream":false} \ No newline at end of file diff --git a/packages/devin/tool-images.test.mjs b/packages/devin/tool-images.test.mjs new file mode 100644 index 0000000..3490160 --- /dev/null +++ b/packages/devin/tool-images.test.mjs @@ -0,0 +1,101 @@ +// The images a tool returned go to Devin with the result that returned +// them, as magpie's built-in sends them (internal/gateway/devin.go, +// buildDevin: a tool message's images, inlineImages(p.Images)). A chat's +// tool message holds text alone, so magpie's gateway hands the plugin those +// images in the user message after the results (buildChat's seeLater); the +// plugin sent them to Devin as a user message of their own, where the +// built-in sent them as the tool's. +import { expect, test } from "bun:test" +import { readFileSync } from "node:fs" +import { join } from "node:path" +import { _internal } from "./index.mjs" + +const dec = new TextDecoder() + +// sent is each message sent: its role, text, the call it answers and its +// images (data and type). +const sent = (b) => + _internal + .fields(b) + .filter((f) => f.num === 3 && f.wire === 2) + .map((f) => { + const m = { role: 0, text: "", answers: "", images: [] } + for (const g of _internal.fields(f.data)) { + if (g.num === 2) m.role = g.n + else if (g.num === 3) m.text = dec.decode(g.data) + else if (g.num === 7) m.answers = dec.decode(g.data) + else if (g.num === 10) m.images.push(_internal.fields(g.data).map((h) => dec.decode(h.data))) + } + return m + }) + +const PNG = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==" + +// magpie's buildChat bodies, as it wrote them (origin/main b03031738, +// buildChat for a Devin model): Codex's view_image turn +// (tool_images_1861_test.go, codexViewImage), and two Read results, the +// first with text and two images, then the user's own image and words +const read = (name) => JSON.parse(readFileSync(join(import.meta.dir, "testdata", name), "utf8")) +const viewImage = read("chat-tool-image.json") + +test("a tool's image goes to Devin with its result, not in a user message of its own", () => { + const got = sent(_internal.build(viewImage, "swe-2", "k")) + expect(got.map((m) => m.role)).toEqual([1, 2, 4]) + const tool = got[2] + expect(tool.answers).toBe("call_view1") + // nothing but the image came back, as the built-in says it + expect(tool.text).toBe("(no output)") + expect(tool.images).toEqual([[PNG, "image/png"]]) +}) + +test("each result keeps its own images and the user's own words and images stay theirs", () => { + const chat = read("chat-tool-images-two.json") + const got = sent(_internal.build(chat, "swe-2", "k")) + expect(got.map((m) => [m.role, m.answers, m.text, m.images])).toEqual([ + [1, "", "shot", []], + [2, "", "", []], + [4, "toolu_1", "two pics", [["AAAA", "image/png"], ["BBBB", "image/jpeg"]]], + [4, "toolu_2", "plain", []], + [1, "", "what are these?", [["CCCC", "image/gif"]]], + ]) +}) + +test("a tool message's own images go with it, and an image Devin can't take (a URL) is left out", () => { + const chat = { + messages: [ + { role: "user", content: "look" }, + { role: "assistant", content: "", tool_calls: [{ id: "c1", type: "function", function: { name: "shot", arguments: "{}" } }] }, + { + role: "tool", + tool_call_id: "c1", + content: [ + { type: "text", text: "done" }, + { type: "image_url", image_url: { url: "data:image/webp;base64,DDDD" } }, + { type: "image_url", image_url: { url: "https://example.com/x.png" } }, + ], + }, + ], + } + const got = sent(_internal.build(chat, "swe-2", "k")) + expect(got[2]).toEqual({ role: 4, text: "done", answers: "c1", images: [["DDDD", "image/webp"]] }) +}) + +test("a user's own words that look like the heading but answer no result just sent stay the user's", () => { + const chat = { + messages: [ + { role: "user", content: "hi" }, + { role: "assistant", content: "ok", tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "c1", content: "text only" }, + { + role: "user", + content: [ + { type: "text", text: "[From the result of read (tool call c9):]" }, + { type: "image_url", image_url: { url: "data:image/png;base64,EEEE" } }, + ], + }, + ], + } + const got = sent(_internal.build(chat, "swe-2", "k")) + expect(got[2]).toEqual({ role: 4, text: "text only", answers: "c1", images: [] }) + expect(got[3]).toEqual({ role: 1, text: "[From the result of read (tool call c9):]", answers: "", images: [["EEEE", "image/png"]] }) +})