diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index ae01fee..e415b0b 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -99,6 +99,15 @@ models to each shape below and Kimi's, GPT's, Gemini's and GLM's to some: (`.`, `:`, `/`, a space, CJK) is sent with `_` there, and the model's calls come back under the tool's own name. +WorkBuddy AI's `gemini-3.8-flash` answers 400 "the conversation must end +with a user message" (11153) to a chat whose tool results are followed by +the user's message, as magpie sends Claude Code's reminders, words typed +mid-task and a tool's images. Such a chat goes again with an empty +assistant message between the results and the user's message, which it +serves; a model that refused it once gets it that way from then on, until +the plugin restarts. A chat ending with the assistant's message (a prefill) +is refused as before. + ## Models When you are signed in, the models are the ones WorkBuddy's product config diff --git a/packages/workbuddy/aftertools.test.mjs b/packages/workbuddy/aftertools.test.mjs new file mode 100644 index 0000000..72b996d --- /dev/null +++ b/packages/workbuddy/aftertools.test.mjs @@ -0,0 +1,95 @@ +// WorkBuddy AI's gemini-3.8-flash answers tool results followed by the +// user's message with 400 code 11153, "the conversation must end with a user +// message" (#113). The body is the one www.workbuddy.ai sent on 2026-10-14. +import { expect, test } from "bun:test" +import { WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" + +const { replyAfterTools } = _internal + +const REFUSAL = JSON.stringify({ + code: 11153, + msg: "the conversation must end with a user message", + requestId: "555fb7db0fb1ef01abc76992cbfcad0e", + extError: { code: "400001", message: "the conversation must end with a user message", param: "", type: "invalid_request_error", StatusCode: 400, Request: null, Response: null }, + displayMsg: { en: "This conversation must end with a user message. Please add your input and retry." }, +}) + +const call = { role: "assistant", content: null, tool_calls: [{ id: "call_1", type: "function", function: { name: "Bash", arguments: '{"command":"ls"}' } }] } +const result = { role: "tool", tool_call_id: "call_1", content: "a.txt\nb.txt" } +const ask = { role: "user", content: "List the files." } +const reminder = { role: "user", content: [{ type: "text", text: "note" }] } + +// served answers like gemini-3.8-flash: tool results then a user message are +// refused, anything else is served +async function withService(fn) { + const realFetch = globalThis.fetch + const sent = [] + globalThis.fetch = async (_url, init) => { + const b = JSON.parse(init.body) + sent.push(b) + const m = b.messages + let i = m.length - 1 + while (i >= 0 && m[i].role === "user") i-- + if (m.at(-1).role !== "user" || (i < m.length - 1 && m[i]?.role === "tool")) { + return new Response(REFUSAL, { status: 400, headers: { "content-type": "application/json" } }) + } + return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + } + try { + const hooks = await WorkBuddyAIAuthPlugin({ client: {} }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "access", uid: "uid", expires: Date.now() + 3600_000 })) + const post = (model, messages) => + loader.fetch("https://www.workbuddy.ai/v2/chat/completions", { method: "POST", body: JSON.stringify({ model, stream: true, messages }) }) + await fn(post, sent) + } finally { + globalThis.fetch = realFetch + } +} + +test("tool results then the user's message go again with an empty reply between them", async () => { + await withService(async (post, sent) => { + const res = await post("gemini-after-tools-a", [ask, call, result, reminder]) + expect(res.status).toBe(200) + expect(sent.length).toBe(2) + const roles = sent[1].messages.map((m) => m.role) + expect(roles).toEqual(["system", "user", "assistant", "tool", "assistant", "user"]) + expect(sent[1].messages[4]).toEqual({ role: "assistant", content: "" }) + // what the user said is still the user's, last + expect(sent[1].messages[5]).toEqual(reminder) + }) +}) + +test("a model that refused it gets the empty reply up front on its next chat", async () => { + await withService(async (post, sent) => { + await post("gemini-after-tools-b", [ask, call, result, reminder]) + sent.length = 0 + const res = await post("gemini-after-tools-b", [ask, call, result, ask, reminder]) + expect(res.status).toBe(200) + expect(sent.length).toBe(1) + expect(sent[0].messages.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool", "assistant", "user", "user"]) + // another model is asked as it was sent + const other = await post("deepseek-after-tools-b", [ask, call, result, { role: "assistant", content: "Two." }, ask]) + expect(other.status).toBe(200) + expect(sent.length).toBe(2) + expect(sent[1].messages.filter((m) => m.role === "assistant" && m.content === "").length).toBe(0) + }) +}) + +test("a chat ending with the assistant's message is a prefill, refused as it was", async () => { + await withService(async (post, sent) => { + const res = await post("gemini-after-tools-c", [ask, call, result, { role: "assistant", content: "There are" }]) + expect(res.status).toBe(400) + expect(sent.length).toBe(1) + expect((await res.json()).msg).toBe("the conversation must end with a user message") + }) +}) + +test("replyAfterTools changes only tool results followed by user messages", () => { + const body = (messages) => JSON.stringify({ model: "m", messages }) + expect(JSON.parse(replyAfterTools(body([ask, call, result, ask, reminder]))).messages.map((m) => m.role)).toEqual(["user", "assistant", "tool", "assistant", "user", "user"]) + expect(replyAfterTools(body([ask]))).toBeNull() + expect(replyAfterTools(body([ask, call, result]))).toBeNull() + expect(replyAfterTools(body([ask, call, result, { role: "assistant", content: "ok" }, ask]))).toBeNull() + expect(replyAfterTools(body([ask, { role: "assistant", content: "hi" }]))).toBeNull() + expect(replyAfterTools("not json")).toBeNull() +}) diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 739e6c4..100de46 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -1262,7 +1262,37 @@ async function liveModels(site, a) { // ---- the plugins -------------------------------------------------------------- +// AFTER_TOOLS_REFUSED is WorkBuddy's 400 code 11153, "the conversation must +// end with a user message", which WorkBuddy AI's gemini-3.8-flash answers to a +// chat whose tool results are followed by the user's message (#113): Claude +// Code's reminders, a user's words sent mid-task, a tool's images, which +// magpie hands over in a user message after the results. It does end with a +// user message; the same chat with any other message between them is served. +// The code is matched whole, as with 14018. +const AFTER_TOOLS_REFUSED = /must end with a user message|["']code["']\s*:\s*["']?11153(?![\d.])/i + +// replyAfterTools is a chat ending with tool results then the user's +// message(s), with an empty assistant message between them, as if the model +// had said nothing after the results. Tried with a real WorkBuddy AI +// account on 2026-10-14: gemini-3.8-flash serves it and follows the user's +// message as a user's, where folded into the tool's result it was read as +// the tool's output and its ask left undone. null for any other chat — one +// ending with the assistant's message is a prefill, refused as it is. +function replyAfterTools(body) { + const b = chatOf(body) + const msgs = b?.messages + if (!Array.isArray(msgs)) return null + let i = msgs.length - 1 + while (i >= 0 && msgs[i]?.role === "user") i-- + if (i === msgs.length - 1 || i < 0 || msgs[i]?.role !== "tool") return null + msgs.splice(i + 1, 0, { role: "assistant", content: "" }) + return JSON.stringify(b) +} + function makePlugin(site) { + // the models of this site that refused tool results then the user's + // message, for this run: their next chats go with replyAfterTools at once + const endsAfterTools = new Set() return async ({ client }) => ({ config: async (config) => { config.provider ??= {} @@ -1328,7 +1358,22 @@ function makePlugin(site) { const fit = fitted(body) body = normalizeToolChoice(fit.body) attend(headers, body, session) - const res = await fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body }) + const send = (b) => fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: b }) + // a model known to turn tool results then the user's message away + // gets the empty reply between them up front (see endsAfterTools) + const model = chatOf(body)?.model + const quiet = endsAfterTools.has(model) ? replyAfterTools(body) : null + let res = await send(quiet ?? body) + if (res.status === 400 && !quiet) { + const text = await res.text() + const again = AFTER_TOOLS_REFUSED.test(text) ? replyAfterTools(body) : null + if (again) { + endsAfterTools.add(model) + res = await send(again) + } else { + res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) + } + } return res.status >= 400 ? explained(res) : kept(await renamed(res, fit.names)) }, } @@ -1468,4 +1513,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf } +export const _internal = { replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 75a944c..6d4b1de 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.19", + "version": "0.1.20", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs",