diff --git a/packages/zcode/README.md b/packages/zcode/README.md index 68f76ca..15d422c 100644 --- a/packages/zcode/README.md +++ b/packages/zcode/README.md @@ -213,6 +213,23 @@ number written into the plugin would hold a Max account to a Lite one's with no way to raise it. A user who knows their plan's cap sets it on the account or the provider in magpie, and magpie's queue follows that. +A run of caps is also the edge firewall's countdown: two days of logs +(11-05 and 11-06) show ~18 requests/min on the Start Plan bringing 3008 +caps in a run, then 3–7 minutes later a 405 block page that refuses the +whole IP for 1–2 hours. The waits absorb most caps, so neither magpie nor +the agent sees the address is saturated and nobody slows the arrival rate. +Five cap-hit requests in one minute now hold Start Plan requests off +`zcode.z.ai` for three minutes, process-wide and for every account, and +answer them here with a 429 and `Retry-After`, so magpie still rests the +account and asks the group's next provider. A coding plan, served by +another host, is never held. The window clears when the hold is armed, so +the hold's own 429s cannot keep it armed, and a request already in +flight stops asking too: once the hold is armed, its remaining waits +answer locally with the hold's 429 instead of asking the counting +firewall again. This is distinct from the network's 405 block page hold +(plugins#649), which is what an IP already refused needs; when both are +on, the 405 hold's answer wins. + ## Two accounts at once Three ZCode accounts used at once from one address can get the address diff --git a/packages/zcode/dual.test.mjs b/packages/zcode/dual.test.mjs index 8b9f6c5..d942ed1 100644 --- a/packages/zcode/dual.test.mjs +++ b/packages/zcode/dual.test.mjs @@ -38,6 +38,9 @@ beforeEach(async () => { _internal.blocked.clear() _internal.sidelined.clear() _internal.edge.until = 0 + _internal.busyHold.until = 0 + _internal.busyHold.hits.length = 0 + _internal.busyHold.now = () => Date.now() sent.length = 0 for (const k of Object.keys(answers)) delete answers[k] globalThis.fetch = async (input, init = {}) => { @@ -440,6 +443,29 @@ test("a gift's block page holds free first on the plan and a trial entry here (p expect([gift(), plan()]).toEqual([1, 2]) }) +// A busy hold keeps the gift off exactly as a block page does: free first +// must leave the dual account's plain model on its coding plan, which is +// never held — not move it onto a route the hold answers without asking. +test("a busy hold holds free first on the plan too, and a trial entry at the local 429", async () => { + planAndBalance() + _internal.busyHold.until = Date.now() + _internal.BUSY_HOLD + answers["/api/v1/zcode-plan/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + answers["/api/anthropic/v1/messages"] = ok({ type: "message", content: [] }) + const opts = await freePlugin({ 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 + // the plain model stays on the coding plan, answered 200, gift untouched + expect((await ask("GLM-5.3-Flash")).status).toBe(200) + expect([gift(), plan()]).toEqual([0, 1]) + // the user's pick of the gift is answered at the hold's own 429 + const res = await ask("GLM-5.3-Flash-Trial") + expect(res.status).toBe(429) + expect(res.headers.get("retry-after")).toMatch(/^\d+$/) + expect(JSON.parse(await res.text()).error.message).toContain("ZCode is busy") + expect([gift(), plan()]).toEqual([0, 1]) +}) + const giftUnreachable = (when = () => true) => { const under = globalThis.fetch globalThis.fetch = async (input, init = {}) => { diff --git a/packages/zcode/index.mjs b/packages/zcode/index.mjs index 28d0155..64ea77e 100644 --- a/packages/zcode/index.mjs +++ b/packages/zcode/index.mjs @@ -1931,6 +1931,56 @@ const BUSY_WAITS = [250, 500, 900, 1600, 2800, 4000] const BUSY_HINT = "ZCode serves one account a few requests at a time, and every agent and session of this computer asks through magpie; this request came behind the others, and the same request a moment later is served" +// busyHold is the firewall's countdown. Two days of logs (11-05 23:06–23:15 +// and 11-06 06:23–06:27) show the same shape: sustained ~18 requests/min on +// the Start Plan brings code-3008 caps in a run, and 3–7.5 minutes later the +// edge firewall (errors.aliyun.com) refuses the whole IP with 405 for 1–2 +// hours. askBusy's per-request waits absorb ~90% of those caps, so neither +// magpie nor the agent sees that the address is saturated and nobody slows +// the arrival rate down. A run of BUSY_N caps in one minute holds the Start +// Plan (zcode.z.ai only, process-wide, every account) off BUSY_HOLD. Replay +// of both days: N=5, H=3min freezes 2–7 minutes before the first 405 and +// spares 37–52 requests. A held request answers 429 with Retry-After, so +// magpie still reads a rate limit, rests the account and fails over; it is +// not the 405/BlockedHint of an IP already refused. The coding plan, on +// another host, is never held. The hold lives in this process's memory +// alone: magpie restarting forgets it. Only model requests are held — +// balance reads, the usage card and check-in still reach zcode.z.ai during +// it (the check-in holds its own reads per account on a 429). +const BUSY_N = 5 +const BUSY_WINDOW = 60_000 +const BUSY_HOLD = 3 * 60_000 +const busyHold = { hits: [], until: 0, now: () => Date.now() } +// busyHold.now is the clock, injectable for tests: a hold's window, its +// length and its expiry all read through it. +const busyHeld = () => busyHold.now() < busyHold.until + +// busyCap records one concurrency cap of a Start Plan request. Only a run +// arms a hold; the window is cleared on arming, and a cap that lands while +// the hold is on counts toward nothing — the hold's own 429s and the first +// caps after it cannot keep re-arming it. +function busyCap() { + if (busyHeld()) return + const now = busyHold.now() + busyHold.hits.push(now) + while (busyHold.hits.length && now - busyHold.hits[0] > BUSY_WINDOW) busyHold.hits.shift() + if (busyHold.hits.length >= BUSY_N) { + busyHold.until = now + BUSY_HOLD + busyHold.hits.length = 0 + } +} + +function busyHeldAnswer() { + const wait = Math.max(1, Math.ceil((busyHold.until - busyHold.now()) / 1000)) + const error = { + type: "rate_limit_error", + message: `ZCode is busy: its concurrency cap was hit ${BUSY_N} times in a minute, so this computer's Start Plan requests are held for ${wait}s to keep the provider's network firewall from blocking this IP; wait a while, or use a GLM Coding Plan model`, + } + return new Response(JSON.stringify({ type: "error", error }), { + status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": String(wait) }, + }) +} + // busy says a 429 is that in-flight cap: its own code (3008, 3009), or its // own words when the envelope carries no code. function busy(status, text) { @@ -1977,17 +2027,26 @@ function busyAnswer(res, text) { // account is saturated rather than busy, and the cap goes back as // busyAnswer's 429. The plan path's patience, shared with free first's // replay, whose plan has a cap of its own. -async function askBusy(u, o, hs) { +async function askBusy(u, o, hs, onCap) { let res = await fetch(u, { ...o, headers: hs }) + let counted = false for (let i = 0; res.status === 429; i++) { const text = await res.text() const cap = busy(429, text) + // one request's retries are one saturation signal, not one per wait + if (cap && !counted) { counted = true; onCap?.() } + // the hold armed: a request already in flight stops asking too. The + // second check catches the asks that capped before the hold armed and + // woke from their wait after it. Keying on onCap keeps the coding plan + // and free first's replay (no onCap) as they are. + if (cap && onCap && busyHeld()) { res = busyHeldAnswer(); break } if (!cap || i >= BUSY_WAITS.length) { res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers }) break } const w = BUSY_WAITS[i] await sleep(Math.round(w * (0.75 + Math.random() * 0.5))) + if (onCap && busyHeld()) { res = busyHeldAnswer(); break } res = await fetch(u, { ...o, headers: hs }) } return res @@ -2594,7 +2653,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { 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) && !giftSidelined(s, m)) { + } else if (!alone && !edgeHeld() && !busyHeld() && 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 @@ -2602,7 +2661,11 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { // the request on the plan with no read per request; a // gift-only account is already on the gift and is left as // it was. A refusal past this check is replayed on the plan - // in the same request (replayOnPlan below). + // in the same request (replayOnPlan below). A busy hold (or + // a block page) keeps the plain model off the gift: the + // coding plan is never held, and free first must not move + // the request onto a route the hold answers 429 without + // asking. const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase()) orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) }) m = raw @@ -2657,8 +2720,14 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { } // 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 + // already left the gift for the plan. Checked before the busy + // hold: an IP the firewall already refused keeps that behavior + // (the 405 magpie reads as the network's), hold or no hold. if (start && edgeHeld()) return kept(edgeHeldAnswer()) + // a run of busy caps held this computer off zcode.z.ai before the + // edge firewall could block the IP: a held request is answered + // here, with a 429 magpie still reads as a rate limit + if (start && busyHeld()) return kept(busyHeldAnswer()) 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") @@ -2698,7 +2767,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) { // the number declared above let res try { - res = await askBusy(url, opts, h) + // Only Start Plan caps count toward the firewall hold: the + // coding plan is served by another host and was never refused + // with the IP's 405. + res = await askBusy(url, opts, h, start ? busyCap : undefined) } catch (e) { // free first moved the request onto the gift, so a gift that // cannot be asked at all — the network, the host — is answered @@ -2903,4 +2975,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, 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, 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 } +export const _internal = { edge, EDGE_HOLD, busyHold, BUSY_N, BUSY_WINDOW, BUSY_HOLD, busyCap, busyHeld, 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 } diff --git a/packages/zcode/package.json b/packages/zcode/package.json index e076c15..ad83275 100644 --- a/packages/zcode/package.json +++ b/packages/zcode/package.json @@ -1,6 +1,6 @@ { "name": "@magpie-community/opencode-zcode-auth", - "version": "0.1.53", + "version": "0.1.54", "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", diff --git a/packages/zcode/start.test.mjs b/packages/zcode/start.test.mjs index a0f4945..2140cd0 100644 --- a/packages/zcode/start.test.mjs +++ b/packages/zcode/start.test.mjs @@ -48,6 +48,9 @@ afterEach(() => { got.length = 0 answer = null _internal.edge.until = 0 + _internal.busyHold.until = 0 + _internal.busyHold.hits.length = 0 + _internal.busyHold.now = () => Date.now() }) const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16) @@ -512,6 +515,15 @@ test("a block page holds the Start Plan off zcode.z.ai for every account a while r = await ask(start("zai")) expect(r.status).toBe(200) expect(messages()).toBe(3) + // both holds on: the edge's 405 wins — an IP the firewall already refused + // keeps that behavior, busy hold or not + _internal.edge.until = Date.now() + _internal.EDGE_HOLD + _internal.busyHold.until = Date.now() + _internal.BUSY_HOLD + answer = () => Response.json({ type: "message", content: [] }) + r = await ask(start("zai")) + expect(r.status).toBe(405) + expect(JSON.parse(r.text).error.message).toStartWith("405 Method Not Allowed — " + START_EDGE) + _internal.busyHold.until = 0 }) test("the Start Plan's 3012 says ZCode blocked the account, and a block page the network (plugins#348, #425)", async () => { @@ -558,3 +570,188 @@ test("the Start Plan's 3012 says ZCode blocked the account, and a block page the expect(r.status).toBe(405) expect(r.text).toBe("request has been blocked") }) + +// 11-06: two days' logs show a burst of 3008 concurrency caps is the edge +// firewall's countdown — 3–7 minutes of ~18 requests/min later the whole IP +// is refused 405 for 1–2 hours. askBusy's per-request waits absorb ~90% of +// the caps, so neither magpie nor the agent ever sees that the address is +// saturated. A run of caps in one minute now holds the Start Plan off for +// three minutes, process-wide, and answers with a 429 + Retry-After so +// magpie still rests the account and asks the group's next provider. The +// coding plan, on another host, is never held. +test("a run of busy caps holds the Start Plan off before the IP is blocked, and nothing else", async () => { + const waits = _internal.BUSY_WAITS.splice(0) + _internal.BUSY_WAITS.push(1) + try { + 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(), retryAfter: res.headers.get("retry-after"), signIn: res.headers.get("x-magpie-sign-in") } + } + const messages = () => got.filter((r) => r.path.endsWith("/messages")).length + const busy = () => Response.json({ code: "3008", msg: "user concurrency limit exceeded" }, { status: 429 }) + // one cap alone is a turn not come: no hold, and the request still went + // upstream (it came back a 429 after the waits, not a local one) + answer = busy + expect((await ask(start("zai"))).status).toBe(429) + expect(messages()).toBeGreaterThanOrEqual(1) + expect(_internal.busyHold.until).toBe(0) + // a run of them holds the gift, with a 429 magpie reads as a rate limit + const before = Date.now() + for (let i = 0; i < 4; i++) await ask(start("zai")) + expect(_internal.busyHold.until).toBeGreaterThanOrEqual(before + _internal.BUSY_HOLD) + expect(_internal.busyHold.until).toBeLessThanOrEqual(Date.now() + _internal.BUSY_HOLD) + got.length = 0 + answer = () => Response.json({ type: "message", content: [] }) + const other = { type: "oauth", access: jwt, refresh: JSON.stringify({ site: "zai", device: "9999***4333-8444***5555", jwt, plan: "Start Plan" }), expires: 0 } + for (const auth of [start("zai"), other]) { + const r = await ask(auth) + expect(r.status).toBe(429) + expect(r.signIn).toBe("kept") + expect(r.retryAfter).toMatch(/^\d+$/) + expect(Number(r.retryAfter)).toBeGreaterThan(0) + expect(Number(r.retryAfter)).toBeLessThanOrEqual(Math.ceil(_internal.BUSY_HOLD / 1000)) + const e = JSON.parse(r.text).error + expect(e.type).toBe("rate_limit_error") + expect(e.message).toContain("busy") + } + expect(messages()).toBe(0) + // the coding plan goes on, held or not + const plan = await ask({ type: "api", key: "one.secret", metadata: { site: "zai" } }) + expect(plan.status).toBe(200) + expect(messages()).toBe(1) + // the hold is over: the Start Plan is asked again, one cap does not re-arm + // it — with hits left as the arming left them (empty), not cleared by hand + _internal.busyHold.until = Date.now() - 1 + answer = busy + expect((await ask(start("zai"))).status).toBe(429) + expect(_internal.busyHold.until).toBeLessThanOrEqual(Date.now()) + _internal.busyHold.until = 0 + } finally { + _internal.BUSY_WAITS.length = 0 + _internal.BUSY_WAITS.push(...waits) + _internal.busyHold.now = () => Date.now() + } +}) + +// The clock is the hold's own, moved by the test: caps spread over more than +// a window never arm a hold, caps landing while the hold is on count toward +// nothing, and the hold ends by the clock without the hits being cleared by +// hand. +test("the busy hold reads its clock: a spread run holds nothing, caps during the hold count toward nothing", async () => { + const waits = _internal.BUSY_WAITS.splice(0) + _internal.BUSY_WAITS.push(1) + const ask = async (auth) => { + routeToFake() + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth, { id: "zcode" }) + return opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode" }, body: agentText }) + } + let clock = 1_000_000_000_000 + _internal.busyHold.now = () => clock + try { + answer = () => Response.json({ code: "3008", msg: "user concurrency limit exceeded" }, { status: 429 }) + // five caps, each a minute and a second apart: no window ever holds five + for (let i = 0; i < 5; i++) { + clock += 61_000 + await ask(start("zai")) + } + expect(_internal.busyHold.until).toBe(0) + // a fast run arms it; caps landing while the hold is on are not counted + clock += 1_000 + for (let i = 0; i < 5; i++) await ask(start("zai")) + const armedAt = clock + expect(_internal.busyHold.until).toBe(armedAt + _internal.BUSY_HOLD) + for (let i = 0; i < 9; i++) { + clock += 1_000 + await ask(start("zai")) + } + expect(_internal.busyHold.until).toBe(armedAt + _internal.BUSY_HOLD) + // the hold expires by the clock with hits empty: one cap does not re-arm + clock = armedAt + _internal.BUSY_HOLD + 1_000 + expect((await ask(start("zai"))).status).toBe(429) + expect(_internal.busyHold.until).toBeLessThanOrEqual(clock) + _internal.busyHold.until = 0 + } finally { + _internal.BUSY_WAITS.length = 0 + _internal.BUSY_WAITS.push(...waits) + _internal.busyHold.now = () => Date.now() + _internal.busyHold.hits.length = 0 + } +}) + +// The hold's guard is the one the serial tests cannot see: requests already +// in flight when the hold arms get their first cap after it. Hold the clock +// still, put 12 Start Plan requests in flight at once, answer them all 3008 +// after they have all reached the fake — with the guard gone, those 12 caps +// arm the hold twice and the second arming pushes `until` out. +test("caps that land after the hold armed change neither hits nor until (requests in flight)", async () => { + const waits = _internal.BUSY_WAITS.splice(0) + _internal.BUSY_WAITS.push(1) + try { + routeToFake() + let clock = 1_000_000_000_000 + _internal.busyHold.now = () => clock + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => start("zai"), { id: "zcode" }) + // the fake parks every /messages request on one gate until the test opens it + let open = () => {} + const gate = new Promise((r) => (open = r)) + answer = async () => { + await gate + return Response.json({ code: "3008", msg: "user concurrency limit exceeded" }, { status: 429 }) + } + const all = Array.from({ length: 12 }, () => + opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode" }, body: agentText })) + // every request is in flight (reached the fake) before any answer comes + while (got.filter((r) => r.path.endsWith("/messages")).length < 12) await Bun.sleep(5) + expect(got.filter((r) => r.path.endsWith("/messages")).length).toBe(12) + clock += 1_000 + open() + const rs = await Promise.all(all) + // all 12 armed the hold on their first caps and were held from then on: + // the caps after arming changed neither hits nor until, no request asked + // again (12 asks, not 24), and each answer is the hold's own 429 with + // its Retry-After, not busyAnswer's bare one + expect(rs.every((r) => r.status === 429)).toBe(true) + expect(got.filter((r) => r.path.endsWith("/messages")).length).toBe(12) + expect(rs.every((r) => r.headers.get("retry-after") === String(_internal.BUSY_HOLD / 1000))).toBe(true) + expect(_internal.busyHold.hits.length).toBe(0) + expect(_internal.busyHold.until).toBe(clock + _internal.BUSY_HOLD) + } finally { + _internal.BUSY_WAITS.length = 0 + _internal.BUSY_WAITS.push(...waits) + _internal.busyHold.now = () => Date.now() + _internal.busyHold.hits.length = 0 + _internal.busyHold.until = 0 + } +}) + +// A slow handful of caps is a plan at its limit, not a firewall countdown: +// the old per-request waits keep serving it. (Only caps on the Start Plan +// count; a coding plan's caps must never hold the gift.) +test("a few caps do not hold the Start Plan, and coding plan caps hold nothing", async () => { + const waits = _internal.BUSY_WAITS.splice(0) + _internal.BUSY_WAITS.push(1) + try { + const ask = async (auth) => { + routeToFake() + const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } }) + const opts = await hooks.auth.loader(async () => auth, { id: "zcode" }) + return opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json", "x-api-key": "zcode" }, body: agentText }) + } + answer = () => Response.json({ code: "3008", msg: "user concurrency limit exceeded" }, { status: 429 }) + for (let i = 0; i < 4; i++) expect((await ask(start("zai"))).status).toBe(429) + expect(_internal.busyHold.until).toBe(0) + // the same run on the coding plan leaves the gift alone + for (let i = 0; i < 8; i++) await ask({ type: "api", key: "one.secret", metadata: { site: "zai" } }) + expect(_internal.busyHold.until).toBe(0) + _internal.busyHold.hits.length = 0 + } finally { + _internal.BUSY_WAITS.length = 0 + _internal.BUSY_WAITS.push(...waits) + _internal.busyHold.now = () => Date.now() + } +})