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 }] })
+})