From 5a9c7768321ec41477c9da59ccba96c4b1988004 Mon Sep 17 00:00:00 2001 From: Jinpy Date: Fri, 30 Oct 2026 14:27:16 +0800 Subject: [PATCH] zcode 0.1.38: freeFirst, the plain model spends the account's gift first (#505) freeFirst (a boolean plugin or provider option): a plain model request spends the dual account's own live gift first, under the name the gift lists, and falls back to the coding plan when the gift can't serve it. Any gift failure (spent 1113/1005, block page, 4xx/5xx, its own waited-out busy cap, a network throw) is replayed on the plan in the same request with the plan's own busy patience; a caller's abort stays an abort. -Trial entries keep their strict meaning. Off by default. zcode 0.1.38. Run at the reviewed head 7ae2ea15d (on main 7673cd0), on mote (macOS, Bun 1.4.2, temp HOME): `bun test` in packages/zcode 173 pass 0 fail; `bun scripts/check.mjs zcode` ok; `npm pack --dry-run` 4 files (README.md, index.mjs, package.json, prompt.mjs) at 0.1.38. Broken by hand: the gift's catch reduced to `throw e` turns "a gift that cannot be asked at all is answered from the plan" red; the abort guard reduced to `if (!freeGift) throw e` turns both abort tests red (2 fail); the signal check alone removed turns the in-flight abort test red. Reviewer probes (abort before/in flight, gift 3008 then throw, gift and plan both throwing, freeFirst off) behave as intended. Not tried: a real dual account against zcode.z.ai; every case here runs against a fetch fake. Co-authored-by: jinpy666 <5868671+jinpy666@users.noreply.github.com> --- packages/zcode/README.md | 38 +++++ packages/zcode/dual.test.mjs | 323 +++++++++++++++++++++++++++++++++++ packages/zcode/index.mjs | 137 +++++++++++++-- packages/zcode/package.json | 2 +- 4 files changed, 482 insertions(+), 18 deletions(-) diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 511aa8b..6908797 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -134,6 +134,44 @@ plan's own in-flight cap (3008/3009) does not: such a request is asked again instead (see [A few at once](#a-few-at-once)). A stream's body is never read or buffered on the way. +**Free first.** Picking `-Trial` by hand keeps the choice the user's, +but an agent that always asks the plain model never sees the gift. +`freeFirst` turns the preference around: the plain model spends the +account's own live gift first, and falls back to the coding plan when +the gift cannot serve it — a bucket that is spent, a model the gift +does not serve, no ZCode session, or the minute's rest a refusal just +earned. Turn it on for the whole plugin in magpie's Plugins › Options + +```json +{ "freeFirst": true } +``` + +or on the provider alone, under `provider.zcode.options` in the config +magpie hands its plugins — a key only `plugins.json`'s `config` carries, +so the plugin's own options are the ones magpie's Plugins › Options +edits. Where both say something, the provider's word stands. An account +with a coding plan and a gift spends the gift until it is spent, then +the plan; a gift-only account already goes to the gift by its plain +names, so the option changes nothing there. Across the accounts magpie +rotates, each spends its own gift before its own plan — which is the +point: free allowance is spent before subscribed quota, on every +account, with no per-account naming to keep up. + +Two boundaries worth knowing. The gift is judged before the request is +sent, from the balance read the plugin keeps for ten minutes: a gift +that runs out between that read and the send has its refusal answered +from the plan in the same request — any gift failure is, its own +waited-out busy cap included, and the replay waits out the plan's busy +cap as any plan request does — and a spent answer or a block page rests +the model a minute and drops the route's balance read, so the requests +behind it go straight to the plan. A gift that cannot be asked at all — +the network, the host — is answered from the plan the same way, the +route read dropped for the next request, while a caller's own abort +stays an abort. The agent sees the plan's answer +either way. And the `-Trial` entries keep their own strict semantics — +asking one is still an explicit pick of the gift alone, never the plan; +a spent one answers 429 with freeFirst on, as it does without it. + ## A few at once A plan serves one account a few requests at a time; past that, ZCode diff --git a/packages/zcode/dual.test.mjs b/packages/zcode/dual.test.mjs index 4c9290e..725473d 100644 --- a/packages/zcode/dual.test.mjs +++ b/packages/zcode/dual.test.mjs @@ -63,6 +63,329 @@ async function sendTo(url, body) { const MSG = "https://api.z.ai/api/anthropic/v1/messages" const body = (model) => JSON.stringify({ model, max_tokens: 100, messages: [{ role: "user", content: "hi" }] }) +// freeFirst: a plain model spends the account's live gift first, and falls +// back to the coding plan when the gift cannot serve it. The -Trial entries +// keep their own strict semantics; nothing else changes. +const freePlugin = async (options) => (await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }, options)).auth + +test("free first spends the gift on the plain model while it has quota", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + 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(res.status).toBe(200) + expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(0) + const m = sent.at(-1) + expect(m.origin).toBe("https://zcode.z.ai") + expect(m.path).toBe("/api/v1/zcode-plan/anthropic/v1/messages") + expect(m.headers.authorization).toBe("Bearer " + jwt) + expect(m.headers["x-api-key"]).toBeUndefined() + expect(JSON.parse(m.body).model).toBe("glm-5.3-flash") +}) + +test("free first falls back to the coding plan once the gift is spent", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, balances: [{ ...balance.balances[0], remaining_units: 0, used_units: 1000 }] }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + 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(res.status).toBe(200) + // the balance reads go to zcode.z.ai; no message does + expect(sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages"))).toHaveLength(0) + const m = sent.at(-1) + expect(m.origin).toBe("https://api.z.ai") + expect(m.headers["x-api-key"]).toBe(KEY) + expect(JSON.parse(m.body).model).toBe("GLM-5.3-Flash") +}) + +test("free first follows the provider's options, and a blocked model waits on the plan", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const opts = await freePlugin().then((h) => h.loader(async () => coding, { id: "zcode", options: { freeFirst: true } })) + const first = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(first.status).toBe(200) + expect(sent.at(-1).origin).toBe("https://zcode.z.ai") + expect(JSON.parse(sent.at(-1).body).model).toBe("glm-5.3-flash") + // a refusal the gift gave a moment ago (the blocked map) sends the plain + // model to the plan until the minute is out + _internal.blocked.set(KEY + "\0" + jwt + "\0glm-5.3-flash", Date.now() + 60_000) + const second = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(second.status).toBe(200) + expect(sent.at(-1).origin).toBe("https://api.z.ai") + expect(JSON.parse(sent.at(-1).body).model).toBe("GLM-5.3-Flash") +}) + +test("free first leaves a model the gift does not serve on the coding plan", async () => { + planAndBalance() + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + 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.2") }) + expect(res.status).toBe(200) + const m = sent.at(-1) + expect(m.origin).toBe("https://api.z.ai") + expect(JSON.parse(m.body).model).toBe("GLM-5.2") +}) + +test("without freeFirst the plain model goes to the coding plan as before", async () => { + planAndBalance() + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const opts = await freePlugin({ freeFirst: false }).then((h) => h.loader(async () => coding, { id: "zcode", options: {} })) + const res = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(res.status).toBe(200) + expect(sent.at(-1).origin).toBe("https://api.z.ai") + expect(JSON.parse(sent.at(-1).body).model).toBe("GLM-5.3-Flash") +}) + +test("free first with no live gift reads the balance once and stays on the plan", async () => { + answers["/api/biz/subscription/list"] = ok([{ productName: "GLM Coding Pro", status: "VALID" }]) + answers["/api/v1/zcode-plan/billing/balance"] = ok({ server_time: now, plans: [], balances: [] }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" })) + for (let i = 0; i < 3; i++) { + const res = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(res.status).toBe(200) + expect(sent.at(-1).origin).toBe("https://api.z.ai") + } + expect(sent.filter((c) => c.path.endsWith("/billing/balance"))).toHaveLength(1) +}) + +test("free first with a failed balance read stays on the plan", async () => { + answers["/api/biz/subscription/list"] = ok([{ productName: "GLM Coding Pro", status: "VALID" }]) + answers["/api/v1/zcode-plan/billing/balance"] = new Response("", { status: 500 }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" })) + for (let i = 0; i < 3; i++) { + const res = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(res.status).toBe(200) + expect(sent.at(-1).origin).toBe("https://api.z.ai") + } + expect(sent.filter((c) => c.path.endsWith("/billing/balance"))).toHaveLength(1) +}) + +test("free first changes nothing for a gift-only account", async () => { + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const giftOnly = { type: "oauth", access: jwt, refresh: JSON.stringify({ site: "zai", jwt, device: DEVICE }) } + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => giftOnly, { id: "zcode" })) + const res = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(res.status).toBe(200) + expect(sent.filter((c) => c.path.endsWith("/billing/balance"))).toHaveLength(0) + const m = sent.at(-1) + expect(m.origin).toBe("https://zcode.z.ai") + expect(JSON.parse(m.body).model).toBe("GLM-5.3-Flash") +}) + +test("a gift that answers spent is answered from the plan in the same request", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ error: { message: "Insufficient balance or no resource package", code: 1113 } }), { status: 429, headers: { "content-type": "application/json" } }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + 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(res.status).toBe(200) + const giftTries = sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages")) + expect(giftTries).toHaveLength(1) + expect(JSON.parse(giftTries[0].body).model).toBe("glm-5.3-flash") + const planTries = sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages")) + expect(planTries).toHaveLength(1) + expect(JSON.parse(planTries[0].body).model).toBe("GLM-5.3-Flash") + // the next request skips the spent gift and goes straight to the plan + await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages"))).toHaveLength(1) +}) + +test("a gift 200 that says the quota is spent is answered from the plan too", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ code: 1005, msg: "exceed quota limit" }), { headers: { "content-type": "application/json" } }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + 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(res.status).toBe(200) + expect(sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages"))).toHaveLength(1) + expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(1) +}) + +test("after the minute's rest the plan keeps serving, inside the route's ten", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ error: { message: "Insufficient balance or no resource package", code: 1113 } }), { status: 429, headers: { "content-type": "application/json" } }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" })) + const first = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(first.status).toBe(200) + // the minute out, the balance still read live: the gift is tried once + // more and answered from the plan again, never a 429 of its own + _internal.blocked.set(KEY + "\0" + jwt + "\0glm-5.3-flash", Date.now() - 1) + const second = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(second.status).toBe(200) + expect(sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages"))).toHaveLength(2) + expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(2) +}) + +test("three requests racing a gift that just ran out all get the plan's answer", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ error: { message: "Insufficient balance or no resource package", code: 1113 } }), { status: 429, headers: { "content-type": "application/json" } }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" })) + const send = () => opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + const rs = await Promise.all([send(), send(), send()]) + expect(rs.map((r) => r.status)).toEqual([200, 200, 200]) + expect(sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages"))).toHaveLength(3) + expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(3) +}) + +test("a -Trial entry keeps its local 429 with freeFirst on", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, balances: [{ ...balance.balances[0], remaining_units: 0, used_units: 1000 }] }) + 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-Trial") }) + expect(res.status).toBe(429) + expect(sent.filter((c) => c.path.endsWith("/messages"))).toHaveLength(0) +}) + +test("a provider options object without freeFirst leaves the plugin's on", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode", options: { freeFirst: undefined } })) + const res = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(res.status).toBe(200) + expect(sent.at(-1).origin).toBe("https://zcode.z.ai") +}) + +const giftSaysSpent = () => new Response(JSON.stringify({ error: { message: "Insufficient balance or no resource package", code: 1113 } }), { status: 429, headers: { "content-type": "application/json" } }) + +test("a replay waits out the plan's own busy cap", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = giftSaysSpent() + let planTries = 0 + answers["/api/anthropic/v1/messages"] = () => { + planTries++ + return planTries === 1 + ? new Response(JSON.stringify({ error: { code: "3008", message: "concurrency limit exceeded" } }), { status: 429, headers: { "content-type": "application/json" } }) + : ok({ type: "message", content: [] }) + } + 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(res.status).toBe(200) + expect(planTries).toBe(2) +}) + +test("a gift that fails for any other reason is answered from the plan too", async () => { + for (const [status, text] of [[500, "boom"], [401, "token expired or incorrect"], [400, "bad request"]]) { + planAndBalance() + _internal.blocked.clear() + sent.length = 0 + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(text, { status }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + 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(res.status).toBe(200) + expect(sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages"))).toHaveLength(1) + expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(1) + } +}) + +test("the gift's own busy cap, waited out, is answered from the plan too", async () => { + planAndBalance() + const waits = _internal.BUSY_WAITS.splice(0) + _internal.BUSY_WAITS.push(1) + try { + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ code: "3008", msg: "user concurrency limit exceeded" }), { status: 429, headers: { "content-type": "application/json" } }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + 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(res.status).toBe(200) + expect(sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages"))).toHaveLength(2) + expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(1) + // a cap is a turn not come, not spent: no minute's rest + expect(_internal.blocked.get(KEY + "\0" + jwt + "\0glm-5.3-flash")).toBeUndefined() + } finally { + _internal.BUSY_WAITS.length = 0 + _internal.BUSY_WAITS.push(...waits) + } +}) + +test("a Start Plan block page is answered from the plan too", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ error: { message: "request has been blocked due to unusual activity", code: 3012 } }), { status: 405, headers: { "content-type": "application/json" } }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + 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(res.status).toBe(200) + expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(1) + // the block rests the model a minute, as a spent answer does + expect(_internal.blocked.get(KEY + "\0" + jwt + "\0glm-5.3-flash")).toBeGreaterThan(Date.now()) +}) + +const giftUnreachable = (when = () => true) => { + const under = globalThis.fetch + globalThis.fetch = async (input, init = {}) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (when(url)) throw new TypeError("fetch failed") + return under(input, init) + } +} + +// giftThrowing replaces fetch with one that throws error() on the gift's +// messages alone — the reads answer as usual — and counts the tries, since +// a request that throws never reaches the fetch fake that fills sent. +const giftThrowing = (error) => { + const under = globalThis.fetch + const tries = { gift: 0, plan: 0 } + globalThis.fetch = async (input, init = {}) => { + const url = new URL(input instanceof Request ? input.url : String(input)) + if (url.origin === "https://zcode.z.ai" && url.pathname.endsWith("/messages")) { + tries.gift++ + throw await error() + } + if (url.origin === "https://api.z.ai" && url.pathname.endsWith("/messages")) tries.plan++ + return under(input, init) + } + return tries +} + +test("a gift that cannot be asked at all is answered from the plan", async () => { + planAndBalance() + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + giftUnreachable((url) => url.origin === "https://zcode.z.ai" && url.pathname.endsWith("/messages")) + 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(res.status).toBe(200) + expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(1) + // the route is dropped, so the next request's balance read finds out + // whether the host is back + expect(_internal.routes.get(KEY + "\0" + jwt)).toBeUndefined() + const second = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") }) + expect(second.status).toBe(200) + expect(sent.filter((c) => c.path.endsWith("/billing/balance"))).toHaveLength(2) +}) + +test("an aborted gift request stays aborted", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const ctl = new AbortController() + ctl.abort() + const tries = await giftThrowing(() => new DOMException("This operation was aborted", "AbortError")) + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" })) + await expect(opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash"), signal: ctl.signal })).rejects.toThrow() + expect(tries.gift).toBe(1) + expect(tries.plan).toBe(0) +}) + +test("an abort while the gift is in flight stays an abort", async () => { + planAndBalance() + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const ctl = new AbortController() + // the abort lands while the ask is away: some runtimes surface it as a + // plain TypeError, and the signal says the caller meant it + const tries = await giftThrowing(() => { + ctl.abort() + return new TypeError("fetch failed") + }) + const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" })) + await expect(opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash"), signal: ctl.signal })).rejects.toThrow() + expect(tries.gift).toBe(1) + expect(tries.plan).toBe(0) +}) + for (const [name, paid, gift] of [ ["a full paid week leaves an available gift usable", 100, 25], ["a spent gift leaves the paid plan usable", 20, 100], diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 2c50f3f..a68018a 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -1731,6 +1731,28 @@ function busyAnswer(res, text) { }) } +// askBusy asks once and, when the answer is the vendor's in-flight cap +// (3008/3009, or its own words), asks again through BUSY_WAITS's waits, a +// quarter of a second and longer — about ten seconds of them. Past that the +// account is saturated rather than busy, and the cap goes back as +// busyAnswer's 429. The plan path's patience, shared with free first's +// replay, whose plan has a cap of its own. +async function askBusy(u, o, hs) { + let res = await fetch(u, { ...o, headers: hs }) + for (let i = 0; res.status === 429; i++) { + const text = await res.text() + const cap = busy(429, text) + if (!cap || i >= BUSY_WAITS.length) { + res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) + break + } + const w = BUSY_WAITS[i] + await sleep(Math.round(w * (0.75 + Math.random() * 0.5))) + res = await fetch(u, { ...o, headers: hs }) + } + return res +} + function model(m, url) { const e = entry(m) return { @@ -2119,12 +2141,17 @@ function sessionOf(id, device) { // ---- the plugin ------------------------------------------------------------------ -export async function ZCodeAuthPlugin({ client }) { +export async function ZCodeAuthPlugin({ client }, options = {}) { const log = (message) => { try { client?.app?.log?.({ body: { service: "zcode-auth", level: "error", message } }) } catch {} } + // freeFirst reads the option from the provider config's options first, + // and from the plugin's own (magpie's Plugins › Options) when the + // provider carries no freeFirst of its own. + const freeFirst = (providerOptions) => + providerOptions?.freeFirst !== undefined ? providerOptions.freeFirst === true : options?.freeFirst === true const oauth = (site) => ({ type: "oauth", label: `ZCode: ${SITES[site].name}${site === "bigmodel" ? " (智谱)" : ""} GLM Coding Plan`, @@ -2230,7 +2257,8 @@ export async function ZCodeAuthPlugin({ client }) { // a dual account's body is read ahead of sending, so a gift that // says it is spent can spend nothing and replay what was asked for let start = alone - let orig, forcedGift = false + let orig, forcedGift = false, freeGift = false + let asked = "" let renamed = false const done = (res) => (renamed ? searchNamed(res) : res) if (opts.body != null) { @@ -2244,6 +2272,7 @@ export async function ZCodeAuthPlugin({ client }) { renamed = true } let m = modelOf(orig) + asked = m if (m.toLowerCase().endsWith("-trial")) { gift ??= await startPlan(s.jwt, s.device).catch(() => null) const raw = giftModel(gift, m) @@ -2255,8 +2284,21 @@ export async function ZCodeAuthPlugin({ client }) { orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: raw }) m = raw forcedGift = true + } else if (!alone && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m)) { + // free first: the plain model spends the account's own live + // gift before it spends the coding plan, under the name the + // gift lists. The gift is the route's cache alone (a failed + // read cached its why), so a gift that cannot be read keeps + // the request on the plan with no read per request; a + // gift-only account is already on the gift and is left as + // it was. A refusal past this check is replayed on the plan + // in the same request (replayOnPlan below). + const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase()) + orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: raw }) + m = raw + freeGift = true } - start = alone || forcedGift + start = alone || forcedGift || freeGift } const swap = (base) => { for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) { @@ -2267,8 +2309,41 @@ export async function ZCodeAuthPlugin({ client }) { } } let h = new Headers(opts.headers) + const askedUrl = url const place = workPlace(h) const sid = sessionOf(h.get("x-session-id"), s.device) + // restModel is the gift saying this model has nothing left: the + // model rests a minute (blocked) and the route is dropped, so + // the requests behind it re-read the balance and go straight to + // the plan. + const restModel = () => { + for (const [k, until] of blocked) if (Date.now() >= until) blocked.delete(k) + blocked.set(s.key + "\0" + s.jwt + "\0" + asked.toLowerCase(), Date.now() + 60_000) + routes.delete(s.key + "\0" + s.jwt) + } + // replayOnPlan is free first's answer to a gift that refused + // what its own balance read had promised: the model as the + // agent sent it, the plan's headers, the plan's own patience + // (askBusy). + const replayOnPlan = async () => { + let u = askedUrl + for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) { + if (u.startsWith(b)) { + u = s.base + u.slice(b.length) + break + } + } + const h2 = new Headers(opts.headers) + workPlace(h2) + h2.set("x-session-id", sid) + h2.delete("authorization") + h2.set("x-api-key", key) + h2.set("Authorization", "Bearer " + key) + h2.delete("content-length") + opts.body = marked(JSON.stringify({ ...JSON.parse(orig), model: asked }), s.device, sid) + delete opts.duplex + return askBusy(u, opts, h2) + } 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") @@ -2306,20 +2381,18 @@ export async function ZCodeAuthPlugin({ client }) { // magpie sends every agent's and every session's requests of this // computer through this one process, and its queue spaces them by // the number declared above - const ask = () => fetch(url, { ...opts, headers: h }) - let res = await ask() - for (let i = 0; res.status === 429; i++) { - const text = await res.text() - const cap = busy(429, text) - if (!cap || i >= BUSY_WAITS.length) { - res = cap - ? busyAnswer(res, text) - : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) - break - } - const w = BUSY_WAITS[i] - await sleep(Math.round(w * (0.75 + Math.random() * 0.5))) - res = await ask() + let res + try { + res = await askBusy(url, opts, h) + } catch (e) { + // free first moved the request onto the gift, so a gift that + // cannot be asked at all — the network, the host — is answered + // from the plan; the route read is dropped, so the next + // request learns whether the host is back. A caller's abort + // stays an abort. + if (!freeGift || opts.signal?.aborted || e?.name === "AbortError") throw e + routes.delete(s.key + "\0" + s.jwt) + res = await replayOnPlan() } // the Start Plan turning the request away says what to do about // it: the account blocked, or the network @@ -2329,6 +2402,10 @@ export async function ZCodeAuthPlugin({ client }) { // a key account sent to the Start Plan (its plan list read // none) reads its plans again on the next request, so a // coding plan that is there after all is used (#369) + if (freeGift) { + restModel() + return done(kept(await replayOnPlan())) + } if (s.key && !forcedGift) routes.delete(s.key + "\0" + s.jwt) return kept(startBlocked(res, text)) } @@ -2361,6 +2438,32 @@ export async function ZCodeAuthPlugin({ client }) { return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text)) } } + // free first's gift answer: the choice was the plugin's, so the + // plan answers what the gift would fail — a spent bucket and a + // refusal like any other 4xx or 5xx among them, the gift's own + // waited-out busy cap included, since the plan's cap is its own. + // A spent answer or a block page rests the model a minute and + // drops the route read; a 401/403 drops the read alone, so the + // next request learns whether the session is gone. Anything + // else — a 200 carrying the answer — goes on as it came. A + // stream's body is never read here. + else if (start && freeGift) { + const json = (res.headers.get("content-type") ?? "").includes("application/json") + if (res.status >= 400 || json) { + const text = await res.text() + const cap = busy(res.status, text) + const spent = !cap && spentUp(text, res.status) + if (spent) { + restModel() + return done(kept(await replayOnPlan())) + } + if (res.status >= 400) { + if (!cap && (res.status === 401 || res.status === 403)) routes.delete(s.key + "\0" + s.jwt) + return done(kept(await replayOnPlan())) + } + return 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 done(kept(res)) diff --git a/packages/zcode/package.json b/packages/zcode/package.json index a29245c..10507f3 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.37", + "version": "0.1.38", "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": "./index.mjs",