@magpie-community/opencode-zcode-auth 0.1.55 → 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
@@ -140,7 +140,7 @@ becomes a 429 and keeps the entry off for a minute. Any other gift
140
140
  answer (its 405, its 401, its 5xx) goes on as it came: the user picked
141
141
  the gift, so the coding plan is not spent behind their back. Every other
142
142
  429 counts as spent — Z.ai's 1302/1303 rate limits among them — while the
143
- 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
144
144
  again instead (see [A few at once](#a-few-at-once)). A stream's body is
145
145
  never read or buffered on the way.
146
146
 
@@ -195,43 +195,61 @@ a spent one answers 429 with freeFirst on, as it does without it.
195
195
  ## A few at once
196
196
 
197
197
  A plan serves one account a few requests at a time; past that, ZCode
198
- answers 429 with code 3008 "user concurrency limit exceeded", or 3009
199
- "model concurrency limit exceeded". magpie funnels every agent's and every
200
- session's requests of one computer through this one plugin process, so
201
- magpie's own queue spaces an account's requests by the number this plugin
202
- declares — `maxConcurrency` on the auth hook, and `magpie.maxConcurrency`
203
- in its `package.json`, both three. A request the vendor refuses anyway
204
- waits a moment (a quarter of a second, then longer — about ten seconds of
205
- waits in all) and asks again, the same request byte for byte. A cap that
206
- 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
207
207
  mean, so the agent reads why. magpie still reads it as a rate limit: the
208
208
  account rests a minute and the request goes to the next member of its
209
- routing group, as it did before.
209
+ routing group.
210
210
 
211
- Three is a default, not a cap the plugin enforces. A plan's real cap
212
- follows its tier — Z.ai serves a Max plan more at once than a Pro, and a
213
- 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
214
214
  ([Z.ai's usage policy](https://docs.z.ai/devpack/usage-policy)), so a
215
215
  number written into the plugin would hold a Max account to a Lite one's
216
216
  with no way to raise it. A user who knows their plan's cap sets it on the
217
217
  account or the provider in magpie, and magpie's queue follows that.
218
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
+
219
230
  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.
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.
235
253
 
236
254
  ## Two accounts at once
237
255
 
package/index.mjs CHANGED
@@ -1953,20 +1953,23 @@ function kept(res, text) {
1953
1953
 
1954
1954
  // ---- the plan's concurrency ------------------------------------------------------
1955
1955
  // ZCode serves one account a few requests at a time. Past that it answers 429
1956
- // with code 3008, "user concurrency limit exceeded", or 3009, "model
1957
- // concurrency limit exceeded": the request's turn has not come — not a plan
1958
- // spent (1113/1005) and not a rate limit (1302/1303). magpie sends every
1959
- // agent's and every session's requests of this computer through this one
1960
- // process, and its own queue spaces an account's requests by the number
1961
- // declared below (DEFAULT_CONCURRENCY, on the auth hook and in package.json);
1962
- // a request the vendor refuses anyway waits a moment and asks again, the same
1963
- // bytes. A refusal is immediate while a turn's answer is not, so a redundant
1964
- // 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).
1965
1966
  //
1966
- // The plugin keeps no gate of its own: a plan's cap depends on its tier (Z.ai
1967
- // serves Max more at once than Pro, and Lite fewer) and is higher off-peak
1968
- // (https://docs.z.ai/devpack/usage-policy), so a number written here would
1969
- // 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.
1970
1973
  const DEFAULT_CONCURRENCY = 3
1971
1974
  // DEFAULT_ACCOUNTS is how many of a user's ZCode accounts magpie sends
1972
1975
  // requests to at the same time (maxAccounts, on the auth hook and in
@@ -1975,30 +1978,163 @@ const DEFAULT_CONCURRENCY = 3
1975
1978
  // once from one address got the address refused with a 405, two didn't. A
1976
1979
  // user sets their own on the provider (Accounts at once), 0 for no limit.
1977
1980
  const DEFAULT_ACCOUNTS = 2
1978
- const BUSY_CODES = new Set(["3008", "3009"])
1979
- // BUSY_WAITS are the waits between asks, longest last: about ten seconds of
1980
- // them. Past that the account is saturated rather than busy, and magpie's
1981
- // routing takes the request (or rests the account, as its 429 says).
1982
- 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.
1983
1991
  const BUSY_HINT =
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"
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
+ }
1985
2115
 
1986
2116
  // busyHold is the firewall's countdown. Two days of logs (11-05 23:06–23:15
1987
2117
  // 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).
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).
2002
2138
  const BUSY_N = 5
2003
2139
  const BUSY_WINDOW = 60_000
2004
2140
  const BUSY_HOLD = 3 * 60_000
@@ -2007,10 +2143,10 @@ const busyHold = { hits: [], until: 0, now: () => Date.now() }
2007
2143
  // length and its expiry all read through it.
2008
2144
  const busyHeld = () => busyHold.now() < busyHold.until
2009
2145
 
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.
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.
2014
2150
  function busyCap() {
2015
2151
  if (busyHeld()) return
2016
2152
  const now = busyHold.now()
@@ -2026,14 +2162,14 @@ function busyHeldAnswer() {
2026
2162
  const wait = Math.max(1, Math.ceil((busyHold.until - busyHold.now()) / 1000))
2027
2163
  const error = {
2028
2164
  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`,
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`,
2030
2166
  }
2031
2167
  return new Response(JSON.stringify({ type: "error", error }), {
2032
2168
  status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": String(wait) },
2033
2169
  })
2034
2170
  }
2035
2171
 
2036
- // 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
2037
2173
  // own words when the envelope carries no code.
2038
2174
  function busy(status, text) {
2039
2175
  if (status !== 429) return false
@@ -2074,19 +2210,20 @@ function busyAnswer(res, text) {
2074
2210
  }
2075
2211
 
2076
2212
  // askBusy asks once and, when the answer is the vendor's in-flight cap
2077
- // (3008/3009, or its own words), asks again through BUSY_WAITS's waits, a
2078
- // quarter of a second and longer — about ten seconds of them. Past that the
2079
- // account is saturated rather than busy, and the cap goes back as
2080
- // busyAnswer's 429. The plan path's patience, shared with free first's
2081
- // 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.
2082
2219
  async function askBusy(u, o, hs, onCap) {
2083
2220
  let res = await fetch(u, { ...o, headers: hs })
2084
- let counted = false
2221
+ let caps = 0
2085
2222
  for (let i = 0; res.status === 429; i++) {
2086
2223
  const text = await res.text()
2087
2224
  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?.() }
2225
+ // one request's refusals are one saturation signal, not one per ask
2226
+ if (cap && ++caps === 2) onCap?.()
2090
2227
  // the hold armed: a request already in flight stops asking too. The
2091
2228
  // second check catches the asks that capped before the hold armed and
2092
2229
  // woke from their wait after it. Keying on onCap keeps the coding plan
@@ -2096,8 +2233,7 @@ async function askBusy(u, o, hs, onCap) {
2096
2233
  res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
2097
2234
  break
2098
2235
  }
2099
- const w = BUSY_WAITS[i]
2100
- await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
2236
+ await sleep(BUSY_WAITS[i])
2101
2237
  if (onCap && busyHeld()) { res = busyHeldAnswer(); break }
2102
2238
  res = await fetch(u, { ...o, headers: hs })
2103
2239
  }
@@ -2657,9 +2793,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2657
2793
  provider: PROVIDER,
2658
2794
  // a plan serves one account a few requests at a time: magpie's own
2659
2795
  // field, so its queue spaces what the agents ask for before the vendor
2660
- // sees it. This is a default, not a cap the plugin enforces — a plan's
2661
- // own cap follows its tier (Max > Pro > Lite) and the time of day, and
2662
- // 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)
2663
2800
  maxConcurrency: DEFAULT_CONCURRENCY,
2664
2801
  // how many accounts take requests at once, the others in reserve
2665
2802
  // (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all
@@ -2689,9 +2826,24 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2689
2826
  baseURL: s0.base + "/v1",
2690
2827
  apiKey: s0.key || "zcode", // the fetch below puts the real one on
2691
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) {
2692
2841
  const auth = await getAuth()
2693
2842
  const s = await located(stateOf(auth))
2694
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))
2695
2847
  let url = input instanceof Request ? input.url : String(input)
2696
2848
  const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
2697
2849
  const { start: alone, gift: known } = await plansOf(s)
@@ -2734,7 +2886,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2734
2886
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
2735
2887
  m = raw
2736
2888
  forcedGift = true
2737
- } 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)) {
2738
2890
  // free first: the plain model spends the account's own live
2739
2891
  // gift before it spends the coding plan, under the name the
2740
2892
  // gift lists. The gift is the route's cache alone (a failed
@@ -2746,7 +2898,9 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2746
2898
  // a block page) keeps the plain model off the gift: the
2747
2899
  // coding plan is never held, and free first must not move
2748
2900
  // the request onto a route the hold answers 429 without
2749
- // 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.
2750
2904
  const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase())
2751
2905
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
2752
2906
  m = raw
@@ -2781,6 +2935,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2781
2935
  // agent sent it, the plan's headers, the plan's own patience
2782
2936
  // (askBusy).
2783
2937
  const replayOnPlan = async () => {
2938
+ // the gift is done with: its slot goes to the next request
2939
+ own.slot?.release()
2784
2940
  let u = askedUrl
2785
2941
  for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
2786
2942
  if (u.startsWith(b)) {
@@ -2809,6 +2965,16 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2809
2965
  // edge firewall could block the IP: a held request is answered
2810
2966
  // here, with a 429 magpie still reads as a rate limit
2811
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
+ }
2812
2978
  if (start) {
2813
2979
  if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
2814
2980
  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 = {}) {
2938
3104
  // A spent bucket's 200 says 429 (spentSaid), as a trial
2939
3105
  // entry's does, so magpie rests the model, not the account
2940
3106
  return done(kept(await spentSaid(res)))
2941
- },
2942
3107
  }
2943
3108
  },
2944
3109
  // the plan's allowance, as magpie's built-in showed it. Each read
@@ -3058,4 +3223,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3058
3223
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
3059
3224
  // out of reach, undefined forgets it
3060
3225
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
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 }
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.55",
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",