diff --git a/packages/devin/README.md b/packages/devin/README.md
index 456ec0d..569f46e 100644
--- a/packages/devin/README.md
+++ b/packages/devin/README.md
@@ -57,6 +57,19 @@ The plugin's `fetch` handles this:
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 …]").
+- The Claude models are asked on Anthropic's Messages API
+ (`@ai-sdk/anthropic`, `POST …/devin/v1/messages`); every other model
+ stays on chat completions (since 0.1.28, #566).
+ - Each text block, system block, tool call turn and tool result is a
+ `ChatMessagePrompt` of its own, in the order the client sent them, and
+ one the client marked with `cache_control` carries
+ `prompt_cache_options {type: EPHEMERAL}` (field 8), as the devin CLI
+ marks its own. Blocks joined into one message lose the mark: a grown
+ history then read only ~558 tokens from the cache.
+ - Claude Code's `x-anthropic-billing-header` line isn't sent: its
+ `cch` changes every turn.
+ - The reply comes back as Anthropic's message or events, with the
+ cache's read and write in `usage`. `/messages/count_tokens` is a 404.
- A request past 8 KiB goes gzipped, as the CLI sends it (since 0.1.21,
#275): Devin turns a body past 10 MiB away with 413.
- It turns the streamed reply back into a chat completion, streamed or
diff --git a/packages/devin/cache-marks.test.mjs b/packages/devin/cache-marks.test.mjs
new file mode 100644
index 0000000..3c5bff4
--- /dev/null
+++ b/packages/devin/cache-marks.test.mjs
@@ -0,0 +1,174 @@
+// Claude Code marks the end of what it wants cached with cache_control on
+// a block, and a growing history (its Auto mode's classifier asks) moves
+// the mark onto the block it adds. On chat completions the blocks were
+// joined into one text with no mark, so a grown history read only ~558
+// tokens from the cache (plugins#566, zelong77). Devin's Claude models are
+// now asked on Anthropic's Messages API: each block goes to Devin as a
+// ChatMessagePrompt of its own, and a marked one carries
+// prompt_cache_options {type: EPHEMERAL} (field 8, 0801), as the devin
+// CLI sends its own.
+import { afterEach, expect, test } from "bun:test"
+import { _internal } from "./index.mjs"
+import { DevinAuthPlugin } from "./index.mjs"
+
+const { PB, frame, fields, buildMessages, completeMessages, build, configModel, runtimeModel, listed, familiesOf, SNAPSHOT, anthropicEffort } = _internal
+const dec = new TextDecoder()
+const enc = new TextEncoder()
+const real = globalThis.fetch
+afterEach(() => (globalThis.fetch = real))
+
+// prompts is each ChatMessagePrompt a request sends: its role, text, call
+// id, calls and field 8's raw bytes
+const prompts = (body) =>
+ fields(body)
+ .filter((f) => f.num === 3 && f.wire === 2)
+ .map((f) => {
+ const p = { role: 0, text: "", cache: null, callID: "", calls: [], images: 0 }
+ 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 === 7) p.callID = dec.decode(g.data)
+ else if (g.num === 8) p.cache = Buffer.from(g.data).toString("hex")
+ else if (g.num === 6) p.calls.push(dec.decode(fields(g.data).find((h) => h.num === 2).data))
+ else if (g.num === 10) p.images++
+ }
+ return p
+ })
+
+const EPHEMERAL = "0801"
+const mark = { type: "ephemeral" }
+const history = (from, n) => Array.from({ length: n }, (_, i) => `step ${from + i}: read src/module_${from + i}.ts`).join("\n")
+const system = [
+ { type: "text", text: "x-anthropic-billing-header: cc_version=2.1.316.e5f; cc_entrypoint=cli; cch=8a1f2;" },
+ { type: "text", text: "You are a security monitor for autonomous AI coding agents.", cache_control: mark },
+]
+// the issue's shape: one user message of , the history, the
+// current action and the closing note, the mark on the history
+const ask = (blocks, action) => ({
+ model: "claude-haiku-5-5",
+ max_tokens: 64,
+ system,
+ messages: [{ role: "user", content: [...blocks, { type: "text", text: "Current action: " + action }, { type: "text", text: "\nClassify the current action." }] }],
+})
+
+test("each user block is a prompt of its own, and only a marked one carries prompt_cache_options (#566)", () => {
+ const round1 = prompts(buildMessages(ask([{ type: "text", text: "" }, { type: "text", text: history(0, 50), cache_control: mark }], "rm -rf build/"), "claude-haiku-5-5", "k"))
+ expect(round1.map((p) => [p.role, p.text.slice(0, 20), p.cache])).toEqual([
+ [1, "You are a security m", EPHEMERAL],
+ [1, "", null],
+ [1, history(0, 50).slice(0, 20), EPHEMERAL],
+ [1, "Current action: rm -", null],
+ [1, "\nClassi", null],
+ ])
+ // the billing line, whose cch changes every turn, isn't sent
+ expect(round1.some((p) => p.text.includes("x-anthropic-billing-header"))).toBe(false)
+})
+
+test("a grown history keeps every prompt the last mark covered as it was sent (yetone/magpie#3835)", () => {
+ const old = [{ type: "text", text: "" }, { type: "text", text: history(0, 50) }]
+ const round1 = prompts(buildMessages(ask([old[0], { ...old[1], cache_control: mark }], "rm -rf build/"), "claude-haiku-5-5", "k"))
+ // the mark moves to the block the history grew by
+ const round2 = prompts(buildMessages(ask([...old, { type: "text", text: history(50, 5), cache_control: mark }], "git push --force"), "claude-haiku-5-5", "k"))
+ expect(round2.slice(0, 3).map((p) => p.text)).toEqual(round1.slice(0, 3).map((p) => p.text))
+ expect(round2[2].cache).toBe(null)
+ expect([round2[3].text, round2[3].cache]).toEqual([history(50, 5), EPHEMERAL])
+})
+
+test("tool calls and results keep their own prompts and marks", () => {
+ const body = buildMessages(
+ {
+ model: "claude-opus-5-5",
+ max_tokens: 400,
+ tools: [{ name: "read_file", description: "Read a file.", input_schema: { type: "object", properties: { path: { type: "string" } } } }, { type: "web_search_20250305", name: "web_search" }],
+ messages: [
+ { role: "user", content: "Read /etc/motd." },
+ { role: "assistant", content: [{ type: "thinking", thinking: "…", signature: "s" }, { type: "text", text: "Reading it." }, { type: "tool_use", id: "toolu_01", name: "read_file", input: { path: "/etc/motd" } }] },
+ { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_01", content: [{ type: "text", text: "Welcome" }, { type: "image", source: { type: "base64", media_type: "image/png", data: "iVBO" } }], cache_control: mark }] },
+ ],
+ },
+ "claude-opus-5-5",
+ "k",
+ )
+ const ps = prompts(body)
+ expect(ps.map((p) => [p.role, p.text.split("\n")[0], p.callID, p.calls, p.cache, p.images])).toEqual([
+ [1, "", "", [], null, 0],
+ [1, "Read /etc/motd.", "", [], null, 0],
+ [2, "Reading it.", "", ["read_file"], null, 0],
+ [4, "Welcome", "toolu_01", [], EPHEMERAL, 1],
+ ])
+ // a server tool isn't offered to Devin
+ const offered = fields(body).filter((f) => f.num === 10).map((f) => dec.decode(fields(f.data).find((g) => g.num === 1).data))
+ expect(offered).toEqual(["read_file"])
+})
+
+test("a Messages request's effort is read as magpie reads it", () => {
+ expect(anthropicEffort({ thinking: { type: "adaptive" }, output_config: { effort: "high" } })).toBe("high")
+ expect(anthropicEffort({ thinking: { type: "enabled", budget_tokens: 10000 } })).toBe("medium")
+ expect(anthropicEffort({ thinking: { type: "disabled" }, output_config: { effort: "high" } })).toBe("")
+ expect(anthropicEffort({})).toBe("")
+})
+
+test("only Claude models are asked on Anthropic's Messages API; others are unchanged", () => {
+ const models = listed(familiesOf(SNAPSHOT), [], {})
+ const claude = models.find((m) => m.id === "claude-opus-5-5")
+ const other = models.find((m) => !/claude/i.test(m.id) && m.efforts.length)
+ expect(claude && other).toBeTruthy()
+ expect(configModel(claude).provider).toEqual({ npm: "@ai-sdk/anthropic", api: "https://server.codeium.com/devin/v1" })
+ expect(runtimeModel(claude).api.npm).toBe("@ai-sdk/anthropic")
+ expect(Object.values(runtimeModel(claude).variants)[0]).toEqual({ effort: claude.efforts[0] })
+ expect(configModel(other).provider).toBeUndefined()
+ expect(runtimeModel(other).api).toEqual({ id: other.id, url: "https://server.codeium.com/devin/v1", npm: "@ai-sdk/openai-compatible" })
+ expect(Object.values(runtimeModel(other).variants)[0]).toEqual({ reasoningEffort: other.efforts[0] })
+ expect(Object.values(configModel(other).variants)[0]).toEqual({ reasoningEffort: other.efforts[0] })
+ // a chat completion still goes as one prompt per message, with no mark
+ const ps = prompts(build({ model: other.id, messages: [{ role: "user", content: [{ type: "text", text: "a" }, { type: "text", text: "b" }] }] }, other.id, "k"))
+ expect(ps.map((p) => [p.text, p.cache])).toEqual([["a\n\nb", null]])
+})
+
+// reply is Devin's answer: text, a call and the usage with the cache's
+// read (field 5) and write (4)
+const reply = () => {
+ const usage = new PB().varint(2, 27).varint(3, 12).varint(4, 560).varint(5, 7318).done()
+ const call = new PB().str(1, "toolu_02").str(2, "read_file").str(3, '{"path":"/a"}').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(new PB().str(3, "Let me look.").done()), frame(new PB().bytes(6, call).varint(5, 10).bytes(7, usage).done()), tail]))
+}
+const ctx = { key: "k", server: "https://devin.test", families: familiesOf(SNAPSHOT) }
+const req = (stream) => ({ model: "claude-haiku-5-5", max_tokens: 64, stream, messages: [{ role: "user", content: [{ type: "text", text: "hi", cache_control: mark }] }] })
+
+test("a whole reply is Anthropic's message, with the cache's read and write", async () => {
+ globalThis.fetch = async () => reply()
+ const res = await completeMessages(ctx, req(false))
+ expect(res.status).toBe(200)
+ const j = await res.json()
+ expect(j.content).toEqual([{ type: "text", text: "Let me look." }, { type: "tool_use", id: "toolu_02", name: "read_file", input: { path: "/a" } }])
+ expect(j.stop_reason).toBe("tool_use")
+ expect(j.usage).toEqual({ input_tokens: 27, output_tokens: 12, cache_read_input_tokens: 7318, cache_creation_input_tokens: 560 })
+})
+
+test("a streamed reply is Anthropic's events", async () => {
+ globalThis.fetch = async () => reply()
+ const res = await completeMessages(ctx, req(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)).toEqual(["message_start", "content_block_start", "content_block_delta", "content_block_stop", "content_block_start", "content_block_delta", "content_block_stop", "message_delta", "message_stop"])
+ expect(ev[4].content_block).toEqual({ type: "tool_use", id: "toolu_02", name: "read_file", input: {} })
+ expect(ev[5].delta).toEqual({ type: "input_json_delta", partial_json: '{"path":"/a"}' })
+ expect(ev[7].delta.stop_reason).toBe("tool_use")
+ expect(ev[7].usage.cache_read_input_tokens).toBe(7318)
+})
+
+test("the loader answers count_tokens in Anthropic's words, without asking Devin", async () => {
+ globalThis.fetch = async () => {
+ throw new Error("no network in tests")
+ }
+ const auth = { type: "api", key: "k" }
+ const { auth: a } = await DevinAuthPlugin({})
+ const { fetch: f } = await a.loader(async () => auth)
+ const res = await f("https://server.codeium.com/devin/v1/messages/count_tokens", { method: "POST", body: "{}" })
+ expect(res.status).toBe(404)
+ expect((await res.json()).type).toBe("error")
+})
diff --git a/packages/devin/index.mjs b/packages/devin/index.mjs
index 87c8172..d0e332e 100644
--- a/packages/devin/index.mjs
+++ b/packages/devin/index.mjs
@@ -17,6 +17,13 @@ import { isAbsolute, join, relative, resolve } from "node:path"
const ID = "devin"
const CHAT = "@ai-sdk/openai-compatible"
+// Devin's Claude models are asked on Anthropic's Messages API, so the
+// client's own blocks and cache marks reach the plugin as it sent them
+// (#566); every other model stays on chat completions
+const ANTHROPIC = "@ai-sdk/anthropic"
+const isClaude = (id) => /claude/i.test(String(id))
+const npmOf = (id) => (isClaude(id) ? ANTHROPIC : CHAT)
+const variantOf = (id, e) => (isClaude(id) ? { effort: e } : { reasoningEffort: e })
const SERVER = "https://server.codeium.com"
const AUTHORIZE = "https://app.devin.ai/auth/cli/continue"
@@ -558,7 +565,8 @@ function configModel(m) {
temperature: true,
modalities: { input: image ? ["text", "image"] : ["text"], output: ["text"] },
limit: { context: m.context, output: m.output },
- ...(m.efforts.length ? { variants: Object.fromEntries(m.efforts.map((e) => [e, { reasoningEffort: e }])) } : {}),
+ ...(isClaude(m.id) ? { provider: { npm: ANTHROPIC, api: BASE } } : {}),
+ ...(m.efforts.length ? { variants: Object.fromEntries(m.efforts.map((e) => [e, variantOf(m.id, e)])) } : {}),
}
}
@@ -568,7 +576,7 @@ function runtimeModel(m) {
id: m.id,
providerID: ID,
name: m.name,
- api: { id: m.id, url: BASE, npm: CHAT },
+ api: { id: m.id, url: BASE, npm: npmOf(m.id) },
status: "active",
headers: {},
options: {},
@@ -584,7 +592,7 @@ function runtimeModel(m) {
interleaved: false,
},
release_date: "",
- variants: Object.fromEntries(m.efforts.map((e) => [e, { reasoningEffort: e }])),
+ variants: Object.fromEntries(m.efforts.map((e) => [e, variantOf(m.id, e)])),
// magpie's: a model the account's quota doesn't count
...(m.free ? { free: true } : {}),
}
@@ -1565,11 +1573,16 @@ function build(chat, uid, key) {
}
msgs[at].text = joinNonEmpty(instructions, msgs[at].text)
}
+ return encodeRequest(msgs, tools, { max: chat.max_completion_tokens || chat.max_tokens, temperature: chat.temperature, top_p: chat.top_p }, uid, key)
+}
+// encodeRequest is the GetChatMessage request of msgs, with tools offered
+// and the sampling asked, to the model uid.
+function encodeRequest(msgs, tools, chat, uid, key) {
const out = new PB().bytes(1, metadata(key))
for (const m of msgs) out.bytes(3, encodeMsg(m))
out.varint(7, 5)
- const max = chat.max_completion_tokens || chat.max_tokens || 128000 // the server holds it to the model's own
+ const max = chat.max || 128000 // the server holds it to the model's own
// Devin answers "an internal error occurred" to a temperature or top_p of
// exactly 0 (on every model: its Claude ones and swe-2), where 1e-6 goes
// through; a 0 is sent as the smallest step above it, as near greedy
@@ -1596,6 +1609,9 @@ function encodeMsg(m) {
if (m.text) b.str(3, m.text)
for (const c of m.calls ?? []) b.bytes(6, new PB().str(1, c.id ?? "").str(2, c.name ?? "").bytes(3, c.args))
if (m.callID) b.str(7, m.callID)
+ // prompt_cache_options {type: EPHEMERAL}, as the devin CLI marks its
+ // 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))
return b.done()
}
@@ -1706,6 +1722,7 @@ async function* events(it) {
total_tokens: prompt + usage.output,
prompt_tokens_details: { cached_tokens: usage.cacheRead, cache_write_tokens: usage.cacheWrite },
},
+ tokens: usage,
}
}
@@ -1726,9 +1743,13 @@ async function* prepend(first, rest) {
// roundtrip sends a chat to GetChatMessage and answers with its event
// iterator, or an error ({status, message}).
-async function roundtrip({ key, server, families }, chat, signal) {
- const uid = variantFor(families, chat.model, effortOf(chat.reasoning_effort))
- const body = frame(build(chat, uid, key))
+// A wire is how a request is read: chat completions' or Messages'.
+const CHAT_WIRE = { effort: (chat) => effortOf(chat.reasoning_effort), build }
+const MESSAGES = { effort: anthropicEffort, build: buildMessages }
+
+async function roundtrip({ key, server, families }, chat, signal, wire = CHAT_WIRE) {
+ const uid = variantFor(families, chat.model, wire.effort(chat))
+ const body = frame(wire.build(chat, uid, key))
let res
try {
res = await fetch(server + CHAT_RPC, {
@@ -1825,6 +1846,262 @@ async function complete({ key, server, families }, chat, signal) {
return new Response(stream, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Magpie-Sign-In": "kept" } })
}
+// ---- Anthropic's Messages, for the Claude models ------------------------------------
+
+// Claude Code's billing line, a system block of its own whose cch changes
+// every turn: Devin would read it as the prompt's first words, and no
+// turn's prefix would be the last's
+const BILLING_LINE = /^x-anthropic-billing-header:(\s*[A-Za-z_]+=[^;\s]*;)*\s*(\n|$)/
+
+// marked says whether the client asked for the cache to end at a block.
+const marked = (b) => !!(b && typeof b === "object" && b.cache_control && typeof b.cache_control === "object")
+
+// anthropicImage is an image block as Devin takes an image, or null for
+// one that carries no bytes (Devin takes no URL).
+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" }
+}
+
+// anthropicEffort is the effort a Messages request asks for, as magpie
+// reads it: output_config's, else the thinking budget's; none with the
+// thinking turned off.
+function anthropicEffort(req) {
+ const t = req.thinking?.type
+ if (t === "disabled") return ""
+ if (req.output_config?.effort) return effortOf(req.output_config.effort)
+ if (t !== "enabled" && t !== "adaptive") return ""
+ const n = Number(req.thinking?.budget_tokens) || 0
+ return n <= 0 ? "" : n <= 4096 ? "low" : n <= 12000 ? "medium" : n <= 24000 ? "high" : "xhigh"
+}
+
+// buildMessages is the GetChatMessage request for a Messages request, to
+// the model uid. Each of the client's blocks is a ChatMessagePrompt of its
+// own, in order, and one the client marked with cache_control carries
+// prompt_cache_options: Devin's cache ends only where a prompt says so,
+// and only at a prompt's end, so a block joined to others lost its mark
+// (#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) {
+ // Messages alternate roles; a client that sends two of one role in a row
+ // means one turn
+ const turns = []
+ for (const m of req.messages ?? []) {
+ if (m?.role !== "user" && m?.role !== "assistant") continue
+ const blocks = typeof m.content === "string" ? (m.content ? [{ type: "text", text: m.content }] : []) : Array.isArray(m.content) ? m.content : []
+ const last = turns[turns.length - 1]
+ if (last?.role === m.role) last.blocks.push(...blocks)
+ else turns.push({ role: m.role, blocks: [...blocks] })
+ }
+
+ const msgs = []
+ let pending = [] // calls the last reply made, not yet answered
+ const answer = () => {
+ for (const c of pending) msgs.push({ role: TOOL, callID: c.id, text: NO_RESULT })
+ pending = []
+ }
+ for (const t of turns) {
+ if (t.role === "assistant") {
+ const own = []
+ const calls = []
+ let mark = false // a tool_use the client marked: the prompt with the calls ends there
+ 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) })
+ 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)
+ }
+ // thinking goes no further: Devin keeps none of a reply's
+ }
+ if (calls.length) {
+ if (!own.length) own.push({ role: ASSISTANT, text: "", calls: [] })
+ own[own.length - 1].calls = calls
+ own[own.length - 1].cache ||= mark
+ }
+ if (!own.length) continue // a turn that only thought
+ answer()
+ msgs.push(...own)
+ pending = [...calls]
+ continue
+ }
+ let held = [] // images ahead of the user's next words in this turn
+ let words = null // the turn's last prompt of the user's own
+ for (const b of t.blocks) {
+ if (b?.type === "tool_result") {
+ // only a call just made is answered, and only once
+ const i = pending.findIndex((c) => c.id === inID(b.tool_use_id))
+ if (i < 0) continue
+ const inner = typeof b.content === "string" ? [{ type: "text", text: b.content }] : Array.isArray(b.content) ? b.content : []
+ const text = inner.filter((x) => x?.type === "text" && x.text).map((x) => x.text).join("\n\n")
+ const images = inner.map(anthropicImage).filter(Boolean)
+ msgs.push({ role: TOOL, callID: pending[i].id, text: text || "(no output)", images, cache: marked(b) || marked(inner[inner.length - 1]) })
+ pending.splice(i, 1)
+ continue
+ }
+ if (b?.type === "text" && typeof b.text === "string") {
+ if (!b.text) {
+ if (marked(b) && words) words.cache = true
+ continue
+ }
+ answer()
+ words = { role: USER, text: b.text, images: held, cache: marked(b) }
+ held = []
+ msgs.push(words)
+ continue
+ }
+ const im = anthropicImage(b)
+ if (!im) continue
+ // an image goes with the words it follows, or the next ones
+ if (words) {
+ words.images.push(im)
+ words.cache ||= marked(b)
+ } else held.push(im)
+ }
+ if (held.length) {
+ answer()
+ msgs.push({ role: USER, text: "", images: held })
+ }
+ }
+ answer()
+ const last = msgs[msgs.length - 1]
+ if (!last || (last.role === ASSISTANT && !last.calls.length)) msgs.push({ role: USER, text: "Please proceed with the task." })
+
+ // the instructions go ahead of the first user prompt, as in build: the
+ // tools' descriptions, then each system block a prompt of its own, as
+ // Anthropic orders them, so a mark on the system covers the tools too
+ const system = []
+ const blocks = typeof req.system === "string" ? [{ type: "text", text: req.system }] : Array.isArray(req.system) ? req.system : []
+ for (const b of blocks) {
+ if (b?.type !== "text" || typeof b.text !== "string") continue
+ const text = b.text.replace(BILLING_LINE, "")
+ if (text.trim()) system.push({ role: USER, text, cache: marked(b) })
+ else if (marked(b) && system.length) system[system.length - 1].cache = true
+ }
+ const f = req.output_config?.format
+ const format = f?.type === "json_schema" ? formatText({ type: "json_schema", schema: f.schema }) : ""
+ if (format) system.push({ role: USER, text: format })
+ let tools = (req.tools ?? [])
+ .filter((t) => (!t?.type || t.type === "custom") && t.name)
+ .map((t) => ({ name: t.name, description: t.description ?? "", schema: objectRoot(t.input_schema) }))
+ if (req.tool_choice?.type === "none") tools = []
+ const described = toolDescriptions(tools)
+ if (described) system.unshift({ role: USER, text: described, cache: false })
+ if (system.length) {
+ const at = msgs.findIndex((m) => m.role === USER)
+ msgs.splice(at < 0 ? 0 : at, 0, ...system)
+ }
+ return encodeRequest(msgs, tools, { max: req.max_tokens, temperature: req.temperature, top_p: req.top_p }, uid, key)
+}
+
+// anthropicError is a failure as Anthropic words one; like errorResponse,
+// it marks nothing of the account.
+function anthropicError({ status, message }) {
+ const type = { 400: "invalid_request_error", 401: "authentication_error", 403: "permission_error", 404: "not_found_error", 413: "request_too_large", 429: "rate_limit_error", 529: "overloaded_error" }[status] ?? "api_error"
+ return new Response(JSON.stringify({ type: "error", error: { type, message } }), {
+ status,
+ headers: { "Content-Type": "application/json", "X-Magpie-Sign-In": "kept" },
+ })
+}
+
+const STOP_REASON = { tool_calls: "tool_use", length: "max_tokens", stop: "end_turn" }
+const anthropicUsage = (t = {}) => ({ input_tokens: t.input ?? 0, output_tokens: t.output ?? 0, cache_read_input_tokens: t.cacheRead ?? 0, cache_creation_input_tokens: t.cacheWrite ?? 0 })
+
+// completeMessages answers a Messages request through GetChatMessage, as
+// Anthropic would: the reply's blocks, its stop reason and the usage with
+// what was read from the cache and written to it.
+async function completeMessages({ key, server, families }, req, signal) {
+ const rt = await roundtrip({ key, server, families }, req, signal, MESSAGES)
+ if (!rt.it) return anthropicError(rt)
+ const it = rt.it
+ const id = "msg_" + randomBytes(12).toString("hex")
+
+ if (!req.stream) {
+ const content = []
+ let stop = "end_turn"
+ let usage = anthropicUsage()
+ const block = (type) => {
+ const b = content[content.length - 1]
+ if (b?.type === type && type !== "tool_use") return b
+ const n = type === "text" ? { type, text: "" } : { type, thinking: "", signature: "" }
+ content.push(n)
+ return n
+ }
+ const args = []
+ 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
+ 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 })
+ }
+ if (e.args) args[e.args.index] += e.args.text
+ if (e.stop) [stop, usage] = [STOP_REASON[e.stop] ?? "end_turn", anthropicUsage(e.tokens)]
+ }
+ for (const b of content) {
+ if (b.type !== "tool_use") continue
+ try {
+ b.input = JSON.parse(args[b.index] || "{}")
+ } catch {
+ b.input = {}
+ }
+ delete b.index
+ }
+ 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" } })
+ }
+
+ const sse = (event, data) => enc.encode(`event: ${event}\ndata: ${JSON.stringify({ type: event, ...data })}\n\n`)
+ let began = false
+ let index = -1
+ let open = "" // the kind of the block being sent: text, thinking or tool_use
+ const stream = new ReadableStream({
+ async pull(ctl) {
+ if (!began) {
+ began = true
+ 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) ctl.enqueue(sse("content_block_stop", { index }))
+ open = ""
+ }
+ const start = (kind, content_block) => {
+ close()
+ index++
+ open = kind
+ ctl.enqueue(sse("content_block_start", { index, content_block }))
+ }
+ const r = await it.next()
+ if (r.done) return ctl.close()
+ 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: "" })
+ ctl.enqueue(sse("content_block_delta", { index, delta: { type: "thinking_delta", thinking: e.reasoning } }))
+ } 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 } }))
+ } else if (e.stop) {
+ close()
+ ctl.enqueue(sse("message_delta", { delta: { stop_reason: STOP_REASON[e.stop] ?? "end_turn", stop_sequence: null }, usage: anthropicUsage(e.tokens) }))
+ ctl.enqueue(sse("message_stop", {}))
+ } else if (e.error) {
+ ctl.enqueue(enc.encode(`event: error\ndata: ${JSON.stringify({ type: "error", error: { type: "api_error", message: e.error.message } })}\n\n`))
+ ctl.close()
+ }
+ },
+ cancel() {
+ it.return?.()
+ },
+ })
+ return new Response(stream, { status: 200, headers: { "Content-Type": "text/event-stream", "Cache-Control": "no-cache", "X-Magpie-Sign-In": "kept" } })
+}
+
// ---- OpenCode 2 ----------------------------------------------------------------------
// OpenCode 2 asks for a default export with an id and a setup(ctx). The
@@ -2423,20 +2700,25 @@ export async function DevinAuthPlugin({ client } = {}) {
baseURL: BASE,
apiKey: auth.key,
async fetch(input, init = {}) {
- const now = await getAuth()
- if (now?.type !== "api" || !now.key) return errorResponse({ status: 401, message: "Devin isn't signed in" })
const url = typeof input === "string" ? input : input instanceof URL ? input.href : input.url
- if (!/\/chat\/completions$/.test(new URL(url).pathname)) return errorResponse({ status: 404, message: "only chat completions are served" })
+ const path = new URL(url).pathname
+ const messages = /\/messages$/.test(path)
+ const now = await getAuth()
+ if (now?.type !== "api" || !now.key) return (messages ? anthropicError : errorResponse)({ status: 401, message: "Devin isn't signed in" })
+ if (!messages && !/\/chat\/completions$/.test(path)) {
+ const e = { status: 404, message: "only chat completions and messages are served" }
+ return /\/messages\//.test(path) ? anthropicError(e) : errorResponse(e)
+ }
let chat
try {
const b = init.body ?? (input instanceof Request ? await input.clone().text() : undefined)
chat = JSON.parse(typeof b === "string" ? b : dec.decode(b))
} catch {
- return errorResponse({ status: 400, message: "a request that isn't JSON" })
+ return (messages ? anthropicError : errorResponse)({ status: 400, message: "a request that isn't JSON" })
}
const { key, server } = await live(now)
const families = await familiesFor(key, server)
- return complete({ key, server, families }, chat, init.signal)
+ return (messages ? completeMessages : complete)({ key, server, families }, chat, init.signal)
},
}
},
@@ -2513,4 +2795,4 @@ export async function DevinAuthPlugin({ client } = {}) {
}
// for tests
-export const _internal = { 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 = { 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 903575e..9fa5171 100644
--- a/packages/devin/package.json
+++ b/packages/devin/package.json
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-devin-auth",
- "version": "0.1.27",
+ "version": "0.1.28",
"description": "Devin subscriptions (the devin CLI's account) in OpenCode and magpie",
"type": "module",
"main": "./index.mjs",