From f2b0dacdb744a0f0478c274a5a4dc4217b75bf21 Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 28 Oct 2026 18:46:03 +0800 Subject: [PATCH] workbuddy 0.1.42: a chat is parsed once on its way, and goes as it came when nothing changed (#461) jihuayu measured a 45 MiB chat going through 0.1.41's fetch: each step (withSystem, fitted, normalizeToolChoice, attend, the model, systemKey) parsed the whole body again, 6 parses a request, and normalizeToolChoice wrote it out whole even for an unchanged "auto". Bun's RSS reached 618-751 MiB for 4 serial requests where passing the body through took 270. prepared parses a request once. Each step makes its own change to that one object, in the same order (systemOn, fitTools, toolChoiceOn; unsignedOn for Messages). attend, the model and the system key read the same object, and a refused system prompt moves on it (systemAsUserOn). The body is written out once, only when a step changed it. The parsed chat is let go before the request is sent. A body a step throws on goes through the steps one by one, as before. The string-level helpers stay as wrappers. What was run, on this tree: - mote, the reporter's benchmark (no network, fetch stubbed, 4 x 45.3 MiB, peak RSS sampled every 5ms): 0.1.41 7 parses/request, 1087.5 MiB parsed, peak RSS 1096 / 979 MiB. This change: 2 parses/request (the request and the stub's SSE reply), 181.3 MiB parsed, peak 682 / 680 MiB. The bodies sent have the same SHA-256 in both. - HOME=$(mktemp -d) bun test packages/workbuddy on mote: 189 pass, 0 fail. bun scripts/check.mjs workbuddy: ok. - oneparse.test.mjs (new): 17 chat shapes, invalid JSON and bytes come out the same as the steps one by one made them, with the same tool names; an unchanged chat goes byte for byte; the loader parses a 2 MiB chat once. Broken by hand: every request sent through the step-by-step fallback, the loader test FAILs (5 parses, want 1). An unchanged "auto" counted as a change, the byte-for-byte test FAILs. - Real account (WorkBuddy AI, free-only on, sandbox HOME, this Mac): deepseek-v4.1-flash, a 373-byte chat and a 205,595-byte chat with a developer message, max_completion_tokens and a dotted tool name, through 0.1.41 and this change: 200 "OK" on all four; no sign-in refreshed. npm has 0.1.41, so 0.1.42 is free. Reported-by: jihuayu --- packages/workbuddy/index.mjs | 199 +++++++++++++++++---------- packages/workbuddy/oneparse.test.mjs | 112 +++++++++++++++ packages/workbuddy/package.json | 2 +- 3 files changed, 243 insertions(+), 70 deletions(-) create mode 100644 packages/workbuddy/oneparse.test.mjs diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 9c39ae1..db1b7bb 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -608,8 +608,13 @@ function isMessages(url, body) { // unsigned thinking is body itself, byte for byte. function withoutUnsigned(body) { const b = chatOf(body) + return unsignedOn(b) ? JSON.stringify(b) : body +} + +// unsignedOn makes withoutUnsigned's change to a body's object; true when it made one +function unsignedOn(b) { const msgs = b?.messages - if (!Array.isArray(msgs)) return body + if (!Array.isArray(msgs)) return false let changed = false for (const m of msgs) { if (m?.role !== "assistant" || !Array.isArray(m.content)) continue @@ -618,7 +623,7 @@ function withoutUnsigned(body) { changed = true m.content = kept.length ? kept : [{ type: "text", text: "" }] } - return changed ? JSON.stringify(b) : body + return changed } // withoutSignedThinking is a Messages body without any thinking block at @@ -674,7 +679,10 @@ function sessionOf(headers) { // already there — the caller's own, or another plugin's — is kept, and the // message and request ids are the same one, as WorkBuddy's client has them. function attend(headers, body, session) { - const chat = chatOf(body) + attendChat(headers, chatOf(body), session) +} + +function attendChat(headers, chat, session) { const conv = conversationKey(chat, session) const msg = hex() headers.set("X-Conversation-Message-ID", msg) @@ -792,29 +800,34 @@ function withSystem(body) { if (typeof body !== "string") return body try { const b = JSON.parse(body) - if (!Array.isArray(b?.messages) || !b.messages.length) return body - let changed = unflag(b.messages) - if (b.max_completion_tokens !== undefined) { - if (b.max_tokens === undefined) b.max_tokens = b.max_completion_tokens - delete b.max_completion_tokens - changed = true - } - for (const m of b.messages) { - if (m?.role !== "developer") continue - m.role = "system" - changed = true - } - if (asReasoning(b.messages)) changed = true - if (b.messages[0]?.role !== "system") { - b.messages.unshift({ role: "system", content: "You are a helpful assistant." }) - changed = true - } - return changed ? JSON.stringify(b) : body + return systemOn(b) ? JSON.stringify(b) : body } catch { return body } } +// systemOn makes withSystem's changes to a chat's object; true when it made any +function systemOn(b) { + if (!Array.isArray(b?.messages) || !b.messages.length) return false + let changed = unflag(b.messages) + if (b.max_completion_tokens !== undefined) { + if (b.max_tokens === undefined) b.max_tokens = b.max_completion_tokens + delete b.max_completion_tokens + changed = true + } + for (const m of b.messages) { + if (m?.role !== "developer") continue + m.role = "system" + changed = true + } + if (asReasoning(b.messages)) changed = true + if (b.messages[0]?.role !== "system") { + b.messages.unshift({ role: "system", content: "You are a helpful assistant." }) + changed = true + } + return changed +} + // WorkBuddy's channel check reads the system and assistant messages only: // tried on 2026-10-21 with real accounts on both builds (glm-5.3, // deepseek-v4.1-flash, gpt-5.5), each refused line was served in the user's @@ -841,7 +854,11 @@ function textOf(content) { // systemKey is the text of a chat's system messages, which a chat refused // once is known by: the same agent's next chat goes with systemAsUser at once function systemKey(body) { - const msgs = chatOf(body)?.messages + return systemKeyOf(chatOf(body)) +} + +function systemKeyOf(chat) { + const msgs = chat?.messages if (!Array.isArray(msgs)) return "" const key = msgs.filter((m) => m?.role === "system").map((m) => textOf(m.content)).join("\n") return key.trim() === DEFAULT_SYSTEM ? "" : key @@ -849,15 +866,21 @@ function systemKey(body) { function systemAsUser(body) { const b = chatOf(body) + return systemAsUserOn(b) ? JSON.stringify(b) : null +} + +// systemAsUserOn makes systemAsUser's move on a chat's object; false when +// there's nothing to move +function systemAsUserOn(b) { const msgs = b?.messages - if (!Array.isArray(msgs)) return null + if (!Array.isArray(msgs)) return false let i = 0 const lead = [] for (; i < msgs.length && msgs[i]?.role === "system"; i++) lead.push(textOf(msgs[i].content)) const said = lead.join("\n\n").trim() const rest = msgs.slice(i).map((m) => (m?.role === "system" ? { ...m, role: "user" } : m)) const moved = said && said !== DEFAULT_SYSTEM - if (!moved && rest.every((m, k) => m === msgs[i + k])) return null + if (!moved && rest.every((m, k) => m === msgs[i + k])) return false if (moved) { const text = INSTRUCTIONS[0] + said + INSTRUCTIONS[1] const u = rest.findIndex((m) => m?.role === "user") @@ -867,7 +890,7 @@ function systemAsUser(body) { else rest[u] = { ...rest[u], content: text } } b.messages = [{ role: "system", content: DEFAULT_SYSTEM }, ...rest] - return JSON.stringify(b) + return true } // normalizeToolChoice converts the object form emitted by OpenAI clients to @@ -877,42 +900,47 @@ function normalizeToolChoice(body) { if (typeof body !== "string") return body try { const b = JSON.parse(body) - if (!b || typeof b !== "object" || Array.isArray(b) || !("tool_choice" in b)) return body - const choice = b.tool_choice - if (typeof choice === "string") { - if (choice.trim().toLowerCase() === "none") { - delete b.tool_choice - delete b.tools - delete b.functions - } - return JSON.stringify(b) - } - if (!choice || typeof choice !== "object" || Array.isArray(choice)) { - delete b.tool_choice - return JSON.stringify(b) - } - const type = typeof choice.type === "string" ? choice.type.trim().toLowerCase() : "" - if (type === "none") { - delete b.tool_choice - delete b.tools - delete b.functions - } else if (type === "auto" || type === "required") { - b.tool_choice = type - } else if (type === "function") { - const fn = choice.function && typeof choice.function === "object" && !Array.isArray(choice.function) - ? choice.function - : undefined - const name = typeof fn?.name === "string" ? fn.name.trim() : "" - b.tool_choice = name || "auto" - } else { - delete b.tool_choice - } - return JSON.stringify(b) + return toolChoiceOn(b) ? JSON.stringify(b) : body } catch { return body } } +// toolChoiceOn makes normalizeToolChoice's change to a chat's object; true +// when it made one (a string choice other than none is WorkBuddy's already) +function toolChoiceOn(b) { + if (!b || typeof b !== "object" || Array.isArray(b) || !("tool_choice" in b)) return false + const choice = b.tool_choice + if (typeof choice === "string") { + if (choice.trim().toLowerCase() !== "none") return false + delete b.tool_choice + delete b.tools + delete b.functions + return true + } + if (!choice || typeof choice !== "object" || Array.isArray(choice)) { + delete b.tool_choice + return true + } + const type = typeof choice.type === "string" ? choice.type.trim().toLowerCase() : "" + if (type === "none") { + delete b.tool_choice + delete b.tools + delete b.functions + } else if (type === "auto" || type === "required") { + b.tool_choice = type + } else if (type === "function") { + const fn = choice.function && typeof choice.function === "object" && !Array.isArray(choice.function) + ? choice.function + : undefined + const name = typeof fn?.name === "string" ? fn.name.trim() : "" + b.tool_choice = name || "auto" + } else { + delete b.tool_choice + } + return true +} + // ---- tools WorkBuddy takes ---------------------------------------------------- // WorkBuddy AI answers 400 code 11133 "Invalid request parameters" (the @@ -1261,6 +1289,40 @@ function fitted(body) { } } +// prepared is a request's body read once for every change the loader makes +// to it and everything it reads off it (plugins#461): a long chat, 45 MiB +// of history, was parsed six times on its way, once by each step, and +// written out again whole by normalizeToolChoice even when nothing changed. +// chat is the parsed body, changed whether any step changed it; the caller +// writes it out once, when it did. Each step is the one its own function +// above makes, in the same order. +function prepared(body, native) { + if (!native && (body instanceof ArrayBuffer || ArrayBuffer.isView(body))) body = new TextDecoder().decode(body) + const none = { body, chat: null, names: new Map(), changed: false } + if (typeof body !== "string") return none + let chat + try { + chat = JSON.parse(body) + } catch { + return none + } + if (chat === null || typeof chat !== "object") return none + if (native) return { body, chat, names: new Map(), changed: unsignedOn(chat) } + try { + let changed = systemOn(chat) + const fit = fitTools(chat) + if (fit.changed) changed = true + if (toolChoiceOn(chat)) changed = true + return { body, chat, names: fit.names, changed } + } catch { + // a shape a step can't take: the steps one by one, each keeping the + // body as it was when it can't, as they always have + const fit = fitted(withSystem(body)) + const out = normalizeToolChoice(fit.body) + return { body: out, chat: chatOf(out), names: fit.names, changed: false } + } +} + // namedBack gives the model's calls in a chat answer (one JSON body, or an // SSE stream's chunks) the names the client gave its tools. function namedBack(v, names) { @@ -2302,16 +2364,13 @@ function makePlugin(site) { // /v1/messages, where a chat is refused 11128. const native = isMessages(req ? req.url : String(input), body) let names = {} - if (!native) { - body = withSystem(body) - const fit = fitted(body) - body = normalizeToolChoice(fit.body) - names = fit.names - } else { - body = withoutUnsigned(body) - } + const p = prepared(body, native) + let chat = p.chat + let changed = p.changed + body = p.body + if (!native) names = p.names chatHeaders(site, headers) - attend(headers, body, session) + attendChat(headers, chat, session) const post = (b) => fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: b }).catch((e) => unanswered(site, a, b, e, init?.signal)) // a 401 is answered once, on whichever try meets it: by a @@ -2358,11 +2417,13 @@ function makePlugin(site) { } // 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 model = chat?.model // a system prompt WorkBuddy refused before goes as the user's // words at once (see systemAsUser) - const sysKey = native ? "" : systemKey(body) - if (sysKey && refusedSystems.has(sysKey)) body = systemAsUser(body) ?? body + const sysKey = native ? "" : systemKeyOf(chat) + if (sysKey && refusedSystems.has(sysKey) && systemAsUserOn(chat)) changed = true + if (changed) body = JSON.stringify(chat) + chat = null const shaped = (b) => (!native && endsAfterTools.has(model) ? replyAfterTools(b) ?? b : b) let res = await send(shaped(body)) // a signature WorkBuddy's own signing didn't make — a session @@ -2592,4 +2653,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } +export const _internal = { FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } diff --git a/packages/workbuddy/oneparse.test.mjs b/packages/workbuddy/oneparse.test.mjs new file mode 100644 index 0000000..4e4c167 --- /dev/null +++ b/packages/workbuddy/oneparse.test.mjs @@ -0,0 +1,112 @@ +// plugins#461 (jihuayu): a 45 MiB chat was parsed six times on its way to +// WorkBuddy, once by each step, and written out whole again even when no +// step changed it. prepared reads it once; what goes out is what the steps +// one by one made of it. +import { expect, test } from "bun:test" +import { WorkBuddyAuthPlugin, _internal } from "./index.mjs" + +const { prepared, withSystem, fitted, normalizeToolChoice, withoutUnsigned } = _internal + +const chats = [ + { model: "deepseek-v4.1-flash", messages: [{ role: "system", content: "Be brief." }, { role: "user", content: "hi" }] }, + { model: "m", messages: [{ role: "system", content: "s" }, { role: "user", content: "hi" }], tool_choice: "auto", tools: [{ type: "function", function: { name: "read", parameters: { type: "object" } } }] }, + { model: "m", messages: [{ role: "developer", content: "d" }, { role: "user", content: "x" }], max_completion_tokens: 9 }, + { model: "m", messages: [{ role: "user", content: "no system" }] }, + { model: "m", messages: [{ role: "system", content: "You are Claude Code, Anthropic's official CLI for Claude" }, { role: "user", content: "q" }] }, + { model: "m", messages: [{ role: "system", content: "s" }, { role: "user", content: "q" }, { role: "assistant", content: "a", reasoning_content: "thought" }, { role: "user", content: "q2" }] }, + { model: "m", messages: [{ role: "system", content: "s" }, { role: "user", content: "run" }], tools: [{ type: "function", function: { name: "fs.read", parameters: { type: "object", properties: { v: { type: ["string", "null"] } } } } }], tool_choice: { type: "function", function: { name: "fs.read" } } }, + { model: "m", messages: [{ role: "system", content: "s" }, { role: "user", content: "x" }], tools: [{ type: "function", function: { name: "a" } }], tool_choice: "none" }, + { model: "m", messages: [{ role: "system", content: "s" }, { role: "user", content: "x" }], tool_choice: { type: "required" } }, + { model: "m", messages: [{ role: "system", content: "s" }, { role: "user", content: "x" }], tool_choice: null }, + { model: "m", messages: [{ role: "system", content: "s" }, { role: "user", content: "x" }], tool_choice: { type: "other" } }, + { model: "m", messages: [] }, + { model: "m" }, + [1, 2], + "a string", + 42, + null, +] + +const stepByStep = (body) => { + const fit = fitted(withSystem(body)) + return { body: normalizeToolChoice(fit.body), names: fit.names } +} +const sent = (p) => (p.changed ? JSON.stringify(p.chat) : p.body) +const read = (s) => { + try { + return JSON.parse(s) + } catch { + return s + } +} + +test("one parse makes what the steps one by one made", () => { + for (const c of chats) { + const body = JSON.stringify(c) + const old = stepByStep(body) + const p = prepared(body, false) + expect(read(sent(p))).toEqual(read(old.body)) + expect([...p.names]).toEqual([...old.names]) + } + for (const body of ["not json", "", "{", new TextEncoder().encode(JSON.stringify(chats[0]))]) { + const old = stepByStep(body) + expect(read(sent(prepared(body, false)))).toEqual(read(old.body)) + } +}) + +test("a chat no step changes goes byte for byte, not written out again", () => { + // spaced as no JSON.stringify writes it: any rewrite would show + const body = `{"model": "m", "messages": [{"role": "system", "content": "s"}, {"role": "user", "content": "x"}], "tool_choice": "auto"}` + const p = prepared(body, false) + expect(p.changed).toBe(false) + expect(sent(p)).toBe(body) +}) + +test("a Messages body is read once too, its unsigned thinking dropped as before", () => { + const body = JSON.stringify({ + model: "claude", + system: [{ type: "text", text: "s" }], + messages: [ + { role: "user", content: "q" }, + { role: "assistant", content: [{ type: "thinking", thinking: "t" }, { type: "text", text: "a" }] }, + { role: "user", content: "q2" }, + ], + }) + expect(read(sent(prepared(body, true)))).toEqual(read(withoutUnsigned(body))) + const plain = JSON.stringify({ model: "claude", messages: [{ role: "user", content: "q" }] }) + expect(sent(prepared(plain, true))).toBe(plain) +}) + +test("the loader parses a long chat once", async () => { + const realFetch = globalThis.fetch + const realParse = JSON.parse + let parses = 0 + let out + JSON.parse = (s, ...a) => { + if (typeof s === "string" && s.length > 1 << 20) parses++ + return realParse(s, ...a) + } + globalThis.fetch = async (_url, init) => { + out = init.body + return new Response('data: {"choices":[{"delta":{"content":"OK"}}]}\n\ndata: [DONE]\n\n', { headers: { "content-type": "text/event-stream" } }) + } + try { + const hooks = await WorkBuddyAuthPlugin({ client: { auth: { set: async () => {} } }, magpie: { option: () => false } }) + const auth = { type: "oauth", access: "test-only", refresh: "test-only", uid: "u", expires: Date.now() + 3600000 } + const loader = await hooks.auth.loader(async () => auth) + const body = JSON.stringify({ + model: "deepseek-v4.1-flash", + stream: true, + tool_choice: "auto", + messages: [{ role: "system", content: "s" }, { role: "user", content: "x".repeat(2 << 20) }], + tools: [{ type: "function", function: { name: "test.tool.name", parameters: { type: "object" } } }], + }) + const res = await loader.fetch("https://synthetic.invalid/v2/chat/completions", { method: "POST", body, headers: { "content-type": "application/json" } }) + await res.text() + expect(parses).toBe(1) + expect(read(out)).toEqual(read(stepByStep(body).body)) + } finally { + globalThis.fetch = realFetch + JSON.parse = realParse + } +}) diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 9a73b2b..7f33750 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.41", + "version": "0.1.42", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs",