zcode 0.1.56: the Start Plan goes three at a time and re-asks a cap twice, as ZCode's client does

Users of other agent apps on the ZCode plugin saw "rate limited 5 times
in a minute" (star21321321124 on Discord). That is the plugin's own
3-minute busy hold (0.1.54, #801), which trips after ZCode refuses five
requests in a minute as over its in-flight cap (429 3008/3009). The
plugin drove those refusals itself:

- It sent every request magpie passed it. magpie's lane is 3 per
  account, but nothing in the plugin held the Start Plan to that.
- It re-asked a capped request up to six times over about 10s
  (BUSY_WAITS 250..4000, from #395). That kept slots taken and drew
  more caps.
- It counted every capped request toward the hold, including ones the
  next re-ask got past.

ZCode 3.17.2, read from its bundle: wqo = {3008, 3009, 3010} and
kqo = [1e3, 2e3]. So a busy cap is re-asked at most twice, after 1s and
2s, Start Plan only. There is no hold, and one main turn runs per
session.

What changes:
- BUSY_WAITS is [1000, 2000], with no jitter, and 3010 counts as busy.
  This applies to every plan, since the coding plan goes through the
  same askBusy.
- startGate: on the Start Plan, an account has at most 3 requests in
  flight (#395 measured about 3: 3 of 12 and 4 of 12 served). The
  account is keyed by uid, then accountId, then key. Further requests
  wait in a FIFO queue in the plugin and are not sent. A slot is freed
  when the upstream body ends, the agent cancels, or its signal aborts
  (the body is pumped eagerly so an unread reply cannot hold a slot).
  After 2 minutes of waiting, the plugin answers 429 rate_limit_error
  with Retry-After 5: "ZCode's free Start Plan serves this account 3
  requests at a time; this one waited 120s behind the others and was
  not sent. Run fewer agents or subagents on ZCode at once, or try
  again". The coding plan stays ungated. Its cap follows the tier (the
  #395 review), and magpie's lane covers it.
- Free first skips the gift while its account's gate is full, so the
  plain model goes to the coding plan rather than queueing.
- The hold counts a request only when ZCode refuses it again at the 1s
  re-ask. N=5, the 60s window and the 3-minute hold are unchanged, as
  is the rule that an in-flight or queued request stops once the hold
  is armed. Its message now says what happened and what to do: "ZCode
  turned away 5 requests in the last minute as too many requests at
  once, each again when asked a second later. So that ZCode's firewall
  does not block this network, magpie sends no free Start Plan
  requests for the next Ns. Wait, run fewer agents or subagents on
  ZCode at once, or use a GLM Coding Plan model". The words avoid
  "plan"+"limit" after "exceeded", which magpie's usedUpWords would
  read as spent.

History checked: #395 (0.1.32) added the long waits and had an
in-plugin gate removed in review, because it held Max coding-plan
accounts to 3 and was keyed on the jwt. This gate is Start Plan only
(one tier) and keyed per account. #801 (0.1.54) added the hold from
the logs of 11-05 23:06 and 11-06 06:23: about 16 to 18 req/min, 7 to
10 in flight, and the first 405 after 205 to 517s. The hold still
trips on sustained refusals: the replay below has the account
saturated elsewhere, and the hold arms within the replayed minute with
nothing sent after it.

Run on mote, HOME=$(mktemp -d), at the rebased head, Bun 1.4.2:
- bun test packages/zcode: 235 pass, 0 fail.
- New inflight.test.mjs: 13 pass. It covers re-ask count and timing
  (3 asks, gaps of about 1s and 2s), 3010, at most 3 in flight of 12
  sent at once, per-account slots, a slot held across re-asks, the
  queue wait running out (nothing sent, plain 429), abort while queued,
  a cancelled stream freeing its slot, the coding plan ungated, a cap
  the 1s re-ask got past not counting, and the hold message. It also
  replays #801's two days at 20x speed against a fake that refuses past
  3 in flight: 0 refusals, peak 3, no hold, all served. A second replay
  with the account saturated elsewhere arms the hold within a minute.
- bun scripts/check.mjs zcode: ok (registry.json, zcode). Repo bun test: 6780 pass, 0 fail, 20 skip, 491 files.
Broken by hand: inflight.test.mjs against 0.1.55's index.mjs gives 11
of 13 red. 0.1.55 made 7 asks, had 12 in flight, drew 24 refusals in
the replay, and armed the hold on caps a re-ask got past. Two pass on
both, as expected: the coding plan stays ungated, and the saturated
replay still holds.
Not tried: real ZCode Start Plan accounts, live; the replay is
synthetic from the #801 figures, as the raw logs are not in the repo.
Not copied from ZCode's client: its "no re-ask on a session's first
turn" rule, since the plugin cannot tell a first turn reliably.

Reported-by: star21321321124
This commit is contained in:
yetone
2026-11-07 17:54:55 +08:00
parent 589fb12334
commit a313a00306
7 changed files with 656 additions and 102 deletions
+47 -29
View File
@@ -140,7 +140,7 @@ 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 other
429 counts as spent — Z.ai's 1302/1303 rate limits among them — while the
plan's own in-flight cap (3008/3009) does not: such a request is asked
plan's own in-flight cap (3008/3009/3010) does not: such a request is asked
again instead (see [A few at once](#a-few-at-once)). A stream's body is
never read or buffered on the way.
@@ -195,43 +195,61 @@ a spent one answers 429 with freeFirst on, as it does without it.
## A few at once
A plan serves one account a few requests at a time; past that, ZCode
answers 429 with code 3008 "user concurrency limit exceeded", or 3009
"model concurrency limit exceeded". magpie funnels every agent's and every
session's requests of one computer through this one plugin process, so
magpie's own queue spaces an account's requests by the number this plugin
declares — `maxConcurrency` on the auth hook, and `magpie.maxConcurrency`
in its `package.json`, both three. A request the vendor refuses anyway
waits a moment (a quarter of a second, then longer — about ten seconds of
waits in all) and asks again, the same request byte for byte. A cap that
outlasts the waits goes on as a 429, ZCode's words followed by what they
answers 429 with code 3008 "user concurrency limit exceeded", 3009
"model concurrency limit exceeded" or 3010. magpie funnels every agent's
and every session's requests of one computer through this one plugin
process, so magpie's own queue spaces an account's requests by the number
this plugin declares — `maxConcurrency` on the auth hook, and
`magpie.maxConcurrency` in its `package.json`, both three. A request the
vendor refuses anyway is asked again after 1s and once more after 2s, the
same request byte for byte, as ZCode's own client (3.17.2) does. A cap
that outlasts both goes on as a 429, ZCode's words followed by what they
mean, so the agent reads why. magpie still reads it as a rate limit: the
account rests a minute and the request goes to the next member of its
routing group, as it did before.
routing group.
Three is a default, not a cap the plugin enforces. A plan's real cap
follows its tier — Z.ai serves a Max plan more at once than a Pro, and a
Lite fewer — and is higher off-peak
For a coding plan three is a default, not a cap the plugin enforces. A
plan's real cap follows its tier — Z.ai serves a Max plan more at once
than a Pro, and a Lite fewer — and is higher off-peak
([Z.ai's usage policy](https://docs.z.ai/devpack/usage-policy)), so a
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.
The free Start Plan is one tier, measured at about three in flight
(plugins#395), so there the plugin keeps its own gate too: an account's
fourth Start Plan request waits in the plugin, in arrival order, until
one of the three has been read to its end (or its agent went away), and
is not sent to be refused. That covers what magpie's queue cannot see —
a `maxConcurrency` raised past three, two magpie providers on one ZCode
account, an older host. A request that has waited two minutes is answered
here with a 429 that says it was not sent and why. Free first skips the
gift while its account's gate is full, so the plain model goes to the
coding plan rather than queueing.
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.
(11-05 and 11-06) show ~18 requests/min on the Start Plan, up to ten in
flight on one account, bringing 3008 caps in a run, then 3–7 minutes
later a 405 block page that refuses the whole IP for 1–2 hours. Up to
0.1.55 the plugin itself added to that run: it sent every request magpie
passed it, asked a capped one again up to six times over about ten
seconds, and counted every capped request toward the hold, so busy agents
tripped the hold on refusals it had caused. With the gate the plugin's
own requests stay under the cap, and a request counts only when ZCode
refuses it again at the 1s re-ask, the sign that someone else (the ZCode
app, another computer on the account) holds the slots. Five such
requests in one minute 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` that say what happened and what to do, 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 or queued stops asking too. 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.
`inflight.test.mjs` replays the two days at 20× speed against a fake that
refuses past three in flight: 0.1.55 drew 24 refusals in it, this version
none.
## Two accounts at once
+2
View File
@@ -53,6 +53,8 @@ afterEach(() => {
globalThis.fetch = real
answer = null
BUSY_WAITS.splice(0, BUSY_WAITS.length, ...WAITS)
// a reply a test leaves unread keeps its Start Plan slot (startGate)
_internal.startGate.lanes.clear()
})
const jwt = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600 })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig"
+6 -2
View File
@@ -41,6 +41,8 @@ beforeEach(async () => {
_internal.busyHold.until = 0
_internal.busyHold.hits.length = 0
_internal.busyHold.now = () => Date.now()
// a reply a test leaves unread keeps its Start Plan slot (startGate)
_internal.startGate.lanes.clear()
sent.length = 0
for (const k of Object.keys(answers)) delete answers[k]
globalThis.fetch = async (input, init = {}) => {
@@ -462,7 +464,7 @@ test("a busy hold holds free first on the plan too, and a trial entry at the loc
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(JSON.parse(await res.text()).error.message).toContain("ZCode turned away 5 requests in the last minute")
expect([gift(), plan()]).toEqual([0, 1])
})
@@ -517,7 +519,9 @@ test("an aborted gift request stays aborted", async () => {
const tries = await giftThrowing(() => new DOMException("This operation was aborted", "AbortError"))
const opts = await freePlugin({ freeFirst: true }).then((h) => h.loader(async () => coding, { id: "zcode" }))
await expect(opts.fetch(MSG, { method: "POST", headers: { "content-type": "application/json" }, body: body("GLM-5.3-Flash"), signal: ctl.signal })).rejects.toThrow()
expect(tries.gift).toBe(1)
// the Start Plan's slot (startGate) is not taken for an agent already
// gone: the gift is never asked, and the plan isn't either
expect(tries.gift).toBe(0)
expect(tries.plan).toBe(0)
})
+221 -56
View File
@@ -1953,20 +1953,23 @@ function kept(res, text) {
// ---- the plan's concurrency ------------------------------------------------------
// ZCode serves one account a few requests at a time. Past that it answers 429
// with code 3008, "user concurrency limit exceeded", or 3009, "model
// concurrency limit exceeded": the request's turn has not come — not a plan
// spent (1113/1005) and not a rate limit (1302/1303). magpie sends every
// agent's and every session's requests of this computer through this one
// process, and its own queue spaces an account's requests by the number
// declared below (DEFAULT_CONCURRENCY, on the auth hook and in package.json);
// a request the vendor refuses anyway waits a moment and asks again, the same
// bytes. A refusal is immediate while a turn's answer is not, so a redundant
// ask costs a round trip and no tokens.
// with code 3008, "user concurrency limit exceeded", 3009, "model
// concurrency limit exceeded", or 3010: the request's turn has not come — not
// a plan spent (1113/1005) and not a rate limit (1302/1303). ZCode's own
// client (3.17.2) reads the three as one ("当前系统繁忙"), asks again after 1s
// and 2s, and then gives up; it sends one request per session at a time and
// has no hold. magpie sends every agent's and every session's requests of
// this computer through this one process, so the plugin does what that
// client does: the Start Plan gets a few requests of an account in flight at
// once (startGate), the rest wait their turn here instead of being sent to be
// refused, and a refusal anyway is asked again twice (BUSY_WAITS).
//
// The plugin keeps no gate of its own: a plan's cap depends on its tier (Z.ai
// serves Max more at once than Pro, and Lite fewer) and is higher off-peak
// (https://docs.z.ai/devpack/usage-policy), so a number written here would
// hold a Max account to a Lite one's, with no way for the user to raise it.
// The coding plan keeps no gate of the plugin's: its cap depends on its tier
// (Z.ai serves Max more at once than Pro, and Lite fewer) and is higher
// off-peak (https://docs.z.ai/devpack/usage-policy), so a number written here
// would hold a Max account to a Lite one's. magpie's own queue spaces it by
// the number declared below (DEFAULT_CONCURRENCY, on the auth hook and in
// package.json), which a user raises on the account.
const DEFAULT_CONCURRENCY = 3
// DEFAULT_ACCOUNTS is how many of a user's ZCode accounts magpie sends
// requests to at the same time (maxAccounts, on the auth hook and in
@@ -1975,30 +1978,163 @@ const DEFAULT_CONCURRENCY = 3
// once from one address got the address refused with a 405, two didn't. A
// user sets their own on the provider (Accounts at once), 0 for no limit.
const DEFAULT_ACCOUNTS = 2
const BUSY_CODES = new Set(["3008", "3009"])
// BUSY_WAITS are the waits between asks, longest last: about ten seconds of
// them. Past that the account is saturated rather than busy, and magpie's
// routing takes the request (or rests the account, as its 429 says).
const BUSY_WAITS = [250, 500, 900, 1600, 2800, 4000]
const BUSY_CODES = new Set(["3008", "3009", "3010"])
// BUSY_WAITS are the waits before each ask again: ZCode's own client's,
// 1s and 2s (kqo in its bundle). Past them the cap goes back to magpie,
// which takes the request to another account or rests this one as its 429
// says. Six asks over ten seconds, before 0.1.56, put two or three times the
// requests a capped account could serve on the wire, and the agents' own
// retries came on top.
const BUSY_WAITS = [1000, 2000]
// The hint names neither "plan" nor "limit": after the vendor's "…limit
// exceeded" either would read to magpie as a plan used up.
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"
"ZCode serves one account a few requests at a time and was still busy when asked again after 1s and 2s; run fewer agents or subagents on ZCode at once, or try again in a moment"
// startGate is the Start Plan's in-flight count per account. PR #395 measured
// one Z.ai gift account at 3 of 12 parallel requests served in one run and 4
// of 12 in another, so three are in flight at once, what magpie's queue sends
// by DEFAULT_CONCURRENCY too. The gate holds them there when that queue
// doesn't: a user who raised the account's number for the coding plan, two
// magpie providers signed in to one account, a host that doesn't read
// maxConcurrency. A cap the server still says now and then (a slot it lets
// go of late, the ZCode app on the same account) the 1s re-ask gets past.
// A request past them waits here, first come first served, until one is
// answered to the end, up to startGate.wait; an agent that gives up leaves
// the queue. A wait that runs out is answered startQueueAnswer's 429,
// nothing sent. The gate lives in this process's memory alone, by account
// (gateKey).
const startGate = { inflight: 3, wait: 120_000, lanes: new Map() }
// startFull says the account's Start Plan slots are all taken, or others wait.
const startFull = (key) => {
const l = startGate.lanes.get(key)
return !!l && (l.busy >= startGate.inflight || l.queue.length > 0)
}
// startSlot waits for one of the account's Start Plan slots: { release },
// null when startGate.wait ran out first, or the agent's abort thrown.
function startSlot(key, signal) {
const lanes = startGate.lanes
let l = lanes.get(key)
if (!l) lanes.set(key, (l = { busy: 0, queue: [] }))
const next = () => {
while (l.busy < startGate.inflight && l.queue.length) l.queue.shift()()
if (!l.busy && !l.queue.length && lanes.get(key) === l) lanes.delete(key)
}
const take = () => {
l.busy++
let gone = false
return {
release() {
if (gone) return
gone = true
l.busy--
next()
},
}
}
if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"))
if (l.busy < startGate.inflight && !l.queue.length) return Promise.resolve(take())
return new Promise((resolve, reject) => {
const leave = () => {
clearTimeout(timer)
signal?.removeEventListener?.("abort", aborted)
const i = l.queue.indexOf(go)
if (i >= 0) l.queue.splice(i, 1)
}
const go = () => {
leave()
resolve(take())
}
const aborted = () => {
leave()
next()
reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"))
}
const timer = setTimeout(() => {
leave()
next()
resolve(null)
}, startGate.wait)
signal?.addEventListener?.("abort", aborted, { once: true })
l.queue.push(go)
})
}
// released hands res on and lets its slot go once ZCode's answer has come
// to its end, failed, or been given up on (the agent's abort, the reader's
// cancel) — the request is in flight at ZCode until then. The answer is read
// as it comes, whether or not the agent reads it yet, so a reply read late,
// or dropped unread, does not keep its slot past ZCode's own end of it.
function released(res, slot, signal) {
if (!slot) return res
if (!res.body) {
slot.release()
return res
}
const reader = res.body.getReader()
const stop = (why) => {
slot.release()
reader.cancel(why).catch(() => {})
}
signal?.addEventListener?.("abort", () => slot.release(), { once: true })
const pump = async (c) => {
try {
for (;;) {
const { done, value } = await reader.read()
if (done) break
c.enqueue(value)
}
slot.release()
c.close()
} catch (e) {
slot.release()
try {
c.error(e)
} catch {}
}
}
// started, not awaited: the agent reads each chunk as it comes
const body = new ReadableStream({ start: (c) => void pump(c), cancel: stop })
return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers })
}
// startQueueAnswer is a request that waited its whole turn behind the
// account's others and was never sent: a 429 magpie reads as a rate limit,
// so it tries the next account, and a short Retry-After.
function startQueueAnswer() {
const error = {
type: "rate_limit_error",
message: `ZCode's free Start Plan serves this account ${startGate.inflight} requests at a time; this one waited ${Math.round(startGate.wait / 1000)}s behind the others and was not sent. Run fewer agents or subagents on ZCode at once, or try again`,
}
return new Response(JSON.stringify({ type: "error", error }), {
status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" },
})
}
// 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).
// the Start Plan, up to ~10 of them in flight against a cap of about three,
// 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. Re-asks
// absorbed ~90% of those caps, so neither magpie nor the agent saw that the
// address was saturated and nobody slowed the arrival rate down. startGate
// now keeps this computer's own requests under the cap, so a cap is ZCode
// busy or another client on the account; a request refused on its first ask
// and again a second later (busyCap) is that, sustained, and BUSY_N of them
// in one minute hold the Start Plan (zcode.z.ai only, process-wide, every
// account) off BUSY_HOLD. A cap the 1s re-ask got past counts for nothing:
// on 0.1.55 every capped request counted, a lone late slot as much as a
// saturated address, and busy afternoons held users for nothing. Replay of
// both days: N=5, H=3min froze 2–7 minutes before the first 405 and spared
// 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
@@ -2007,10 +2143,10 @@ const busyHold = { hits: [], until: 0, now: () => Date.now() }
// 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.
// busyCap records one sustained 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()
@@ -2026,14 +2162,14 @@ 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`,
message: `ZCode turned away ${BUSY_N} requests in the last minute as too many requests at once, each again when asked a second later. So that ZCode's firewall does not block this network, magpie sends no free Start Plan requests for the next ${wait}s. Wait, run fewer agents or subagents on ZCode at once, 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
// busy says a 429 is that in-flight cap: its own code (3008, 3009, 3010), or its
// own words when the envelope carries no code.
function busy(status, text) {
if (status !== 429) return false
@@ -2074,19 +2210,20 @@ function busyAnswer(res, text) {
}
// askBusy asks once and, when the answer is the vendor's in-flight cap
// (3008/3009, or its own words), asks again through BUSY_WAITS's waits, a
// quarter of a second and longer — about ten seconds of them. Past that the
// account is saturated rather than busy, and the cap goes back as
// busyAnswer's 429. The plan path's patience, shared with free first's
// replay, whose plan has a cap of its own.
// (3008/3009/3010, or its own words), asks again after BUSY_WAITS's waits,
// 1s and then 2s, as ZCode's own client does. Past them the cap goes back as
// busyAnswer's 429. A request refused again at its 1s re-ask is a sustained
// cap, told to onCap once (the firewall hold's count); one the re-ask got
// past is not. 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, onCap) {
let res = await fetch(u, { ...o, headers: hs })
let counted = false
let caps = 0
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?.() }
// one request's refusals are one saturation signal, not one per ask
if (cap && ++caps === 2) 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
@@ -2096,8 +2233,7 @@ async function askBusy(u, o, hs, onCap) {
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)))
await sleep(BUSY_WAITS[i])
if (onCap && busyHeld()) { res = busyHeldAnswer(); break }
res = await fetch(u, { ...o, headers: hs })
}
@@ -2657,9 +2793,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
provider: PROVIDER,
// a plan serves one account a few requests at a time: magpie's own
// field, so its queue spaces what the agents ask for before the vendor
// sees it. This is a default, not a cap the plugin enforces — a plan's
// own cap follows its tier (Max > Pro > Lite) and the time of day, and
// a user who knows theirs can raise this on the account
// sees it. For the coding plan this is a default, not a cap the plugin
// enforces — its cap follows its tier (Max > Pro > Lite) and the time
// of day, and a user who knows theirs can raise this on the account.
// The Start Plan has the plugin's own gate below it (startGate)
maxConcurrency: DEFAULT_CONCURRENCY,
// how many accounts take requests at once, the others in reserve
// (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all
@@ -2689,9 +2826,24 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
baseURL: s0.base + "/v1",
apiKey: s0.key || "zcode", // the fetch below puts the real one on
async fetch(input, init) {
// a Start Plan request holds one of its account's slots
// (startSlot) until its answer has been read to the end
const own = {}
try {
return released(await serve(input, init, own), own.slot, own.signal)
} catch (e) {
own.slot?.release()
throw e
}
},
}
async function serve(input, init, own) {
const auth = await getAuth()
const s = await located(stateOf(auth))
if (!s) throw new Error("not signed in to ZCode")
// the account a Start Plan slot belongs to: its user id, which a
// renewed session keeps, before the key or session itself
const gateKey = String(auth?.uid || auth?.accountId || holdKey(s))
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: known } = await plansOf(s)
@@ -2734,7 +2886,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() && !busyHeld() && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
} else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && 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
@@ -2746,7 +2898,9 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
// 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.
// asking. Nor onto a gift whose slots are all taken
// (startFull): the plan serves it now, the gift only after
// the others.
const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase())
orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
m = raw
@@ -2781,6 +2935,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
// agent sent it, the plan's headers, the plan's own patience
// (askBusy).
const replayOnPlan = async () => {
// the gift is done with: its slot goes to the next request
own.slot?.release()
let u = askedUrl
for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
if (u.startsWith(b)) {
@@ -2809,6 +2965,16 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
// 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())
// the account's Start Plan slots (startGate): a request past them
// waits here for one rather than being sent to be refused
if (start) {
own.slot = await startSlot(gateKey, opts.signal)
own.signal = opts.signal
if (!own.slot) return kept(startQueueAnswer())
// a hold may have armed while it waited
if (edgeHeld()) return kept(edgeHeldAnswer())
if (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")
@@ -2938,7 +3104,6 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
// A spent bucket's 200 says 429 (spentSaid), as a trial
// entry's does, so magpie rests the model, not the account
return done(kept(await spentSaid(res)))
},
}
},
// the plan's allowance, as magpie's built-in showed it. Each read
@@ -3058,4 +3223,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, 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, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
export const _internal = { edge, EDGE_HOLD, busyHold, startGate, 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, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
+355
View File
@@ -0,0 +1,355 @@
// What ZCode's own client (3.17.2) does with its Start Plan's in-flight cap,
// the plugin does: an account's requests go a few at a time (startGate), the
// rest wait their turn here instead of being sent to be refused, a refusal
// (3008/3009/3010) is asked again twice, after 1s and 2s, and the firewall
// hold counts only a refusal that a re-ask didn't get past. The requests go
// to a local Bun.serve that counts what is in flight; nothing reaches z.ai.
import { afterAll, afterEach, beforeAll, beforeEach, expect, test } from "bun:test"
import { homedir, tmpdir } from "node:os"
import { realpathSync } from "node:fs"
import { ZCodeAuthPlugin, _internal } from "./index.mjs"
const { BUSY_WAITS, startGate, busyHold } = _internal
const WAITS = [...BUSY_WAITS]
const GATE = { ...startGate, lanes: undefined }
let server
const got = [] // every request the fake took: when, whose
let answer = null // (req) => Response, what the fake answers
const now = { flight: new Map(), peak: new Map() } // in flight per account
beforeAll(() => {
if (![tmpdir(), realpathSync(tmpdir())].some((t) => homedir().startsWith(t))) throw new Error("run with HOME=$(mktemp -d) bun test")
server = Bun.serve({
port: 0,
async fetch(req) {
const who = req.headers.get("authorization") ?? ""
const path = new URL(req.url).pathname
const n = (now.flight.get(who) ?? 0) + 1
now.flight.set(who, n)
now.peak.set(who, Math.max(now.peak.get(who) ?? 0, n))
got.push({ at: Date.now(), who, path, flight: n })
try {
await req.text()
return answer ? await answer({ who, flight: n, path }) : Response.json({ type: "message", content: [] })
} finally {
now.flight.set(who, now.flight.get(who) - 1)
}
},
})
})
afterAll(() => server?.stop(true))
const real = globalThis.fetch
const HOSTS = ["https://zcode.z.ai", "https://api.z.ai", "https://open.bigmodel.cn"]
beforeEach(() => {
globalThis.fetch = (input, init) => {
const url = input instanceof Request ? input.url : String(input)
const host = HOSTS.find((h) => url.startsWith(h + "/"))
if (!host) throw new Error("no network in tests: " + url)
return real(`http://127.0.0.1:${server.port}/${new URL(host).host}${url.slice(host.length)}`, init)
}
got.length = 0
answer = null
now.flight.clear()
now.peak.clear()
_internal.routes.clear()
_internal.blocked.clear()
})
afterEach(() => {
globalThis.fetch = real
BUSY_WAITS.splice(0, BUSY_WAITS.length, ...WAITS)
startGate.inflight = GATE.inflight
startGate.wait = GATE.wait
startGate.lanes.clear()
busyHold.until = 0
busyHold.hits.length = 0
busyHold.now = () => Date.now()
_internal.edge.until = 0
})
const DEVICE = "11111111-2222-4333-8444-555555555555"
const jwtOf = (n) => ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600, n })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig"
const startAuth = (n = 1) => {
const jwt = jwtOf(n)
return { type: "oauth", access: jwt, refresh: JSON.stringify({ site: "zai", device: DEVICE, jwt, plan: "Start Plan" }), expires: 0 }
}
const planAuth = () => ({ type: "api", key: "one.secret", metadata: { site: "zai" } })
const BODY = JSON.stringify({ model: "GLM-5.3", max_tokens: 16, messages: [{ role: "user", content: "hi" }] })
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const CAP = () => Response.json({ code: 3008, msg: "user concurrency limit exceeded" }, { status: 429 })
const OK = () => Response.json({ type: "message", content: [] })
const messages = () => got.filter((r) => r.path.endsWith("/messages"))
async function loader(auth) {
const hooks = await ZCodeAuthPlugin({ client: { auth: { set: async () => {} } } })
return hooks.auth.loader(async () => auth, { id: "zcode" })
}
// one sends a request through opts and reads its answer to the end, as an
// agent's client does
async function one(opts, signal) {
const res = await opts.fetch("https://api.z.ai/api/anthropic/v1/messages", {
method: "POST",
headers: { "content-type": "application/json", "x-api-key": "zcode", "anthropic-version": "2023-06-01" },
body: BODY,
signal,
})
return { status: res.status, text: await res.text(), retryAfter: res.headers.get("retry-after") }
}
test("a cap is asked again twice, after 1s and 2s, then goes back to magpie", async () => {
answer = CAP
const opts = await loader(startAuth())
const res = await one(opts)
expect(res.status).toBe(429)
// three asks: the first and two again (0.1.55 asked seven times)
const asks = messages()
expect(asks.length).toBe(3)
const gaps = [asks[1].at - asks[0].at, asks[2].at - asks[1].at]
expect(gaps[0]).toBeGreaterThanOrEqual(950)
expect(gaps[0]).toBeLessThan(1600)
expect(gaps[1]).toBeGreaterThanOrEqual(1950)
expect(gaps[1]).toBeLessThan(2600)
expect(JSON.parse(res.text).msg).toContain("asked again after 1s and 2s")
})
test("3010 is a cap too, as ZCode's client reads it", async () => {
BUSY_WAITS.splice(0, BUSY_WAITS.length, 1, 1)
let n = 0
answer = () => (++n === 1 ? Response.json({ code: "3010", msg: "busy" }, { status: 429 }) : OK())
const res = await one(await loader(startAuth()))
expect(res.status).toBe(200)
expect(messages().length).toBe(2)
})
test("twelve Start Plan requests at once: three of an account in flight, the rest wait their turn", async () => {
answer = async () => {
await sleep(60)
return OK()
}
const opts = await loader(startAuth())
const rs = await Promise.all(Array.from({ length: 12 }, () => one(opts)))
expect(rs.every((r) => r.status === 200)).toBe(true)
// every request sent once, never more than three at once (0.1.55: 12)
expect(messages().length).toBe(12)
expect(Math.max(...now.peak.values())).toBe(3)
})
test("each account has slots of its own", async () => {
answer = async () => {
await sleep(60)
return OK()
}
const [a, b] = await Promise.all([loader(startAuth(1)), loader(startAuth(2))])
const rs = await Promise.all([...Array.from({ length: 5 }, () => one(a)), ...Array.from({ length: 5 }, () => one(b))])
expect(rs.every((r) => r.status === 200)).toBe(true)
expect([...now.peak.values()]).toEqual([3, 3])
})
test("a slot is held across the re-asks, and let go when the answer has been read", async () => {
BUSY_WAITS.splice(0, BUSY_WAITS.length, 50, 50)
const opts = await loader(startAuth())
let n = 0
answer = () => (++n <= 3 ? CAP() : OK())
// the first three are capped once each and wait 50ms with their slots; a
// fourth sent meanwhile waits behind them rather than adding to the cap
const rs = await Promise.all(Array.from({ length: 4 }, () => one(opts)))
expect(rs.every((r) => r.status === 200)).toBe(true)
expect(Math.max(...now.peak.values())).toBeLessThanOrEqual(3)
// the fourth went out only once a slot was let go: after a re-ask
const asks = messages()
expect(asks.length).toBe(7)
expect(asks.slice(0, 3).every((r) => r.at < asks[3].at)).toBe(true)
})
test("a wait that runs out is answered here, plainly, and nothing is sent", async () => {
startGate.wait = 150
let free = () => {}
const held = new Promise((r) => (free = r))
answer = async () => {
await held
return OK()
}
const opts = await loader(startAuth())
const first = Array.from({ length: 3 }, () => one(opts))
while (messages().length < 3) await sleep(5)
const t0 = Date.now()
const late = await one(opts)
expect(Date.now() - t0).toBeGreaterThanOrEqual(140)
expect(late.status).toBe(429)
expect(late.retryAfter).toBe("5")
const e = JSON.parse(late.text).error
expect(e.type).toBe("rate_limit_error")
expect(e.message).toContain("serves this account 3 requests at a time")
expect(e.message).toContain("was not sent")
expect(messages().length).toBe(3)
free()
expect((await Promise.all(first)).every((r) => r.status === 200)).toBe(true)
// the slots are back: the next request goes out at once
expect((await one(opts)).status).toBe(200)
expect(messages().length).toBe(4)
})
test("an agent that gives up while waiting leaves the queue", async () => {
let free = () => {}
const held = new Promise((r) => (free = r))
answer = async () => {
await held
return OK()
}
const opts = await loader(startAuth())
const first = Array.from({ length: 3 }, () => one(opts))
while (messages().length < 3) await sleep(5)
const ctl = new AbortController()
const gone = one(opts, ctl.signal)
const next = one(opts)
await sleep(20)
ctl.abort()
await expect(gone).rejects.toThrow()
free()
await Promise.all(first)
expect((await next).status).toBe(200)
// the request that gave up was never sent; the one behind it was
expect(messages().length).toBe(4)
expect(startGate.lanes.size).toBe(0)
})
test("a stream the agent stops reading lets its slot go", async () => {
answer = () =>
new Response(
new ReadableStream({
pull: async (c) => {
await sleep(20)
c.enqueue(new TextEncoder().encode("event: ping\ndata: {}\n\n"))
},
}),
{ headers: { "content-type": "text/event-stream" } },
)
const opts = await loader(startAuth())
const send = () => opts.fetch("https://api.z.ai/api/anthropic/v1/messages", { method: "POST", headers: { "content-type": "application/json" }, body: BODY })
const streams = await Promise.all([send(), send(), send()])
const fourth = send()
await sleep(50)
expect(messages().length).toBe(3)
const r = streams[0].body.getReader()
await r.read()
await r.cancel()
const res = await fourth
expect(res.status).toBe(200)
expect(messages().length).toBe(4)
for (const s of [res, ...streams.slice(1)]) await s.body.cancel()
})
test("the coding plan keeps no gate of the plugin's", async () => {
answer = async () => {
await sleep(60)
return OK()
}
const opts = await loader(planAuth())
const rs = await Promise.all(Array.from({ length: 8 }, () => one(opts)))
expect(rs.every((r) => r.status === 200)).toBe(true)
expect(Math.max(...now.peak.values())).toBe(8)
expect(startGate.lanes.size).toBe(0)
})
test("a cap the 1s re-ask got past counts toward no hold", async () => {
BUSY_WAITS.splice(0, BUSY_WAITS.length, 1, 1)
const opts = await loader(startAuth())
// every request is refused once, then served: a slot let go late, not a
// saturated address (0.1.55 held the Start Plan after five of these)
let n = 0
answer = () => (n++ % 2 === 0 ? CAP() : OK())
for (let i = 0; i < 8; i++) expect((await one(opts)).status).toBe(200)
expect(busyHold.until).toBe(0)
expect(busyHold.hits.length).toBe(0)
})
test("five requests refused again at their re-ask hold the Start Plan, in plain words", async () => {
BUSY_WAITS.splice(0, BUSY_WAITS.length, 1, 1)
const opts = await loader(startAuth())
let n = 0
// refused twice, then served at the 2s re-ask: still a sustained cap
answer = () => (n++ % 3 < 2 ? CAP() : OK())
for (let i = 0; i < 4; i++) expect((await one(opts)).status).toBe(200)
expect(busyHold.until).toBe(0)
// the fifth is refused again at its 1s re-ask: the hold arms, and its 2s
// re-ask is not sent
const fifth = await one(opts)
expect(fifth.status).toBe(429)
expect(messages().length).toBe(4 * 3 + 2)
expect(busyHold.until).toBeGreaterThan(Date.now())
const sent = messages().length
const held = await one(opts)
expect(held.status).toBe(429)
expect(messages().length).toBe(sent)
const said = JSON.parse(held.text).error.message
expect(said).toContain("ZCode turned away 5 requests in the last minute as too many requests at once")
expect(said).toContain("so that ZCode's firewall does not block this network".replace(/^s/, "S"))
expect(said).toContain("Wait, run fewer agents or subagents on ZCode at once, or use a GLM Coding Plan model")
})
// The scenario of #801's two days of logs (11-05 23:06, 11-06 06:23): agents
// asking the Start Plan of one account ~18 times a minute, up to ten at once,
// against an in-flight cap of about three; the edge firewall blocked the IP
// 3–7.5 minutes in. Replayed here at 20× speed — a minute is 3s, each turn
// 5–12s (0.25–0.6s), the re-ask waits and the hold's clock scaled alike —
// against a fake that refuses past three in flight. The plugin's own requests
// never go past the cap, so the vendor never refuses one, nothing is asked
// twice and no hold is needed; the requests that came faster than three at a
// time could serve waited here instead.
test("replay of #801's logs: nothing past the cap reaches ZCode, nothing refused, no hold", async () => {
const F = 20
BUSY_WAITS.splice(0, BUSY_WAITS.length, ...WAITS.map((w) => w / F))
startGate.wait = 120_000 / F
const t0 = Date.now()
busyHold.now = () => t0 + (Date.now() - t0) * F
let refused = 0
answer = async ({ flight }) => {
if (flight > 3) {
refused++
return CAP()
}
await sleep((5_000 + Math.random() * 7_000) / F)
return OK()
}
const opts = await loader(startAuth())
// four minutes of arrivals, ~18 a minute, in bursts of up to five
const sends = []
let at = 0
while (at < (4 * 60_000) / F) {
const burst = 1 + Math.floor(Math.random() * 5)
for (let i = 0; i < burst; i++) sends.push(sleep(at).then(() => one(opts)))
at += (burst * 60_000) / 18 / F
}
const rs = await Promise.all(sends)
expect(refused).toBe(0)
expect(Math.max(...now.peak.values())).toBeLessThanOrEqual(3)
expect(messages().length).toBe(rs.filter((r) => r.status === 200).length)
expect(busyHold.until).toBe(0)
// 3 slots of 5–12s turns serve ~25 a minute: every arrival was served
expect(rs.every((r) => r.status === 200)).toBe(true)
}, 30_000)
// The same replay with the account's slots taken by someone else (the ZCode
// app, another computer): ZCode refuses this computer's requests on and on.
// The hold still trips inside the replayed minute, and from then on nothing
// is sent until it ends — the firewall's protection #801 added.
test("replay with the account saturated elsewhere: the hold still trips within a minute", async () => {
const F = 20
BUSY_WAITS.splice(0, BUSY_WAITS.length, ...WAITS.map((w) => w / F))
const t0 = Date.now()
busyHold.now = () => t0 + (Date.now() - t0) * F
answer = CAP
const opts = await loader(startAuth())
const sends = []
for (let i = 0; i < 36; i++) sends.push(sleep((i * 60_000) / 18 / F).then(() => one(opts)))
const rs = await Promise.all(sends)
expect(rs.every((r) => r.status === 429)).toBe(true)
const armed = busyHold.until - _internal.BUSY_HOLD
expect(armed - t0).toBeLessThan(60_000)
// nothing went upstream after the hold armed (scaled back to real time)
const armedReal = t0 + (armed - t0) / F
expect(messages().filter((r) => r.at > armedReal + 5).length).toBe(0)
// and the upstream asks stayed within three per request
expect(messages().length).toBeLessThanOrEqual(3 * rs.length)
}, 30_000)
+1 -1
View File
@@ -1,6 +1,6 @@
{
"name": "@magpie-community/opencode-zcode-auth",
"version": "0.1.55",
"version": "0.1.56",
"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",
+24 -14
View File
@@ -51,6 +51,8 @@ afterEach(() => {
_internal.busyHold.until = 0
_internal.busyHold.hits.length = 0
_internal.busyHold.now = () => Date.now()
// a reply a test leaves unread keeps its Start Plan slot (startGate)
_internal.startGate.lanes.clear()
})
const sha = (s) => createHash("sha256").update(s, "utf8").digest("hex").slice(0, 16)
@@ -618,7 +620,7 @@ test("a run of busy caps holds the Start Plan off before the IP is blocked, and
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(e.message).toContain("ZCode turned away 5 requests in the last minute")
}
expect(messages()).toBe(0)
// the coding plan goes on, held or not
@@ -686,10 +688,12 @@ test("the busy hold reads its clock: a spread run holds nothing, caps during the
})
// 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.
// in flight when the hold arms get their counted cap after it. Hold the
// clock still, put 12 Start Plan requests in flight at once — four accounts,
// three each, as startGate lets them — and answer them all 3008 after they
// have all reached the fake. No first cap counts; the 1s re-asks are
// refused again and the fifth of those arms the hold. With the guard gone,
// the seven after it count toward a second hold.
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)
@@ -698,7 +702,12 @@ test("caps that land after the hold armed change neither hits nor until (request
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" })
const accounts = [1, 2, 3, 4].map((n) => {
const own = ["{}", JSON.stringify({ exp: Math.floor(Date.now() / 1000) + 3600, n })].map((s) => Buffer.from(s).toString("base64url")).join(".") + ".sig"
const s = { site: "zai", device: DEVICE, jwt: own, plan: "Start Plan" }
return { type: "oauth", access: own, refresh: JSON.stringify(s), expires: 0 }
})
const loaders = await Promise.all(accounts.map((a) => hooks.auth.loader(async () => a, { 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))
@@ -706,21 +715,22 @@ test("caps that land after the hold armed change neither hits nor until (request
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 }))
const all = loaders.flatMap((opts) =>
Array.from({ length: 3 }, () =>
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
// every request was refused twice; the fifth second refusal armed the
// hold, and the ones after it changed neither hits nor until. Each
// answer is the hold's own 429 with its Retry-After or, for the four
// that armed it, busyAnswer's
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(got.filter((r) => r.path.endsWith("/messages")).length).toBe(24)
expect(rs.filter((r) => r.headers.get("retry-after") === String(_internal.BUSY_HOLD / 1000)).length).toBeGreaterThanOrEqual(8)
expect(_internal.busyHold.hits.length).toBe(0)
expect(_internal.busyHold.until).toBe(clock + _internal.BUSY_HOLD)
} finally {