@magpie-community/opencode-zcode-auth 0.1.63 → 0.1.65

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 +19 -2
  2. package/index.mjs +78 -13
  3. package/package.json +1 -1
package/README.md CHANGED
@@ -275,6 +275,19 @@ the slots. An account whose slots are taken elsewhere is narrowed to one
275
275
  within a few refusals and then refused alone, so the firewall hold still
276
276
  comes before the 405.
277
277
 
278
+ Since 0.1.64 the request that brought about such a narrowing is not
279
+ failed either. Up to 0.1.63 it went back to magpie as a 429 after its
280
+ re-asks, so two sessions on an account served one at a time showed a 429
281
+ every time the narrowing ran out (JJLIN070414 on X), and with one account
282
+ the agent was told it. Now it gives its slot back at once, without the 2s
283
+ re-ask, and waits at the head of the queue until one of the account's
284
+ other requests has ended, then is sent again, as ZCode's own client
285
+ (its dynamic-workflow governor) cuts its cap and queues a capped request
286
+ rather than failing it. The waits share the gate's two minutes, after
287
+ which it is answered here with the queue's 429. A request refused alone,
288
+ or free first's gift (which goes to the coding plan), is answered as
289
+ before.
290
+
278
291
  ## Two accounts at once
279
292
 
280
293
  Three ZCode accounts used at once from one address can get the address
@@ -337,8 +350,12 @@ menu bar pass it over. The name is a fixed sentence magpie can
337
350
  translate; the count and the plan's own name are the display. Reading
338
351
  the card never claims one. A preview that fails, or lists nothing, adds
339
352
  no line at all, and a card that is an error keeps its error. Claim the
340
- plan in the ZCode app (open it once), or let the daily claim below do it;
341
- the next read shows it as an ordinary gift bucket.
353
+ plan in the ZCode app (open it once); while ZCode asks its security check
354
+ for a claim, as it does now, the daily claim below posts none. The next
355
+ read shows it as an ordinary gift bucket: its `-Trial` entry is listed and
356
+ free first spends it. Until then a `-Trial` pick that finds no gift is
357
+ refused with the held plan's name and "claim it in the ZCode app", not
358
+ only "no active limited quota" (heduian and bg5eau on X, 11-14).
342
359
 
343
360
  ## The daily claim
344
361
 
