From 2b56b3bc4f4abbcc68a7a1c3dc350605fa8a7352 Mon Sep 17 00:00:00 2001 From: wendyeq Date: Mon, 26 Oct 2026 16:02:38 +0800 Subject: [PATCH] zcode: name the conversation in x-session-id as a bare UUID, so BigModel's prompt cache hits (#388) ZCode's client names every request's conversation in x-session-id: a bare UUID, the same on each turn (3.14.3 xst/Tst). BigModel keeps a prompt's cache for the requests that name the same session. The plugin sent none, so a long conversation seldom hit the cache (#387). Every zcode request, on the Start Plan and on Coding Plan or team seats alike, now carries it: - the agent's session (chat.headers' sessionID, which magpie fills) goes as it is when it is a UUID, lower-cased; - any other id (magpie-, ses_..., sess_...) goes as a stable UUID made from its sha256; - with no session, a UUID made from the device. metadata.user_id's session_id is the same UUID, in dress() and marked(). Reviewed at 48013c0, which addresses all four points of the earlier review (UUID shape, session_id in user_id, rebase onto 0.1.30, no "Closes #387"): - TMPDIR= HOME=$(mktemp -d) bun test in packages/zcode: 125 pass, 0 fail. bun scripts/check.mjs zcode passes. Merges cleanly onto main. - With main's index.mjs and the PR's tests: 17 fail (all 7 new session tests, plus the start, userid and dual assertions on the header). - Probe through the plugin's chat.headers and loader fetch, as magpie's host calls them (host.js passes sessionID and sets out.headers before the fetch): magpie- twice gives the same UUID in the header and in user_id.session_id, and ses_other gives a different UUID. None contains magpie, ses_ or sess_. Not tried: a real BigModel request (the author's hit-rate numbers are the evidence: 3/12 before, 24/24 after through magpie). --- packages/zcode/README.md | 11 +++- packages/zcode/dual.test.mjs | 6 +- packages/zcode/index.mjs | 56 ++++++++++++---- packages/zcode/session.test.mjs | 109 ++++++++++++++++++++++++++++++++ packages/zcode/start.test.mjs | 26 +++++--- packages/zcode/userid.test.mjs | 4 +- 6 files changed, 185 insertions(+), 27 deletions(-) create mode 100644 packages/zcode/session.test.mjs diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 0d22e84..df29079 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -30,7 +30,8 @@ over Anthropic's Messages API. Provider id: `zcode`. 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 + same on every start. Every request also carries the `x-session-id` + header below. 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 @@ -40,6 +41,14 @@ over Anthropic's Messages API. Provider id: `zcode`. firewall says this network's address was blocked instead. - The Start Plan's token can't be refreshed. When it runs out, sign in again. + - Every request, on any plan, names its conversation in `x-session-id`, + as ZCode does: a bare UUID, the same on each turn. BigModel's prompt + cache follows it: without it a long conversation's turns hit the cache + about one time in twenty, with it nearly every turn (#387). The + agent's own session id (magpie tells it to the plugin) goes as it is + when it is a UUID, else as a UUID made from it, so the vendor sees + only ZCode's format; with none, a UUID made from the device. The same + id is `metadata.user_id`'s `session_id`, as in ZCode's requests. - **ZCode: a team's GLM Coding Plan** - For an account with a plan of its own and a seat on a team's plan (#285). The sign-ins above take the account's own plan, as ZCode does diff --git a/packages/zcode/dual.test.mjs b/packages/zcode/dual.test.mjs index df5213b..03dc9ba 100644 --- a/packages/zcode/dual.test.mjs +++ b/packages/zcode/dual.test.mjs @@ -246,8 +246,10 @@ 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") - // 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: "" }) } }) + // as sent, but for the sign-in's device and the conversation, as ZCode names them (#387) + const session = _internal.sessionOf("", DEVICE) + expect(m.headers["x-session-id"]).toBe(session) + expect(JSON.parse(m.body)).toEqual({ ...JSON.parse(body("GLM-5.3")), metadata: { user_id: JSON.stringify({ device_id: DEVICE, account_uuid: "", session_id: session }) } }) 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 f7e8308..3684a3c 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -50,12 +50,15 @@ 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") +// uuidOf is a version 4 shaped UUID made from a seed: the same seed gives +// the same UUID every time +const uuidOf = (seed) => { + const h = createHash("sha256").update(seed).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)}` } +// 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) => uuidOf("zcode-device\0" + key) 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 @@ -1732,7 +1735,7 @@ function contextPrefix() { // sign-in's device. site names the powered-by line's provider, place where // the agent works (workPlace). A body that isn't a Messages request goes as // it is. -function dress(text, site, device, place) { +function dress(text, site, device, place, session) { if (typeof text !== "string" || !text.includes("messages")) return text let b try { @@ -1772,7 +1775,7 @@ 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: userIdOf(device) } + b.metadata = { ...meta, user_id: userIdOf(device, session) } return JSON.stringify(b) } @@ -1780,13 +1783,14 @@ function dress(text, site, device, place) { // 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: "" }) +// lands anywhere and its cache is mostly missed (#387). Its session_id is +// the request's x-session-id (sessionOf), as ZCode's is. +const userIdOf = (device, session = "") => JSON.stringify({ device_id: device, account_uuid: "", session_id: session }) // 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) { +function marked(text, device, session) { if (typeof text !== "string" || !device || !text.includes("messages")) return text let b try { @@ -1797,10 +1801,25 @@ function marked(text, device) { 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) } + b.metadata = { ...meta, user_id: userIdOf(device, session) } return JSON.stringify(b) } +// sessionOf is the x-session-id a request goes with, as ZCode's client +// (3.14.3, glm/zcode.cjs xst and Tst) sends it: a bare UUID, the same on +// every turn of a conversation. BigModel keeps a prompt's cache for the +// requests that name the same session and seldom for those that name none +// (#387). The agent's session (chat.headers below) goes as it is when it is +// a UUID, else as a UUID made from it, so the vendor sees only ZCode's +// format, never magpie's or another agent's; with none, a UUID made from +// the device. +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i +function sessionOf(id, device) { + const own = typeof id === "string" ? id.trim() : "" + if (UUID.test(own)) return own.toLowerCase() + return uuidOf(own ? "zcode-session\0" + own : "zcode-session-device\0" + (device ?? "")) +} + // ---- the plugin ------------------------------------------------------------------ export async function ZCodeAuthPlugin({ client }) { @@ -1815,6 +1834,14 @@ export async function ZCodeAuthPlugin({ client }) { authorize: () => authorize(site, log), }) return { + // the agent's session, which magpie tells the plugins here and not + // in the request, goes on as x-session-id (sessionOf) + "chat.headers": async (input, output) => { + const provider = input?.model?.providerID ?? input?.provider?.info?.id + if (provider !== PROVIDER) return + const id = input?.sessionID + if (typeof id === "string" && id.trim()) output.headers["x-session-id"] = sessionOf(id) + }, config: async (cfg) => { cfg.provider ??= {} const was = cfg.provider[PROVIDER] ?? {} @@ -1934,6 +1961,7 @@ export async function ZCodeAuthPlugin({ client }) { } let h = new Headers(opts.headers) const place = workPlace(h) + const sid = sessionOf(h.get("x-session-id"), s.device) if (start) { if (jwtExpired(s.jwt)) throw new Error(EXPIRED) if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again") @@ -1941,9 +1969,10 @@ export async function ZCodeAuthPlugin({ client }) { // the Start Plan is served only to what looks like ZCode's own request url = startURL(url) h = startHeaders(h, s.jwt) + h.set("x-session-id", sid) if (opts.body != null) { const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()) - opts.body = dress(text, s.site, s.device, place) + opts.body = dress(text, s.site, s.device, place, sid) delete opts.duplex h.delete("content-length") } @@ -1954,12 +1983,13 @@ export async function ZCodeAuthPlugin({ client }) { // 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) + const next = marked(text, s.device, sid) if (next !== text) h.delete("content-length") opts.body = next delete opts.duplex } if (renamed) h.delete("content-length") + h.set("x-session-id", sid) h.delete("authorization") h.set("x-api-key", key) h.set("Authorization", "Bearer " + key) @@ -2112,4 +2142,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, marked, keyDevice } +export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, dress, PROMPT, marked, keyDevice, sessionOf } diff --git a/packages/zcode/session.test.mjs b/packages/zcode/session.test.mjs new file mode 100644 index 0000000..0a76f9a --- /dev/null +++ b/packages/zcode/session.test.mjs @@ -0,0 +1,109 @@ +// Every request names its conversation in x-session-id, as ZCode's client +// (3.14.3, glm/zcode.cjs xst and Tst) does: a bare UUID, the same on each +// turn. BigModel's prompt cache follows it (#387). The agent's session +// comes through chat.headers: a UUID goes as it is, anything else, magpie's +// own magpie- among them, as a UUID made from it; with none, a UUID +// made from the device. metadata.user_id's session_id is the same UUID. +// Nothing leaves the machine: the plugin's fetch is the fake here. +import { afterEach, beforeEach, expect, test } from "bun:test" +import { homedir, tmpdir } from "node:os" +import { realpathSync } from "node:fs" + +if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test") +const { ZCodeAuthPlugin, _internal } = await import("./index.mjs") + +const jwt = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig" +const DEVICE = "11111111-2222-4333-8444-555555555555" +const KEY = "session.secret" +const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/ +const AGENT = "01A17286-ABCD-4EF0-9123-456789ABCDEF" // Claude Code's kind of session +const coding = { type: "oauth", access: KEY, refresh: JSON.stringify({ site: "bigmodel", base: "https://open.bigmodel.cn/api/anthropic", key: KEY, device: DEVICE, plan: "GLM Coding Pro" }), expires: 0 } +const start = { type: "oauth", access: jwt, refresh: JSON.stringify({ site: "zai", base: "https://api.z.ai/api/anthropic", jwt, device: DEVICE }), expires: 0 } + +const sent = [] +const real = globalThis.fetch +beforeEach(() => { + _internal.routes.clear() + sent.length = 0 + globalThis.fetch = async (input, init = {}) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + sent.push({ origin: url.origin, path: url.pathname, headers: Object.fromEntries(new Headers(init.headers ?? {})), body: init.body }) + if (url.pathname.endsWith("/messages")) return new Response(JSON.stringify({ type: "message", content: [] }), { headers: { "content-type": "application/json" } }) + if (url.pathname === "/api/biz/subscription/list") return new Response(JSON.stringify({ code: 0, data: [{ productName: "GLM Coding Pro", status: "VALID" }] })) + return new Response("", { status: 404 }) + } +}) +afterEach(() => (globalThis.fetch = real)) + +const plugin = async () => ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) +const body = JSON.stringify({ model: "glm-5.3-flash", max_tokens: 100, messages: [{ role: "user", content: "hi" }] }) +async function send(auth, url, headers = {}) { + const opts = await (await plugin()).auth.loader(async () => auth, { id: "zcode" }) + return opts.fetch(url, { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode", ...headers }, body }) +} +const message = () => sent.filter((c) => c.path.endsWith("/messages")).at(-1) +const sessionIn = (m) => JSON.parse(JSON.parse(m.body).metadata.user_id).session_id +const CODING = "https://open.bigmodel.cn/api/anthropic/v1/messages" +const hook = async (sessionID, providerID = "zcode") => { + const out = { headers: {} } + await (await plugin())["chat.headers"]({ sessionID, model: { providerID } }, out) + return out.headers +} + +test("an agent's UUID session goes as it is, in lower case", async () => { + expect(await hook(AGENT)).toEqual({ "x-session-id": AGENT.toLowerCase() }) + expect(_internal.sessionOf(AGENT, DEVICE)).toBe(AGENT.toLowerCase()) +}) + +test("any other session goes as a UUID made from it, the same every time", async () => { + for (const id of ["magpie-0123456789abcdef01234567", "ses_3f2a9c1b7e", "sess_abc", "a b/c"]) { + const sid = (await hook(id))["x-session-id"] + expect(sid).toMatch(UUID) + expect(sid).not.toMatch(/magpie|ses_|sess_/) + expect(await hook(id)).toEqual({ "x-session-id": sid }) + expect(_internal.sessionOf(sid)).toBe(sid) // a UUID made once stays as it is + } + expect(_internal.sessionOf("magpie-a")).not.toBe(_internal.sessionOf("magpie-b")) +}) + +test("chat.headers names a session for zcode only, and only when there is one", async () => { + expect(await hook(AGENT, "openai")).toEqual({}) + expect(await hook("")).toEqual({}) + expect(await hook(undefined)).toEqual({}) +}) + +test("a coding plan request keeps the agent's session, in the header and metadata.user_id alike", async () => { + await send(coding, CODING, { "x-session-id": AGENT.toLowerCase() }) + expect(message().headers["x-session-id"]).toBe(AGENT.toLowerCase()) + // the body goes as sent, but for metadata.user_id naming the device and the session (#387) + const b = JSON.parse(message().body) + expect(JSON.parse(b.metadata.user_id)).toEqual({ device_id: DEVICE, account_uuid: "", session_id: AGENT.toLowerCase() }) + delete b.metadata + expect(b).toEqual(JSON.parse(body)) +}) + +test("a session that reaches the request unmapped goes as its UUID too", async () => { + await send(coding, CODING, { "x-session-id": "magpie-0123456789abcdef01234567" }) + const sid = message().headers["x-session-id"] + expect(sid).toBe(_internal.sessionOf("magpie-0123456789abcdef01234567")) + expect(sessionIn(message())).toBe(sid) +}) + +test("a coding plan request with no session names a UUID made from the device", async () => { + await send(coding, CODING) + const first = message().headers["x-session-id"] + expect(first).toMatch(UUID) + expect(first).not.toBe(DEVICE) + expect(first).not.toContain(DEVICE) + expect(sessionIn(message())).toBe(first) + await send(coding, CODING) + expect(message().headers["x-session-id"]).toBe(first) +}) + +test("a Start Plan request carries the session in the header and metadata.user_id alike", async () => { + _internal.routes.set("\0" + jwt, { start: true, gift: null, at: Date.now(), ttl: 600_000 }) + await send(start, "https://api.z.ai/api/anthropic/v1/messages", { "x-session-id": AGENT }) + expect(message().origin).toBe("https://zcode.z.ai") + expect(message().headers["x-session-id"]).toBe(AGENT.toLowerCase()) + expect(sessionIn(message())).toBe(AGENT.toLowerCase()) +}) diff --git a/packages/zcode/start.test.mjs b/packages/zcode/start.test.mjs index f9f798a..10aef18 100644 --- a/packages/zcode/start.test.mjs +++ b/packages/zcode/start.test.mjs @@ -119,7 +119,8 @@ const reminder = { }, ], } -const userID = JSON.stringify({ device_id: DEVICE, account_uuid: "", session_id: "" }) +// the device, and the conversation as x-session-id names it; the agent named none +const userID = () => JSON.stringify({ device_id: DEVICE, account_uuid: "", session_id: _internal.sessionOf("", DEVICE) }) // a request as OpenCode's @ai-sdk/anthropic makes one, cache marks and all const agentBody = { @@ -215,6 +216,8 @@ test("a Start Plan request carries ZCode's headers, and only those", async () => "x-zcode-session-type": "main", "x-zcode-trace-id": h["x-zcode-trace-id"], "x-zcode-query-source": "main_turn", + // the conversation, as ZCode names it; the agent told none (#387) + "x-session-id": _internal.sessionOf("", DEVICE), }) expect(h["x-api-key"]).toBeUndefined() expect(h["x-device-mid"]).toBeUndefined() @@ -250,7 +253,7 @@ test("a Start Plan request from Claude Code goes with ZCode's headers alone, wit const h = own(r.headers) for (const k of Object.keys(CLAUDE_CODE)) if (!TRANSPORT.has(k)) expect(h[k]).toBeUndefined() expect(Object.keys(h).sort()).toEqual( - ["authorization", "anthropic-version", "content-type", "http-referer", "user-agent", "x-zcode-app-version", "x-title", "x-release-channel", "x-client-language", "x-client-timezone", "x-zcode-agent", "x-platform", "x-os-category", "x-os-version", "x-request-id", "x-zcode-session-type", "x-zcode-trace-id", "x-zcode-query-source"].sort(), + ["authorization", "anthropic-version", "content-type", "http-referer", "user-agent", "x-zcode-app-version", "x-title", "x-release-channel", "x-client-language", "x-client-timezone", "x-zcode-agent", "x-platform", "x-os-category", "x-os-version", "x-request-id", "x-zcode-session-type", "x-zcode-trace-id", "x-zcode-query-source", "x-session-id"].sort(), ) expect(r.headers.accept).not.toBe(CLAUDE_CODE.accept) } @@ -277,7 +280,7 @@ test("a Start Plan request's body is dressed as ZCode's", async () => { { role: "user", content: [{ type: "tool_result", tool_use_id: "t1", content: "x" }, { type: "text", text: "and now?", cache_control: eph }] }, ], tools: [{ name: "read", description: "Read a file", input_schema: { type: "object" } }], - metadata: { other: "kept", user_id: userID }, + metadata: { other: "kept", user_id: userID() }, stream: true, }) // the blocks' texts, by the plugin's hashes @@ -287,7 +290,7 @@ test("a Start Plan request's body is dressed as ZCode's", async () => { expect(dyn.startsWith("\n\n" + PROMPT.beforeEnvironment + "\n\n# Environment\n")).toBe(true) expect(dyn.endsWith("\n\n" + PROMPT.afterEnvironment + "\n\nYou are opencode, an agent.\n\nProject instructions.")).toBe(true) expect(sha(dyn.slice(2, 2 + 3065))).toBe("bbdc66b399d297ff") - expect(JSON.parse(b.metadata.user_id)).toEqual({ device_id: DEVICE, account_uuid: "", session_id: "" }) + expect(b.metadata.user_id).toBe(userID()) // exactly one cache mark in the turns, and none on the tools expect((r.body.match(/cache_control/g) ?? []).length).toBe(4) }) @@ -301,7 +304,7 @@ test("a BigModel sign-in's Start Plan names bigmodel-api; a string turn takes th max_tokens: 100, system: zcodeSystem("bigmodel-api/GLM-5.2", undefined, [" Be brief. "]), messages: [reminder, { role: "user", content: [{ type: "text", text: "hello", cache_control: eph }] }], - metadata: { user_id: userID }, + metadata: { user_id: userID() }, }) }) @@ -310,7 +313,7 @@ test("a Start Plan body with no model has no powered-by line; a blank system add expect(JSON.parse(r.body)).toEqual({ system: zcodeSystem(""), messages: [reminder, { role: "user", content: [{ type: "text", text: "x", cache_control: eph }] }], - metadata: { user_id: userID }, + metadata: { user_id: userID() }, }) }) @@ -365,16 +368,19 @@ test("magpie's word on the folder goes to no vendor on a Coding Plan request eit }) // 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) +// it, but for metadata.user_id naming the account's device and x-session-id +// the conversation, one UUID in both, as ZCode's client does on every plan +// (#387); the agent named no session, so it is the device's const agentText = JSON.stringify(agentBody) const sentAsIs = (r, key, path, device) => { expect(r.path).toBe(path) const b = JSON.parse(r.body) - expect(JSON.parse(b.metadata.user_id)).toEqual({ device_id: device, account_uuid: "", session_id: "" }) + const { "x-session-id": sid, ...h } = own(r.headers) + expect(sid).toBe(_internal.sessionOf("", device)) + expect(JSON.parse(b.metadata.user_id)).toEqual({ device_id: device, account_uuid: "", session_id: sid }) delete b.metadata.user_id expect(b).toEqual(agentBody) - expect(own(r.headers)).toEqual({ + expect(h).toEqual({ authorization: "Bearer " + key, "x-api-key": key, "anthropic-version": "2023-06-01", diff --git a/packages/zcode/userid.test.mjs b/packages/zcode/userid.test.mjs index 9ccc882..2a31cf1 100644 --- a/packages/zcode/userid.test.mjs +++ b/packages/zcode/userid.test.mjs @@ -69,7 +69,9 @@ 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: "" }) + const { sessionOf } = require("./index.mjs")._internal + // and the conversation, as x-session-id names it; Pi named none (#387) + expect(userIdOf(body)).toEqual({ device_id: DEVICE, account_uuid: "", session_id: sessionOf("", DEVICE) }) // the rest of the request is the agent's, as it sent it const b = JSON.parse(body) delete b.metadata