From 57598ad4107c2ea7b6484bc210bae0b638d1a5fa Mon Sep 17 00:00:00 2001 From: yetone Date: Sun, 25 Oct 2026 18:25:51 +0800 Subject: [PATCH] zcode 0.1.30: a coding plan's requests name the device in metadata.user_id, as ZCode's do (#387) wendyeq measured BigModel's GLM Coding Plan through magpie hitting the prompt cache 1 time in 19 without metadata.user_id and 13 in 16 with it; the official ZCode on the same account reads 95-98% of input from cache. The plugin only put user_id on the Start Plan's dressed body; a coding plan or team request went as the agent sent it, and Pi sends none. ZCode 3.14.3 (glm/zcode.cjs) sets it on every Anthropic-format request, not only the Start Plan's: Pst() returns MLs({deviceMid, sessionId}) for any providerKind "anthropic", and vWr() puts it in providerOptions.anthropic.metadata.userId for both generateText and streamText. The value is {"device_id":,"account_uuid":"", "session_id":...}. Now a coding plan or team request to .../v1/messages gets metadata.user_id = {"device_id":, "account_uuid":"","session_id":""}, the same value dress() puts on the Start Plan's, when the agent sent no user_id of its own; other metadata is kept and content-length dropped when the body changed. count_tokens and non-Messages bodies go as they were. An account known only by a key (a pasted API key, or a saved state with no device) gets a device id hashed from the key, so it is the same on every start rather than anyDevice, which was new per process. Differences from ZCode, kept on purpose: ZCode overwrites any user_id and fills session_id with its session (sess_ prefix stripped); this keeps an agent's own user_id and sends session_id "" as dress() does, one stable value per account. Tests: userid.test.mjs (new, 6 tests; 5 red on origin/main's index.mjs, the count_tokens one passes there as it should). start, toolsearch and dual tests that pinned coding plan bodies byte for byte now expect the agent's body plus the device's user_id. Run at this tree: HOME=$(mktemp -d) bun test -> 2672 pass, 1 skip, 0 fail across 229 files; bun scripts/check.mjs ok. Not tried: a real BigModel or Z.ai coding plan request, so the cache hit rate after the change is the reporter's measurement, not mine. --- packages/zcode/README.md | 7 +- packages/zcode/dual.test.mjs | 3 +- packages/zcode/index.mjs | 50 +++++++++++- packages/zcode/package.json | 2 +- packages/zcode/start.test.mjs | 27 ++++--- packages/zcode/toolsearch.test.mjs | 4 + packages/zcode/userid.test.mjs | 117 +++++++++++++++++++++++++++++ 7 files changed, 193 insertions(+), 17 deletions(-) create mode 100644 packages/zcode/userid.test.mjs diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 61f8355..0d22e84 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -25,7 +25,12 @@ over Anthropic's Messages API. Provider id: `zcode`. agent's system prompt at the end of the third (a fourth block is refused, #343), the day in a `` turn before the agent's turns, and the sign-in's device id in `metadata.user_id`. GLM Coding - Plan and team requests go as the agent sent them. zcode.z.ai also + Plan and team requests go as the agent sent them, but for that same + `metadata.user_id` when the agent sent none: ZCode puts it on every + request, and the plan's endpoint keeps a prompt cache on the machine it + picks by it, so without it the cache is mostly missed (#387). An + account known only by its key gets a device id made from the key, the + same on every start. zcode.z.ai also answers 405 code 3012 to every request of an account its risk control blocked, ZCode's own app's included (plugins#348). That answer comes back as ZCode's words, then "ZCode's risk control blocked this account diff --git a/packages/zcode/dual.test.mjs b/packages/zcode/dual.test.mjs index c14a2fe..df5213b 100644 --- a/packages/zcode/dual.test.mjs +++ b/packages/zcode/dual.test.mjs @@ -246,7 +246,8 @@ test("a model the gift does not serve goes to the coding plan as sent", async () const m = sent.at(-1) expect(m.origin).toBe("https://api.z.ai") expect(m.path).toBe("/api/anthropic/v1/messages") - expect(m.body).toBe(body("GLM-5.3")) + // as sent, but for the sign-in's device, as ZCode names it (#387) + expect(JSON.parse(m.body)).toEqual({ ...JSON.parse(body("GLM-5.3")), metadata: { user_id: JSON.stringify({ device_id: DEVICE, account_uuid: "", session_id: "" }) } }) expect(m.headers["x-api-key"]).toBe(KEY) expect(m.headers["x-title"]).toBeUndefined() }) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index cf69602..f7e8308 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -50,6 +50,12 @@ const siteOf = (s) => (s === "bigmodel" ? "bigmodel" : "zai") const platform = () => `${process.platform}-${process.arch}` // darwin-arm64, win32-x64, linux-x64, as ZCode names them const uuid = () => crypto.randomUUID() const anyDevice = uuid() // X-Device-Mid for calls made signed out (the model list) +// keyDevice is a device id for an account known only by its key: the same +// key gives the same id on every start, as a sign-in's saved device does +const keyDevice = (key) => { + const h = createHash("sha256").update("zcode-device\0" + key).digest("hex") + return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${((parseInt(h[16], 16) & 3) | 8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}` +} const first = (...ss) => ss.map((s) => (typeof s === "string" ? s.trim() : "")).find((s) => s) ?? "" // STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a @@ -1265,11 +1271,13 @@ function stateOf(auth) { } } const site = siteOf(s.site) - return { ...s, site, base: s.base || SITES[site].base, key: s.key ?? (s.jwt ? "" : auth.access), device: s.device || anyDevice } + const key = s.key ?? (s.jwt ? "" : auth.access) + return { ...s, site, base: s.base || SITES[site].base, key, device: s.device || (key ? keyDevice(key) : anyDevice) } } if (auth?.type === "api") { const site = siteOf(auth.metadata?.site) - return { site, base: SITES[site].base, key: String(auth.key ?? "").trim(), device: anyDevice } + const key = String(auth.key ?? "").trim() + return { site, base: SITES[site].base, key, device: key ? keyDevice(key) : anyDevice } } return null } @@ -1764,7 +1772,32 @@ function dress(text, site, device, place) { } if (Array.isArray(b.tools)) for (const t of b.tools) if (t && typeof t === "object") delete t.cache_control const meta = b.metadata && typeof b.metadata === "object" ? b.metadata : {} - b.metadata = { ...meta, user_id: JSON.stringify({ device_id: device, account_uuid: "", session_id: "" }) } + b.metadata = { ...meta, user_id: userIdOf(device) } + return JSON.stringify(b) +} + +// userIdOf is metadata.user_id as ZCode's client (3.14.3, glm/zcode.cjs +// MLs and vWr) puts it on every Anthropic-format request, a coding plan's +// too: the machine's device id, no account uuid. The plan's endpoint keeps +// a prompt cache on the machine it picks by it, so a request without it +// lands anywhere and its cache is mostly missed (#387). +const userIdOf = (device) => JSON.stringify({ device_id: device, account_uuid: "", session_id: "" }) + +// marked is a coding plan's Messages request body with metadata.user_id +// as ZCode sends it, when the agent sent none of its own. Anything else, +// a body that isn't a Messages request among them, goes as it is. +function marked(text, device) { + if (typeof text !== "string" || !device || !text.includes("messages")) return text + let b + try { + b = JSON.parse(text) + } catch { + return text + } + if (!b || typeof b !== "object" || Array.isArray(b) || !Array.isArray(b.messages)) return text + const meta = b.metadata && typeof b.metadata === "object" && !Array.isArray(b.metadata) ? b.metadata : {} + if (typeof meta.user_id === "string" && meta.user_id.trim()) return text + b.metadata = { ...meta, user_id: userIdOf(device) } return JSON.stringify(b) } @@ -1917,6 +1950,15 @@ export async function ZCodeAuthPlugin({ client }) { } else { if (!key) throw new Error("ZCode's sign-in has no key; sign in again") swap(s.base) + // a Messages request names the device, as ZCode's does (#387); + // count_tokens and other paths ZCode never sends go as they are + if (opts.body != null && /\/v1\/messages$/.test(new URL(url).pathname)) { + const text = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text() + const next = marked(text, s.device) + if (next !== text) h.delete("content-length") + opts.body = next + delete opts.duplex + } if (renamed) h.delete("content-length") h.delete("authorization") h.set("x-api-key", key) @@ -2070,4 +2112,4 @@ export async function ZCodeAuthPlugin({ client }) { // config sets what zcodeConfig has read, for tests: null is ZCode's config // out of reach, undefined forgets it const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() }) -export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT } +export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT, marked, keyDevice } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index c69ffee..2466f02 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.29", + "version": "0.1.30", "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/start.test.mjs b/packages/zcode/start.test.mjs index a6ac802..f9f798a 100644 --- a/packages/zcode/start.test.mjs +++ b/packages/zcode/start.test.mjs @@ -4,7 +4,8 @@ // (#343), the day in a // turn of its own, one cache mark in the turns, none on // the tools and the sign-in's device id in metadata.user_id. A GLM Coding -// Plan or team request goes as the agent sent it. The requests go to a +// Plan or team request goes as the agent sent it, but for that device id, +// which ZCode puts on every request (#387). The requests go to a // local Bun.serve that records them; nothing reaches z.ai or bigmodel. import { afterAll, afterEach, beforeAll, expect, test } from "bun:test" import { createHash } from "node:crypto" @@ -12,13 +13,13 @@ import { arch, homedir, release, tmpdir } from "node:os" import { basename } from "node:path" import { realpathSync } from "node:fs" -let ZCodeAuthPlugin, PROMPT +let ZCodeAuthPlugin, PROMPT, _internal let server const got = [] let answer = null // what the fake answers instead, when set 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")) + ;({ ZCodeAuthPlugin, _internal } = await import("./index.mjs")) PROMPT = (await import("./prompt.mjs")).default server = Bun.serve({ port: 0, @@ -359,14 +360,20 @@ test("magpie's word on the folder goes to no vendor on a Coding Plan request eit await send({ type: "api", key: "one.secret", metadata: { site: "zai" } }, agentText, { place: { dir: "%2Fx", git: "no" } }), "one.secret", "/api.z.ai/api/anthropic/v1/messages", + _internal.keyDevice("one.secret"), ) }) -// the GLM Coding Plan and team seats: as the agent sent it, as 0.1.6 sent it +// the GLM Coding Plan and team seats: as the agent sent it, as 0.1.6 sent +// it, but for metadata.user_id naming the account's device as ZCode's +// client does on every plan (#387) const agentText = JSON.stringify(agentBody) -const sentAsIs = (r, key, path) => { +const sentAsIs = (r, key, path, device) => { expect(r.path).toBe(path) - expect(r.body).toBe(agentText) + const b = JSON.parse(r.body) + expect(JSON.parse(b.metadata.user_id)).toEqual({ device_id: device, account_uuid: "", session_id: "" }) + delete b.metadata.user_id + expect(b).toEqual(agentBody) expect(own(r.headers)).toEqual({ authorization: "Bearer " + key, "x-api-key": key, @@ -377,19 +384,19 @@ const sentAsIs = (r, key, path) => { } test("a GLM Coding Plan key's request goes as the agent sent it", async () => { - sentAsIs(await send({ type: "api", key: "one.secret", metadata: { site: "zai" } }, agentText), "one.secret", "/api.z.ai/api/anthropic/v1/messages") + sentAsIs(await send({ type: "api", key: "one.secret", metadata: { site: "zai" } }, agentText), "one.secret", "/api.z.ai/api/anthropic/v1/messages", _internal.keyDevice("one.secret")) got.length = 0 - sentAsIs(await send({ type: "api", key: "two.secret", metadata: { site: "bigmodel" } }, agentText, { url: "https://open.bigmodel.cn/api/anthropic/v1/messages" }), "two.secret", "/open.bigmodel.cn/api/anthropic/v1/messages") + sentAsIs(await send({ type: "api", key: "two.secret", metadata: { site: "bigmodel" } }, agentText, { url: "https://open.bigmodel.cn/api/anthropic/v1/messages" }), "two.secret", "/open.bigmodel.cn/api/anthropic/v1/messages", _internal.keyDevice("two.secret")) }) test("a team seat's request goes as the agent sent it, ZCode's token or not", async () => { const s = { site: "zai", base: "https://api.z.ai/api/anthropic", key: "seat.secret", token: "tok", org: "o1", project: "p1", jwt, device: DEVICE } const auth = { type: "oauth", access: s.key, refresh: JSON.stringify(s), expires: 0 } - sentAsIs(await send(auth, agentText, { requests: 2 }), "seat.secret", "/api.z.ai/api/anthropic/v1/messages") + sentAsIs(await send(auth, agentText, { requests: 2 }), "seat.secret", "/api.z.ai/api/anthropic/v1/messages", DEVICE) expect(got.filter((r) => r.path.endsWith("/billing/balance"))).toHaveLength(1) expect(got.filter((r) => r.path.endsWith("/subscription/list"))).toHaveLength(0) got.length = 0 - sentAsIs(await send({ ...auth, refresh: JSON.stringify({ ...s, jwt: "" }) }, agentText), "seat.secret", "/api.z.ai/api/anthropic/v1/messages") + sentAsIs(await send({ ...auth, refresh: JSON.stringify({ ...s, jwt: "" }) }, agentText), "seat.secret", "/api.z.ai/api/anthropic/v1/messages", DEVICE) expect(got).toHaveLength(1) }) diff --git a/packages/zcode/toolsearch.test.mjs b/packages/zcode/toolsearch.test.mjs index 257c7bc..9023a99 100644 --- a/packages/zcode/toolsearch.test.mjs +++ b/packages/zcode/toolsearch.test.mjs @@ -120,6 +120,10 @@ test("a request without Claude Code's search goes as the agent sent it", async ( body.tools = body.tools.filter((t) => t.name !== "ToolSearch") body.messages = body.messages.slice(0, 2) const { sent } = await send(coding, body) + // but for the device ZCode names on every request (#387) + expect(typeof sent.metadata?.user_id).toBe("string") + delete sent.metadata.user_id + if (!Object.keys(sent.metadata).length && !body.metadata) delete sent.metadata expect(sent).toEqual(body) }) diff --git a/packages/zcode/userid.test.mjs b/packages/zcode/userid.test.mjs new file mode 100644 index 0000000..9ccc882 --- /dev/null +++ b/packages/zcode/userid.test.mjs @@ -0,0 +1,117 @@ +// A coding plan's requests name the device in metadata.user_id, as ZCode's +// client (3.14.3, glm/zcode.cjs MLs and vWr) does on every Anthropic-format +// request, not on the Start Plan's alone (#387, wendyeq): BigModel's +// endpoint keeps a prompt cache on the machine it picks by it, and Pi's +// requests without it hit the cache 1 time in 19. The requests go to a +// local Bun.serve that records them; nothing reaches z.ai or bigmodel.cn. +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 = [] +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() }) + 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 +}) + +const DEVICE = "11111111-2222-4333-8444-555555555555" +// a BigModel coding plan sign-in, its device saved with it +const signedIn = { type: "oauth", access: "id.secret", refresh: JSON.stringify({ site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", key: "id.secret", device: DEVICE }), expires: 0 } +// an API key the user pasted, with no sign-in behind it +const pasted = { type: "api", key: "id.pasted", metadata: { site: "bigmodel" } } + +async function send(auth, body, path = "/v1/messages") { + routeToFake() + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth, { id: "zcode" }) + const text = typeof body === "string" ? body : JSON.stringify(body) + const headers = { "content-type": "application/json", "x-api-key": "zcode", "anthropic-version": "2023-06-01", "content-length": String(Buffer.byteLength(text)) } + await opts.fetch("https://open.bigmodel.cn/api/anthropic" + path, { method: "POST", headers, body: text }) + expect(got.length).toBe(1) + return { body: got[0].body, path: got[0].path } +} + +// Pi's request, as it reached magpie: no metadata +const pi = () => ({ + model: "GLM-5.3-Flash", + max_tokens: 16000, + stream: true, + system: [{ type: "text", text: "You are Pi.", cache_control: { type: "ephemeral" } }], + messages: [{ role: "user", content: [{ type: "text", text: "hello", cache_control: { type: "ephemeral" } }] }], +}) +const userIdOf = (b) => JSON.parse(JSON.parse(b).metadata.user_id) + +test("a coding plan's Messages request names the sign-in's device, as ZCode's does", async () => { + const { body, path } = await send(signedIn, pi()) + expect(path).toBe("/open.bigmodel.cn/api/anthropic/v1/messages") + expect(userIdOf(body)).toEqual({ device_id: DEVICE, account_uuid: "", session_id: "" }) + // the rest of the request is the agent's, as it sent it + const b = JSON.parse(body) + delete b.metadata + expect(b).toEqual(pi()) +}) + +test("every request of one account names the same device", async () => { + const a = userIdOf((await send(signedIn, pi())).body) + got.length = 0 + const b = userIdOf((await send(signedIn, { ...pi(), messages: [...pi().messages, { role: "assistant", content: "hi" }, { role: "user", content: "again" }] })).body) + expect(a).toEqual(b) +}) + +test("a pasted key's device is the same on every start, and its own", () => { + const { keyDevice, stateOf } = require("./index.mjs")._internal + expect(stateOf(pasted).device).toBe(keyDevice("id.pasted")) + expect(stateOf(pasted).device).toBe(stateOf({ ...pasted }).device) + expect(stateOf({ ...pasted, key: "id.other" }).device).not.toBe(stateOf(pasted).device) + expect(keyDevice("id.pasted")).toMatch(/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/) + // a sign-in's saved device wins + expect(stateOf(signedIn).device).toBe(DEVICE) +}) + +test("a pasted key's request names its device too", async () => { + const { keyDevice } = require("./index.mjs")._internal + const { body } = await send(pasted, pi()) + expect(userIdOf(body).device_id).toBe(keyDevice("id.pasted")) +}) + +test("an agent's own user_id and other metadata are kept", async () => { + const own = JSON.stringify({ device_id: "cc", account_uuid: "x", session_id: "s" }) + const { body } = await send(signedIn, { ...pi(), metadata: { user_id: own } }) + expect(JSON.parse(body).metadata).toEqual({ user_id: own }) + got.length = 0 + const other = await send(signedIn, { ...pi(), metadata: { trace: "t" } }) + expect(JSON.parse(other.body).metadata.trace).toBe("t") + expect(userIdOf(other.body).device_id).toBe(DEVICE) +}) + +test("count_tokens and a body that isn't a Messages request go as they are", async () => { + const counted = JSON.stringify({ model: "GLM-5.3-Flash", messages: [{ role: "user", content: "hi" }] }) + expect((await send(signedIn, counted, "/v1/messages/count_tokens")).body).toBe(counted) + got.length = 0 + expect((await send(signedIn, "not json, messages")).body).toBe("not json, messages") +})