diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index 28e1099..bb73a6a 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -235,7 +235,16 @@ is used. - Kimi-K3, Kimi-K2.6 - MiniMax-M3 -A model's reasoning levels are its variants (`reasoningEffort`). +A model's reasoning levels are its variants (`reasoningEffort`). A chat +that names no level goes at the model's own default from the config +(`reasoning.defaultEffort`, "high" for DeepSeek-V4.1-Flash), as WorkBuddy's +client sends it: WorkBuddy doesn't think when a chat names none, so +OpenCode's default variant got answers without thinking. An effort the +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. 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/aftertools.test.mjs b/packages/workbuddy/aftertools.test.mjs index 72b996d..59ba298 100644 --- a/packages/workbuddy/aftertools.test.mjs +++ b/packages/workbuddy/aftertools.test.mjs @@ -3,6 +3,7 @@ // 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" +import { unz } from "./testdata/unz.mjs" const { replyAfterTools } = _internal @@ -25,7 +26,7 @@ async function withService(fn) { const realFetch = globalThis.fetch const sent = [] globalThis.fetch = async (_url, init) => { - const b = JSON.parse(init.body) + const b = JSON.parse(unz(init.body)) sent.push(b) const m = b.messages let i = m.length - 1 diff --git a/packages/workbuddy/apikey.test.mjs b/packages/workbuddy/apikey.test.mjs index 1c10414..ca4b23b 100644 --- a/packages/workbuddy/apikey.test.mjs +++ b/packages/workbuddy/apikey.test.mjs @@ -13,6 +13,10 @@ afterEach(() => (globalThis.fetch = real)) const KEY = "ck_test0000000000abcdefgh" const OK = () => new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) +// chatsOf are the requests sent but the product config, which a chat with +// no effort of its own may read first for its default (withDefaultEffort) +const chatsOf = (sent) => sent.filter((s) => !s.url.endsWith("/v3/config")) + // record answers each fetch with reply and keeps the URL and headers sent function record(reply = OK) { const sent = [] @@ -57,9 +61,9 @@ for (const [plugin, site, url] of [ expect(typeof opts.fetch).toBe("function") const res = await chat(opts, url) expect(res.status).toBe(200) - expect(sent).toHaveLength(1) - const h = sent[0].headers - expect(sent[0].url).toBe(url) + expect(chatsOf(sent)).toHaveLength(1) + const h = chatsOf(sent)[0].headers + expect(chatsOf(sent)[0].url).toBe(url) expect(h.get("x-api-key")).toBe(KEY) expect(h.get("authorization")).toBe("Bearer " + KEY) expect(h.get("x-user-id")).toBe("anonymous_abcdefgh") @@ -74,8 +78,8 @@ for (const [plugin, site, url] of [ const hooks = await plugin({ client: {} }) const opts = await hooks.auth.loader(async () => ({ type: "oauth", access: "tok", refresh: "r", uid: "u1", expires: Date.now() + 3600_000 })) await chat(opts, url) - const h = sent[0].headers - expect(sent[0].url).toBe(url) + const h = chatsOf(sent)[0].headers + expect(chatsOf(sent)[0].url).toBe(url) expect(h.get("authorization")).toBe("Bearer tok") expect(h.has("x-api-key")).toBe(false) expect(h.get("x-user-id")).toBe("u1") @@ -88,7 +92,7 @@ for (const [plugin, site, url] of [ const opts = await hooks.auth.loader(async () => ({ type: "api", key: KEY })) const res = await chat(opts, url) expect(res.status).toBe(401) - expect(sent).toHaveLength(1) // no refresh asked, no second send + expect(chatsOf(sent)).toHaveLength(1) // no refresh asked, no second send expect(res.headers.get("X-Magpie-Sign-In")).toBe("expired") const { error } = await res.json() expect(error.message).toContain("refused this API key (401)") diff --git a/packages/workbuddy/default-effort.test.mjs b/packages/workbuddy/default-effort.test.mjs new file mode 100644 index 0000000..a4d8f35 --- /dev/null +++ b/packages/workbuddy/default-effort.test.mjs @@ -0,0 +1,151 @@ +// troilus1011 on X: WorkBuddy's DeepSeek in OpenCode thought at low and +// high, never at the default. OpenCode's default variant names no effort, +// and WorkBuddy doesn't think without one; WorkBuddy's own client sends the +// config's reasoning.defaultEffort (configureThinkingSettings). The config +// below is the China build's own for deepseek-v4.1-flash (2026-10-28), with +// models beside it that take no effort or another default. +// +// runmiNeverstop on X: 2.89 GB up to copilot.tencent.com. WorkBuddy's own +// client gzips a model request's body (GzipRequestProcessor); the plugin +// sent it as plain JSON. Every fetch here is a fake. +import { afterEach, expect, test } from "bun:test" +import { WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" +import { unz } from "./testdata/unz.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const CONFIG = { + code: 0, + data: { + agents: [{ name: "cli", models: ["deepseek-v4.1-flash", "glm-5.2", "auto", "odd-default", "claude-opus-5.5"] }], + models: [ + { id: "deepseek-v4.1-flash", name: "Deepseek-V4.1-Flash", supportsReasoning: true, onlyReasoning: true, + reasoning: { canDisableThinking: true, defaultEffort: "high", summary: "auto", supportedEfforts: ["low", "high", "max"] } }, + { id: "glm-5.2", name: "GLM-5.2", supportsReasoning: true, + reasoning: { canDisableThinking: true, defaultEffort: "xhigh", summary: "auto", supportedEfforts: ["high", "xhigh"] } }, + { id: "auto", name: "Auto" }, + // a default its own levels don't hold: WorkBuddy's client clamps it, + // the plugin leaves it to the server + { id: "odd-default", name: "Odd", supportsReasoning: true, reasoning: { defaultEffort: "medium", supportedEfforts: ["low", "high"] } }, + { id: "claude-opus-5.5", name: "Claude-Opus-5.5", supportsReasoning: true, reasoning: { defaultEffort: "high", supportedEfforts: ["low", "high", "xhigh"] } }, + ], + }, +} + +const OK = () => new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + +// serve answers /v3/config with config() and anything else with OK, and +// keeps each request: its URL, headers, the body on the wire and as text +function serve(config = () => Response.json(CONFIG)) { + const sent = [] + globalThis.fetch = async (url, init) => { + const u = String(url) + sent.push({ url: u, headers: new Headers(init?.headers), wire: init?.body, text: unz(init?.body) }) + if (u.endsWith("/v3/config")) return config() + return OK() + } + return sent +} + +const AUTH = { type: "oauth", access: "tok", refresh: "r", uid: "u1", expires: Date.now() + 3600_000 } +const CN_CHAT = "https://copilot.tencent.com/v2/chat/completions" +const chatsOf = (sent) => sent.filter((s) => !s.url.endsWith("/v3/config")) + +async function loader(plugin = WorkBuddyAuthPlugin) { + const h = await plugin({ client: {} }) + return h.auth.loader(async () => AUTH) +} + +const ask = (opts, model, extra = {}, url = CN_CHAT) => + opts.fetch(url, { method: "POST", body: JSON.stringify({ model, stream: true, messages: [{ role: "user", content: "hi" }], ...extra }) }) + +test("a DeepSeek chat that names no effort goes at the config's default, as WorkBuddy's client asks it", async () => { + const sent = serve() + const opts = await loader() + expect((await ask(opts, "deepseek-v4.1-flash")).status).toBe(200) + const [c] = chatsOf(sent) + expect(JSON.parse(c.text).reasoning_effort).toBe("high") + // another model's default is its own + await ask(opts, "glm-5.2") + expect(JSON.parse(chatsOf(sent)[1].text).reasoning_effort).toBe("xhigh") + // the list was read once for both + expect(sent.filter((s) => s.url.endsWith("/v3/config"))).toHaveLength(1) +}) + +test("an effort the client named goes as it came, none too, and the list isn't read for it", async () => { + const sent = serve() + const opts = await loader() + for (const e of ["none", "low", "max"]) await ask(opts, "deepseek-v4.1-flash", { reasoning_effort: e }) + await ask(opts, "deepseek-v4.1-flash", { reasoning: { effort: "low" } }) + const chats = chatsOf(sent).map((c) => JSON.parse(c.text)) + expect(chats.map((c) => c.reasoning_effort)).toEqual(["none", "low", "max", undefined]) + expect(chats[3].reasoning).toEqual({ effort: "low" }) + expect(sent.filter((s) => s.url.endsWith("/v3/config"))).toHaveLength(0) +}) + +test("a model that takes no effort, or whose default its levels don't hold, gets none", async () => { + const sent = serve() + const opts = await loader() + await ask(opts, "auto") + await ask(opts, "odd-default") + await ask(opts, "not-listed") + for (const c of chatsOf(sent)) expect(JSON.parse(c.text).reasoning_effort).toBeUndefined() +}) + +test("a config that can't be read leaves the chat as it came, and is tried again a minute later, not on each chat", async () => { + const sent = serve(() => new Response("down", { status: 502 })) + const opts = await loader() + expect((await ask(opts, "deepseek-v4.1-flash")).status).toBe(200) + expect((await ask(opts, "deepseek-v4.1-flash")).status).toBe(200) + for (const c of chatsOf(sent)) expect(JSON.parse(c.text).reasoning_effort).toBeUndefined() + expect(sent.filter((s) => s.url.endsWith("/v3/config"))).toHaveLength(1) +}) + +test("a chat goes gzipped, as WorkBuddy's client sends it, on both builds", async () => { + for (const [plugin, url] of [ + [WorkBuddyAuthPlugin, CN_CHAT], + [WorkBuddyAIAuthPlugin, "https://www.workbuddy.ai/v2/chat/completions"], + ]) { + const sent = serve() + const opts = await loader(plugin) + const history = Array.from({ length: 200 }, (_, i) => ({ role: i % 2 ? "assistant" : "user", content: `step ${i}: read src/file${i}.ts and run the tests again` })) + const body = JSON.stringify({ model: "deepseek-v4.1-flash", reasoning_effort: "high", stream: true, messages: [{ role: "system", content: "You are an agent." }, ...history] }) + await opts.fetch(url, { method: "POST", body }) + const [c] = chatsOf(sent) + expect(c.url).toBe(url) + expect(c.headers.get("content-encoding")).toBe("gzip") + expect(c.headers.has("content-length")).toBe(false) + expect(typeof c.wire).not.toBe("string") + expect(JSON.parse(c.text)).toEqual(JSON.parse(body)) + expect(c.wire.byteLength * 5).toBeLessThan(Buffer.byteLength(body)) + } +}) + +test("a body handed over as bytes goes gzipped too", async () => { + const sent = serve() + const opts = await loader() + const body = JSON.stringify({ model: "glm-5.2", reasoning_effort: "high", stream: true, messages: [{ role: "system", content: "You are an agent." }, { role: "user", content: "hi" }] }) + await opts.fetch(CN_CHAT, { method: "POST", body: new TextEncoder().encode(body) }) + const [c] = chatsOf(sent) + expect(c.headers.get("content-encoding")).toBe("gzip") + expect(JSON.parse(c.text)).toEqual(JSON.parse(body)) +}) + +test("a Claude request on Messages goes as it came: neither gzipped nor given an effort", async () => { + const sent = serve() + const opts = await loader() + const body = JSON.stringify({ model: "claude-opus-5.5", max_tokens: 100, stream: true, messages: [{ role: "user", content: "hi" }] }) + await opts.fetch("https://copilot.tencent.com/v1/messages", { method: "POST", body }) + const [c] = chatsOf(sent) + expect(c.headers.has("content-encoding")).toBe(false) + expect(c.wire).toBe(body) +}) + +test("defaultEffortOf reads defaultEffort, else effort, held to the model's levels", () => { + const { defaultEffortOf } = _internal + expect(defaultEffortOf({ reasoning: { defaultEffort: "high" } }, ["low", "high"])).toBe("high") + expect(defaultEffortOf({ reasoning: { effort: "medium" } }, ["low", "medium", "high", "max"])).toBe("medium") + expect(defaultEffortOf({ reasoning: { defaultEffort: "medium" } }, ["low", "high"])).toBeUndefined() + expect(defaultEffortOf({}, ["low"])).toBeUndefined() +}) diff --git a/packages/workbuddy/freeonly.test.mjs b/packages/workbuddy/freeonly.test.mjs index e97f6ec..7f80ee5 100644 --- a/packages/workbuddy/freeonly.test.mjs +++ b/packages/workbuddy/freeonly.test.mjs @@ -5,6 +5,7 @@ // reaches the network. import { afterEach, expect, test } from "bun:test" import { WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" +import { unz } from "./testdata/unz.mjs" const real = globalThis.fetch afterEach(() => (globalThis.fetch = real)) @@ -35,7 +36,7 @@ function serve(config = () => Response.json(CONFIG)) { const sent = [] globalThis.fetch = async (url, init) => { const u = String(url) - sent.push({ url: u, body: init?.body }) + sent.push({ url: u, body: unz(init?.body) }) if (u.endsWith("/v3/config")) return config() return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) } @@ -119,11 +120,13 @@ for (const [plugin, site, url] of [ expect(sent.filter((s) => s.url === url)).toHaveLength(0) }) - test(`${site}: off, a paid model's request goes as before, the list not read`, async () => { + test(`${site}: off, a paid model's request goes as before, the list not read for its price`, async () => { const sent = serve() const h = await plugin({ client: {}, magpie: magpieWith({}) }) const opts = await h.auth.loader(async () => ({ type: "api", key: KEY })) - expect((await chat(opts, url, "glm-5.3")).status).toBe(200) + // the effort named: nothing to read the list for (withDefaultEffort) + const res = await opts.fetch(url, { method: "POST", body: JSON.stringify({ model: "glm-5.3", reasoning_effort: "low", stream: true, messages: [{ role: "user", content: "hi" }] }) }) + expect(res.status).toBe(200) expect(sent.map((s) => s.url)).toEqual([url]) }) } diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index db1b7bb..b6c3e59 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -13,6 +13,7 @@ import { createHash, randomBytes } from "node:crypto" import { readFileSync } from "node:fs" import { homedir } from "node:os" import { join } from "node:path" +import { gzipSync } from "node:zlib" const APP_VERSION = "2.0.0" // the version WorkBuddy's sign-in page is opened with const POLL_MS = 1000 @@ -1289,6 +1290,24 @@ function fitted(body) { } } +// gzipped is a chat's body compressed, as WorkBuddy's own client sends its +// model requests: its CLI's GzipRequestProcessor (WorkBuddy 5.9.3, CLI +// 2.165.0; WorkBuddy AI 5.8.4 the same) gzips each POST's body and sets +// Content-Encoding: gzip when the product's RequestBodyGzip feature is on, +// which both builds' product.json turn on and /v3/config (merged over it) +// doesn't turn off. Sent as plain JSON, a long agent conversation went up +// whole on every step: runmiNeverstop on X saw 2.89 GB up to +// 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 + if (typeof b === "string") return gzipSync(Buffer.from(b)) + if (b instanceof ArrayBuffer || ArrayBuffer.isView(b)) return gzipSync(b) + return null +} + // 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 @@ -2119,6 +2138,37 @@ function effortsOf(d, site, id) { return EFFORT_ORDER.filter((e) => set.has(e)) } +// 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 +// the config's reasoning.defaultEffort, else reasoning.effort, and sends it +// as reasoning_effort unless thinking was turned off. A request with no +// reasoning_effort is not thinking on WorkBuddy's side: measured 2026-10-28 +// on www.workbuddy.ai, deepseek-v4.1-flash (defaultEffort "high") answered +// with 0 reasoning tokens without one, and thought at low and high +// (troilus1011 on X, OpenCode's default variant). A default the model's +// levels don't hold is left out, as the CLI clamps it to one they do. +function defaultEffortOf(d, efforts) { + const own = d.reasoning?.defaultEffort ?? d.reasoning?.effort + return typeof own === "string" && efforts.includes(own) ? own : undefined +} + +// withDefaultEffort gives a chat that names no effort the model's default +// (defaultEffortOf), as WorkBuddy's client sends it; true when it did. An +// effort the client named, "none" too, goes as it came. +function withDefaultEffort(chat, list) { + if (!chat || typeof chat !== "object" || namesEffort(chat)) return false + const m = list?.find((x) => x.id === chat.model) + if (!m?.effort) return false + chat.reasoning_effort = m.effort + return true +} + +// namesEffort is whether a chat names its effort itself, in either spelling +function namesEffort(chat) { + return chat.reasoning_effort !== undefined || (!!chat.reasoning && typeof chat.reasoning === "object" && chat.reasoning.effort !== undefined) +} + async function liveModels(site, a) { const headers = new Headers() sign(site, a, headers) @@ -2145,6 +2195,8 @@ async function liveModels(site, a) { if (es.length) { const canOff = d.reasoning?.canDisableThinking m.efforts = [...(!d.onlyReasoning && (canOff == null || canOff) ? ["none"] : []), ...es] + const def = defaultEffortOf(d, es) + if (def) m.effort = def } } out.push(m) @@ -2238,6 +2290,24 @@ function makePlugin(site) { if (lists.size > 64) lists.delete(lists.keys().next().value) return list } + // effortList is the list a chat's default effort is read from + // (withDefaultEffort): listed's, or null when there is none to read — a + // key WorkBuddy's CLI reads no config with (as models does), or a read + // that failed within PRICE_TTL, so a config that can't be read costs a + // chat one try a minute, not one each + const unlisted = new Map() + const effortList = async (a) => { + if (a.source === "key" && !remoteConfig(a.key)) return null + const k = listKey(a) + if (Date.now() - (unlisted.get(k) ?? 0) < PRICE_TTL) return null + try { + return await listed(a) + } catch { + unlisted.set(k, Date.now()) + if (unlisted.size > 64) unlisted.delete(unlisted.keys().next().value) + return null + } + } const freeOnly = () => magpie?.option?.(site.id, FREE_ONLY) === true // onlyFree is a list with the switch on: its free models, or a failure // when there are none to tell (magpie then keeps the list it had) @@ -2369,10 +2439,20 @@ function makePlugin(site) { let changed = p.changed body = p.body if (!native) names = p.names + // 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 chatHeaders(site, headers) 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)) + 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) + 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)) + } // a 401 is answered once, on whichever try meets it: by a // sign-in with another access token (reissued), the request // sent once more with it, never again after that; else, or @@ -2653,4 +2733,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, prepared, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } +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 } diff --git a/packages/workbuddy/native.test.mjs b/packages/workbuddy/native.test.mjs index 2fb0966..801db4e 100644 --- a/packages/workbuddy/native.test.mjs +++ b/packages/workbuddy/native.test.mjs @@ -15,6 +15,7 @@ import { afterAll, afterEach, beforeAll, expect, test } from "bun:test" import { realpathSync } from "node:fs" import { homedir, tmpdir } from "node:os" +import { unz } from "./testdata/unz.mjs" let WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal beforeAll(async () => { @@ -246,7 +247,7 @@ function serve({ good = ["old"] } = {}) { globalThis.fetch = async (url, init) => { const u = new URL(String(url instanceof Request ? url.url : url)) const headers = new Headers(init?.headers) - calls.push({ url: u.href, path: u.pathname, headers, body: init?.body }) + calls.push({ url: u.href, path: u.pathname, headers, body: unz(init?.body) }) if (u.pathname === REFRESH) return ok(RENEWED) const token = (headers.get("authorization") ?? "").replace(/^Bearer /, "") return good.includes(token) ? new Response(SSE, { headers: { "content-type": "text/event-stream" } }) : refusedToken() @@ -355,7 +356,7 @@ test("a chat request still goes through the chat route's rewrites", async () => const opts = await hooks.auth.loader(async () => signedIn()) const body = JSON.stringify({ model: "glm-5.3", max_completion_tokens: 4096, stream: true, messages: [{ role: "user", content: "hi" }] }) await opts.fetch("https://copilot.tencent.com/v2/chat/completions", { method: "POST", body }) - const sent = JSON.parse(calls[0].body) + const sent = JSON.parse(calls.find((c) => c.path === "/v2/chat/completions").body) expect(sent.max_tokens).toBe(4096) expect(sent.max_completion_tokens).toBeUndefined() expect(sent.messages[0].role).toBe("system") @@ -446,7 +447,7 @@ test("a signature WorkBuddy didn't make is refused once, then the request goes w const u = new URL(String(url)) if (u.pathname.endsWith("/token/refresh")) return ok(RENEWED) n++ - seen.push(JSON.parse(init.body)) + seen.push(JSON.parse(unz(init.body))) // the first try is refused, the retry (without thinking) answers return n === 1 ? new Response(REFUSAL, { status: 500 }) : new Response(SSE, { headers: { "content-type": "text/event-stream" } }) } diff --git a/packages/workbuddy/oneparse.test.mjs b/packages/workbuddy/oneparse.test.mjs index 4e4c167..e9eae9d 100644 --- a/packages/workbuddy/oneparse.test.mjs +++ b/packages/workbuddy/oneparse.test.mjs @@ -4,6 +4,7 @@ // one by one made of it. import { expect, test } from "bun:test" import { WorkBuddyAuthPlugin, _internal } from "./index.mjs" +import { unz } from "./testdata/unz.mjs" const { prepared, withSystem, fitted, normalizeToolChoice, withoutUnsigned } = _internal @@ -87,7 +88,7 @@ test("the loader parses a long chat once", async () => { return realParse(s, ...a) } globalThis.fetch = async (_url, init) => { - out = init.body + out = unz(init.body) return new Response('data: {"choices":[{"delta":{"content":"OK"}}]}\n\ndata: [DONE]\n\n', { headers: { "content-type": "text/event-stream" } }) } try { diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 7f33750..3cc9964 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.42", + "version": "0.1.43", "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/reasoning.test.mjs b/packages/workbuddy/reasoning.test.mjs index 2627924..4f884cc 100644 --- a/packages/workbuddy/reasoning.test.mjs +++ b/packages/workbuddy/reasoning.test.mjs @@ -4,6 +4,7 @@ // the one Grok Build 1.0.67 sends after a tool call. import { expect, test } from "bun:test" import { WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" +import { unz } from "./testdata/unz.mjs" const { asReasoning } = _internal @@ -20,7 +21,7 @@ async function upstream(messages) { const realFetch = globalThis.fetch const sent = [] globalThis.fetch = async (url, init) => { - if (String(url).includes("/chat/completions")) sent.push(JSON.parse(init.body)) + if (String(url).includes("/chat/completions")) sent.push(JSON.parse(unz(init.body))) return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) } try { diff --git a/packages/workbuddy/request.test.mjs b/packages/workbuddy/request.test.mjs index 07d3d56..e6a1e41 100644 --- a/packages/workbuddy/request.test.mjs +++ b/packages/workbuddy/request.test.mjs @@ -2,6 +2,7 @@ // request shape than pi-ai's default Chat Completions payload. import { expect, test } from "bun:test" import { WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" +import { unz } from "./testdata/unz.mjs" const { withSystem, normalizeToolChoice, fitted } = _internal @@ -58,7 +59,7 @@ test("loader sends the normalized body to WorkBuddy", async () => { const realFetch = globalThis.fetch let sent globalThis.fetch = async (_url, init) => { - sent = JSON.parse(init.body) + sent = JSON.parse(unz(init.body)) return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) } try { diff --git a/packages/workbuddy/reset.test.mjs b/packages/workbuddy/reset.test.mjs index 7f330b7..c5bb9d9 100644 --- a/packages/workbuddy/reset.test.mjs +++ b/packages/workbuddy/reset.test.mjs @@ -5,6 +5,7 @@ // socket, so Bun's fetch meets the same reset it met on www.workbuddy.ai. import { afterAll, beforeAll, expect, test } from "bun:test" import net from "node:net" +import { randomBytes } from "node:crypto" import { WorkBuddyAIAuthPlugin, WorkBuddyAuthPlugin, _internal } from "./index.mjs" const { EDGE_READS } = _internal @@ -56,7 +57,8 @@ beforeAll(async () => { afterAll(() => server.close()) -// chat is a loader fetch of a body of about size bytes, signed in as token, +// chat is a loader fetch of a body of about size bytes on the wire, signed +// in as token, // with the site (WorkBuddy AI's, else the China build's) served by the fake async function chat(token, size, plugin = WorkBuddyAIAuthPlugin, site = "https://www.workbuddy.ai") { const realFetch = globalThis.fetch @@ -69,7 +71,9 @@ async function chat(token, size, plugin = WorkBuddyAIAuthPlugin, site = "https:/ stream: true, messages: [ { role: "system", content: "You are helpful." }, - { role: "user", content: "x".repeat(size) }, + // a chat goes gzipped, so its text is random: base64 of random bytes + // gzips to about 3/4 of its length, and size is what goes out + { role: "user", content: randomBytes(Math.ceil(size * 1.4)).toString("base64").slice(0, Math.ceil(size * 1.4)) }, ], }) return await loader.fetch(site + "/v2/chat/completions", { method: "POST", body }) diff --git a/packages/workbuddy/systemasuser.test.mjs b/packages/workbuddy/systemasuser.test.mjs index 67a986f..e428f70 100644 --- a/packages/workbuddy/systemasuser.test.mjs +++ b/packages/workbuddy/systemasuser.test.mjs @@ -7,6 +7,7 @@ // Claude Code's identity line. import { expect, test } from "bun:test" import { WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" +import { unz } from "./testdata/unz.mjs" const { systemAsUser, REFUSED_HINT, DEFAULT_SYSTEM } = _internal @@ -36,7 +37,7 @@ async function withService(Plugin, fn, answer) { const realFetch = globalThis.fetch const sent = [] globalThis.fetch = async (_url, init) => { - const b = JSON.parse(init.body) + const b = JSON.parse(unz(init.body)) sent.push(b) const said = answer?.(b) if (said) return said diff --git a/packages/workbuddy/testdata/unz.mjs b/packages/workbuddy/testdata/unz.mjs new file mode 100644 index 0000000..39b431e --- /dev/null +++ b/packages/workbuddy/testdata/unz.mjs @@ -0,0 +1,10 @@ +// unz is a request body as the text it carries: a chat goes gzipped (see +// gzipped in index.mjs), anything else as it was sent +import { gunzipSync } from "node:zlib" + +export function unz(b) { + if (b == null || typeof b === "string") return b + const u = b instanceof ArrayBuffer ? new Uint8Array(b) : new Uint8Array(b.buffer, b.byteOffset, b.byteLength) + if (u[0] === 0x1f && u[1] === 0x8b) return new TextDecoder().decode(gunzipSync(u)) + return b +} diff --git a/packages/workbuddy/unauthorized.test.mjs b/packages/workbuddy/unauthorized.test.mjs index 7a3ef8c..3456107 100644 --- a/packages/workbuddy/unauthorized.test.mjs +++ b/packages/workbuddy/unauthorized.test.mjs @@ -11,6 +11,7 @@ import { test, expect, afterAll, beforeAll, afterEach } from "bun:test" import { mkdirSync, writeFileSync, rmSync, realpathSync } from "node:fs" import { homedir, tmpdir } from "node:os" import { join } from "node:path" +import { unz } from "./testdata/unz.mjs" let WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal beforeAll(async () => { @@ -51,9 +52,12 @@ function serve({ good = ["new"], refresh = () => ok(RENEWED), chat, meter } = {} globalThis.fetch = async (url, init) => { const u = new URL(String(url instanceof Request ? url.url : url)) const headers = new Headers(init?.headers) - calls.push({ path: u.pathname, headers, body: init?.body }) + calls.push({ path: u.pathname, headers, body: unz(init?.body) }) const token = (headers.get("authorization") ?? "").replace(/^Bearer /, "") if (u.pathname === REFRESH) return refresh(headers) + // the model list a chat that names no effort reads its default from + // (withDefaultEffort): no model listed, so no effort added + if (u.pathname === "/v3/config") return ok({ models: [] }) if (u.pathname === SUMMARY) return meter ? meter(token) : good.includes(token) ? ok({ IsPaidUser: false, Packages: [] }) : refusedToken() if (chat) return chat(token) return good.includes(token) ? new Response(STREAM, { headers: { "content-type": "text/event-stream" } }) : refusedToken()