diff --git a/packages/commandcode/CHANGELOG.md b/packages/commandcode/CHANGELOG.md index 6564b84..5ba908d 100644 --- a/packages/commandcode/CHANGELOG.md +++ b/packages/commandcode/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 0.1.22 + +- Reflection's Beam (`reflection/beam:free`) is sent each earlier assistant + message's reasoning in `reasoning_content`: its own when the history kept + it, the thinking sent back as `reasoning`, else a period. Beam answered a + one-turn chat and turned the second turn away with 400 "Missing required + parameter: 'messages[N].reasoning_content'", a reply another model made + included (EDwinpzy on magpie's Discord). Another model the Provider API + turns away the same way is asked once more with it filled, and is sent it + from then on. Other models' requests go as they came. + ## 0.1.20 - The Credits window of a Go, GOAT or Pro account says credits, not diff --git a/packages/commandcode/index.mjs b/packages/commandcode/index.mjs index c996223..4187c01 100644 --- a/packages/commandcode/index.mjs +++ b/packages/commandcode/index.mjs @@ -72,6 +72,43 @@ const THINK_OFF = new Set([ ]) const OFF_EFFORTS = ["none", "low", "high", "max"] +// REASONING_BACK are the models the Provider API wants each earlier +// assistant message's reasoning back from, in reasoning_content, on every +// turn, not only a tool call's: Reflection's Beam (reflection/beam:free) +// answers the second turn of a chat whose first reply has none 400 +// "Missing required parameter: 'messages[1].reasoning_content'", the +// history another model made too, and takes it with something there +// (EDwinpzy on magpie's Discord, 0.1.2717). Its list says nothing of it, +// so any other model the Provider API asks the same of (REASONING_ASKED) +// is asked once more with it filled, and remembered (reasoningAsked). +const REASONING_BACK = /^reflection\/beam(?:[:-]|$)/i +const REASONING_ASKED = /\breasoning_content\b[^"]{0,80}\b(?:missing|required|must be (?:passed|provided|included))|\b(?:missing|required)\b[^"]{0,80}\breasoning_content\b/i +// NO_THOUGHT is the reasoning a message with none goes with: a turn +// another model made, or one whose thinking the client kept nothing of. +// Not blank: what is required may be read as missing when it is only +// whitespace, and a period says nothing to the model. +const NO_THOUGHT = "." +const reasoningAsked = new Set() +const wantsReasoning = (model) => REASONING_BACK.test(String(model ?? "")) || reasoningAsked.has(String(model ?? "")) + +// withReasoningBack is messages with each assistant message's reasoning +// in reasoning_content: its own when it has some, the thinking it sent +// back in reasoning, else NO_THOUGHT; the same array when none lacks it. +function withReasoningBack(messages) { + if (!Array.isArray(messages)) return messages + let changed = false + const out = messages.map((m) => { + if (m?.role !== "assistant") return m + const own = m.reasoning_content + if (typeof own === "string" && own.trim()) return m + const r = typeof m.reasoning === "string" && m.reasoning.trim() ? m.reasoning : NO_THOUGHT + const { reasoning, ...rest } = m + changed = true + return { ...rest, reasoning_content: r } + }) + return changed ? out : messages +} + // The plan's models when its list can't be asked: Claude on Messages, the // rest on chat completions. Pictures as models.dev has them (DeepSeek V4 // and GLM-5.3 read text alone, so say nothing). @@ -1402,15 +1439,19 @@ async function generate(key, chat, signal, place, zdr = false) { // "off", is "off" for a model that turns thinking off (THINK_OFF), and // left out for any other, which refuses both "none" and "off" (#334). A // Google model's tools have the $refs Google can't take written out -// (googleSchema). +// (googleSchema). A model that wants its reasoning back (wantsReasoning) +// has it on each assistant message (withReasoningBack). function providerBody(chat) { let out = chat + if (wantsReasoning(chat?.model)) { + const messages = withReasoningBack(chat.messages) + if (messages !== chat.messages) out = { ...chat, messages } + } const e = chat?.reasoning_effort - if (e === "none" || e === "off") { - out = { ...chat } + if ((e === "none" || e === "off") && !(e === "off" && THINK_OFF.has(chat.model))) { + out = { ...out } if (THINK_OFF.has(chat.model)) out.reasoning_effort = "off" else delete out.reasoning_effort - if (e === out.reasoning_effort) out = chat } if (isGoogle(chat?.model) && Array.isArray(chat.tools)) { let changed = false @@ -1453,7 +1494,7 @@ async function systemOne(key, init, input, place, zdr) { // ---- the plugin --------------------------------------------------------------- -export const _internal = { googleSchema, isGoogle, JEV, projectSlug, subsSeen, extraSeen, waits, liveKey, failure, goModels, refuses, GO_MODELS, GO_REFUSED, zdrOn } +export const _internal = { googleSchema, isGoogle, JEV, reasoningAsked, NO_THOUGHT, projectSlug, subsSeen, extraSeen, waits, liveKey, failure, goModels, refuses, GO_MODELS, GO_REFUSED, zdrOn } export async function CommandCodePlugin({ client, magpie } = {}) { // isGo keeps a key as Go's, for its models and endpoint: in the @@ -1514,16 +1555,29 @@ export async function CommandCodePlugin({ client, magpie } = {}) { } // the Provider API's answer goes on as it came, the account // kept, unless it is a 401 for a key whoami refuses (told) + const method = init.method ?? (input instanceof Request ? input.method : "POST") const body = chatting ? providerBody(chat) : undefined - const res = await (body === undefined + let res = await (body === undefined ? fetch(input, { ...init, headers }) - : fetch(url, { ...init, method: init.method ?? (input instanceof Request ? input.method : "POST"), headers, body })) + : fetch(url, { ...init, method, headers, body })) if (res.ok) return kept(res) + let text = await res.text() + // a model asking for each earlier message's reasoning back, which + // its list doesn't say: it has it from now on, and this request + // is asked once more with it + if (chatting && res.status === 400 && REASONING_ASKED.test(text) && !wantsReasoning(chat?.model)) { + reasoningAsked.add(String(chat.model)) + const again = providerBody(chat) + if (again !== undefined && again !== body) { + res = await fetch(url, { ...init, method, headers, body: again }) + if (res.ok) return kept(res) + text = await res.text() + } + } // a Go key the plan wasn't known for (billing/subscriptions slow // or failing, nothing saved yet) is refused by the Provider API // (#969): it is Go from now on, and a chat completion is asked // again where Go is served - const text = await res.text() if (GO_NO_API.test(text)) { await isGo(key, (await getAuth()) ?? auth) if (chatting) return told(key, await generate(key, chat, init.signal, place, zdr)) diff --git a/packages/commandcode/package.json b/packages/commandcode/package.json index b5d10f9..f0cfd33 100644 --- a/packages/commandcode/package.json +++ b/packages/commandcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-commandcode-auth", - "version": "0.1.21", + "version": "0.1.22", "description": "Command Code plans (Pro, GOAT, Max, Ultra, Go, Teams) in OpenCode and magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/commandcode/reasoning-back.test.mjs b/packages/commandcode/reasoning-back.test.mjs new file mode 100644 index 0000000..c3c1e92 --- /dev/null +++ b/packages/commandcode/reasoning-back.test.mjs @@ -0,0 +1,175 @@ +// EDwinpzy (magpie's Discord, #feedback, magpie 0.1.2717): Command Code's +// reflection/beam:free answers a fresh one-turn chat, and turns the second +// turn away with 400 "Missing required parameter: +// 'messages[N].reasoning_content'": it wants every earlier assistant +// message's reasoning back, a reply another model made too, and takes the +// request once each has something there. Seen through magpie's +// /v1/chat/completions and /v1/responses alike; both reach the plugin as a +// chat completion whose assistant turn has no reasoning_content. The +// refusal's words are the reporter's; the JSON around them is the Provider +// API's error shape, not bytes saved from Beam. +import { afterEach, expect, test } from "bun:test" +import { CommandCodePlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => { + globalThis.fetch = real + _internal.subsSeen.clear() + _internal.extraSeen.clear() + _internal.reasoningAsked.clear() +}) + +const BEAM = "reflection/beam:free" + +// refusal is the Provider API's 400 for the first assistant message at i +// with no reasoning +const refusal = (i) => + Response.json( + { + error: { + message: `Missing required parameter: 'messages[${i}].reasoning_content'.`, + type: "invalid_request_error", + param: `messages[${i}].reasoning_content`, + code: "missing_required_parameter", + }, + }, + { status: 400 }, + ) + +// vendor answers as Beam does for the models in strict: a request with an +// assistant message whose reasoning_content is missing or blank is turned +// away; any other model takes anything. It records each body sent. +function vendor(strict = [BEAM]) { + const sent = [] + globalThis.fetch = async (input, init = {}) => { + const path = new URL(typeof input === "string" ? input : input.url ?? String(input)).pathname + if (!path.endsWith("/chat/completions")) return new Response("", { status: 404 }) + const body = JSON.parse(init.body ?? (await input.text())) + sent.push(body) + if (strict.includes(body.model)) { + const i = body.messages.findIndex((m) => m.role === "assistant" && !(typeof m.reasoning_content === "string" && m.reasoning_content.trim())) + if (i >= 0) return refusal(i) + } + return Response.json({ choices: [{ index: 0, message: { role: "assistant", content: "ok" }, finish_reason: "stop" }] }) + } + return sent +} + +async function fetcher() { + const hooks = await CommandCodePlugin() + const opts = await hooks.auth.loader(async () => ({ type: "api", key: "k", metadata: { plan: "GOAT" } })) + return (body) => opts.fetch("https://api.commandcode.ai/provider/v1/chat/completions", { method: "POST", body: JSON.stringify(body) }) +} + +// The reporter's second turn as magpie hands it to the plugin from each +// route: /v1/chat/completions relays the client's history (its own Beam +// reply, kept without reasoning, and another model's), /v1/responses +// builds the same turns from the Responses items. +const SECOND_TURNS = { + "chat completions": { + model: BEAM, + stream: true, + messages: [ + { role: "user", content: "hi" }, + { role: "assistant", content: "Hello! How can I help?" }, + { role: "user", content: "what model are you?" }, + ], + }, + responses: { + model: BEAM, + stream: true, + messages: [ + { role: "system", content: "You are a helpful assistant." }, + { role: "user", content: "hi" }, + { role: "assistant", content: "Hello! How can I help?" }, + { role: "user", content: "what model are you?" }, + ], + }, +} + +for (const [route, turn] of Object.entries(SECOND_TURNS)) { + test(`Beam's second turn (${route}) goes with each earlier reply's reasoning, and is answered`, async () => { + const sent = vendor() + const send = await fetcher() + const res = await send(turn) + expect(res.status).toBe(200) + expect(sent.length).toBe(1) + const a = sent[0].messages.filter((m) => m.role === "assistant") + expect(a.length).toBe(1) + expect(a[0].reasoning_content).toBe(_internal.NO_THOUGHT) + expect(a[0].content).toBe("Hello! How can I help?") + // nothing else of the request changes + expect(sent[0].messages.map(({ reasoning_content, ...m }) => m)).toEqual(turn.messages) + expect(sent[0].stream).toBe(true) + }) +} + +test("a reply's own reasoning goes back as it was; one sent as reasoning goes as reasoning_content", async () => { + const sent = vendor() + const send = await fetcher() + const res = await send({ + model: BEAM, + messages: [ + { role: "user", content: "a" }, + { role: "assistant", content: "b", reasoning_content: "thought b" }, + { role: "user", content: "c" }, + { role: "assistant", content: "d", reasoning: "thought d" }, + { role: "user", content: "e" }, + // a tool turn of another model, which magpie sends with a space + { role: "assistant", content: null, reasoning_content: " ", tool_calls: [{ id: "t1", type: "function", function: { name: "ls", arguments: "{}" } }] }, + { role: "tool", tool_call_id: "t1", content: "x" }, + ], + }) + expect(res.status).toBe(200) + const a = sent[0].messages.filter((m) => m.role === "assistant") + expect(a[0].reasoning_content).toBe("thought b") + expect(a[1].reasoning_content).toBe("thought d") + expect("reasoning" in a[1]).toBe(false) + expect(a[2].reasoning_content).toBe(_internal.NO_THOUGHT) + expect(a[2].tool_calls[0].id).toBe("t1") +}) + +test("a fresh one-turn request goes as it came", async () => { + const sent = vendor() + const send = await fetcher() + const body = { model: BEAM, messages: [{ role: "user", content: "hi" }] } + expect((await send(body)).status).toBe(200) + expect(sent[0]).toEqual(body) +}) + +test("another model's history goes as it came", async () => { + const sent = vendor() + const send = await fetcher() + const body = { ...SECOND_TURNS["chat completions"], model: "stealth/glyph-cluster:free" } + expect((await send(body)).status).toBe(200) + expect(sent.length).toBe(1) + expect(sent[0]).toEqual(body) +}) + +test("a model the Provider API asks the same of is asked once more with it, and has it from then on", async () => { + const model = "someone/new-reasoner" + const sent = vendor([model]) + const send = await fetcher() + const body = { ...SECOND_TURNS["chat completions"], model } + expect((await send(body)).status).toBe(200) + expect(sent.length).toBe(2) + expect(sent[0].messages[1].reasoning_content).toBeUndefined() + expect(sent[1].messages[1].reasoning_content).toBe(_internal.NO_THOUGHT) + // the next request is filled at once + expect((await send(body)).status).toBe(200) + expect(sent.length).toBe(3) + expect(sent[2].messages[1].reasoning_content).toBe(_internal.NO_THOUGHT) +}) + +test("a 400 about something else is not asked again", async () => { + const sent = [] + globalThis.fetch = async (input, init = {}) => { + sent.push(JSON.parse(init.body)) + return Response.json({ error: { message: "Missing required parameter: 'messages'.", type: "invalid_request_error" } }, { status: 400 }) + } + const send = await fetcher() + const res = await send({ ...SECOND_TURNS["chat completions"], model: "stealth/glyph-cluster:free" }) + expect(res.status).toBe(400) + expect(sent.length).toBe(1) + expect(_internal.reasoningAsked.size).toBe(0) +})