@magpie-community/opencode-zcode-auth 0.1.53 → 0.1.55

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.
Files changed (3) hide show
  1. package/README.md +28 -1
  2. package/index.mjs +163 -8
  3. package/package.json +1 -1
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
@@ -213,6 +216,23 @@ 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
+ A run of caps is also the edge firewall's countdown: two days of logs
220
+ (11-05 and 11-06) show ~18 requests/min on the Start Plan bringing 3008
221
+ caps in a run, then 3–7 minutes later a 405 block page that refuses the
222
+ whole IP for 1–2 hours. The waits absorb most caps, so neither magpie nor
223
+ the agent sees the address is saturated and nobody slows the arrival rate.
224
+ Five cap-hit requests in one minute now hold Start Plan requests off
225
+ `zcode.z.ai` for three minutes, process-wide and for every account, and
226
+ answer them here with a 429 and `Retry-After`, so magpie still rests the
227
+ account and asks the group's next provider. A coding plan, served by
228
+ another host, is never held. The window clears when the hold is armed, so
229
+ the hold's own 429s cannot keep it armed, and a request already in
230
+ flight stops asking too: once the hold is armed, its remaining waits
231
+ answer locally with the hold's 429 instead of asking the counting
232
+ firewall again. This is distinct from the network's 405 block page hold
233
+ (plugins#649), which is what an IP already refused needs; when both are
234
+ on, the 405 hold's answer wins.
235
+
216
236
  ## Two accounts at once
217
237
 
218
238
  Three ZCode accounts used at once from one address can get the address
@@ -309,6 +329,13 @@ the body's code, not the HTTP status:
309
329
  read is *failed*, never nothing to claim;
310
330
  - code 0: *claimed* (the next request uses the plan);
311
331
  - code 1003 "target already exists" (HTTP 200): *done*, claimed before;
332
+ - ZCode's own client config (`GET /api/v1/client/configs`, read at most
333
+ every ten minutes) says whether a claim needs its security check
334
+ (`captcha.enabled`). While it does, which is so since 11-07, nothing is
335
+ posted: every plan answers *captcha*, "claim it in the ZCode app", since
336
+ a claim without the app's proof only spends one of ZCode's refusals. A
337
+ config that doesn't read answers *failed*, and nothing is posted then
338
+ either;
312
339
  - code 3007 "captcha verify failed": *captcha*, the plan is claimed in
313
340
  the ZCode app — the claim is gated on the Aliyun captcha the app's
314
341
  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
@@ -1931,6 +1983,56 @@ const BUSY_WAITS = [250, 500, 900, 1600, 2800, 4000]
1931
1983
  const BUSY_HINT =
1932
1984
  "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"
1933
1985
 
