From af360a529df5295e9c31fefe81e3158802ca0f3a Mon Sep 17 00:00:00 2001 From: yetone Date: Wed, 21 Oct 2026 18:28:06 +0800 Subject: [PATCH] workbuddy 0.1.29: a system prompt refused as an unapproved channel goes again as the user's instructions Wing on Discord (10-21) got 400 11128 "Illegal API invocation from an unapproved channel" from an agent we couldn't name, and so did others (miaopasi; itsuki with dsh). FLAGGED rewords the lines we've met, so any agent with a line not met yet is refused. What WorkBuddy checks (real accounts on both builds, 2026-10-21, CN glm-5.3 / deepseek-v4.1-flash, AI gpt-5.5 / glm-5.3): - Only system and assistant messages are checked. Each refused line (Claude Code's identity line, "Main branch (you will usually use this for PRs): main", DeepSeek Harness's opening) was served as a user message, as a user message's parts and as a tool result, and refused again in the system message or an assistant message. - An identity line is refused only at the start of a message (a leading space or "Hi.\n" passes; the line at the end of omp's 10.5K prompt passes). It is matched case-insensitively. "Main branch ..." is refused anywhere. Whitespace must match exactly: a double space or a ZWSP passes. - With no system message, the AI build answers 11128 "first message is not system prompt". The change: on that refusal, the chat is sent once more with its system prompt moved into the first user message, inside tags, and "You are a helpful assistant." as the system message. A later system message becomes a user message where it stands. The refused system prompt is remembered (up to 256), so that agent's next chats go moved without a refusal first. FLAGGED stays, so lines we know still go as system. A refusal that stands after the move still ends in REFUSED_HINT with X-Magpie-Sign-In: kept, so no account is rested. The added text names no one. Run, with FLAGGED emptied in a copy so that only the move could pass: - probe, the plugin's fetch with real accounts: the CC, Main-branch and DeepSeek Harness lines each went 400 then 200 on CN glm-5.3, CN deepseek-v4.1-flash, AI gpt-5.5 and AI glm-5.3. The second chat with the same prompt was 200 at once. - OpenCode 2.0.25 on workbuddy-ai glm-5.3 with an agent prompt opening with Claude Code's line. Bridge log: upstream 400 sys: "You are Claude Code, Anthropic's offici upstream 200 sys: "You are a helpful assistant." next: user ... It added power() to calc.py with tool calls. - omp 18.9.1 on workbuddy deepseek-v4.1-flash with --system-prompt opening "You are an AI agent powered by DeepSeek Harness" and holding the Main-branch line: one 400, then four 200s moved. It added divide() with a zero guard and ran it. - HOME=$(mktemp -d) bun test in packages/workbuddy: 111 pass, 0 fail. bun scripts/check.mjs: ok. - systemasuser.test.mjs uses WorkBuddy's literal 11128 body. Run against the 0.1.28 index.mjs, 7 of its 9 tests fail; the other two are guards that nothing is sent again. Not tried: Wing's own agent (unknown; "omp" by the name is a Discord server tag), dsh on the CN build through the move, and how well each model follows instructions from the user turn over a long session. They followed them in the runs above. --- packages/workbuddy/README.md | 14 +- packages/workbuddy/index.mjs | 84 ++++++++++- packages/workbuddy/package.json | 2 +- packages/workbuddy/systemasuser.test.mjs | 169 +++++++++++++++++++++++ 4 files changed, 258 insertions(+), 11 deletions(-) create mode 100644 packages/workbuddy/systemasuser.test.mjs diff --git a/packages/workbuddy/README.md b/packages/workbuddy/README.md index d1a2a09..e1071a5 100644 --- a/packages/workbuddy/README.md +++ b/packages/workbuddy/README.md @@ -86,9 +86,17 @@ default one, as the app does. WorkBuddy refuses some agents' identity lines as an "unapproved channel" (11128), so those lines are reworded before a chat goes out. Since 0.1.27 (#279) that includes DeepSeek Harness's opening line. A refusal of words -not reworded yet ends in a hint that names no one client (since 0.1.28): -WorkBuddy refused words in this client's prompt; use it from Hermes, -OpenCode or Pi, or add another provider to the group. +not reworded yet is sent once more, since 0.1.29, with the system prompt +moved into the first user message (inside `` tags) and +WorkBuddy's default system prompt in its place: WorkBuddy checks only the +system and assistant messages, and the line it matched is then in neither. +A system message later in the chat becomes a user message where it stands. +The plugin remembers each refused system prompt while it is loaded, so that +agent's next chats go moved at once. A refusal that stands after the move +(words in an assistant message) ends in a hint that names no one client +(since 0.1.28): WorkBuddy refused words in this client's prompt; use it from +Hermes, OpenCode or Pi, or add another provider to the group. Neither +refusal rests the account. The loader also translates OpenAI-compatible request spellings WorkBuddy doesn't take: `max_completion_tokens` becomes `max_tokens`, `developer` diff --git a/packages/workbuddy/index.mjs b/packages/workbuddy/index.mjs index 2f5316a..3cbc9df 100644 --- a/packages/workbuddy/index.mjs +++ b/packages/workbuddy/index.mjs @@ -542,6 +542,61 @@ function withSystem(body) { } } +// WorkBuddy's channel check reads the system and assistant messages only: +// tried on 2026-10-21 with real accounts on both builds (glm-5.3, +// deepseek-v4.1-flash, gpt-5.5), each refused line was served in the user's +// message, a tool's result and a user message's parts, and refused again in +// the system or an assistant message. It matches a known line whole and +// exactly (one extra space lets it through), so FLAGGED only ever knows the +// lines met so far, and another agent's opening line is refused until one is +// added (Wing on Discord, 10-21, with an agent we couldn't name). +// +// systemAsUser is body with its system prompt read to the model as the +// first thing the user says, in INSTRUCTIONS' tags, and WorkBuddy's default +// system prompt first, as both builds want a system message there (11128 +// "first message is not system prompt"). A system message later in the chat +// becomes the user's where it stands. null when there's nothing to move. +const DEFAULT_SYSTEM = "You are a helpful assistant." +const INSTRUCTIONS = ["\n", "\n"] + +function textOf(content) { + if (typeof content === "string") return content + if (!Array.isArray(content)) return "" + return content.map((p) => (typeof p?.text === "string" ? p.text : "")).filter(Boolean).join("\n") +} + +// systemKey is the text of a chat's system messages, which a chat refused +// once is known by: the same agent's next chat goes with systemAsUser at once +function systemKey(body) { + const msgs = chatOf(body)?.messages + if (!Array.isArray(msgs)) return "" + const key = msgs.filter((m) => m?.role === "system").map((m) => textOf(m.content)).join("\n") + return key.trim() === DEFAULT_SYSTEM ? "" : key +} + +function systemAsUser(body) { + const b = chatOf(body) + const msgs = b?.messages + if (!Array.isArray(msgs)) return null + let i = 0 + const lead = [] + for (; i < msgs.length && msgs[i]?.role === "system"; i++) lead.push(textOf(msgs[i].content)) + const said = lead.join("\n\n").trim() + const rest = msgs.slice(i).map((m) => (m?.role === "system" ? { ...m, role: "user" } : m)) + const moved = said && said !== DEFAULT_SYSTEM + if (!moved && rest.every((m, k) => m === msgs[i + k])) return null + if (moved) { + const text = INSTRUCTIONS[0] + said + INSTRUCTIONS[1] + const u = rest.findIndex((m) => m?.role === "user") + if (u < 0) rest.unshift({ role: "user", content: text }) + else if (typeof rest[u].content === "string") rest[u] = { ...rest[u], content: text + "\n\n" + rest[u].content } + else if (Array.isArray(rest[u].content)) rest[u] = { ...rest[u], content: [{ type: "text", text }, ...rest[u].content] } + else rest[u] = { ...rest[u], content: text } + } + b.messages = [{ role: "system", content: DEFAULT_SYSTEM }, ...rest] + return JSON.stringify(b) +} + // normalizeToolChoice converts the object form emitted by OpenAI clients to // WorkBuddy's string form. It runs after fitted(), so a named choice follows a // tool name that was made safe for WorkBuddy. @@ -1559,6 +1614,9 @@ 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 const endsAfterTools = new Set() + // 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 }) => ({ config: async (config) => { config.provider ??= {} @@ -1629,15 +1687,27 @@ function makePlugin(site) { // a model known to turn tool results then the user's message away // gets the empty reply between them up front (see endsAfterTools) const model = chatOf(body)?.model - const quiet = endsAfterTools.has(model) ? replyAfterTools(body) : null - let res = await send(quiet ?? body) - if (res.status === 400 && !quiet) { - const text = await res.text() - const again = AFTER_TOOLS_REFUSED.test(text) ? replyAfterTools(body) : null + // a system prompt WorkBuddy refused before goes as the user's + // words at once (see systemAsUser) + const sysKey = systemKey(body) + if (sysKey && refusedSystems.has(sysKey)) body = systemAsUser(body) ?? body + const shaped = (b) => (endsAfterTools.has(model) ? replyAfterTools(b) ?? b : b) + let res = await send(shaped(body)) + if (res.status === 400) { + let text = await res.text() + const moved = REFUSED.test(text) && sysKey && !refusedSystems.has(sysKey) ? systemAsUser(body) : null + if (moved) { + refusedSystems.add(sysKey) + if (refusedSystems.size > 256) refusedSystems.delete(refusedSystems.values().next().value) + body = moved + res = await send(shaped(body)) + if (res.status === 400) text = await res.text() + } + const again = res.status === 400 && !endsAfterTools.has(model) && AFTER_TOOLS_REFUSED.test(text) ? replyAfterTools(body) : null if (again) { endsAfterTools.add(model) res = await send(again) - } else { + } else if (res.status === 400) { res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) } } @@ -1785,4 +1855,4 @@ export const WorkBuddyAuthPlugin = makePlugin(SITES.workbuddy) export const WorkBuddyAIAuthPlugin = makePlugin(SITES["workbuddy-ai"]) // for tests -export const _internal = { 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 } +export const _internal = { 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 } diff --git a/packages/workbuddy/package.json b/packages/workbuddy/package.json index 78d567d..db08278 100644 --- a/packages/workbuddy/package.json +++ b/packages/workbuddy/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-workbuddy-auth", - "version": "0.1.28", + "version": "0.1.29", "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/systemasuser.test.mjs b/packages/workbuddy/systemasuser.test.mjs new file mode 100644 index 0000000..67a986f --- /dev/null +++ b/packages/workbuddy/systemasuser.test.mjs @@ -0,0 +1,169 @@ +// WorkBuddy refuses a chat whose system (or an assistant) message holds a +// line it knows from another agent, as 400 11128 "Illegal API invocation +// from an unapproved channel"; the user's and tools' messages aren't read. +// Opening lines are matched only at the start of the message, others +// anywhere in it. REFUSAL is the body copilot.tencent.com and +// www.workbuddy.ai both sent on 2026-10-21 for a system prompt opening with +// Claude Code's identity line. +import { expect, test } from "bun:test" +import { WorkBuddyAuthPlugin, WorkBuddyAIAuthPlugin, _internal } from "./index.mjs" + +const { systemAsUser, REFUSED_HINT, DEFAULT_SYSTEM } = _internal + +const REFUSAL = JSON.stringify({ + code: 11128, + msg: "Illegal API invocation from an unapproved channel", + requestId: "77e85b2840d5e111705b54090bc89318", + displayMsg: { en: "Request blocked. Please send it again", zh: "请求被拦截,请重新发送", "zh-hant": "請求已被攔截,請重新傳送" }, + displayTips: { + en: "This call failed channel verification, possibly because it was not sent from an official client. Please resend from the official client.", + zh: "这次调用没通过渠道校验,可能不是官方客户端发出的。请用官方版本重新发送。", + "zh-hant": "本次呼叫未通過通路驗證,可能不是官方用戶端發出。請使用官方版本重新傳送。", + }, + actions: ["EDIT_INPUT", "SUBMIT_FEEDBACK"], +}) +const NOT_FIRST = JSON.stringify({ code: 11128, msg: "first message is not system prompt", requestId: "e83a1453a850789c0e647f25f0e788af" }) + +// lines FLAGGED doesn't know, refused as WorkBuddy refuses known ones: an +// agent's opening line at the start, a fingerprint anywhere +const OPENING = "You are Example Agent, the official CLI of Example Inc." +const ANYWHERE = "Example fingerprint (you will usually see this)" + +const text = (c) => (typeof c === "string" ? c : Array.isArray(c) ? c.map((p) => p?.text ?? "").join("") : "") +const refuses = (m) => (m.role === "system" || m.role === "assistant") && (text(m.content).toLowerCase().startsWith(OPENING.toLowerCase()) || text(m.content).includes(ANYWHERE)) + +async function withService(Plugin, fn, answer) { + const realFetch = globalThis.fetch + const sent = [] + globalThis.fetch = async (_url, init) => { + const b = JSON.parse(init.body) + sent.push(b) + const said = answer?.(b) + if (said) return said + if (b.messages.some(refuses)) return new Response(REFUSAL, { status: 400, headers: { "content-type": "application/json; charset=utf-8" } }) + return new Response("data: [DONE]\n\n", { headers: { "content-type": "text/event-stream" } }) + } + try { + const hooks = await Plugin({ client: {} }) + const loader = await hooks.auth.loader(async () => ({ type: "oauth", access: "access", uid: "uid", expires: Date.now() + 3600_000 })) + const post = (body) => loader.fetch("https://copilot.tencent.com/v2/chat/completions", { method: "POST", body: JSON.stringify({ model: "glm-5.3", stream: true, ...body }) }) + await fn(post, sent) + } finally { + globalThis.fetch = realFetch + } +} + +const tools = [{ type: "function", function: { name: "read", description: "Reads a file.", parameters: { type: "object", properties: { path: { type: "string" } }, required: ["path"] } } }] +let n = 0 +// a system prompt of its own per test: what was refused stays remembered for as +// long as the plugin is loaded, across sign-ins +const systemOf = () => ({ role: "system", content: OPENING + "\nUse the tools to answer. (" + ++n + ")" }) +const ask = { role: "user", content: "Read calc.py." } + +for (const [name, Plugin] of [["WorkBuddy", WorkBuddyAuthPlugin], ["WorkBuddy AI", WorkBuddyAIAuthPlugin]]) { + test(`${name}: a refused system prompt goes again as the user's instructions, tools and all`, async () => { + const system = systemOf() + await withService(Plugin, async (post, sent) => { + const res = await post({ messages: [system, ask], tools }) + expect(res.status).toBe(200) + expect(sent.length).toBe(2) + const again = sent[1] + expect(again.messages[0]).toEqual({ role: "system", content: DEFAULT_SYSTEM }) + expect(again.messages[1]).toEqual({ role: "user", content: "\n" + system.content + "\n\n\nRead calc.py." }) + expect(again.messages.length).toBe(2) + expect(again.tools.map((t) => t.function.name)).toEqual(["read"]) + }) + }) +} + +test("the same system prompt's next chat goes moved at once, and another's is tried as it is", async () => { + const system = systemOf() + await withService(WorkBuddyAuthPlugin, async (post, sent) => { + await post({ messages: [system, ask], tools }) + const call = { role: "assistant", content: null, tool_calls: [{ id: "c1", type: "function", function: { name: "read", arguments: '{"path":"calc.py"}' } }] } + const result = { role: "tool", tool_call_id: "c1", content: "def add(a, b): return a + b" } + const res = await post({ messages: [system, ask, call, result], tools }) + expect(res.status).toBe(200) + expect(sent.length).toBe(3) + expect(sent[2].messages.map((m) => m.role)).toEqual(["system", "user", "assistant", "tool"]) + expect(sent[2].messages[1].content.startsWith("\n" + OPENING)).toBe(true) + // what the tool said and what the assistant called stay as they were + expect(sent[2].messages[2]).toEqual(call) + expect(sent[2].messages[3]).toEqual(result) + await post({ messages: [{ role: "system", content: "You are a coding agent." }, ask] }) + expect(sent.length).toBe(4) + expect(sent[3].messages[0].content).toBe("You are a coding agent.") + }) +}) + +test("a line refused anywhere in the system prompt is moved too", async () => { + await withService(WorkBuddyAIAuthPlugin, async (post, sent) => { + const res = await post({ messages: [{ role: "system", content: "You are a coding agent.\n\nGit status:\n" + ANYWHERE }, ask] }) + expect(res.status).toBe(200) + expect(sent.length).toBe(2) + expect(sent[1].messages[1].content).toContain(ANYWHERE) + }) +}) + +test("a refusal that stands after the move is the user's, with the hint, tried once", async () => { + const system = systemOf() + await withService(WorkBuddyAuthPlugin, async (post, sent) => { + // an assistant message WorkBuddy refuses too, which nothing moves + const res = await post({ messages: [system, ask, { role: "assistant", content: OPENING }, { role: "user", content: "go on" }] }) + expect(res.status).toBe(400) + expect(sent.length).toBe(2) + expect(res.headers.get("X-Magpie-Sign-In")).toBe("kept") + expect((await res.json()).error.message).toBe("Illegal API invocation from an unapproved channel — " + REFUSED_HINT) + }) +}) + +test("a chat with nothing to move isn't sent again", async () => { + await withService(WorkBuddyAuthPlugin, async (post, sent) => { + const res = await post({ messages: [{ role: "user", content: "hi" }, { role: "assistant", content: OPENING }, ask] }) + expect(res.status).toBe(400) + expect(sent.length).toBe(1) + }) +}) + +test("11128 for another reason moves nothing", async () => { + await withService( + WorkBuddyAIAuthPlugin, + async (post, sent) => { + const res = await post({ messages: [{ role: "system", content: "You are a coding agent." }, ask] }) + expect(res.status).toBe(400) + expect(sent.length).toBe(1) + }, + () => new Response(NOT_FIRST, { status: 400, headers: { "content-type": "application/json" } }), + ) +}) + +test("systemAsUser: parts, a later system message, no user message", () => { + const parts = JSON.parse( + systemAsUser( + JSON.stringify({ + messages: [ + { role: "system", content: [{ type: "text", text: OPENING }, { type: "text", text: "Be brief." }] }, + { role: "user", content: [{ type: "text", text: "look" }, { type: "image_url", image_url: { url: "data:image/png;base64,AA==" } }] }, + { role: "assistant", content: "ok" }, + { role: "system", content: "Reminder: be brief." }, + { role: "user", content: "next" }, + ], + }), + ), + ) + expect(parts.messages[0]).toEqual({ role: "system", content: DEFAULT_SYSTEM }) + expect(parts.messages[1].content[0]).toEqual({ type: "text", text: "\n" + OPENING + "\nBe brief.\n" }) + expect(parts.messages[1].content.slice(1).map((p) => p.type)).toEqual(["text", "image_url"]) + expect(parts.messages[3]).toEqual({ role: "user", content: "Reminder: be brief." }) + + const alone = JSON.parse(systemAsUser(JSON.stringify({ messages: [{ role: "system", content: OPENING }] }))) + expect(alone.messages).toEqual([{ role: "system", content: DEFAULT_SYSTEM }, { role: "user", content: "\n" + OPENING + "\n" }]) + + expect(systemAsUser(JSON.stringify({ messages: [{ role: "system", content: DEFAULT_SYSTEM }, ask] }))).toBeNull() +}) + +test("the words the move adds name no one", () => { + const out = systemAsUser(JSON.stringify({ messages: [{ role: "system", content: "x" }, ask] })) + const added = out.replace(/"x"|Read calc\.py\.|You are a helpful assistant\./g, "") + expect(added).not.toMatch(/magpie|workbuddy|codebuddy|opencode|claude|codex/i) +})