@magpie-community/opencode-zcode-auth 0.1.31 → 0.1.32

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 +27 -3
  2. package/index.mjs +96 -4
  3. package/package.json +4 -1
package/README.md CHANGED
@@ -128,9 +128,33 @@ coding plan; when the gift answers a trial entry with a quota error
128
128
  "exceed quota limit", which it can answer inside an HTTP 200) that too
129
129
  becomes a 429 and keeps the entry off for a minute. Any other gift
130
130
  answer (its 405, its 401, its 5xx) goes on as it came: the user picked
131
- the gift, so the coding plan is not spent behind their back. Every 429
132
- counts as spent, Z.ai's 1302/1303 rate limits among them. A stream's
133
- body is never read or buffered on the way.
131
+ the gift, so the coding plan is not spent behind their back. Every other
132
+ 429 counts as spent — Z.ai's 1302/1303 rate limits among them — while the
133
+ plan's own in-flight cap (3008/3009) does not: such a request is asked
134
+ again instead (see [A few at once](#a-few-at-once)). A stream's body is
135
+ never read or buffered on the way.
136
+
137
+ ## A few at once
138
+
139
+ A plan serves one account a few requests at a time; past that, ZCode
140
+ answers 429 with code 3008 "user concurrency limit exceeded", or 3009
141
+ "model concurrency limit exceeded". magpie funnels every agent's and every
142
+ session's requests of one computer through this one plugin process, so
143
+ magpie's own queue spaces an account's requests by the number this plugin
144
+ declares — `maxConcurrency` on the auth hook, and `magpie.maxConcurrency`
145
+ in its `package.json`, both three. A request the vendor refuses anyway
146
+ waits a moment (a quarter of a second, then longer — about ten seconds of
147
+ waits in all) and asks again, the same request byte for byte. A cap that
148
+ outlasts the waits goes on as it came, ZCode's words followed by what it
149
+ is, so magpie can move that request along instead of resting the account.
150
+
151
+ Three is a default, not a cap the plugin enforces. A plan's real cap
152
+ follows its tier — Z.ai serves a Max plan more at once than a Pro, and a
153
+ Lite fewer — and is higher off-peak
154
+ ([Z.ai's usage policy](https://docs.z.ai/devpack/usage-policy)), so a
155
+ number written into the plugin would hold a Max account to a Lite one's
156
+ with no way to raise it. A user who knows their plan's cap sets it on the
157
+ account or the provider in magpie, and magpie's queue follows that.
134
158
 
135
159
  ## The usage card
136
160
 
package/index.mjs CHANGED
@@ -265,9 +265,11 @@ const giftUsable = (s, gift, m) => !jwtExpired(s.jwt) && giftServes(gift, m) &&
265
265
 
266
266
  // spentUp is the gift saying it has nothing left to spend: its own no-
267
267
  // resource-package code 1113, its "exceed quota limit" 1005 — a spent gift
268
- // can answer a 200 with a JSON body carrying one of those codes. Every 429
269
- // counts as spent, Z.ai's 1302/1303 rate limits among them.
268
+ // can answer a 200 with a JSON body carrying one of those codes. Every other
269
+ // 429 counts as spent, Z.ai's 1302/1303 rate limits among them; the plan's
270
+ // own in-flight cap (3008/3009) does not, since it is a turn not yet come.
270
271
  function spentUp(text, status) {
272
+ if (busy(status, text)) return false
271
273
  if (status === 429) return true
272
274
  let b
273
275
  try { b = JSON.parse(text) } catch { return false }
@@ -1516,6 +1518,71 @@ function kept(res, text) {
1516
1518
  return new Response(text !== undefined ? text : res.body, { status: res.status, statusText: res.statusText, headers: h })
1517
1519
  }
1518
1520
 
1521
+ // ---- the plan's concurrency ------------------------------------------------------
1522
+ // ZCode serves one account a few requests at a time. Past that it answers 429
1523
+ // with code 3008, "user concurrency limit exceeded", or 3009, "model
1524
+ // concurrency limit exceeded": the request's turn has not come — not a plan
1525
+ // spent (1113/1005) and not a rate limit (1302/1303). magpie sends every
1526
+ // agent's and every session's requests of this computer through this one
1527
+ // process, and its own queue spaces an account's requests by the number
1528
+ // declared below (DEFAULT_CONCURRENCY, on the auth hook and in package.json);
1529
+ // a request the vendor refuses anyway waits a moment and asks again, the same
1530
+ // bytes. A refusal is immediate while a turn's answer is not, so a redundant
1531
+ // ask costs a round trip and no tokens.
1532
+ //
1533
+ // The plugin keeps no gate of its own: a plan's cap depends on its tier (Z.ai
1534
+ // serves Max more at once than Pro, and Lite fewer) and is higher off-peak
1535
+ // (https://docs.z.ai/devpack/usage-policy), so a number written here would
1536
+ // hold a Max account to a Lite one's, with no way for the user to raise it.
1537
+ const DEFAULT_CONCURRENCY = 3
1538
+ const BUSY_CODES = new Set(["3008", "3009"])
1539
+ // BUSY_WAITS are the waits between asks, longest last: about ten seconds of
1540
+ // them. Past that the account is saturated rather than busy, and magpie's
1541
+ // routing takes the request (or rests the account, as its 429 says).
1542
+ const BUSY_WAITS = [250, 500, 900, 1600, 2800, 4000]
1543
+ const BUSY_HINT =
1544
+ "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"
1545
+
1546
+ // busy says a 429 is that in-flight cap: its own code (3008, 3009), or its
1547
+ // own words when the envelope carries no code.
1548
+ function busy(status, text) {
1549
+ if (status !== 429) return false
1550
+ let b
1551
+ try {
1552
+ b = JSON.parse(text)
1553
+ } catch {
1554
+ return false
1555
+ }
1556
+ if (!b || typeof b !== "object") return false
1557
+ const say = (v) => (v == null || typeof v === "object" ? "" : String(v))
1558
+ if (BUSY_CODES.has(say(b.code) || say(b.error?.code))) return true
1559
+ return /concurrency limit exceeded/i.test(say(b.msg) + " " + say(b.message) + " " + say(b.error?.message) + " " + say(b.error))
1560
+ }
1561
+
1562
+ // busyAnswer is the vendor's cap refusal as the agent reads it: its words,
1563
+ // then what they are and what to do, as noPlanKey says why a key has no plan.
1564
+ function busyAnswer(res, text) {
1565
+ const h = new Headers(res.headers)
1566
+ h.set("content-type", "application/json")
1567
+ let v
1568
+ try {
1569
+ v = JSON.parse(text)
1570
+ } catch {}
1571
+ if (v && typeof v === "object") {
1572
+ const said = first(v.msg, v.message, v.error?.message, typeof v.error === "string" ? v.error : "", `${res.status}`)
1573
+ const code = v.code ?? v.error?.code
1574
+ const head = code != null && !said.includes(String(code)) ? `${said} (${res.status}, code ${code})` : said
1575
+ const message = `${head} — ${BUSY_HINT}`
1576
+ const out = v.error && typeof v.error === "object" ? { ...v, error: { ...v.error, message } } : { ...v, msg: message }
1577
+ return new Response(JSON.stringify(out), { status: res.status, statusText: res.statusText, headers: h })
1578
+ }
1579
+ return new Response(JSON.stringify({ type: "error", error: { type: "rate_limit_error", message: `${res.status} ${STATUS_TEXT[res.status] ?? res.statusText} — ${BUSY_HINT}`.trim() } }), {
1580
+ status: res.status,
1581
+ statusText: res.statusText,
1582
+ headers: h,
1583
+ })
1584
+ }
1585
+
1519
1586
  function model(m, url) {
1520
1587
  const e = entry(m)
1521
1588
  return {
@@ -1979,6 +2046,12 @@ export async function ZCodeAuthPlugin({ client }) {
1979
2046
  },
1980
2047
  auth: {
1981
2048
  provider: PROVIDER,
2049
+ // a plan serves one account a few requests at a time: magpie's own
2050
+ // field, so its queue spaces what the agents ask for before the vendor
2051
+ // sees it. This is a default, not a cap the plugin enforces — a plan's
2052
+ // own cap follows its tier (Max > Pro > Lite) and the time of day, and
2053
+ // a user who knows theirs can raise this on the account
2054
+ maxConcurrency: DEFAULT_CONCURRENCY,
1982
2055
  async loader(getAuth, provider) {
1983
2056
  const s0 = stateOf(await getAuth())
1984
2057
  if (!s0) return {}
@@ -2076,7 +2149,26 @@ export async function ZCodeAuthPlugin({ client }) {
2076
2149
  h.set("x-api-key", key)
2077
2150
  h.set("Authorization", "Bearer " + key)
2078
2151
  }
2079
- let res = await fetch(url, { ...opts, headers: h })
2152
+ // a refusal that is the account's or the model's own in-flight
2153
+ // cap is asked again a moment later (see the plan's concurrency):
2154
+ // magpie sends every agent's and every session's requests of this
2155
+ // computer through this one process, and its queue spaces them by
2156
+ // the number declared above
2157
+ const ask = () => fetch(url, { ...opts, headers: h })
2158
+ let res = await ask()
2159
+ for (let i = 0; res.status === 429; i++) {
2160
+ const text = await res.text()
2161
+ const cap = busy(429, text)
2162
+ if (!cap || i >= BUSY_WAITS.length) {
2163
+ res = cap
2164
+ ? busyAnswer(res, text)
2165
+ : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
2166
+ break
2167
+ }
2168
+ const w = BUSY_WAITS[i]
2169
+ await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
2170
+ res = await ask()
2171
+ }
2080
2172
  // the Start Plan turning the request away says what to do about
2081
2173
  // it: the account blocked, or the network
2082
2174
  if (start && res.status >= 400) {
@@ -2229,4 +2321,4 @@ export async function ZCodeAuthPlugin({ client }) {
2229
2321
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
2230
2322
  // out of reach, undefined forgets it
2231
2323
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
2232
- export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf }
2324
+ export const _internal = { config, entry, limitWindows, termOf, startUsage, routes, blocked, plansOf, giftOf, dualUsage, claimHint, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, located, dress, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.31",
3
+ "version": "0.1.32",
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",
5
5
  "type": "module",
6
6
  "main": "./index.mjs",
@@ -12,5 +12,8 @@
12
12
  "type": "git",
13
13
  "url": "git+https://github.com/magpie-community/plugins.git",
14
14
  "directory": "packages/zcode"
15
+ },
16
+ "magpie": {
17
+ "maxConcurrency": 3
15
18
  }
16
19
  }