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

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
@@ -144,6 +144,14 @@ 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
 
147
+ Since 0.1.58 the trial entries are marked free in the model list: they
148
+ spend the gift, which costs nothing. magpie then reads a coding plan
149
+ model's weekly or monthly limit (code 1310) as that model's, not the
150
+ account's, so the account's `-Trial` entries are still asked while the
151
+ plan's model rests (plugins#438). In magpie's pickers the trial entries
152
+ carry the Free mark, and a routing group that prefers free models picks
153
+ them first.
154
+
147
155
  **Free first.** Picking `-Trial` by hand keeps the choice the user's,
148
156
  but an agent that always asks the plain model never sees the gift.
149
157
  `freeFirst`, on by default since 0.1.42, turns the preference around:
@@ -251,6 +259,20 @@ already refused needs; when both are on, the 405 hold's answer wins.
251
259
  refuses past three in flight: 0.1.55 drew 24 refusals in it, this version
252
260
  none.
253
261
 
262
+ Some accounts are served fewer than three at a time (plugins#438: one
263
+ account, one agent, refused at two in flight). Since 0.1.58 a request
264
+ refused again at its 1s re-ask while others of the same account were in
265
+ flight beside it narrows that account's gate to one fewer than were in
266
+ flight, at least one, for five minutes, after which it is back to three.
267
+ Such a refusal is this computer asking too much at once, which the
268
+ narrowed gate now stops, so it counts toward no hold; up to 0.1.57 those
269
+ refusals armed the hold at about five requests a minute, and armed it
270
+ again within a minute of its end. A request refused again alone, nothing
271
+ else of its account in flight, still counts as before: someone else holds
272
+ the slots. An account whose slots are taken elsewhere is narrowed to one
273
+ within a few refusals and then refused alone, so the firewall hold still
274
+ comes before the 405.
275
+
254
276
  ## Two accounts at once
255
277
 
256
278
  Three ZCode accounts used at once from one address can get the address
package/index.mjs CHANGED
@@ -2004,12 +2004,46 @@ const BUSY_HINT =
2004
2004
  // the queue. A wait that runs out is answered startQueueAnswer's 429,
2005
2005
  // nothing sent. The gate lives in this process's memory alone, by account
2006
2006
  // (gateKey).
2007
- const startGate = { inflight: 3, wait: 120_000, lanes: new Map() }
2007
+ //
2008
+ // An account ZCode serves fewer than that (plugins#438: one account, one
2009
+ // agent, never more than two in flight, and refused at two) is narrowed:
2010
+ // a request refused again at its 1s re-ask while others of this computer
2011
+ // were in flight beside it (busyCap) tells the cap is below the gate, and
2012
+ // the account's gate goes down to one fewer than were in flight, at least
2013
+ // one, for NARROW_FOR. Such a cap is this computer asking too much at once,
2014
+ // which the narrowed gate now stops, so it counts toward no firewall hold.
2015
+ // narrow is kept apart from lanes, which go when idle; now is its clock,
2016
+ // injectable for tests.
2017
+ const NARROW_FOR = 5 * 60_000
2018
+ const startGate = { inflight: 3, wait: 120_000, lanes: new Map(), narrow: new Map(), now: () => Date.now() }
2019
+
2020
+ // limitOf is how many of the account's Start Plan requests go at once: the
2021
+ // gate's number, or less while the account is narrowed.
2022
+ function limitOf(key) {
2023
+ const n = startGate.narrow.get(key)
2024
+ if (!n) return startGate.inflight
2025
+ if (startGate.now() >= n.until) {
2026
+ startGate.narrow.delete(key)
2027
+ return startGate.inflight
2028
+ }
2029
+ return Math.min(startGate.inflight, n.limit)
2030
+ }
2031
+
2032
+ // narrowed lowers the account's gate below the requests that were in flight
2033
+ // when one was refused again (busy, its own included), and says whether it
2034
+ // did: a lone request refused again is not this computer's doing.
2035
+ function narrowed(key) {
2036
+ const busy = startGate.lanes.get(key)?.busy ?? 0
2037
+ if (busy < 2) return false
2038
+ const limit = Math.max(1, Math.min(limitOf(key), busy - 1))
2039
+ startGate.narrow.set(key, { limit, until: startGate.now() + NARROW_FOR })
2040
+ return true
2041
+ }
2008
2042
 
2009
2043
  // startFull says the account's Start Plan slots are all taken, or others wait.
2010
2044
  const startFull = (key) => {
2011
2045
  const l = startGate.lanes.get(key)
2012
- return !!l && (l.busy >= startGate.inflight || l.queue.length > 0)
2046
+ return !!l && (l.busy >= limitOf(key) || l.queue.length > 0)
2013
2047
  }
2014
2048
 
2015
2049
  // startSlot waits for one of the account's Start Plan slots: { release },
@@ -2019,7 +2053,7 @@ function startSlot(key, signal) {
2019
2053
  let l = lanes.get(key)
2020
2054
  if (!l) lanes.set(key, (l = { busy: 0, queue: [] }))
2021
2055
  const next = () => {
2022
- while (l.busy < startGate.inflight && l.queue.length) l.queue.shift()()
2056
+ while (l.busy < limitOf(key) && l.queue.length) l.queue.shift()()
2023
2057
  if (!l.busy && !l.queue.length && lanes.get(key) === l) lanes.delete(key)
2024
2058
  }
2025
2059
  const take = () => {
@@ -2035,7 +2069,7 @@ function startSlot(key, signal) {
2035
2069
  }
2036
2070
  }
2037
2071
  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())
2072
+ if (l.busy < limitOf(key) && !l.queue.length) return Promise.resolve(take())
2039
2073
  return new Promise((resolve, reject) => {
2040
2074
  const leave = () => {
2041
2075
  clearTimeout(timer)
@@ -2103,10 +2137,11 @@ function released(res, slot, signal) {
2103
2137
  // startQueueAnswer is a request that waited its whole turn behind the
2104
2138
  // account's others and was never sent: a 429 magpie reads as a rate limit,
2105
2139
  // so it tries the next account, and a short Retry-After.
2106
- function startQueueAnswer() {
2140
+ function startQueueAnswer(key) {
2141
+ const n = limitOf(key)
2107
2142
  const error = {
2108
2143
  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`,
2144
+ message: `ZCode's free Start Plan serves this account ${n} request${n === 1 ? "" : "s"} 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
2145
  }
2111
2146
  return new Response(JSON.stringify({ type: "error", error }), {
2112
2147
  status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" },
@@ -2124,7 +2159,14 @@ function startQueueAnswer() {
2124
2159
  // busy or another client on the account; a request refused on its first ask
2125
2160
  // and again a second later (busyCap) is that, sustained, and BUSY_N of them
2126
2161
  // 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:
2162
+ // account) off BUSY_HOLD. A sustained cap of a request with others of the
2163
+ // same account in flight beside it counts for nothing either: it narrows the
2164
+ // account's gate (startGate), which then sends no more than ZCode serves
2165
+ // (plugins#438: an account served one at a time, two in flight from one
2166
+ // agent, held again and again at ~5 requests/min). #801's caps came with up
2167
+ // to ~10 in flight, which the gate now never sends, and an account whose
2168
+ // slots are taken elsewhere is narrowed to one within a few caps and then
2169
+ // refused alone, which counts as before. A cap the 1s re-ask got past counts for nothing:
2128
2170
  // on 0.1.55 every capped request counted, a lone late slot as much as a
2129
2171
  // saturated address, and busy afternoons held users for nothing. Replay of
2130
2172
  // both days: N=5, H=3min froze 2–7 minutes before the first 405 and spared
@@ -2147,7 +2189,8 @@ const busyHeld = () => busyHold.now() < busyHold.until
2147
2189
  // Only a run arms a hold; the window is cleared on arming, and a cap that
2148
2190
  // lands while the hold is on counts toward nothing — the hold's own 429s and
2149
2191
  // the first caps after it cannot keep re-arming it.
2150
- function busyCap() {
2192
+ function busyCap(key) {
2193
+ if (key != null && narrowed(key)) return
2151
2194
  if (busyHeld()) return
2152
2195
  const now = busyHold.now()
2153
2196
  busyHold.hits.push(now)
@@ -2158,6 +2201,15 @@ function busyCap() {
2158
2201
  }
2159
2202
  }
2160
2203
 
2204
+ // BUSY_HOLD_MARK marks an answer the hold made up: a request the gate or the
2205
+ // hold stopped locally never reached ZCode, and it says nothing about the
2206
+ // gift's quota. The gift paths (a -Trial pick, free first) read the mark
2207
+ // before they judge the answer spent, so a hold's 429 passes through as the
2208
+ // rate limit it is and arms no minute's rest (11-08: the hold's answer
2209
+ // through a -Trial entry read as "over its quota" with half the free quota
2210
+ // left).
2211
+ const BUSY_HOLD_MARK = "x-magpie-busy-hold"
2212
+
2161
2213
  function busyHeldAnswer() {
2162
2214
  const wait = Math.max(1, Math.ceil((busyHold.until - busyHold.now()) / 1000))
2163
2215
  const error = {
@@ -2165,7 +2217,8 @@ function busyHeldAnswer() {
2165
2217
  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`,
2166
2218
  }
2167
2219
  return new Response(JSON.stringify({ type: "error", error }), {
2168
- status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": String(wait) },
2220
+ status: 429, statusText: STATUS_TEXT[429],
2221
+ headers: { "content-type": "application/json", "retry-after": String(wait), [BUSY_HOLD_MARK]: "1" },
2169
2222
  })
2170
2223
  }
2171
2224
 
@@ -2779,7 +2832,11 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2779
2832
  }
2780
2833
  const id = giftID(raw)
2781
2834
  if (out[id]) continue
2782
- out[id] = model({ ...about(raw), id }, url)
2835
+ // a trial entry is the gift's, which costs nothing: marked free,
2836
+ // so magpie reads a GLM Coding Plan model's weekly or monthly
2837
+ // limit (1310) as that model's, and the account's trial entries,
2838
+ // spent from the gift's own buckets, are still asked (plugins#438)
2839
+ out[id] = { ...model({ ...about(raw), id }, url), free: true }
2783
2840
  }
2784
2841
  // a fallback tells magpie to keep the list it was told last, which
2785
2842
  // predates the gift read just made: an account whose gift lists
@@ -2970,7 +3027,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2970
3027
  if (start) {
2971
3028
  own.slot = await startSlot(gateKey, opts.signal)
2972
3029
  own.signal = opts.signal
2973
- if (!own.slot) return kept(startQueueAnswer())
3030
+ if (!own.slot) return kept(startQueueAnswer(gateKey))
2974
3031
  // a hold may have armed while it waited
2975
3032
  if (edgeHeld()) return kept(edgeHeldAnswer())
2976
3033
  if (busyHeld()) return kept(busyHeldAnswer())
@@ -3019,7 +3076,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3019
3076
  // Only Start Plan caps count toward the firewall hold: the
3020
3077
  // coding plan is served by another host and was never refused
3021
3078
  // with the IP's 405.
3022
- res = await askBusy(url, opts, h, start ? busyCap : undefined)
3079
+ res = await askBusy(url, opts, h, start ? () => busyCap(gateKey) : undefined)
3023
3080
  } catch (e) {
3024
3081
  // free first moved the request onto the gift, so a gift that
3025
3082
  // cannot be asked at all — the network, the host — is answered
@@ -3067,7 +3124,11 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3067
3124
  const json = (res.headers.get("content-type") ?? "").includes("application/json")
3068
3125
  if (res.status >= 400 || json) {
3069
3126
  const text = await res.text()
3070
- const spent = spentUp(text, res.status)
3127
+ // the hold's own answer (BUSY_HOLD_MARK) is a rate limit the
3128
+ // gift never said: it passes through as it came and arms
3129
+ // no rest
3130
+ const held = res.headers.get(BUSY_HOLD_MARK) === "1"
3131
+ const spent = !held && spentUp(text, res.status)
3071
3132
  if (!spent && res.status < 400) return done(kept(res, text))
3072
3133
  if (spent) rest(blocked, s.key + "\0" + s.jwt + "\0" + modelOf(orig).toLowerCase())
3073
3134
  return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text))
@@ -3087,7 +3148,9 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3087
3148
  if (res.status >= 400 || json) {
3088
3149
  const text = await res.text()
3089
3150
  const cap = busy(res.status, text)
3090
- const spent = !cap && spentUp(text, res.status)
3151
+ // the hold's own answer is no spent answer either (see the
3152
+ // -Trial path above)
3153
+ const spent = !cap && res.headers.get(BUSY_HOLD_MARK) !== "1" && spentUp(text, res.status)
3091
3154
  if (spent) {
3092
3155
  restModel(true)
3093
3156
  return done(kept(await spentSaid(await replayOnPlan())))
@@ -3223,4 +3286,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3223
3286
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
3224
3287
  // out of reach, undefined forgets it
3225
3288
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
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 }
3289
+ export const _internal = { edge, EDGE_HOLD, busyHold, startGate, NARROW_FOR, limitOf, 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,7 +85,6 @@ 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
90
89
  // neither can one whose own validate() accepts an empty answer (the
91
90
  // browser sign-in's optional API key)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.56",
3
+ "version": "0.1.58",
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",