From 3d355d349d985a78c982a086f80f741e7e639802 Mon Sep 17 00:00:00 2001 From: yetone Date: Thu, 22 Oct 2026 10:00:12 +0800 Subject: [PATCH] zed 0.1.11: a {role: "system"} message inside an Anthropic request reaches Zed as user text where it was said, not as a role Zed refuses Roy on Discord, Claude Code through magpie on a Zed subscription: "API Error: 400 Zed: failed to parse Anthropic request: unknown variant system, expected user or assistant". Cause: Claude Code (2.1.288 on) writes {role: "system"} messages inside messages[]: an empty one carrying a turn's effort as output_config, and (2.1.296) one after tool results with its hooks' notices, and what the user typed while a tool ran. Anthropic's API takes them in place. magpie's gateway passes them on as written (anthropic_shapes.go mends only after a refusal matching `messages.N.role`, which Zed's serde message doesn't), and the plugin's providerRequest "anthropic" case forwarded them to Zed, whose Anthropic Role is user | assistant only. Fix: providerRequest's anthropic case runs withoutSystemTurns. Each system message's text goes, as text blocks (cache_control kept), into a user turn at the same place: appended to the user message before it; else after the leading tool_result blocks of the user message after it (tool results must stay first); else a user message of its own. One with no text (an effort alone) is left out; the request's top-level output_config still carries the effort. Why in place and not folded into the top-level system: the prompt cache's prefix is tools, then system, then messages. Text appended to system on each turn that has a notice changes the prefix ahead of every message, so the whole conversation misses the cache from then on, while merging in place changes only bytes at the conversation's tail, which the next request repeats unchanged (the transform is deterministic per message). It also keeps the meaning Anthropic's API gives the message: said at that point in the turn, not standing instructions for the whole conversation. magpie's own withSystemOnTop folds to the top for Command Code, which refuses the role by name; that path never fires for Zed's wording. Siblings, not changed: responses (OpenAI Responses) and chat (xAI Chat Completions) both have system/developer roles in their own message schemas, so a system message there is not this error; gemini has no system role in contents (the AI SDK sends systemInstruction). None was tried against Zed's cloud with a mid-conversation system message, and there is no report of one. Tests (system-role.test.mjs, built from Claude Code's shapes and checking the provider_request the plugin hands Zed's /completions): a hook notice after tool results joins their user turn after the results and system stays as sent; an empty effort-only system message is left out; system text before a tool-result user turn goes after the results, and one after an assistant turn becomes a user turn. With index.mjs reverted to 43ffb46 all 3 fail; with the fix all pass. Run at 43ffb46 + this change: `HOME=$(mktemp -d) bun test` in packages/zed: 47 pass, 0 fail. `bun scripts/check.mjs`: ok (exit 0). Not tried: a real Zed account (none in a sandbox HOME here); the shape Zed accepts is Anthropic's user/assistant messages, as the plugin already sends for every request without system messages. --- packages/zed/index.mjs | 63 +++++++++++++++++ packages/zed/package.json | 2 +- packages/zed/system-role.test.mjs | 111 ++++++++++++++++++++++++++++++ 3 files changed, 175 insertions(+), 1 deletion(-) create mode 100644 packages/zed/system-role.test.mjs diff --git a/packages/zed/index.mjs b/packages/zed/index.mjs index 03d1617..2b30e07 100644 --- a/packages/zed/index.mjs +++ b/packages/zed/index.mjs @@ -552,6 +552,68 @@ function wireOf(url) { const WIRE_VENDOR = { anthropic: "anthropic", responses: "open_ai", chat: "x_ai", gemini: "google" } +// Claude Code (2.1.288 on) puts {role: "system"} messages inside an +// Anthropic request's messages: a turn's effort as output_config on an empty +// one, and its hooks' notices and what the user typed while a tool ran after +// the tool results (2.1.296). Anthropic's own API takes them where they sit; +// Zed's cloud takes only user and assistant there and answers 400 "failed +// to parse Anthropic request: unknown variant `system`, expected `user` or +// `assistant`". withoutSystemTurns keeps each one's text where it was, as +// text blocks of a user turn: appended to the user message before it, else +// put after the tool results at the head of the user message after it, else +// a user message of its own. One with no text (an effort alone) is left out; +// the request's own output_config still asks for the turn's effort. Kept in +// place, not moved to the top-level system: system comes before every +// message in the prompt cache's prefix, so text added there each turn would +// miss the cache for the whole conversation, and the notice would lose +// where in the turn it was said. +function systemBlocks(content) { + if (typeof content === "string") return content ? [{ type: "text", text: content }] : [] + if (!Array.isArray(content)) return [] + return content.filter((b) => b && typeof b === "object" && !(b.type === "text" && !b.text)) +} + +function asBlocks(content) { + if (Array.isArray(content)) return content + if (typeof content === "string" && content) return [{ type: "text", text: content }] + return [] +} + +function withoutSystemTurns(messages) { + if (!messages.some((m) => m?.role === "system")) return messages + const out = [] + let pending = [] // system text waiting for the user message after it + for (const m of messages) { + if (m?.role === "system") { + const blocks = systemBlocks(m.content) + if (!blocks.length) continue + const prev = out.at(-1) + if (prev?.role === "user" && !pending.length) prev.content = [...asBlocks(prev.content), ...blocks] + else pending.push(...blocks) + continue + } + if (pending.length) { + if (m?.role === "user") { + const c = asBlocks(m.content) + let i = 0 + while (i < c.length && c[i]?.type === "tool_result") i++ + out.push({ ...m, content: [...c.slice(0, i), ...pending, ...c.slice(i)] }) + pending = [] + continue + } + out.push({ role: "user", content: pending }) + pending = [] + } + out.push(m) + } + if (pending.length) { + const prev = out.at(-1) + if (prev?.role === "user") prev.content = [...asBlocks(prev.content), ...pending] + else out.push({ role: "user", content: pending }) + } + return out +} + // providerRequest is the request as Zed takes it for its provider's API, // and whether the caller asked for a stream (Zed always streams). function providerRequest(wire, req, model) { @@ -567,6 +629,7 @@ function providerRequest(wire, req, model) { if (b?.type === "tool_result" && !("is_error" in b)) b.is_error = false } } + if (Array.isArray(req.messages)) req.messages = withoutSystemTurns(req.messages) return { req, stream } } case "responses": { diff --git a/packages/zed/package.json b/packages/zed/package.json index 99f4803..a885a4b 100644 --- a/packages/zed/package.json +++ b/packages/zed/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zed-auth", - "version": "0.1.10", + "version": "0.1.11", "description": "Sign in to a Zed subscription (Zed Pro, trial, student, business) from OpenCode or magpie", "type": "module", "main": "./index.mjs", diff --git a/packages/zed/system-role.test.mjs b/packages/zed/system-role.test.mjs new file mode 100644 index 0000000..96da9c1 --- /dev/null +++ b/packages/zed/system-role.test.mjs @@ -0,0 +1,111 @@ +// Claude Code puts {role: "system"} messages inside an Anthropic request's +// messages (a turn's effort, its hooks' notices after tool results). Zed's +// cloud takes only user and assistant there: 400 "failed to parse Anthropic +// request: unknown variant `system`, expected `user` or `assistant`" (Roy on +// Discord). The plugin sends their text in a user turn, where it was said. +import { afterEach, expect, test } from "bun:test" +import { _internal } from "./index.mjs" + +const real = globalThis.fetch +afterEach(() => { + globalThis.fetch = real + _internal.tokens.clear() +}) + +const s = { userId: "4242", access: "plain-access", systemId: "", org: "org-me", plan: "zed_pro", who: "octo" } + +// sent is the provider_request the plugin hands Zed for an Anthropic body. +async function sent(body) { + let got + globalThis.fetch = async (url, init) => { + const path = new URL(String(url)).pathname + if (path === "/client/llm_tokens") return Response.json({ token: "llm-token" }) + if (path === "/completions") { + got = JSON.parse(init.body) + const ev = (e) => JSON.stringify({ event: e }) + return new Response( + [ + ev({ type: "message_start", message: { id: "m1", type: "message", role: "assistant", model: "claude-sonnet-5", content: [], usage: { input_tokens: 1, output_tokens: 0 } } }), + ev({ type: "message_delta", delta: { stop_reason: "end_turn" }, usage: { output_tokens: 1 } }), + ev({ type: "message_stop" }), + JSON.stringify({ status: "stream_ended" }), + ].join("\n") + "\n", + { headers: { "x-zed-server-supports-status-messages": "true" } }, + ) + } + return new Response("", { status: 404 }) + } + const res = await _internal.complete(s, "https://cloud.zed.dev/v1/messages", { method: "POST", body: JSON.stringify(body) }) + await res.text() + return got.provider_request +} + +const roles = (r) => r.messages.map((m) => m.role) +const SYSTEM = [{ type: "text", text: "You are Claude Code.", cache_control: { type: "ephemeral" } }] +const NOTICE = "PostToolUse:Read hook additional context: the file is generated" + +test("a hook notice after tool results joins their user turn, after the results", async () => { + const r = await sent({ + model: "claude-sonnet-5", + stream: true, + max_tokens: 100, + system: SYSTEM, + messages: [ + { role: "user", content: "read a.go" }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Read", input: { file_path: "a.go" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "package a" }] }, + { role: "system", content: NOTICE }, + ], + }) + expect(roles(r)).toEqual(["user", "assistant", "user"]) + expect(r.messages[2].content).toEqual([ + { type: "tool_result", tool_use_id: "t1", content: "package a", is_error: false }, + { type: "text", text: NOTICE }, + ]) + // the top-level system, the cache's prefix, is as the agent sent it + expect(r.system).toEqual(SYSTEM) +}) + +test("an empty system message that only carries a turn's effort is left out", async () => { + const r = await sent({ + model: "claude-sonnet-5", + stream: true, + max_tokens: 100, + output_config: { effort: "high" }, + messages: [ + { role: "user", content: "hi" }, + { role: "system", content: [], output_config: { effort: "low" } }, + { role: "assistant", content: "hello" }, + { role: "user", content: "again" }, + ], + }) + expect(r.messages).toEqual([ + { role: "user", content: "hi" }, + { role: "assistant", content: "hello" }, + { role: "user", content: "again" }, + ]) + expect(r.output_config).toEqual({ effort: "high" }) +}) + +test("system text before a user turn goes after its tool results, and one after an assistant turn is a user turn", async () => { + const r = await sent({ + model: "claude-sonnet-5", + stream: true, + max_tokens: 100, + messages: [ + { role: "user", content: "go" }, + { role: "assistant", content: [{ type: "tool_use", id: "t1", name: "Bash", input: { command: "ls" } }] }, + { role: "system", content: [{ type: "text", text: "The user sent a new message while you were working:\nstop", cache_control: { type: "ephemeral" } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "a.go", is_error: false }, { type: "text", text: "9" }] }, + { role: "assistant", content: "Stopping." }, + { role: "system", content: NOTICE }, + ], + }) + expect(roles(r)).toEqual(["user", "assistant", "user", "assistant", "user"]) + expect(r.messages[2].content).toEqual([ + { type: "tool_result", tool_use_id: "t1", content: "a.go", is_error: false }, + { type: "text", text: "The user sent a new message while you were working:\nstop", cache_control: { type: "ephemeral" } }, + { type: "text", text: "9" }, + ]) + expect(r.messages[4]).toEqual({ role: "user", content: [{ type: "text", text: NOTICE }] }) +})