diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index bb73a6a..7505fc4 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -244,7 +244,9 @@ client names, `none` too, goes as it came. A chat goes gzipped (`Content-Encoding: gzip`), as WorkBuddy's own client sends its model requests (`RequestBodyGzip` in both builds' product.json). -Claude's Messages route goes as it came. +Claude's Messages route goes as it came, and so does anything that isn't a +chat completion: magpie's drawings (`/v2/images/generations`, +`/v2/images/edits`) go as plain JSON, which is all the images API reads. A model's price is its `credits` ("x0.29") and the config's `modelPromotions`. A discount for whole days (Step-5-Preview's 独家限免) is diff --git a/packages/workbuddy/images.test.mjs b/packages/workbuddy/images.test.mjs new file mode 100644 index 0000000..9593b0b --- /dev/null +++ b/packages/workbuddy/images.test.mjs @@ -0,0 +1,90 @@ +// iwinux on Discord (2026-10-28 22:30 UTC+8): magpie's image MCP through +// WorkBuddy AI failed from the minute 0.1.43 was published with +// 400 Bad Request: Unmarshal create image params failed with error: +// invalid character '\x1f' looking for beginning of value (11101) +// 0.1.43 gzipped every body the loader's fetch sent that wasn't Messages, +// and magpie's drawing (internal/gateway/draw_workbuddy.go) sends its JSON +// to /v2/images/generations and /v2/images/edits through that same +// fetch. The images API reads the body as plain JSON and met gzip's first +// byte. Only a chat completion goes gzipped. Every fetch here is a fake. +import { afterEach, expect, test } from "bun:test" +import { WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const bytesOf = (b) => + b == null ? new Uint8Array() : typeof b === "string" ? new TextEncoder().encode(b) : b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array(b.buffer, b.byteOffset, b.byteLength) + +// serve is WorkBuddy's images API as it answered iwinux: it unmarshals the +// raw bytes as JSON, whatever Content-Encoding says, and names the first +// byte it can't read as Go's encoding/json does +function serve() { + const sent = [] + globalThis.fetch = async (url, init) => { + const u = String(url) + const raw = bytesOf(init?.body) + sent.push({ url: u, headers: new Headers(init?.headers), raw }) + if (u.endsWith("/v3/config")) return Response.json({ code: 0, data: { models: [] } }) + try { + JSON.parse(new TextDecoder().decode(raw)) + } catch { + const c = raw[0] < 0x20 ? `'\\x${raw[0].toString(16).padStart(2, "0")}'` : `'${String.fromCharCode(raw[0])}'` + return new Response( + JSON.stringify({ code: 11101, msg: `Unmarshal create image params failed with error: invalid character ${c} looking for beginning of value` }), + { status: 400, statusText: "Bad Request", headers: { "content-type": "application/json" } }, + ) + } + return Response.json({ code: 0, msg: "ok", data: { created: 1, data: [{ b64_json: "aGk=" }] } }) + } + return sent +} + +const AUTH = { type: "oauth", access: "tok", refresh: "r", uid: "u1", expires: Date.now() + 3600_000 } + +async function loader(plugin) { + const h = await plugin({ client: {} }) + return h.auth.loader(async () => AUTH) +} + +// draw is the request magpie's drawWorkBuddy sends, as host.js hands it +// over: a JSON string to an absolute URL +const draw = (opts, url, body) => + opts.fetch(url, { method: "POST", headers: { "content-type": "application/json", accept: "application/json" }, body: JSON.stringify(body) }) + +for (const [name, plugin, site] of [ + ["WorkBuddy AI", WorkBuddyAIAuthPlugin, "https://www.workbuddy.ai"], + ["WorkBuddy", WorkBuddyAuthPlugin, "https://copilot.tencent.com"], +]) { + test(`${name}: a drawing goes as plain JSON, not gzipped`, async () => { + const sent = serve() + const opts = await loader(plugin) + const res = await draw(opts, `${site}/v2/images/generations`, { model: "gpt-image-2.5-sunburst", prompt: "a bird", n: 1, size: "1024x1024", response_format: "b64_json" }) + const text = await res.text() + expect(text).not.toContain("invalid character") + expect(res.status).toBe(200) + const [r] = sent.filter((s) => s.url.endsWith("/v2/images/generations")) + expect(r.raw[0]).toBe("{".charCodeAt(0)) + expect(r.headers.get("content-encoding")).toBeNull() + expect(JSON.parse(new TextDecoder().decode(r.raw)).prompt).toBe("a bird") + }) + + test(`${name}: an edit goes as plain JSON too`, async () => { + const sent = serve() + const opts = await loader(plugin) + const res = await draw(opts, `${site}/v2/images/edits`, { model: "gpt-image-2.5-sunburst", prompt: "make it red", n: 1, image: ["data:image/png;base64,aGk="] }) + expect(res.status).toBe(200) + const [r] = sent.filter((s) => s.url.endsWith("/v2/images/edits")) + expect(r.raw[0]).toBe("{".charCodeAt(0)) + expect(r.headers.get("content-encoding")).toBeNull() + }) + + test(`${name}: a chat still goes gzipped`, async () => { + const sent = serve() + const opts = await loader(plugin) + await opts.fetch(`${site}/v2/chat/completions`, { method: "POST", body: JSON.stringify({ model: "auto", stream: true, messages: [{ role: "user", content: "hi" }] }) }) + const [c] = sent.filter((s) => s.url.endsWith("/v2/chat/completions")) + expect(c.headers.get("content-encoding")).toBe("gzip") + expect([c.raw[0], c.raw[1]]).toEqual([0x1f, 0x8b]) + }) +} diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index ac56429..ec554d9 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -1336,9 +1336,13 @@ function fitted(body) { // copilot.tencent.com against 258 MB down. Measured 2026-10-28 on // www.workbuddy.ai: a gzipped chat answers as the plain one does. A // Messages request (Claude on the China build) goes as it came: that route -// wasn't tried gzipped. null when the body isn't sent gzipped. -function gzipped(native, b) { - if (native) return null +// wasn't tried gzipped. Only a chat completion goes gzipped (isCompletion): +// WorkBuddy's images API reads its body as plain JSON, and magpie's drawing +// (/v2/images/generations, /v2/images/edits) is sent through this same +// fetch; gzipped it answered 400 11101 "invalid character '\x1f'" (iwinux on +// Discord, 0.1.43). null when the body isn't sent gzipped. +function gzipped(completion, b) { + if (!completion) return null if (typeof b === "string") return gzipSync(Buffer.from(b)) if (b instanceof ArrayBuffer || ArrayBuffer.isView(b)) return gzipSync(b) return null @@ -2174,6 +2178,19 @@ function effortsOf(d, site, id) { return EFFORT_ORDER.filter((e) => set.has(e)) } +// isCompletion is whether a request is a chat completion: one to +// .../chat/completions, or, with no URL to read, a body holding a chat's +// messages. Nothing else the loader's fetch sends (magpie's drawings to +// /v2/images/*) is a chat: it goes neither gzipped nor given an effort. +function isCompletion(url, chat) { + let path = "" + try { + path = new URL(String(url ?? "")).pathname + } catch {} + if (path) return /\/chat\/completions$/.test(path) + return Array.isArray(chat?.messages) +} + // defaultEffortOf is the level WorkBuddy's own client asks a model for when // the user picked none: its CLI's configureThinkingSettings (WorkBuddy // 5.9.3, CLI 2.165.0) takes the session's effort, else the settings', else @@ -2486,13 +2503,14 @@ function makePlugin(site) { // 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 - if (!native && chat && !namesEffort(chat) && withDefaultEffort(chat, await effortList(a))) changed = true + const completion = !native && isCompletion(req ? req.url : input, chat) + if (completion && chat && !namesEffort(chat) && withDefaultEffort(chat, await effortList(a))) changed = true chatHeaders(site, headers) attendChat(headers, chat, session) const post = (b) => { // a chat goes gzipped, as WorkBuddy's client sends it // (gzipped); its size on the wire is what unanswered weighs - const z = gzipped(native, b) + const z = gzipped(completion, b) if (z) headers.set("Content-Encoding", "gzip") else headers.delete("Content-Encoding") return fetch(req ? req.url : input, { ...init, method: init?.method ?? req?.method, headers, body: z ?? b }).catch((e) => unanswered(site, a, z ?? b, e, init?.signal)) diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 7b42ccd..f5ab59d 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.44", + "version": "0.1.45", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs",