zcode 0.1.9: the gift's models are trial entries the user picks, not an automatic gift-first route (#21)
Why: 0.1.8 sent every request for a gift-served model to the gift first, so a user who meant to spend the coding plan had no say, and the card hid the gift's models behind notModels. The gift is an allowance outside the plan; spending it should be a choice. What: every model a live gift bucket serves is listed again as <model>-Trial, in the catalog's spelling (GLM-5.3-Flash-Trial), and a request for that entry goes to the gift dressed as ZCode's own; a plain model always spends the coding plan. A trial entry whose bucket is spent or blocked answers 429 without touching the coding plan, as do the gift's quota errors (1113, 1005 inside a 200); any other gift answer goes on as it came. The usage card names the gift window by its trial model, drops the plan prefix, and puts MCP - Month last. Tests: dual.test.mjs rewritten for the new routing (a plain model to the coding plan whatever the gift holds, a trial entry to the gift), usage.test.mjs and gift.test.mjs follow the naming; bun test (65 pass in the package, 516 in the repo) and bun scripts/check.mjs zcode pass.
This commit is contained in:
+25
-18
@@ -54,30 +54,32 @@ Before each request, the plugin checks which plan the account is on, and
|
||||
asks again every 10 minutes:
|
||||
|
||||
- If the key's account has a GLM Coding Plan
|
||||
(`/api/biz/subscription/list`), its requests go to that plan —
|
||||
except for a model the account's gift plans also serve, which goes to
|
||||
the gift first (see below).
|
||||
(`/api/biz/subscription/list`), its requests go to that plan. A model
|
||||
the account's gift plans also serve is listed again as
|
||||
`<model>-Trial`; asking that entry spends the gift (see below).
|
||||
- Otherwise they go to the gift plans.
|
||||
|
||||
Every request carries the key as both `x-api-key` and
|
||||
`Authorization: Bearer`.
|
||||
|
||||
**Spending the gift first.** An account with a GLM Coding Plan can also
|
||||
hold gift plans from ZCode activities, ones that expire on a fixed date.
|
||||
Their allowance would lapse unused if every request went to the coding
|
||||
plan, so the plugin reads the gift's balance (per the sign-in's session,
|
||||
kept for 10 minutes) and sends a request for a model the gift still has
|
||||
quota to spend to the gift first, dressed as ZCode's own. A bucket is
|
||||
judged spent only by its `remaining_units` — a missing one is unknown,
|
||||
not spent — and a model whose every bucket says none goes straight to
|
||||
the coding plan without asking. When the gift can't serve the request —
|
||||
any answer 400 or over (its 405, its 401, its 5xx), or its quota error
|
||||
**The gift's trial entries.** An account with a GLM Coding Plan can
|
||||
also hold gift plans from ZCode activities, ones that expire on a fixed
|
||||
date. Their allowance would lapse unused if every request went to the
|
||||
coding plan, so the plugin reads the gift's balance (per the sign-in's
|
||||
session, kept for 10 minutes) and lists every model a live bucket
|
||||
serves again as `<model>-Trial`, named in the catalog's spelling
|
||||
(GLM-5.3-Flash-Trial). Asking a trial entry sends the model to the
|
||||
gift, dressed as ZCode's own; asking the plain model spends the coding
|
||||
plan — the choice is the user's. A bucket is judged spent only by its
|
||||
`remaining_units` — a missing one is unknown, not spent. A trial entry
|
||||
whose bucket is spent or blocked answers 429 without touching the
|
||||
coding plan; when the gift answers a trial entry with a quota error
|
||||
(code 1113 "Insufficient balance or no resource package", code 1005
|
||||
"exceed quota limit", which it can answer inside an HTTP 200) — the
|
||||
plugin replays the request once to the coding plan, as the agent sent
|
||||
it. Only a quota answer keeps that model off the gift for a minute; a
|
||||
refusal that says nothing about quota is asked again next request. Every
|
||||
429 counts as spent, Z.ai's 1302/1303 rate limits among them. A stream's
|
||||
"exceed quota limit", which it can answer inside an HTTP 200) that too
|
||||
becomes a 429 and keeps the entry off for a minute. Any other gift
|
||||
answer (its 405, its 401, its 5xx) goes on as it came: the user picked
|
||||
the gift, so the coding plan is not spent behind their back. Every 429
|
||||
counts as spent, Z.ai's 1302/1303 rate limits among them. A stream's
|
||||
body is never read or buffered on the way.
|
||||
|
||||
## The usage card
|
||||
@@ -105,3 +107,8 @@ minutes. When the config can't be read, the plugin falls back to this list:
|
||||
| GLM-5-Turbo | 200K | 64K | none, high |
|
||||
|
||||
The Start Plan has all of these except GLM-5.3.
|
||||
|
||||
A gift plan's models appear again as `<model>-Trial` entries, so a
|
||||
request can spend the gift's quota on purpose. A trial entry is listed
|
||||
while any live bucket serves its model, spent buckets included (a spent
|
||||
entry answers 429 rather than vanishing mid-session).
|
||||
|
||||
@@ -0,0 +1,72 @@
|
||||
# ZCode limited-quota model entries
|
||||
|
||||
## Goal
|
||||
|
||||
Keep the plan's normal model list and existing request behavior. Append distinct
|
||||
`<original-model>-Trial` entries from live ZCode balance data, including models
|
||||
absent from the normal plan catalog, named in the catalog's spelling. A trial
|
||||
entry spends the gift; a plain model always spends the coding plan — the choice
|
||||
is the user's. Display names and IDs use English. All production changes remain
|
||||
in the ZCode plugin.
|
||||
|
||||
## Verification layers
|
||||
|
||||
Use the plugin repository's existing Bun tests for model discovery, quota
|
||||
metadata and HTTP routing. Check the emitted metadata against the current
|
||||
Magpie plugin contract. No new UI page or test framework is introduced.
|
||||
|
||||
## Scenarios
|
||||
|
||||
### Add a real limited-quota model
|
||||
|
||||
- Given a coding-plan account has an active grant for a model absent from its plan catalog.
|
||||
- When the plugin discovers its models.
|
||||
- Then it includes that model as `<original-model>-Trial` alongside unchanged plan entries.
|
||||
|
||||
### Keep grant models discoverable while their quota is exhausted
|
||||
|
||||
- Given an active grant has an exhausted bucket.
|
||||
- When the plugin discovers its models.
|
||||
- Then its gift entry remains discoverable with the exhausted gift quota applied to that entry.
|
||||
|
||||
### Ignore ended grants and unrelated capabilities
|
||||
|
||||
- Given a balance includes expired grants or non-model capabilities.
|
||||
- When the plugin discovers its models.
|
||||
- Then neither creates gift model entries.
|
||||
|
||||
### Restore the upstream model name
|
||||
|
||||
- Given a request selects a discovered gift model.
|
||||
- When the plugin sends the request to the grant endpoint.
|
||||
- Then the request contains the original model name, without the Trial suffix.
|
||||
|
||||
### Keep a gift request within the gift pool
|
||||
|
||||
- Given the gift endpoint refuses a request and the coding plan still has credit.
|
||||
- When the selected model is a gift entry.
|
||||
- Then the plugin returns the refusal without sending a paid-plan request.
|
||||
|
||||
### Reject unavailable gift quota without spending paid credit
|
||||
|
||||
- Given the selected gift model is exhausted, unavailable, or temporarily blocked.
|
||||
- When a request selects that gift entry.
|
||||
- Then the plugin returns a clear error without sending a paid-plan request.
|
||||
|
||||
### Scope quota to the selected pool
|
||||
|
||||
- Given the coding-plan week is exhausted and a gift remains available.
|
||||
- When Magpie evaluates the gift entry's quota metadata.
|
||||
- Then only the corresponding gift allowance applies to that entry.
|
||||
|
||||
### Allow a live sibling bucket
|
||||
|
||||
- Given one gift bucket is exhausted and another live bucket serves the same model.
|
||||
- When the plugin maps gift model quotas.
|
||||
- Then the exhausted sibling does not make that gift entry appear exhausted.
|
||||
|
||||
### Keep plain models on the coding plan
|
||||
|
||||
- Given a caller uses an existing model ID without the Trial suffix.
|
||||
- When the plugin routes the request.
|
||||
- Then the request spends the coding plan, whatever the gift holds.
|
||||
+169
-37
@@ -1,10 +1,10 @@
|
||||
// A dual account (a GLM Coding Plan and gift plans) shows both allowances on
|
||||
// its card and spends the gift first: a request for a model the gift serves
|
||||
// goes to the Start Plan, dressed as ZCode's; when the gift says it is spent
|
||||
// the same request is replayed once to the coding plan, undressed, and that
|
||||
// model keeps to the coding plan for a minute. Anything else the gift says
|
||||
// (its 405, its "unusual activity") stands as the answer. Nothing leaves the
|
||||
// machine: the plugin's fetch is the fake here.
|
||||
// its card. A plain model always spends the coding plan; the gift is spent
|
||||
// only through its trial entries (GLM-5.3-Flash-Trial), the user's pick. A
|
||||
// trial entry whose bucket is spent or blocked answers 429 locally; the
|
||||
// gift's own quota answers (its 1113, its 1005 inside a 200) become 429 and
|
||||
// keep the entry off for a minute, while any other gift answer goes on as it
|
||||
// came. 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"
|
||||
@@ -63,6 +63,134 @@ 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" }] })
|
||||
|
||||
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],
|
||||
["two available pools keep their windows apart", 20, 25],
|
||||
["two spent pools keep the paid limit visible", 100, 100],
|
||||
]) {
|
||||
test(name, async () => {
|
||||
planAndBalance()
|
||||
answers["/api/monitor/usage/quota/limit"] = ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: paid }] })
|
||||
answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, balances: [{ ...balance.balances[0], used_units: gift * 10, remaining_units: 1000 - gift * 10 }] })
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
const u = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(u.windows[0].used).toBe(paid)
|
||||
expect(u.windows[1].used).toBe(gift)
|
||||
expect(u.windows[0].notModels).toEqual(["glm-5.3-flash-trial"])
|
||||
expect(u.windows[1].models).toEqual(["GLM-5.3-Flash-Trial"])
|
||||
expect(JSON.stringify(u)).not.toContain("_spent")
|
||||
// a plain model spends the coding plan whatever the gift holds
|
||||
let before = sent.length
|
||||
expect((await sendTo(MSG, body("GLM-5.3-Flash"))).status).toBe(200)
|
||||
expect(sent.slice(before).at(-1).origin).toBe("https://api.z.ai")
|
||||
expect(sent.slice(before).filter((c) => c.path.endsWith("/messages"))).toHaveLength(1)
|
||||
// the trial entry spends the gift while it has quota, and nothing else
|
||||
before = sent.length
|
||||
const t = await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
|
||||
if (gift < 100) {
|
||||
expect(t.status).toBe(200)
|
||||
expect(sent.slice(before).at(-1).origin).toBe("https://zcode.z.ai")
|
||||
} else {
|
||||
expect(t.status).toBe(429)
|
||||
expect(sent.slice(before).filter((c) => c.path.endsWith("/messages"))).toHaveLength(0)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
test("a spent gift retires its trial entry from the request cache", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/monitor/usage/quota/limit"] = ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: 20 }] })
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
await sendTo(MSG, body("GLM-5.3-Flash-Trial")) // warms the ten-minute request cache
|
||||
answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, balances: [{ ...balance.balances[0], used_units: 1000, remaining_units: 0 }] })
|
||||
const u = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(u.windows[1].models).toEqual(["GLM-5.3-Flash-Trial"])
|
||||
const before = sent.length
|
||||
expect((await sendTo(MSG, body("GLM-5.3-Flash-Trial"))).status).toBe(429)
|
||||
expect(sent.slice(before).filter((c) => c.path.endsWith("/messages"))).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("fresh usage recognizes a newly replenished gift without waiting for the request cache", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/monitor/usage/quota/limit"] = ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: 100 }] })
|
||||
answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, balances: [{ ...balance.balances[0], used_units: 1000, remaining_units: 0 }] })
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
await sendTo(MSG, body("GLM-5.3-Flash-Trial")) // refused locally, the bucket spent
|
||||
answers["/api/v1/zcode-plan/billing/balance"] = ok(balance)
|
||||
const u = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(u.windows[0].notModels).toEqual(["glm-5.3-flash-trial"])
|
||||
const before = sent.length
|
||||
expect((await sendTo(MSG, body("GLM-5.3-Flash-Trial"))).status).toBe(200)
|
||||
expect(sent.slice(before).at(-1).origin).toBe("https://zcode.z.ai")
|
||||
})
|
||||
|
||||
test("an expired gift restores the paid windows and retires its cached route", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/monitor/usage/quota/limit"] = ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: 20 }] })
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
await sendTo(MSG, body("glm-5.3-flash"))
|
||||
answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, plans: [{ ...balance.plans[0], ends_at: now - 1 }] })
|
||||
const u = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(u.windows).toHaveLength(1)
|
||||
expect(u.windows[0].notModels).toBeUndefined()
|
||||
const before = sent.length
|
||||
await sendTo(MSG, body("glm-5.3-flash"))
|
||||
expect(sent.slice(before).at(-1).origin).toBe("https://api.z.ai")
|
||||
})
|
||||
|
||||
test("a trial entry's quota refusal answers 429 and blocks the entry for a minute", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/monitor/usage/quota/limit"] = ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: 100 }] })
|
||||
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: [] })
|
||||
expect((await sendTo(MSG, body("GLM-5.3-Flash-Trial"))).status).toBe(429)
|
||||
expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(0)
|
||||
const u = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(u.windows[0].notModels).toEqual(["glm-5.3-flash-trial"])
|
||||
expect(u.windows[1].models).toEqual(["GLM-5.3-Flash-Trial"])
|
||||
_internal.blocked.clear()
|
||||
const renewed = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(renewed.windows[0].notModels).toEqual(["glm-5.3-flash-trial"])
|
||||
expect(renewed.windows[1].aside).not.toBe(true)
|
||||
})
|
||||
|
||||
test("blocking one model leaves another model of the same gift bucket usable", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/monitor/usage/quota/limit"] = ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: 100 }] })
|
||||
answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, balances: [{ ...balance.balances[0], capabilities: ["model:glm-5.3-flash", "model:GLM-5.2"] }] })
|
||||
_internal.blocked.set(KEY + "\0" + jwt + "\0glm-5.3-flash", Date.now() + 60_000)
|
||||
const u = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(u.windows[0].notModels).toEqual(["glm-5.3-flash-trial", "glm-5.2-trial"])
|
||||
expect(u.windows[1].models).toEqual(["GLM-5.3-Flash-Trial", "GLM-5.2-Trial"])
|
||||
expect(u.windows[1].aside).not.toBe(true)
|
||||
})
|
||||
|
||||
test("a spent bucket without remaining_units is skipped using its used and total counts", async () => {
|
||||
planAndBalance()
|
||||
const spent = { ...balance.balances[0], used_units: "1000", total_units: "1000" }
|
||||
delete spent.remaining_units
|
||||
answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, balances: [spent] })
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
await sendTo(MSG, body("glm-5.3-flash"))
|
||||
expect(sent.at(-1).origin).toBe("https://api.z.ai")
|
||||
expect(sent.filter((c) => c.path === "/api/v1/zcode-plan/anthropic/v1/messages")).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("a spent gift-only account keeps its spent window as a routing limit", async () => {
|
||||
answers["/api/v1/zcode-plan/billing/balance"] = ok({ ...balance, balances: [{ ...balance.balances[0], used_units: 1000, remaining_units: 0 }] })
|
||||
const only = { type: "oauth", access: jwt, refresh: JSON.stringify({ site: "zai", base: "https://api.z.ai/api/anthropic", jwt, device: DEVICE }), expires: 0 }
|
||||
const u = await (await hooks()).usage(async () => only, { id: "zcode" })
|
||||
expect(u.windows[0].used).toBe(100)
|
||||
expect(u.windows[0].aside).toBeUndefined()
|
||||
expect(JSON.stringify(u)).not.toContain("_spent")
|
||||
})
|
||||
|
||||
|
||||
test("the card shows the Coding windows and the gift's buckets together", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/monitor/usage/quota/limit"] = ok({ level: "pro", limits: [{ type: "CREDIT_LIMIT", unit: 3, number: 5, usage: 2000, remaining: 1500, percentage: 25 }] })
|
||||
@@ -70,8 +198,8 @@ test("the card shows the Coding windows and the gift's buckets together", async
|
||||
expect(u.plan).toBe("GLM Coding Pro")
|
||||
expect(u.signIn).toBe("kept")
|
||||
expect(u.error).toBeUndefined()
|
||||
expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Start Plan · Trust Build"])
|
||||
expect(u.windows[1]).toMatchObject({ used: 25, display: "250 / 1000", models: ["glm-5.3-flash"] })
|
||||
expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Trust Build"])
|
||||
expect(u.windows[1]).toMatchObject({ used: 25, display: "250 / 1000", models: ["GLM-5.3-Flash-Trial"] })
|
||||
expect(u.until).toBeUndefined()
|
||||
expect(u.renew).toBeUndefined()
|
||||
expect(u.windows[1].resetsAt).toBe(new Date((now + 3600) * 1000).toISOString())
|
||||
@@ -86,12 +214,18 @@ test("a gift read that fails after the gift was known leaves just the Coding car
|
||||
const u = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(u.windows.map((w) => w.name)).toEqual(["5 hours"])
|
||||
expect(u.error).toBeUndefined()
|
||||
expect(_internal.routes.get(KEY + "\0" + jwt).gift).toBeNull()
|
||||
expect(_internal.routes.get(KEY + "\0" + jwt).ttl).toBe(60_000)
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
const before = sent.length
|
||||
await sendTo(MSG, body("glm-5.3-flash"))
|
||||
expect(sent.slice(before).at(-1).origin).toBe("https://api.z.ai")
|
||||
})
|
||||
|
||||
test("a model the gift serves goes to the Start Plan, dressed", async () => {
|
||||
test("a trial entry goes to the Start Plan, dressed", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
const res = await sendTo(MSG, body("glm-5.3-flash"))
|
||||
const res = await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
|
||||
expect(res.status).toBe(200)
|
||||
expect(sent.length).toBe(3) // the plan list and the balance read, then the message
|
||||
const m = sent.at(-1)
|
||||
@@ -101,6 +235,7 @@ test("a model the gift serves goes to the Start Plan, dressed", async () => {
|
||||
expect(m.headers.authorization).toBe("Bearer " + jwt)
|
||||
expect(m.headers["x-api-key"]).toBeUndefined()
|
||||
expect(JSON.parse(m.body).system.length).toBeGreaterThan(1) // dressed
|
||||
expect(JSON.parse(m.body).model).toBe("glm-5.3-flash") // the entry's own model
|
||||
})
|
||||
|
||||
test("a model the gift does not serve goes to the coding plan as sent", async () => {
|
||||
@@ -116,54 +251,49 @@ test("a model the gift does not serve goes to the coding plan as sent", async ()
|
||||
expect(m.headers["x-title"]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("a spent gift replays the request once to the coding plan, undressed", async () => {
|
||||
test("a spent bucket answers the trial entry 429 without touching the coding plan", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ error: { code: "1113", message: "Insufficient balance or no resource package" } }), { status: 429 })
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
const res = await sendTo(MSG, body("glm-5.3-flash"))
|
||||
expect(res.status).toBe(200)
|
||||
const m = sent.at(-1)
|
||||
expect(m.origin).toBe("https://api.z.ai")
|
||||
expect(m.body).toBe(body("glm-5.3-flash")) // the agent's body, not dressed
|
||||
expect(m.headers["x-api-key"]).toBe(KEY)
|
||||
// the second try for the same model skips the gift: kept off for a minute
|
||||
const res = await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
|
||||
expect(res.status).toBe(429)
|
||||
expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(0)
|
||||
// the minute's block keeps the next one off the gift too
|
||||
const before = sent.length
|
||||
await sendTo(MSG, body("glm-5.3-flash"))
|
||||
expect(sent.slice(before).at(-1).origin).toBe("https://api.z.ai")
|
||||
await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
|
||||
expect(sent.slice(before).filter((c) => c.path.endsWith("/messages"))).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("a gift's 200 with a quota error replays to the coding plan too", async () => {
|
||||
test("a trial entry's quota error inside a 200 becomes 429", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ code: 1005, msg: "exceed quota limit", logid: "x" }), { status: 200, headers: { "content-type": "application/json" } })
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
const res = await sendTo(MSG, body("glm-5.3-flash"))
|
||||
expect(res.status).toBe(200)
|
||||
const m = sent.at(-1)
|
||||
expect(m.origin).toBe("https://api.z.ai")
|
||||
expect(m.body).toBe(body("glm-5.3-flash"))
|
||||
const res = await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
|
||||
expect(res.status).toBe(429)
|
||||
expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("a gift's 200 success answers normally: no replay", async () => {
|
||||
test("a trial entry's 200 success answers normally: no replay", async () => {
|
||||
planAndBalance()
|
||||
const sse = new Response("data: {}\n\n", { status: 200, headers: { "content-type": "text/event-stream" } })
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = sse
|
||||
const res = await sendTo(MSG, body("glm-5.3-flash"))
|
||||
const res = await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get("x-magpie-sign-in")).toBe("kept")
|
||||
expect(sent.filter((c) => c.path === "/api/anthropic/v1/messages").length).toBe(0)
|
||||
expect(await res.text()).toBe("data: {}\n\n")
|
||||
})
|
||||
|
||||
test("a gift refusal replays to the coding plan but keeps the gift unblocked", async () => {
|
||||
test("a gift refusal answers the trial entry as it came, unblocked", async () => {
|
||||
planAndBalance()
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ code: "3012", msg: "unusual activity" }), { status: 405 })
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
const res = await sendTo(MSG, body("glm-5.3-flash"))
|
||||
expect(res.status).toBe(200)
|
||||
expect(sent.at(-1).origin).toBe("https://api.z.ai")
|
||||
const res = await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
|
||||
expect(res.status).toBe(405)
|
||||
expect(sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages"))).toHaveLength(0)
|
||||
expect(_internal.blocked.size).toBe(0)
|
||||
const before = sent.length
|
||||
await sendTo(MSG, body("glm-5.3-flash"))
|
||||
await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
|
||||
expect(sent.slice(before).some((c) => c.origin === "https://zcode.z.ai")).toBe(true)
|
||||
})
|
||||
|
||||
@@ -233,11 +363,11 @@ test("every live plan spends first by its buckets' models, and the card shows th
|
||||
})
|
||||
answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] })
|
||||
// models of both live plans go to the gift first
|
||||
for (const m of ["glm-5.3-flash", "GLM-5.2"]) {
|
||||
// plain models stay on the coding plan; the trial entries spend the gift
|
||||
for (const [m, origin] of [["glm-5.3-flash", "https://api.z.ai"], ["GLM-5.2", "https://api.z.ai"], ["GLM-5.3-Flash-Trial", "https://zcode.z.ai"], ["GLM-5.2-Trial", "https://zcode.z.ai"]]) {
|
||||
const before = sent.length
|
||||
expect((await sendTo(MSG, body(m))).status).toBe(200)
|
||||
expect(sent.slice(before).at(-1).origin).toBe("https://zcode.z.ai")
|
||||
expect(sent.slice(before).at(-1).origin).toBe(origin)
|
||||
}
|
||||
// the ended plan's bucket does not put GLM-4 on the gift
|
||||
const before = sent.length
|
||||
@@ -245,8 +375,10 @@ test("every live plan spends first by its buckets' models, and the card shows th
|
||||
expect(sent.slice(before).at(-1).origin).toBe("https://api.z.ai")
|
||||
// the card shows both plans' live buckets, spent ones included, none of the ended plan's
|
||||
const u = await (await hooks()).usage(async () => coding, { id: "zcode" })
|
||||
expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Start Plan · Trust Build", "GLM Festival Grant · GLM-5.2", "GLM Festival Grant · GLM-5.2 late"])
|
||||
expect(u.windows.map((w) => w.name)).toEqual(["5 hours", "Trust Build", "GLM-5.2-Trial", "GLM-5.2 late"])
|
||||
expect(u.windows.some((w) => w.name === "Old")).toBe(false)
|
||||
expect(u.windows[0].notModels).toEqual(["glm-5.3-flash-trial", "glm-5.2-trial"])
|
||||
expect(u.windows.at(-1).aside).toBe(true) // a spent sibling cannot cap a live bucket
|
||||
})
|
||||
|
||||
test("a gift-only account sends every request to the gift, and reads no balance to do it", async () => {
|
||||
|
||||
@@ -0,0 +1,188 @@
|
||||
import { afterEach, beforeEach, expect, spyOn, 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 in an isolated home")
|
||||
const { ZCodeAuthPlugin, _internal } = await import("./index.mjs")
|
||||
const now = Math.trunc(Date.now() / 1000)
|
||||
const jwt = ["{}", JSON.stringify({ exp: now + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".synthetic"
|
||||
const state = { site: "zai", base: "https://api.z.ai/api/anthropic", key: "synthetic-key", jwt, device: "11111111-2222-4333-8444-555555555555", plan: "GLM Coding Pro" }
|
||||
const auth = { type: "oauth", access: state.key, refresh: JSON.stringify(state), expires: 0 }
|
||||
const original = "glm-limited-preview"
|
||||
const alias = original + "-Trial"
|
||||
const MSG = "https://api.z.ai/api/anthropic/v1/messages"
|
||||
const ok = (data) => new Response(JSON.stringify({ code: 0, data }), { headers: { "content-type": "application/json" } })
|
||||
const real = globalThis.fetch
|
||||
const sent = []
|
||||
let balance, paid, giftReply
|
||||
|
||||
beforeEach(() => {
|
||||
_internal.routes.clear()
|
||||
_internal.blocked.clear()
|
||||
sent.length = 0
|
||||
paid = 100
|
||||
giftReply = new Response(JSON.stringify({ type: "message", content: [] }), { headers: { "content-type": "application/json" } })
|
||||
balance = {
|
||||
server_time: now,
|
||||
plans: [{ plan_id: "grant", user_plan_id: "g1", name: "Festival Grant", status: "active", ends_at: now + 86400 }],
|
||||
balances: [{ plan_id: "grant", user_plan_id: "g1", show_name: "Limited credit", capabilities: ["model:" + original], total_units: 100, used_units: 25, remaining_units: 75, expires_at: now + 3600 }],
|
||||
}
|
||||
globalThis.fetch = async (input, init = {}) => {
|
||||
const url = new URL(input instanceof Request ? input.url : String(input))
|
||||
if (url.pathname === "/api/biz/subscription/list") return ok([{ productName: "GLM Coding Pro", status: "VALID" }])
|
||||
if (url.pathname === "/api/monitor/usage/quota/limit") return ok({ limits: [{ type: "CREDIT_LIMIT", unit: 6, number: 1, percentage: paid, nextResetTime: (now + 86400) * 1000 }] })
|
||||
if (url.pathname === "/api/v1/zcode-plan/billing/balance") return ok(balance)
|
||||
if (url.pathname.endsWith("/messages")) {
|
||||
const text = init.body ?? (input instanceof Request ? await input.text() : undefined)
|
||||
sent.push({ origin: url.origin, path: url.pathname, body: JSON.parse(text) })
|
||||
return url.origin === "https://zcode.z.ai" ? giftReply.clone() : ok({ type: "message", content: [] })
|
||||
}
|
||||
throw new Error("unmocked request blocked: " + url.pathname)
|
||||
}
|
||||
})
|
||||
afterEach(() => { globalThis.fetch = real })
|
||||
const hooks = async () => (await ZCodeAuthPlugin({ client: {} }))
|
||||
const send = async (model = alias, credentials = auth) => {
|
||||
const loader = await (await hooks()).auth.loader(async () => credentials, { id: "zcode" })
|
||||
return loader.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model, messages: [{ role: "user", content: "hi" }], max_tokens: 10 }) })
|
||||
}
|
||||
|
||||
test("real balance data adds a gift model absent from the coding catalog", async () => {
|
||||
const h = await hooks()
|
||||
const plan = await h.provider.models({ models: {} }, { auth: { type: "api", key: state.key } })
|
||||
const models = await h.provider.models({ models: {} }, { auth })
|
||||
expect(plan[original]).toBeUndefined()
|
||||
expect(models[alias]).toMatchObject({ id: alias, name: alias, api: { id: alias } })
|
||||
for (const [id, m] of Object.entries(plan)) expect(models[id]).toEqual(m)
|
||||
expect(Object.keys(models).filter((id) => id.endsWith("-Trial"))).toEqual([alias])
|
||||
})
|
||||
|
||||
test("an exhausted but active limited grant remains discoverable", async () => {
|
||||
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
|
||||
const models = await (await hooks()).provider.models({ models: {} }, { auth })
|
||||
expect(models[alias]?.name).toBe(alias)
|
||||
})
|
||||
|
||||
test("gift model names come from every live grant, not a fixed Flash model", async () => {
|
||||
balance.balances[0].capabilities = ["model:" + original, "model:glm-another-preview", "tool:web-search"]
|
||||
const models = await (await hooks()).provider.models({ models: {} }, { auth })
|
||||
expect(Object.keys(models).filter((id) => id.endsWith("-Trial")).sort()).toEqual(["glm-another-preview-Trial", alias].sort())
|
||||
expect(Object.keys(models).some((id) => id.includes("tool:"))).toBe(false)
|
||||
})
|
||||
|
||||
test("expired grants do not add gift model entries", async () => {
|
||||
balance.plans[0].ends_at = now - 1
|
||||
const models = await (await hooks()).provider.models({ models: {} }, { auth })
|
||||
expect(models[alias]).toBeUndefined()
|
||||
})
|
||||
|
||||
test("fresh usage keeps gift discovery available after a bucket is spent", async () => {
|
||||
const h = await hooks()
|
||||
await h.auth.usage(async () => auth, { id: "zcode" })
|
||||
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
|
||||
await h.auth.usage(async () => auth, { id: "zcode" })
|
||||
const models = await h.provider.models({ models: {} }, { auth })
|
||||
expect(models[alias]?.name).toBe(alias)
|
||||
})
|
||||
|
||||
test("a gift alias sends the original model only to the limited-quota endpoint", async () => {
|
||||
expect((await send()).status).toBe(200)
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0]).toMatchObject({ origin: "https://zcode.z.ai", body: { model: original } })
|
||||
expect(JSON.stringify(sent[0].body)).not.toContain(alias)
|
||||
})
|
||||
|
||||
test("a gift alias in a Request body is restored before sending upstream", async () => {
|
||||
const loader = await (await hooks()).auth.loader(async () => auth, { id: "zcode" })
|
||||
const request = new Request(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ model: alias, messages: [{ role: "user", content: "hi" }] }) })
|
||||
expect((await loader.fetch(request)).status).toBe(200)
|
||||
expect(sent[0]).toMatchObject({ origin: "https://zcode.z.ai", body: { model: original } })
|
||||
})
|
||||
|
||||
test("a gift refusal does not spend the paid plan", async () => {
|
||||
paid = 0
|
||||
giftReply = new Response(JSON.stringify({ error: { message: "unavailable" } }), { status: 403, headers: { "content-type": "application/json" } })
|
||||
expect((await send()).status).toBe(403)
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
||||
})
|
||||
|
||||
test("a gift quota error inside HTTP 200 becomes 429 without paid fallback", async () => {
|
||||
paid = 0
|
||||
giftReply = new Response(JSON.stringify({ code: "1005", msg: "exceed quota limit" }), { headers: { "content-type": "application/json" } })
|
||||
expect((await send()).status).toBe(429)
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0].origin).toBe("https://zcode.z.ai")
|
||||
})
|
||||
|
||||
test("an exhausted gift alias is refused locally without a paid request", async () => {
|
||||
paid = 0
|
||||
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
|
||||
expect((await send()).status).toBe(429)
|
||||
expect(sent).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("gift-only accounts can use their real gift alias", async () => {
|
||||
const only = { type: "oauth", access: jwt, refresh: JSON.stringify({ ...state, key: undefined, plan: undefined }), expires: 0 }
|
||||
expect((await send(alias, only)).status).toBe(200)
|
||||
expect(sent).toHaveLength(1)
|
||||
expect(sent[0].body.model).toBe(original)
|
||||
})
|
||||
|
||||
test("gift quota applies to the alias without the paid-week constraint", async () => {
|
||||
const u = await (await hooks()).auth.usage(async () => auth, { id: "zcode" })
|
||||
expect(u.windows[0].notModels).toContain(alias.toLowerCase())
|
||||
expect(u.windows[1].models).toContain(alias)
|
||||
expect(u.windows[1].used).toBe(25)
|
||||
})
|
||||
|
||||
test("an exhausted gift remains scoped to its alias while paid quota stays usable", async () => {
|
||||
paid = 20
|
||||
Object.assign(balance.balances[0], { used_units: 100, remaining_units: 0 })
|
||||
const u = await (await hooks()).auth.usage(async () => auth, { id: "zcode" })
|
||||
expect(u.windows[0].notModels).toContain(alias.toLowerCase())
|
||||
expect(u.windows[1].models).toEqual([alias])
|
||||
expect(u.windows[1].used).toBe(100)
|
||||
expect(u.windows[1].aside).not.toBe(true)
|
||||
})
|
||||
|
||||
test("a spent sibling does not exhaust a gift alias with a live bucket", async () => {
|
||||
balance.balances.push({ ...balance.balances[0], show_name: "Spent sibling", used_units: 100, remaining_units: 0 })
|
||||
const u = await (await hooks()).auth.usage(async () => auth, { id: "zcode" })
|
||||
expect(u.windows[1].models).toContain(alias)
|
||||
expect(u.windows[2].aside).toBe(true)
|
||||
})
|
||||
|
||||
test("a temporary gift block never turns an alias into a paid request", async () => {
|
||||
paid = 0
|
||||
_internal.blocked.set(state.key + "\0" + jwt + "\0" + original, Date.now() + 60_000)
|
||||
expect((await send()).status).toBe(429)
|
||||
expect(sent).toHaveLength(0)
|
||||
})
|
||||
|
||||
test("case variants of the same grant model keep one stable gift entry after usage refresh", async () => {
|
||||
balance.balances[0].capabilities = ["model:" + original.toUpperCase()]
|
||||
balance.balances.push({ ...balance.balances[0], capabilities: ["model:" + original], used_units: 100, remaining_units: 0 })
|
||||
const h = await hooks()
|
||||
const before = await h.provider.models({ models: {} }, { auth })
|
||||
await h.auth.usage(async () => auth, { id: "zcode" })
|
||||
const after = await h.provider.models({ models: {} }, { auth })
|
||||
const ids = (m) => Object.keys(m).filter((id) => id.endsWith("-Trial"))
|
||||
expect(ids(before)).toEqual([original.toUpperCase() + "-Trial"])
|
||||
expect(ids(after)).toEqual(ids(before))
|
||||
})
|
||||
|
||||
test("a grant ending before the normal route TTL is removed on the next model read", async () => {
|
||||
balance.plans[0].ends_at = now + 30
|
||||
const clientStart = now * 1000 + 1500
|
||||
const clock = spyOn(Date, "now").mockReturnValue(clientStart)
|
||||
try {
|
||||
const h = await hooks()
|
||||
expect((await h.provider.models({ models: {} }, { auth }))[alias]).toBeDefined()
|
||||
balance.server_time = now + 31
|
||||
clock.mockReturnValue(clientStart + 31_000)
|
||||
expect((await h.provider.models({ models: {} }, { auth }))[alias]).toBeUndefined()
|
||||
} finally {
|
||||
clock.mockRestore()
|
||||
}
|
||||
})
|
||||
+133
-55
@@ -130,6 +130,29 @@ const num = (v) => {
|
||||
return typeof n === "number" && Number.isFinite(n) ? n : undefined
|
||||
}
|
||||
|
||||
// the alias is the catalog spelling of the model plus -trial, so the picker
|
||||
// reads GLM-5.3-Trial while the loader strips it back to the raw name
|
||||
const giftID = (m) => (MODELS.find((x) => x.id.toLowerCase() === String(m).toLowerCase())?.id ?? m) + "-Trial"
|
||||
const uniqueModels = (names) => {
|
||||
const byName = new Map()
|
||||
for (const m of names) if (!byName.has(m.toLowerCase())) byName.set(m.toLowerCase(), m)
|
||||
return [...byName.values()]
|
||||
}
|
||||
const giftNames = (g) => g?.allModels ?? g?.models ?? []
|
||||
const giftModel = (g, id) => giftNames(g).find((m) => giftID(m).toLowerCase() === id.toLowerCase())
|
||||
const bucketModels = (x) => (Array.isArray(x.capabilities) ? x.capabilities : [])
|
||||
.map((c) => String(c ?? "").trim()).filter((c) => c.startsWith("model:") || !c.includes(":"))
|
||||
.map((c) => c.replace(/^model:/, "").trim()).filter(Boolean)
|
||||
|
||||
// Both the card and the request route use the same test for a spent bucket.
|
||||
// Older balances may omit remaining_units but still tell used and total.
|
||||
const giftSpent = (x) => {
|
||||
const left = num(x.remaining_units)
|
||||
if (left !== undefined) return left <= 0
|
||||
const total = num(x.total_units), used = num(x.used_units)
|
||||
return total !== undefined && used !== undefined && used >= total
|
||||
}
|
||||
|
||||
// startPlan is the gift an account can spend now ({models}), as ZCode reads
|
||||
// its balance: several plans can be active at once, and a model routes to
|
||||
// the gift when any of them has a live bucket serving it — a bucket past
|
||||
@@ -143,7 +166,8 @@ async function startPlan(jwt, device) {
|
||||
const same = (x, p) => (x.user_plan_id && p.user_plan_id ? x.user_plan_id === p.user_plan_id : String(x.plan_id ?? "") === String(p.plan_id ?? ""))
|
||||
const plans = Array.isArray(b.plans) ? b.plans : []
|
||||
const balances = Array.isArray(b.balances) ? b.balances : []
|
||||
const ms = new Set()
|
||||
const ms = new Set(), all = new Map()
|
||||
let ttl = 600_000
|
||||
let any = false
|
||||
let name = ""
|
||||
for (const p of plans) {
|
||||
@@ -151,22 +175,21 @@ async function startPlan(jwt, device) {
|
||||
const end = num(p?.ends_at)
|
||||
if (st !== "active" || (end > 0 && end <= now)) continue
|
||||
any = true
|
||||
if (end > 0) ttl = Math.min(ttl, (end - now) * 1000)
|
||||
if (!name) name = String(p?.name ?? "").trim()
|
||||
for (const x of balances) {
|
||||
if (!same(x, p)) continue
|
||||
const exp = num(x.expires_at)
|
||||
if (exp > 0 && exp <= now) continue
|
||||
// a bucket spends when it has quota: only remaining_units says so, and
|
||||
// a model whose every bucket says none drops out of models, so its
|
||||
// requests go to the coding plan without first asking the gift
|
||||
if ((num(x.remaining_units) ?? 1) <= 0) continue
|
||||
for (const c of Array.isArray(x.capabilities) ? x.capabilities : []) {
|
||||
const m = String(c ?? "").trim().replace(/^model:/, "").trim()
|
||||
if (m) ms.add(m)
|
||||
if (exp > 0) ttl = Math.min(ttl, (exp - now) * 1000)
|
||||
// Spent buckets still declare models; only live ones can spend now.
|
||||
for (const m of bucketModels(x)) {
|
||||
if (!all.has(m.toLowerCase())) all.set(m.toLowerCase(), m)
|
||||
if (!giftSpent(x)) ms.add(m)
|
||||
}
|
||||
}
|
||||
}
|
||||
return any ? { name: name || "Start Plan", models: [...ms] } : null
|
||||
return any ? { name: name || "Start Plan", models: [...ms], allModels: [...all.values()], ttl } : null
|
||||
}
|
||||
|
||||
// plansOf says where an account's requests go and what more it can spend:
|
||||
@@ -202,7 +225,7 @@ async function plansOf(s) {
|
||||
sure = false
|
||||
} catch {}
|
||||
}
|
||||
const out = { start, gift, at: Date.now(), ttl: sure ? 600_000 : 60_000 }
|
||||
const out = { start, gift, at: Date.now(), ttl: Math.min(sure ? 600_000 : 60_000, gift?.ttl ?? 600_000) }
|
||||
routes.set(id, out)
|
||||
return out
|
||||
}
|
||||
@@ -214,6 +237,8 @@ const blocked = new Map()
|
||||
// giftServes: the gift's buckets name their models lowercased ("glm-5.3-
|
||||
// flash"); what is asked for arrives as the plan lists it ("GLM-5.3-Flash").
|
||||
const giftServes = (gift, m) => (gift.models ?? []).some((x) => x.toLowerCase() === m.toLowerCase())
|
||||
const giftUsable = (s, gift, m) => !jwtExpired(s.jwt) && giftServes(gift, m) &&
|
||||
Date.now() >= (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
|
||||
|
||||
// spentUp is the gift saying it has nothing left to spend: its own no-
|
||||
// resource-package code 1113, its "exceed quota limit" 1005 — a spent gift
|
||||
@@ -478,15 +503,15 @@ async function giftOf(s) {
|
||||
const total = startNum(x.total_units), left = startNum(x.remaining_units)
|
||||
let used = startNum(x.used_units)
|
||||
if (total === undefined && used === undefined && left === undefined) continue
|
||||
const models = (Array.isArray(x.capabilities) ? x.capabilities : [])
|
||||
.map((c) => String(c ?? "").trim().replace(/^model:/, "").trim()).filter(Boolean)
|
||||
const models = bucketModels(x)
|
||||
const base = first(str(x.show_name), models.join(", "), "Credits")
|
||||
const w = { name: base, used: 0, _plan: str(owner.name) }
|
||||
const w = { name: base, used: 0, _plan: str(owner.name), _spent: giftSpent(x) }
|
||||
if (used === undefined) used = total !== undefined && left !== undefined ? total - left : 0
|
||||
if (total > 0) {
|
||||
w.used = (100 * used) / total
|
||||
w.display = `${compact(used)} / ${compact(total)}`
|
||||
}
|
||||
if (w._spent) w.used = Math.max(100, w.used)
|
||||
if (exp > 0) w.resetsAt = new Date(Math.trunc(exp) * 1000).toISOString()
|
||||
let span = 0
|
||||
for (const p of plans) {
|
||||
@@ -513,27 +538,67 @@ const NO_START = "this account has no GLM Coding Plan, and ZCode's Start Plan ha
|
||||
async function startUsage(s) {
|
||||
const g = await giftOf(s)
|
||||
if (!g) return { error: NO_START }
|
||||
for (const w of g.windows) delete w._plan
|
||||
for (const w of g.windows) {
|
||||
if (w.models?.length) w.models = [...w.models, ...w.models.map(giftID)]
|
||||
delete w._plan
|
||||
delete w._spent
|
||||
}
|
||||
return g
|
||||
}
|
||||
|
||||
// dualUsage is an account with both a Coding Plan and a gift: its card shows
|
||||
// both allowances, the Coding windows first and the gift's buckets after,
|
||||
// each keeping its own models and end. The gift's windows carry their plan's
|
||||
// name as a prefix so they are not mistaken for the coding plan's own. A
|
||||
// gift read that fails leaves just the Coding card: magpie hides a card's
|
||||
// windows behind an error and leaves it out of the menu bar and auto-switch,
|
||||
// so erroring here would hide a working Coding Plan over a gift hiccup.
|
||||
// dualUsage shows both pools but only the pool a request can use counts
|
||||
// for its model. Live gift models don't spend the Coding windows; spent
|
||||
// or blocked gift buckets stay visible without holding up the Coding Plan.
|
||||
// Fresh usage also updates the request cache, so a replenished or spent
|
||||
// gift takes effect before its ten-minute route cache expires. A failed
|
||||
// gift read leaves the working Coding Plan's card and route alone.
|
||||
async function dualUsage(s) {
|
||||
const out = await codingUsage(s)
|
||||
const cached = routes.get(s.key + "\0" + s.jwt)
|
||||
try {
|
||||
const g = await giftOf(s)
|
||||
if (g) out.windows = [...out.windows, ...g.windows.map((w) => {
|
||||
const p = w._plan
|
||||
delete w._plan
|
||||
return p && p !== w.name ? { ...w, name: p + " · " + w.name } : w
|
||||
})]
|
||||
} catch {}
|
||||
const gift = g ? { name: g.plan, models: [...new Set(g.windows.filter((w) => !w._spent)
|
||||
.flatMap((w) => w.models ?? []).map((m) => m.toLowerCase()))],
|
||||
allModels: uniqueModels(g.windows.flatMap((w) => w.models ?? [])) } : null
|
||||
if (cached) {
|
||||
cached.gift = gift
|
||||
const ends = g ? [g.until, ...g.windows.map((w) => w.resetsAt)].map((t) => Date.parse(t)).filter(Number.isFinite) : []
|
||||
if (ends.length) cached.ttl = Math.min(cached.ttl, Math.max(0, Math.min(...ends) - cached.at))
|
||||
}
|
||||
if (g) {
|
||||
// the gift's models are its trial entries alone: a plain model stays
|
||||
// on the coding plan, and the user picks the gift by its entry
|
||||
const notModels = gift.allModels.map((m) => giftID(m).toLowerCase())
|
||||
if (notModels.length) out.windows = out.windows.map((w) => w.aside ? w : { ...w, notModels })
|
||||
// Several buckets may serve one model: one spent sibling cannot block it.
|
||||
const best = new Map()
|
||||
g.windows.forEach((w, i) => {
|
||||
for (const m of w.models ?? []) {
|
||||
const key = m.toLowerCase(), old = best.get(key), prev = g.windows[old]
|
||||
if (old === undefined || (prev._spent && !w._spent) || (prev._spent === w._spent && w.used < prev.used)) best.set(key, i)
|
||||
}
|
||||
})
|
||||
out.windows.push(...g.windows.map(({ _plan: p, _spent, ...w }, i) => {
|
||||
const selected = gift.allModels.filter((m) => best.get(m.toLowerCase()) === i)
|
||||
const models = selected.map(giftID)
|
||||
const scoped = models.length ? { ...w, models } : { ...w, aside: true }
|
||||
// the card names a bucket's model as the picker does (GLM-5.3-Flash-Trial);
|
||||
// no plan prefix — the card's section header already says the account
|
||||
let name = w.name
|
||||
for (const m of selected) {
|
||||
const at = name.toLowerCase().indexOf(m.toLowerCase())
|
||||
if (at >= 0) name = name.slice(0, at) + giftID(m) + name.slice(at + m.length)
|
||||
}
|
||||
return { ...scoped, name }
|
||||
}))
|
||||
}
|
||||
} catch {
|
||||
if (cached) {
|
||||
cached.gift = null
|
||||
cached.at = Date.now()
|
||||
cached.ttl = 60_000 // an uncertain gift is read again sooner
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -1285,15 +1350,24 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
async models(provider, { auth } = {}) {
|
||||
const s = stateOf(auth)
|
||||
if (!s) return provider.models
|
||||
const start = await plansOf(s).then((r) => r.start).catch(() => false)
|
||||
const { start, gift: known } = await plansOf(s).catch(() => ({ start: false, gift: null }))
|
||||
const gift = start ? await startPlan(s.jwt, s.device).catch(() => null) : known
|
||||
const base = start ? START_BASE : s.base
|
||||
let ms = modelsOf(await zcodeConfig().catch(() => null), planID(base))
|
||||
const cfg = await zcodeConfig().catch(() => null)
|
||||
let ms = modelsOf(cfg, planID(base))
|
||||
// ZCode's config can't be had: its table stands in, and magpie keeps
|
||||
// the list it was told last, as the built-in keeps the one it fetched last
|
||||
const fell = !ms.length
|
||||
if (fell) ms = start ? START_MODELS : MODELS
|
||||
const url = s.base + "/v1"
|
||||
const out = Object.fromEntries(ms.map((m) => [m.id, model(m, url)]))
|
||||
const details = [...ms, ...modelsOf(cfg, planID(START_BASE)), ...START_MODELS]
|
||||
for (const raw of giftNames(gift)) {
|
||||
const id = giftID(raw)
|
||||
if (out[id]) continue
|
||||
const m = details.find((m) => m.id.toLowerCase() === raw.toLowerCase()) ?? { efforts: [] }
|
||||
out[id] = model({ ...m, id }, url)
|
||||
}
|
||||
if (fell) out[Symbol.for("magpie.fellBack")] = true
|
||||
return out
|
||||
},
|
||||
@@ -1313,7 +1387,8 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
if (!s) throw new Error("not signed in to ZCode")
|
||||
let url = input instanceof Request ? input.url : String(input)
|
||||
const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
|
||||
const { start: alone, gift } = await plansOf(s)
|
||||
const { start: alone, gift: known } = await plansOf(s)
|
||||
let gift = known
|
||||
let key = s.key
|
||||
if (isTeam(s) && !key) {
|
||||
key = await teamKey(s)
|
||||
@@ -1325,14 +1400,24 @@ 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
|
||||
if (!alone && gift && opts.body != null) {
|
||||
let orig, forcedGift = false
|
||||
if (opts.body != null) {
|
||||
orig = opts.body = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()
|
||||
delete opts.duplex
|
||||
const m = modelOf(orig)
|
||||
// a ZCode sign-in past its end reaches no gift: the coding plan
|
||||
// takes the request, as it did before the gift was known
|
||||
start = !!m && !jwtExpired(s.jwt) && giftServes(gift, m) && Date.now() >= (blocked.get(s.key + "\0" + s.jwt + "\0" + m) ?? 0)
|
||||
let m = modelOf(orig)
|
||||
if (m.toLowerCase().endsWith("-trial")) {
|
||||
gift ??= await startPlan(s.jwt, s.device).catch(() => null)
|
||||
const raw = giftModel(gift, m)
|
||||
const available = raw && giftUsable(s, gift, raw)
|
||||
if (!available) {
|
||||
const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `ZCode's limited quota for ${raw} is exhausted or temporarily unavailable` : `ZCode has no active limited quota for ${m}` }
|
||||
return kept(new Response(JSON.stringify({ type: "error", error }), { status: raw ? 429 : 400, headers: { "content-type": "application/json" } }))
|
||||
}
|
||||
orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: raw })
|
||||
m = raw
|
||||
forcedGift = true
|
||||
}
|
||||
start = alone || forcedGift
|
||||
}
|
||||
const swap = (base) => {
|
||||
for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
|
||||
@@ -1363,18 +1448,13 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
h.set("Authorization", "Bearer " + key)
|
||||
}
|
||||
let res = await fetch(url, { ...opts, headers: h })
|
||||
// a dual account's gift answer that can't serve the request goes
|
||||
// to its coding plan instead, as the agent sent it: any status
|
||||
// 400 or over (its 405, its 401, its 5xx — a paid plan is waiting,
|
||||
// and a gift that keeps refusing would otherwise black out the
|
||||
// account), and its quota answers inside a 200. Only a quota
|
||||
// answer keeps that model off the gift for a minute: a refusal
|
||||
// that says nothing about quota is asked again next request.
|
||||
// Every 429 counts as spent, Z.ai's 1302/1303 rate limits among
|
||||
// them — replaying one to the coding plan is the good answer, and
|
||||
// the minute's block keeps a rate limit from being knocked twice.
|
||||
// A stream's body is never read here.
|
||||
if (start && !alone) {
|
||||
// a trial entry's gift answer that can't serve the request is
|
||||
// the agent's answer, not the coding plan's: the user picked the
|
||||
// gift, so a spent bucket says 429 (its quota error inside a 200
|
||||
// among them) and anything else goes on as it came. A quota
|
||||
// answer keeps that model off the gift for a minute, so a rate
|
||||
// limit is not knocked twice. A stream's body is never read here.
|
||||
if (start && forcedGift) {
|
||||
const json = (res.headers.get("content-type") ?? "").includes("application/json")
|
||||
if (res.status >= 400 || json) {
|
||||
const text = await res.text()
|
||||
@@ -1382,14 +1462,9 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
if (!spent && res.status < 400) return 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), Date.now() + 60_000)
|
||||
blocked.set(s.key + "\0" + s.jwt + "\0" + modelOf(orig).toLowerCase(), Date.now() + 60_000)
|
||||
}
|
||||
swap(s.base)
|
||||
h = new Headers(opts.headers)
|
||||
h.delete("authorization")
|
||||
h.set("x-api-key", key)
|
||||
h.set("Authorization", "Bearer " + key)
|
||||
res = await fetch(url, { ...opts, body: orig, headers: h })
|
||||
return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : kept(res, text)
|
||||
}
|
||||
}
|
||||
// the plan's answer goes on as it came, the account kept: the
|
||||
@@ -1411,6 +1486,9 @@ export async function ZCodeAuthPlugin({ client }) {
|
||||
const saved = (out) => {
|
||||
const plan = s.plan || auth?.plan
|
||||
if (plan && !out.plan) out.plan = plan
|
||||
// MCP reads as a footnote: its window goes last on the card
|
||||
if (Array.isArray(out.windows) && out.windows.some((w) => w.name === "MCP · Month"))
|
||||
out.windows = [...out.windows.filter((w) => w.name !== "MCP · Month"), ...out.windows.filter((w) => w.name === "MCP · Month")]
|
||||
out.signIn = "kept"
|
||||
return out
|
||||
}
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@magpie-community/opencode-zcode-auth",
|
||||
"version": "0.1.8",
|
||||
"version": "0.1.9",
|
||||
"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",
|
||||
|
||||
@@ -144,7 +144,7 @@ test("ZCode's Start Plan: its buckets, each for its models", async () => {
|
||||
signIn: "kept",
|
||||
plan: "Start Plan", until: new Date((now + 7 * 86400) * 1000).toISOString(), renew: "off",
|
||||
windows: [{ name: "GLM-5.1", used: 25, display: "250000 / 1000000", resetsAt: new Date((now + 3600) * 1000).toISOString(), span: 86400,
|
||||
models: ["GLM-5.1"] }],
|
||||
models: ["GLM-5.1", "GLM-5.1-Trial"] }],
|
||||
})
|
||||
expect(calls[0].url.origin).toBe("https://zcode.z.ai")
|
||||
expect(calls[0].headers["X-Device-Mid"]).toBe("11111111-2222-4333-8444-555555555555")
|
||||
@@ -159,7 +159,7 @@ test("ZCode's Start Plan: its buckets, each for its models", async () => {
|
||||
balance = startBalance(now, "active")
|
||||
balance.balances = [{ plan_id: "zai-start-plan", capabilities: [" model: GLM-5-Turbo ", "model:"], total_units: 200, remaining_units: "150",
|
||||
period_start: now, period_end: now + 7 * 86400 }]
|
||||
expect((await usage(auth)).windows).toEqual([{ name: "GLM-5-Turbo", used: 25, display: "50 / 200", span: 7 * 86400, models: ["GLM-5-Turbo"] }])
|
||||
expect((await usage(auth)).windows).toEqual([{ name: "GLM-5-Turbo", used: 25, display: "50 / 200", span: 7 * 86400, models: ["GLM-5-Turbo", "GLM-5-Turbo-Trial"] }])
|
||||
|
||||
// its token run out
|
||||
expect(await usage(oauth({ site: "zai", jwt: jwt(now - 60) }))).toEqual({ signIn: "kept", error: "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)" })
|
||||
|
||||
Reference in New Issue
Block a user