diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index f47bb4d..3bf0045 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -1459,6 +1459,110 @@ function startHeaders(h, jwt) { return out } +// Claude Code's tool search, as ZCode's plans take it. Claude Code +// (2.1.310) offers a tool named ToolSearch, names its deferred tools in a +// system turn, and sends a deferred tool's schema with defer_loading only +// once a search loaded it (a tool_reference in a ToolSearch result), with +// a DeferredToolPlaceholder that keeps the search on. api.z.ai's +// Anthropic endpoint, given a tool named exactly ToolSearch, shows the +// model none of the other tools, Bash, Read and Write among them, but +// those a tool_reference loaded: a subagent, which hasn't searched, +// reports only the deferred tools, and the main turn has to search for +// Bash before it can run it (小八 on Discord, 10-24; the beta header +// changes nothing, the name alone does). ZCode itself sends no ToolSearch +// and no defer_loading. So the search goes as SEARCH_ALIAS, in the tools +// and in the turns that called it, the tools Claude Code sent with their +// schemas go as ZCode's do, without defer_loading, and the placeholder is +// left out; the model's calls to SEARCH_ALIAS come back as ToolSearch +// (searchNamed). +const SEARCH = "ToolSearch" +const SEARCH_ALIAS = "ToolSearchTool" +const PLACEHOLDER = "DeferredToolPlaceholder" + +// searchless is a Messages request body without Claude Code's ToolSearch +// name, and whether it had the tool; anything else goes as it is. +function searchless(text) { + if (typeof text !== "string" || !text.includes(`"${SEARCH}"`)) return { text, renamed: false } + let b + try { + b = JSON.parse(text) + } catch { + return { text, renamed: false } + } + if (!b || !Array.isArray(b.tools) || !b.tools.some((t) => t?.name === SEARCH)) return { text, renamed: false } + // a tool of the alias's own name keeps it; the search can't then be renamed + if (b.tools.some((t) => t?.name === SEARCH_ALIAS)) return { text, renamed: false } + b.tools = b.tools + .filter((t) => t?.name !== PLACEHOLDER) + .map((t) => { + if (!t || typeof t !== "object") return t + const { defer_loading, ...rest } = t + return t.name === SEARCH ? { ...rest, name: SEARCH_ALIAS } : rest + }) + if (Array.isArray(b.messages)) + for (const m of b.messages) + if (m?.role === "assistant" && Array.isArray(m.content)) + for (const x of m.content) if (x?.type === "tool_use" && x.name === SEARCH) x.name = SEARCH_ALIAS + if (b.tool_choice?.type === "tool" && b.tool_choice.name === SEARCH) b.tool_choice.name = SEARCH_ALIAS + return { text: JSON.stringify(b), renamed: true } +} + +// searchNamed is an answer to a request searchless renamed, the model's +// calls to SEARCH_ALIAS named ToolSearch again, as Claude Code runs them: +// a stream's content_block_start events, or a whole message's content. +function searchNamed(res) { + if (!res.body) return res + const type = res.headers.get("content-type") ?? "" + const named = (block) => { + if (block?.type === "tool_use" && block.name === SEARCH_ALIAS) { + block.name = SEARCH + return true + } + return false + } + const line = (l) => { + if (!l.startsWith("data:") || !l.includes(`"${SEARCH_ALIAS}"`)) return l + try { + const d = JSON.parse(l.slice(5)) + return named(d?.content_block) ? "data: " + JSON.stringify(d) : l + } catch { + return l + } + } + if (type.includes("text/event-stream")) { + const dec = new TextDecoder() + const enc = new TextEncoder() + let held = "" + const body = res.body.pipeThrough( + new TransformStream({ + transform(chunk, ctl) { + held += dec.decode(chunk, { stream: true }) + const i = held.lastIndexOf("\n") + if (i < 0) return + ctl.enqueue(enc.encode(held.slice(0, i + 1).split("\n").map(line).join("\n"))) + held = held.slice(i + 1) + }, + flush(ctl) { + held += dec.decode() + if (held) ctl.enqueue(enc.encode(line(held))) + }, + }), + ) + return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers }) + } + if (!type.includes("json")) return res + return res.text().then((text) => { + let out = text + if (text.includes(`"${SEARCH_ALIAS}"`)) { + try { + const v = JSON.parse(text) + if (Array.isArray(v?.content) && v.content.map(named).some(Boolean)) out = JSON.stringify(v) + } catch {} + } + return new Response(out, { status: res.status, statusText: res.statusText, headers: res.headers }) + }) +} + // startURL is a Start Plan request's URL without the query the agent put // on it: Claude Code asks /v1/messages?beta=true, which magpie passes on, // and ZCode asks /v1/messages alone. @@ -1670,9 +1774,18 @@ export async function ZCodeAuthPlugin({ client }) { // says it is spent can spend nothing and replay what was asked for let start = alone let orig, forcedGift = false + let renamed = false + const done = (res) => (renamed ? searchNamed(res) : res) if (opts.body != null) { orig = opts.body = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text() delete opts.duplex + // Claude Code's tool search goes under another name, or + // ZCode's plans show the model no other tool (searchless) + const plain = searchless(orig) + if (plain.renamed) { + orig = opts.body = plain.text + renamed = true + } let m = modelOf(orig) if (m.toLowerCase().endsWith("-trial")) { gift ??= await startPlan(s.jwt, s.device).catch(() => null) @@ -1714,6 +1827,7 @@ export async function ZCodeAuthPlugin({ client }) { } else { if (!key) throw new Error("ZCode's sign-in has no key; sign in again") swap(s.base) + if (renamed) h.delete("content-length") h.delete("authorization") h.set("x-api-key", key) h.set("Authorization", "Bearer " + key) @@ -1737,17 +1851,17 @@ export async function ZCodeAuthPlugin({ client }) { if (res.status >= 400 || json) { const text = await res.text() const spent = spentUp(text, res.status) - if (!spent && res.status < 400) return kept(res, text) + if (!spent && res.status < 400) return done(kept(res, text)) if (spent) { for (const [k, until] of blocked) if (Date.now() >= until) blocked.delete(k) blocked.set(s.key + "\0" + s.jwt + "\0" + modelOf(orig).toLowerCase(), Date.now() + 60_000) } - return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : kept(res, text) + return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text)) } } // the plan's answer goes on as it came, the account kept: the // built-in never marked a ZCode account lapsed nor cleared one - return kept(res) + return done(kept(res)) }, } }, diff --git a/packages/zcode/package.json b/packages/zcode/package.json index 1c1a486..46a2099 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.23", + "version": "0.1.24", "description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan", "type": "module", "main": "./index.mjs", diff --git a/packages/zcode/toolsearch.test.mjs b/packages/zcode/toolsearch.test.mjs new file mode 100644 index 0000000..257c7bc --- /dev/null +++ b/packages/zcode/toolsearch.test.mjs @@ -0,0 +1,191 @@ +// Claude Code's tool search on ZCode's plans (小八 on Discord, 10-24). +// api.z.ai's Anthropic endpoint, given a tool named exactly ToolSearch, +// shows the model no other tool but those a tool_reference loaded, so a +// Claude Code subagent saw only its deferred tools and no Bash, Read or +// Write. The search goes to the plan as ToolSearchTool, the tools without +// defer_loading and the placeholder, and the model's calls come back to +// Claude Code as ToolSearch. The requests go to a local Bun.serve that +// records them; nothing reaches z.ai. +import { afterAll, afterEach, beforeAll, expect, test } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +let ZCodeAuthPlugin +let server +const got = [] +let answer = null +beforeAll(async () => { + if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") + ;({ ZCodeAuthPlugin } = await import("./index.mjs")) + server = Bun.serve({ + port: 0, + async fetch(req) { + got.push({ path: new URL(req.url).pathname, headers: Object.fromEntries(req.headers), body: await req.text() }) + if (answer) return answer() + return Response.json({ type: "message", content: [] }) + }, + }) +}) +afterAll(() => server?.stop(true)) + +const real = globalThis.fetch +const HOSTS = ["https://zcode.z.ai", "https://api.z.ai", "https://open.bigmodel.cn"] +function routeToFake() { + globalThis.fetch = (input, init) => { + const url = input instanceof Request ? input.url : String(input) + const host = HOSTS.find((h) => url.startsWith(h + "/")) + if (!host) throw new Error("no network in tests: " + url) + return real(`http://127.0.0.1:${server.port}/${new URL(host).host}${url.slice(host.length)}`, init) + } +} +afterEach(() => { + globalThis.fetch = real + got.length = 0 + answer = null +}) + +const jwt = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" +const coding = { type: "oauth", access: "id.secret", refresh: JSON.stringify({ site: "zai", key: "id.secret" }), expires: 0 } +const startPlan = { type: "oauth", access: jwt, refresh: JSON.stringify({ site: "zai", device: "11111111-2222-4333-8444-555555555555", jwt }), expires: 0 } + +async function send(auth, body) { + routeToFake() + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth, { id: "zcode" }) + const headers = { + "content-type": "application/json", + "x-api-key": "zcode", + "anthropic-version": "2023-06-01", + "anthropic-beta": "claude-code-20250219,mid-conversation-tool-changes-2026-07-01,advanced-tool-use-2025-11-20", + } + const res = await opts.fetch("https://api.z.ai/api/anthropic/v1/messages?beta=true", { method: "POST", headers, body: JSON.stringify(body) }) + return { res, sent: got.length ? JSON.parse(got[got.length - 1].body) : null } +} + +const schema = { type: "object", properties: { command: { type: "string" } } } +// a Claude Code 2.1.310 subagent's request, as it reached magpie: its tools +// in Claude Code's order, the placeholder deferred, an MCP tool a search +// loaded (deferred, its schema sent), and the search that loaded it +const claudeCode = () => ({ + model: "glm-5.3", + max_tokens: 32000, + stream: true, + system: [{ type: "text", text: "You are an agent for Claude Code, Anthropic's official CLI for Claude." }], + messages: [ + { role: "user", content: [{ type: "text", text: "List the files here with Bash, then report." }] }, + { role: "system", content: [{ type: "text", text: "The following deferred tools are now available via ToolSearch.\nmcp__probe__probe_0" }] }, + { role: "assistant", content: [{ type: "tool_use", id: "toolu_s", name: "ToolSearch", input: { query: "select:mcp__probe__probe_0", max_results: 5 } }] }, + { role: "user", content: [{ type: "tool_result", tool_use_id: "toolu_s", content: [{ type: "tool_reference", tool_name: "mcp__probe__probe_0" }] }, { type: "text", text: "go on" }] }, + ], + tools: [ + { name: "Agent", description: "Launch a new agent", input_schema: schema }, + { name: "Bash", description: "Executes a bash command", input_schema: schema }, + { name: "Read", description: "Reads a file", input_schema: schema }, + { name: "ToolSearch", description: "Fetches full schema definitions for deferred tools", input_schema: schema }, + { name: "DeferredToolPlaceholder", description: "Reserved placeholder that keeps deferred tool loading active; never call this tool.", input_schema: { type: "object", properties: {} }, defer_loading: true }, + { name: "Write", description: "Writes a file", input_schema: schema }, + { name: "mcp__probe__probe_0", description: "Probe tool 0", input_schema: schema, defer_loading: true }, + ], +}) + +function expectSearchless(sent) { + const names = sent.tools.map((t) => t.name) + expect(names).toEqual(["Agent", "Bash", "Read", "ToolSearchTool", "Write", "mcp__probe__probe_0"]) + expect(sent.tools.some((t) => "defer_loading" in t)).toBe(false) + expect(JSON.stringify(sent)).not.toContain('"name":"ToolSearch"') + const call = sent.messages.flatMap((m) => (Array.isArray(m.content) ? m.content : [])).find((x) => x.type === "tool_use") + expect(call).toMatchObject({ id: "toolu_s", name: "ToolSearchTool" }) + const result = sent.messages.flatMap((m) => (Array.isArray(m.content) ? m.content : [])).find((x) => x.type === "tool_result") + expect(result.content).toEqual([{ type: "tool_reference", tool_name: "mcp__probe__probe_0" }]) +} + +test("a GLM Coding Plan request offers Claude Code's search as ToolSearchTool, every tool undeferred", async () => { + const { res, sent } = await send(coding, claudeCode()) + expect(res.status).toBe(200) + expect(got[0].path).toBe("/api.z.ai/api/anthropic/v1/messages") + expectSearchless(sent) + // the rest of the request is the agent's + expect(sent.system).toEqual(claudeCode().system) + expect(got[0].headers["anthropic-beta"]).toContain("advanced-tool-use-2025-11-20") +}) + +test("a Start Plan request offers it as ToolSearchTool too", async () => { + const { sent } = await send(startPlan, claudeCode()) + expect(got[0].path).toBe("/zcode.z.ai/api/v1/zcode-plan/anthropic/v1/messages") + expectSearchless(sent) +}) + +test("a request without Claude Code's search goes as the agent sent it", async () => { + const body = claudeCode() + body.tools = body.tools.filter((t) => t.name !== "ToolSearch") + body.messages = body.messages.slice(0, 2) + const { sent } = await send(coding, body) + expect(sent).toEqual(body) +}) + +const sse = (events) => events.map((e) => `event: ${e.type}\ndata: ${JSON.stringify(e)}\n\n`).join("") + +test("the model's streamed call to ToolSearchTool reaches Claude Code as ToolSearch", async () => { + const events = [ + { type: "message_start", message: { id: "m1", type: "message", role: "assistant", content: [], usage: { input_tokens: 1, output_tokens: 0 } } }, + { type: "content_block_start", index: 0, content_block: { type: "text", text: "" } }, + { type: "content_block_delta", index: 0, delta: { type: "text_delta", text: 'I will call "ToolSearchTool".' } }, + { type: "content_block_stop", index: 0 }, + { type: "content_block_start", index: 1, content_block: { type: "tool_use", id: "toolu_1", name: "ToolSearchTool", input: {} } }, + { type: "content_block_delta", index: 1, delta: { type: "input_json_delta", partial_json: '{"query":"select:Bash"}' } }, + { type: "content_block_stop", index: 1 }, + { type: "content_block_start", index: 2, content_block: { type: "tool_use", id: "toolu_2", name: "Bash", input: {} } }, + { type: "content_block_stop", index: 2 }, + { type: "message_delta", delta: { stop_reason: "tool_use" }, usage: { output_tokens: 9 } }, + { type: "message_stop" }, + ] + const text = sse(events) + // in small chunks, so an event's line arrives in pieces + answer = () => { + const bytes = new TextEncoder().encode(text) + const cut = 7 // lines and multi-byte reads cross chunks + return new Response( + new ReadableStream({ + start(c) { + for (let i = 0; i < bytes.length; i += cut) c.enqueue(bytes.slice(i, i + cut)) + c.close() + }, + }), + { headers: { "content-type": "text/event-stream" } }, + ) + } + const { res } = await send(coding, claudeCode()) + const back = (await res.text()) + .split("\n") + .filter((l) => l.startsWith("data:")) + .map((l) => JSON.parse(l.slice(5))) + expect(back.length).toBe(events.length) + expect(back[4].content_block).toEqual({ type: "tool_use", id: "toolu_1", name: "ToolSearch", input: {} }) + expect(back[7].content_block.name).toBe("Bash") + // the model's own text is its own + expect(back[2].delta.text).toBe('I will call "ToolSearchTool".') + expect(back.filter((_, i) => i !== 4)).toEqual(events.filter((_, i) => i !== 4)) +}) + +test("a whole message's call to ToolSearchTool reaches Claude Code as ToolSearch, on the Start Plan too", async () => { + for (const auth of [coding, startPlan]) { + answer = () => + Response.json({ + type: "message", + role: "assistant", + content: [ + { type: "text", text: "ToolSearchTool" }, + { type: "tool_use", id: "toolu_1", name: "ToolSearchTool", input: { query: "select:Read" } }, + ], + stop_reason: "tool_use", + }) + const body = { ...claudeCode(), stream: false } + const { res } = await send(auth, body) + const v = await res.json() + expect(v.content).toEqual([ + { type: "text", text: "ToolSearchTool" }, + { type: "tool_use", id: "toolu_1", name: "ToolSearch", input: { query: "select:Read" } }, + ]) + got.length = 0 + } +})