diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index 44d3100..0c610c6 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -239,6 +239,17 @@ serves; a model that refused it once gets it that way from then on, until the plugin restarts. A chat ending with the assistant's message (a prefill) is refused as before. +WorkBuddy's safety filter can refuse a reply it has begun: +`deepseek-v4.1-flash` reasoned, said "Sorry, I can't respond to this +question.", and ended with `finish_reason: "content_filter"` and no output +tokens, all under a 200 (#540). Since 0.2.4 that line is taken out of a +streamed chat ending `content_filter`, so the reply says nothing before the +filter's stop: magpie hands such a refusal to the group's next member +instead of passing it to the agent as an answer. Only text that is still +the filter's line is held, so any other reply's words go as they come; the +same words ending `stop`, or the filter cutting off a reply after other +words, go through as they came. + ## Models When you are signed in, the models are the ones WorkBuddy's product config diff --git a/packages/workbuddy/filtered.test.mjs b/packages/workbuddy/filtered.test.mjs new file mode 100644 index 0000000..7cbd750 --- /dev/null +++ b/packages/workbuddy/filtered.test.mjs @@ -0,0 +1,123 @@ +// WorkBuddy's safety filter refusing a reply it had begun (itspig, plugins +// #540): deepseek-v4.1-flash on copilot.tencent.com reasoned, said "Sorry, +// I can't respond to this question.", and ended finish_reason +// content_filter with 0 output tokens, all under a 200. The text is taken +// out, so the reply says nothing before content_filter: the refusal magpie +// asks the group's next member for. +import { expect, test } from "bun:test" +import { WorkBuddyAuthPlugin } from "./index.mjs" + +const said = "Sorry, I can't respond to this question." + +const chunk = (delta, finish = null, usage) => + `data: ${JSON.stringify({ id: "c1", object: "chat.completion.chunk", model: "deepseek-v4.1-flash", choices: [{ index: 0, delta, finish_reason: finish }], ...(usage ? { usage } : {}) })}\n\n` + +const zero = { prompt_tokens: 0, completion_tokens: 0, total_tokens: 0 } + +// pieces is a stream's bytes cut where the given cuts fall, as a server's +// writes may +function streamOf(text, cuts = 7) { + const b = new TextEncoder().encode(text) + return new ReadableStream({ + start(c) { + for (let i = 0; i < b.length; i += cuts) c.enqueue(b.slice(i, i + cuts)) + c.close() + }, + }) +} + +async function through(upstream, cuts) { + const realFetch = globalThis.fetch + globalThis.fetch = async (url) => { + if (String(url).includes("/chat/completions")) return new Response(streamOf(upstream, cuts), { headers: { "content-type": "text/event-stream" } }) + return new Response("{}", { headers: { "content-type": "application/json" } }) + } + try { + const hooks = await WorkBuddyAuthPlugin({ client: {} }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "access", uid: "uid", expires: Date.now() + 3600_000 })) + const res = await loader.fetch("https://copilot.tencent.com/v2/chat/completions", { + method: "POST", + body: JSON.stringify({ model: "deepseek-v4.1-flash", stream: true, reasoning_effort: "high", messages: [{ role: "user", content: "hi" }] }), + }) + expect(res.status).toBe(200) + return await res.text() + } finally { + globalThis.fetch = realFetch + } +} + +const contents = (out) => + out + .split("\n\n") + .filter((e) => e.startsWith("data: {")) + .map((e) => JSON.parse(e.slice(6)).choices?.[0]) + .filter(Boolean) + +for (const [name, text] of [ + ["in one delta", [chunk({ content: said })]], + ["a few words at a time", [chunk({ content: "Sorry" }), chunk({ content: ", I can't" }), chunk({ content: " respond to this question." })]], +]) { + for (const cuts of [7, 1 << 20]) { + test(`the filter's text before content_filter is taken out, ${name}, ${cuts > 7 ? "whole" : "cut"}`, async () => { + const upstream = + chunk({ role: "assistant", reasoning_content: "" }) + + chunk({ reasoning_content: "The user is asking" }) + + chunk({ reasoning_content: " about it." }) + + text.join("") + + chunk({}, "content_filter", zero) + + "data: [DONE]\n\n" + const out = await through(upstream, cuts) + expect(out).not.toContain("Sorry") + const cs = contents(out) + expect(cs.map((c) => c.delta.reasoning_content ?? "").join("")).toBe("The user is asking about it.") + expect(cs.some((c) => typeof c.delta.content === "string" && c.delta.content)).toBe(false) + expect(cs.at(-1).finish_reason).toBe("content_filter") + expect(out.endsWith("data: [DONE]\n\n")).toBe(true) + }) + } +} + +test("the filter's text in the chunk that ends content_filter is taken out", async () => { + const out = await through(chunk({ reasoning_content: "hm" }) + chunk({ content: said }, "content_filter", zero) + "data: [DONE]\n\n") + expect(out).not.toContain("Sorry") + expect(contents(out).at(-1).finish_reason).toBe("content_filter") +}) + +test("the same words as an answer that ends stop go through whole", async () => { + const upstream = chunk({ reasoning_content: "hm" }) + chunk({ content: "Sorry" }) + chunk({ content: ", I can't respond to this question." }) + chunk({}, "stop") + "data: [DONE]\n\n" + expect(await through(upstream)).toBe(upstream) +}) + +test("a reply that only begins like it goes through as it came", async () => { + const upstream = chunk({ content: "Sorry" }) + chunk({ content: ", I can't find that file." }) + chunk({}, "stop") + "data: [DONE]\n\n" + expect(await through(upstream)).toBe(upstream) +}) + +test("a reply cut off by content_filter after other words keeps them", async () => { + const upstream = chunk({ content: "Here is the plan: " }) + chunk({ content: said }) + chunk({}, "content_filter") + "data: [DONE]\n\n" + expect(await through(upstream)).toBe(upstream) +}) + +test("an answer's words are not held", async () => { + // the first chunk that isn't the filter's goes out before the stream ends + const enc = new TextEncoder() + let push + const body = new ReadableStream({ start: (c) => (push = c) }) + const realFetch = globalThis.fetch + globalThis.fetch = async (url) => + String(url).includes("/chat/completions") + ? new Response(body, { headers: { "content-type": "text/event-stream" } }) + : new Response("{}", { headers: { "content-type": "application/json" } }) + try { + const hooks = await WorkBuddyAuthPlugin({ client: {} }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "access", uid: "uid", expires: Date.now() + 3600_000 })) + const res = await loader.fetch("https://copilot.tencent.com/v2/chat/completions", { method: "POST", body: JSON.stringify({ model: "deepseek-v4.1-flash", stream: true, messages: [{ role: "user", content: "hi" }] }) }) + const rd = res.body.getReader() + push.enqueue(enc.encode(chunk({ content: "Hello" }))) + const { value } = await rd.read() + expect(new TextDecoder().decode(value)).toContain("Hello") + push.close() + } finally { + globalThis.fetch = realFetch + } +}) diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index b8b1664..65e8564 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -1599,6 +1599,106 @@ function renamed(res, names) { return new Response(body, { status: res.status, statusText: res.statusText, headers }) } +// FILTER_SAYS is the text WorkBuddy's safety filter puts in a reply it ends +// with finish_reason "content_filter": deepseek-v4.1-flash on +// copilot.tencent.com reasoned, said this, and ended content_filter with +// no output tokens counted (itspig, plugins #540). +const FILTER_SAYS = ["Sorry, I can't respond to this question."] + +// filterSaid tells whether text said so far may still be FILTER_SAYS. +const filterSaid = (text) => { + const t = text.replace(/’/g, "'").trimStart() + return t !== "" && FILTER_SAYS.some((s) => s.startsWith(t)) +} + +// unsaid is a streamed chat whose reply WorkBuddy's filter refused with its +// text (FILTER_SAYS) and finish_reason content_filter, with the text taken +// out: a reply that says nothing before content_filter is the refusal magpie +// asks the group's next member for, where a 200 that said something is an +// answer the agent fails on ("The model refused to complete the request", +// plugins #540). Only text that is still the filter's is held, so any other +// reply's first words go as they come, and one that only begins like it is +// let through at its first word that isn't, or at its end. +function unsaid(res) { + if (!res.body || !/event-stream/i.test(res.headers.get("content-type") ?? "")) return res + const headers = new Headers(res.headers) + headers.delete("content-length") + headers.delete("content-encoding") + const dec = new TextDecoder() + const enc = new TextEncoder() + let rest = "" + let open = true // the reply may still be the filter's + let said = "" + let held = [] // events held while it may be + const chunkOf = (ev) => { + const m = /^data:\s?(.*)$/m.exec(ev) + if (!m || m[1] === "[DONE]") return null + try { + const v = JSON.parse(m[1]) + return v && typeof v === "object" ? v : null + } catch { + return null + } + } + // without is ev with the filter's text taken out, or "" when nothing + // else is in it + const without = (ev) => { + const v = chunkOf(ev) + const c = v?.choices?.[0] + if (!c?.delta || typeof c.delta.content !== "string") return ev + delete c.delta.content + const left = Object.keys(c.delta).filter((k) => k !== "role") + if (!left.length && c.finish_reason == null && v.usage == null) return "" + return `data: ${JSON.stringify(v)}` + } + const event = (ev) => { + if (!open) return [ev] + const c = chunkOf(ev)?.choices?.[0] + const text = typeof c?.delta?.content === "string" ? c.delta.content : "" + const finish = c?.finish_reason + if (c?.delta?.tool_calls || (text && !filterSaid(said + text))) { + open = false + const out = [...held, ev] + held = [] + return out + } + said += text + if (finish === "content_filter" && said) { + open = false + const out = [...held, ev].map(without).filter(Boolean) + held = [] + return out + } + if (finish) { + open = false + const out = [...held, ev] + held = [] + return out + } + if (!said) return [ev] // reasoning, the role, before any text + held.push(ev) + return [] + } + const body = res.body.pipeThrough( + new TransformStream({ + transform(chunk, ctl) { + rest = (rest + dec.decode(chunk, { stream: true })).replace(/\r\n/g, "\n") + const evs = rest.split("\n\n") + rest = evs.pop() + const out = evs.flatMap(event) + if (out.length) ctl.enqueue(enc.encode(out.map((e) => e + "\n\n").join(""))) + }, + flush(ctl) { + rest += dec.decode() + const out = held.map((e) => e + "\n\n").join("") + rest + held = [] + if (out) ctl.enqueue(enc.encode(out)) + }, + }), + ) + return new Response(body, { status: res.status, statusText: res.statusText, headers }) +} + // ---- signing in ------------------------------------------------------------- // poll asks path until WorkBuddy answers with data, retrying the codes @@ -3439,7 +3539,7 @@ function makePlugin(site) { } if (ours.has(res)) return res // renewed here: a mark the account had comes off - return res.status >= 400 ? explained(res) : kept(native ? res : await renamed(res, names), renewed ? "renewed" : "kept") + return res.status >= 400 ? explained(res) : kept(native ? res : unsaid(await renamed(res, names)), renewed ? "renewed" : "kept") }, } }, @@ -3652,4 +3752,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -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, accountName, 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, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, 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, accountName, notDesktop, textOnly, runsOutOf, packagesOf, endOf, enterpriseHeaders, enterpriseOf, liveModels, browserSignIn, withSystem, asReasoning, normalizeToolChoice, fitTools, fitted, renamed, unsaid, FILTER_SAYS, unflagged, usageOf, desktopHeld, explained, REFUSED_HINT, RESTRICTED_HINT, EXHAUSTED_HINT, REFUSED_DOC, commaPaused, commaPausedOn, opened, freeCredits, creditsOf, priceOf, fresh, SITES, renewing, renewed, SESSION, attend, scopeOf, turnKey, conversationKey, signatureOf, isMessages, withoutUnsigned, withoutSignedThinking, prepared, answeredBefore, nativeOf, modelOf, configModels, freeWindowOf, tokensShort, freeWindowRows, freeWindowLedger, readLedgerTail, pinned, rowTime, rowAccount, ofAccount, windowOffset, windowReset, FREE_WINDOW_MODELS, FREE_WINDOW_SPAN, FREE_WINDOW_GAP, FREE_WINDOW_LEAD, checkinOf, API_MESSAGES: NPM_MESSAGES, API_CHAT: NPM } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 87e3793..a1424d6 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.2.3", + "version": "0.2.4", "description": "OpenCode provider plugins for WorkBuddy's plans: WorkBuddy (CodeBuddy, copilot.tencent.com) and WorkBuddy AI (www.workbuddy.ai)", "type": "module", "main": "./index.mjs",