@magpie-community/opencode-zcode-auth 0.1.57 → 0.1.59

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 +24 -0
  2. package/index.mjs +132 -13
  3. package/package.json +1 -1
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:
@@ -157,6 +165,8 @@ keeps the plain models on the plan. The JSON below still works, and a
157
165
  `freeFirst: false` there keeps it off whatever the switch says. Turn it
158
166
  off for the whole plugin in magpie's Plugins › Options
159
167
 
168
+ Since 0.1.59 a reply the gift answered says its model as the picker lists it (`GLM-5.3-Flash-Trial`), whether free first or a `-Trial` pick sent the request, so the Usage page, the sessions and the request log show which route spent the turn; a reply the coding plan answered, a free-first replay among them, keeps the plan's name.
169
+
160
170
  ```json
161
171
  { "freeFirst": false }
162
172
  ```
@@ -251,6 +261,20 @@ already refused needs; when both are on, the 405 hold's answer wins.
251
261
  refuses past three in flight: 0.1.55 drew 24 refusals in it, this version
252
262
  none.
253
263
 
264
+ Some accounts are served fewer than three at a time (plugins#438: one
265
+ account, one agent, refused at two in flight). Since 0.1.58 a request
266
+ refused again at its 1s re-ask while others of the same account were in
267
+ flight beside it narrows that account's gate to one fewer than were in
268
+ flight, at least one, for five minutes, after which it is back to three.
269
+ Such a refusal is this computer asking too much at once, which the
270
+ narrowed gate now stops, so it counts toward no hold; up to 0.1.57 those
271
+ refusals armed the hold at about five requests a minute, and armed it
272
+ again within a minute of its end. A request refused again alone, nothing
273
+ else of its account in flight, still counts as before: someone else holds
274
+ the slots. An account whose slots are taken elsewhere is narrowed to one
275
+ within a few refusals and then refused alone, so the firewall hold still
276
+ comes before the 405.
277
+
254
278
  ## Two accounts at once
255
279
 
256
280
  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)
@@ -2532,6 +2575,69 @@ function searchNamed(res) {
2532
2575
  })
2533
2576
  }
2534
2577
 
2578
+ // trialNamed is a gift's answer with its model said as the picker lists it
2579
+ // (GLM-5.3-Flash-Trial): the gift answers under the plain name, as the coding
2580
+ // plan does, so the Usage page, the sessions and the request log named the
2581
+ // plan's model whichever route served it, and a user with free first on
2582
+ // could not tell whether the free quota was spent (WJaunita45604 on X). A
2583
+ // failed answer, or a body that is not JSON or an event stream, goes on as it
2584
+ // came.
2585
+ function trialNamed(res, name) {
2586
+ if (!res.body || res.status >= 400) return res
2587
+ const type = res.headers.get("content-type") ?? ""
2588
+ const set = (d) => {
2589
+ if (d && typeof d === "object") {
2590
+ if (typeof d.model === "string") d.model = name
2591
+ if (typeof d.message?.model === "string") d.message.model = name
2592
+ return true
2593
+ }
2594
+ return false
2595
+ }
2596
+ const line = (l) => {
2597
+ if (!l.startsWith("data:") || !l.includes('"model"')) return l
2598
+ try {
2599
+ const d = JSON.parse(l.slice(5))
2600
+ return set(d) ? "data: " + JSON.stringify(d) : l
2601
+ } catch {
2602
+ return l
2603
+ }
2604
+ }
2605
+ const h = new Headers(res.headers)
2606
+ if (type.includes("text/event-stream")) {
2607
+ const dec = new TextDecoder()
2608
+ const enc = new TextEncoder()
2609
+ let held = ""
2610
+ const body = res.body.pipeThrough(
2611
+ new TransformStream({
2612
+ transform(chunk, ctl) {
2613
+ held += dec.decode(chunk, { stream: true })
2614
+ const i = held.lastIndexOf("\n")
2615
+ if (i < 0) return
2616
+ ctl.enqueue(enc.encode(held.slice(0, i + 1).split("\n").map(line).join("\n")))
2617
+ held = held.slice(i + 1)
2618
+ },
2619
+ flush(ctl) {
2620
+ held += dec.decode()
2621
+ if (held) ctl.enqueue(enc.encode(line(held)))
2622
+ },
2623
+ }),
2624
+ )
2625
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: h })
2626
+ }
2627
+ if (!type.includes("json")) return res
2628
+ return res.text().then((text) => {
2629
+ let out = text
2630
+ if (text.includes('"model"')) {
2631
+ try {
2632
+ const v = JSON.parse(text)
2633
+ if (set(v)) out = JSON.stringify(v)
2634
+ } catch {}
2635
+ }
2636
+ h.delete("content-length")
2637
+ return new Response(out, { status: res.status, statusText: res.statusText, headers: h })
2638
+ })
2639
+ }
2640
+
2535
2641
  // startURL is a Start Plan request's URL without the query the agent put
