@magpie-community/opencode-zcode-auth 0.1.55 → 0.1.57
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 +47 -29
- package/index.mjs +240 -59
- package/opencode2.mjs +4 -2
- package/package.json +1 -1
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",
|
|
199
|
-
"model concurrency limit exceeded". magpie funnels every agent's
|
|
200
|
-
session's requests of one computer through this one plugin
|
|
201
|
-
magpie's own queue spaces an account's requests by the number
|
|
202
|
-
declares — `maxConcurrency` on the auth hook, and
|
|
203
|
-
in its `package.json`, both three. A request the
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
outlasts
|
|
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
|
|
209
|
+
routing group.
|
|
210
210
|
|
|
211
|
-
|
|
212
|
-
follows its tier — Z.ai serves a Max plan more at once
|
|
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
|
|
221
|
-
caps in a run, then 3–7 minutes
|
|
222
|
-
whole IP for 1–2 hours.
|
|
223
|
-
the
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
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",
|
|
1957
|
-
// concurrency limit exceeded": the request's turn has not come — not
|
|
1958
|
-
// spent (1113/1005) and not a rate limit (1302/1303).
|
|
1959
|
-
//
|
|
1960
|
-
//
|
|
1961
|
-
//
|
|
1962
|
-
//
|
|
1963
|
-
//
|
|
1964
|
-
//
|
|
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
|
|
1967
|
-
// serves Max more at once than Pro, and Lite fewer) and is higher
|
|
1968
|
-
// (https://docs.z.ai/devpack/usage-policy), so a number written here
|
|
1969
|
-
// hold a Max account to a Lite one's
|
|
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
|
|
1980
|
-
//
|
|
1981
|
-
//
|
|
1982
|
-
|
|
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
|
|
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
|
|
1989
|
-
//
|
|
1990
|
-
//
|
|
1991
|
-
// magpie nor the agent
|
|
1992
|
-
//
|
|
1993
|
-
//
|
|
1994
|
-
//
|
|
1995
|
-
//
|
|
1996
|
-
//
|
|
1997
|
-
//
|
|
1998
|
-
//
|
|
1999
|
-
//
|
|
2000
|
-
//
|
|
2001
|
-
//
|
|
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.
|
|
2011
|
-
// arms a hold; the window is cleared on arming, and a cap that
|
|
2012
|
-
// the hold is on counts toward nothing — the hold's own 429s and
|
|
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()
|
|
@@ -2022,18 +2158,28 @@ function busyCap() {
|
|
|
2022
2158
|
}
|
|
2023
2159
|
}
|
|
2024
2160
|
|
|
2161
|
+
// BUSY_HOLD_MARK marks an answer the hold made up: a request the gate or the
|
|
2162
|
+
// hold stopped locally never reached ZCode, and it says nothing about the
|
|
2163
|
+
// gift's quota. The gift paths (a -Trial pick, free first) read the mark
|
|
2164
|
+
// before they judge the answer spent, so a hold's 429 passes through as the
|
|
2165
|
+
// rate limit it is and arms no minute's rest (11-08: the hold's answer
|
|
2166
|
+
// through a -Trial entry read as "over its quota" with half the free quota
|
|
2167
|
+
// left).
|
|
2168
|
+
const BUSY_HOLD_MARK = "x-magpie-busy-hold"
|
|
2169
|
+
|
|
2025
2170
|
function busyHeldAnswer() {
|
|
2026
2171
|
const wait = Math.max(1, Math.ceil((busyHold.until - busyHold.now()) / 1000))
|
|
2027
2172
|
const error = {
|
|
2028
2173
|
type: "rate_limit_error",
|
|
2029
|
-
message: `ZCode
|
|
2174
|
+
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
2175
|
}
|
|
2031
2176
|
return new Response(JSON.stringify({ type: "error", error }), {
|
|
2032
|
-
status: 429, statusText: STATUS_TEXT[429],
|
|
2177
|
+
status: 429, statusText: STATUS_TEXT[429],
|
|
2178
|
+
headers: { "content-type": "application/json", "retry-after": String(wait), [BUSY_HOLD_MARK]: "1" },
|
|
2033
2179
|
})
|
|
2034
2180
|
}
|
|
2035
2181
|
|
|
2036
|
-
// busy says a 429 is that in-flight cap: its own code (3008, 3009), or its
|
|
2182
|
+
// busy says a 429 is that in-flight cap: its own code (3008, 3009, 3010), or its
|
|
2037
2183
|
// own words when the envelope carries no code.
|
|
2038
2184
|
function busy(status, text) {
|
|
2039
2185
|
if (status !== 429) return false
|
|
@@ -2074,19 +2220,20 @@ function busyAnswer(res, text) {
|
|
|
2074
2220
|
}
|
|
2075
2221
|
|
|
2076
2222
|
// askBusy asks once and, when the answer is the vendor's in-flight cap
|
|
2077
|
-
// (3008/3009, or its own words), asks again
|
|
2078
|
-
//
|
|
2079
|
-
//
|
|
2080
|
-
//
|
|
2081
|
-
//
|
|
2223
|
+
// (3008/3009/3010, or its own words), asks again after BUSY_WAITS's waits,
|
|
2224
|
+
// 1s and then 2s, as ZCode's own client does. Past them the cap goes back as
|
|
2225
|
+
// busyAnswer's 429. A request refused again at its 1s re-ask is a sustained
|
|
2226
|
+
// cap, told to onCap once (the firewall hold's count); one the re-ask got
|
|
2227
|
+
// past is not. The plan path's patience, shared with free first's replay,
|
|
2228
|
+
// whose plan has a cap of its own.
|
|
2082
2229
|
async function askBusy(u, o, hs, onCap) {
|
|
2083
2230
|
let res = await fetch(u, { ...o, headers: hs })
|
|
2084
|
-
let
|
|
2231
|
+
let caps = 0
|
|
2085
2232
|
for (let i = 0; res.status === 429; i++) {
|
|
2086
2233
|
const text = await res.text()
|
|
2087
2234
|
const cap = busy(429, text)
|
|
2088
|
-
// one request's
|
|
2089
|
-
if (cap &&
|
|
2235
|
+
// one request's refusals are one saturation signal, not one per ask
|
|
2236
|
+
if (cap && ++caps === 2) onCap?.()
|
|
2090
2237
|
// the hold armed: a request already in flight stops asking too. The
|
|
2091
2238
|
// second check catches the asks that capped before the hold armed and
|
|
2092
2239
|
// woke from their wait after it. Keying on onCap keeps the coding plan
|
|
@@ -2096,8 +2243,7 @@ async function askBusy(u, o, hs, onCap) {
|
|
|
2096
2243
|
res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
|
|
2097
2244
|
break
|
|
2098
2245
|
}
|
|
2099
|
-
|
|
2100
|
-
await sleep(Math.round(w * (0.75 + Math.random() * 0.5)))
|
|
2246
|
+
await sleep(BUSY_WAITS[i])
|
|
2101
2247
|
if (onCap && busyHeld()) { res = busyHeldAnswer(); break }
|
|
2102
2248
|
res = await fetch(u, { ...o, headers: hs })
|
|
2103
2249
|
}
|
|
@@ -2657,9 +2803,10 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2657
2803
|
provider: PROVIDER,
|
|
2658
2804
|
// a plan serves one account a few requests at a time: magpie's own
|
|
2659
2805
|
// field, so its queue spaces what the agents ask for before the vendor
|
|
2660
|
-
// sees it.
|
|
2661
|
-
//
|
|
2662
|
-
// a user who knows theirs can raise this on the account
|
|
2806
|
+
// sees it. For the coding plan this is a default, not a cap the plugin
|
|
2807
|
+
// enforces — its cap follows its tier (Max > Pro > Lite) and the time
|
|
2808
|
+
// of day, and a user who knows theirs can raise this on the account.
|
|
2809
|
+
// The Start Plan has the plugin's own gate below it (startGate)
|
|
2663
2810
|
maxConcurrency: DEFAULT_CONCURRENCY,
|
|
2664
2811
|
// how many accounts take requests at once, the others in reserve
|
|
2665
2812
|
// (DEFAULT_ACCOUNTS); a magpie that doesn't read it uses them all
|
|
@@ -2689,9 +2836,24 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2689
2836
|
baseURL: s0.base + "/v1",
|
|
2690
2837
|
apiKey: s0.key || "zcode", // the fetch below puts the real one on
|
|
2691
2838
|
async fetch(input, init) {
|
|
2839
|
+
// a Start Plan request holds one of its account's slots
|
|
2840
|
+
// (startSlot) until its answer has been read to the end
|
|
2841
|
+
const own = {}
|
|
2842
|
+
try {
|
|
2843
|
+
return released(await serve(input, init, own), own.slot, own.signal)
|
|
2844
|
+
} catch (e) {
|
|
2845
|
+
own.slot?.release()
|
|
2846
|
+
throw e
|
|
2847
|
+
}
|
|
2848
|
+
},
|
|
2849
|
+
}
|
|
2850
|
+
async function serve(input, init, own) {
|
|
2692
2851
|
const auth = await getAuth()
|
|
2693
2852
|
const s = await located(stateOf(auth))
|
|
2694
2853
|
if (!s) throw new Error("not signed in to ZCode")
|
|
2854
|
+
// the account a Start Plan slot belongs to: its user id, which a
|
|
2855
|
+
// renewed session keeps, before the key or session itself
|
|
2856
|
+
const gateKey = String(auth?.uid || auth?.accountId || holdKey(s))
|
|
2695
2857
|
let url = input instanceof Request ? input.url : String(input)
|
|
2696
2858
|
const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
|
|
2697
2859
|
const { start: alone, gift: known } = await plansOf(s)
|
|
@@ -2734,7 +2896,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2734
2896
|
orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
|
|
2735
2897
|
m = raw
|
|
2736
2898
|
forcedGift = true
|
|
2737
|
-
} else if (!alone && !edgeHeld() && !busyHeld() && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
|
|
2899
|
+
} else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
|
|
2738
2900
|
// free first: the plain model spends the account's own live
|
|
2739
2901
|
// gift before it spends the coding plan, under the name the
|
|
2740
2902
|
// gift lists. The gift is the route's cache alone (a failed
|
|
@@ -2746,7 +2908,9 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2746
2908
|
// a block page) keeps the plain model off the gift: the
|
|
2747
2909
|
// coding plan is never held, and free first must not move
|
|
2748
2910
|
// the request onto a route the hold answers 429 without
|
|
2749
|
-
// asking.
|
|
2911
|
+
// asking. Nor onto a gift whose slots are all taken
|
|
2912
|
+
// (startFull): the plan serves it now, the gift only after
|
|
2913
|
+
// the others.
|
|
2750
2914
|
const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase())
|
|
2751
2915
|
orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
|
|
2752
2916
|
m = raw
|
|
@@ -2781,6 +2945,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2781
2945
|
// agent sent it, the plan's headers, the plan's own patience
|
|
2782
2946
|
// (askBusy).
|
|
2783
2947
|
const replayOnPlan = async () => {
|
|
2948
|
+
// the gift is done with: its slot goes to the next request
|
|
2949
|
+
own.slot?.release()
|
|
2784
2950
|
let u = askedUrl
|
|
2785
2951
|
for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
|
|
2786
2952
|
if (u.startsWith(b)) {
|
|
@@ -2809,6 +2975,16 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2809
2975
|
// edge firewall could block the IP: a held request is answered
|
|
2810
2976
|
// here, with a 429 magpie still reads as a rate limit
|
|
2811
2977
|
if (start && busyHeld()) return kept(busyHeldAnswer())
|
|
2978
|
+
// the account's Start Plan slots (startGate): a request past them
|
|
2979
|
+
// waits here for one rather than being sent to be refused
|
|
2980
|
+
if (start) {
|
|
2981
|
+
own.slot = await startSlot(gateKey, opts.signal)
|
|
2982
|
+
own.signal = opts.signal
|
|
2983
|
+
if (!own.slot) return kept(startQueueAnswer())
|
|
2984
|
+
// a hold may have armed while it waited
|
|
2985
|
+
if (edgeHeld()) return kept(edgeHeldAnswer())
|
|
2986
|
+
if (busyHeld()) return kept(busyHeldAnswer())
|
|
2987
|
+
}
|
|
2812
2988
|
if (start) {
|
|
2813
2989
|
if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
|
|
2814
2990
|
if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
|
|
@@ -2901,7 +3077,11 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2901
3077
|
const json = (res.headers.get("content-type") ?? "").includes("application/json")
|
|
2902
3078
|
if (res.status >= 400 || json) {
|
|
2903
3079
|
const text = await res.text()
|
|
2904
|
-
|
|
3080
|
+
// the hold's own answer (BUSY_HOLD_MARK) is a rate limit the
|
|
3081
|
+
// gift never said: it passes through as it came and arms
|
|
3082
|
+
// no rest
|
|
3083
|
+
const held = res.headers.get(BUSY_HOLD_MARK) === "1"
|
|
3084
|
+
const spent = !held && spentUp(text, res.status)
|
|
2905
3085
|
if (!spent && res.status < 400) return done(kept(res, text))
|
|
2906
3086
|
if (spent) rest(blocked, s.key + "\0" + s.jwt + "\0" + modelOf(orig).toLowerCase())
|
|
2907
3087
|
return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text))
|
|
@@ -2921,7 +3101,9 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2921
3101
|
if (res.status >= 400 || json) {
|
|
2922
3102
|
const text = await res.text()
|
|
2923
3103
|
const cap = busy(res.status, text)
|
|
2924
|
-
|
|
3104
|
+
// the hold's own answer is no spent answer either (see the
|
|
3105
|
+
// -Trial path above)
|
|
3106
|
+
const spent = !cap && res.headers.get(BUSY_HOLD_MARK) !== "1" && spentUp(text, res.status)
|
|
2925
3107
|
if (spent) {
|
|
2926
3108
|
restModel(true)
|
|
2927
3109
|
return done(kept(await spentSaid(await replayOnPlan())))
|
|
@@ -2938,7 +3120,6 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2938
3120
|
// A spent bucket's 200 says 429 (spentSaid), as a trial
|
|
2939
3121
|
// entry's does, so magpie rests the model, not the account
|
|
2940
3122
|
return done(kept(await spentSaid(res)))
|
|
2941
|
-
},
|
|
2942
3123
|
}
|
|
2943
3124
|
},
|
|
2944
3125
|
// the plan's allowance, as magpie's built-in showed it. Each read
|
|
@@ -3058,4 +3239,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
3058
3239
|
// config sets what zcodeConfig has read, for tests: null is ZCode's config
|
|
3059
3240
|
// out of reach, undefined forgets it
|
|
3060
3241
|
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 }
|
|
3242
|
+
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
|
@@ -85,8 +85,10 @@ export function fieldsOf(prompts) {
|
|
|
85
85
|
if (p.placeholder) f.placeholder = String(p.placeholder)
|
|
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
|
-
// a prompt shown only when another answer says so can't be required
|
|
89
|
-
|
|
88
|
+
// a prompt shown only when another answer says so can't be required, and
|
|
89
|
+
// neither can one whose own validate() accepts an empty answer (the
|
|
90
|
+
// browser sign-in's optional API key)
|
|
91
|
+
if (!p.condition && p.required !== false) f.required = true
|
|
90
92
|
out.push(f)
|
|
91
93
|
}
|
|
92
94
|
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.
|
|
3
|
+
"version": "0.1.57",
|
|
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",
|