@magpie-community/opencode-zcode-auth 0.1.59 → 0.1.61
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/index.mjs +105 -8
- 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 {
|
|
@@ -1249,6 +1251,7 @@ async function personalResets(root, key) {
|
|
|
1249
1251
|
// hours and of the week, of which only those still available count (one
|
|
1250
1252
|
// run out stays listed a week, available false), each with its own end
|
|
1251
1253
|
// (each, soonest first, one with no end last) and the soonest as until.
|
|
1254
|
+
// One whose end has passed is not counted, whatever its flag says.
|
|
1252
1255
|
// null when the list can't be read, so no count is shown rather than 0,
|
|
1253
1256
|
// and when it holds none.
|
|
1254
1257
|
async function resetsOf(url, auth, headers) {
|
|
@@ -1264,8 +1267,11 @@ async function resetsOf(url, auth, headers) {
|
|
|
1264
1267
|
let n = 0
|
|
1265
1268
|
for (const x of Array.isArray(rs) ? rs : []) {
|
|
1266
1269
|
if (x?.available !== true) continue
|
|
1267
|
-
n++
|
|
1268
1270
|
const t = when(x.expireTime)
|
|
1271
|
+
// a reset past its end is no reset: the list can still flag it
|
|
1272
|
+
// available, and the vendor's page puts it among the expired
|
|
1273
|
+
if (t && t <= Date.now()) continue
|
|
1274
|
+
n++
|
|
1269
1275
|
if (t && (!until || t < until)) until = t
|
|
1270
1276
|
each.push(t ? { until: new Date(t).toISOString(), window } : { window })
|
|
1271
1277
|
}
|
|
@@ -1675,29 +1681,101 @@ function ownLocation(store, key) {
|
|
|
1675
1681
|
// its key: the secret of the key it names, read as ZCode lists the
|
|
1676
1682
|
// project's keys (BigModel's token bare, Z.ai's as a Bearer). Nothing is
|
|
1677
1683
|
// 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
|
|
1684
|
+
// before; any other failure is said. A key read is kept for the token, and
|
|
1685
|
+
// the last key read for the location (lastKeys) serves while a read can't
|
|
1686
|
+
// reach Z.ai, so a network that drops one read keeps the plan's key; an
|
|
1687
|
+
// answer that refused the read (a 401, a 500) is said as before. The read
|
|
1688
|
+
// is bounded (KEY_READ_MS): an ask that hung for minutes
|
|
1689
|
+
// held the request with it (#1020, takomitkm). A read that never reached
|
|
1690
|
+
// Z.ai — the socket (ECONNRESET), a timeout, the name — with no key read
|
|
1691
|
+
// before is thrown marked unreached, which serve answers as a wall
|
|
1692
|
+
// (wallAnswer): it is the network, not the sign-in, so it says nothing of
|
|
1693
|
+
// signing in again.
|
|
1679
1694
|
const locatedKeys = new Map()
|
|
1695
|
+
const lastKeys = new Map()
|
|
1696
|
+
const KEY_READ_MS = 20_000
|
|
1680
1697
|
async function located(s) {
|
|
1681
1698
|
if (!s || s.key || !s.loc || !s.token) return s
|
|
1682
1699
|
const l = s.loc
|
|
1683
|
-
const
|
|
1700
|
+
const at = [s.site, l.origin, l.org, l.project, l.apiKeyId].join("\0")
|
|
1701
|
+
const id = s.token + "\0" + at
|
|
1684
1702
|
let got = locatedKeys.get(id)
|
|
1685
1703
|
if (!got || (got.err && Date.now() - got.at >= 60_000)) {
|
|
1686
1704
|
const auth = s.site === "zai" ? "Bearer " + s.token : s.token
|
|
1687
1705
|
try {
|
|
1688
|
-
const secret = first((await call("GET", `${keysURL(l.origin, l.org, l.project)}/copy/${encodeURIComponent(l.apiKeyId)}`, { auth }))?.secretKey)
|
|
1706
|
+
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
1707
|
got = secret ? { key: `${l.apiKeyId}.${secret}` } : { err: new Error("no secret for the key") }
|
|
1690
1708
|
} catch (e) {
|
|
1691
1709
|
got = e?.status === 404 ? { key: "" } : { err: e }
|
|
1692
1710
|
}
|
|
1711
|
+
if (got.err && unreached(got.err) && lastKeys.get(at)) got.key = lastKeys.get(at)
|
|
1712
|
+
else if (!got.err) lastKeys.set(at, got.key)
|
|
1693
1713
|
got.at = Date.now()
|
|
1694
1714
|
locatedKeys.set(id, got)
|
|
1695
1715
|
}
|
|
1696
|
-
if (got.err
|
|
1716
|
+
if (got.err && !got.key) {
|
|
1717
|
+
const name = SITES[s.site].name
|
|
1718
|
+
if (unreached(got.err)) {
|
|
1719
|
+
const e = new Error(`ZCode's ${name} coding plan key: ${got.err.message} — ${name} could not be reached, so the request was not sent`)
|
|
1720
|
+
e.unreached = true
|
|
1721
|
+
throw e
|
|
1722
|
+
}
|
|
1723
|
+
throw new Error(`ZCode's ${name} coding plan key: ${got.err.message} — sign in to ZCode again`)
|
|
1724
|
+
}
|
|
1697
1725
|
if (got.key) s.key = got.key
|
|
1698
1726
|
return s
|
|
1699
1727
|
}
|
|
1700
1728
|
|
|
1729
|
+
// unreached says whether a fetch failed before any answer: the socket
|
|
1730
|
+
// closed or refused, a timeout, a name that didn't resolve. An answer with
|
|
1731
|
+
// a status (ZError) never is, nor is a caller's abort.
|
|
1732
|
+
const UNREACHED = /ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|EAI_AGAIN|ECONNABORTED|EHOSTUNREACH|ENETUNREACH|socket connection was closed|ConnectionRefused|ConnectionClosed|FailedToOpenSocket|fetch failed|timed out/i
|
|
1733
|
+
function unreached(e) {
|
|
1734
|
+
if (!e || e instanceof ZError || e.name === "AbortError") return false
|
|
1735
|
+
if (e.name === "TimeoutError") return true
|
|
1736
|
+
return [e.code, e.message, e.cause?.code, e.cause?.message].some((x) => typeof x === "string" && UNREACHED.test(x))
|
|
1737
|
+
}
|
|
1738
|
+
|
|
1739
|
+
// wallAnswer is a lane that can't serve the request now — not reached, or
|
|
1740
|
+
// its plan known full — told to magpie as a wall: a 429 whose error.code
|
|
1741
|
+
// is one of magpie's wallCodes (yetone/magpie@067e4c484), which it sends
|
|
1742
|
+
// once, never again in place, and rests as a rate limit, a minute at
|
|
1743
|
+
// first, while the next account is asked. A thrown error was a 502 that
|
|
1744
|
+
// magpie asked again eight times (#1020). The words are kept off magpie's
|
|
1745
|
+
// quota and credit words, so the rest stays a brief one.
|
|
1746
|
+
function wallAnswer(message) {
|
|
1747
|
+
const error = { type: "rate_limit_error", code: "user_model_rate_limited", message }
|
|
1748
|
+
return new Response(JSON.stringify({ type: "error", error }), { status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json" } })
|
|
1749
|
+
}
|
|
1750
|
+
|
|
1751
|
+
// planFull is a coding plan key whose last usage read showed a window
|
|
1752
|
+
// counted full with its reset ahead: until then (and for PLAN_FULL_TRUST
|
|
1753
|
+
// after the read at most) free first's replay doesn't send to it.
|
|
1754
|
+
const planFull = new Map()
|
|
1755
|
+
const PLAN_FULL_TRUST = 30 * 60_000
|
|
1756
|
+
function notePlan(key, windows) {
|
|
1757
|
+
if (!key) return
|
|
1758
|
+
let until = 0
|
|
1759
|
+
for (const w of windows ?? []) {
|
|
1760
|
+
if (w.aside) continue
|
|
1761
|
+
const full = (isNum(w.amount) && isNum(w.limit) && w.limit > 0 && w.amount >= w.limit) || (isNum(w.used) && w.used >= 100)
|
|
1762
|
+
const t = Date.parse(w.resetsAt ?? "")
|
|
1763
|
+
if (full && t > Date.now()) until = Math.max(until, t)
|
|
1764
|
+
}
|
|
1765
|
+
if (until) planFull.set(key, { until, at: Date.now() })
|
|
1766
|
+
else planFull.delete(key)
|
|
1767
|
+
}
|
|
1768
|
+
function planFullUntil(key) {
|
|
1769
|
+
const f = key && planFull.get(key)
|
|
1770
|
+
if (!f) return 0
|
|
1771
|
+
const now = Date.now()
|
|
1772
|
+
if (now >= f.until || now - f.at >= PLAN_FULL_TRUST) {
|
|
1773
|
+
planFull.delete(key)
|
|
1774
|
+
return 0
|
|
1775
|
+
}
|
|
1776
|
+
return f.until
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1701
1779
|
// ownSignIn is what ZCode is signed in to now: the account, its coding
|
|
1702
1780
|
// plan key, ZCode's session token (the Start Plan's key) and the team plan
|
|
1703
1781
|
// it is switched to; null when it has none of them.
|
|
@@ -2959,7 +3037,15 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2959
3037
|
}
|
|
2960
3038
|
async function serve(input, init, own) {
|
|
2961
3039
|
const auth = await getAuth()
|
|
2962
|
-
|
|
3040
|
+
let s
|
|
3041
|
+
try {
|
|
3042
|
+
s = await located(stateOf(auth))
|
|
3043
|
+
} catch (e) {
|
|
3044
|
+
// the plan's key couldn't be read for the network: a wall,
|
|
3045
|
+
// sent once (wallAnswer), not a 502 asked again (#1020)
|
|
3046
|
+
if (e?.unreached) return kept(wallAnswer(e.message))
|
|
3047
|
+
throw e
|
|
3048
|
+
}
|
|
2963
3049
|
if (!s) throw new Error("not signed in to ZCode")
|
|
2964
3050
|
// the account a Start Plan slot belongs to: its user id, which a
|
|
2965
3051
|
// renewed session keeps, before the key or session itself
|
|
@@ -3082,7 +3168,18 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
3082
3168
|
h2.delete("content-length")
|
|
3083
3169
|
opts.body = marked(JSON.stringify({ ...JSON.parse(orig), model: asked }), s.device, sid)
|
|
3084
3170
|
delete opts.duplex
|
|
3085
|
-
|
|
3171
|
+
// a plan the last usage read showed full isn't sent to: it
|
|
3172
|
+
// would only refuse (#1020)
|
|
3173
|
+
const full = planFullUntil(key)
|
|
3174
|
+
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`)
|
|
3175
|
+
try {
|
|
3176
|
+
return await askBusy(u, opts, h2)
|
|
3177
|
+
} catch (e) {
|
|
3178
|
+
// a plan that can't be reached is a wall too, sent once; a
|
|
3179
|
+
// caller's abort stays an abort
|
|
3180
|
+
if (opts.signal?.aborted || !unreached(e)) throw e
|
|
3181
|
+
return wallAnswer(`ZCode's ${SITES[s.site].name} GLM Coding Plan: ${e.message} — it could not be reached, so the request was not sent`)
|
|
3182
|
+
}
|
|
3086
3183
|
}
|
|
3087
3184
|
// a block page held this computer off zcode.z.ai (edge): the
|
|
3088
3185
|
// Start Plan and a picked gift are answered here; free first
|
|
@@ -3358,4 +3455,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
3358
3455
|
// config sets what zcodeConfig has read, for tests: null is ZCode's config
|
|
3359
3456
|
// out of reach, undefined forgets it
|
|
3360
3457
|
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 }
|
|
3458
|
+
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.
|
|
3
|
+
"version": "0.1.61",
|
|
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",
|