2536
2642
  // on it: Claude Code asks /v1/messages?beta=true, which magpie passes on,
2537
2643
  // and ZCode asks /v1/messages alone.
@@ -2789,7 +2895,11 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2789
2895
  }
2790
2896
  const id = giftID(raw)
2791
2897
  if (out[id]) continue
2792
- out[id] = model({ ...about(raw), id }, url)
2898
+ // a trial entry is the gift's, which costs nothing: marked free,
2899
+ // so magpie reads a GLM Coding Plan model's weekly or monthly
2900
+ // limit (1310) as that model's, and the account's trial entries,
2901
+ // spent from the gift's own buckets, are still asked (plugins#438)
2902
+ out[id] = { ...model({ ...about(raw), id }, url), free: true }
2793
2903
  }
2794
2904
  // a fallback tells magpie to keep the list it was told last, which
2795
2905
  // predates the gift read just made: an account whose gift lists
@@ -2870,9 +2980,15 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2870
2980
  // says it is spent can spend nothing and replay what was asked for
2871
2981
  let start = alone
2872
2982
  let orig, forcedGift = false, freeGift = false
2983
+ // the gift's -Trial name while the gift is the route that answers
2984
+ // (a free-first request replayed on the plan clears it)
2985
+ let giftName = ""
2873
2986
  let asked = ""
2874
2987
  let renamed = false
2875
- const done = (res) => (renamed ? searchNamed(res) : res)
2988
+ const done = (res) => {
2989
+ if (giftName) res = trialNamed(res, giftName)
2990
+ return renamed ? searchNamed(res) : res
2991
+ }
2876
2992
  if (opts.body != null) {
2877
2993
  orig = opts.body = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()
2878
2994
  delete opts.duplex
@@ -2896,6 +3012,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2896
3012
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
2897
3013
  m = raw
2898
3014
  forcedGift = true
3015
+ giftName = giftID(raw)
2899
3016
  } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
2900
3017
  // free first: the plain model spends the account's own live
2901
3018
  // gift before it spends the coding plan, under the name the
@@ -2915,6 +3032,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2915
3032
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
2916
3033
  m = raw
2917
3034
  freeGift = true
3035
+ giftName = giftID(raw)
2918
3036
  }
2919
3037
  start = alone || forcedGift || freeGift
2920
3038
  }
@@ -2947,6 +3065,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2947
3065
  const replayOnPlan = async () => {
2948
3066
  // the gift is done with: its slot goes to the next request
2949
3067
  own.slot?.release()
3068
+ giftName = ""
2950
3069
  let u = askedUrl
2951
3070
  for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
2952
3071
  if (u.startsWith(b)) {
@@ -2980,7 +3099,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2980
3099
  if (start) {
2981
3100
  own.slot = await startSlot(gateKey, opts.signal)
2982
3101
  own.signal = opts.signal
2983
- if (!own.slot) return kept(startQueueAnswer())
3102
+ if (!own.slot) return kept(startQueueAnswer(gateKey))
2984
3103
  // a hold may have armed while it waited
2985
3104
  if (edgeHeld()) return kept(edgeHeldAnswer())
2986
3105
  if (busyHeld()) return kept(busyHeldAnswer())
@@ -3029,7 +3148,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3029
3148
  // Only Start Plan caps count toward the firewall hold: the
3030
3149
  // coding plan is served by another host and was never refused
3031
3150
  // with the IP's 405.
3032
- res = await askBusy(url, opts, h, start ? busyCap : undefined)
3151
+ res = await askBusy(url, opts, h, start ? () => busyCap(gateKey) : undefined)
3033
3152
  } catch (e) {
3034
3153
  // free first moved the request onto the gift, so a gift that
3035
3154
  // cannot be asked at all — the network, the host — is answered
@@ -3239,4 +3358,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3239
3358
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
3240
3359
  // out of reach, undefined forgets it
3241
3360
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
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 }
3361
+ 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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.57",
3
+ "version": "0.1.59",
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",