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

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 (2) hide show
  1. package/index.mjs +100 -7
  2. package/package.json +1 -1
package/index.mjs CHANGED
@@ -510,6 +510,7 @@ async function codingUsage(s) {
510
510
  const level = typeof d.level === "string" ? d.level : ""
511
511
  if (level) out.plan = "GLM Coding " + level[0].toUpperCase() + level.slice(1)
512
512
  out.windows = limitWindows(d)
513
+ notePlan(s.key, out.windows)
513
514
  const resets = personalResets(root, s.key)
514
515
  let subs = null
515
516
  try {
@@ -1211,6 +1212,7 @@ async function teamUsage(s, key) {
1211
1212
  const headers = teamHeaders(s.base, s.org, s.project)
1212
1213
  const d = (await call("GET", root + "/api/monitor/usage/quota/limit?type=2", { auth: key, headers })) ?? {}
1213
1214
  const out = { windows: limitWindows(d) }
1215
+ notePlan(key, out.windows)
1214
1216
  if (!s.token) return out
1215
1217
  const resets = teamResets(root, s.token, headers)
1216
1218
  try {
@@ -1675,29 +1677,101 @@ function ownLocation(store, key) {
1675
1677
  // its key: the secret of the key it names, read as ZCode lists the
1676
1678
  // project's keys (BigModel's token bare, Z.ai's as a Bearer). Nothing is
1677
1679
  // made: a location whose key is gone (404) leaves the sign-in keyless, as
1678
- // before; any other failure is said. A key read is kept for the token.
1680
+ // before; any other failure is said. A key read is kept for the token, and
1681
+ // the last key read for the location (lastKeys) serves while a read can't
1682
+ // reach Z.ai, so a network that drops one read keeps the plan's key; an
1683
+ // answer that refused the read (a 401, a 500) is said as before. The read
1684
+ // is bounded (KEY_READ_MS): an ask that hung for minutes
1685
+ // held the request with it (#1020, takomitkm). A read that never reached
1686
+ // Z.ai — the socket (ECONNRESET), a timeout, the name — with no key read
1687
+ // before is thrown marked unreached, which serve answers as a wall
1688
+ // (wallAnswer): it is the network, not the sign-in, so it says nothing of
1689
+ // signing in again.
1679
1690
  const locatedKeys = new Map()
1691
+ const lastKeys = new Map()
1692
+ const KEY_READ_MS = 20_000
1680
1693
  async function located(s) {
1681
1694
  if (!s || s.key || !s.loc || !s.token) return s
1682
1695
  const l = s.loc
1683
- const id = [s.token, l.origin, l.org, l.project, l.apiKeyId].join("\0")
1696
+ const at = [s.site, l.origin, l.org, l.project, l.apiKeyId].join("\0")
1697
+ const id = s.token + "\0" + at
1684
1698
  let got = locatedKeys.get(id)
1685
1699
  if (!got || (got.err && Date.now() - got.at >= 60_000)) {
1686
1700
  const auth = s.site === "zai" ? "Bearer " + s.token : s.token
1687
1701
  try {
1688
- const secret = first((await call("GET", `${keysURL(l.origin, l.org, l.project)}/copy/${encodeURIComponent(l.apiKeyId)}`, { auth }))?.secretKey)
1702
+ const secret = first((await call("GET", `${keysURL(l.origin, l.org, l.project)}/copy/${encodeURIComponent(l.apiKeyId)}`, { auth, signal: AbortSignal.timeout(KEY_READ_MS) }))?.secretKey)
1689
1703
  got = secret ? { key: `${l.apiKeyId}.${secret}` } : { err: new Error("no secret for the key") }
1690
1704
  } catch (e) {
1691
1705
  got = e?.status === 404 ? { key: "" } : { err: e }
1692
1706
  }
1707
+ if (got.err && unreached(got.err) && lastKeys.get(at)) got.key = lastKeys.get(at)
1708
+ else if (!got.err) lastKeys.set(at, got.key)
1693
1709
  got.at = Date.now()
1694
1710
  locatedKeys.set(id, got)
1695
1711
  }
1696
- if (got.err) throw new Error(`ZCode's ${SITES[s.site].name} coding plan key: ${got.err.message} — sign in to ZCode again`)
1712
+ if (got.err && !got.key) {
1713
+ const name = SITES[s.site].name
1714
+ if (unreached(got.err)) {
1715
+ const e = new Error(`ZCode's ${name} coding plan key: ${got.err.message} — ${name} could not be reached, so the request was not sent`)
1716
+ e.unreached = true
1717
+ throw e
1718
+ }
1719
+ throw new Error(`ZCode's ${name} coding plan key: ${got.err.message} — sign in to ZCode again`)
1720
+ }
1697
1721
  if (got.key) s.key = got.key
1698
1722
  return s
1699
1723
  }
1700
1724
 
1725
+ // unreached says whether a fetch failed before any answer: the socket
1726
+ // closed or refused, a timeout, a name that didn't resolve. An answer with
1727
+ // a status (ZError) never is, nor is a caller's abort.
1728
+ const UNREACHED = /ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|EAI_AGAIN|ECONNABORTED|EHOSTUNREACH|ENETUNREACH|socket connection was closed|ConnectionRefused|ConnectionClosed|FailedToOpenSocket|fetch failed|timed out/i
1729
+ function unreached(e) {
1730
+ if (!e || e instanceof ZError || e.name === "AbortError") return false
1731
+ if (e.name === "TimeoutError") return true
1732
+ return [e.code, e.message, e.cause?.code, e.cause?.message].some((x) => typeof x === "string" && UNREACHED.test(x))
1733
+ }
1734
+
1735
+ // wallAnswer is a lane that can't serve the request now — not reached, or
1736
+ // its plan known full — told to magpie as a wall: a 429 whose error.code
1737
+ // is one of magpie's wallCodes (yetone/magpie@067e4c484), which it sends
1738
+ // once, never again in place, and rests as a rate limit, a minute at
1739
+ // first, while the next account is asked. A thrown error was a 502 that
1740
+ // magpie asked again eight times (#1020). The words are kept off magpie's
1741
+ // quota and credit words, so the rest stays a brief one.
1742
+ function wallAnswer(message) {
1743
+ const error = { type: "rate_limit_error", code: "user_model_rate_limited", message }
1744
+ return new Response(JSON.stringify({ type: "error", error }), { status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json" } })
1745
+ }
1746
+
1747
+ // planFull is a coding plan key whose last usage read showed a window
1748
+ // counted full with its reset ahead: until then (and for PLAN_FULL_TRUST
1749
+ // after the read at most) free first's replay doesn't send to it.
1750
+ const planFull = new Map()
1751
+ const PLAN_FULL_TRUST = 30 * 60_000
1752
+ function notePlan(key, windows) {
1753
+ if (!key) return
1754
+ let until = 0
1755
+ for (const w of windows ?? []) {
1756
+ if (w.aside) continue
1757
+ const full = (isNum(w.amount) && isNum(w.limit) && w.limit > 0 && w.amount >= w.limit) || (isNum(w.used) && w.used >= 100)
1758
+ const t = Date.parse(w.resetsAt ?? "")
1759
+ if (full && t > Date.now()) until = Math.max(until, t)
1760
+ }
1761
+ if (until) planFull.set(key, { until, at: Date.now() })
1762
+ else planFull.delete(key)
1763
+ }
1764
+ function planFullUntil(key) {
1765
+ const f = key && planFull.get(key)
1766
+ if (!f) return 0
1767
+ const now = Date.now()
1768
+ if (now >= f.until || now - f.at >= PLAN_FULL_TRUST) {
1769
+ planFull.delete(key)
1770
+ return 0
1771
+ }
1772
+ return f.until
1773
+ }
1774
+
1701
1775
  // ownSignIn is what ZCode is signed in to now: the account, its coding
1702
1776
  // plan key, ZCode's session token (the Start Plan's key) and the team plan
1703
1777
  // it is switched to; null when it has none of them.
@@ -2959,7 +3033,15 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
2959
3033
  }
2960
3034
  async function serve(input, init, own) {
2961
3035
  const auth = await getAuth()
2962
- const s = await located(stateOf(auth))
3036
+ let s
3037
+ try {
3038
+ s = await located(stateOf(auth))
3039
+ } catch (e) {
3040
+ // the plan's key couldn't be read for the network: a wall,
3041
+ // sent once (wallAnswer), not a 502 asked again (#1020)
3042
+ if (e?.unreached) return kept(wallAnswer(e.message))
3043
+ throw e
3044
+ }
2963
3045
  if (!s) throw new Error("not signed in to ZCode")
2964
3046
  // the account a Start Plan slot belongs to: its user id, which a
2965
3047
  // renewed session keeps, before the key or session itself
@@ -3082,7 +3164,18 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3082
3164
  h2.delete("content-length")
3083
3165
  opts.body = marked(JSON.stringify({ ...JSON.parse(orig), model: asked }), s.device, sid)
3084
3166
  delete opts.duplex
3085
- return askBusy(u, opts, h2)
3167
+ // a plan the last usage read showed full isn't sent to: it
3168
+ // would only refuse (#1020)
3169
+ const full = planFullUntil(key)
3170
+ if (full) return wallAnswer(`ZCode's ${SITES[s.site].name} GLM Coding Plan was full at its last read, until ${new Date(full).toISOString()}, so the request was not sent to it`)
3171
+ try {
3172
+ return await askBusy(u, opts, h2)
3173
+ } catch (e) {
3174
+ // a plan that can't be reached is a wall too, sent once; a
3175
+ // caller's abort stays an abort
3176
+ if (opts.signal?.aborted || !unreached(e)) throw e
3177
+ return wallAnswer(`ZCode's ${SITES[s.site].name} GLM Coding Plan: ${e.message} — it could not be reached, so the request was not sent`)
3178
+ }
3086
3179
  }
3087
3180
  // a block page held this computer off zcode.z.ai (edge): the
3088
3181
  // Start Plan and a picked gift are answered here; free first
@@ -3358,4 +3451,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3358
3451
  // config sets what zcodeConfig has read, for tests: null is ZCode's config
3359
3452
  // out of reach, undefined forgets it
3360
3453
  const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
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 }
3454
+ 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 }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@magpie-community/opencode-zcode-auth",
3
- "version": "0.1.59",
3
+ "version": "0.1.60",
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",