diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs index 7dfff7b..4eb6d1d 100644 --- a/packages/devin/index.mjs +++ b/packages/devin/index.mjs @@ -5,6 +5,7 @@ // chat completion chunks. Ported from magpie's built-in Devin account // (internal/provider/devin*.go, internal/gateway/devin.go). +import { Buffer } from "node:buffer" import { createHash, randomBytes, randomUUID } from "node:crypto" import { createServer, STATUS_CODES } from "node:http" import { gunzipSync } from "node:zlib" @@ -1097,6 +1098,20 @@ const osName = () => (process.platform === "win32" ? "windows" : process.platfor const metadata = (key) => new PB().str(1, "devin-cli").str(2, CLI_VERSION).str(3, key).str(4, "en").str(5, osName()).str(7, CLI_VERSION).str(12, "chisel").str(28, "chisel") +// Devin names a call after its tool and turn (Bash:0#a65b6a5e…), and +// Claude Code takes a tool_use id only of [A-Za-z0-9_-]: it drops a call +// whose id has the ':' or '#', and the turn fails "could not be parsed" +// (yetone/magpie#1304). Such an id goes out as "dv_" and its base64url, and +// comes back to Devin as it was, so its result still answers its call. An +// id that is already safe goes out as it came, unless it begins "dv_". +const SAFE_ID = /^[A-Za-z0-9_-]+$/ +const outID = (id) => (SAFE_ID.test(id) && !id.startsWith("dv_") ? id : "dv_" + Buffer.from(id).toString("base64url")) +const inID = (id) => { + if (typeof id !== "string" || !id.startsWith("dv_") || !SAFE_ID.test(id)) return id + const raw = Buffer.from(id.slice(3), "base64url").toString() + return raw && outID(raw) === id ? raw : id +} + // build is the GetChatMessage request for a chat completion, to the model // uid. function build(chat, uid, key) { @@ -1113,7 +1128,7 @@ function build(chat, uid, key) { continue } if (m.role === "assistant") { - const calls = (m.tool_calls ?? []).map((c) => ({ id: c.id, name: c.function?.name, args: argsOf(c.function?.arguments) })) + 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") : "" if (!text && !calls.length) continue // a turn that only thought, or failed answer() @@ -1125,7 +1140,7 @@ function build(chat, uid, key) { } if (m.role === "tool") { // only a call just made is answered, and only once - const i = pending.findIndex((c) => c.id === m.tool_call_id) + 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 }) @@ -1286,7 +1301,7 @@ async function* events(it) { } if (name) { tools++ - yield { tool: { index: tools, id: id || "call_" + randomBytes(12).toString("hex"), name } } + yield { tool: { index: tools, id: id ? outID(id) : "call_" + randomBytes(12).toString("hex"), name } } } if (args && tools >= 0) yield { args: { index: tools, text: args } } } else if (x.num === 5 && x.wire === 0) stop = x.n @@ -1566,4 +1581,4 @@ export async function DevinAuthPlugin() { } // for tests -export const _internal = { objectRoot, seesImages, imagesFor, forgetSaid: () => said.clear(), parseModelConfigs, SNAPSHOT_IMAGES, withImages, forgetImages: () => (seen = null), effortOf, runtimeModel, configModel, live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readsHome, tierName, whoByKey, success, familiesFor, readCredentials, credentials, fields, frame, PB, events, frames } +export const _internal = { outID, inID, objectRoot, seesImages, imagesFor, forgetSaid: () => said.clear(), parseModelConfigs, SNAPSHOT_IMAGES, withImages, forgetImages: () => (seen = null), effortOf, runtimeModel, configModel, live, build, failure, complete, parseFamilies, listed, variantFor, familiesOf, SNAPSHOT, parseStatus, readsHome, tierName, whoByKey, success, familiesFor, readCredentials, credentials, fields, frame, PB, events, frames } diff --git a/packages/devin/package.json b/packages/devin/package.json index eb43659..d95b9ec 100644 --- a/packages/devin/package.json +++ b/packages/devin/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-devin-auth", - "version": "0.1.12", + "version": "0.1.13", "description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/devin/tool-ids.test.mjs b/packages/devin/tool-ids.test.mjs new file mode 100644 index 0000000..29fb977 --- /dev/null +++ b/packages/devin/tool-ids.test.mjs @@ -0,0 +1,84 @@ +// Devin's SWE-2 names a call "Bash:0#a65b6a5e02194b87bbc796c4428c946d" +// (yetone/magpie#1304, StarMoonCity's capture). Claude Code takes a +// tool_use id only of [A-Za-z0-9_-] and dropped every such call ("The +// model's tool call could not be parsed"). The id goes out safe, and its +// result goes back to Devin under the id Devin gave. +import { afterEach, expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +const { PB, frame, fields, build, complete } = _internal +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const RAW = "Bash:0#a65b6a5e02194b87bbc796c4428c946d" // the reporter's literal id +const ARGS = '{"command":"date","description":"Print the date"}' +const SAFE = /^[A-Za-z0-9_-]+$/ +const enc = new TextEncoder() +const dec = new TextDecoder() + +const reply = () => { + const call = new PB().str(1, RAW).str(2, "Bash").str(3, ARGS).done() + const msg = new PB().bytes(6, call).varint(5, 10).done() + const end = enc.encode("{}") + const tail = new Uint8Array(5 + end.length) + tail[0] = 2 + new DataView(tail.buffer).setUint32(1, end.length) + tail.set(end, 5) + return new Response(new Blob([frame(msg), tail])) +} + +const ask = async (stream) => { + globalThis.fetch = async () => reply() + const res = await complete( + { key: "k", server: "https://devin.test", families: _internal.familiesOf(_internal.SNAPSHOT) }, + { model: "swe-2", stream, messages: [{ role: "user", content: "用 Bash 跑一下 date" }] }, + ) + return res.text() +} + +const sentIDs = (chat) => { + const out = { calls: [], answers: [] } + for (const f of fields(build(chat, "swe-2-high", "k"))) { + if (f.num !== 3 || f.wire !== 2) continue + for (const g of fields(f.data)) { + if (g.num === 6) out.calls.push(dec.decode(fields(g.data).find((h) => h.num === 1).data)) + if (g.num === 7) out.answers.push(dec.decode(g.data)) + } + } + return out +} + +const answered = (id) => ({ + messages: [ + { role: "user", content: "用 Bash 跑一下 date" }, + { role: "assistant", content: null, tool_calls: [{ id, type: "function", function: { name: "Bash", arguments: ARGS } }] }, + { role: "tool", tool_call_id: id, content: "Thu Oct 8 10:00:00 CST 2026" }, + ], +}) + +for (const stream of [false, true]) + test(`Devin's call id goes out of [A-Za-z0-9_-] only and comes back as Devin gave it (${stream ? "streamed" : "whole"})`, async () => { + const body = await ask(stream) + let id + if (stream) { + for (const line of body.split("\n")) + if (line.startsWith("data: {")) id ??= JSON.parse(line.slice(6)).choices?.[0]?.delta?.tool_calls?.[0]?.id + } else id = JSON.parse(body).choices[0].message.tool_calls[0].id + expect(id).toMatch(SAFE) + const sent = sentIDs(answered(id)) + expect(sent.calls).toEqual([RAW]) + expect(sent.answers).toEqual([RAW]) + }) + +test("a safe id goes both ways as it came", () => { + for (const id of ["toolu_01AbC", "call_abc-123"]) { + expect(_internal.outID(id)).toBe(id) + expect(sentIDs(answered(id))).toEqual({ calls: [id], answers: [id] }) + } +}) + +test("an id of the caller's own that begins dv_ goes both ways as it came", () => { + for (const id of ["dv_", "dv_abc", "dv_QmFzaDowI2E"]) expect(_internal.inID(_internal.outID(id))).toBe(id) + // not one outID makes: sent to Devin untouched + for (const id of ["dv_", "dv_abc"]) expect(sentIDs(answered(id))).toEqual({ calls: [id], answers: [id] }) +})