diff --git a/packages/zcode/README.md b/packages/zcode/README.md index c292bd5..f2348cb 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -165,6 +165,8 @@ keeps the plain models on the plan. The JSON below still works, and a `freeFirst: false` there keeps it off whatever the switch says. Turn it off for the whole plugin in magpie's Plugins › Options +Since 0.1.59 a reply the gift answered says its model as the picker lists it (`GLM-5.3-Flash-Trial`), whether free first or a `-Trial` pick sent the request, so the Usage page, the sessions and the request log show which route spent the turn; a reply the coding plan answered, a free-first replay among them, keeps the plan's name. + ```json { "freeFirst": false } ``` diff --git a/packages/zcode/dual.test.mjs b/packages/zcode/dual.test.mjs index 4f83e37..17bcbb5 100644 --- a/packages/zcode/dual.test.mjs +++ b/packages/zcode/dual.test.mjs @@ -977,3 +977,48 @@ test("a card read reads the route again", async () => { expect(u.windows[0].used).toBe(10) expect(_internal.routes.get(id)).toMatchObject({ start: false, gift: { models: ["glm-5.3-flash"] } }) }) + +// The gift answers under the plain model's name, as the coding plan does, so +// the Usage page, the sessions and the request log named the plan's model +// whichever route served the turn. The gift's answer says the -Trial entry +// the picker lists; the plan's stays as it came (WJaunita45604 on X). +const msg = (model) => ({ id: "msg_1", type: "message", role: "assistant", model, content: [], usage: { input_tokens: 1, output_tokens: 1 } }) +const json = (v) => new Response(JSON.stringify(v), { status: 200, headers: { "content-type": "application/json" } }) +const sse = (model) => + new Response( + `event: message_start\ndata: ${JSON.stringify({ type: "message_start", message: msg(model) })}\n\n` + + `event: content_block_delta\ndata: ${JSON.stringify({ type: "content_block_delta", delta: { type: "text_delta", text: "a \"model\" word" } })}\n\n`, + { status: 200, headers: { "content-type": "text/event-stream" } }, + ) + +test("free first's answer from the gift names the -Trial entry, in a whole reply and in a stream", async () => { + planAndBalance() + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" })) + const ask = () => opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = json(msg("glm-5.3-flash")) + const whole = await ask() + expect(sent.at(-1).origin).toBe("https://zcode.z.ai") + expect((await whole.json()).model).toBe("GLM-5.3-Flash-Trial") + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = sse("GLM-5.3-Flash") + const text = await (await ask()).text() + expect(text).toContain('"model":"GLM-5.3-Flash-Trial"') + // the model's own words are not touched + expect(text).toContain('a \\"model\\" word') +}) + +test("a -Trial pick's answer names the -Trial entry too", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = json(msg("glm-5.3-flash")) + const res = await sendTo(MSG, body("GLM-5.3-Flash-Trial")) + expect((await res.json()).model).toBe("GLM-5.3-Flash-Trial") +}) + +test("free first's answer from the coding plan keeps the plan's model name", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ error: { message: "nope" } }), { status: 500, headers: { "content-type": "application/json" } }) + answers["/api/anthropic/v1/messages"] = json(msg("glm-5.3-flash")) + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" })) + const res = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(sent.at(-1).origin).toBe("https://api.z.ai") + expect((await res.json()).model).toBe("glm-5.3-flash") +}) diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index eeecfa0..35affe1 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -2575,6 +2575,69 @@ function searchNamed(res) { }) } +// trialNamed is a gift's answer with its model said as the picker lists it +// (GLM-5.3-Flash-Trial): the gift answers under the plain name, as the coding +// plan does, so the Usage page, the sessions and the request log named the +// plan's model whichever route served it, and a user with free first on +// could not tell whether the free quota was spent (WJaunita45604 on X). A +// failed answer, or a body that is not JSON or an event stream, goes on as it +// came. +function trialNamed(res, name) { + if (!res.body || res.status >= 400) return res + const type = res.headers.get("content-type") ?? "" + const set = (d) => { + if (d && typeof d === "object") { + if (typeof d.model === "string") d.model = name + if (typeof d.message?.model === "string") d.message.model = name + return true + } + return false + } + const line = (l) => { + if (!l.startsWith("data:") || !l.includes('"model"')) return l + try { + const d = JSON.parse(l.slice(5)) + return set(d) ? "data: " + JSON.stringify(d) : l + } catch { + return l + } + } + const h = new Headers(res.headers) + 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: h }) + } + if (!type.includes("json")) return res + return res.text().then((text) => { + let out = text + if (text.includes('"model"')) { + try { + const v = JSON.parse(text) + if (set(v)) out = JSON.stringify(v) + } catch {} + } + h.delete("content-length") + return new Response(out, { status: res.status, statusText: res.statusText, headers: h }) + }) +} + // 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. @@ -2917,9 +2980,15 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { // says it is spent can spend nothing and replay what was asked for let start = alone let orig, forcedGift = false, freeGift = false + // the gift's -Trial name while the gift is the route that answers + // (a free-first request replayed on the plan clears it) + let giftName = "" let asked = "" let renamed = false - const done = (res) => (renamed ? searchNamed(res) : res) + const done = (res) => { + if (giftName) res = trialNamed(res, giftName) + return 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 @@ -2943,6 +3012,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) }) m = raw forcedGift = true + giftName = giftID(raw) } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) { // free first: the plain model spends the account's own live // gift before it spends the coding plan, under the name the @@ -2962,6 +3032,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) }) m = raw freeGift = true + giftName = giftID(raw) } start = alone || forcedGift || freeGift } @@ -2994,6 +3065,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { const replayOnPlan = async () => { // the gift is done with: its slot goes to the next request own.slot?.release() + giftName = "" let u = askedUrl for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) { if (u.startsWith(b)) { diff --git a/packages/zcode/package.json b/packages/zcode/package.json index 26e59c7..05cd3d2 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.58", + "version": "0.1.59", "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, and claims its gift plans daily", "type": "module", "main": "./opencode.mjs",