@magpie-community/opencode-zcode-auth 0.1.58 → 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.
- package/README.md +2 -0
- package/index.mjs +173 -8
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -165,6 +165,8 @@ keeps the plain models on the plan. The JSON below still works, and a
|
|
|
165
165
|
`freeFirst: false` there keeps it off whatever the switch says. Turn it
|
|
166
166
|
off for the whole plugin in magpie's Plugins › Options
|
|
167
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
|
+
|
|
168
170
|
```json
|
|
169
171
|
{ "freeFirst": false }
|
|
170
172
|
```
|
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
|
|
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
|
|
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.
|
|
@@ -2575,6 +2649,69 @@ function searchNamed(res) {
|
|
|
2575
2649
|
})
|
|
2576
2650
|
}
|
|
2577
2651
|
|
|
2652
|
+
// trialNamed is a gift's answer with its model said as the picker lists it
|
|
2653
|
+
// (GLM-5.3-Flash-Trial): the gift answers under the plain name, as the coding
|
|
2654
|
+
// plan does, so the Usage page, the sessions and the request log named the
|
|
2655
|
+
// plan's model whichever route served it, and a user with free first on
|
|
2656
|
+
// could not tell whether the free quota was spent (WJaunita45604 on X). A
|
|
2657
|
+
// failed answer, or a body that is not JSON or an event stream, goes on as it
|
|
2658
|
+
// came.
|
|
2659
|
+
function trialNamed(res, name) {
|
|
2660
|
+
if (!res.body || res.status >= 400) return res
|
|
2661
|
+
const type = res.headers.get("content-type") ?? ""
|
|
2662
|
+
const set = (d) => {
|
|
2663
|
+
if (d && typeof d === "object") {
|
|
2664
|
+
if (typeof d.model === "string") d.model = name
|
|
2665
|
+
if (typeof d.message?.model === "string") d.message.model = name
|
|
2666
|
+
return true
|
|
2667
|
+
}
|
|
2668
|
+
return false
|
|
2669
|
+
}
|
|
2670
|
+
const line = (l) => {
|
|
2671
|
+
if (!l.startsWith("data:") || !l.includes('"model"')) return l
|
|
2672
|
+
try {
|
|
2673
|
+
const d = JSON.parse(l.slice(5))
|
|
2674
|
+
return set(d) ? "data: " + JSON.stringify(d) : l
|
|
2675
|
+
} catch {
|
|
2676
|
+
return l
|
|
2677
|
+
}
|
|
2678
|
+
}
|
|
2679
|
+
const h = new Headers(res.headers)
|
|
2680
|
+
if (type.includes("text/event-stream")) {
|
|
2681
|
+
const dec = new TextDecoder()
|
|
2682
|
+
const enc = new TextEncoder()
|
|
2683
|
+
let held = ""
|
|
2684
|
+
const body = res.body.pipeThrough(
|
|
2685
|
+
new TransformStream({
|
|
2686
|
+
transform(chunk, ctl) {
|
|
2687
|
+
held += dec.decode(chunk, { stream: true })
|
|
2688
|
+
const i = held.lastIndexOf("\n")
|
|
2689
|
+
if (i < 0) return
|
|
2690
|
+
ctl.enqueue(enc.encode(held.slice(0, i + 1).split("\n").map(line).join("\n")))
|
|
2691
|
+
held = held.slice(i + 1)
|
|
2692
|
+
},
|
|
2693
|
+
flush(ctl) {
|
|
2694
|
+
held += dec.decode()
|
|
2695
|
+
if (held) ctl.enqueue(enc.encode(line(held)))
|
|
2696
|
+
},
|
|
2697
|
+
}),
|
|
2698
|
+
)
|
|
2699
|
+
return new Response(body, { status: res.status, statusText: res.statusText, headers: h })
|
|
2700
|
+
}
|
|
2701
|
+
if (!type.includes("json")) return res
|
|
2702
|
+
return res.text().then((text) => {
|
|
2703
|
+
let out = text
|
|
2704
|
+
if (text.includes('"model"')) {
|
|
2705
|
+
try {
|
|
2706
|
+
const v = JSON.parse(text)
|
|
2707
|
+
if (set(v)) out = JSON.stringify(v)
|
|
2708
|
+
} catch {}
|
|
2709
|
+
}
|
|
2710
|
+
h.delete("content-length")
|
|
2711
|
+
return new Response(out, { status: res.status, statusText: res.statusText, headers: h })
|
|
2712
|
+
})
|
|
2713
|
+
}
|
|
2714
|
+
|
|
2578
2715
|
// startURL is a Start Plan request's URL without the query the agent put
|
|
2579
2716
|
// on it: Claude Code asks /v1/messages?beta=true, which magpie passes on,
|
|
2580
2717
|
// and ZCode asks /v1/messages alone.
|
|
@@ -2896,7 +3033,15 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2896
3033
|
}
|
|
2897
3034
|
async function serve(input, init, own) {
|
|
2898
3035
|
const auth = await getAuth()
|
|
2899
|
-
|
|
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
|
+
}
|
|
2900
3045
|
if (!s) throw new Error("not signed in to ZCode")
|
|
2901
3046
|
// the account a Start Plan slot belongs to: its user id, which a
|
|
2902
3047
|
// renewed session keeps, before the key or session itself
|
|
@@ -2917,9 +3062,15 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2917
3062
|
// says it is spent can spend nothing and replay what was asked for
|
|
2918
3063
|
let start = alone
|
|
2919
3064
|
let orig, forcedGift = false, freeGift = false
|
|
3065
|
+
// the gift's -Trial name while the gift is the route that answers
|
|
3066
|
+
// (a free-first request replayed on the plan clears it)
|
|
3067
|
+
let giftName = ""
|
|
2920
3068
|
let asked = ""
|
|
2921
3069
|
let renamed = false
|
|
2922
|
-
const done = (res) =>
|
|
3070
|
+
const done = (res) => {
|
|
3071
|
+
if (giftName) res = trialNamed(res, giftName)
|
|
3072
|
+
return renamed ? searchNamed(res) : res
|
|
3073
|
+
}
|
|
2923
3074
|
if (opts.body != null) {
|
|
2924
3075
|
orig = opts.body = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()
|
|
2925
3076
|
delete opts.duplex
|
|
@@ -2943,6 +3094,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2943
3094
|
orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
|
|
2944
3095
|
m = raw
|
|
2945
3096
|
forcedGift = true
|
|
3097
|
+
giftName = giftID(raw)
|
|
2946
3098
|
} else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
|
|
2947
3099
|
// free first: the plain model spends the account's own live
|
|
2948
3100
|
// gift before it spends the coding plan, under the name the
|
|
@@ -2962,6 +3114,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2962
3114
|
orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
|
|
2963
3115
|
m = raw
|
|
2964
3116
|
freeGift = true
|
|
3117
|
+
giftName = giftID(raw)
|
|
2965
3118
|
}
|
|
2966
3119
|
start = alone || forcedGift || freeGift
|
|
2967
3120
|
}
|
|
@@ -2994,6 +3147,7 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
2994
3147
|
const replayOnPlan = async () => {
|
|
2995
3148
|
// the gift is done with: its slot goes to the next request
|
|
2996
3149
|
own.slot?.release()
|
|
3150
|
+
giftName = ""
|
|
2997
3151
|
let u = askedUrl
|
|
2998
3152
|
for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
|
|
2999
3153
|
if (u.startsWith(b)) {
|
|
@@ -3010,7 +3164,18 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
3010
3164
|
h2.delete("content-length")
|
|
3011
3165
|
opts.body = marked(JSON.stringify({ ...JSON.parse(orig), model: asked }), s.device, sid)
|
|
3012
3166
|
delete opts.duplex
|
|
3013
|
-
|
|
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
|
+
}
|
|
3014
3179
|
}
|
|
3015
3180
|
// a block page held this computer off zcode.z.ai (edge): the
|
|
3016
3181
|
// Start Plan and a picked gift are answered here; free first
|
|
@@ -3286,4 +3451,4 @@ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
|
|
|
3286
3451
|
// config sets what zcodeConfig has read, for tests: null is ZCode's config
|
|
3287
3452
|
// out of reach, undefined forgets it
|
|
3288
3453
|
const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
|
|
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 }
|
|
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.
|
|
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",
|