@magpie-community/opencode-zcode-auth 0.1.54 → 0.1.56

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -31,7 +31,10 @@ over Anthropic's Messages API. Provider id: `zcode`.
31
31
  picks by it, so without it the cache is mostly missed (#387). An
32
32
  account known only by its key gets a device id made from the key, the
33
33
  same on every start. Every request also carries the `x-session-id`
34
- header below. zcode.z.ai also
34
+ header below. ZCode's headers are the desktop app's (3.17.2):
35
+ `X-Title: Z Code@electron`, and an `x-query-id` per user turn, a UUID
36
+ that stays the same through the turn's tool results and is new with
37
+ the next user message, as ZCode makes one per query. zcode.z.ai also
35
38
  answers 405 code 3012 to every request of an account its risk control
36
39
  blocked, ZCode's own app's included (plugins#348). That answer comes
37
40
  back as ZCode's words, then "ZCode's risk control blocked this account
@@ -137,7 +140,7 @@ becomes a 429 and keeps the entry off for a minute. Any other gift
137
140
  answer (its 405, its 401, its 5xx) goes on as it came: the user picked
138
141
  the gift, so the coding plan is not spent behind their back. Every other
139
142
  429 counts as spent — Z.ai's 1302/1303 rate limits among them — while the
140
- plan's own in-flight cap (3008/3009) does not: such a request is asked
143
+ plan's own in-flight cap (3008/3009/3010) does not: such a request is asked
141
144
  again instead (see [A few at once](#a-few-at-once)). A stream's body is
142
145
  never read or buffered on the way.
143
146
 
@@ -192,43 +195,61 @@ a spent one answers 429 with freeFirst on, as it does without it.
192
195
  ## A few at once
193
196
 
194
197
  A plan serves one account a few requests at a time; past that, ZCode
195
- answers 429 with code 3008 "user concurrency limit exceeded", or 3009
196
- "model concurrency limit exceeded". magpie funnels every agent's and every
197
- session's requests of one computer through this one plugin process, so
198
- magpie's own queue spaces an account's requests by the number this plugin
199
- declares — `maxConcurrency` on the auth hook, and `magpie.maxConcurrency`
200
- in its `package.json`, both three. A request the vendor refuses anyway
201
- waits a moment (a quarter of a second, then longer — about ten seconds of
202
- waits in all) and asks again, the same request byte for byte. A cap that
203
- outlasts the waits goes on as a 429, ZCode's words followed by what they
198
+ answers 429 with code 3008 "user concurrency limit exceeded", 3009
199
+ "model concurrency limit exceeded" or 3010. magpie funnels every agent's
200
+ and every session's requests of one computer through this one plugin
201
+ process, so magpie's own queue spaces an account's requests by the number
202
+ this plugin declares — `maxConcurrency` on the auth hook, and
203
+ `magpie.maxConcurrency` in its `package.json`, both three. A request the
204
+ vendor refuses anyway is asked again after 1s and once more after 2s, the
205
+ same request byte for byte, as ZCode's own client (3.17.2) does. A cap
206
+ that outlasts both goes on as a 429, ZCode's words followed by what they
204
207
  mean, so the agent reads why. magpie still reads it as a rate limit: the
205
208
  account rests a minute and the request goes to the next member of its
206
- routing group, as it did before.
209
+ routing group.
207
210
 
208
- Three is a default, not a cap the plugin enforces. A plan's real cap
209
- follows its tier — Z.ai serves a Max plan more at once than a Pro, and a
210
- Lite fewer — and is higher off-peak
211
+ For a coding plan three is a default, not a cap the plugin enforces. A
212
+ plan's real cap follows its tier — Z.ai serves a Max plan more at once
213
+ than a Pro, and a Lite fewer — and is higher off-peak
211
214
  ([Z.ai's usage policy](https://docs.z.ai/devpack/usage-policy)), so a
212
215
  number written into the plugin would hold a Max account to a Lite one's
213
216
  with no way to raise it. A user who knows their plan's cap sets it on the
214
217
  account or the provider in magpie, and magpie's queue follows that.
215
218
 
219
+ The free Start Plan is one tier, measured at about three in flight
220
+ (plugins#395), so there the plugin keeps its own gate too: an account's
221
+ fourth Start Plan request waits in the plugin, in arrival order, until
222
+ one of the three has been read to its end (or its agent went away), and
223
+ is not sent to be refused. That covers what magpie's queue cannot see —
224
+ a `maxConcurrency` raised past three, two magpie providers on one ZCode
225
+ account, an older host. A request that has waited two minutes is answered
226
+ here with a 429 that says it was not sent and why. Free first skips the
227
+ gift while its account's gate is full, so the plain model goes to the
228
+ coding plan rather than queueing.
229
+
216
230
  A run of caps is also the edge firewall's countdown: two days of logs
217
- (11-05 and 11-06) show ~18 requests/min on the Start Plan bringing 3008
218
- caps in a run, then 3–7 minutes later a 405 block page that refuses the
219
- whole IP for 1–2 hours. The waits absorb most caps, so neither magpie nor
220
- the agent sees the address is saturated and nobody slows the arrival rate.
221
- Five cap-hit requests in one minute now hold Start Plan requests off
222
- `zcode.z.ai` for three minutes, process-wide and for every account, and
223
- answer them here with a 429 and `Retry-After`, so magpie still rests the
224
- account and asks the group's next provider. A coding plan, served by
225
- another host, is never held. The window clears when the hold is armed, so
226
- the hold's own 429s cannot keep it armed, and a request already in
227
- flight stops asking too: once the hold is armed, its remaining waits
228
- answer locally with the hold's 429 instead of asking the counting
229
- firewall again. This is distinct from the network's 405 block page hold
230
- (plugins#649), which is what an IP already refused needs; when both are
231
- on, the 405 hold's answer wins.
231
+ (11-05 and 11-06) show ~18 requests/min on the Start Plan, up to ten in
232
+ flight on one account, bringing 3008 caps in a run, then 3–7 minutes
233
+ later a 405 block page that refuses the whole IP for 1–2 hours. Up to
234
+ 0.1.55 the plugin itself added to that run: it sent every request magpie
235
+ passed it, asked a capped one again up to six times over about ten
236
+ seconds, and counted every capped request toward the hold, so busy agents
237
+ tripped the hold on refusals it had caused. With the gate the plugin's
238
+ own requests stay under the cap, and a request counts only when ZCode
239
+ refuses it again at the 1s re-ask, the sign that someone else (the ZCode
240
+ app, another computer on the account) holds the slots. Five such
241
+ requests in one minute hold Start Plan requests off `zcode.z.ai` for
242
+ three minutes, process-wide and for every account, and answer them here
243
+ with a 429 and `Retry-After` that say what happened and what to do, so
244
+ magpie still rests the account and asks the group's next provider. A
245
+ coding plan, served by another host, is never held. The window clears
246
+ when the hold is armed, so the hold's own 429s cannot keep it armed, and
247
+ a request already in flight or queued stops asking too. This is distinct
248
+ from the network's 405 block page hold (plugins#649), which is what an IP
249
+ already refused needs; when both are on, the 405 hold's answer wins.
250
+ `inflight.test.mjs` replays the two days at 20× speed against a fake that
251
+ refuses past three in flight: 0.1.55 drew 24 refusals in it, this version
252
+ none.
232
253
 
233
254
  ## Two accounts at once
234
255
 
@@ -326,6 +347,13 @@ the body's code, not the HTTP status:
326
347
  read is *failed*, never nothing to claim;
327
348
  - code 0: *claimed* (the next request uses the plan);
328
349
  - code 1003 "target already exists" (HTTP 200): *done*, claimed before;
350
+ - ZCode's own client config (`GET /api/v1/client/configs`, read at most
351
+ every ten minutes) says whether a claim needs its security check
352
+ (`captcha.enabled`). While it does, which is so since 11-07, nothing is
353
+ posted: every plan answers *captcha*, "claim it in the ZCode app", since
354
+ a claim without the app's proof only spends one of ZCode's refusals. A
355
+ config that doesn't read answers *failed*, and nothing is posted then
356
+ either;
329
357
  - code 3007 "captcha verify failed": *captcha*, the plan is claimed in
330
358
  the ZCode app — the claim is gated on the Aliyun captcha the app's
331
359
  renderer answers, and a claim from outside the app is refused it
package/index.mjs CHANGED
@@ -789,6 +789,23 @@ function noteRateLimit(key, saidMs, message) {
789
789
  }
790
790
  const CAPTCHA_WORDS = /captcha/i
791
791
 
792
+ // claimNeedsCaptcha says whether ZCode's claims want its security check
793
+ // now, from what client/configs says: its captcha (Aliyun's, which the
794
+ // ZCode app passes before every claim, invisibly as a rule, and sends as
795
+ // X-Aliyun-Captcha-Verify-Param, 3.17.2's requestVerificationClaimHeaders)
796
+ // switched on. No captcha in the configs is no check, as the app reads it
797
+ // (readRequestVerificationConfig gives null, and the claim goes without
798
+ // the header); one that isn't an object is unknown, null.
799
+ // skip_model_request is the same check for Start Plan requests, which it
800
+ // spares (true on 11-07); it is not read here.
801
+ function claimNeedsCaptcha(c) {
802
+ const k = c?.configs?.captcha
803
+ if (k == null) return false
804
+ if (typeof k !== "object" || Array.isArray(k)) return null
805
+ return k.enabled !== false
806
+ }
807
+ const CAPTCHA_CLAIM = "claim it in the ZCode app: ZCode asks its security check before a claim, which only the app passes, so the daily check-in leaves it to the app"
808
+
792
809
  // The marketing feed and the claim are gated on the client's version:
793
810
  // under an older version's header the feed answers empty (11-03, #678:
794
811
  // the day's banner showed for 3.17.2 and for no older one), so they go,
@@ -977,6 +994,24 @@ async function claimDaily(s) {
977
994
  ? { outcome: "failed", message: unread.join("; ") }
978
995
  : { outcome: "inactive", message: "no ZCode gift plan to claim", until: recheck() }
979
996
  }
997
+ // a claim ZCode guards with its security check is not posted: the app
998
+ // passes it before each claim and sends the proof in a header, which
999
+ // this plugin can't make, and a claim without it only gets 3007 again
1000
+ // (young02036 on Discord, 11-07: asked every day, never claimed). The
1001
+ // plans are named, to claim in the ZCode app. A config that doesn't
1002
+ // read leaves it unknown: nothing is posted, and it is asked again.
1003
+ let guarded
1004
+ try {
1005
+ guarded = claimNeedsCaptcha(await clientConfigs())
1006
+ } catch (e) {
1007
+ guarded = null
1008
+ unread.push(`ZCode's client config: ${e?.message ?? String(e)}`)
1009
+ }
1010
+ if (guarded !== false) {
1011
+ rateWait.delete(holdKey(s))
1012
+ if (guarded === null) return { outcome: "failed", message: [...plans.map((p) => `${p.name}: not claimed, ZCode's security check for claims can't be read`), ...unread].join("; ") }
1013
+ return { outcome: "captcha", message: plans.map((p) => `${p.name}: ${CAPTCHA_CLAIM}`).join("; ") }
1014
+ }
980
1015
  const got = []
981
1016
  for (const p of plans) got.push({ name: p.name, ...(await claimOne(s, p.plan_id)) })
982
1017
  const named = (o) => got.filter((g) => g.outcome === o).map((g) => g.name)
@@ -1833,7 +1868,7 @@ function localConfig() {
1833
1868
  // remoteConfig is the release of ZCode's provider config zcode.z.ai names now.
1834
1869
  async function remoteConfig() {
1835
1870
  const signal = AbortSignal.timeout(8000)
1836
- const c = await call("GET", `${ZCODE}/api/v1/client/configs?app_version=${APP_VERSION}&platform=${platform()}`, { signal })
1871
+ const c = await clientConfigs()
1837
1872
  const url = c?.configs?.builtin_provider_config_json
1838
1873
  if (!String(url ?? "").startsWith("https://")) throw new Error("ZCode's configs name no provider config")
1839
1874
  const res = await fetch(url, { headers: { "User-Agent": UA }, signal })
@@ -1841,6 +1876,23 @@ async function remoteConfig() {
1841
1876
  return res.json()
1842
1877
  }
1843
1878
 
1879
+ // clientConfigs is what zcode.z.ai tells this client version
1880
+ // (/api/v1/client/configs): the provider config's address, and the
1881
+ // captcha its claims and requests need (claimNeedsCaptcha). A read that
1882
+ // came through is kept for 10 minutes; a failed one is not kept, and
1883
+ // throws.
1884
+ let clientCache = null
1885
+ async function clientConfigs() {
1886
+ if (clientCache && Date.now() - clientCache.at < 600_000) return clientCache.c
1887
+ const c = await call("GET", `${ZCODE}/api/v1/client/configs?app_version=${APP_VERSION}&platform=${platform()}`, { signal: AbortSignal.timeout(8000) })
1888
+ clientCache = { c, at: Date.now() }
1889
+ return c
1890
+ }
1891
+ // resetClientConfigs is for tests: the next read asks zcode.z.ai again.
1892
+ export function resetClientConfigs() {
1893
+ clientCache = null
1894
+ }
1895
+
1844
1896
  // config is ZCode's provider config, the later of zcode.z.ai's and an
1845
1897
  // installed ZCode's, kept for 10 minutes.
1846
1898
  let cfgCache = null
@@ -1901,20 +1953,23 @@ function kept(res, text) {
1901
1953
 
1902
1954
  // ---- the plan's concurrency ------------------------------------------------------
1903
1955
  // ZCode serves one account a few requests at a time. Past that it answers 429
1904
- // with code 3008, "user concurrency limit exceeded", or 3009, "model
1905
- // concurrency limit exceeded": the request's turn has not come — not a plan
1906
- // spent (1113/1005) and not a rate limit (1302/1303). magpie sends every
1907
- // agent's and every session's requests of this computer through this one
1908
- // process, and its own queue spaces an account's requests by the number
1909
- // declared below (DEFAULT_CONCURRENCY, on the auth hook and in package.json);
1910
- // a request the vendor refuses anyway waits a moment and asks again, the same
1911
- // bytes. A refusal is immediate while a turn's answer is not, so a redundant
1912
- // ask costs a round trip and no tokens.
1956
+ // with code 3008, "user concurrency limit exceeded", 3009, "model
1957
+ // concurrency limit exceeded", or 3010: the request's turn has not come — not
1958
+ // a plan spent (1113/1005) and not a rate limit (1302/1303). ZCode's own
1959
+ // client (3.17.2) reads the three as one ("当前系统繁忙"), asks again after 1s
1960
+ // and 2s, and then gives up; it sends one request per session at a time and
1961
+ // has no hold. magpie sends every agent's and every session's requests of
1962
+ // this computer through this one process, so the plugin does what that
1963
+ // client does: the Start Plan gets a few requests of an account in flight at
1964
+ // once (startGate), the rest wait their turn here instead of being sent to be
1965
+ // refused, and a refusal anyway is asked again twice (BUSY_WAITS).
1913
1966
  //
1914
- // The plugin keeps no gate of its own: a plan's cap depends on its tier (Z.ai
1915
- // serves Max more at once than Pro, and Lite fewer) and is higher off-peak
1916
- // (https://docs.z.ai/devpack/usage-policy), so a number written here would
1917
- // hold a Max account to a Lite one's, with no way for the user to raise it.
1967
+ // The coding plan keeps no gate of the plugin's: its cap depends on its tier
1968
+ // (Z.ai serves Max more at once than Pro, and Lite fewer) and is higher
1969
+ // off-peak (https://docs.z.ai/devpack/usage-policy), so a number written here
1970
+ // would hold a Max account to a Lite one's. magpie's own queue spaces it by
1971
+ // the number declared below (DEFAULT_CONCURRENCY, on the auth hook and in
1972
+ // package.json), which a user raises on the account.
1918
1973
  const DEFAULT_CONCURRENCY = 3
1919
1974
  // DEFAULT_ACCOUNTS is how many of a user's ZCode accounts magpie sends
1920
1975
  // requests to at the same time (maxAccounts, on the auth hook and in
@@ -1923,30 +1978,163 @@ const DEFAULT_CONCURRENCY = 3
1923
1978
  // once from one address got the address refused with a 405, two didn't. A
1924
1979
  // user sets their own on the provider (Accounts at once), 0 for no limit.
1925
1980
  const DEFAULT_ACCOUNTS = 2
1926
- const BUSY_CODES = new Set(["3008", "3009"])
1927
- // BUSY_WAITS are the waits between asks, longest last: about ten seconds of
1928
- // them. Past that the account is saturated rather than busy, and magpie's
1929
- // routing takes the request (or rests the account, as its 429 says).
1930
- const BUSY_WAITS = [250, 500, 900, 1600, 2800, 4000]
1981
+ const BUSY_CODES = new Set(["3008", "3009", "3010"])
1982
+ // BUSY_WAITS are the waits before each ask again: ZCode's own client's,
1983
+ // 1s and 2s (kqo in its bundle). Past them the cap goes back to magpie,
1984
+ // which takes the request to another account or rests this one as its 429
1985
+ // says. Six asks over ten seconds, before 0.1.56, put two or three times the
1986
+ // requests a capped account could serve on the wire, and the agents' own
1987
+ // retries came on top.
1988
+ const BUSY_WAITS = [1000, 2000]
1989
+ // The hint names neither "plan" nor "limit": after the vendor's "…limit
1990
+ // exceeded" either would read to magpie as a plan used up.
1931
1991
  const BUSY_HINT =
1932
- "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"
1992
+ "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"
1993
+
1994
+ // startGate is the Start Plan's in-flight count per account. PR #395 measured
1995
+ // one Z.ai gift account at 3 of 12 parallel requests served in one run and 4
1996
+ // of 12 in another, so three are in flight at once, what magpie's queue sends
1997
+ // by DEFAULT_CONCURRENCY too. The gate holds them there when that queue
1998
+ // doesn't: a user who raised the account's number for the coding plan, two
1999
+ // magpie providers signed in to one account, a host that doesn't read
2000
+ // maxConcurrency. A cap the server still says now and then (a slot it lets
2001
+ // go of late, the ZCode app on the same account) the 1s re-ask gets past.
2002
+ // A request past them waits here, first come first served, until one is
2003
+ // answered to the end, up to startGate.wait; an agent that gives up leaves
2004
+ // the queue. A wait that runs out is answered startQueueAnswer's 429,
2005
+ // nothing sent. The gate lives in this process's memory alone, by account
2006
+ // (gateKey).
2007
+ const startGate = { inflight: 3, wait: 120_000, lanes: new Map() }
2008
+
2009
+ // startFull says the account's Start Plan slots are all taken, or others wait.
2010
+ const startFull = (key) => {
2011
+ const l = startGate.lanes.get(key)
2012
+ return !!l && (l.busy >= startGate.inflight || l.queue.length > 0)
2013
+ }
2014
+
2015
+ // startSlot waits for one of the account's Start Plan slots: { release },
2016
+ // null when startGate.wait ran out first, or the agent's abort thrown.
2017
+ function startSlot(key, signal) {
2018
+ const lanes = startGate.lanes
2019
+ let l = lanes.get(key)
2020
+ if (!l) lanes.set(key, (l = { busy: 0, queue: [] }))
2021
+ const next = () => {
2022
+ while (l.busy < startGate.inflight && l.queue.length) l.queue.shift()()
2023
+ if (!l.busy && !l.queue.length && lanes.get(key) === l) lanes.delete(key)
2024
+ }
2025
+ const take = () => {
2026
+ l.busy++
2027
+ let gone = false
2028
+ return {
2029
+ release() {
2030
+ if (gone) return
2031
+ gone = true
2032
+ l.busy--
2033
+ next()
2034
+ },
2035
+ }
2036
+ }
2037
+ if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"))
2038
+ if (l.busy < startGate.inflight && !l.queue.length) return Promise.resolve(take())
2039
+ return new Promise((resolve, reject) => {
2040
+ const leave = () => {
2041
+ clearTimeout(timer)
2042
+ signal?.removeEventListener?.("abort", aborted)
2043
+ const i = l.queue.indexOf(go)
2044
+ if (i >= 0) l.queue.splice(i, 1)
2045
+ }
2046
+ const go = () => {
2047
+ leave()
2048
+ resolve(take())
2049
+ }
2050
+ const aborted = () => {
2051
+ leave()
2052
+ next()
2053
+ reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"))
2054
+ }
2055
+ const timer = setTimeout(() => {
2056
+ leave()
2057
+ next()
2058
+ resolve(null)
2059
+ }, startGate.wait)
2060
+ signal?.addEventListener?.("abort", aborted, { once: true })
2061
+ l.queue.push(go)
2062
+ })
2063
+ }
2064
+
2065
+ // released hands res on and lets its slot go once ZCode's answer has come
2066
+ // to its end, failed, or been given up on (the agent's abort, the reader's
2067
+ // cancel) — the request is in flight at ZCode until then. The answer is read
2068
+ // as it comes, whether or not the agent reads it yet, so a reply read late,
2069
+ // or dropped unread, does not keep its slot past ZCode's own end of it.
2070
+ function released(res, slot, signal) {
2071
+ if (!slot) return res
2072
+ if (!res.body) {
2073
+ slot.release()
2074
+ return res
2075
+ }
2076
+ const reader = res.body.getReader()
2077
+ const stop = (why) => {
2078
+ slot.release()
2079
+ reader.cancel(why).catch(() => {})
2080
+ }
2081
+ signal?.addEventListener?.("abort", () => slot.release(), { once: true })
2082
+ const pump = async (c) => {
2083
+ try {
2084
+ for (;;) {
2085
+ const { done, value } = await reader.read()
2086
+ if (done) break
2087
+ c.enqueue(value)
2088
+ }
2089
+ slot.release()
2090
+ c.close()
2091
+ } catch (e) {
2092
+ slot.release()
2093
+ try {
2094
+ c.error(e)
2095
+ } catch {}
2096
+ }
2097
+ }
2098
+ // started, not awaited: the agent reads each chunk as it comes
2099
+ const body = new ReadableStream({ start: (c) => void pump(c), cancel: stop })
2100
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers })
2101
+ }
2102
+
2103
+ // startQueueAnswer is a request that waited its whole turn behind the
2104
+ // account's others and was never sent: a 429 magpie reads as a rate limit,
2105
+ // so it tries the next account, and a short Retry-After.
2106
+ function startQueueAnswer() {
2107
+ const error = {
2108
+ type: "rate_limit_error",
2109
+ 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`,
2110
+ }
2111
+ return new Response(JSON.stringify({ type: "error", error }), {
2112
+ status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" },
2113
+ })
2114
+ }
1933
2115
 
1934
2116
  // busyHold is the firewall's countdown. Two days of logs (11-05 23:06–23:15
1935
2117
  // and 11-06 06:23–06:27) show the same shape: sustained ~18 requests/min on
1936
- // the Start Plan brings code-3008 caps in a run, and 3–7.5 minutes later the
1937
- // edge firewall (errors.aliyun.com) refuses the whole IP with 405 for 1–2
1938
- // hours. askBusy's per-request waits absorb ~90% of those caps, so neither
1939
- // magpie nor the agent sees that the address is saturated and nobody slows
1940
- // the arrival rate down. A run of BUSY_N caps in one minute holds the Start
1941
- // Plan (zcode.z.ai only, process-wide, every account) off BUSY_HOLD. Replay
1942
- // of both days: N=5, H=3min freezes 2–7 minutes before the first 405 and
1943
- // spares 37–52 requests. A held request answers 429 with Retry-After, so
1944
- // magpie still reads a rate limit, rests the account and fails over; it is
1945
- // not the 405/BlockedHint of an IP already refused. The coding plan, on
1946
- // another host, is never held. The hold lives in this process's memory
1947
- // alone: magpie restarting forgets it. Only model requests are held —
1948
- // balance reads, the usage card and check-in still reach zcode.z.ai during
1949
- // it (the check-in holds its own reads per account on a 429).
2118
+ // the Start Plan, up to ~10 of them in flight against a cap of about three,
2119
+ // brings code-3008 caps in a run, and 3–7.5 minutes later the edge firewall
2120
+ // (errors.aliyun.com) refuses the whole IP with 405 for 1–2 hours. Re-asks
2121
+ // absorbed ~90% of those caps, so neither magpie nor the agent saw that the
2122
+ // address was saturated and nobody slowed the arrival rate down. startGate
2123
+ // now keeps this computer's own requests under the cap, so a cap is ZCode
2124
+ // busy or another client on the account; a request refused on its first ask
2125
+ // and again a second later (busyCap) is that, sustained, and BUSY_N of them
2126
+ // in one minute hold the Start Plan (zcode.z.ai only, process-wide, every
2127
+ // account) off BUSY_HOLD. A cap the 1s re-ask got past counts for nothing:
2128
+ // on 0.1.55 every capped request counted, a lone late slot as much as a
2129
+ // saturated address, and busy afternoons held users for nothing. Replay of
2130
+ // both days: N=5, H=3min froze 2–7 minutes before the first 405 and spared
2131
+ // 37–52 requests. A held request answers 429 with Retry-After, so magpie
2132
+ // still reads a rate limit, rests the account and fails over; it is not the
2133
+ // 405/BlockedHint of an IP already refused. The coding plan, on another
2134
+ // host, is never held. The hold lives in this process's memory alone: magpie
2135
+ // restarting forgets it. Only model requests are held — balance reads, the
2136
+ // usage card and check-in still reach zcode.z.ai during it (the check-in
2137
+ // holds its own reads per account on a 429).
1950
2138
  const BUSY_N = 5
1951
2139
  const BUSY_WINDOW = 60_000
1952
2140
  const BUSY_HOLD = 3 * 60_000
@@ -1955,10 +2143,10 @@ const busyHold = { hits: [], until: 0, now: () => Date.now() }
1955
2143
  // length and its expiry all read through it.
1956
2144
  const busyHeld = () => busyHold.now() < busyHold.until
1957
2145
 
1958
- // busyCap records one concurrency cap of a Start Plan request. Only a run
1959
- // arms a hold; the window is cleared on arming, and a cap that lands while
1960
- // the hold is on counts toward nothing — the hold's own 429s and the first
1961
- // caps after it cannot keep re-arming it.
2146
+ // busyCap records one sustained concurrency cap of a Start Plan request.
2147
+ // Only a run arms a hold; the window is cleared on arming, and a cap that
2148
+ // lands while the hold is on counts toward nothing — the hold's own 429s and
2149
+ // the first caps after it cannot keep re-arming it.
1962
2150
  function busyCap() {
1963
2151
  if (busyHeld()) return
1964
2152
  const now = busyHold.now()
@@ -1974,14 +2162,14 @@ function busyHeldAnswer() {
1974
2162
  const wait = Math.max(1, Math.ceil((busyHold.until - busyHold.now()) / 1000))
1975
2163
  const error = {
1976
2164
  type: "rate_limit_error",
1977
- 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`,
2165
+ 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`,
1978
2166
  }
1979
2167
  return new Response(JSON.stringify({ type: "error", error }), {
1980
2168
  status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": String(wait) },
1981
2169
  })
1982
2170
  }
1983
2171
 
1984
- // busy says a 429 is that in-flight cap: its own code (3008, 3009), or its
2172
+ // busy says a 429 is that in-flight cap: its own code (3008, 3009, 3010), or its
1985
2173
  // own words when the envelope carries no code.
1986
2174
  function busy(status, text) {
1987
2175
  if (status !== 429) return false
@@ -2022,19 +2210,20 @@ function busyAnswer(res, text) {
2022
2210
  }
2023
2211
 
2024
2212
  // askBusy asks once and, when the answer is the vendor's in-flight cap
2025
- // (3008/3009, or its own words), asks again through BUSY_WAITS's waits, a
2026
- // quarter of a second and longer — about ten seconds of them. Past that the
2027
- // account is saturated rather than busy, and the cap goes back as
2028
- // busyAnswer's 429. The plan path's patience, shared with free first's
2029
- // replay, whose plan has a cap of its own.
2213
+ // (3008/3009/3010, or its own words), asks again after BUSY_WAITS's waits,
2214
+ // 1s and then 2s, as ZCode's own client does. Past them the cap goes back as
2215
+ // busyAnswer's 429. A request refused again at its 1s re-ask is a sustained
2216
+ // cap, told to onCap once (the firewall hold's count); one the re-ask got
2217
+ // past is not. The plan path's patience, shared with free first's replay,
2218
+ // whose plan has a cap of its own.
2030
2219
  async function askBusy(u, o, hs, onCap) {
2031
2220
  let res = await fetch(u, { ...o, headers: hs })
2032
- let counted = false
2221
+ let caps = 0
2033
2222
  for (let i = 0; res.status === 429; i++) {
2034
2223
  const text = await res.text()
2035
2224
  const cap = busy(429, text)
2036
- // one request's retries are one saturation signal, not one per wait
2037
- if (cap && !counted) { counted = true; onCap?.() }
2225
+ // one request's refusals are one saturation signal, not one per ask
2226
+ if (cap && ++caps === 2) onCap?.()
2038
2227
  // the hold armed: a request already in flight stops asking too. The
2039
2228
  // second check catches the asks that capped before the hold armed and
2040
2229
  // woke from their wait after it. Keying on onCap keeps the coding plan
@@ -2044,8 +2233,7 @@ async function askBusy(u, o, hs, onCap) {
2044
2233
  res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
2045
2234
  break
2046
2235
  }
2047
- const w = BUSY_WAITS[i]
2048
- await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
2236
+ await sleep(BUSY_WAITS[i])
2049
2237
  if (onCap && busyHeld()) { res = busyHeldAnswer(); break }
2050
2238
  res = await fetch(u, { ...o, headers: hs })
2051
2239
  }
@@ -2182,7 +2370,12 @@ function startHeaders(h, jwt) {
2182
2370
  out.set("HTTP-Referer", ZCODE)
2183
2371
  out.set("User-Agent", UA + " ai-sdk/anthropic/3.0.81")
2184
2372
  out.set("X-ZCode-App-Version", APP_VERSION)
2185
- out.set("X-Title", "Z Code@cli")
2373
+ // the desktop app's agent names itself electron: 3.17.2's
2374
+ // zcode-protocol-entrypoint passes sourceTitle "electron", and a bare
2375
+ // run under app-server says the same (Mvc in glm/zcode.cjs); "cli" is
2376
+ // the zcode command line's alone, which sends no X-Device-Mid on the
2377
+ // app's calls and no desktop prompt texts, as this plugin does
2378
+ out.set("X-Title", "Z Code@electron")
2186
2379
  out.set("X-Release-Channel", "production")
2187
2380
  const o = intl()
2188
2381
  out.set("X-Client-Language", o.locale || "unknown")
@@ -2201,6 +2394,30 @@ function startHeaders(h, jwt) {
2201
2394
  return out
2202
2395
  }
2203
2396
 
2397
+ // queryOf is the request's x-query-id, as 3.17.2's
2398
+ // createModelRequestAttributionHeaders (zft in glm/zcode.cjs) sends it:
2399
+ // the user's query, "query_" + a UUID with the prefix cut, the same for
2400
+ // every request of one turn (the tool calls the model makes on the way)
2401
+ // and a new one for the next thing the user says. The agent's turns are
2402
+ // counted: a user message that carries text, not tool results alone,
2403
+ // starts a query. A body that doesn't read gives none, and none is sent.
2404
+ function queryOf(text, session) {
2405
+ let b
2406
+ try {
2407
+ b = JSON.parse(text)
2408
+ } catch {
2409
+ return ""
2410
+ }
2411
+ if (!Array.isArray(b?.messages)) return ""
2412
+ let n = 0
2413
+ for (const m of b.messages) {
2414
+ if (m?.role !== "user") continue
2415
+ const c = m.content
2416
+ if (typeof c === "string" ? c.trim() : Array.isArray(c) && c.some((x) => x && x.type !== "tool_result")) n++
2417
+ }
2418
+ return n ? uuidOf("zcode-query\0" + session + "\0" + n) : ""
2419
+ }
2420
+
2204
2421
  // Claude Code's tool search, as ZCode's plans take it. Claude Code
2205
2422
  // (2.1.310) offers a tool named ToolSearch, names its deferred tools in a
2206
2423
  // system turn, and sends a deferred tool's schema with defer_loading only
@@ -2576,9 +2793,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2576
2793
  provider: PROVIDER,
2577
2794
  // a plan serves one account a few requests at a time: magpie's own
2578
2795
  // field, so its queue spaces what the agents ask for before the vendor
2579
- // sees it. This is a default, not a cap the plugin enforces — a plan's
2580
- // own cap follows its tier (Max > Pro > Lite) and the time of day, and
2581
- // a user who knows theirs can raise this on the account
2796
+ // sees it. For the coding plan this is a default, not a cap the plugin
2797
+ // enforces — its cap follows its tier (Max > Pro > Lite) and the time
2798
+ // of day, and a user who knows theirs can raise this on the account.
2799
+ // The Start Plan has the plugin's own gate below it (startGate)
2582
2800
  maxConcurrency: DEFAULT_CONCURRENCY,
2583
2801
  // how many accounts take requests at once, the others in reserve
2584
2802
  // (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all
@@ -2608,9 +2826,24 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2608
2826
  baseURL: s0.base + "/v1",
2609
2827
  apiKey: s0.key || "zcode", // the fetch below puts the real one on
2610
2828
  async fetch(input, init) {
2829
+ // a Start Plan request holds one of its account's slots
2830
+ // (startSlot) until its answer has been read to the end
2831
+ const own = {}
2832
+ try {
2833
+ return released(await serve(input, init, own), own.slot, own.signal)
2834
+ } catch (e) {
2835
+ own.slot?.release()
2836
+ throw e
2837
+ }
2838
+ },
2839
+ }
2840
+ async function serve(input, init, own) {
2611
2841
  const auth = await getAuth()
2612
2842
  const s = await located(stateOf(auth))
2613
2843
  if (!s) throw new Error("not signed in to ZCode")
2844
+ // the account a Start Plan slot belongs to: its user id, which a
2845
+ // renewed session keeps, before the key or session itself
2846
+ const gateKey = String(auth?.uid || auth?.accountId || holdKey(s))
2614
2847
  let url = input instanceof Request ? input.url : String(input)
2615
2848
  const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
2616
2849
  const { start: alone, gift: known } = await plansOf(s)
@@ -2653,7 +2886,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2653
2886
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
2654
2887
  m = raw
2655
2888
  forcedGift = true
2656
- } else if (!alone && !edgeHeld() && !busyHeld() && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
2889
+ } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
2657
2890
  // free first: the plain model spends the account's own live
2658
2891
  // gift before it spends the coding plan, under the name the
2659
2892
  // gift lists. The gift is the route's cache alone (a failed
@@ -2665,7 +2898,9 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2665
2898
  // a block page) keeps the plain model off the gift: the
2666
2899
  // coding plan is never held, and free first must not move
2667
2900
  // the request onto a route the hold answers 429 without
2668
- // asking.
2901
+ // asking. Nor onto a gift whose slots are all taken
2902
+ // (startFull): the plan serves it now, the gift only after
2903
+ // the others.
2669
2904
  const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase())
2670
2905
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
2671
2906
  m = raw
@@ -2700,6 +2935,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2700
2935
  // agent sent it, the plan's headers, the plan's own patience
2701
2936
  // (askBusy).
2702
2937
  const replayOnPlan = async () => {
2938
+ // the gift is done with: its slot goes to the next request
2939
+ own.slot?.release()
2703
2940
  let u = askedUrl
2704
2941
  for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
2705
2942
  if (u.startsWith(b)) {
@@ -2728,6 +2965,16 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2728
2965
  // edge firewall could block the IP: a held request is answered
2729
2966
  // here, with a 429 magpie still reads as a rate limit
2730
2967
  if (start && busyHeld()) return kept(busyHeldAnswer())
2968
+ // the account's Start Plan slots (startGate): a request past them
2969
+ // waits here for one rather than being sent to be refused
2970
+ if (start) {
2971
+ own.slot = await startSlot(gateKey, opts.signal)
2972
+ own.signal = opts.signal
2973
+ if (!own.slot) return kept(startQueueAnswer())
2974
+ // a hold may have armed while it waited
2975
+ if (edgeHeld()) return kept(edgeHeldAnswer())
2976
+ if (busyHeld()) return kept(busyHeldAnswer())
2977
+ }
2731
2978
  if (start) {
2732
2979
  if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
2733
2980
  if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
@@ -2739,6 +2986,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2739
2986
  if (opts.body != null) {
2740
2987
  const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text())
2741
2988
  opts.body = dress(text, s.site, s.device, place, sid)
2989
+ const q = queryOf(text, sid)
2990
+ if (q) h.set("x-query-id", q)
2742
2991
  delete opts.duplex
2743
2992
  h.delete("content-length")
2744
2993
  }
@@ -2855,7 +3104,6 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2855
3104
  // A spent bucket's 200 says 429 (spentSaid), as a trial
2856
3105
  // entry's does, so magpie rests the model, not the account
2857
3106
  return done(kept(await spentSaid(res)))
2858
- },
2859
3107
  }
2860
3108
  },
2861
3109
  // the plan's allowance, as magpie's built-in showed it. Each read
@@ -2975,4 +3223,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2975
3223
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
2976
3224
  // out of reach, undefined forgets it
2977
3225
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
2978
- 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 }
3226
+ 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 }
package/opencode2.mjs CHANGED
@@ -86,7 +86,10 @@ export function fieldsOf(prompts) {
86
86
  if (p.type === "select" && Array.isArray(p.options))
87
87
  f.options = p.options.map((o) => ({ value: String(o.value), label: String(o.label ?? o.value), ...(o.hint ? { description: String(o.hint) } : {}) }))
88
88
  // a prompt shown only when another answer says so can't be required
89
- if (!p.condition) f.required = true
89
+ // a prompt shown only when another answer says so can't be required, and
90
+ // neither can one whose own validate() accepts an empty answer (the
91
+ // browser sign-in's optional API key)
92
+ if (!p.condition && p.required !== false) f.required = true
90
93
  out.push(f)
91
94
  }
92
95
  return out.length ? out : undefined
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.54",
3
+ "version": "0.1.56",
4
4
  "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",
5
5
  "type": "module",
6
6
  "main": "./opencode.mjs",