1986
+ // busyHold is the firewall's countdown. Two days of logs (11-05 23:06–23:15
1987
+ // and 11-06 06:23–06:27) show the same shape: sustained ~18 requests/min on
1988
+ // the Start Plan brings code-3008 caps in a run, and 3–7.5 minutes later the
1989
+ // edge firewall (errors.aliyun.com) refuses the whole IP with 405 for 1–2
1990
+ // hours. askBusy's per-request waits absorb ~90% of those caps, so neither
1991
+ // magpie nor the agent sees that the address is saturated and nobody slows
1992
+ // the arrival rate down. A run of BUSY_N caps in one minute holds the Start
1993
+ // Plan (zcode.z.ai only, process-wide, every account) off BUSY_HOLD. Replay
1994
+ // of both days: N=5, H=3min freezes 2–7 minutes before the first 405 and
1995
+ // spares 37–52 requests. A held request answers 429 with Retry-After, so
1996
+ // magpie still reads a rate limit, rests the account and fails over; it is
1997
+ // not the 405/BlockedHint of an IP already refused. The coding plan, on
1998
+ // another host, is never held. The hold lives in this process's memory
1999
+ // alone: magpie restarting forgets it. Only model requests are held —
2000
+ // balance reads, the usage card and check-in still reach zcode.z.ai during
2001
+ // it (the check-in holds its own reads per account on a 429).
2002
+ const BUSY_N = 5
2003
+ const BUSY_WINDOW = 60_000
2004
+ const BUSY_HOLD = 3 * 60_000
2005
+ const busyHold = { hits: [], until: 0, now: () => Date.now() }
2006
+ // busyHold.now is the clock, injectable for tests: a hold's window, its
2007
+ // length and its expiry all read through it.
2008
+ const busyHeld = () => busyHold.now() < busyHold.until
2009
+
2010
+ // busyCap records one concurrency cap of a Start Plan request. Only a run
2011
+ // arms a hold; the window is cleared on arming, and a cap that lands while
2012
+ // the hold is on counts toward nothing — the hold's own 429s and the first
2013
+ // caps after it cannot keep re-arming it.
2014
+ function busyCap() {
2015
+ if (busyHeld()) return
2016
+ const now = busyHold.now()
2017
+ busyHold.hits.push(now)
2018
+ while (busyHold.hits.length && now - busyHold.hits[0] > BUSY_WINDOW) busyHold.hits.shift()
2019
+ if (busyHold.hits.length >= BUSY_N) {
2020
+ busyHold.until = now + BUSY_HOLD
2021
+ busyHold.hits.length = 0
2022
+ }
2023
+ }
2024
+
2025
+ function busyHeldAnswer() {
2026
+ const wait = Math.max(1, Math.ceil((busyHold.until - busyHold.now()) / 1000))
2027
+ const error = {
2028
+ type: "rate_limit_error",
2029
+ 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`,
2030
+ }
2031
+ return new Response(JSON.stringify({ type: "error", error }), {
2032
+ status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": String(wait) },
2033
+ })
2034
+ }
2035
+
1934
2036
  // busy says a 429 is that in-flight cap: its own code (3008, 3009), or its
1935
2037
  // own words when the envelope carries no code.
1936
2038
  function busy(status, text) {
@@ -1977,17 +2079,26 @@ function busyAnswer(res, text) {
1977
2079
  // account is saturated rather than busy, and the cap goes back as
1978
2080
  // busyAnswer's 429. The plan path's patience, shared with free first's
1979
2081
  // replay, whose plan has a cap of its own.
1980
- async function askBusy(u, o, hs) {
2082
+ async function askBusy(u, o, hs, onCap) {
1981
2083
  let res = await fetch(u, { ...o, headers: hs })
2084
+ let counted = false
1982
2085
  for (let i = 0; res.status === 429; i++) {
1983
2086
  const text = await res.text()
1984
2087
  const cap = busy(429, text)
2088
+ // one request's retries are one saturation signal, not one per wait
2089
+ if (cap && !counted) { counted = true; onCap?.() }
2090
+ // the hold armed: a request already in flight stops asking too. The
2091
+ // second check catches the asks that capped before the hold armed and
2092
+ // woke from their wait after it. Keying on onCap keeps the coding plan
2093
+ // and free first's replay (no onCap) as they are.
2094
+ if (cap && onCap && busyHeld()) { res = busyHeldAnswer(); break }
1985
2095
  if (!cap || i >= BUSY_WAITS.length) {
1986
2096
  res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
1987
2097
  break
1988
2098
  }
1989
2099
  const w = BUSY_WAITS[i]
1990
2100
  await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
2101
+ if (onCap && busyHeld()) { res = busyHeldAnswer(); break }
1991
2102
  res = await fetch(u, { ...o, headers: hs })
1992
2103
  }
1993
2104
  return res
@@ -2123,7 +2234,12 @@ function startHeaders(h, jwt) {
2123
2234
  out.set("HTTP-Referer", ZCODE)
2124
2235
  out.set("User-Agent", UA + " ai-sdk/anthropic/3.0.81")
2125
2236
  out.set("X-ZCode-App-Version", APP_VERSION)
2126
- out.set("X-Title", "Z Code@cli")
2237
+ // the desktop app's agent names itself electron: 3.17.2's
2238
+ // zcode-protocol-entrypoint passes sourceTitle "electron", and a bare
2239
+ // run under app-server says the same (Mvc in glm/zcode.cjs); "cli" is
2240
+ // the zcode command line's alone, which sends no X-Device-Mid on the
2241
+ // app's calls and no desktop prompt texts, as this plugin does
2242
+ out.set("X-Title", "Z Code@electron")
2127
2243
  out.set("X-Release-Channel", "production")
2128
2244
  const o = intl()
2129
2245
  out.set("X-Client-Language", o.locale || "unknown")
@@ -2142,6 +2258,30 @@ function startHeaders(h, jwt) {
2142
2258
  return out
2143
2259
  }
2144
2260
 
2261
+ // queryOf is the request's x-query-id, as 3.17.2's
2262
+ // createModelRequestAttributionHeaders (zft in glm/zcode.cjs) sends it:
2263
+ // the user's query, "query_" + a UUID with the prefix cut, the same for
2264
+ // every request of one turn (the tool calls the model makes on the way)
2265
+ // and a new one for the next thing the user says. The agent's turns are
2266
+ // counted: a user message that carries text, not tool results alone,
2267
+ // starts a query. A body that doesn't read gives none, and none is sent.
2268
+ function queryOf(text, session) {
2269
+ let b
2270
+ try {
2271
+ b = JSON.parse(text)
2272
+ } catch {
2273
+ return ""
2274
+ }
2275
+ if (!Array.isArray(b?.messages)) return ""
2276
+ let n = 0
2277
+ for (const m of b.messages) {
2278
+ if (m?.role !== "user") continue
2279
+ const c = m.content
2280
+ if (typeof c === "string" ? c.trim() : Array.isArray(c) && c.some((x) => x && x.type !== "tool_result")) n++
2281
+ }
2282
+ return n ? uuidOf("zcode-query\0" + session + "\0" + n) : ""
2283
+ }
2284
+
2145
2285
  // Claude Code's tool search, as ZCode's plans take it. Claude Code
2146
2286
  // (2.1.310) offers a tool named ToolSearch, names its deferred tools in a
2147
2287
  // system turn, and sends a deferred tool's schema with defer_loading only
@@ -2594,7 +2734,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2594
2734
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
2595
2735
  m = raw
2596
2736
  forcedGift = true
2597
- } else if (!alone && !edgeHeld() && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
2737
+ } else if (!alone && !edgeHeld() && !busyHeld() && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
2598
2738
  // free first: the plain model spends the account's own live
2599
2739
  // gift before it spends the coding plan, under the name the
2600
2740
  // gift lists. The gift is the route's cache alone (a failed
@@ -2602,7 +2742,11 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2602
2742
  // the request on the plan with no read per request; a
2603
2743
  // gift-only account is already on the gift and is left as
2604
2744
  // it was. A refusal past this check is replayed on the plan
2605
- // in the same request (replayOnPlan below).
2745
+ // in the same request (replayOnPlan below). A busy hold (or
2746
+ // a block page) keeps the plain model off the gift: the
2747
+ // coding plan is never held, and free first must not move
2748
+ // the request onto a route the hold answers 429 without
2749
+ // asking.
2606
2750
  const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase())
2607
2751
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
2608
2752
  m = raw
@@ -2657,8 +2801,14 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2657
2801
  }
2658
2802
  // a block page held this computer off zcode.z.ai (edge): the
2659
2803
  // Start Plan and a picked gift are answered here; free first
2660
- // already left the gift for the plan
2804
+ // already left the gift for the plan. Checked before the busy
2805
+ // hold: an IP the firewall already refused keeps that behavior
2806
+ // (the 405 magpie reads as the network's), hold or no hold.
2661
2807
  if (start && edgeHeld()) return kept(edgeHeldAnswer())
2808
+ // a run of busy caps held this computer off zcode.z.ai before the
2809
+ // edge firewall could block the IP: a held request is answered
2810
+ // here, with a 429 magpie still reads as a rate limit
2811
+ if (start && busyHeld()) return kept(busyHeldAnswer())
2662
2812
  if (start) {
2663
2813
  if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
2664
2814
  if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
@@ -2670,6 +2820,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2670
2820
  if (opts.body != null) {
2671
2821
  const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text())
2672
2822
  opts.body = dress(text, s.site, s.device, place, sid)
2823
+ const q = queryOf(text, sid)
2824
+ if (q) h.set("x-query-id", q)
2673
2825
  delete opts.duplex
2674
2826
  h.delete("content-length")
2675
2827
  }
@@ -2698,7 +2850,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2698
2850
  // the number declared above
2699
2851
  let res
2700
2852
  try {
2701
- res = await askBusy(url, opts, h)
2853
+ // Only Start Plan caps count toward the firewall hold: the
2854
+ // coding plan is served by another host and was never refused
2855
+ // with the IP's 405.
2856
+ res = await askBusy(url, opts, h, start ? busyCap : undefined)
2702
2857
  } catch (e) {
2703
2858
  // free first moved the request onto the gift, so a gift that
2704
2859
  // cannot be asked at all — the network, the host — is answered
@@ -2903,4 +3058,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2903
3058
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
2904
3059
  // out of reach, undefined forgets it
2905
3060
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
2906
- export const _internal = { edge, EDGE_HOLD, config, entry, limitWindows, termOf, startUsage, routes, blocked, sidelined, plansOf, giftOf, dualUsage, claimHint, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, DEFAULT_ACCOUNTS }
3061
+ 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 }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.53",
3
+ "version": "0.1.55",
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",