zcode 0.1.49: a free-first refusal no longer answers the -Trial entry a local "quota exhausted" 429; free first gets a switch in magpie's provider editor

Can4ry_ on X (11-04): testing GLM-5.3-Flash-Trial in magpie answered
"429 · ZCode's limited quota for glm-5.3-flash is exhausted or temporarily
unavailable" while ZCode's own app was served, glm-5.3-flash kept using
the Coding Plan after the Start Plan opened at 23:00, and there was no
freeFirst setting under the ZCode provider.

Cause: free first's plain GLM-5.3-Flash request goes to the gift first.
When zcode.z.ai turned it away with 405/3012 (risk control, or 0.1.46/0.1.47's
3.14.3 prompt texts), restModel rested glm-5.3-flash in `blocked`, the same
map a -Trial entry's quota check reads. So for the next minute the Trial
entry answered a local 429 that called the quota exhausted, without asking
ZCode, and every plain request in that minute went to the plan. The
suffix it added, "ZCode answered 429", was wrong too, and it pushed the
spent words off the end of the message, so magpie's zcodeSpentWords
didn't match and the gateway rested the whole account.

Change:
- A free-first refusal that is not a quota answer rests the model in a
  new `sidelined` map, read by free first only. A quota answer still rests
  it in `blocked`, which the -Trial entry obeys too.
- The local 429 keeps "ZCode's limited quota for X is exhausted or
  temporarily unavailable" last; why it rests now goes in front.
- auth.options declares a "Free quota first" switch (free_first, on by
  default, zh/zh-TW/ja/de words), read through input.magpie.options. Off
  keeps the plain models on the plan. A JSON freeFirst: false still turns
  it off; an absent key (an older magpie, OpenCode) leaves the JSON's word.
- README says where the switch is and what a refusal rests now.

Run: bun test packages/zcode on mote under a temp HOME, 197 pass, 0 fail.
bun scripts/check.mjs on mote, exit 0.

Broken by hand: the new dual tests against HEAD's index.mjs (the old
code), 4 fail. "a free-first refusal leaves the -Trial entry asking
ZCode" fails with 429 for 200, the reported case. The others are the
spent words test (no match), the switch test, and the block-page test,
whose second plain request went to the gift again.

Not tried: a real account. The owner's account has no live Start Plan to
be refused or spent. Not tried: magpie's editor showing the switch. That
comes from host.js optionsOf and app.js pluginOptionsField, unchanged.
This commit is contained in:
yetone
2026-11-04 01:59:22 +08:00
parent 97e9c23804
commit 36a017ac9e
4 changed files with 132 additions and 25 deletions
+12 -3
View File
@@ -147,8 +147,12 @@ but an agent that always asks the plain model never sees the gift.
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 off for the whole plugin
in magpie's Plugins › Options
minute's rest a refusal just earned. In magpie, the switch is in the
provider's editor: Providers › ZCode, **Free quota first** under Plugin
options, just above Advanced (since 0.1.49). It is on by default; off
keeps the plain models on the plan. The JSON below still works, and a
`freeFirst: false` there keeps it off whatever the switch says. Turn it
off for the whole plugin in magpie's Plugins › Options
```json
{ "freeFirst": false }
@@ -172,7 +176,12 @@ 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 —
behind it go straight to the plan. Only a spent answer holds the
model's `-Trial` entry too; a refusal for another reason (a 405/3012)
keeps free first off the gift for the minute but leaves the `-Trial`
entry asking ZCode, which answers it as it came. Before 0.1.49 the two
rests were one, and a refused free-first request made the next `-Trial`
request answer a local "quota exhausted" 429 without asking. 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
+66 -2
View File
@@ -36,6 +36,7 @@ const real = globalThis.fetch
beforeEach(async () => {
_internal.routes.clear()
_internal.blocked.clear()
_internal.sidelined.clear()
_internal.edge.until = 0
sent.length = 0
for (const k of Object.keys(answers)) delete answers[k]
@@ -336,8 +337,71 @@ test("a Start Plan block page is answered from the plan too", async () => {
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())
// the block keeps free first off the gift a minute, but it is no quota
// answer, so a -Trial entry is not held by it (sidelined, not blocked)
expect(_internal.sidelined.get(KEY + "\0" + jwt + "\0glm-5.3-flash")).toBeGreaterThan(Date.now())
expect(_internal.blocked.get(KEY + "\0" + jwt + "\0glm-5.3-flash")).toBeUndefined()
const again = await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") })
expect(again.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(2)
})
// Can4ry_ on X: free first's GLM-5.3-Flash was turned away (405/3012) and
// rested, and the GLM-5.3-Flash-Trial test then answered a local "quota
// exhausted" 429 without asking ZCode, while ZCode's own app was served
test("a free-first refusal leaves the -Trial entry asking ZCode", async () => {
planAndBalance()
let gift = 0
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = () => {
gift++
return gift === 1
? new Response(JSON.stringify({ error: { message: "request has been blocked due to unusual activity", code: 3012 } }), { status: 405, headers: { "content-type": "application/json" } })
: new Response(JSON.stringify({ type: "message", content: [] }), { 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 ask = (model) => opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body(model) })
expect((await ask("GLM-5.3-Flash")).status).toBe(200)
const res = await ask("GLM-5.3-Flash-Trial")
expect(res.status).toBe(200)
expect(gift).toBe(2)
expect(JSON.parse(sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages")).at(-1).body).model).toBe("GLM-5.3-Flash")
})
// magpie's gateway knows the plugin's spent words only at the end of the
// message (zcode_trial.go's zcodeSpentWords), so a rested entry's local 429
// keeps them last, or the whole account would rest
test("a rested -Trial entry's local 429 ends with the words magpie reads", async () => {
planAndBalance()
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response(JSON.stringify({ code: "1113", msg: "余额不足" }), { headers: { "content-type": "application/json" } })
expect((await sendTo(MSG, body("GLM-5.3-Flash-Trial"))).status).toBe(429)
const before = sent.length
const res = await sendTo(MSG, body("GLM-5.3-Flash-Trial"))
expect(res.status).toBe(429)
expect(sent.slice(before).some((c) => c.path.endsWith("/messages"))).toBe(false)
const said = JSON.parse(await res.text()).error.message
const m = said.match(/(?:^|: )ZCode's limited quota for (\S+) is exhausted or temporarily unavailable$/)
expect(m?.[1].toLowerCase()).toBe("glm-5.3-flash")
expect(said).toContain("not asked again for a minute")
})
test("magpie's free-first switch is declared on, and off keeps the plain model 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 plugin = async (value) => (await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } }, magpie: { options: (p) => (p === "zcode" ? { free_first: value } : {}) } }, {})).auth
const on = await plugin(true)
expect(on.options.find((o) => o.key === "free_first")).toMatchObject({ default: true, labels: { zh: "优先用免费额度" } })
const ask = async (h) => (await h.loader(async () => coding, { id: "zcode" })).fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") })
expect((await ask(on)).status).toBe(200)
expect(sent.at(-1).origin).toBe("https://zcode.z.ai")
expect((await ask(await plugin(false))).status).toBe(200)
expect(sent.at(-1).origin).toBe("https://api.z.ai")
// the switch on never undoes a freeFirst: false the user wrote
const opts = await on.loader(async () => coding, { id: "zcode", options: { freeFirst: false } })
await opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash") })
expect(sent.at(-1).origin).toBe("https://api.z.ai")
})
test("a gift's block page holds free first on the plan and a trial entry here (plugins#649)", async () => {
+53 -19
View File
@@ -23,6 +23,8 @@ import { isAbsolute, join } from "node:path"
import PROMPT from "./prompt.mjs"
const PROVIDER = "zcode"
// FREE_FIRST is magpie's switch for free first in the provider's editor
const FREE_FIRST = "free_first"
const ZCODE = "https://zcode.z.ai"
const ZAI_API = "https://api.z.ai"
const BIGMODEL_API = "https://bigmodel.cn" // BigModel's business API, where ZCode asks it
@@ -274,6 +276,17 @@ async function plansOf(s) {
// blocked remembers the models a gift said it has none left for: a key+jwt+
// model for a minute, so one turn that is refused does not ask again.
const blocked = new Map()
// sidelined remembers, the same way, the models whose gift turned free
// first away for another reason (a 405/3012, a block page): free first
// leaves them on the plan for the minute, but a -Trial entry, the user's
// own pick of the gift, still asks ZCode and gets its real answer. Once
// one rest served both, and a refusal under free first answered the
// Trial entry locally as a quota "exhausted" it never was (Can4ry_ on X).
const sidelined = new Map()
const rest = (map, k) => {
for (const [x, until] of map) if (Date.now() >= until) map.delete(x)
map.set(k, Date.now() + 60_000)
}
// 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").
@@ -281,6 +294,7 @@ const giftServes = (gift, m) => (gift.models ?? []).some((x) => x.toLowerCase()
const giftRested = (s, m) => Date.now() < (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
const giftUsable = (s, gift, m) => !jwtExpired(s.jwt) && giftServes(gift, m) &&
Date.now() >= (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
const giftSidelined = (s, m) => Date.now() < (sidelined.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
@@ -2278,7 +2292,7 @@ function sessionOf(id, device) {
// ---- the plugin ------------------------------------------------------------------
export async function ZCodeAuthPlugin({ client }, options = {}) {
export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
const log = (message) => {
try {
client?.app?.log?.({ body: { service: "zcode-auth", level: "error", message } })
@@ -2289,9 +2303,14 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
// provider carries no freeFirst of its own. It is on unless one of them
// says false: a gift ZCode hands out (each weekend, sgfvdsg86265 on X)
// lapses unused behind an agent that asks the plain model, and every
// failure of the gift is answered from the plan.
// failure of the gift is answered from the plan. magpie's switch in the
// provider's editor (FREE_FIRST, auth.options below) turns it off too;
// it is on by default, so a JSON freeFirst: false a user wrote before
// the switch existed keeps it off. A key magpie doesn't report (an older
// magpie, OpenCode) leaves it as the JSON says.
const freeFirst = (providerOptions) =>
providerOptions?.freeFirst !== undefined ? providerOptions.freeFirst !== false : options?.freeFirst !== false
magpie?.options?.(PROVIDER)?.[FREE_FIRST] !== false &&
(providerOptions?.freeFirst !== undefined ? providerOptions.freeFirst !== false : options?.freeFirst !== false)
const oauth = (site) => ({
type: "oauth",
label: `ZCode: ${SITES[site].name}${site === "bigmodel" ? " (智谱)" : ""} GLM Coding Plan`,
@@ -2374,6 +2393,23 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
// how many accounts take requests at once, the others in reserve
// (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all
maxAccounts: DEFAULT_ACCOUNTS,
// magpie's own switches (OpenCode never reads auth.options), read at
// each request through input.magpie
options: [
{
key: FREE_FIRST,
label: "Free quota first",
description: "When on, the plain GLM models spend ZCode's free Start Plan quota (the -Trial entries' quota) before the GLM Coding Plan, and go to the plan when it is spent or refused. Off: only the -Trial entries use it. freeFirst: false in the options JSON turns it off too.",
labels: { zh: "优先用免费额度", "zh-TW": "優先用免費額度", ja: "無料枠を優先", de: "Gratis-Kontingent zuerst" },
descriptions: {
zh: "开启后,普通的 GLM 模型先用 ZCode 的免费 Start Plan 额度(即 -Trial 条目的额度),用完或被拒时再用 GLM Coding Plan。关闭后只有 -Trial 条目会用它。选项 JSON 里的 freeFirst: false 也会关闭它。",
"zh-TW": "開啟後,一般的 GLM 模型先用 ZCode 的免費 Start Plan 額度(即 -Trial 項目的額度),用完或被拒時再用 GLM Coding Plan。關閉後只有 -Trial 項目會用它。選項 JSON 裡的 freeFirst: false 也會關閉它。",
ja: "オンにすると、通常の GLM モデルは GLM Coding Plan より先に ZCode の無料 Start Plan 枠(-Trial 項目の枠)を使い、使い切るか拒否されるとプランに戻ります。オフでは -Trial 項目だけが使います。オプション JSON の freeFirst: false でもオフになります。",
de: "Ist dies an, nutzen die normalen GLM-Modelle zuerst ZCodes freies Start-Plan-Kontingent (das der -Trial-Einträge) und erst danach den GLM Coding Plan. Aus: nur die -Trial-Einträge nutzen es. freeFirst: false im Optionen-JSON schaltet es auch aus.",
},
default: true,
},
],
async loader(getAuth, provider) {
const s0 = stateOf(await getAuth())
if (!s0) return {}
@@ -2421,13 +2457,13 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
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${giftRested(s, raw) ? " (ZCode answered 429 to the last request for it, so it is not asked again for a minute)" : ""}` : `ZCode has no active limited quota for ${m}` }
const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `${giftRested(s, raw) ? `ZCode said the last request for ${raw} was over its quota, so it is not asked again for a minute: ` : ""}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: wireModel(raw) })
m = raw
forcedGift = true
} else if (!alone && !edgeHeld() && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m)) {
} else if (!alone && !edgeHeld() && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
// free first: the plain model spends the account's own live
// gift before it spends the coding plan, under the name the
// gift lists. The gift is the route's cache alone (a failed
@@ -2455,13 +2491,14 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
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)
// restModel is free first's gift turning this model away: the
// model rests a minute and the route is dropped, so the requests
// behind it re-read the balance and go straight to the plan. A
// quota answer rests it in blocked, which a -Trial entry obeys
// too; any other refusal (spent false) in sidelined, which only
// free first reads.
const restModel = (spent) => {
rest(spent ? blocked : sidelined, s.key + "\0" + s.jwt + "\0" + asked.toLowerCase())
routes.delete(s.key + "\0" + s.jwt)
}
// replayOnPlan is free first's answer to a gift that refused
@@ -2552,7 +2589,7 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
// a block page holds every request off zcode.z.ai a while
if (EDGE_PAGE.test(text)) edge.until = Date.now() + EDGE_HOLD
if (freeGift) {
restModel()
restModel(false)
return done(kept(await replayOnPlan()))
}
if (s.key && !forcedGift) routes.delete(s.key + "\0" + s.jwt)
@@ -2580,10 +2617,7 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
const text = await res.text()
const spent = spentUp(text, res.status)
if (!spent && res.status < 400) return done(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).toLowerCase(), Date.now() + 60_000)
}
if (spent) rest(blocked, s.key + "\0" + s.jwt + "\0" + modelOf(orig).toLowerCase())
return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text))
}
}
@@ -2603,7 +2637,7 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
const cap = busy(res.status, text)
const spent = !cap && spentUp(text, res.status)
if (spent) {
restModel()
restModel(true)
return done(kept(await replayOnPlan()))
}
if (res.status >= 400) {
@@ -2736,4 +2770,4 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
// config sets what zcodeConfig has read, for tests: null is ZCode's config
// out of reach, undefined forgets it
const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
export const _internal = { edge, EDGE_HOLD, config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
export const _internal = { edge, EDGE_HOLD, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-zcode-auth",
"version": "0.1.48",
"version": "0.1.49",
"description": "OpenCode provider plugin: signs in to Z.ai's or BigModel's (智谱) GLM Coding Plan as ZCode does, including team seats and ZCode's Start Plan, and claims its gift plans daily",
"type": "module",
"main": "./opencode.mjs",