package/index.mjs CHANGED
@@ -715,6 +715,28 @@ async function claimHint(s) {
715
715
  return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` }
716
716
  }
717
717
 
718
+ // unclaimed names the gift plans ZCode holds for the account but has not
719
+ // put on it (toClaim), for a -Trial pick that finds no gift: the weekend
720
+ // plan (ZCODE WEEKEND BUILD) comes only by a claim, and the claim needs
721
+ // the ZCode app's captcha (claimDaily posts none), so until it is
722
+ // claimed in the app the pick's quota does not exist yet (heduian and
723
+ // bg5eau on X, 11-14). The refusal says where the quota is rather than
724
+ // only that there is none. Kept ten minutes per session, so an agent
725
+ // retrying the pick doesn't read the feed each time; a read that fails
726
+ // names none and is not kept.
727
+ const unclaimedSeen = new Map()
728
+ async function unclaimed(s) {
729
+ if (!s.jwt || jwtExpired(s.jwt)) return []
730
+ const k = s.jwt
731
+ const c = unclaimedSeen.get(k)
732
+ if (c && Date.now() - c.at < 600_000) return c.names
733
+ const got = await toClaim(s).catch(() => null)
734
+ if (!got || got.unread.length) return []
735
+ const names = uniqueModels(got.plans.map((p) => first(p.name, p.plan_id)).filter(Boolean))
736
+ unclaimedSeen.set(k, { at: Date.now(), names })
737
+ return names
738
+ }
739
+
718
740
  // ---- the daily claim ---------------------------------------------------------------
719
741
 
720
742
  // CLAIMED_ALREADY is /billing/claim's body code for a plan the account
@@ -2044,7 +2066,11 @@ function kept(res, text) {
2044
2066
  // this computer through this one process, so the plugin does what that
2045
2067
  // client does: the Start Plan gets a few requests of an account in flight at
2046
2068
  // once (startGate), the rest wait their turn here instead of being sent to be
2047
- // refused, and a refusal anyway is asked again twice (BUSY_WAITS).
2069
+ // refused, and a refusal anyway is asked again twice (BUSY_WAITS). A refusal
2070
+ // of a request sent beside others of the same account lowers that account's
2071
+ // gate and waits its turn again (askBusy's requeue), as ZCode's own
2072
+ // dynamic-workflow governor cuts its cap and queues a capped subagent
2073
+ // request rather than failing it.
2048
2074
  //
2049
2075
  // The coding plan keeps no gate of the plugin's: its cap depends on its tier
2050
2076
  // (Z.ai serves Max more at once than Pro, and Lite fewer) and is higher
@@ -2068,6 +2094,10 @@ const BUSY_CODES = new Set(["3008", "3009", "3010"])
2068
2094
  // requests a capped account could serve on the wire, and the agents' own
2069
2095
  // retries came on top.
2070
2096
  const BUSY_WAITS = [1000, 2000]
2097
+ // REQUEUE_MAX bounds how often one request is handed back to the gate by a
2098
+ // narrowing (askBusy): each narrowing lowers the gate, three to one at most
2099
+ // takes two, so more is a fault of the count, not ZCode.
2100
+ const REQUEUE_MAX = 4
2071
2101
  // The hint names neither "plan" nor "limit": after the vendor's "…limit
2072
2102
  // exceeded" either would read to magpie as a plan used up.
2073
2103
  const BUSY_HINT =
@@ -2129,8 +2159,10 @@ const startFull = (key) => {
2129
2159
  }
2130
2160
 
2131
2161
  // startSlot waits for one of the account's Start Plan slots: { release },
2132
- // null when startGate.wait ran out first, or the agent's abort thrown.
2133
- function startSlot(key, signal) {
2162
+ // null when the wait (startGate.wait unless given) ran out first, or the
2163
+ // agent's abort thrown. A request handed back by a narrowing (requeued) was
2164
+ // first in line already, so it waits at the head of the queue.
2165
+ function startSlot(key, signal, { wait = startGate.wait, front = false } = {}) {
2134
2166
  const lanes = startGate.lanes
2135
2167
  let l = lanes.get(key)
2136
2168
  if (!l) lanes.set(key, (l = { busy: 0, queue: [] }))
@@ -2172,9 +2204,10 @@ function startSlot(key, signal) {
2172
2204
  leave()
2173
2205
  next()
2174
2206
  resolve(null)
2175
- }, startGate.wait)
2207
+ }, Math.max(0, wait))
2176
2208
  signal?.addEventListener?.("abort", aborted, { once: true })
2177
- l.queue.push(go)
2209
+ if (front) l.queue.unshift(go)
2210
+ else l.queue.push(go)
2178
2211
  })
2179
2212
  }
2180
2213
 
@@ -2270,10 +2303,12 @@ const busyHeld = () => busyHold.now() < busyHold.until
2270
2303
  // busyCap records one sustained concurrency cap of a Start Plan request.
2271
2304
  // Only a run arms a hold; the window is cleared on arming, and a cap that
2272
2305
  // lands while the hold is on counts toward nothing — the hold's own 429s and
2273
- // the first caps after it cannot keep re-arming it.
2306
+ // the first caps after it cannot keep re-arming it. It says true when the
2307
+ // cap narrowed the account instead: the request is then requeued, not
2308
+ // failed (see askBusy).
2274
2309
  function busyCap(key) {
2275
- if (key != null && narrowed(key)) return
2276
- if (busyHeld()) return
2310
+ if (key != null && narrowed(key)) return true
2311
+ if (busyHeld()) return false
2277
2312
  const now = busyHold.now()
2278
2313
  busyHold.hits.push(now)
2279
2314
  while (busyHold.hits.length && now - busyHold.hits[0] > BUSY_WINDOW) busyHold.hits.shift()
@@ -2281,6 +2316,7 @@ function busyCap(key) {
2281
2316
  busyHold.until = now + BUSY_HOLD
2282
2317
  busyHold.hits.length = 0
2283
2318
  }
2319
+ return false
2284
2320
  }
2285
2321
 
2286
2322
  // BUSY_HOLD_MARK marks an answer the hold made up: a request the gate or the
@@ -2349,8 +2385,13 @@ function busyAnswer(res, text) {
2349
2385
  // 1s and then 2s, as ZCode's own client does. Past them the cap goes back as
2350
2386
  // busyAnswer's 429. A request refused again at its 1s re-ask is a sustained
2351
2387
  // cap, told to onCap once (the firewall hold's count); one the re-ask got
2352
- // past is not. The plan path's patience, shared with free first's replay,
2353
- // whose plan has a cap of its own.
2388
+ // past is not. When onCap says the cap narrowed the account (others of this
2389
+ // computer were in flight on it), asking again in 2s would only be refused
2390
+ // beside them again: the busyAnswer goes back at once marked `requeue`, and
2391
+ // the Start Plan path waits for one of those others to end and sends it
2392
+ // again (JJLIN070414 on X: two sessions on one account, each pair's second
2393
+ // request failed 429 where ZCode's own client queues it). The plan path's
2394
+ // patience, shared with free first's replay, whose plan has a cap of its own.
2354
2395
  async function askBusy(u, o, hs, onCap) {
2355
2396
  let res = await fetch(u, { ...o, headers: hs })
2356
2397
  let caps = 0
@@ -2358,7 +2399,11 @@ async function askBusy(u, o, hs, onCap) {
2358
2399
  const text = await res.text()
2359
2400
  const cap = busy(429, text)
2360
2401
  // one request's refusals are one saturation signal, not one per ask
2361
- if (cap && ++caps === 2) onCap?.()
2402
+ if (cap && ++caps === 2 && onCap?.() === true) {
2403
+ res = busyAnswer(res, text)
2404
+ res.requeue = true
2405
+ break
2406
+ }
2362
2407
  // the hold armed: a request already in flight stops asking too. The
2363
2408
  // second check catches the asks that capped before the hold armed and
2364
2409
  // woke from their wait after it. Keying on onCap keeps the coding plan
@@ -3096,7 +3141,8 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3096
3141
  const raw = giftModel(gift, m)
3097
3142
  const available = raw && giftUsable(s, gift, raw)
3098
3143
  if (!available) {
3099
- const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `${giftRested(s, raw) ? `ZCode said the last request for ${raw} was over its quota, so it is not asked again for a minute: ` : ""}ZCode's limited quota for ${raw} is exhausted or temporarily unavailable` : `ZCode has no active limited quota for ${m}` }
3144
+ const held = raw ? [] : await unclaimed(s)
3145
+ const error = { type: raw ? "rate_limit_error" : "invalid_request_error", message: raw ? `${giftRested(s, raw) ? `ZCode said the last request for ${raw} was over its quota, so it is not asked again for a minute: ` : ""}ZCode's limited quota for ${raw} is exhausted or temporarily unavailable` : `ZCode has no active limited quota for ${m}${held.length ? `. ZCode holds ${held.join(", ")} for this account unclaimed: claim it in the ZCode app (its claim needs the app's security check), and ${m} spends it` : ""}` }
3100
3146
  return kept(new Response(JSON.stringify({ type: "error", error }), { status: raw ? 429 : 400, headers: { "content-type": "application/json" } }))
3101
3147
  }
3102
3148
  orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
@@ -3250,6 +3296,25 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3250
3296
  // coding plan is served by another host and was never refused
3251
3297
  // with the IP's 405.
3252
3298
  res = await askBusy(url, opts, h, start ? () => busyCap(gateKey) : undefined)
3299
+ // a cap this computer brought on itself, with others of the
3300
+ // account in flight beside it, narrowed the account's gate:
3301
+ // the request gives its slot back and waits, first in line,
3302
+ // until one of those others has ended, then is sent again —
3303
+ // queued, as ZCode's own client queues its subagents' caps,
3304
+ // not failed. Free first's gift goes to the plan instead,
3305
+ // which serves it now. The waits share one startGate.wait;
3306
+ // each turn the gate is lower or the request is alone, where
3307
+ // a cap is ZCode's or another client's and goes back as it
3308
+ // did.
3309
+ const until = Date.now() + startGate.wait
3310
+ for (let turn = 0; res.requeue && !freeGift && turn < REQUEUE_MAX; turn++) {
3311
+ own.slot?.release()
3312
+ own.slot = await startSlot(gateKey, opts.signal, { wait: until - Date.now(), front: true })
3313
+ if (!own.slot) return kept(startQueueAnswer(gateKey))
3314
+ if (edgeHeld()) return kept(edgeHeldAnswer())
3315
+ if (busyHeld()) return kept(busyHeldAnswer())
3316
+ res = await askBusy(url, opts, h, () => busyCap(gateKey))
3317
+ }
3253
3318
  } catch (e) {
3254
3319
  // free first moved the request onto the gift, so a gift that
3255
3320
  // cannot be asked at all — the network, the host — is answered
@@ -3459,4 +3524,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3459
3524
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
3460
3525
  // out of reach, undefined forgets it
3461
3526
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
3462
- export const _internal = { wallAnswer, unreached, planFull, notePlan, planFullUntil, locatedKeys, lastKeys, 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 }
3527
+ export const _internal = { wallAnswer, unreached, planFull, notePlan, planFullUntil, locatedKeys, lastKeys, 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, unclaimed, unclaimedSeen, 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.63",
3
+ "version": "0.1.65",
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",