zcode 0.1.43: a block page holds zcode.z.ai off three minutes, for every account (#649, frank6com)

frank6com's 405 ("the provider's network firewall blocked requests from
this IP") is Aliyun's edge firewall in front of zcode.z.ai answering
POST /api/v1/zcode-plan/anthropic/v1/messages (the Start Plan) with its
405 HTML page. It is the address, not the method nor the account: ZCode's
own app got the same 405. Two Start Plan accounts and three sessions with
subagents (up to 6 requests at once from one IP), and every request after
the block went on knocking on the firewall, from both accounts, since the
gateway falls back but rests nothing for an edge block.

Now a block page sets a process-wide hold (edge.until, EDGE_HOLD three
minutes): while it lasts, a Start Plan request and a picked -Trial entry
are answered here with the same 405, permission_error and
provider.BlockedHint word for word, plus until when, so magpie's
EdgeBlocked and retryable still send the request to the group's next
provider. Free first leaves the gift and keeps a dual account on its
coding plan (api.z.ai, another host). A 3012 or a bare 405 is the
account's and holds nothing. The first request after the hold asks again.

Run, at this head, on mote:
- packages/zcode: bun test, 189 pass, 0 fail.
- bun scripts/check.mjs zcode: ok.
- Broken by hand: without the line that sets the hold, both new tests
  are red (65 pass, 2 fail in start + dual); without !edgeHeld() in free
  first, the dual test is red (66 pass, 1 fail).

Not tried: a real zcode.z.ai request. Reproducing needs the address
blocked, and asking until it is would block the owner's network. The page
the tests use is the one plugins#425 recorded.
This commit is contained in:
yetone
2026-11-03 02:28:30 +08:00
parent 58adeadfac
commit 036fb6ed43
5 changed files with 121 additions and 4 deletions
+8 -1
View File
@@ -38,7 +38,14 @@ over Anthropic's Messages API. Provider id: `zcode`.
for unusual activity (code 3012); …", which magpie reads as the account
restricted: it rests, and the group's other providers are used. Only
ZCode support lifts such a block. A block page from ZCode's edge
firewall says this network's address was blocked instead.
firewall says this network's address was blocked instead. Since 0.1.43
(plugins#649) such a page also holds zcode.z.ai off for three minutes,
for every account of the plugin, since they share the address: the
Start Plan and a picked `-Trial` entry are answered at once with the
same 405 and words, so magpie still uses the group's other providers,
and free first keeps a dual account on its coding plan. The first
request after the three minutes asks again. A GLM Coding Plan key, on
api.z.ai, is never held.
- The Start Plan's token can't be refreshed. When it runs out, sign in
again.
- Every request, on any plan, names its conversation in `x-session-id`,
+24
View File
@@ -36,6 +36,7 @@ const real = globalThis.fetch
beforeEach(async () => {
_internal.routes.clear()
_internal.blocked.clear()
_internal.edge.until = 0
sent.length = 0
for (const k of Object.keys(answers)) delete answers[k]
globalThis.fetch = async (input, init = {}) => {
@@ -339,6 +340,29 @@ test("a Start Plan block page is answered from the plan too", async () => {
expect(_internal.blocked.get(KEY + "\0" + jwt + "\0glm-5.3-flash")).toBeGreaterThan(Date.now())
})
test("a gift's block page holds free first on the plan and a trial entry here (plugins#649)", async () => {
planAndBalance()
answers["/api/v1/zcode-plan/anthropic/v1/messages"] = new Response("<html>Sorry, your request has been blocked due to unusual activity. errors.aliyun.com</html>", { status: 405, headers: { "content-type": "text/html" } })
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) })
const gift = () => sent.filter((c) => c.origin === "https://zcode.z.ai" && c.path.endsWith("/messages")).length
const plan = () => sent.filter((c) => c.origin === "https://api.z.ai" && c.path.endsWith("/messages")).length
expect((await ask("GLM-5.3-Flash")).status).toBe(200)
expect([gift(), plan()]).toEqual([1, 1])
expect(_internal.edge.until).toBeGreaterThan(Date.now())
// the model's minute of rest is not what holds it: a model the gift
// serves, unrested, stays on the plan too while the address is held
_internal.blocked.clear()
expect((await ask("GLM-5.3-Flash")).status).toBe(200)
expect([gift(), plan()]).toEqual([1, 2])
// the user's pick of the gift is answered here, the network's 405
const res = await ask("GLM-5.3-Flash-Trial")
expect(res.status).toBe(405)
expect(JSON.parse(await res.text()).error.message).toContain("the provider's network firewall blocked requests from this IP")
expect([gift(), plan()]).toEqual([1, 2])
})
const giftUnreachable = (when = () => true) => {
const under = globalThis.fetch
globalThis.fetch = async (input, init = {}) => {
+35 -2
View File
@@ -1899,6 +1899,33 @@ const START_REFUSED = /unusual activity|request has been blocked|"code"\s*:\s*"?
// or code 3012.
const startRefused = (status, text) => status >= 400 && (status === 405 || START_REFUSED.test(text))
// edge is the hold a block page puts on this computer's address: zcode.z.ai
// (the Start Plan, a gift) is not asked again until edge.until, and its
// requests are answered here with the same 405 and START_EDGE, so magpie
// still reads them as the network's (provider.EdgeBlocked) and asks the
// group's next provider. Every account of this process goes out from the
// one address, so the hold is the process's, not an account's. Asking on
// while the address is blocked, from every account and every session, only
// knocks again on a firewall that is counting (plugins#649: two accounts,
// three sessions and their subagents, and ZCode's own app blocked too; a
// block in #369 lasted about seven minutes). EDGE_HOLD is short enough that
// a user who switched network or proxy waits little for it.
const EDGE_HOLD = 3 * 60_000
const edge = { until: 0 }
const edgeHeld = () => Date.now() < edge.until
function hhmm(t) {
const d = new Date(t)
return String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0") + ":" + String(d.getSeconds()).padStart(2, "0")
}
// edgeHeldAnswer is a held request's answer: the block page's status and
// meaning, and until when this computer holds off.
function edgeHeldAnswer() {
const error = { type: "permission_error", message: `405 ${STATUS_TEXT[405]} — ${START_EDGE} (ZCode's Start Plan is not asked again from here until ${hhmm(edge.until)}, plugins#649)` }
return new Response(JSON.stringify({ type: "error", error }), { status: 405, statusText: STATUS_TEXT[405], headers: { "content-type": "application/json" } })
}
// startBlocked is the refusal's answer: what the vendor said (its status
// for a block page), then what it means. A block page is the network's;
// anything else, ZCode's JSON 3012 or a bare 405, the account's.
@@ -2382,7 +2409,7 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
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)) {
} else if (!alone && !edgeHeld() && 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
@@ -2442,6 +2469,10 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
delete opts.duplex
return askBusy(u, opts, h2)
}
// a block page held this computer off zcode.z.ai (edge): the
// Start Plan and a picked gift are answered here; free first
// already left the gift for the plan
if (start && edgeHeld()) return kept(edgeHeldAnswer())
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")
@@ -2500,6 +2531,8 @@ export async function ZCodeAuthPlugin({ client }, options = {}) {
// 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)
// 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()
return done(kept(await replayOnPlan()))
@@ -2685,4 +2718,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 = { 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, 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.42",
"version": "0.1.43",
"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",
+53
View File
@@ -47,6 +47,7 @@ afterEach(() => {
globalThis.fetch = real
got.length = 0
answer = null
_internal.edge.until = 0
})
const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16)
@@ -410,6 +411,57 @@ test("a team seat's request goes as the agent sent it, ZCode's token or not", as
const START_RESTRICTED = "ZCode's risk control blocked this account for unusual activity (code 3012); it rests, and the group's other providers are used. If the ZCode app fails on this account too, only ZCode support can lift the block"
const START_EDGE = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy"
// plugins#649: a block page is the address's, so the requests after it are
// held off zcode.z.ai a while, from every account of the process, and
// answered with the same 405 and hint; the coding plan, on another host,
// goes on. A 3012 is the account's and holds nothing.
test("a block page holds the Start Plan off zcode.z.ai for every account a while, and nothing else (plugins#649)", async () => {
const ask = async (auth) => {
routeToFake()
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } })
const opts = await hooks.auth.loader(async () => auth, { id: "zcode" })
const res = await opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode" }, body: agentText })
return { status: res.status, text: await res.text(), signIn: res.headers.get("x-magpie-sign-in") }
}
const messages = () => got.filter((r) => r.path.endsWith("/messages")).length
// a 3012 holds nothing: the next request is asked
answer = () => Response.json({ code: 3012, msg: "request has been blocked due to unusual activity." }, { status: 405 })
await ask(start("zai"))
await ask(start("zai"))
expect(messages()).toBe(2)
got.length = 0
answer = () => new Response("<html>Sorry, your request has been blocked due to unusual activity. errors.aliyun.com</html>", { status: 405, headers: { "content-type": "text/html" } })
const before = Date.now()
let r = await ask(start("zai"))
expect(r.status).toBe(405)
expect(messages()).toBe(1)
expect(_internal.edge.until).toBeGreaterThanOrEqual(before + _internal.EDGE_HOLD)
expect(_internal.edge.until).toBeLessThanOrEqual(Date.now() + _internal.EDGE_HOLD)
// held: the same account and another one are answered here, with the
// same status and magpie's BlockedHint, so the gateway still falls back
answer = () => Response.json({ type: "message", content: [] })
const other = { type: "oauth", access: jwt, refresh: JSON.stringify({ site: "zai", device: "99999999-2222-4333-8444-555555555555", jwt, plan: "Start Plan" }), expires: 0 }
for (const auth of [start("zai"), other]) {
r = await ask(auth)
expect(r.status).toBe(405)
expect(r.signIn).toBe("kept")
const e = JSON.parse(r.text).error
expect(e.type).toBe("permission_error")
expect(e.message).toStartWith("405 Method Not Allowed — " + START_EDGE + " (")
expect(e.message).toMatch(/until \d\d:\d\d:\d\d/)
}
expect(messages()).toBe(1)
// a GLM Coding Plan key goes to api.z.ai, held or not
r = await ask({ type: "api", key: "one.secret", metadata: { site: "zai" } })
expect(r.status).toBe(200)
expect(messages()).toBe(2)
// once the hold is over, the Start Plan is asked again
_internal.edge.until = Date.now() - 1
r = await ask(start("zai"))
expect(r.status).toBe(200)
expect(messages()).toBe(3)
})
test("the Start Plan's 3012 says ZCode blocked the account, and a block page the network (plugins#348, #425)", async () => {
const ask = async (auth, url = "https://api.z.ai/api/anthropic/v1/messages") => {
routeToFake()
@@ -442,6 +494,7 @@ test("the Start Plan's 3012 says ZCode blocked the account, and a block page the
expect(r.status).toBe(405)
expect(JSON.parse(r.text)).toEqual({ type: "error", error: { type: "permission_error", message: "405 Method Not Allowed — " + START_EDGE } })
expect(r.text).not.toMatch(/request has been blocked/)
_internal.edge.until = 0
// any other refusal of the Start Plan goes on as it came
answer = () => Response.json({ type: "error", error: { type: "overloaded_error", message: "busy" } }, { status: 529 })
r = await ask(start("zai"))