From 5d1beb37e0af4d8f9f90ea7138550320341fb1b6 Mon Sep 17 00:00:00 2001 From: tearslee Date: Thu, 8 Oct 2026 16:41:53 +0800 Subject: [PATCH] workbuddy: one user send, one X-Conversation-Request-ID (#48) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit WorkBuddy's backend counts a user send as one request by X-Conversation-Request-ID. The China build was sent no conversation headers at all, and the international build a new pair on every request, so one send that takes several steps — a tool result sent back, a retry, another account answering — was counted as a request of its own: one conversation showed up in the usage detail as many requests. The ids are now made as workbuddy2api's fix makes them: the turn's from the body's last user message (its place and its signature, a tool result's part left out), the conversation's from the session magpie or OpenCode names — the chat.headers hook now carries it — else from the chat's first user message; nothing is made up when neither names one. The message and request ids stay each request's own, and both builds carry the ids now. Co-authored-by: tearslee <16331052+tearslee@users.noreply.github.com> --- packages/workbuddy/README.md | 16 +- packages/workbuddy/conversation.test.mjs | 197 +++++++++++++++++++++++ packages/workbuddy/index.mjs | 165 +++++++++++++++++-- packages/workbuddy/package.json | 2 +- 4 files changed, 369 insertions(+), 11 deletions(-) create mode 100644 packages/workbuddy/conversation.test.mjs diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index 44448c2..3426ef6 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -55,7 +55,21 @@ They are streamed only; WorkBuddy refuses a chat that isn't. Each chat carries WorkBuddy's headers: - `Authorization`, `X-User-Id`, `X-Domain`, `X-Product: SaaS`, `X-IDE-Type: WorkBuddy`; - `User-Agent: WorkBuddy/5.5.6`. Without it, WorkBuddy answers error 10085; -- WorkBuddy AI also takes its client and conversation headers. +- the client's, which WorkBuddy's usage list shows as the client that asked + (使用端): `X-Agent-Purpose: conversation`, `X-IDE-Name: WorkBuddy`, + `X-IDE-Version`, `X-Agent-Intent: craft`, `X-Requested-With`. Both builds + send them, as WorkBuddy's own client does; a chat without them is counted + under no client at all; +- the conversation's ids: `X-Conversation-ID`, `X-Conversation-Request-ID`, + `X-Conversation-Message-ID`, `X-Request-ID`. WorkBuddy's backend counts a + user send as one request by `X-Conversation-Request-ID`, so every step of + one send — a tool result sent back, a retry, another account answering — + carries the same one, and the user's next message carries another. The + conversation's is the session magpie (or OpenCode) names the request by, + else the chat's first user message; nothing is made up when neither names + one, a made-up conversation of the request's own being what splits one + conversation into many in the usage detail; +- WorkBuddy AI also takes `X-Agent-Type: main`. A chat that doesn't open with a system message is given WorkBuddy's default one, as the app does. diff --git a/packages/workbuddy/conversation.test.mjs b/packages/workbuddy/conversation.test.mjs new file mode 100644 index 0000000..0e1bae4 --- /dev/null +++ b/packages/workbuddy/conversation.test.mjs @@ -0,0 +1,197 @@ +// One user send is one request to WorkBuddy's backend, whatever it takes: +// every step of it — a tool result sent back, a retry, another account +// answering — carries the same X-Conversation-Request-ID, and the user's next +// message carries another. A conversation's turns share its +// X-Conversation-ID, from the session magpie (or OpenCode) names, else from +// the chat's first user message; each request has a message id of its own. +import { afterEach, expect, test } from "bun:test" +import { WorkBuddyAIAuthPlugin, WorkBuddyAuthPlugin, _internal } from "./index.mjs" + +const { SESSION, signatureOf } = _internal +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +// ask sends a chat as magpie's host does: the chat.headers hook is told the +// session, then the loader's fetch is given what it added, and the request +// WorkBuddy was sent is read back. Nothing leaves the machine. +async function ask(body, { session = "", provider = "workbuddy", plugin = WorkBuddyAuthPlugin, headers = {} } = {}) { + const sent = [] + globalThis.fetch = async (url, init) => { + sent.push(new Headers(init?.headers)) + return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + } + const hooks = await plugin({ client: {} }) + const out = { headers: { ...headers } } + await hooks["chat.headers"]({ sessionID: session, model: { providerID: provider, id: "glm-5.3" }, provider: { info: { id: provider } } }, out) + const l = await hooks.auth.loader(async () => ({ type: "oauth", access: "tok", uid: "u1", expires: Date.now() + 3600_000 })) + const res = await l.fetch("https://copilot.tencent.com/v2/chat/completions", { + method: "POST", + headers: new Headers(out.headers), + body: typeof body === "string" ? body : JSON.stringify(body), + }) + expect(res.status).toBe(200) + return sent.at(-1) +} + +const chat = (...messages) => ({ model: "glm-5.3", stream: true, messages }) +const system = { role: "system", content: "be brief" } +// send is a user send: its message, and nothing of what answering it added +const send = (text) => chat(system, { role: "user", content: text }) +// later is a send of a conversation that has been answered before +const later = (first, text) => chat(system, { role: "user", content: first }, { role: "assistant", content: "hi" }, { role: "user", content: text }) +const call = { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: "{}" } }] } +const result = { role: "tool", tool_call_id: "c1", content: "a.go" } +const HEX32 = /^[0-9a-f]{32}$/ +const turn = (h) => h.get("x-conversation-request-id") +const conv = (h) => h.get("x-conversation-id") +const message = (h) => h.get("x-conversation-message-id") + +test("one send's steps carry one turn id; the user's next message another", async () => { + const asked = await ask(send("跑一下")) + const called = await ask(chat(system, { role: "user", content: "跑一下" }, call)) + const answered = await ask(chat(system, { role: "user", content: "跑一下" }, call, result)) + const ids = [asked, called, answered].map(turn) + expect(ids[0]).toMatch(HEX32) + expect(new Set(ids).size).toBe(1) + // the user's next message is another turn + expect(turn(await ask(later("跑一下", "再来一次")))).not.toBe(ids[0]) + // the same words asked again later are a turn of their own too: the place + // of the message is part of the key + expect(turn(await ask(chat(system, { role: "user", content: "跑一下" }, { role: "assistant", content: "hi" }, { role: "user", content: "跑一下" })))).not.toBe(ids[0]) + // the message's id is its own on each request, and is the request's id + expect(new Set([asked, called, answered].map(message)).size).toBe(3) + for (const h of [asked, called, answered]) expect(message(h)).toBe(h.get("x-request-id")) +}) + +test("a conversation's turns share one id, named by the session magpie gives", async () => { + const one = await ask(send("fix the bug"), { session: "ses_1" }) + const two = await ask(later("fix the bug", "and then?"), { session: "ses_1" }) + expect(conv(one)).toMatch(HEX32) + expect(conv(two)).toBe(conv(one)) + // another session is another conversation, the same words or not + const other = await ask(send("fix the bug"), { session: "ses_2" }) + expect(conv(other)).not.toBe(conv(one)) + // and the session itself goes no further than here + for (const h of [one, two]) expect(h.get(SESSION)).toBe(null) +}) + +test("with no session, the first user message names the conversation", async () => { + const one = await ask(send("hi")) + const two = await ask(chat(system, { role: "user", content: "hi" }, { role: "assistant", content: "hi" }, call, result)) + expect(conv(one)).toMatch(HEX32) + // a step of the same send: the same conversation, and the same turn + expect(conv(two)).toBe(conv(one)) + expect(turn(two)).toBe(turn(one)) + // the user's next message: the same conversation, a turn of its own + const next = await ask(later("hi", "and then?")) + expect(conv(next)).toBe(conv(one)) + expect(turn(next)).not.toBe(turn(one)) + expect(conv(await ask(send("hello")))).not.toBe(conv(one)) + // an image of its own is a conversation's first message too, and signs it + const image = await ask(chat(system, { role: "user", content: [{ type: "image_url", image_url: { url: "data:image/png;base64,AA" } }] })) + expect(conv(image)).toMatch(HEX32) + expect(conv(image)).not.toBe(conv(one)) +}) + +test("nothing names a conversation: no conversation id, the turn's still there", async () => { + // no user message at all + const none = await ask(chat(system)) + expect(conv(none)).toBe(null) + expect(turn(none)).toMatch(HEX32) + // a body that isn't a chat + const bytes = await ask("not json") + expect(conv(bytes)).toBe(null) + expect(turn(bytes)).toMatch(HEX32) + expect(new Set([turn(none), turn(bytes)]).size).toBe(2) +}) + +test("a caller's own ids are kept", async () => { + const h = await ask(send("hi"), { headers: { "x-conversation-request-id": "caller-turn", "x-conversation-id": "caller-conv" } }) + expect(turn(h)).toBe("caller-turn") + expect(conv(h)).toBe("caller-conv") +}) + +test("WorkBuddy AI takes the ids too, with its client's headers", async () => { + const ai = await ask(send("hi"), { provider: "workbuddy-ai", plugin: WorkBuddyAIAuthPlugin }) + expect(turn(ai)).toMatch(HEX32) + expect(conv(ai)).toMatch(HEX32) + expect(ai.get("x-ide-name")).toBe("WorkBuddy") + expect(ai.get("user-agent")).toBe("WorkBuddy/5.5.6") +}) + +test("both builds carry what the usage list shows as the client (使用端)", async () => { + // WorkBuddy's own client sends the whole attribution group on both builds; + // a chat missing any of it is counted under no client at all + const attribution = { + "x-agent-purpose": "conversation", + "x-ide-name": "WorkBuddy", + "x-ide-type": "WorkBuddy", + "x-ide-version": "5.5.6", + "x-product": "SaaS", + "x-agent-intent": "craft", + "x-requested-with": "XMLHttpRequest", + } + for (const [provider, plugin] of [["workbuddy", WorkBuddyAuthPlugin], ["workbuddy-ai", WorkBuddyAIAuthPlugin]]) { + const h = await ask(send("hi"), { provider, plugin }) + for (const [name, want] of Object.entries(attribution)) { + expect([provider, name, h.get(name)]).toEqual([provider, name, want]) + } + } +}) + +test("the hook leaves other providers' requests alone", async () => { + const hooks = await WorkBuddyAuthPlugin({ client: {} }) + const out = { headers: {} } + await hooks["chat.headers"]({ sessionID: "ses_1", model: { providerID: "workbuddy-ai" }, provider: { info: { id: "workbuddy-ai" } } }, out) + expect(out.headers).toEqual({}) +}) + +test("a message's signature is its text, a digest of what isn't, no tool result", () => { + expect(signatureOf("a")).toBe("a") + expect(signatureOf([{ type: "text", text: "a" }, { type: "text", text: "b" }])).toBe("ab") + expect(signatureOf([{ type: "image_url", image_url: { url: "data:image/png;base64,AA" } }])).toMatch(/^\[image_url:[0-9a-f]{8}\]$/) + // Anthropic's shape: a tool result carried beside the user's own words + const carried = [{ type: "tool_result", tool_use_id: "c1", content: "a.go" }, { type: "text", text: "now answer" }] + expect(signatureOf(carried)).toBe("now answer") + expect(signatureOf([{ type: "tool_result", tool_use_id: "c1", content: "a.go" }])).toBe("") + expect(signatureOf(null)).toBe("") + expect(signatureOf(undefined)).toBe("") +}) + +test("a tool result carried in a user message is not the user's words", async () => { + // Anthropic's shape: the result rides in a user message right after the call + const carried = (out) => ({ role: "user", content: [{ type: "tool_result", tool_use_id: "c1", content: out }] }) + const one = await ask(chat(system, { role: "user", content: "hi" }, call, carried("a.go"))) + const two = await ask(chat(system, { role: "user", content: "hi" }, call, carried("b.go"))) + expect(turn(one)).toBe(turn(two)) + expect(conv(one)).toBe(conv(two)) + // the user's own next message still changes the turn + const next = await ask(chat(system, { role: "user", content: "hi" }, call, carried("b.go"), { role: "assistant", content: "done" }, { role: "user", content: "and then?" })) + expect(turn(next)).not.toBe(turn(one)) +}) + +test("a tool result's image sent as a user message is not a turn of its own", async () => { + // pi sends a result's images in a user message right after the result + const attached = (image) => ({ role: "user", content: [{ type: "text", text: "Attached image(s) from tool result:" }, { type: "image_url", image_url: { url: "data:image/png;base64," + image } }] }) + const call2 = { role: "assistant", content: null, tool_calls: [{ id: "c2", type: "function", function: { name: "read_image", arguments: "{}" } }] } + const result2 = { role: "tool", tool_call_id: "c2", content: "b.png" } + const head = [system, { role: "user", content: "看图" }] + const ids = [ + await ask(chat(...head, call)), + await ask(chat(...head, call, result, attached("AA"))), + await ask(chat(...head, call, result, attached("AA"), call2, result2, attached("BB"))), + ].map(turn) + expect(ids[0]).toMatch(HEX32) + expect(new Set(ids).size).toBe(1) +}) + +test("the same words in another conversation are another turn", async () => { + const one = await ask(send("继续"), { session: "ses_1" }) + const other = await ask(send("继续"), { session: "ses_2" }) + expect(turn(other)).not.toBe(turn(one)) + // with no session either: the first message names the conversation, and the + // turn with it + const a = await ask(later("fix it", "继续")) + expect(turn(await ask(later("fix it", "继续")))).toBe(turn(a)) + expect(turn(await ask(later("other", "继续")))).not.toBe(turn(a)) +}) diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 3cbca71..40f758c 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -8,7 +8,7 @@ // streamed only, with WorkBuddy's headers: a request whose User-Agent isn't // WorkBuddy/ is refused (error 10085). -import { randomBytes } from "node:crypto" +import { createHash, randomBytes } from "node:crypto" import { readFileSync } from "node:fs" import { homedir } from "node:os" import { join } from "node:path" @@ -235,7 +235,18 @@ async function refreshed(site, auth) { return Object.keys(out).length ? out : undefined } -// sign sets on headers what WorkBuddy's desktop app sends with a chat. +// sign sets on headers what WorkBuddy's desktop app sends with a chat: the +// account's own, the client's, and the attribution WorkBuddy's usage list +// shows as the client that asked (使用端). The chat's ids — the +// conversation's, the turn's, the message's — are attend's below. +// +// WorkBuddy's own client sends the whole of this on both builds +// (application-manifest.js: X-Agent-Purpose "conversation", X-IDE-Name/Type +// "WorkBuddy", X-IDE-Version, X-Product "SaaS"); a chat without them is +// counted under no client at all, which is the empty 使用端 a request shows +// when only some of the group is there. The gate below used to give the China +// build none of the client's headers, so every China-build request was +// attribution-less. function sign(site, a, headers) { headers.set("Authorization", "Bearer " + a.access) headers.set("X-User-Id", a.uid ?? "") @@ -243,18 +254,144 @@ function sign(site, a, headers) { headers.set("X-Product", "SaaS") headers.set("X-IDE-Type", "WorkBuddy") headers.set("User-Agent", "WorkBuddy/" + UA_VERSION) - if (!site.ai) return headers.set("X-Requested-With", "XMLHttpRequest") headers.set("X-Agent-Intent", "craft") - headers.set("X-Agent-Type", "main") + headers.set("X-Agent-Purpose", "conversation") headers.set("X-IDE-Name", "WorkBuddy") headers.set("X-IDE-Version", UA_VERSION) - const conv = hex() - if (!headers.has("X-Conversation-ID")) headers.set("X-Conversation-ID", conv) - if (!headers.has("X-Conversation-Request-ID")) headers.set("X-Conversation-Request-ID", conv) + if (!site.ai) return + headers.set("X-Agent-Type", "main") +} + +// WorkBuddy's own client names each chat to its gateway four ways: the +// conversation it belongs to, the user send (turn) it answers, the message +// itself, and the request that carried it. Its backend counts a user send as +// one request by X-Conversation-Request-ID: a chat carrying a new one every +// time is counted on its own, so one send that takes several steps — a tool +// call answered and sent again, a retry, another account answering — shows up +// in the usage detail as many requests. The ids below are made from what +// names the conversation and the turn, so every step of one send carries the +// same turn id and the user's next message carries another, as WorkBuddy's +// own client does. + +// SESSION carries the conversation magpie (or OpenCode) names a request by, +// from the chat.headers hook to the loader's fetch. It goes no further. +const SESSION = "x-magpie-workbuddy-session" + +// SALT is what the ids are derived with, so an id says nothing of the words +// it was made from. New in each process, as WorkBuddy's own ids are one +// conversation's own within a run. +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. +function idFor(kind, key) { + return createHash("sha256").update(`${SALT}|${kind}|${key}`).digest("hex").slice(0, 32) +} + +// signatureOf is a message content's signature: its text, and a digest of +// every part that isn't text (an image, a file), so a turn of images alone is +// a turn of its own too. A tool result's part — carried in a user message by +// 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 = "" + 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)}]` + } + } + return out +} + +// answeredBefore is whether msgs[i] answers the message before it — a tool's +// result, or an assistant's calls — rather than carrying the user's own +// words. A client that sends a tool result's images in a user message (pi's +// "Attached image(s) from tool result:") puts that message right after the +// result, and a turn keyed on it would be a turn of its own on every step. +function answeredBefore(msgs, i) { + const prev = msgs[i - 1] + if (prev === null || typeof prev !== "object") return false + if (prev.role === "tool") return true + return prev.role === "assistant" && Array.isArray(prev.tool_calls) && prev.tool_calls.length > 0 +} + +// turnKey names the user send a chat answers: the body's last user message +// that is the user's own, by its place and its signature. Every step of one +// send repeats it; the user's next message changes it. "" for a chat whose +// last such message has nothing signable in it (an empty message) or which +// has none at all: the caller then makes a fresh id for that request, as +// before these were derived at all. +function turnKey(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}` : "" + } + return "" +} + +// conversationKey names the conversation a chat belongs to: the session +// magpie or OpenCode names (its chat.headers hook), else the chat's first +// user message, which every later turn of it repeats. "" when neither names +// one — a body that isn't a chat, or one with no user message in it — and no +// 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}` + 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}` + } + return "" +} + +// chatOf is a chat's body as the object it is, null for one that isn't: a +// body that isn't text (bytes), or isn't JSON at all. +function chatOf(body) { + if (typeof body !== "string") return null + try { + const b = JSON.parse(body) + return b !== null && typeof b === "object" ? b : null + } catch { + return null + } +} + +// sessionOf takes the session a chat.headers hook named off the headers, +// with the header: it goes no further than here. Its length is capped as +// magpie's own session ids are, the id below being derived from it anyway. +function sessionOf(headers) { + const s = String(headers.get(SESSION) ?? "").trim() + headers.delete(SESSION) + return s.slice(0, 128) +} + +// attend sets a chat's ids on the headers its request goes to WorkBuddy +// with: the message's (each request its own, as the client makes them), the +// turn's (one user send, whatever it takes), and the conversation's. A header +// 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) + const conv = conversationKey(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) + // 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()) + } + if (conv && !headers.has("X-Conversation-ID")) headers.set("X-Conversation-ID", idFor("conversation", conv)) } // FLAGGED are the words WorkBuddy refuses a chat for, "Illegal API @@ -674,6 +811,13 @@ function makePlugin(site) { p.api ??= api(site) p.models = { ...configModels(site), ...(p.models ?? {}) } }, + // the conversation's id, which the chats below carry to WorkBuddy: + // magpie's (or OpenCode's) session for this request, when it names one + "chat.headers": async (input, output) => { + const id = input?.model?.providerID ?? input?.provider?.info?.id + if (id !== site.id || !input?.sessionID) return + output.headers[SESSION] = String(input.sessionID).slice(0, 128) + }, provider: { id: site.id, // the account's own list, when it's signed in and WorkBuddy answers; @@ -714,10 +858,13 @@ function makePlugin(site) { headers.delete("authorization") headers.delete("x-api-key") headers.delete("content-length") + const session = sessionOf(headers) sign(site, a, headers) let body = init?.body if (body === undefined && req) body = await req.clone().text() - const res = await fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: withSystem(body) }) + body = withSystem(body) + attend(headers, body, session) + const res = await fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body }) return res.status >= 400 ? explained(res) : kept(res) }, } @@ -823,4 +970,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { withSystem, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, fresh, SITES, renewing, renewed } +export const _internal = { withSystem, unflagged, usageOf, desktopHeld, explained, REFUSED_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 f8d762b..ba25eaa 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.10", + "version": "0.1.11", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs",