diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index b6c3e59..ac56429 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -459,8 +459,28 @@ const SALT = randomBytes(16).toString("hex") // idFor is the 32 hex digits WorkBuddy's own ids are made of, made of a // name of the thing the id is for (a turn, a conversation) and what names it. +// key is a string, or the pieces it is made of: the digest is the same +// either way, and a key made of a 45 MiB message is never joined into one +// string to be hashed (plugins#461). Each piece goes to the hash whole: +// Bun reads a one-byte string's bytes in place, where a piece cut into +// slices was measured costing a copy of each slice. function idFor(kind, key) { - return createHash("sha256").update(`${SALT}|${kind}|${key}`).digest("hex").slice(0, 32) + const h = createHash("sha256").update(`${SALT}|${kind}|`) + // a surrogate pair's first half ending one piece waits for the next, as + // the joined key would hold the pair together + let held = "" + for (let piece of typeof key === "string" ? [key] : key) { + if (held) piece = held + piece + held = "" + const c = piece.charCodeAt(piece.length - 1) + if (c >= 0xd800 && c <= 0xdbff) { + held = piece.slice(-1) + piece = piece.slice(0, -1) + } + h.update(piece) + } + if (held) h.update(held) + return h.digest("hex").slice(0, 32) } // signatureOf is a message content's signature: its text, and a digest of @@ -469,14 +489,20 @@ function idFor(kind, key) { // clients of Anthropic's shape β€” is left out: it is not what the user said, // and it changes with every step of the send. function signatureOf(content) { - if (typeof content === "string") return content - if (!Array.isArray(content)) return "" - let out = "" + return signatureParts(content).join("") +} + +// signatureParts is signatureOf in the pieces it is joined from, none empty +function signatureParts(content) { + if (typeof content === "string") return content ? [content] : [] + if (!Array.isArray(content)) return [] + const out = [] for (const part of content) { const type = part?.type ?? "" - if (type === "" || type === "text") out += typeof part?.text === "string" ? part.text : "" - else if (type !== "tool_result" && type !== "tool-result") { - out += `[${type}:${createHash("sha256").update(JSON.stringify(part)).digest("hex").slice(0, 8)}]` + if (type === "" || type === "text") { + if (typeof part?.text === "string" && part.text) out.push(part.text) + } else if (type !== "tool_result" && type !== "tool-result") { + out.push(`[${type}:${createHash("sha256").update(JSON.stringify(part)).digest("hex").slice(0, 8)}]`) } } return out @@ -522,13 +548,18 @@ function hasBlock(m, type) { // has none at all: the caller then makes a fresh id for that request, as // before these were derived at all. function turnKey(chat) { + return turnParts(chat).join("") +} + +// turnParts is turnKey in pieces (idFor takes them): [] for "" +function turnParts(chat) { const msgs = Array.isArray(chat?.messages) ? chat.messages : [] for (let i = msgs.length - 1; i >= 0; i--) { if (msgs[i]?.role !== "user" || answeredBefore(msgs, i)) continue - const sig = signatureOf(msgs[i].content) - return sig ? `u${i}:${sig}` : "" + const sig = signatureParts(msgs[i].content) + return sig.length ? [`u${i}:`, ...sig] : [] } - return "" + return [] } // conversationKey names the conversation a chat belongs to: the session @@ -538,14 +569,19 @@ function turnKey(chat) { // conversation id is sent then: a made-up one would be a conversation of the // request's own, which is what fragments the usage detail in the first place. function conversationKey(chat, session) { - if (session) return `session:${session}` + return conversationParts(chat, session).join("") +} + +// conversationParts is conversationKey in pieces (idFor takes them): [] for "" +function conversationParts(chat, session) { + if (session) return [`session:${session}`] const msgs = Array.isArray(chat?.messages) ? chat.messages : [] for (const m of msgs) { if (m?.role !== "user") continue - const sig = signatureOf(m.content) - if (sig) return `first:${sig}` + const sig = signatureParts(m.content) + if (sig.length) return ["first:", ...sig] } - return "" + return [] } // isMessages says whether a request is an Anthropic Messages one, which @@ -684,17 +720,17 @@ function attend(headers, body, session) { } function attendChat(headers, chat, session) { - const conv = conversationKey(chat, session) + const conv = conversationParts(chat, session) const msg = hex() headers.set("X-Conversation-Message-ID", msg) headers.set("X-Request-ID", msg) if (!headers.has("X-Conversation-Request-ID")) { - const turn = turnKey(chat) + const turn = turnParts(chat) // a turn is a conversation's own: two conversations whose user message // reads the same are still two sends, not one - headers.set("X-Conversation-Request-ID", turn ? idFor("turn", `${conv}|${turn}`) : hex()) + headers.set("X-Conversation-Request-ID", turn.length ? idFor("turn", [...conv, "|", ...turn]) : hex()) } - if (conv && !headers.has("X-Conversation-ID")) headers.set("X-Conversation-ID", idFor("conversation", conv)) + if (conv.length && !headers.has("X-Conversation-ID")) headers.set("X-Conversation-ID", idFor("conversation", conv)) } // FLAGGED are the words WorkBuddy refuses a chat for, "Illegal API @@ -2237,13 +2273,19 @@ const AFTER_TOOLS_REFUSED = /must end with a user message|["']code["']\s*:\s*["' // ending with the assistant's message is a prefill, refused as it is. function replyAfterTools(body) { const b = chatOf(body) + return replyAfterToolsOn(b) ? JSON.stringify(b) : null +} + +// replyAfterToolsOn makes replyAfterTools's change on a chat's object; false +// for a chat it doesn't take +function replyAfterToolsOn(b) { const msgs = b?.messages - if (!Array.isArray(msgs)) return null + if (!Array.isArray(msgs)) return false 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 + if (i === msgs.length - 1 || i < 0 || msgs[i]?.role !== "tool") return false msgs.splice(i + 1, 0, { role: "assistant", content: "" }) - return JSON.stringify(b) + return true } // FREE_ONLY is the switch that keeps an account off credits (#430): its @@ -2411,18 +2453,6 @@ function makePlugin(site) { sign(site, a, headers) let body = init?.body if (body === undefined && req) body = await req.clone().text() - // the switch is checked before anything is sent: a model not - // free, or one whose price can't be read, never reaches WorkBuddy - if (freeOnly()) { - const model = chatOf(typeof body === "string" ? body : bodyString(body))?.model - let list - try { - list = await listed(a) - } catch (e) { - return notFree(site, model, e?.message ?? String(e)) - } - if (!list.some((m) => m.id === model && m.free)) return notFree(site, model) - } // An Anthropic request goes as the agent sent it: WorkBuddy // serves these models on Messages itself, and the rewrites // below (a default system message, the chat endpoint's @@ -2433,12 +2463,26 @@ function makePlugin(site) { // Codex's and DeepSeek Harness's openings all answer on // /v1/messages, where a chat is refused 11128. const native = isMessages(req ? req.url : String(input), body) - let names = {} - const p = prepared(body, native) - let chat = p.chat - let changed = p.changed - body = p.body - if (!native) names = p.names + // read once (prepared): nothing below parses the body again on + // its way out, and nothing keeps the parsed chat once it is + // written (plugins#461) + let chat, changed, names + ;({ body, chat, changed, names } = prepared(body, native)) + if (native) names = {} + // the switch is checked before anything is sent: a model not + // free, or one whose price can't be read, never reaches + // WorkBuddy. The model is read off the chat parsed above; a body + // prepared leaves unread (bytes on Messages) is read for it. + if (freeOnly()) { + const model = (chat ?? chatOf(typeof body === "string" ? body : bodyString(body)))?.model + let list + try { + list = await listed(a) + } catch (e) { + return notFree(site, model, e?.message ?? String(e)) + } + if (!list.some((m) => m.id === model && m.free)) return notFree(site, model) + } // a chat that names no effort is asked at the model's default, // as WorkBuddy's client asks it (withDefaultEffort); with no // list to read (effortList) the chat goes as it came @@ -2502,10 +2546,16 @@ function makePlugin(site) { // words at once (see systemAsUser) const sysKey = native ? "" : systemKeyOf(chat) if (sysKey && refusedSystems.has(sysKey) && systemAsUserOn(chat)) changed = true + // shaped is a body as such a model takes it. The first try's + // is made on the chat already parsed, after the move above, + // as shaped would make it of the body written; a resend with + // the system prompt moved (below) is shaped again, and a body + // that has the reply already is left as it is. + const shaped = (b) => (!native && endsAfterTools.has(model) ? replyAfterTools(b) ?? b : b) + if (!native && endsAfterTools.has(model) && replyAfterToolsOn(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)) + let res = await send(body) // a signature WorkBuddy's own signing didn't make β€” a session // moved here from another provider keeps its thinking blocks, // and a truncated or altered one reads the same way β€” is 11159 @@ -2733,4 +2783,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { withDefaultEffort, defaultEffortOf, gzipped, 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 } +export const _internal = { idFor, replyAfterToolsOn, withDefaultEffort, defaultEffortOf, gzipped, 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 index e9eae9d..29fea25 100644 --- a/packages/workbuddy/oneparse.test.mjs +++ b/packages/workbuddy/oneparse.test.mjs @@ -111,3 +111,64 @@ test("the loader parses a long chat once", async () => { JSON.parse = realParse } }) + +// counted is what the loader parsed and wrote out of chats over 1 MiB, +// through a plugin with the given magpie options, for each chat sent; the +// fake answers each chat with answer(text) or OK +async function counted(bodies, { option = () => false, answer = () => null, auth } = {}) { + const realFetch = globalThis.fetch + const realParse = JSON.parse + const realStringify = JSON.stringify + const n = { parses: 0, writes: 0 } + JSON.parse = (s, ...a) => { + if (typeof s === "string" && s.length > 1 << 20) n.parses++ + return realParse(s, ...a) + } + JSON.stringify = (...a) => { + const s = realStringify(...a) + if (typeof s === "string" && s.length > 1 << 20) n.writes++ + return s + } + globalThis.fetch = async (url, init) => { + if (String(url).endsWith("/v3/config")) return Response.json({ code: 0, data: { agents: [{ name: "cli", models: ["hy3", "gemini-461"] }], models: [{ id: "hy3", credits: "x0.00" }, { id: "gemini-461", credits: "x0.00" }] } }) + return answer(unz(init.body)) ?? new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + } + const out = [] + try { + const hooks = await WorkBuddyAuthPlugin({ client: { auth: { set: async () => {} } }, magpie: { option } }) + const loader = await hooks.auth.loader(async () => auth ?? { type: "oauth", access: "test-only", refresh: "test-only", uid: "u", expires: Date.now() + 3600000 }) + for (const body of bodies) { + n.parses = n.writes = 0 + const res = await loader.fetch("https://copilot.tencent.com/v2/chat/completions", { method: "POST", body, headers: { "content-type": "application/json" } }) + await res.text() + out.push({ status: res.status, ...n }) + } + } finally { + globalThis.fetch = realFetch + JSON.parse = realParse + JSON.stringify = realStringify + } + return out +} + +const long = (model, extra = {}) => + JSON.stringify({ model, stream: true, messages: [{ role: "system", content: "s" }, { role: "user", content: "x".repeat(2 << 20) }], ...extra }) + +test("with Free models only on, the model is read off the one parse", async () => { + const [r] = await counted([long("hy3")], { option: (_p, k) => k === "free_only", auth: { type: "api", key: "ck_test0000000000abcdefgh" } }) + expect(r).toEqual({ status: 200, parses: 1, writes: 0 }) +}) + +test("a model that wants the reply after tools has it put in on the one parse", async () => { + const call = { role: "assistant", content: "", tool_calls: [{ id: "c", type: "function", function: { name: "bash", arguments: "{}" } }] } + const chat = (n) => JSON.stringify({ model: "gemini-461", messages: [{ role: "user", content: "go" }, call, { role: "tool", tool_call_id: "c", content: "y".repeat(2 << 20) }, { role: "user", content: `now ${n}` }] }) + // refused unless the reply sits after the tool's result; read without a + // parse of its own, which would be counted + const answer = (text) => + text.indexOf('{"role":"assistant","content":""}') > text.indexOf('"role":"tool"') ? null : new Response('{"error":{"code":11153}}', { status: 400 }) + // the first teaches the plugin (refused, sent again with the reply); the + // second has it up front: read once, written once + const [first, second] = await counted([chat(1), chat(2)], { answer }) + expect(first.status).toBe(200) + expect(second).toEqual({ status: 200, parses: 1, writes: 1 }) +}) diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 3cc9964..7b42ccd 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.43", + "version": "0.1.44", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs", diff --git a/packages/workbuddy/sent.test.mjs b/packages/workbuddy/sent.test.mjs new file mode 100644 index 0000000..ff4b2b6 --- /dev/null +++ b/packages/workbuddy/sent.test.mjs @@ -0,0 +1,27 @@ +// plugins#461: the chat is read once and its ids made without joining a +// long message into new strings. What goes to WorkBuddy is what 0.1.43 +// sent, byte for byte: testdata/sent-0.1.43.json is testdata/sent.mjs run +// against 0.1.43's index.mjs (the npm tarball's), each body by its sha256 +// and each derived id by which requests share it. Every fetch is a fake. +import { expect, test } from "bun:test" +import { readFileSync } from "node:fs" +import * as mod from "./index.mjs" +import { sentBy } from "./testdata/sent.mjs" + +const was = JSON.parse(readFileSync(new URL("./testdata/sent-0.1.43.json", import.meta.url), "utf8")) + +test("every chat goes as 0.1.43 sent it, retries and the free-only switch included", async () => { + // in this order: the second run meets what the first taught the plugin + // (a model that wants the reply after tools, a refused system prompt) + expect(await sentBy(mod, false)).toEqual(was.off) + expect(await sentBy(mod, true)).toEqual(was.freeOnly) +}) + +test("an id made of pieces is the id of the pieces joined, a surrogate pair split between them too", () => { + const { idFor } = mod._internal + const smile = "πŸ™‚" + for (const pieces of [["first:", "a", "[image_url:0123abcd]"], ["x" + smile[0], smile[1] + "y"], ["lone" + smile[0]], [smile[0], smile[0], smile[1]], ["", "u3:", "Γ©δΈ­"]]) { + expect(idFor("turn", pieces)).toBe(idFor("turn", pieces.join(""))) + } + expect(idFor("turn", ["a"])).not.toBe(idFor("conversation", ["a"])) +}) diff --git a/packages/workbuddy/testdata/sent-0.1.43.json b/packages/workbuddy/testdata/sent-0.1.43.json new file mode 100644 index 0000000..730c53d --- /dev/null +++ b/packages/workbuddy/testdata/sent-0.1.43.json @@ -0,0 +1,315 @@ +{ + "off": [ + { + "label": "plain", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "59e90e18037612eb444dbe2ba1b5f4fc1c50849589240970357f54c92a441048", + "conversation": "id0", + "turn": "id1" + } + ] + }, + { + "label": "opencode tools", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "4313871b1ee3a9d4e0869676cc2ffc48a887316367b1f42a11566dd35296c6c6", + "conversation": "id2", + "turn": "id3" + } + ] + }, + { + "label": "default effort", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "22b7f46b07d89c0679760d51f1fe53d547359574debe333354a73818e1037826", + "conversation": "id4", + "turn": "id5" + } + ] + }, + { + "label": "developer, no system", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "6a1ce08aeb4e013e8287698e442754da229f5d0385d07ef6be2f575d58c77a7f", + "conversation": "id6", + "turn": "id7" + } + ] + }, + { + "label": "after tools, refused", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "0d1ac7ee8e1a928d0df5493c9c931d6798a8677d38cb9ded11359f1e8b04a556", + "conversation": "id2", + "turn": "id3" + }, + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "41ff2bb4e605ad82d6684e9806531c0546771f5d5c3d58ed5a639ae7aae14935", + "conversation": "id2", + "turn": "id3" + } + ] + }, + { + "label": "after tools, known", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "4cca50eea274fe1d53883803cf1a21b5da19864e8e5b86c6921df800a0e8ee61", + "conversation": "id2", + "turn": "id8" + } + ] + }, + { + "label": "system refused", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "98a7e94ac60d64c3adaf1e98e076437680e46008d364795871dcd8a6a30c7ab3", + "conversation": "id0", + "turn": "id1" + }, + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "124f305a6897261515325c9d4d7c4b6e5a2e586e984ed252a93d24ed09242548", + "conversation": "id0", + "turn": "id1" + } + ] + }, + { + "label": "system known refused", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "a0dc1ed8a18b73f19334ac0318692c8d16bc8998e3429b88e912228e7db0e52e", + "conversation": "id9", + "turn": "id10" + } + ] + }, + { + "label": "both", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "d11353aaad5d4d10d08cb99fd2cfb1857e8e3f0c85f64e096caa0c2e8ce3e94c", + "conversation": "id11", + "turn": "id12" + }, + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "6719aef9e98e84fd8cf019cc07853063cc2c67655c635ec94358c16dc92c6e09", + "conversation": "id11", + "turn": "id12" + } + ] + }, + { + "label": "messages", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v1/messages", + "encoding": null, + "body": "189ca577bde99c23451117367dbcdd13d191124ed3d522e1908f3036b4164be0", + "conversation": "id13", + "turn": "id14" + } + ] + }, + { + "label": "bytes", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "7303f704d6aab8b9e19ec838c85b75d2619c099bd11055d8fb316a6e33c699e6", + "conversation": "id15", + "turn": "id16" + } + ] + }, + { + "label": "not json", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "92072df399cb74703f8e86f450d552bc0bb01eeeb98a90985a1b7772c8fd0016", + "conversation": null, + "turn": "id17" + } + ] + } + ], + "freeOnly": [ + { + "label": "plain", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "59e90e18037612eb444dbe2ba1b5f4fc1c50849589240970357f54c92a441048", + "conversation": "id0", + "turn": "id1" + } + ] + }, + { + "label": "opencode tools", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "4313871b1ee3a9d4e0869676cc2ffc48a887316367b1f42a11566dd35296c6c6", + "conversation": "id2", + "turn": "id3" + } + ] + }, + { + "label": "default effort", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "22b7f46b07d89c0679760d51f1fe53d547359574debe333354a73818e1037826", + "conversation": "id4", + "turn": "id5" + } + ] + }, + { + "label": "developer, no system", + "status": 404, + "sent": [] + }, + { + "label": "after tools, refused", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "41ff2bb4e605ad82d6684e9806531c0546771f5d5c3d58ed5a639ae7aae14935", + "conversation": "id2", + "turn": "id3" + } + ] + }, + { + "label": "after tools, known", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "4cca50eea274fe1d53883803cf1a21b5da19864e8e5b86c6921df800a0e8ee61", + "conversation": "id2", + "turn": "id6" + } + ] + }, + { + "label": "system refused", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "124f305a6897261515325c9d4d7c4b6e5a2e586e984ed252a93d24ed09242548", + "conversation": "id0", + "turn": "id1" + } + ] + }, + { + "label": "system known refused", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "a0dc1ed8a18b73f19334ac0318692c8d16bc8998e3429b88e912228e7db0e52e", + "conversation": "id7", + "turn": "id8" + } + ] + }, + { + "label": "both", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "6719aef9e98e84fd8cf019cc07853063cc2c67655c635ec94358c16dc92c6e09", + "conversation": "id9", + "turn": "id10" + } + ] + }, + { + "label": "messages", + "status": 404, + "sent": [] + }, + { + "label": "bytes", + "status": 200, + "sent": [ + { + "url": "https://www.workbuddy.ai/v2/chat/completions", + "encoding": "gzip", + "body": "7303f704d6aab8b9e19ec838c85b75d2619c099bd11055d8fb316a6e33c699e6", + "conversation": "id11", + "turn": "id12" + } + ] + }, + { + "label": "not json", + "status": 404, + "sent": [] + } + ] +} diff --git a/packages/workbuddy/testdata/sent.mjs b/packages/workbuddy/testdata/sent.mjs new file mode 100644 index 0000000..a20c1c7 --- /dev/null +++ b/packages/workbuddy/testdata/sent.mjs @@ -0,0 +1,113 @@ +// sentBy runs a few realistic chats through a WorkBuddy plugin module's +// loader and gives back every request it sent WorkBuddy, as the bytes on +// the wire read back (see unz), their encoding, and the ids derived from +// the chat. Every fetch is a fake. sent.test.mjs holds the result to what +// workbuddy 0.1.43 sent for the same chats (plugins#461); this runs any +// version's index.mjs, which is how those hashes were made. +import { createHash } from "node:crypto" +import { unz } from "./unz.mjs" + +const CONFIG = { + code: 0, + data: { + agents: [{ name: "cli", models: ["deepseek-v4.1-flash", "hy3", "gemini-sent-461", "glm-5.2"] }], + models: [ + { id: "deepseek-v4.1-flash", credits: "x0.00", supportsReasoning: true, onlyReasoning: true, + reasoning: { canDisableThinking: true, defaultEffort: "high", supportedEfforts: ["low", "high", "max"] } }, + { id: "hy3", credits: "x0.00" }, + { id: "gemini-sent-461", credits: "x0.00" }, + { id: "glm-5.2", credits: "x0.79", supportsReasoning: true, reasoning: { defaultEffort: "xhigh", supportedEfforts: ["high", "xhigh"] } }, + ], + }, +} + +const AFTER_TOOLS = JSON.stringify({ error: { message: "the conversation must end with a user message", code: 11153 } }) +const REFUSAL = JSON.stringify({ error: { message: "unapproved channel", code: 14018 } }) + +// what an agent sends: OpenCode's tool names and schemas, a tool turn, an +// earlier turn's reasoning, an image, a long system prompt +const SYSTEM = "You are opencode, an interactive CLI tool.\n".repeat(40) +const TOOLS = [ + { type: "function", function: { name: "read", description: "Read a file", parameters: { type: "object", properties: { filePath: { type: "string" }, offset: { type: ["number", "null"] } }, required: ["filePath"] } } }, + { type: "function", function: { name: "github.create_issue", description: "MCP", parameters: { type: "object", properties: { title: { type: "string" }, labels: { type: "array", items: { type: "string" } } } } } }, + { type: "function", function: { name: "bash", parameters: { type: "object", properties: { command: { type: "string" } }, required: ["command"], additionalProperties: false } } }, +] +const call = { role: "assistant", content: "", reasoning_content: "I should list them.", 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\nδΈ­ζ–‡.md πŸ™‚" } +const image = { type: "image_url", image_url: { url: "data:image/png;base64," + Buffer.from("not really a png").toString("base64") } } + +export const CHATS = [ + // as an agent spaced it, nothing to change: goes byte for byte + ["plain", "https://www.workbuddy.ai/v2/chat/completions", `{"model": "hy3", "stream": true, "messages": [{"role": "system", "content": "Be brief."}, {"role": "user", "content": "hi"}], "reasoning_effort": "low"}`], + ["opencode tools", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "deepseek-v4.1-flash", stream: true, stream_options: { include_usage: true }, max_tokens: 32000, messages: [{ role: "system", content: SYSTEM }, { role: "user", content: "List the files." }, call, result, { role: "user", content: [{ type: "text", text: "and this" }, image] }], tools: TOOLS, tool_choice: "auto" })], + ["default effort", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "deepseek-v4.1-flash", stream: true, messages: [{ role: "user", content: "hi πŸ™‚" }], tools: TOOLS, tool_choice: { type: "function", function: { name: "github.create_issue" } } })], + ["developer, no system", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "glm-5.2", messages: [{ role: "developer", content: "d" }, { role: "user", content: "x" }], max_completion_tokens: 9, reasoning: { effort: "high" } })], + // gemini answers 11153 to tools then the user: the reply goes between + // them, and the next chat has it up front + ["after tools, refused", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "gemini-sent-461", stream: true, messages: [{ role: "system", content: "s" }, { role: "user", content: "List the files." }, call, result, { role: "user", content: "now" }], tools: TOOLS })], + ["after tools, known", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "gemini-sent-461", stream: true, messages: [{ role: "system", content: "s" }, { role: "user", content: "List the files." }, call, result, { role: "user", content: [{ type: "text", text: "r" }] }, { role: "user", content: "now" }], tools: TOOLS })], + // a system prompt refused once goes as the user's words, at once next time + ["system refused", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "hy3", messages: [{ role: "system", content: "REFUSE-461 " + SYSTEM }, { role: "user", content: "hi" }] })], + ["system known refused", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "hy3", messages: [{ role: "system", content: "REFUSE-461 " + SYSTEM }, { role: "user", content: "hi again" }], tools: TOOLS })], + ["both", "https://www.workbuddy.ai/v2/chat/completions", JSON.stringify({ model: "gemini-sent-461", messages: [{ role: "system", content: "REFUSE-461 " + SYSTEM }, { role: "user", content: "go" }, call, result, { role: "system", content: "late" }, { role: "user", content: "now" }] })], + // a Claude model on Messages goes as it came but for unsigned thinking + ["messages", "https://www.workbuddy.ai/v1/messages", JSON.stringify({ model: "claude-opus-5.5", max_tokens: 64, 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" }] })], + ["bytes", "https://www.workbuddy.ai/v2/chat/completions", new TextEncoder().encode(JSON.stringify({ model: "hy3", messages: [{ role: "user", content: "bytes ΓΌ" }], tools: TOOLS }))], + ["not json", "https://www.workbuddy.ai/v2/chat/completions", "{not json"], +] + +const sha = (s) => createHash("sha256").update(s ?? "").digest("hex") + +// sentBy(mod, freeOnly) is what mod's WorkBuddy AI plugin sent for CHATS, +// with the "Free models only" switch on or off +export async function sentBy(mod, freeOnly = false) { + const real = globalThis.fetch + const sent = [] + globalThis.fetch = async (url, init) => { + const u = String(url) + if (u.endsWith("/v3/config")) return Response.json(CONFIG) + const h = new Headers(init?.headers) + const text = unz(init?.body) + const s = typeof text === "string" ? text : new TextDecoder().decode(text) + sent.push({ url: u, encoding: h.get("content-encoding"), body: sha(s), conversation: h.get("x-conversation-id"), turn: h.get("x-conversation-request-id") }) + if (s.includes("REFUSE-461") && s.includes('"role":"system","content":"REFUSE-461')) return new Response(REFUSAL, { status: 400, headers: { "content-type": "application/json" } }) + if (s.includes('"gemini-sent-461"')) { + const m = JSON.parse(s).messages + let i = m.length - 1 + while (i >= 0 && m[i].role === "user") i-- + if (i < m.length - 1 && m[i]?.role === "tool") return new Response(AFTER_TOOLS, { status: 400, headers: { "content-type": "application/json" } }) + } + return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + } + try { + const hooks = await mod.WorkBuddyAIAuthPlugin({ client: { auth: { set: async () => {} } }, magpie: { option: (_p, k) => freeOnly && k === "free_only" } }) + 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 out = [] + for (const [label, url, body] of CHATS) { + const from = sent.length + const res = await loader.fetch(url, { method: "POST", body, headers: { "content-type": "application/json" } }) + await res.text() + out.push({ label, status: res.status, sent: sent.slice(from) }) + } + return canonical(out) + } finally { + globalThis.fetch = real + } +} + +// canonical names each derived id by where it first showed up, as the ids +// are salted afresh in each process: what stays is which requests share one +function canonical(out) { + const seen = new Map() + const name = (id) => { + if (id == null) return null + if (!seen.has(id)) seen.set(id, `id${seen.size}`) + return seen.get(id) + } + for (const o of out) for (const s of o.sent) { + s.conversation = name(s.conversation) + s.turn = name(s.turn) + } + return out +}