From 18268848d313220a437e46c9eca3acfdfa974798 Mon Sep 17 00:00:00 2001 From: yetone Date: Tue, 27 Oct 2026 17:14:51 +0800 Subject: [PATCH] workbuddy 0.1.38: a "Free models only" switch that never spends credits (#430) kongbai01203 asked for a hard stop on WorkBuddy credits: use only the free models, and never let a paid one through by mistake. Each site (workbuddy, workbuddy-ai) now declares a magpie plugin option, free_only, "Free models only", off by default. With it on: - models() lists only the models priced free now (priceOf: a model free only at night, or one with no price, is paid). A list that can't be read, or an API key WorkBuddy lists no prices for, is a failure, not the built-in list. - fetch reads the model from the body and, unless /v3/config lists it as free, answers 404 model_not_found itself and sends nothing. The message has no quota words, so magpie's gateway rests that model only and falls through, not the account. A price list that can't be read answers 503 and sends nothing. The list is kept a minute per account for requests. Off, nothing changes: the config isn't read on a request. Run: - HOME=$(mktemp -d) bun test packages/workbuddy: 179 pass (freeonly.test.mjs new, both sites); bun scripts/check.mjs: ok. - Real accounts, sandbox magpie (HOME under the scratchpad, magpie wb-free-only branch, this package added by path): with the switch on for workbuddy-ai the list went 26 -> 2 (hy3, deepseek-v4.1-flash) within 2s, workbuddy (own switch) stayed at 19; gpt-5.4 got the 404 with nothing sent, hy3 and deepseek-v4.1-flash answered. Off: 26 again, gpt-6-luna and gpt-5.4 answered (no rest left on gpt-5.4). Broken by hand: without the fetch check 4 tests fail; with onlyFree returning every model 2 fail. Not tried: the GUI switch itself (set through /api/settings/plugin-option); the workbuddy (China) site's switch with a real request; Responses or Anthropic bodies against the real API (the model is read the same way). --- packages/workbuddy/README.md | 16 ++++ packages/workbuddy/freeonly.test.mjs | 129 +++++++++++++++++++++++++++ packages/workbuddy/index.mjs | 107 +++++++++++++++++++--- packages/workbuddy/package.json | 2 +- 4 files changed, 241 insertions(+), 13 deletions(-) create mode 100644 packages/workbuddy/freeonly.test.mjs diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index b3059db..9fad81d 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -228,6 +228,22 @@ some hours of the day (Hy4 preview, free 23:00–8:00) is given as its full price, never as free: magpie keeps the list until it asks again, so a list asked for at night would say "free" all day (#121). +### Free models only + +Each site (WorkBuddy, WorkBuddy AI) has a "Free models only" switch in its +provider settings in magpie, off by default (#430). When it is on: + +- the list holds only the models the site serves at no cost now. A model free + only at night, or one with no price, counts as paid; +- a request for any other model is answered by the plugin with a 404 + `model_not_found` and never sent, so no credits are spent. magpie rests + only that model and tries the next provider; +- if the price list can't be read, nothing is sent (503), since whether the + model is free is unknown. An API key WorkBuddy lists no prices for lists + no models. + +The price list is read again at most once a minute for requests. + ## Credits in magpie magpie's usage card shows the account's credits from the resource summary. diff --git a/packages/workbuddy/freeonly.test.mjs b/packages/workbuddy/freeonly.test.mjs new file mode 100644 index 0000000..e97f6ec --- /dev/null +++ b/packages/workbuddy/freeonly.test.mjs @@ -0,0 +1,129 @@ +// plugins#430 (kongbai01203): "Free models only" is a hard stop on credits. +// With it on, the list holds only the models WorkBuddy serves at no cost, +// and a request for any other is answered here and never reaches WorkBuddy; +// so is one whose price can't be read. Every fetch here is a fake; nothing +// reaches the network. +import { afterEach, expect, test } from "bun:test" +import { WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => (globalThis.fetch = real)) + +const KEY = "ck_test0000000000abcdefgh" +const CONFIG = { + code: 0, + data: { + agents: [{ name: "cli", models: ["hy3", "glm-5.3", "hy4-preview", "auto", "claude-sonnet-5"] }], + models: [ + { id: "hy3", credits: "x0.00" }, + { id: "glm-5.3", credits: "x0.79" }, + // free only at night: paid here (#121) + { id: "hy4-preview", credits: "x0.29" }, + // no price said: not free + { id: "auto" }, + { id: "claude-sonnet-5", credits: "x1.00" }, + ], + modelPromotions: [ + { discount: { discountedCredits: "0.00x", factor: 0 }, enabled: true, kind: "discount", modelIds: ["hy4-preview"], schedule: { daily: [{ start: "23:00", end: "23:59" }] } }, + ], + }, +} + +// serve answers /v3/config with config (or fails it) and a chat with OK, +// and keeps every URL asked +function serve(config = () => Response.json(CONFIG)) { + const sent = [] + globalThis.fetch = async (url, init) => { + const u = String(url) + sent.push({ url: u, body: init?.body }) + if (u.endsWith("/v3/config")) return config() + return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + } + return sent +} + +const chat = (opts, url, model) => + opts.fetch(url, { method: "POST", body: JSON.stringify({ model, stream: true, messages: [{ role: "user", content: "hi" }] }) }) + +const magpieWith = (on) => ({ option: (provider, key) => on[provider]?.[key] === true }) + +for (const [plugin, site, url] of [ + [WorkBuddyAuthPlugin, "workbuddy", "https://copilot.tencent.com/v2/chat/completions"], + [WorkBuddyAIAuthPlugin, "workbuddy-ai", "https://www.workbuddy.ai/v2/chat/completions"], +]) { + test(`${site}: declares the switch, off by default`, async () => { + const h = await plugin({ client: {} }) + const o = h.auth.options.find((x) => x.key === _internal.FREE_ONLY) + expect(o.label).toBe("Free models only") + expect(o.default).toBeUndefined() + }) + + test(`${site}: on, the list holds only the free models; off, all of them`, async () => { + serve() + const auth = { type: "api", key: KEY } + const on = await plugin({ client: {}, magpie: magpieWith({ [site]: { free_only: true } }) }) + const cfg = { provider: {} } + await on.config(cfg) + expect(Object.keys(await on.provider.models(cfg.provider[site], { auth }))).toEqual(["hy3"]) + const off = await plugin({ client: {}, magpie: magpieWith({}) }) + expect(Object.keys(await off.provider.models(cfg.provider[site], { auth }))).toEqual(["hy3", "glm-5.3", "hy4-preview", "auto", "claude-sonnet-5"]) + // the other site's switch is its own + const other = site === "workbuddy" ? "workbuddy-ai" : "workbuddy" + const theirs = await plugin({ client: {}, magpie: magpieWith({ [other]: { free_only: true } }) }) + expect(Object.keys(await theirs.provider.models(cfg.provider[site], { auth }))).toHaveLength(5) + }) + + test(`${site}: on, a list that can't be read is a failure, not the built-in list`, async () => { + serve(() => new Response("down", { status: 502 })) + const h = await plugin({ client: {}, magpie: magpieWith({ [site]: { free_only: true } }) }) + const cfg = { provider: {} } + await h.config(cfg) + await expect(h.provider.models(cfg.provider[site], { auth: { type: "api", key: KEY } })).rejects.toThrow() + // a key WorkBuddy lists no prices for, too + await expect(h.provider.models(cfg.provider[site], { auth: { type: "api", key: "sk-other" } })).rejects.toThrow(/Free models only/) + // off, the built-in list as before + const off = await plugin({ client: {} }) + expect(Object.keys(await off.provider.models(cfg.provider[site], { auth: { type: "api", key: KEY } })).length).toBeGreaterThan(0) + }) + + test(`${site}: on, a paid or unpriced model's request never reaches WorkBuddy`, async () => { + const sent = serve() + const h = await plugin({ client: {}, magpie: magpieWith({ [site]: { free_only: true } }) }) + const opts = await h.auth.loader(async () => ({ type: "api", key: KEY })) + for (const model of ["glm-5.3", "hy4-preview", "auto", "claude-sonnet-5", "not-listed", undefined]) { + const res = await chat(opts, url, model) + expect(res.status).toBe(404) + const e = (await res.json()).error + expect(e.code).toBe("model_not_found") + expect(e.message).toContain("Free models only") + // magpie's gateway rests the model, not the account, for these words + expect(e.message).toMatch(/model.{0,80}not available/i) + expect(e.message).not.toMatch(/quota|insufficient|balance|credit|billing|exceeded|limit/i) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + } + expect(sent.filter((s) => !s.url.endsWith("/v3/config"))).toHaveLength(0) + // the free one goes, and the list was read once for all of them + const res = await chat(opts, url, "hy3") + expect(res.status).toBe(200) + expect(sent.filter((s) => s.url === url)).toHaveLength(1) + expect(sent.filter((s) => s.url.endsWith("/v3/config"))).toHaveLength(1) + }) + + test(`${site}: on, a price that can't be read sends nothing`, async () => { + const sent = serve(() => new Response("down", { status: 502 })) + const h = await plugin({ client: {}, magpie: magpieWith({ [site]: { free_only: true } }) }) + const opts = await h.auth.loader(async () => ({ type: "api", key: KEY })) + const res = await chat(opts, url, "hy3") + expect(res.status).toBe(503) + expect((await res.json()).error.message).toContain("is unknown") + 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 () => { + 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) + expect(sent.map((s) => s.url)).toEqual([url]) + }) +} diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index db8a637..1d92450 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -592,6 +592,12 @@ function withoutSignedThinking(body) { // 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. +// bodyString is a body given as bytes, as text; anything else is null. +function bodyString(body) { + if (body instanceof ArrayBuffer || ArrayBuffer.isView(body)) return new TextDecoder().decode(body) + return null +} + function chatOf(body) { if (typeof body !== "string") return null try { @@ -2027,6 +2033,29 @@ function replyAfterTools(body) { return JSON.stringify(b) } +// FREE_ONLY is the switch that keeps an account off credits (#430): its +// list holds only the models WorkBuddy serves at no cost (priceOf's free), +// and a request for any other is answered here, never sent. A price that +// can't be read is not free, and a list that can't be read sends nothing. +const FREE_ONLY = "free_only" +// PRICE_TTL is how long a list read for that check is used before it is +// read again: a promotion that ends stops counting as free within it. +const PRICE_TTL = 60_000 + +// notFree is the answer to a request the switch keeps from WorkBuddy. Its +// words say the model, not the account, is what is turned away, so magpie +// rests that model alone and asks another provider of it; they name no +// quota or credit, which would rest the whole account as out of credit. +function notFree(site, model, why) { + const msg = why + ? `${site.name}'s model list couldn't be read (${why}), so whether model ${model || "(none)"} is free is unknown; with "Free models only" on it isn't sent` + : `model ${model || "(none)"} is not available while "Free models only" is on: ${site.name} charges for it. Turn the switch off in ${site.name}'s provider settings to use it` + return new Response(JSON.stringify({ error: { message: msg, type: "invalid_request_error", code: why ? "free_only_unknown" : "model_not_found" } }), { + status: why ? 503 : 404, + headers: { "content-type": "application/json", "X-Magpie-Sign-In": "kept" }, + }) +} + function makePlugin(site) { // the models of this site that refused tool results then the user's // message, for this run: their next chats go with replyAfterTools at once @@ -2034,7 +2063,30 @@ function makePlugin(site) { // the system prompts this run WorkBuddy refused as an unapproved channel: // their next chats go with systemAsUser at once, not refused first const refusedSystems = new Set() - return async ({ client }) => ({ + return async ({ client, magpie }) => { + // each account's list as last read, for FREE_ONLY: {at, list} + const lists = new Map() + const listKey = (a) => `${a.uid ?? ""}|${a.enterpriseId ?? ""}|${a.source === "key" ? a.key : ""}` + // listed is the account's live list, read again past PRICE_TTL + const listed = async (a, fresh = false) => { + const k = listKey(a) + const was = lists.get(k) + if (!fresh && was && Date.now() - was.at < PRICE_TTL) return was.list + const list = await liveModels(site, a) + lists.set(k, { at: Date.now(), list }) + if (lists.size > 64) lists.delete(lists.keys().next().value) + return list + } + 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) + const onlyFree = (ms) => { + if (!freeOnly()) return ms + const free = ms.filter((m) => m.free) + if (!free.length) throw new Error(`${site.name} lists no free model, and "Free models only" is on`) + return free + } + return { config: async (config) => { config.provider ??= {} config.provider[site.id] ??= {} @@ -2059,23 +2111,34 @@ function makePlugin(site) { if (auth?.type === "api") { // asked as WorkBuddy's own CLI asks with a key (remoteConfig) const a = keyAccount(auth) - if (!a || !remoteConfig(a.key)) return provider.models - try { - const ms = await liveModels(site, a) - return ms.length ? Object.fromEntries(ms.map((m) => [m.id, modelOf(site, provider, m)])) : provider.models - } catch { + if (!a || !remoteConfig(a.key)) { + if (freeOnly()) throw new Error(`${site.name} lists no prices for this key, and "Free models only" is on`) return provider.models } + let ms + try { + ms = await listed(a, true) + } catch (e) { + if (freeOnly()) throw e + return provider.models + } + if (!ms.length && !freeOnly()) return provider.models + return Object.fromEntries(onlyFree(ms).map((m) => [m.id, modelOf(site, provider, m)])) } if (auth?.type !== "oauth" || !(auth.access || auth.source)) return provider.models + let ms try { const a = await current(site, client, auth) - const ms = await liveModels(site, a) - if (!ms.length) return provider.models - return Object.fromEntries(ms.map((m) => [m.id, modelOf(site, provider, m)])) - } catch { + ms = await listed(a, true) + } catch (e) { + // with the switch on, a list without prices would offer models + // that cost credits: the failure goes up, and magpie keeps the + // list it had + if (freeOnly()) throw e return provider.models } + if (!ms.length && !freeOnly()) return provider.models + return Object.fromEntries(onlyFree(ms).map((m) => [m.id, modelOf(site, provider, m)])) }, }, auth: { @@ -2087,6 +2150,13 @@ function makePlugin(site) { // and is renewed as before. refreshLead: LEAD_MS, refresh: (auth) => refreshed(site, auth), + options: [ + { + key: FREE_ONLY, + label: "Free models only", + description: `Lists only the models ${site.name} serves at no cost, and turns away a request for any other here instead of sending it, so no credits are spent. A model free only at night counts as paid.`, + }, + ], async loader(getAuth) { const auth = await getAuth() if (auth?.type !== "oauth" && auth?.type !== "api") return {} @@ -2110,6 +2180,18 @@ 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 @@ -2304,7 +2386,8 @@ function makePlugin(site) { }, ], }, - }) + } + } } // REFUSED_HINT is what the user can do about WorkBuddy's "Illegal API @@ -2409,4 +2492,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { 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, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } +export const _internal = { FREE_ONLY, PRICE_TTL, keyAccount, remoteConfig, cycleOf, typeUnions, systemAsUser, systemKey, DEFAULT_SYSTEM, EDGE_READS, fitShape, replyAfterTools, AFTER_TOOLS_REFUSED, enterpriseUsageOf, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, normalizeToolChoice, fitTools, fitted, renamed, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, answeredBefore, nativeOf, modelOf, configModels, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 684f2e1..3b60c58 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.37", + "version": "0.1.38", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs",