@jianmu-plugins/opencode-zcode-auth 0.0.0-stage → 0.1.68

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 ADDED
@@ -0,0 +1,3632 @@
1
+ // ZCode's GLM Coding Plan, as an OpenCode provider plugin.
2
+ //
3
+ // ZCode (zcode.z.ai) signs in to a Z.ai account, or a BigModel (智谱,
4
+ // bigmodel.cn) one, through a flow zcode.z.ai opens and is polled for. With
5
+ // the account's sign-in it finds or makes the coding plan key it uses (the
6
+ // key named zcode-api-key in the account's default project) and sends the
7
+ // models' requests, Anthropic's Messages, to the plan's endpoint:
8
+ // api.z.ai/api/anthropic or open.bigmodel.cn/api/anthropic.
9
+ //
10
+ // An account with no plan of its own may have a seat on a team's plan (a
11
+ // project of type 2, and its zcode-team-api-key), or ZCode's free Start
12
+ // Plan, served by zcode.z.ai itself to ZCode's own session token (a JWT
13
+ // that can't be refreshed: when it runs out, sign in again).
14
+ //
15
+ // The sign-in is kept as OpenCode keeps an OAuth one: `access` is the key,
16
+ // `refresh` the rest of it as JSON (site, base, key, jwt, team project,
17
+ // plan, device id), `accountId` the account's email.
18
+
19
+ import { createDecipheriv, createHash } from "node:crypto"
20
+ import { existsSync, readFileSync, readdirSync } from "node:fs"
21
+ import { arch, homedir, release, userInfo } from "node:os"
22
+ import { isAbsolute, join } from "node:path"
23
+ import PROMPT from "./prompt.mjs"
24
+
25
+ const PROVIDER = "zcode"
26
+ // FREE_FIRST is magpie's switch for free first in the provider's editor
27
+ const FREE_FIRST = "free_first"
28
+ const ZCODE = "https://zcode.z.ai"
29
+ const ZAI_API = "https://api.z.ai"
30
+ const BIGMODEL_API = "https://bigmodel.cn" // BigModel's business API, where ZCode asks it
31
+ const ZAI_BASE = "https://api.z.ai/api/anthropic"
32
+ const BIGMODEL_BASE = "https://open.bigmodel.cn/api/anthropic"
33
+ const START_BASE = ZCODE + "/api/v1/zcode-plan/anthropic"
34
+ // APP_VERSION is the ZCode this signs in and asks as, on every call. ZCode
35
+ // gates by it: its marketing feed answers empty to an older one (#678),
36
+ // and its Start Plan balance "judges capability by the real app_version"
37
+ // (zaiStartPlanBilling.ts in zai-org/ZCode@a9fe401, 3.17.2).
38
+ const APP_VERSION = "3.17.2"
39
+ const UA = "ZCode/" + APP_VERSION
40
+
41
+ // ZCode's models before its config is read; the Start Plan has all but GLM-5.3.
42
+ const MODELS = [
43
+ { id: "GLM-5.3", context: 1_000_000, output: 128_000, efforts: ["low", "high", "max"] },
44
+ { id: "GLM-5.3-Flash", context: 1_000_000, output: 128_000, efforts: ["low", "high", "max"] },
45
+ { id: "GLM-5.2", context: 1_000_000, output: 128_000, efforts: ["none", "high", "max"] },
46
+ { id: "GLM-5-Turbo", context: 200_000, output: 64_000, efforts: ["none", "high"] },
47
+ ]
48
+ const START_MODELS = MODELS.filter((m) => m.id !== "GLM-5.3")
49
+
50
+ const SITES = {
51
+ zai: { name: "Z.ai", api: ZAI_API, base: ZAI_BASE, subscribe: "z.ai/subscribe" },
52
+ bigmodel: { name: "BigModel", api: BIGMODEL_API, base: BIGMODEL_BASE, subscribe: "bigmodel.cn/glm-coding" },
53
+ }
54
+ const siteOf = (s) => (s === "bigmodel" ? "bigmodel" : "zai")
55
+
56
+ const platform = () => `${process.platform}-${process.arch}` // darwin-arm64, win32-x64, linux-x64, as ZCode names them
57
+ const uuid = () => crypto.randomUUID()
58
+ const anyDevice = uuid() // X-Device-Mid for calls made signed out (the model list)
59
+ // uuidOf is a version 4 shaped UUID made from a seed: the same seed gives
60
+ // the same UUID every time
61
+ const uuidOf = (seed) => {
62
+ const h = createHash("sha256").update(seed).digest("hex")
63
+ return `${h.slice(0, 8)}-${h.slice(8, 12)}-4${h.slice(13, 16)}-${((parseInt(h[16], 16) & 3) | 8).toString(16)}${h.slice(17, 20)}-${h.slice(20, 32)}`
64
+ }
65
+ // keyDevice is a device id for an account known only by its key: the same
66
+ // key gives the same id on every start, as a sign-in's saved device does
67
+ const keyDevice = (key) => uuidOf("zcode-device\0" + key)
68
+ const first = (...ss) => ss.map((s) => (typeof s === "string" ? s.trim() : "")).find((s) => s) ?? ""
69
+
70
+ // STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a
71
+ // refusal with no message in.
72
+ const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
73
+ 408: "Request Timeout", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable",
74
+ 504: "Gateway Timeout" }
75
+
76
+ class ZError extends Error {
77
+ constructor(message, status) {
78
+ super(message)
79
+ this.status = status
80
+ }
81
+ }
82
+
83
+ // call asks one of Z.ai's JSON endpoints, which wrap what they say in
84
+ // {code, msg, data}: a code of 0 or 200 is a success. zcode.z.ai is told
85
+ // the machine's id (X-Device-Mid), as ZCode tells it.
86
+ async function call(method, url, { auth, body, headers, device, signal } = {}) {
87
+ const h = { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA }
88
+ if (auth) h.Authorization = auth
89
+ if (url.startsWith(ZCODE + "/")) h["X-Device-Mid"] = device || anyDevice
90
+ Object.assign(h, headers ?? {})
91
+ const res = await fetch(url, { method, headers: h, body: body === undefined ? undefined : JSON.stringify(body), signal })
92
+ const text = await res.text()
93
+ let env
94
+ try {
95
+ env = JSON.parse(text)
96
+ } catch {}
97
+ const code = env?.code == null ? "" : String(env.code)
98
+ if (!res.ok) {
99
+ const said = env?.msg ? (code && code !== "0" ? `${env.msg} (${res.status}, code ${code})` : `${env.msg} (${res.status})`) : (STATUS_TEXT[res.status] ?? `${res.status} ${res.statusText}`.trim())
100
+ const err = new ZError(said, res.status)
101
+ err.code = Number(code) || 0 // 3002 and the like: so a caller can tell a rate limit from a failure
102
+ err.retryAfterMs = retryAfterMs(res) // 0 unless the reply carried a Retry-After
103
+ throw err
104
+ }
105
+ if (!env || typeof env !== "object") throw new ZError("not JSON", res.status)
106
+ if (code && code !== "0" && code !== "200") throw new ZError(env.msg || `error ${code}`, res.status)
107
+ return env.data ?? null
108
+ }
109
+
110
+ // ---- the account's plan ----------------------------------------------------------
111
+
112
+ const rootOf = (base) => {
113
+ try {
114
+ const u = new URL(base)
115
+ return `${u.protocol}//${u.host}`
116
+ } catch {
117
+ return ZAI_API
118
+ }
119
+ }
120
+ const isTeam = (s) => !!(s.org && s.project)
121
+
122
+ // plan names the coding plan a key has, "" for none.
123
+ async function plan(s) {
124
+ const subs = (await call("GET", rootOf(s.base) + "/api/biz/subscription/list", { auth: s.key })) ?? []
125
+ return (Array.isArray(subs) ? subs : []).find((x) => String(x.status).toUpperCase() === "VALID")?.productName ?? ""
126
+ }
127
+
128
+ function jwtExpiry(jwt) {
129
+ const p = String(jwt ?? "").split(".")
130
+ if (p.length !== 3) return 0
131
+ try {
132
+ const claims = JSON.parse(Buffer.from(p[1], "base64url").toString("utf8"))
133
+ return Number(claims.exp) > 0 ? Number(claims.exp) * 1000 : 0
134
+ } catch {
135
+ return 0
136
+ }
137
+ }
138
+ const jwtExpired = (jwt) => {
139
+ const t = jwtExpiry(jwt)
140
+ return t > 0 && Date.now() > t
141
+ }
142
+ // EXPIRED is the built-in's words (errZCodeExpired) for a Start Plan
143
+ // sign-in past its end.
144
+ const EXPIRED = "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)"
145
+
146
+ const num = (v) => {
147
+ const n = typeof v === "string" ? parseFloat(v) : v
148
+ return typeof n === "number" && Number.isFinite(n) ? n : undefined
149
+ }
150
+
151
+ // the alias is the catalog spelling of the model plus -trial, so the picker
152
+ // reads GLM-5.3-Trial while the loader strips it back to the raw name
153
+ const giftID = (m) => (MODELS.find((x) => x.id.toLowerCase() === String(m).toLowerCase())?.id ?? m) + "-Trial"
154
+ const uniqueModels = (names) => {
155
+ const byName = new Map()
156
+ for (const m of names) if (!byName.has(m.toLowerCase())) byName.set(m.toLowerCase(), m)
157
+ return [...byName.values()]
158
+ }
159
+ const giftNames = (g) => g?.allModels ?? g?.models ?? []
160
+ // wireModel is a gift model as ZCode sends it: the buckets name it lowercased
161
+ // ("glm-5.3-flash"), the app's request carries its registry id
162
+ // ("GLM-5.3-Flash"; normalizeOfficialGlmModelId's spelling). Names ZCode
163
+ // does not know go as the bucket wrote them.
164
+ const wireModel = (m) => MODELS.find((x) => x.id.toLowerCase() === String(m).toLowerCase())?.id ?? m
165
+ const giftModel = (g, id) => giftNames(g).find((m) => giftID(m).toLowerCase() === id.toLowerCase())
166
+ const bucketModels = (x) => (Array.isArray(x.capabilities) ? x.capabilities : [])
167
+ .map((c) => String(c ?? "").trim()).filter((c) => c.startsWith("model:") || !c.includes(":"))
168
+ .map((c) => c.replace(/^model:/, "").trim()).filter(Boolean)
169
+
170
+ // Both the card and the request route use the same test for a spent bucket.
171
+ // Older balances may omit remaining_units but still tell used and total.
172
+ const giftSpent = (x) => {
173
+ const left = num(x.remaining_units)
174
+ if (left !== undefined) return left <= 0
175
+ const total = num(x.total_units), used = num(x.used_units)
176
+ return total !== undefined && used !== undefined && used >= total
177
+ }
178
+
179
+ // startPlan is the gift an account can spend now ({models}), as ZCode reads
180
+ // its balance: several plans can be active at once, and a model routes to
181
+ // the gift when any of them has a live bucket serving it — a bucket past
182
+ // its plan's own end, or one whose remaining_units says none, is skipped
183
+ // rather than asked and refused. models are those live buckets' names.
184
+ //
185
+ // coming (sign-in only) also takes a plan that has not started yet, as
186
+ // ZCode's own check does (resolveStartPlanBalanceAvailability's "pending"
187
+ // counts as entitled): {name, models: [], coming: true}. Requests and the
188
+ // card never ask for it: a plan not started serves nothing yet.
189
+ async function startPlan(jwt, device, coming = false) {
190
+ if (!jwt) throw new Error("not signed in to ZCode")
191
+ if (jwtExpired(jwt)) throw new Error(EXPIRED)
192
+ const b = (await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/balance?app_version=${APP_VERSION}`, { auth: "Bearer " + jwt, device })) ?? {}
193
+ const now = num(b.server_time) > 0 ? num(b.server_time) : Date.now() / 1000
194
+ const same = (x, p) => (x.user_plan_id && p.user_plan_id ? x.user_plan_id === p.user_plan_id : String(x.plan_id ?? "") === String(p.plan_id ?? ""))
195
+ const plans = Array.isArray(b.plans) ? b.plans : []
196
+ const balances = Array.isArray(b.balances) ? b.balances : []
197
+ const ms = new Set(), all = new Map()
198
+ let ttl = 600_000
199
+ let any = false
200
+ let name = ""
201
+ for (const p of plans) {
202
+ const st = String(p?.status ?? "").trim().toLowerCase()
203
+ const end = num(p?.ends_at)
204
+ if (st !== "active" || (end > 0 && end <= now) || notStarted(p, now)) continue
205
+ any = true
206
+ if (end > 0) ttl = Math.min(ttl, (end - now) * 1000)
207
+ if (!name) name = String(p?.name ?? "").trim()
208
+ for (const x of balances) {
209
+ if (!same(x, p)) continue
210
+ const exp = num(x.expires_at)
211
+ if (exp > 0 && exp <= now) continue
212
+ if (exp > 0) ttl = Math.min(ttl, (exp - now) * 1000)
213
+ // Spent buckets still declare models; only live ones can spend now.
214
+ for (const m of bucketModels(x)) {
215
+ if (!all.has(m.toLowerCase())) all.set(m.toLowerCase(), m)
216
+ if (!giftSpent(x)) ms.add(m)
217
+ }
218
+ }
219
+ }
220
+ if (any) return { name: name || "Start Plan", models: [...ms], allModels: [...all.values()], ttl }
221
+ if (!coming) return null
222
+ const next = plans.filter((p) => notStarted(p, now) && !(num(p?.ends_at) > 0 && num(p?.ends_at) <= now))
223
+ .sort((a, b) => startNum(a.starts_at) - startNum(b.starts_at))[0]
224
+ return next ? { name: String(next.name ?? "").trim() || "Start Plan", models: [], allModels: [], ttl, coming: true } : null
225
+ }
226
+
227
+ // plansOf says where an account's requests go and what more it can spend:
228
+ // {start, gift}. start is what onStart said: an account with no coding plan
229
+ // sends every request to the gift and reads no balance to do it; a
230
+ // sign-in with no ZCode token and a key whose plan-list read found
231
+ // no gift stay on the coding plan. gift is what a coding account also holds:
232
+ // the gift plans ({models}), and its requests spend the gift for a model it
233
+ // serves, until it says it is spent (see blocked). Asked again after 10
234
+ // minutes (a minute when unsure — a plan-list read that failed is retried
235
+ // sooner; a gift read that failed simply leaves gift null until the next
236
+ // ask).
237
+ const routes = new Map()
238
+ async function plansOf(s) {
239
+ if (!s.jwt) return { start: false, gift: null }
240
+ if (!s.key && !isTeam(s)) return { start: true, gift: null }
241
+ const id = s.key + "\0" + s.jwt
242
+ const r = routes.get(id)
243
+ if (r && Date.now() - r.at < r.ttl) return r
244
+ let start = false
245
+ let gift = null
246
+ let sure = false
247
+ try {
248
+ // A team seat stays on its team even when its personal plan list is
249
+ // empty. Its ZCode session still holds the person's gift plans.
250
+ if (!isTeam(s) && !(await plan(s))) start = true
251
+ else {
252
+ // a gift read that failed is unknown, not "no gift": asked again in
253
+ // a minute, so its trial entries come back with the next list (an
254
+ // expired session is known: the card says to sign in again)
255
+ let failed = false
256
+ gift = await startPlan(s.jwt, s.device).catch(() => ((failed = !jwtExpired(s.jwt)), null))
257
+ sure = !failed
258
+ }
259
+ // a key whose plan list read no plan, where the last read found one,
260
+ // is asked again in a minute rather than sent to the Start Plan for
261
+ // ten: one list without the plan (a renewal's boundary, a hiccup)
262
+ // turned a GLM Coding Plan account's every request into the Start
263
+ // Plan's 405 until the route was read again (#369)
264
+ if (start) sure = !(s.key && r && !r.start)
265
+ } catch {
266
+ // the plan list could not be read. An account the last read found with
267
+ // no coding plan stays on the Start Plan for the minute: the dual route
268
+ // would send its key to the coding plan's host, which bills a key with
269
+ // no plan pay-as-you-go while the free quota sits unspent (bg5eau on
270
+ // X). Any other key account takes the dual route (start stays false,
271
+ // the gift is kept, a minute's ttl), so a gift refusal still replays to
272
+ // the coding plan rather than blacking out
273
+ if (r?.start) start = true
274
+ else {
275
+ try {
276
+ gift = await startPlan(s.jwt, s.device)
277
+ } catch {}
278
+ }
279
+ sure = false
280
+ }
281
+ const out = { start, gift, at: Date.now(), ttl: Math.min(sure ? 600_000 : 60_000, gift?.ttl ?? 600_000) }
282
+ routes.set(id, out)
283
+ return out
284
+ }
285
+
286
+ // blocked remembers the models a gift said it has none left for: a key+jwt+
287
+ // model for a minute, so one turn that is refused does not ask again.
288
+ const blocked = new Map()
289
+ // sidelined remembers, the same way, the models whose gift turned free
290
+ // first away for another reason (a 405/3012, a block page): free first
291
+ // leaves them on the plan for the minute, but a -Trial entry, the user's
292
+ // own pick of the gift, still asks ZCode and gets its real answer. Once
293
+ // one rest served both, and a refusal under free first answered the
294
+ // Trial entry locally as a quota "exhausted" it never was (Can4ry_ on X).
295
+ const sidelined = new Map()
296
+ const rest = (map, k) => {
297
+ for (const [x, until] of map) if (Date.now() >= until) map.delete(x)
298
+ map.set(k, Date.now() + 60_000)
299
+ }
300
+
301
+ // giftServes: the gift's buckets name their models lowercased ("glm-5.3-
302
+ // flash"); what is asked for arrives as the plan lists it ("GLM-5.3-Flash").
303
+ const giftServes = (gift, m) => (gift.models ?? []).some((x) => x.toLowerCase() === m.toLowerCase())
304
+ const giftRested = (s, m) => Date.now() < (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
305
+ const giftUsable = (s, gift, m) => !jwtExpired(s.jwt) && giftServes(gift, m) &&
306
+ Date.now() >= (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
307
+ const giftSidelined = (s, m) => Date.now() < (sidelined.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
308
+
309
+ // spentUp is the gift saying it has nothing left to spend: its own no-
310
+ // resource-package code 1113, its "exceed quota limit" 1005 — a spent gift
311
+ // can answer a 200 with a JSON body carrying one of those codes. Every other
312
+ // 429 counts as spent, Z.ai's 1302/1303 rate limits among them; the plan's
313
+ // own in-flight cap (3008/3009) does not, since it is a turn not yet come.
314
+ function spentUp(text, status) {
315
+ if (busy(status, text)) return false
316
+ if (status === 429) return true
317
+ let b
318
+ try { b = JSON.parse(text) } catch { return false }
319
+ if (!b || typeof b !== "object") return false
320
+ const code = (v) => String(v ?? "")
321
+ const c1 = code(b.code), c2 = code(b.error?.code)
322
+ return c1 === "1113" || c1 === "1005" || c2 === "1113" || c2 === "1005"
323
+ }
324
+
325
+ // spentSaid is an answer that carries spentUp's code inside a 200, as a
326
+ // spent bucket's can, said as the 429 it is (plugins#817: a Start Plan
327
+ // account's GLM-5.3 out for the day answered 200 "exceed quota limit",
328
+ // which magpie took for a reply that did not stream and rested the whole
329
+ // account, GLM-5.3-Flash's own bucket with it). Any other answer goes on
330
+ // as it came; a stream's body is never read here.
331
+ async function spentSaid(res) {
332
+ if (res.status >= 400 || !(res.headers.get("content-type") ?? "").includes("application/json")) return res
333
+ const text = await res.text()
334
+ const status = spentUp(text, res.status) ? 429 : res.status
335
+ return new Response(text, { status, statusText: status === 429 ? "Too Many Requests" : res.statusText, headers: res.headers })
336
+ }
337
+
338
+ // ---- keys ------------------------------------------------------------------------
339
+
340
+ function teamHeaders(base, org, project) {
341
+ return {
342
+ "Bigmodel-Organization": org,
343
+ "Bigmodel-Project": project,
344
+ "Set-Language": base.includes("bigmodel.cn") ? "zh" : "en",
345
+ "Accept-Language": "en-US,en",
346
+ }
347
+ }
348
+
349
+ const keysURL = (root, org, project) =>
350
+ `${root}/api/biz/v1/organization/${encodeURIComponent(org)}/projects/${encodeURIComponent(project)}/api_keys`
351
+
352
+ // projectKey finds the project's key named want.name (of want.keyType, when
353
+ // given), makes it when it isn't there and reads its secret: `<id>.<secret>`.
354
+ async function projectKey(site, keys, auth, headers, want) {
355
+ const name = SITES[site].name
356
+ let list
357
+ try {
358
+ list = (await call("GET", keys, { auth, headers })) ?? []
359
+ } catch (e) {
360
+ throw new Error(`${name} API keys: ${e.message}`)
361
+ }
362
+ const typed = "keyType" in want
363
+ let id = ""
364
+ for (const k of Array.isArray(list) ? list : []) {
365
+ if (k.name === want.name && (!typed || String(k.keyType) === String(want.keyType)) && first(k.apiKey)) id = first(k.apiKey)
366
+ }
367
+ if (!id) {
368
+ try {
369
+ id = first((await call("POST", keys, { auth, headers, body: want }))?.apiKey)
370
+ } catch (e) {
371
+ throw new Error(`${name} API key: ${e.message}`)
372
+ }
373
+ }
374
+ let secret = ""
375
+ if (id) {
376
+ try {
377
+ secret = first((await call("GET", `${keys}/copy/${encodeURIComponent(id)}`, { auth, headers }))?.secretKey)
378
+ } catch (e) {
379
+ throw new Error(`${name} API key: ${e.message}`)
380
+ }
381
+ }
382
+ if (id && !secret && typed) return id // a team's key with no secret goes as it is
383
+ if (!id || !secret) throw new Error(`${name} gave no API key`)
384
+ return `${id}.${secret}`
385
+ }
386
+
387
+ // teamKey is a team seat's key when the sign-in kept none.
388
+ const teamKeys = new Map()
389
+ async function teamKey(s) {
390
+ if (s.key) return s.key
391
+ const id = [s.token, s.org, s.project].join("\0")
392
+ const got = teamKeys.get(id)
393
+ if (got && (!got.err || Date.now() - got.at < 60_000)) {
394
+ if (got.err) throw got.err
395
+ return got.key
396
+ }
397
+ const site = s.base.includes("bigmodel.cn") ? "bigmodel" : "zai"
398
+ try {
399
+ const key = await projectKey(site, keysURL(SITES[site].api, s.org, s.project), s.token, teamHeaders(s.base, s.org, s.project), { name: "zcode-team-api-key", keyType: 2 })
400
+ teamKeys.set(id, { key, at: Date.now() })
401
+ return key
402
+ } catch (e) {
403
+ const err = new Error(`ZCode's team plan: ${e.message} — sign in to ZCode again`)
404
+ teamKeys.set(id, { err, at: Date.now() })
405
+ throw err
406
+ }
407
+ }
408
+
409
+ // ---- allowance ---------------------------------------------------------------------
410
+ // As magpie's built-in told it (internal/provider zcode.go, zcode_start.go,
411
+ // zcode_team.go): the Coding Plan's windows and term, the Start Plan's
412
+ // buckets, or a team seat's windows and its plan's end.
413
+
414
+ // bizRoot is the business API of the site a plan is served from.
415
+ function bizRoot(base) {
416
+ let h = ""
417
+ try {
418
+ h = new URL(base).host.toLowerCase()
419
+ } catch {}
420
+ return h === new URL(BIGMODEL_BASE).host || h.endsWith("bigmodel.cn") ? BIGMODEL_API : rootOf(base)
421
+ }
422
+
423
+ // spanOf reads a limit's window, in seconds: unit 3 counts hours, 6 weeks
424
+ // (and 1, 4, 5 minutes, days and months by the same count). A team's five
425
+ // hours come with no count.
426
+ function spanOf(unit, n) {
427
+ n = Math.trunc(Number(n) || 0)
428
+ if (unit === 3 && n <= 0) n = 5
429
+ n = Math.max(n, 1)
430
+ return { 1: 60, 3: 3600, 4: 86400, 5: 30 * 86400, 6: 7 * 86400 }[unit] * n || 0
431
+ }
432
+
433
+ function windowName(span) {
434
+ if (span === 0) return "Credits"
435
+ if (span < 86400) return `${Math.trunc(span / 3600)} hours`
436
+ if (span === 7 * 86400) return "Weekly"
437
+ if (span >= 28 * 86400) return "Monthly"
438
+ return `${Math.trunc(span / 86400)} days`
439
+ }
440
+
441
+ // compact is a count as magpie says one: whole, else to two places.
442
+ const compact = (n) => (Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/0+$/, "").replace(/\.$/, ""))
443
+ const isNum = (v) => typeof v === "number" && Number.isFinite(v)
444
+
445
+ // limitWindows are /api/monitor/usage/quota/limit's limits as windows: what
446
+ // is used of the whole when both are told (the whole less what remains, or
447
+ // the current value), else the percentage given. TIME_LIMIT is the month's
448
+ // MCP tool calls, which ZCode shows but never stops the models on, so it is
449
+ // set aside, as is a limit whose whole is told as 0: no cap (an older
450
+ // plan's), which the vendor may still give as 100% used. A window whose
451
+ // count is told carries it as amount of limit, so magpie's card says the
452
+ // count as used or as left, as it says the share beside it (#659).
453
+ function limitWindows(d) {
454
+ const out = []
455
+ for (const x of d?.limits ?? []) {
456
+ const span = spanOf(Math.trunc(Number(x?.unit) || 0), x?.number)
457
+ const w = { name: windowName(span), used: 0 }
458
+ if (String(x?.type ?? "").toUpperCase() === "TIME_LIMIT") (w.name = "MCP · Month"), (w.aside = true)
459
+ if (isNum(x?.percentage)) w.used = x.percentage
460
+ if (x?.usage === 0) (w.used = 0), (w.aside = true)
461
+ if (isNum(x?.usage) && x.usage > 0) {
462
+ const total = x.usage
463
+ if (isNum(x.remaining)) {
464
+ const used = total - x.remaining
465
+ w.used = (100 * used) / total
466
+ w.amount = used
467
+ w.limit = total
468
+ w.display = `${compact(used)} / ${compact(total)}`
469
+ } else if (isNum(x.currentValue)) {
470
+ if (!isNum(x.percentage)) w.used = (100 * x.currentValue) / total
471
+ w.amount = x.currentValue
472
+ w.limit = total
473
+ w.display = `${compact(x.currentValue)} / ${compact(total)}`
474
+ }
475
+ }
476
+ const reset = Math.trunc(Number(x?.nextResetTime) || 0)
477
+ if (reset > 0) w.resetsAt = new Date(reset).toISOString()
478
+ if (span) w.span = span
479
+ out.push(w)
480
+ }
481
+ return out
482
+ }
483
+
484
+ // beijing reads the plan's times, "2026-10-18 12:00:00" in Beijing: ms, or 0.
485
+ function beijing(s) {
486
+ s = String(s ?? "").trim().replace(" ", "T")
487
+ if (!/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2})?$/.test(s)) return 0
488
+ const t = Date.parse(s + (s.length === 10 ? "T00:00:00" : "") + "+08:00")
489
+ return Number.isFinite(t) ? t : 0
490
+ }
491
+
492
+ // termOf is how long a GLM Coding plan is paid for: the valid
493
+ // subscription's next renewal, a charge when it renews itself, else the
494
+ // end of its time, the last date its "valid" span names.
495
+ function termOf(subs) {
496
+ for (const x of Array.isArray(subs) ? subs : []) {
497
+ if (String(x?.status ?? "").toUpperCase() !== "VALID") continue
498
+ const auto = x.autoRenew === true || x.autoRenew === 1
499
+ const t = beijing(typeof x.nextRenewTime === "string" ? x.nextRenewTime : "")
500
+ if (t) return { until: new Date(t).toISOString(), renew: auto ? "auto" : "off" }
501
+ const ds = String(typeof x.valid === "string" ? x.valid : "").match(/\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?/g) ?? []
502
+ if (ds.length && !auto) {
503
+ const end = beijing(ds[ds.length - 1])
504
+ if (end) return { until: new Date(end).toISOString(), renew: "off" }
505
+ }
506
+ return {}
507
+ }
508
+ return {}
509
+ }
510
+
511
+ // codingUsage is a Coding Plan key's allowance: credits per five hours and
512
+ // per week, the plan's level and its term.
513
+ async function codingUsage(s) {
514
+ const root = rootOf(s.base)
515
+ const d = (await call("GET", root + "/api/monitor/usage/quota/limit", { auth: s.key })) ?? {}
516
+ const out = {}
517
+ const level = typeof d.level === "string" ? d.level : ""
518
+ if (level) out.plan = "GLM Coding " + level[0].toUpperCase() + level.slice(1)
519
+ out.windows = limitWindows(d)
520
+ notePlan(s.key, out.windows)
521
+ const resets = personalResets(root, s.key)
522
+ let subs = null
523
+ try {
524
+ subs = await call("GET", root + "/api/biz/subscription/list", { auth: s.key })
525
+ Object.assign(out, termOf(subs))
526
+ } catch {}
527
+ const r = await resets
528
+ if (r) out.resets = r
529
+ // a key whose account has no plan in force, read as such, says so
530
+ // rather than showing an empty card: what a key can spend is a GLM
531
+ // Coding Plan alone (a ZCode gift plan is never one, see NO_PLAN_KEY).
532
+ // A list that couldn't be read, a level, a counted window or a plan
533
+ // the sign-in saved keeps the card as it was.
534
+ const valid = (Array.isArray(subs) ? subs : []).some((x) => String(x?.status ?? "").toUpperCase() === "VALID")
535
+ if (subs !== null && !valid && !level && !s.plan && !out.windows.some((w) => !w.aside)) return { error: NO_PLAN_KEY }
536
+ return out
537
+ }
538
+
539
+ // NO_PLAN_KEY is a key with no GLM Coding Plan behind it. ZCode's gift
540
+ // plans (its Start Plan, ZCode 1024 Dev Day) are served by zcode.z.ai
541
+ // to ZCode's own session token, which a sign-in with ZCode (the app's,
542
+ // or Z.ai's or BigModel's in the browser) carries and a key never does:
543
+ // with a key, a gift-only account has nothing to spend, and Z.ai answers
544
+ // each request 1113 (rtbeilin on X, 10-24).
545
+ const NO_PLAN_KEY =
546
+ "this key's account has no GLM Coding Plan; ZCode's gift plans (the Start Plan, ZCode 1024 Dev Day) are spent only with ZCode's sign-in, never with a key — add the account with \"ZCode app's sign-in\" or a ZCode sign-in in the browser"
547
+
548
+ // noPlanKey is a coding plan's 1113 refusal (no plan, no resource
549
+ // package) to a sign-in with no ZCode session, its message followed by
550
+ // NO_PLAN_KEY; anything else goes on as it came. Read only once the
551
+ // answer has failed.
552
+ function noPlanKey(res, text) {
553
+ let v
554
+ try {
555
+ v = JSON.parse(text)
556
+ } catch {
557
+ return null
558
+ }
559
+ // Z.ai names the code in error.code ("1113", as magpie's
560
+ // zhipu_coding_test has it) or error.type (its 401's "1000"), BigModel's
561
+ // envelope in code
562
+ if (![v?.error?.code, v?.error?.type, v?.code].some((c) => String(c ?? "") === "1113")) return null
563
+ const said = first(v?.error?.message, v?.msg, v?.message)
564
+ const out = v?.error && typeof v.error === "object" ? { ...v, error: { ...v.error, message: (said ? said + " — " : "") + NO_PLAN_KEY } } : { ...v, msg: (said ? said + " — " : "") + NO_PLAN_KEY }
565
+ const h = new Headers(res.headers)
566
+ h.set("content-type", "application/json")
567
+ return new Response(JSON.stringify(out), { status: res.status, statusText: res.statusText, headers: h })
568
+ }
569
+
570
+ // startNum reads a number the balance gives as a number or a string.
571
+ function startNum(v) {
572
+ if (isNum(v)) return v
573
+ if (typeof v === "string" && v.trim() !== "") {
574
+ const n = Number(v.trim())
575
+ if (!Number.isNaN(n)) return n
576
+ }
577
+ return undefined
578
+ }
579
+
580
+ // notStarted is a plan whose starts_at is still to come (a Start Plan
581
+ // that takes effect at 23:00 today, windy on Discord): it serves nothing
582
+ // yet, so no request is routed to it and its buckets don't count, but the
583
+ // card names it with its start. ZCode's balance gives every plan a
584
+ // starts_at in Unix seconds; which status a plan not started yet carries
585
+ // is not known, so any but "expired" is taken.
586
+ function notStarted(p, now) {
587
+ const at = startNum(p?.starts_at)
588
+ return at > now && String(p?.status ?? "").trim().toLowerCase() !== "expired"
589
+ }
590
+
591
+ // PENDING is the card's line for a gift plan that has not started yet: a
592
+ // fixed sentence, so magpie translates it; the plan's name and its start,
593
+ // in this computer's time, are the display. Set aside: it stops nothing.
594
+ const PENDING = "ZCode gift plan not started yet"
595
+ const two = (n) => String(n).padStart(2, "0")
596
+ const localTime = (sec) => {
597
+ const d = new Date(Math.trunc(sec) * 1000)
598
+ return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`
599
+ }
600
+ const pendingLines = (g) => (g?.pending ?? []).map((p) => ({ name: PENDING, used: 0, aside: true, display: `${p.name} · ${localTime(p.start)}` }))
601
+
602
+ // giftOf reads the balance and returns the gift's card fields: its plans and
603
+ // windows. Several plans can be active at once, so every live plan's buckets
604
+ // show, each keeping its own models and end; the plan and end put on the
605
+ // card (for a gift-only account) are the soonest-ending live plan's. null
606
+ // when there is no live plan to show.
607
+ async function giftOf(s) {
608
+ if (!s.jwt) throw new Error("not signed in to ZCode")
609
+ if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
610
+ const b = (await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/balance?app_version=${APP_VERSION}`, { auth: "Bearer " + s.jwt, device: s.device })) ?? {}
611
+ const str = (v) => (typeof v === "string" ? v : "")
612
+ const plans = (Array.isArray(b.plans) ? b.plans : []).map((p) => ({ ...p, status: str(p?.status), user_plan_id: str(p?.user_plan_id), plan_id: str(p?.plan_id) }))
613
+ const now = startNum(b.server_time) > 0 ? startNum(b.server_time) : Math.trunc(Date.now() / 1000)
614
+ const over = new Set()
615
+ for (const p of plans) {
616
+ const end = startNum(p.ends_at)
617
+ if (end > 0 && end <= now && p.status.trim().toLowerCase() === "active") p.status = "expired"
618
+ if (p.status.trim().toLowerCase() === "expired") over.add(p.user_plan_id + "\0" + p.plan_id)
619
+ }
620
+ const same = (x, p) => (x.user_plan_id && p.user_plan_id ? x.user_plan_id === p.user_plan_id : String(x.plan_id ?? "") === String(p.plan_id ?? ""))
621
+ const balances = (Array.isArray(b.balances) ? b.balances : [])
622
+ .map((x) => ({ ...x, user_plan_id: str(x?.user_plan_id), plan_id: str(x?.plan_id) }))
623
+ .filter((x) => {
624
+ let keep = true
625
+ for (const p of plans) {
626
+ if (!same(x, p)) continue
627
+ keep = !over.has(p.user_plan_id + "\0" + p.plan_id)
628
+ if (keep) break
629
+ }
630
+ return keep
631
+ })
632
+
633
+ // a plan not started yet is named with its start, soonest first; its
634
+ // buckets, if the balance lists any, wait for it
635
+ const pending = plans.filter((p) => notStarted(p, now))
636
+ .map((p) => ({ name: first(str(p.name), "Start Plan"), start: startNum(p.starts_at) }))
637
+ .sort((a, b) => a.start - b.start)
638
+
639
+ // every live plan counts as the gift: no plan-name filter decides it,
640
+ // the balance says what the session can spend
641
+ let active = null
642
+ for (const p of plans) {
643
+ if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) continue
644
+ const end = startNum(p.ends_at)
645
+ if (end > 0 && end <= now) continue
646
+ if (active && !(end > 0 && (!startNum(active.end) || end < startNum(active.end)))) continue
647
+ active = { name: first(str(p.name), "Start Plan"), end, until: end > 0 ? new Date(Math.trunc(end) * 1000).toISOString() : "" }
648
+ }
649
+ if (!active && !pending.length) return null
650
+ // with no live plan, the one starting soonest names the card
651
+ const out = { plan: active?.name ?? pending[0].name, windows: [], live: !!active, pending }
652
+ if (active?.until) Object.assign(out, { until: active.until, renew: "off" })
653
+ const live = plans.filter((p) => {
654
+ if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) return false
655
+ const end = startNum(p.ends_at)
656
+ return !(end > 0 && end <= now)
657
+ })
658
+ for (const x of balances) {
659
+ const owner = live.find((p) => same(x, p))
660
+ if (!owner) continue
661
+ const exp = startNum(x.expires_at)
662
+ if (exp > 0 && exp <= now) continue // a bucket past its own end is over
663
+ const total = startNum(x.total_units), left = startNum(x.remaining_units)
664
+ let used = startNum(x.used_units)
665
+ if (total === undefined && used === undefined && left === undefined) continue
666
+ const models = bucketModels(x)
667
+ const base = first(str(x.show_name), models.join(", "), "Credits")
668
+ const w = { name: base, used: 0, _plan: str(owner.name), _spent: giftSpent(x) }
669
+ if (used === undefined) used = total !== undefined && left !== undefined ? total - left : 0
670
+ if (total > 0) {
671
+ // the bucket's count as amount of limit, as the Coding windows' is
672
+ // (#659): magpie says it as used or as left, as it says the share
673
+ w.used = (100 * used) / total
674
+ w.amount = used
675
+ w.limit = total
676
+ w.display = `${compact(used)} / ${compact(total)}`
677
+ }
678
+ if (w._spent) w.used = Math.max(100, w.used)
679
+ if (exp > 0) w.resetsAt = new Date(Math.trunc(exp) * 1000).toISOString()
680
+ let span = 0
681
+ for (const p of plans) {
682
+ if (!same(x, p)) continue
683
+ for (const e of Array.isArray(p.entitlements) ? p.entitlements : []) {
684
+ if (str(e?.entitlement_id) === str(x.entitlement_id)) span = periodOf(str(e?.period))
685
+ }
686
+ }
687
+ if (!span) {
688
+ const a = startNum(x.period_start), z = startNum(x.period_end)
689
+ if (a !== undefined && z !== undefined && z > a) span = Math.trunc(z - a)
690
+ }
691
+ if (span) w.span = span
692
+ if (models.length) w.models = models
693
+ out.windows.push(w)
694
+ }
695
+ return out
696
+ }
697
+
698
+ // CLAIM_HINT is the claim line's name: a fixed sentence, so magpie
699
+ // translates it with the interface's own language (the plan's name and
700
+ // the count are data, and go in the display, which is shown as it came).
701
+ const CLAIM_HINT = "Gift plans to claim in the ZCode app"
702
+
703
+ // claimHint is the card's line for gift plans ZCode is holding for the
704
+ // account but has not put on it: the app's banners (marketing/touch)
705
+ // list them (toClaim). The
706
+ // card only names them: they are claimed in the ZCode app, or by the
707
+ // daily claim (claimDaily) when the user turned it on; on 10-06 a claim
708
+ // without the app's Aliyun captcha attestation was refused (3007). A window, set aside (it is no
709
+ // allowance: using it up stops nothing), so the card shows it and
710
+ // routing, caps and the menu bar pass it over. The window's name is a
711
+ // fixed sentence, so magpie can translate it (a display is shown as it
712
+ // came); the count and the plan's own name go in the display. null when
713
+ // there is nothing to claim, the preview failing or listing none among
714
+ // it: a failed read is no line at all, never a card or a refusal of its
715
+ // own.
716
+ async function claimHint(s) {
717
+ if (!s.jwt || jwtExpired(s.jwt)) return null
718
+ const { plans } = await toClaim(s)
719
+ if (!plans.length) return null
720
+ const n = plans.length
721
+ const plan = first(...plans.map((p) => p.name), "ZCode gift plan")
722
+ return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` }
723
+ }
724
+
725
+ // unclaimed names the gift plans ZCode holds for the account but has not
726
+ // put on it (toClaim), for a -Trial pick that finds no gift: the weekend
727
+ // plan (ZCODE WEEKEND BUILD) comes only by a claim, and the claim needs
728
+ // the ZCode app's captcha (claimDaily posts none), so until it is
729
+ // claimed in the app the pick's quota does not exist yet (heduian and
730
+ // bg5eau on X, 11-14). The refusal says where the quota is rather than
731
+ // only that there is none. Kept ten minutes per session, so an agent
732
+ // retrying the pick doesn't read the feed each time; a read that fails
733
+ // names none and is not kept.
734
+ // aloneSeen is a gift-only account's balance as last read (the model list
735
+ // reads it), kept ten minutes. A request reads no balance on its own: only
736
+ // a model the kept balance doesn't name has it read again (aloneGift), so
737
+ // a gift claimed since is not refused. A read that fails is not kept.
738
+ const aloneSeen = new Map()
739
+ const aloneNames = (s) => {
740
+ const c = aloneSeen.get(s.jwt)
741
+ return c && Date.now() - c.at < 600_000 ? giftNames(c.gift) : []
742
+ }
743
+ async function aloneGift(s) {
744
+ let gift
745
+ try {
746
+ gift = await startPlan(s.jwt, s.device)
747
+ } catch {
748
+ return null
749
+ }
750
+ aloneSeen.set(s.jwt, { at: Date.now(), gift })
751
+ return gift
752
+ }
753
+
754
+ const unclaimedSeen = new Map()
755
+ async function unclaimed(s) {
756
+ if (!s.jwt || jwtExpired(s.jwt)) return []
757
+ const k = s.jwt
758
+ const c = unclaimedSeen.get(k)
759
+ if (c && Date.now() - c.at < 600_000) return c.names
760
+ const got = await toClaim(s).catch(() => null)
761
+ if (!got || got.unread.length) return []
762
+ const names = uniqueModels(got.plans.map((p) => first(p.name, p.plan_id)).filter(Boolean))
763
+ unclaimedSeen.set(k, { at: Date.now(), names })
764
+ return names
765
+ }
766
+
767
+ // ---- the daily claim ---------------------------------------------------------------
768
+
769
+ // CLAIMED_ALREADY is /billing/claim's body code for a plan the account
770
+ // has claimed before: HTTP 200 {"code":1003,"msg":"target already
771
+ // exists"} (magpie-community/plugins#503, a real reply), the desktop
772
+ // app's manualClaimPlan.claim.failure.alreadyClaimed. CAPTCHA is its
773
+ // answer to a claim without the Aliyun captcha attestation the ZCode app's
774
+ // renderer makes: HTTP 400 {"code":3007,"msg":"captcha verify failed"}
775
+ // (seen 10-06, #30).
776
+ const CLAIMED_ALREADY = 1003
777
+ const CAPTCHA = 3007
778
+ // NOT_ELIGIBLE is /billing/claim's body code for a plan the account is not
779
+ // offered at that moment: HTTP 400 {"code":1004,…}. A stale APP_VERSION
780
+ // answers it for every account at once (11-04: six accounts all answered
781
+ // 1004 under 3.16.3's header, and four of them claimed with code 0 under
782
+ // 3.17.2's, one night, with nothing else changed).
783
+ const NOT_ELIGIBLE = 1004
784
+ // RATE_LIMITED is Z.ai's "请求过于频繁" body code, its answer (with HTTP
785
+ // 429) to a client that asked too often. #503 (MiniFullC, 11-04) read 180
786
+ // "gift plans to claim: Too Many Requests" over four days at magpie's
787
+ // 30-minute retry, so asking again the same half hour keeps the limit on.
788
+ // magpie asks a failed again once retryAfter() has passed, whatever the
789
+ // answer's `until` says (the contract reads `until` as when an answer
790
+ // stops standing, not as the earliest time to ask again), so the account
791
+ // is held here instead: while the wait lasts, claimDaily answers the same
792
+ // failed again, `until` and all, and asks ZCode nothing. A Retry-After
793
+ // ZCode sent is honored up to RATE_LIMIT_MAX_MS; without one the
794
+ // account's own wait doubles from RECHECK_MS, and a read that comes
795
+ // through forgets it.
796
+ const RATE_LIMITED = 3002
797
+ const RATE_LIMIT_MAX_MS = 6 * 60 * 60_000
798
+ const rateWait = new Map() // s.key -> { ms, until, message }: the hold this account is under
799
+ // resetRateWait is for tests: it forgets the holds, and with `expire` it
800
+ // back-dates them, standing where the wait has passed. The plugin itself
801
+ // forgets a hold by reading through or by waiting it out, never by calling
802
+ // this.
803
+ export function resetRateWait(expire = false) {
804
+ if (!expire) {
805
+ rateWait.clear()
806
+ return
807
+ }
808
+ for (const [k, h] of rateWait) rateWait.set(k, { ...h, until: new Date(Date.now() - 1).toISOString() })
809
+ }
810
+ // holdKey names the account a wait belongs to. stateOf gives key: "" to a
811
+ // sign-in that has a jwt and no API key — the Start-Plan-only sign-ins
812
+ // that claim gift plans, #503's case — so the key alone would put every
813
+ // one of them under a single hold, and one account's 429 would answer for
814
+ // all of them. The jwt tells them apart; a renewed token starting its own
815
+ // wait is fine.
816
+ const holdKey = (s) => s.key || s.jwt
817
+ // retryAfterMs is a Retry-After header, in seconds or as an HTTP date, in
818
+ // ms; 0 when there is none or it doesn't read.
819
+ function retryAfterMs(res) {
820
+ const v = first(res?.headers?.get?.("retry-after"))
821
+ if (!v) return 0
822
+ const secs = Number(v)
823
+ if (Number.isFinite(secs) && secs > 0) return secs * 1000
824
+ const at = Date.parse(v)
825
+ return Number.isFinite(at) ? Math.max(0, at - Date.now()) : 0
826
+ }
827
+ // noteRateLimit remembers the wait this account is under, with the failed
828
+ // that wait answers with, and says when it ends: a Retry-After ZCode sent
829
+ // is taken as it is, up to the cap; without one the wait doubles from
830
+ // RECHECK_MS (and never falls below it), so a client ZCode keeps turning
831
+ // away asks less and less.
832
+ function noteRateLimit(key, saidMs, message) {
833
+ const last = rateWait.get(key)?.ms ?? 0
834
+ const want = saidMs > 0 ? saidMs : Math.max(RECHECK_MS, last * 2)
835
+ const ms = Math.min(RATE_LIMIT_MAX_MS, want)
836
+ const until = new Date(Date.now() + ms).toISOString()
837
+ rateWait.set(key, { ms, until, message })
838
+ return until
839
+ }
840
+ const CAPTCHA_WORDS = /captcha/i
841
+
842
+ // claimNeedsCaptcha says whether ZCode's claims want its security check
843
+ // now, from what client/configs says: its captcha (Aliyun's, which the
844
+ // ZCode app passes before every claim, invisibly as a rule, and sends as
845
+ // X-Aliyun-Captcha-Verify-Param, 3.17.2's requestVerificationClaimHeaders)
846
+ // switched on. No captcha in the configs is no check, as the app reads it
847
+ // (readRequestVerificationConfig gives null, and the claim goes without
848
+ // the header); one that isn't an object is unknown, null.
849
+ // skip_model_request is the same check for Start Plan requests, which it
850
+ // spares (true on 11-07); it is not read here.
851
+ function claimNeedsCaptcha(c) {
852
+ const k = c?.configs?.captcha
853
+ if (k == null) return false
854
+ if (typeof k !== "object" || Array.isArray(k)) return null
855
+ return k.enabled !== false
856
+ }
857
+ const CAPTCHA_CLAIM = "claim it in the ZCode app: ZCode asks its security check before a claim, which only the app passes, so the daily check-in leaves it to the app"
858
+
859
+ // The marketing feed and the claim are gated on the client's version:
860
+ // under an older version's header the feed answers empty (11-03, #678:
861
+ // the day's banner showed for 3.17.2 and for no older one), so they go,
862
+ // as every call does, as the current client (APP_VERSION) sends them.
863
+ const marketingHeaders = () => ({ "X-ZCode-App-Version": APP_VERSION, "X-Platform": platform(), "X-Client-Language": clientLanguage() })
864
+
865
+ // claimOne asks /billing/claim for one plan and says what its body says:
866
+ // "claimed" (code 0), "done" (code 1003, claimed before), "captcha" (the
867
+ // claim wants the app's captcha), else "failed" with why. Only a body
868
+ // that reads decides: an HTTP error without one, or text that isn't
869
+ // JSON, is failed (unknown), never claimed. Only the code is read (#503
870
+ // has a real code 0 reply, "Plan claimed successfully.").
871
+ async function claimOne(s, planID) {
872
+ let res, text
873
+ try {
874
+ res = await fetch(`${ZCODE}/api/v1/zcode-plan/billing/claim`, {
875
+ method: "POST",
876
+ headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA, Authorization: "Bearer " + s.jwt, "X-Device-Mid": s.device || anyDevice, ...marketingHeaders() },
877
+ body: JSON.stringify({ plan_id: planID }),
878
+ })
879
+ text = await res.text()
880
+ } catch (e) {
881
+ return { outcome: "failed", why: e?.message ?? String(e) }
882
+ }
883
+ let env
884
+ try {
885
+ env = JSON.parse(text)
886
+ } catch {}
887
+ const code = env && typeof env === "object" && env.code != null && String(env.code).trim() !== "" ? Number(env.code) : NaN
888
+ const msg = typeof env?.msg === "string" ? env.msg : ""
889
+ // a rate limit is no claim: it is said as one, and carries how long to wait
890
+ if (res.status === 429 || code === RATE_LIMITED) return { outcome: "failed", why: `${msg || STATUS_TEXT[429]} (HTTP ${res.status}${Number.isFinite(code) ? `, code ${code}` : ""})`, rate: retryAfterMs(res) }
891
+ if (code === CAPTCHA || CAPTCHA_WORDS.test(msg)) return { outcome: "captcha", why: msg || `code ${code}` }
892
+ if (code === CLAIMED_ALREADY) return { outcome: "done" }
893
+ if (code === NOT_ELIGIBLE) return { outcome: "ineligible", why: msg || `code ${code}` }
894
+ if (code === 0 && res.ok) return { outcome: "claimed" }
895
+ if (!Number.isFinite(code)) return { outcome: "failed", why: `HTTP ${res.status}, unreadable reply ${String(text ?? "").trim().slice(0, 120) || "(empty)"}` }
896
+ return { outcome: "failed", why: `${msg || "error"} (HTTP ${res.status}, code ${code})` }
897
+ }
898
+
899
+ // TOUCH is ZCode's marketing feed: the ZCode app's claim banners come
900
+ // from it. A banner plan ("ZCODE WEEKEND BUILD", 10-30) is served only
901
+ // while the app shows its banner, and the app claims it through the same
902
+ // /billing/claim (#503's capture of 10-30, kongbai01203: GET
903
+ // /api/v1/marketing/touch?seq=<n, counting up from 0> with the session,
904
+ // X-Device-Mid, X-Client-Language and X-ZCode-App-Version, answered
905
+ // data.deliveries[].banner.buttons[].action = {"type":"claim_zcode_plan",
906
+ // "args":{"plan_id":…}} and the plan's name in
907
+ // banner.background.args.zcode_plan.name). The v3.17 client reads this
908
+ // feed alone: the old preview polling is gone, and the rewards center's
909
+ // gifts are the rewards website's, claimed in the client.
910
+ const TOUCH = "/api/v1/marketing/touch"
911
+ const CLAIM_ACTION = "claim_zcode_plan"
912
+ // touchSeq is the feed's seq: ZCode's own count of its feed requests
913
+ // since the process started, from 0, one GET per refresh. It is not a
914
+ // page: "仅供服务端日志定位,不改变投放判断" (docs/marketing-touch-client.md,
915
+ // marketingTouchService.ts's bootRequestSeq, zai-org/ZCode@a9fe401), so a
916
+ // check-in asks once, never seq 0..8 in a row (plugins#676), and a banner
917
+ // seen at one seq and not another is a delivery arriving later.
918
+ let touchSeq = 0
919
+ // clientLanguage is the language ZCode names to marketing/touch: zh-CN or
920
+ // en-US, its two UI languages, never another (marketingTouchService's
921
+ // localeSchema), so a computer set to zh-Hans-CN or en-GB asks as ZCode does.
922
+ const clientLanguage = () => {
923
+ let l = ""
924
+ try {
925
+ l = Intl.DateTimeFormat().resolvedOptions().locale || ""
926
+ } catch {}
927
+ return /^zh\b/i.test(l) ? "zh-CN" : "en-US"
928
+ }
929
+
930
+ // touchPlans is the plans marketing/touch's deliveries offer to claim:
931
+ // [{plan_id, name}], [] for a feed with no deliveries, null for one that
932
+ // doesn't read. Each delivery is searched for its claim_zcode_plan
933
+ // actions and its zcode_plan's name, wherever the banner keeps them, so
934
+ // a button moved inside the banner is still found.
935
+ function touchPlans(d) {
936
+ if (d == null) return []
937
+ if (typeof d !== "object" || Array.isArray(d)) return null
938
+ if (d.deliveries == null) return []
939
+ if (!Array.isArray(d.deliveries)) return null
940
+ const out = []
941
+ for (const dv of d.deliveries) {
942
+ const ids = [], names = []
943
+ const walk = (v, depth) => {
944
+ if (!v || typeof v !== "object" || depth > 12) return
945
+ if (Array.isArray(v)) return v.forEach((x) => walk(x, depth + 1))
946
+ if (v.type === CLAIM_ACTION && typeof v.args?.plan_id === "string" && v.args.plan_id.trim()) ids.push(v.args.plan_id.trim())
947
+ if (v.zcode_plan && typeof v.zcode_plan === "object" && typeof v.zcode_plan.name === "string") names.push(v.zcode_plan.name)
948
+ for (const k of Object.keys(v)) walk(v[k], depth + 1)
949
+ }
950
+ walk(dv, 0)
951
+ for (const id of ids) out.push({ plan_id: id, name: first(names[0] ?? "", id) })
952
+ }
953
+ return out
954
+ }
955
+
956
+ // toClaim is every gift plan the account can claim: what the app's
957
+ // marketing feed offers (its banners). The v3.17 client replaced the old
958
+ // preview polling with the feed alone (docs/marketing-touch-client.md in
959
+ // zai-org/ZCode), so the preview is read no more; a rewards center's gift
960
+ // lives on the rewards website, outside this API, and is claimed in the
961
+ // client. unread names a feed that didn't read: its plans are unknown,
962
+ // never none.
963
+ async function toClaim(s) {
964
+ const plans = [], unread = []
965
+ const add = (p) => {
966
+ if (!plans.some((q) => q.plan_id === p.plan_id)) plans.push(p)
967
+ }
968
+ let d
969
+ try {
970
+ d = await call("GET", `${ZCODE}${TOUCH}?seq=${touchSeq++}`, { auth: "Bearer " + s.jwt, device: s.device, headers: marketingHeaders() })
971
+ } catch (e) {
972
+ unread.push(`gift plans to claim: ${e?.message ?? String(e)}`)
973
+ // rate is the ms ZCode asked to wait (0 when it sent no Retry-After),
974
+ // null when this was not a rate limit at all
975
+ return { plans, unread, rate: e?.status === 429 || e?.code === RATE_LIMITED ? (e.retryAfterMs || 0) : null }
976
+ }
977
+ const got = touchPlans(d)
978
+ if (!got) unread.push("gift plans to claim: the plan list doesn't read")
979
+ else got.forEach(add)
980
+ return { plans, unread, rate: null }
981
+ }
982
+
983
+ // RECHECK is how long an "nothing to claim" stands before magpie's loop
984
+ // asks again: ZCode drops gift plans into the feed during the day (a
985
+ // weekend banner, say) on its own schedule, and the day's ask
986
+ // may have run hours before, so an inactive settled for the day lets a
987
+ // plan sit unclaimed past its short life (the weekend plan of
988
+ // testdata/touch-1030-wk.json starts 19:00 Beijing). `until` wakes the
989
+ // loop again in half an hour, and it asks again all day while neither
990
+ // list names a plan — two GETs and no claim posted. The other settled
991
+ // answers stand for the day: a claimed plan leaves the feed, so asking
992
+ // a claimed account again half an hour later finds nothing and flips
993
+ // its card from "Checked in today" to "No check-in event now"; a
994
+ // captcha plan re-asked makes ZCode demand its captcha again each time,
995
+ // and a done plan re-asked posts a claim it already answered 1003. The
996
+ // same shape as Qoder's campaign that opens mid-day, asked again on
997
+ // magpie's side there (yetone/magpie#2696). A failed needs no until:
998
+ // magpie asks a failed again after 30 minutes of its own.
999
+ const RECHECK_MS = 30 * 60_000
1000
+ const recheck = () => new Date(Date.now() + RECHECK_MS).toISOString()
1001
+
1002
+ // claimDaily claims every gift plan ZCode offers the account (#503:
1003
+ // toClaim, the app's banners and its preview), as auth.checkin's answer:
1004
+ // inactive when neither lists one, claimed when one was claimed now,
1005
+ // done when each was claimed before, captcha when ZCode wants the app's
1006
+ // captcha for one (it is claimed in the ZCode app), ineligible when
1007
+ // ZCode is not offering one at that moment (code 1004, read again later
1008
+ // in the day), failed when a list
1009
+ // or a claim can't be read. A rate-limited read (HTTP 429, or code 3002)
1010
+ // is not asked again either: the account is held here until the wait ends
1011
+ // (a Retry-After ZCode sent, else the account's own wait doubling from
1012
+ // RECHECK_MS, out to RATE_LIMIT_MAX_MS — see RATE_LIMITED), and every ask
1013
+ // inside the wait answers the failed it already gave, without a request.
1014
+ // The hold belongs to one account (`s.key || s.jwt`) and lives in this
1015
+ // process's memory alone: a magpie restart forgets it. magpie from
1016
+ // v0.1.3165 honors a failed's `until` itself; older versions wait for
1017
+ // this hold, which is why it stays.
1018
+ // A failed one is asked again later in the
1019
+ // day, when a plan claimed now answers 1003. An inactive stands only
1020
+ // until RECHECK_MS from now, so a plan dropped into the feed later in
1021
+ // the day is still claimed; the other settled answers stand for the day
1022
+ // (see RECHECK).
1023
+ // Nothing here marks the account: a failed claim keeps its sign-in.
1024
+ async function claimDaily(s) {
1025
+ if (!s?.jwt) return { outcome: "ineligible", message: "ZCode's gift plans are claimed with a ZCode sign-in; this account has none" }
1026
+ if (jwtExpired(s.jwt)) return { outcome: "failed", message: EXPIRED }
1027
+ // a rate limit this account is still under: the same failed again, and
1028
+ // not one request (magpie asks a failed again after 30 minutes of its
1029
+ // own, so holding it is the plugin's job — see RATE_LIMITED)
1030
+ const held = rateWait.get(holdKey(s))
1031
+ if (held && Date.now() < Date.parse(held.until)) return { outcome: "failed", message: held.message, until: held.until }
1032
+ const { plans, unread, rate = null } = await toClaim(s)
1033
+ // a rate-limited read: held here until the wait is over
1034
+ if (rate !== null) {
1035
+ const message = unread.join("; ") || "ZCode rate limited this account"
1036
+ return { outcome: "failed", message, until: noteRateLimit(holdKey(s), rate, message) }
1037
+ }
1038
+ // the feed answered and no claim is read: the wait is over. It is not
1039
+ // forgotten before the claims below, so a claim ZCode keeps limiting
1040
+ // waits longer each time (see noteRateLimit)
1041
+ if (!plans.length) {
1042
+ rateWait.delete(holdKey(s))
1043
+ return unread.length
1044
+ ? { outcome: "failed", message: unread.join("; ") }
1045
+ : { outcome: "inactive", message: "no ZCode gift plan to claim", until: recheck() }
1046
+ }
1047
+ // a claim ZCode guards with its security check is not posted: the app
1048
+ // passes it before each claim and sends the proof in a header, which
1049
+ // this plugin can't make, and a claim without it only gets 3007 again
1050
+ // (young02036 on Discord, 11-07: asked every day, never claimed). The
1051
+ // plans are named, to claim in the ZCode app. A config that doesn't
1052
+ // read leaves it unknown: nothing is posted, and it is asked again.
1053
+ let guarded
1054
+ try {
1055
+ guarded = claimNeedsCaptcha(await clientConfigs())
1056
+ } catch (e) {
1057
+ guarded = null
1058
+ unread.push(`ZCode's client config: ${e?.message ?? String(e)}`)
1059
+ }
1060
+ if (guarded !== false) {
1061
+ rateWait.delete(holdKey(s))
1062
+ if (guarded === null) return { outcome: "failed", message: [...plans.map((p) => `${p.name}: not claimed, ZCode's security check for claims can't be read`), ...unread].join("; ") }
1063
+ return { outcome: "captcha", message: plans.map((p) => `${p.name}: ${CAPTCHA_CLAIM}`).join("; ") }
1064
+ }
1065
+ const got = []
1066
+ for (const p of plans) got.push({ name: p.name, ...(await claimOne(s, p.plan_id)) })
1067
+ const named = (o) => got.filter((g) => g.outcome === o).map((g) => g.name)
1068
+ const claimed = named("claimed")
1069
+ const said = [
1070
+ claimed.length ? `claimed ${claimed.join(", ")}` : "",
1071
+ ...got.filter((g) => g.outcome === "captcha").map((g) => `${g.name}: claim it in the ZCode app (${g.why})`),
1072
+ ...got.filter((g) => g.outcome === "ineligible").map((g) => `${g.name}: ${g.why}`),
1073
+ ...got.filter((g) => g.outcome === "failed").map((g) => `${g.name}: ${g.why}`),
1074
+ ...unread,
1075
+ ].filter(Boolean).join("; ")
1076
+ // a plan claimed now is used by the next request, not ten minutes on
1077
+ if (claimed.length) routes.delete(s.key + "\0" + s.jwt)
1078
+ // a claim ZCode rate limited: the plan may still be there, later
1079
+ const limitedClaim = got.find((g) => g.rate !== undefined)
1080
+ if (limitedClaim) return { outcome: "failed", message: said, until: noteRateLimit(holdKey(s), limitedClaim.rate, said) }
1081
+ rateWait.delete(holdKey(s)) // nothing in this check-in was rate limited: the wait is over
1082
+ // a list that didn't read may hold a plan not claimed: asked again
1083
+ if (unread.length || got.some((g) => g.outcome === "failed")) return { outcome: "failed", message: said }
1084
+ if (got.some((g) => g.outcome === "captcha")) return { outcome: "captcha", message: said }
1085
+ if (claimed.length) return { outcome: "claimed", message: said }
1086
+ // a plan not offered now can be offered later in the day (11-04: an
1087
+ // account's GLOBAL BUILD banner showed 28 minutes after it signed in),
1088
+ // so an ineligible is read again half an hour out, as an inactive is
1089
+ if (got.some((g) => g.outcome === "ineligible")) return { outcome: "ineligible", message: said, until: recheck() }
1090
+ return { outcome: "done", message: `already claimed: ${named("done").join(", ")}` }
1091
+ }
1092
+
1093
+ // GIFT_SIGN_IN is the card's line for an account whose gift plans can't
1094
+ // be read: ZCode's gift plans (the Start Plan, ZCode 1024 Dev Day, ZCode
1095
+ // Trust Build) are served by zcode.z.ai to ZCode's own session alone, so
1096
+ // a GLM Coding Plan key, or a sign-in whose ZCode session has run out
1097
+ // (that token can't be renewed), lists no <model>-Trial entries and
1098
+ // spends the coding plan alone. A fixed sentence, so magpie can
1099
+ // translate it; why goes in the display. Set aside: it stops nothing.
1100
+ const GIFT_SIGN_IN = "ZCode gift plans (-Trial models) need ZCode's sign-in"
1101
+ function giftSignIn(s, key) {
1102
+ if (!s.jwt) {
1103
+ if (key) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "not read with an API key: add the account with a ZCode sign-in" }
1104
+ if (s.source === "zcode" && ownStoreUnreadable()) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: UNREADABLE_SIGN_IN }
1105
+ return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "this sign-in has no ZCode session: sign in again" }
1106
+ }
1107
+ if (jwtExpired(s.jwt)) return { name: GIFT_SIGN_IN, used: 0, aside: true, display: "ZCode's sign-in has expired: sign in again" }
1108
+ return null
1109
+ }
1110
+
1111
+ // startUsage is a gift-only account's card: its buckets, or the words
1112
+ // for having none to show. The card's header already names the plan, so
1113
+ // the windows of one plan keep their own names; with several plans each
1114
+ // bucket is named after its plan (see byPlan).
1115
+ const NO_START = "this account has no GLM Coding Plan, and ZCode's Start Plan has ended or was never started"
1116
+ async function startUsage(s) {
1117
+ const g = await giftOf(s)
1118
+ if (!g) return { error: NO_START }
1119
+ const best = bestBuckets(g.windows)
1120
+ const label = byPlan(g.windows)
1121
+ g.windows = countedFirst(g.windows.map(({ _plan, _spent, ...w }, i) => {
1122
+ w.name = label(w.name, _plan)
1123
+ if (!w.models?.length) return w
1124
+ // a model two plans give (Trust Build's and the Start Plan's Flash)
1125
+ // counts on the bucket ZCode spends now; the other stays on the card
1126
+ // without holding the model up (ganlerk, Discord)
1127
+ const models = w.models.filter((m) => best.get(m.toLowerCase()) === i)
1128
+ if (!models.length) {
1129
+ delete w.models
1130
+ return { ...w, aside: true }
1131
+ }
1132
+ return { ...w, models: [...models, ...models.map(giftID)] }
1133
+ }))
1134
+ g.windows.push(...pendingLines(g))
1135
+ delete g.live
1136
+ delete g.pending
1137
+ return g
1138
+ }
1139
+
1140
+ // byPlan names a bucket after its plan ("GLM-5.3 · ZCode 1024 Dev Day")
1141
+ // when the gift's buckets come from more than one plan: two plans each
1142
+ // give a GLM-5.3, and named alike a spent one and a live one can't be
1143
+ // told apart (01huadalang, Discord: the new-user plan's spent GLM-5.3
1144
+ // showed, the 1024 plan's own GLM-5.3 didn't). One plan's buckets keep
1145
+ // their own names, as the card's header names the plan.
1146
+ function byPlan(windows) {
1147
+ const several = new Set(windows.map((w) => w._plan || "")).size > 1
1148
+ return (name, plan) => (several && plan ? name + " · " + plan : name)
1149
+ }
1150
+
1151
+ // countedFirst puts the buckets a request spends before those set aside
1152
+ // (a spent bucket another plan's live one stands in for), each group in
1153
+ // the balance's order: magpie's account row shows a card's first two
1154
+ // windows and leaves the rest to its tooltip, so a spent plan listed first
1155
+ // hid the live plan's allowance for the same model.
1156
+ const countedFirst = (ws) => [...ws.filter((w) => !w.aside), ...ws.filter((w) => w.aside)]
1157
+
1158
+ // bestBuckets is, for each model the gift's buckets serve, the index of
1159
+ // the one a request spends: a live one before a spent one, the least
1160
+ // used of those. The server picks among an account's buckets itself
1161
+ // (ZCode sends no plan with a request), so one spent bucket doesn't stop
1162
+ // a model another still has.
1163
+ function bestBuckets(windows) {
1164
+ const best = new Map()
1165
+ windows.forEach((w, i) => {
1166
+ for (const m of w.models ?? []) {
1167
+ const key = m.toLowerCase(), old = best.get(key), prev = windows[old]
1168
+ if (old === undefined || (prev._spent && !w._spent) || (prev._spent === w._spent && w.used < prev.used)) best.set(key, i)
1169
+ }
1170
+ })
1171
+ return best
1172
+ }
1173
+
1174
+ // giftReadable: ZCode's session can read the gift beside a coding plan,
1175
+ // so the card asks for it even when no gift is live for requests: a plan
1176
+ // that starts later is named on the card (windy, Discord), not left out
1177
+ // because nothing could be spent yet.
1178
+ const giftReadable = (s) => !!s.jwt && !jwtExpired(s.jwt)
1179
+
1180
+ // dualUsage shows both pools but only the pool a request can use counts
1181
+ // for its model. Live gift models don't spend the Coding windows; spent
1182
+ // or blocked gift buckets stay visible without holding up the Coding Plan.
1183
+ // Fresh usage also updates the request cache, so a replenished or spent
1184
+ // gift takes effect before its ten-minute route cache expires. A failed
1185
+ // gift read leaves the working Coding Plan's card and route alone.
1186
+ async function dualUsage(s, out) {
1187
+ out ??= await codingUsage(s)
1188
+ const cached = routes.get(s.key + "\0" + s.jwt)
1189
+ try {
1190
+ const g = await giftOf(s)
1191
+ const gift = g?.live ? { name: g.plan, models: [...new Set(g.windows.filter((w) => !w._spent)
1192
+ .flatMap((w) => w.models ?? []).map((m) => m.toLowerCase()))],
1193
+ allModels: uniqueModels(g.windows.flatMap((w) => w.models ?? [])) } : null
1194
+ if (cached) {
1195
+ cached.gift = gift
1196
+ // a plan that starts later is read again when it starts
1197
+ const ends = g ? [g.until, ...g.windows.map((w) => w.resetsAt)].map((t) => Date.parse(t))
1198
+ .concat(g.pending.map((p) => p.start * 1000)).filter(Number.isFinite) : []
1199
+ if (ends.length) cached.ttl = Math.min(cached.ttl, Math.max(0, Math.min(...ends) - cached.at))
1200
+ }
1201
+ if (g?.live) {
1202
+ // the gift's models are its trial entries alone: a plain model stays
1203
+ // on the coding plan, and the user picks the gift by its entry
1204
+ const notModels = gift.allModels.map((m) => giftID(m).toLowerCase())
1205
+ if (notModels.length) out.windows = out.windows.map((w) => w.aside ? w : { ...w, notModels })
1206
+ // Several buckets may serve one model: one spent sibling cannot block it.
1207
+ const best = bestBuckets(g.windows)
1208
+ // beside the Coding Plan's windows every gift bucket is named after
1209
+ // its plan, one plan or several: "GLM-5.1-Trial · Start Plan" can't
1210
+ // be read as the Coding Plan's own (windy, Discord). The bucket's
1211
+ // own name (ZCode's show_name, as its "Today's balance" lists it)
1212
+ // comes first: magpie's ring and account row cut a long name short,
1213
+ // and "ZCODE GLOBAL BUI…" said neither the model nor the plan's
1214
+ // kind, so the Start Plan read as missing (Danbuth, plugins#504)
1215
+ const label = (name, plan) => name + " · " + first(plan, "Start Plan")
1216
+ out.windows.push(...countedFirst(g.windows.map(({ _plan: p, _spent, ...w }, i) => {
1217
+ const selected = gift.allModels.filter((m) => best.get(m.toLowerCase()) === i)
1218
+ const models = selected.map(giftID)
1219
+ const scoped = models.length ? { ...w, models } : { ...w, aside: true }
1220
+ // the card names a bucket's model as the picker does (GLM-5.3-Flash-Trial)
1221
+ let name = w.name
1222
+ for (const m of selected) {
1223
+ const at = name.toLowerCase().indexOf(m.toLowerCase())
1224
+ if (at >= 0) name = name.slice(0, at) + giftID(m) + name.slice(at + m.length)
1225
+ }
1226
+ return { ...scoped, name: label(name, p) }
1227
+ })))
1228
+ }
1229
+ if (g) out.windows.push(...pendingLines(g))
1230
+ } catch {
1231
+ if (cached) {
1232
+ cached.gift = null
1233
+ cached.at = Date.now()
1234
+ cached.ttl = 60_000 // an uncertain gift is read again sooner
1235
+ }
1236
+ }
1237
+ return out
1238
+ }
1239
+
1240
+ // periodOf reads an entitlement's period: "daily", "weekly", "monthly".
1241
+ function periodOf(p) {
1242
+ p = p.toLowerCase()
1243
+ if (p.includes("day") || p.includes("daily")) return 86400
1244
+ if (p.includes("week")) return 7 * 86400
1245
+ if (p.includes("month")) return 30 * 86400
1246
+ return 0
1247
+ }
1248
+
1249
+ // when is a team plan's end: a time in Beijing, or a Unix time in seconds
1250
+ // or milliseconds; ms, or 0.
1251
+ function when(v) {
1252
+ if (typeof v === "string") {
1253
+ const t = beijing(v)
1254
+ if (t) return t
1255
+ }
1256
+ const n = startNum(v)
1257
+ if (n > 0) return n > 1e12 ? Math.trunc(n) : Math.trunc(n) * 1000
1258
+ return 0
1259
+ }
1260
+
1261
+ // teamUsage is a team seat's allowance: the team plan's five hours and
1262
+ // week, and the plan's name and end.
1263
+ async function teamUsage(s, key) {
1264
+ const root = bizRoot(s.base)
1265
+ const headers = teamHeaders(s.base, s.org, s.project)
1266
+ const d = (await call("GET", root + "/api/monitor/usage/quota/limit?type=2", { auth: key, headers })) ?? {}
1267
+ const out = { windows: limitWindows(d) }
1268
+ notePlan(key, out.windows)
1269
+ if (!s.token) return out
1270
+ const resets = teamResets(root, s.token, headers)
1271
+ try {
1272
+ const t = (await call("GET", root + "/api/biz/team/subscribe/product/querySubscribeDetail", { auth: s.token, headers })) ?? {}
1273
+ const usable = (t.hasSubscription == null || t.hasSubscription === true) && String(t.status ?? "").toUpperCase() === "EFFECTIVE" &&
1274
+ String(t.memberGrantStatus ?? "").toUpperCase() === "VALID"
1275
+ if (usable) {
1276
+ if (typeof t.productName === "string" && t.productName) out.plan = t.productName
1277
+ const end = when(t.subscribeEndTime)
1278
+ if (end) Object.assign(out, { until: new Date(end).toISOString(), renew: "off" })
1279
+ }
1280
+ } catch {}
1281
+ const r = await resets
1282
+ if (r) out.resets = r
1283
+ return out
1284
+ }
1285
+
1286
+ // teamResets is how many resets a team member may spend, of the five hours
1287
+ // and of the week, marked a team's (team: true), as the built-in's
1288
+ // zhipuTeamResets did. null when it can't be told or there are none.
1289
+ async function teamResets(root, auth, headers) {
1290
+ const r = await resetsOf(root + "/api/biz/customer-package-reset/list?targetType=TEAM", auth, headers)
1291
+ if (r) r.team = true
1292
+ return r
1293
+ }
1294
+
1295
+ // personalResets is how many resets a GLM Coding Plan of a person's own
1296
+ // holds, as bigmodel.cn's usage page lists them, asked with the plan's
1297
+ // key (the built-in's zhipuPersonalResets). Only read: a reset is spent
1298
+ // on the vendor's own page, never from here.
1299
+ async function personalResets(root, key) {
1300
+ return resetsOf(root + "/api/biz/customer-package-reset/list?targetType=PERSONAL", key)
1301
+ }
1302
+
1303
+ // resetsOf reads customer-package-reset/list: the resets of the five
1304
+ // hours and of the week, of which only those still available count (one
1305
+ // run out stays listed a week, available false), each with its own end
1306
+ // (each, soonest first, one with no end last) and the soonest as until.
1307
+ // One whose end has passed is not counted, whatever its flag says.
1308
+ // null when the list can't be read, so no count is shown rather than 0,
1309
+ // and when it holds none.
1310
+ async function resetsOf(url, auth, headers) {
1311
+ let d
1312
+ try {
1313
+ d = (await call("GET", url, { auth, headers })) ?? {}
1314
+ } catch {
1315
+ return null
1316
+ }
1317
+ let until = 0
1318
+ const each = []
1319
+ const count = (rs, window) => {
1320
+ let n = 0
1321
+ for (const x of Array.isArray(rs) ? rs : []) {
1322
+ if (x?.available !== true) continue
1323
+ const t = when(x.expireTime)
1324
+ // a reset past its end is no reset: the list can still flag it
1325
+ // available, and the vendor's page puts it among the expired
1326
+ if (t && t <= Date.now()) continue
1327
+ n++
1328
+ if (t && (!until || t < until)) until = t
1329
+ each.push(t ? { until: new Date(t).toISOString(), window } : { window })
1330
+ }
1331
+ return n
1332
+ }
1333
+ const fiveHour = count(d.fiveHourResets, "fiveHour")
1334
+ const weekly = count(d.weekResets, "weekly")
1335
+ if (fiveHour + weekly === 0) return null
1336
+ const end = (c) => (c.until ? Date.parse(c.until) : Infinity)
1337
+ each.sort((a, b) => (end(a) === end(b) ? 0 : end(a) < end(b) ? -1 : 1))
1338
+ const r = { count: fiveHour + weekly, byWindow: true, fiveHour, weekly }
1339
+ if (until) r.until = new Date(until).toISOString()
1340
+ r.each = each
1341
+ return r
1342
+ }
1343
+
1344
+ // ---- signing in ------------------------------------------------------------------
1345
+
1346
+ // bizAuth is the Authorization a sign-in gives the business API: Z.ai's
1347
+ // token exchanged for a business one, as a Bearer; BigModel's goes bare.
1348
+ async function bizAuth(site, token) {
1349
+ if (site === "bigmodel") return token
1350
+ let biz
1351
+ try {
1352
+ biz = await call("POST", ZAI_API + "/api/auth/z/login", { body: { token } })
1353
+ } catch (e) {
1354
+ throw new Error(`Z.ai sign-in: ${e.message}`)
1355
+ }
1356
+ if (!biz?.access_token) throw new Error("Z.ai sign-in: no token")
1357
+ return "Bearer " + biz.access_token
1358
+ }
1359
+
1360
+ // mintKey is the account's own coding plan key, in its default project
1361
+ // ("默认机构" / "默认项目", else the first), and the plan it has.
1362
+ async function mintKey(site, root, auth, info) {
1363
+ let org = ""
1364
+ let proj = ""
1365
+ for (const o of info?.organizations ?? []) {
1366
+ const ps = (o.projects ?? []).filter((p) => p.projectId && String(p.projectType) !== "2")
1367
+ if (!o.organizationId || !ps.length) continue
1368
+ const def = (ps.find((p) => String(p.projectName ?? "").includes("默认项目")) ?? ps[0]).projectId
1369
+ const named = String(o.organizationName ?? "").includes("默认机构")
1370
+ if (!org || named) {
1371
+ org = o.organizationId
1372
+ proj = def
1373
+ if (named) break
1374
+ }
1375
+ }
1376
+ if (!org) throw new Error(`this ${SITES[site].name} account has no project for an API key`)
1377
+ const key = await projectKey(site, keysURL(root, org, proj), auth, undefined, { name: "zcode-api-key" })
1378
+ const s = { key, base: SITES[site].base }
1379
+ try {
1380
+ return { s, plan: await plan(s) }
1381
+ } catch (e) {
1382
+ throw new Error(`GLM Coding Plan: ${e.message}`)
1383
+ }
1384
+ }
1385
+
1386
+ // teamSignIn is the account's seat on a team's plan: the first team project
1387
+ // whose plan is in force and gives it a seat, and that project's key.
1388
+ async function teamSignIn(site, root, auth, info) {
1389
+ const base = SITES[site].base
1390
+ const ps = []
1391
+ for (const o of info?.organizations ?? [])
1392
+ for (const p of o.projects ?? []) if (o.organizationId && p.projectId && String(p.projectType) === "2") ps.push({ org: o.organizationId, project: p.projectId })
1393
+ if (!ps.length) return { err: "no team plan", none: true }
1394
+ let why = ""
1395
+ let last = ""
1396
+ for (const p of ps) {
1397
+ let d
1398
+ try {
1399
+ d = (await call("GET", root + "/api/biz/team/subscribe/product/querySubscribeDetail", { auth, headers: teamHeaders(base, p.org, p.project) })) ?? {}
1400
+ } catch (e) {
1401
+ last = e.message
1402
+ continue
1403
+ }
1404
+ const status = String(d.status ?? "").toUpperCase()
1405
+ const grant = String(d.memberGrantStatus ?? "").toUpperCase()
1406
+ if (!(d.hasSubscription !== false && status === "EFFECTIVE" && grant === "VALID")) {
1407
+ if (!why && status === "EFFECTIVE" && grant === "UNASSIGNED")
1408
+ why = `this ${SITES[site].name} account is in a team with a GLM Coding Plan but has no seat on it yet — ask the team's admin to give it one, then sign in again`
1409
+ if (!why && status === "EXPIRED") why = `the ${SITES[site].name} team's GLM Coding Plan this account is in has expired`
1410
+ continue
1411
+ }
1412
+ let key
1413
+ try {
1414
+ key = await projectKey(site, keysURL(root, p.org, p.project), auth, teamHeaders(base, p.org, p.project), { name: "zcode-team-api-key", keyType: 2 })
1415
+ } catch (e) {
1416
+ return { err: `the team's GLM Coding Plan: ${e.message}`, why: `the team's GLM Coding Plan: ${e.message}` }
1417
+ }
1418
+ return { s: { key, base, token: auth, org: p.org, project: p.project }, plan: first(d.productName, "GLM Coding Team") }
1419
+ }
1420
+ if (why) return { err: why, why }
1421
+ const err = `the team's GLM Coding Plan: ${last || "no seat on it"}`
1422
+ return { err, why: err }
1423
+ }
1424
+
1425
+ // signedIn is what a sign-in gives: the account's coding plan key and plan;
1426
+ // or, with none of its own, a seat on a team's plan; or else ZCode's token
1427
+ // for its Start Plan while the account has one. Asked for the team's plan
1428
+ // (onTeam), it is the team seat alone, as ZCode's plan picker gives a team
1429
+ // plan beside the account's own (a "team-coding-plan" selection): an
1430
+ // account with both is signed in to each as an account of its own (#285).
1431
+ async function signedIn(site, token, jwt, device, onTeam = false) {
1432
+ const name = SITES[site].name
1433
+ const root = SITES[site].api
1434
+ let s = null
1435
+ let err = null
1436
+ let team = ""
1437
+ if (onTeam) {
1438
+ const auth = await bizAuth(site, token)
1439
+ let info
1440
+ try {
1441
+ info = await call("GET", root + "/api/biz/customer/getCustomerInfo", { auth })
1442
+ } catch (e) {
1443
+ throw new Error(`${name} account: ${e.message}`)
1444
+ }
1445
+ const t = await teamSignIn(site, root, auth, info)
1446
+ if (t.s) return { ...t.s, jwt, plan: t.plan }
1447
+ if (t.none) throw new Error(`this ${name} account has no seat on a team's GLM Coding Plan — sign in with "ZCode: ${name} GLM Coding Plan" for its own plan`)
1448
+ throw new Error(t.why ?? t.err)
1449
+ }
1450
+ try {
1451
+ const auth = await bizAuth(site, token)
1452
+ let info
1453
+ try {
1454
+ info = await call("GET", root + "/api/biz/customer/getCustomerInfo", { auth })
1455
+ } catch (e) {
1456
+ throw new Error(`${name} account: ${e.message}`)
1457
+ }
1458
+ const own = await mintKey(site, root, auth, info).catch((e) => ({ e }))
1459
+ if (own.e) err = own.e
1460
+ else if (own.plan) return { ...own.s, jwt, plan: own.plan }
1461
+ else s = own.s
1462
+ const t = await teamSignIn(site, root, auth, info)
1463
+ if (t.s) return { ...t.s, jwt, plan: t.plan }
1464
+ team = t.why ?? ""
1465
+ } catch (e) {
1466
+ err = e
1467
+ }
1468
+ let berr = null
1469
+ if (jwt) {
1470
+ try {
1471
+ const sp = await startPlan(jwt, device, true)
1472
+ if (sp) return { ...(err || !s?.key ? { base: SITES[site].base } : s), jwt, plan: sp.name }
1473
+ } catch (e) {
1474
+ berr = e
1475
+ }
1476
+ }
1477
+ if (team && berr) throw new Error(`${team}; ZCode's Start Plan: ${berr.message}`)
1478
+ if (team) throw new Error(team)
1479
+ if (err && berr) throw new Error(`${err.message}; ZCode's Start Plan: ${berr.message}`)
1480
+ if (err) throw err
1481
+ if (berr) throw new Error(`this ${name} account has no GLM Coding Plan, of its own or a team's, and ZCode's Start Plan could not be read: ${berr.message}`)
1482
+ throw new Error(
1483
+ `this ${name} account has no GLM Coding Plan, of its own or a team's, and ZCode's Start Plan has ended or was never started — subscribe at ${SITES[site].subscribe}, then sign in again`,
1484
+ )
1485
+ }
1486
+
1487
+ // TEAM marks a team seat's account name beside the account's own.
1488
+ const TEAM = "team"
1489
+ const who = (u) => first(String(u?.email ?? "").replace(/@phone\.local$/, ""), u?.name, u?.user_id, "ZCode")
1490
+ // uidOf is the account's user id, kept beside its name: magpie tells two
1491
+ // accounts of one name apart by it, a name being no one's own (wakkana on
1492
+ // Discord, WorkBuddy's)
1493
+ const uidOf = (u) => (u?.user_id === undefined || u?.user_id === null ? "" : String(u.user_id).trim())
1494
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
1495
+
1496
+ // authorize opens ZCode's sign-in flow on site; its callback polls it.
1497
+ // onTeam signs in to the account's seat on a team's plan, named apart from
1498
+ // the account's own plan (the host keeps one entry per account name).
1499
+ async function authorize(site, log, onTeam = false) {
1500
+ const poll = "Bearer " + Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex")
1501
+ const device = uuid()
1502
+ let flow
1503
+ try {
1504
+ flow = await call("POST", ZCODE + "/api/v1/oauth/cli/init", { auth: poll, body: { provider: site }, device })
1505
+ } catch (e) {
1506
+ throw new Error(`ZCode sign-in: ${e.message}`)
1507
+ }
1508
+ let u
1509
+ try {
1510
+ u = new URL(flow?.authorize_url)
1511
+ } catch {}
1512
+ if (!flow?.flow_id || u?.protocol !== "https:") throw new Error("ZCode gave no sign-in page")
1513
+ // where Z.ai or BigModel sends the browser back, as ZCode sets it (BigModel's page names it redirect)
1514
+ const back = `${ZCODE}/app/oauth/login?` + new URLSearchParams({ redirect: "zcode://oauth/callback", app_version: APP_VERSION })
1515
+ u.searchParams.set(site === "bigmodel" ? "redirect" : "redirect_uri", back)
1516
+ const interval = Math.max(Number(flow.poll_interval_sec) || 0, 1) * 1000
1517
+ const deadline = Number(flow.expires_at) > 0 ? Number(flow.expires_at) * 1000 : Date.now() + 5 * 60_000
1518
+ return {
1519
+ url: u.toString(),
1520
+ instructions: `Sign in to ${SITES[site].name} in the browser; this finishes on its own.`,
1521
+ method: "auto",
1522
+ async callback() {
1523
+ const fail = (msg) => (log(msg), { type: "failed", error: msg })
1524
+ for (;;) {
1525
+ await sleep(interval)
1526
+ if (Date.now() > deadline) return fail("the sign-in expired; start again")
1527
+ let got
1528
+ try {
1529
+ got = (await call("GET", `${ZCODE}/api/v1/oauth/cli/poll/${encodeURIComponent(flow.flow_id)}`, { auth: poll, device })) ?? {}
1530
+ } catch (e) {
1531
+ if (e.status >= 400 && e.status < 500 && e.status !== 408 && e.status !== 429) return fail("ZCode sign-in: " + e.message)
1532
+ continue // a hiccup: ask again
1533
+ }
1534
+ const token = site === "bigmodel" ? first(got.bigmodel?.access_token, got.bigmodel?.accessToken) : first(got.zai?.access_token)
1535
+ if (got.status === "pending" || !got.status) continue
1536
+ if (got.status === "failed") return fail(`the sign-in was declined on ${SITES[site].name}`)
1537
+ if (got.status !== "ready" || !token) return fail("ZCode sign-in: unexpected answer " + got.status)
1538
+ let s
1539
+ try {
1540
+ s = await signedIn(site, token, first(got.token), device, onTeam)
1541
+ } catch (e) {
1542
+ return fail(e.message)
1543
+ }
1544
+ const state = { site, device, ...s }
1545
+ return {
1546
+ type: "success",
1547
+ refresh: JSON.stringify(state),
1548
+ access: s.key || s.jwt || "",
1549
+ // the key doesn't run out; ZCode's token, when it is all there is, does
1550
+ expires: s.key || isTeam(s) ? 0 : jwtExpiry(s.jwt),
1551
+ accountId: onTeam ? `${who(got.user)} (${TEAM})` : who(got.user),
1552
+ ...(uidOf(got.user) ? { uid: uidOf(got.user) } : {}),
1553
+ }
1554
+ }
1555
+ },
1556
+ }
1557
+ }
1558
+
1559
+ // ---- ZCode's own sign-in ------------------------------------------------------------
1560
+ // ZCode keeps its sign-in in ~/.zcode/v2/credentials.json, each value
1561
+ // encrypted (AES-256-GCM, "enc:v1:<iv>.<tag>.<data>") with a key made from
1562
+ // the machine's user; ~/.zcode/v2/setting.json says whether it is on a
1563
+ // team's plan. An account signed in "as ZCode" reads them for every
1564
+ // request, so it follows ZCode's own sign-in, its renewed session and its
1565
+ // switches between plans, as magpie's built-in did (zcode.go zcodeOwn).
1566
+ //
1567
+ // ZCode 3.14 can move its data (数据存储路径, "data storage path"): it copies
1568
+ // ~/.zcode/v2 to <folder>/.zcode/v2, all but setting.json, and from its next
1569
+ // start reads credentials.json and runtime/provider from there. The choice
1570
+ // stays in the home folder's setting.json as dataBaseDir, which ZCode's main
1571
+ // process reads before anything else (readBootstrapDataBaseDirFromDisk);
1572
+ // setting.json itself, and the team plan it names, stay in the home folder.
1573
+
1574
+ // settingDir is where ZCode keeps setting.json, moved or not.
1575
+ const settingDir = () => join(homedir(), ".zcode", "v2")
1576
+
1577
+ // dataIn is the folder ZCode keeps its .zcode data in: the home folder,
1578
+ // unless dataBaseDir moved it. A value that isn't an absolute path is
1579
+ // ignored, as magpie's built-in does (internal/appdir ZCodeDataIn).
1580
+ function dataIn() {
1581
+ const d = readJSON(join(settingDir(), "setting.json"))?.dataBaseDir
1582
+ const t = typeof d === "string" ? d.trim() : ""
1583
+ return t && isAbsolute(t) ? t : homedir()
1584
+ }
1585
+
1586
+ // zcodeDir is where ZCode keeps credentials.json and runtime/provider.
1587
+ const zcodeDir = () => join(dataIn(), ".zcode", "v2")
1588
+
1589
+ // secret is the key ZCode encrypts its credentials with.
1590
+ function secret() {
1591
+ let seed = process.env.ZCODE_CREDENTIAL_SECRET
1592
+ if (!seed) {
1593
+ let name = ""
1594
+ try {
1595
+ name = userInfo().username
1596
+ } catch {}
1597
+ name = name.slice(name.lastIndexOf("\\") + 1) // DOMAIN\user
1598
+ seed = `zcode-credential-fallback:${process.platform}:${homedir()}:${name}`
1599
+ }
1600
+ return createHash("sha256").update(seed).digest()
1601
+ }
1602
+
1603
+ function decrypt(key, v) {
1604
+ if (typeof v !== "string" || !v.startsWith("enc:v1:")) return null
1605
+ const parts = v.slice(7).split(".")
1606
+ if (parts.length !== 3) return null
1607
+ try {
1608
+ const [iv, tag, data] = parts.map((p) => Buffer.from(p.replace(/=+$/, ""), "base64url"))
1609
+ const d = createDecipheriv("aes-256-gcm", key, iv)
1610
+ d.setAuthTag(tag)
1611
+ return Buffer.concat([d.update(data), d.final()]).toString("utf8")
1612
+ } catch {
1613
+ return null
1614
+ }
1615
+ }
1616
+
1617
+ // UNREADABLE_SIGN_IN says why a sign-in "as ZCode" has no session to
1618
+ // read: ZCode 3.18 writes credentials.json's values as "enc:v2:os:…",
1619
+ // which looks bound to the system's own key store, and this plugin reads
1620
+ // enc:v1 alone (#1196).
1621
+ const UNREADABLE_SIGN_IN = "ZCode 3.18 keeps its sign-in in a new form this plugin can't read yet: add the account with a Z.ai or BigModel sign-in"
1622
+
1623
+ // ownStoreUnreadable says whether ZCode's credentials.json holds values
1624
+ // in a form decrypt can't read.
1625
+ function ownStoreUnreadable() {
1626
+ const store = readJSON(join(zcodeDir(), "credentials.json"))
1627
+ if (!store || typeof store !== "object") return false
1628
+ return Object.values(store).some((v) => typeof v === "string" && v.startsWith("enc:") && !v.startsWith("enc:v1:"))
1629
+ }
1630
+
1631
+ function readJSON(path) {
1632
+ try {
1633
+ return JSON.parse(readFileSync(path, "utf8"))
1634
+ } catch {
1635
+ return null
1636
+ }
1637
+ }
1638
+
1639
+ // ownTeam is the team plan ZCode switched to, when it did.
1640
+ function ownTeam(store, key) {
1641
+ const set = readJSON(join(settingDir(), "setting.json"))
1642
+ if (!set) return null
1643
+ const families = set.providerFamilyDomain === "zai" || set.providerFamilyDomain === "bigmodel" ? [set.providerFamilyDomain] : ["zai", "bigmodel"]
1644
+ for (const fam of families) {
1645
+ let org = ""
1646
+ let project = ""
1647
+ const sel = set.providerFamilyConnectionSelections?.[fam]
1648
+ if (sel) {
1649
+ if (sel.kind === "team-coding-plan") [org, project] = [first(sel.organizationId), first(sel.projectId)]
1650
+ } else {
1651
+ // before providerFamilyConnectionSelections
1652
+ const legacy = first(set.modelProviderFamilySelectedKeys?.[fam])
1653
+ const pre = `team-plan:builtin:${fam}-coding-plan:`
1654
+ if (legacy.startsWith(pre)) {
1655
+ const ps = legacy.slice(pre.length).split(":")
1656
+ if (ps.length === 3) {
1657
+ try {
1658
+ ;[org, project] = [decodeURIComponent(ps[1]), decodeURIComponent(ps[2])]
1659
+ } catch {}
1660
+ }
1661
+ }
1662
+ }
1663
+ if (!org || !project) continue
1664
+ const tok = first(decrypt(key, store[`oauth:${fam}:access_token`]))
1665
+ if (!tok) continue
1666
+ // a stale token ZCode won't use either
1667
+ if (fam === "bigmodel" && first(decrypt(key, store.zcodejwttoken)) === tok) continue
1668
+ return { site: fam, base: SITES[fam].base, key: "", token: tok, org, project }
1669
+ }
1670
+ return null
1671
+ }
1672
+
1673
+ // configKey is the coding plan key ZCode's config.json gives its built-in
1674
+ // coding plan provider, Z.ai's first, as ZCode lists them; ZCode reads it
1675
+ // as it is, and one written encrypted is read too.
1676
+ function configKey(key) {
1677
+ const providers = readJSON(join(zcodeDir(), "config.json"))?.provider
1678
+ if (!providers || typeof providers !== "object") return null
1679
+ for (const [ids, base] of [
1680
+ [["builtin:zai-coding-plan", "account:zai-individual-coding-plan"], ZAI_BASE],
1681
+ [["builtin:bigmodel-coding-plan", "account:bigmodel-individual-coding-plan"], BIGMODEL_BASE],
1682
+ ]) {
1683
+ for (const id of ids) {
1684
+ let k = providers[id]?.options?.apiKey
1685
+ if (typeof k !== "string") continue
1686
+ k = k.trim()
1687
+ if (k.startsWith("enc:")) k = first(decrypt(key, k))
1688
+ if (k.includes(".") && !/[\s{$]/.test(k)) return { key: k, base }
1689
+ }
1690
+ }
1691
+ return null
1692
+ }
1693
+
1694
+ // ownLocation is where ZCode 3.16 finds the account's own coding plan key
1695
+ // when it keeps none: credentials.json's
1696
+ // project-key-location:v1:<[origin, family, accountId, team, 1, selection]>,
1697
+ // URI-encoded JSON, holds { organizationId, projectId, apiKeyId } (its
1698
+ // ProjectAccessTokenClient). ZCode trades that key for a short-lived
1699
+ // project token each time; here its secret is read (located), as a sign-in
1700
+ // here reads its own key's. The account's own (team null), of the family
1701
+ // ZCode is on first, else Z.ai's, as ZCode lists them; one of another
1702
+ // account the profile names is left alone (meraki7304, #410).
1703
+ const LOCATION = "project-key-location:v1:"
1704
+ function ownLocation(store, key) {
1705
+ const set = readJSON(join(settingDir(), "setting.json"))
1706
+ const fams = set?.providerFamilyDomain === "bigmodel" ? ["bigmodel", "zai"] : ["zai", "bigmodel"]
1707
+ const found = []
1708
+ for (const [name, v] of Object.entries(store)) {
1709
+ if (!name.startsWith(LOCATION)) continue
1710
+ let at
1711
+ try {
1712
+ at = JSON.parse(decodeURIComponent(name.slice(LOCATION.length)))
1713
+ } catch {
1714
+ continue
1715
+ }
1716
+ if (!Array.isArray(at) || at[3] !== null || String(at[4]) !== "1" || !fams.includes(at[1])) continue
1717
+ let loc
1718
+ try {
1719
+ loc = JSON.parse(decrypt(key, v) ?? "")
1720
+ } catch {}
1721
+ const org = first(loc?.organizationId), project = first(loc?.projectId), apiKeyId = first(loc?.apiKeyId)
1722
+ if (!org || !project || !apiKeyId) continue
1723
+ found.push({ site: at[1], origin: typeof at[0] === "string" ? at[0] : "", account: String(at[2] ?? ""), org, project, apiKeyId })
1724
+ }
1725
+ for (const site of fams) {
1726
+ const token = first(decrypt(key, store[`oauth:${site}:access_token`]))
1727
+ if (!token) continue
1728
+ let me = ""
1729
+ try {
1730
+ me = String(JSON.parse(decrypt(key, store[`oauth:${site}:user_info`]) ?? "{}")?.id ?? "")
1731
+ } catch {}
1732
+ const mine = found.filter((l) => l.site === site && (!me || l.account === me))
1733
+ if (!mine.length) continue
1734
+ const l = mine[0]
1735
+ // the origin ZCode asked, when it is the site's own; else the site's API
1736
+ let origin = SITES[site].api
1737
+ try {
1738
+ const u = new URL(l.origin)
1739
+ const h = u.host.toLowerCase()
1740
+ if (u.protocol === "https:" && (site === "zai" ? h === "z.ai" || h.endsWith(".z.ai") : h === "bigmodel.cn" || h.endsWith(".bigmodel.cn"))) origin = u.origin
1741
+ } catch {}
1742
+ return { site, base: SITES[site].base, token, loc: { origin, org: l.org, project: l.project, apiKeyId: l.apiKeyId } }
1743
+ }
1744
+ return null
1745
+ }
1746
+
1747
+ // located gives a sign-in that has only ZCode's key location (ownLocation)
1748
+ // its key: the secret of the key it names, read as ZCode lists the
1749
+ // project's keys (BigModel's token bare, Z.ai's as a Bearer). Nothing is
1750
+ // made: a location whose key is gone (404) leaves the sign-in keyless, as
1751
+ // before; any other failure is said. A key read is kept for the token, and
1752
+ // the last key read for the location (lastKeys) serves while a read can't
1753
+ // reach Z.ai, so a network that drops one read keeps the plan's key; an
1754
+ // answer that refused the read (a 401, a 500) is said as before. The read
1755
+ // is bounded (KEY_READ_MS): an ask that hung for minutes
1756
+ // held the request with it (#1020, takomitkm). A read that never reached
1757
+ // Z.ai — the socket (ECONNRESET), a timeout, the name — with no key read
1758
+ // before is thrown marked unreached, which serve answers as a wall
1759
+ // (wallAnswer): it is the network, not the sign-in, so it says nothing of
1760
+ // signing in again.
1761
+ const locatedKeys = new Map()
1762
+ const lastKeys = new Map()
1763
+ const KEY_READ_MS = 20_000
1764
+ async function located(s) {
1765
+ if (!s || s.key || !s.loc || !s.token) return s
1766
+ const l = s.loc
1767
+ const at = [s.site, l.origin, l.org, l.project, l.apiKeyId].join("\0")
1768
+ const id = s.token + "\0" + at
1769
+ let got = locatedKeys.get(id)
1770
+ if (!got || (got.err && Date.now() - got.at >= 60_000)) {
1771
+ const auth = s.site === "zai" ? "Bearer " + s.token : s.token
1772
+ try {
1773
+ 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)
1774
+ got = secret ? { key: `${l.apiKeyId}.${secret}` } : { err: new Error("no secret for the key") }
1775
+ } catch (e) {
1776
+ got = e?.status === 404 ? { key: "" } : { err: e }
1777
+ }
1778
+ if (got.err && unreached(got.err) && lastKeys.get(at)) got.key = lastKeys.get(at)
1779
+ else if (!got.err) lastKeys.set(at, got.key)
1780
+ got.at = Date.now()
1781
+ locatedKeys.set(id, got)
1782
+ }
1783
+ if (got.err && !got.key) {
1784
+ const name = SITES[s.site].name
1785
+ if (unreached(got.err)) {
1786
+ const e = new Error(`ZCode's ${name} coding plan key: ${got.err.message} — ${name} could not be reached, so the request was not sent`)
1787
+ e.unreached = true
1788
+ throw e
1789
+ }
1790
+ throw new Error(`ZCode's ${name} coding plan key: ${got.err.message} — sign in to ZCode again`)
1791
+ }
1792
+ if (got.key) s.key = got.key
1793
+ return s
1794
+ }
1795
+
1796
+ // unreached says whether a fetch failed before any answer: the socket
1797
+ // closed or refused, a timeout, a name that didn't resolve. An answer with
1798
+ // a status (ZError) never is, nor is a caller's abort.
1799
+ const UNREACHED = /ECONNRESET|ECONNREFUSED|ETIMEDOUT|EPIPE|ENOTFOUND|EAI_AGAIN|ECONNABORTED|EHOSTUNREACH|ENETUNREACH|socket connection was closed|ConnectionRefused|ConnectionClosed|FailedToOpenSocket|fetch failed|timed out/i
1800
+ function unreached(e) {
1801
+ if (!e || e instanceof ZError || e.name === "AbortError") return false
1802
+ if (e.name === "TimeoutError") return true
1803
+ return [e.code, e.message, e.cause?.code, e.cause?.message].some((x) => typeof x === "string" && UNREACHED.test(x))
1804
+ }
1805
+
1806
+ // wallAnswer is a lane that can't serve the request now — not reached, or
1807
+ // its plan known full — told to magpie as a wall: a 429 whose error.code
1808
+ // is one of magpie's wallCodes (yetone/magpie@067e4c484), which it sends
1809
+ // once, never again in place, and rests as a rate limit, a minute at
1810
+ // first, while the next account is asked. A thrown error was a 502 that
1811
+ // magpie asked again eight times (#1020). The words are kept off magpie's
1812
+ // quota and credit words, so the rest stays a brief one.
1813
+ function wallAnswer(message) {
1814
+ const error = { type: "rate_limit_error", code: "user_model_rate_limited", message }
1815
+ return new Response(JSON.stringify({ type: "error", error }), { status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json" } })
1816
+ }
1817
+
1818
+ // planFull is a coding plan key whose last usage read showed a window
1819
+ // counted full with its reset ahead: until then (and for PLAN_FULL_TRUST
1820
+ // after the read at most) free first's replay doesn't send to it.
1821
+ const planFull = new Map()
1822
+ const PLAN_FULL_TRUST = 30 * 60_000
1823
+ function notePlan(key, windows) {
1824
+ if (!key) return
1825
+ let until = 0
1826
+ for (const w of windows ?? []) {
1827
+ if (w.aside) continue
1828
+ const full = (isNum(w.amount) && isNum(w.limit) && w.limit > 0 && w.amount >= w.limit) || (isNum(w.used) && w.used >= 100)
1829
+ const t = Date.parse(w.resetsAt ?? "")
1830
+ if (full && t > Date.now()) until = Math.max(until, t)
1831
+ }
1832
+ if (until) planFull.set(key, { until, at: Date.now() })
1833
+ else planFull.delete(key)
1834
+ }
1835
+ function planFullUntil(key) {
1836
+ const f = key && planFull.get(key)
1837
+ if (!f) return 0
1838
+ const now = Date.now()
1839
+ if (now >= f.until || now - f.at >= PLAN_FULL_TRUST) {
1840
+ planFull.delete(key)
1841
+ return 0
1842
+ }
1843
+ return f.until
1844
+ }
1845
+
1846
+ // ownSignIn is what ZCode is signed in to now: the account, its coding
1847
+ // plan key, ZCode's session token (the Start Plan's key) and the team plan
1848
+ // it is switched to; null when it has none of them.
1849
+ function ownSignIn() {
1850
+ const store = readJSON(join(zcodeDir(), "credentials.json"))
1851
+ if (!store || typeof store !== "object") return null
1852
+ const key = secret()
1853
+ let s = { key: "", base: "" }
1854
+ for (const [name, v] of Object.entries(store)) {
1855
+ // account-provider:coding-plan:account:zai-individual-coding-plan:account:<uuid>:api-key
1856
+ if (!name.includes(":coding-plan:") || !name.endsWith(":api-key")) continue
1857
+ const k = decrypt(key, v)
1858
+ if (!k || !k.includes(".")) continue
1859
+ const base = name.includes(":bigmodel-") ? BIGMODEL_BASE : ZAI_BASE
1860
+ // Z.ai's first, as ZCode lists it
1861
+ if (!s.key || (base === ZAI_BASE && s.base !== ZAI_BASE)) s = { key: k, base }
1862
+ }
1863
+ // ZCode 3.15 keeps no plan key in its credentials; the one it uses sits
1864
+ // in config.json, the provider's options.apiKey (yetone/magpie#2130)
1865
+ if (!s.key) s = configKey(key) || s
1866
+ // ZCode 3.16 keeps neither: only where the key is (#410)
1867
+ if (!s.key) s = ownLocation(store, key) || s
1868
+ const jwt = first(first(decrypt(key, store.zcodejwttoken)).replace(/^Bearer /, ""))
1869
+ const team = ownTeam(store, key)
1870
+ if (team) s = { ...team, jwt }
1871
+ else s = { ...s, jwt, base: s.base || ZAI_BASE, site: s.base === BIGMODEL_BASE ? "bigmodel" : "zai" }
1872
+ if (!s.key && !s.jwt && !isTeam(s)) return null
1873
+ let info = {}
1874
+ // The JWT belongs to the app's active sign-in. Cached profiles from
1875
+ // another provider must not name it, and 3.18's China sign-in is zai_cn.
1876
+ const active = decrypt(key, store["oauth:active_provider"])
1877
+ const families = [...new Set([active, "zai", "zai_cn", "bigmodel"].filter((x) => ["zai", "zai_cn", "bigmodel"].includes(x)))]
1878
+ for (const name of families.map((x) => `oauth:${x}:user_info`)) {
1879
+ const v = decrypt(key, store[name])
1880
+ if (v && !first(info.email, info.name, info.user_id)) {
1881
+ try {
1882
+ info = JSON.parse(v)
1883
+ } catch {}
1884
+ }
1885
+ }
1886
+ return { ...s, user: who(info), uid: uidOf(info) }
1887
+ }
1888
+
1889
+ // asZCode is the sign-in "as ZCode": what it reads is ZCode's own.
1890
+ function asZCode() {
1891
+ return {
1892
+ url: "",
1893
+ instructions: "Uses the account the ZCode app is signed in to, and follows it while ZCode stays signed in to that account.",
1894
+ method: "auto",
1895
+ async callback() {
1896
+ const own = ownSignIn()
1897
+ if (!own) return { type: "failed", error: ownStoreUnreadable() ? UNREADABLE_SIGN_IN : "ZCode isn't signed in on this computer; sign in to ZCode, or sign in to Z.ai or BigModel here" }
1898
+ const { user, uid, ...s } = own
1899
+ const state = { source: "zcode", device: anyDevice, ...s }
1900
+ return { type: "success", refresh: JSON.stringify(state), access: s.key || s.jwt || "", expires: 0, accountId: user, ...(uid ? { uid } : {}) }
1901
+ },
1902
+ }
1903
+ }
1904
+
1905
+ // stateOf is a stored sign-in as the requests need it.
1906
+ function stateOf(auth) {
1907
+ if (auth?.type === "oauth") {
1908
+ let s = {}
1909
+ try {
1910
+ s = JSON.parse(auth.refresh)
1911
+ } catch {}
1912
+ if (s.source === "zcode") {
1913
+ // ZCode's own, read now, while ZCode is signed in to this same
1914
+ // account. Signed out, or signed in to another account since, it is
1915
+ // what it was when this was signed in: another account's key would
1916
+ // send this account's requests as that one, and an expired session
1917
+ // says sign in again (EXPIRED) rather than borrowing another's.
1918
+ const own = ownSignIn()
1919
+ // (by user id where both have one: another account may share the name)
1920
+ if (own && own.user === String(auth.accountId ?? "") && (!own.uid || !auth.uid || own.uid === String(auth.uid))) {
1921
+ const { user, uid: _uid, ...now } = own
1922
+ s = { source: "zcode", device: s.device, plan: s.plan, ...now }
1923
+ }
1924
+ }
1925
+ const site = siteOf(s.site)
1926
+ const key = s.key ?? (s.jwt ? "" : auth.access)
1927
+ return { ...s, site, base: s.base || SITES[site].base, key, device: s.device || (key ? keyDevice(key) : anyDevice) }
1928
+ }
1929
+ if (auth?.type === "api") {
1930
+ const site = siteOf(auth.metadata?.site)
1931
+ const key = String(auth.key ?? "").trim()
1932
+ return { site, base: SITES[site].base, key, device: key ? keyDevice(key) : anyDevice }
1933
+ }
1934
+ return null
1935
+ }
1936
+
1937
+ // ---- models ----------------------------------------------------------------------
1938
+
1939
+ // planID is ZCode's providerId for the plan served at base; a team's plan
1940
+ // has the individual one's models.
1941
+ const planID = (base) =>
1942
+ base.includes("/zcode-plan/")
1943
+ ? "account:zai-start-plan"
1944
+ : base.includes("bigmodel.cn")
1945
+ ? "account:bigmodel-individual-coding-plan"
1946
+ : "account:zai-individual-coding-plan"
1947
+
1948
+ const efforts = (vs) => [...new Set(vs.map((v) => (v === "disabled" ? "none" : v === "enabled" ? "high" : v)))]
1949
+
1950
+ // modelsOf is a plan's models in ZCode's provider config.
1951
+ function modelsOf(cfg, plan) {
1952
+ const c = cfg?.config ?? {}
1953
+ const ids = []
1954
+ const on = new Set()
1955
+ const add = (id) => {
1956
+ if (!on.has(id.toLowerCase())) on.add(id.toLowerCase()), ids.push(id)
1957
+ }
1958
+ for (const r of c.providerConfigRules?.providerRules ?? []) if (r.providerId === plan) (r.builtinModelIds ?? []).forEach(add)
1959
+ const off = new Set()
1960
+ for (const r of c.modelConfigRules?.builtinProviderModelRules ?? []) {
1961
+ if (r.providerId !== plan) continue
1962
+ if (r.config?.enabled === false) off.add(String(r.modelId).toLowerCase())
1963
+ else add(r.modelId)
1964
+ }
1965
+ const out = []
1966
+ for (const id of ids) {
1967
+ if (off.has(id.toLowerCase())) continue
1968
+ const m = { id, context: 0, output: 0, efforts: [] }
1969
+ for (const r of c.modelConfigRules?.modelRules ?? []) {
1970
+ let re
1971
+ try {
1972
+ re = new RegExp(`^(?:${r.modelMatch})$`, "i")
1973
+ } catch {
1974
+ continue
1975
+ }
1976
+ if (!re.test(id)) continue
1977
+ const x = r.config ?? {}
1978
+ if (x.properties?.contextWindow > 0) m.context = x.properties.contextWindow
1979
+ if (x.optionSpecs?.maxOutputTokens?.max > 0) m.output = x.optionSpecs.maxOutputTokens.max
1980
+ if (typeof x.properties?.inputFormat?.supportsImage === "boolean") m.image = x.properties.inputFormat.supportsImage
1981
+ if (x.optionSpecs?.reasoningLevel?.values?.length) m.efforts = efforts(x.optionSpecs.reasoningLevel.values)
1982
+ }
1983
+ out.push(m)
1984
+ }
1985
+ return out
1986
+ }
1987
+
1988
+ // localConfig is the latest provider config an installed ZCode has.
1989
+ function localConfig() {
1990
+ const files = []
1991
+ const rt = join(zcodeDir(), "runtime", "provider")
1992
+ const walk = (dir, depth) => {
1993
+ let es = []
1994
+ try {
1995
+ es = readdirSync(dir, { withFileTypes: true })
1996
+ } catch {
1997
+ return
1998
+ }
1999
+ for (const e of es) {
2000
+ if (depth < 3 && e.isDirectory()) walk(join(dir, e.name), depth + 1)
2001
+ else if (depth === 3 && e.name === "zcode-builtin.json") files.push(join(dir, e.name))
2002
+ }
2003
+ }
2004
+ walk(rt, 0)
2005
+ if (process.platform === "darwin") files.push("/Applications/ZCode.app/Contents/Resources/config/provider/zcode-builtin.json")
2006
+ let best = null
2007
+ for (const f of files) {
2008
+ try {
2009
+ if (!existsSync(f)) continue
2010
+ const b = JSON.parse(readFileSync(f, "utf8"))
2011
+ if (!best || (b.revision ?? 0) > (best.revision ?? 0)) best = b
2012
+ } catch {}
2013
+ }
2014
+ return best
2015
+ }
2016
+
2017
+ // remoteConfig is the release of ZCode's provider config zcode.z.ai names now.
2018
+ async function remoteConfig() {
2019
+ const signal = AbortSignal.timeout(8000)
2020
+ const c = await clientConfigs()
2021
+ const url = c?.configs?.builtin_provider_config_json
2022
+ if (!String(url ?? "").startsWith("https://")) throw new Error("ZCode's configs name no provider config")
2023
+ const res = await fetch(url, { headers: { "User-Agent": UA }, signal })
2024
+ if (!res.ok) throw new Error(`ZCode's provider config: ${res.status}`)
2025
+ return res.json()
2026
+ }
2027
+
2028
+ // clientConfigs is what zcode.z.ai tells this client version
2029
+ // (/api/v1/client/configs): the provider config's address, and the
2030
+ // captcha its claims and requests need (claimNeedsCaptcha). A read that
2031
+ // came through is kept for 10 minutes; a failed one is not kept, and
2032
+ // throws.
2033
+ let clientCache = null
2034
+ async function clientConfigs() {
2035
+ if (clientCache && Date.now() - clientCache.at < 600_000) return clientCache.c
2036
+ const c = await call("GET", `${ZCODE}/api/v1/client/configs?app_version=${APP_VERSION}&platform=${platform()}`, { signal: AbortSignal.timeout(8000) })
2037
+ clientCache = { c, at: Date.now() }
2038
+ return c
2039
+ }
2040
+ // resetClientConfigs is for tests: the next read asks zcode.z.ai again.
2041
+ export function resetClientConfigs() {
2042
+ clientCache = null
2043
+ }
2044
+
2045
+ // config is ZCode's provider config, the later of zcode.z.ai's and an
2046
+ // installed ZCode's, kept for 10 minutes.
2047
+ let cfgCache = null
2048
+ async function zcodeConfig() {
2049
+ if (cfgCache && Date.now() - cfgCache.at < 600_000) return cfgCache.cfg
2050
+ let cfg = null
2051
+ try {
2052
+ cfg = await remoteConfig()
2053
+ } catch {}
2054
+ const local = localConfig()
2055
+ if (local && (!cfg || (local.revision ?? 0) > (cfg.revision ?? 0))) cfg = local
2056
+ cfgCache = { cfg, at: Date.now() }
2057
+ return cfg
2058
+ }
2059
+
2060
+ // variants are a model's reasoning efforts as @ai-sdk/anthropic options.
2061
+ const BUDGET = { minimal: 1024, low: 4096, medium: 8192, high: 16_000, max: 31_999 }
2062
+ function variants(es) {
2063
+ const out = {}
2064
+ for (const e of es) out[e] = e === "none" ? { thinking: { type: "disabled" } } : { thinking: { type: "enabled", budgetTokens: BUDGET[e] ?? 16_000 } }
2065
+ return out
2066
+ }
2067
+
2068
+ // entry is a model as a config hook declares it.
2069
+ const entry = (m) => ({
2070
+ id: m.id,
2071
+ name: m.id,
2072
+ reasoning: m.efforts.some((e) => e !== "none"),
2073
+ tool_call: true,
2074
+ attachment: !!m.image,
2075
+ modalities: { input: m.image ? ["text", "image"] : ["text"], output: ["text"] },
2076
+ // what ZCode's config names, else 0 (unknown), as magpie's built-in
2077
+ limit: { context: m.context || 0, output: m.output || 0 },
2078
+ cost: { input: 0, output: 0, cache_read: 0, cache_write: 0 },
2079
+ variants: variants(m.efforts),
2080
+ })
2081
+
2082
+ // model is a model as OpenCode's provider hands it to provider.models.
2083
+ // modelOf reads the model a Messages body asks for.
2084
+ function modelOf(text) {
2085
+ try {
2086
+ const m = JSON.parse(text)?.model
2087
+ return typeof m === "string" ? m : ""
2088
+ } catch {
2089
+ return ""
2090
+ }
2091
+ }
2092
+
2093
+ // kept passes a response on as it came, the account kept: the built-in
2094
+ // never marked a ZCode account lapsed nor cleared one.
2095
+ function kept(res, text) {
2096
+ const h = new Headers(res.headers)
2097
+ h.delete("content-length")
2098
+ h.delete("content-encoding")
2099
+ h.set("X-Magpie-Sign-In", "kept")
2100
+ return new Response(text !== undefined ? text : res.body, { status: res.status, statusText: res.statusText, headers: h })
2101
+ }
2102
+
2103
+ // ---- the plan's concurrency ------------------------------------------------------
2104
+ // ZCode serves one account a few requests at a time. Past that it answers 429
2105
+ // with code 3008, "user concurrency limit exceeded", 3009, "model
2106
+ // concurrency limit exceeded", or 3010: the request's turn has not come — not
2107
+ // a plan spent (1113/1005) and not a rate limit (1302/1303). ZCode's own
2108
+ // client (3.17.2) reads the three as one ("当前系统繁忙"), asks again after 1s
2109
+ // and 2s, and then gives up; it sends one request per session at a time and
2110
+ // has no hold. magpie sends every agent's and every session's requests of
2111
+ // this computer through this one process, so the plugin does what that
2112
+ // client does: the Start Plan gets a few requests of an account in flight at
2113
+ // once (startGate), the rest wait their turn here instead of being sent to be
2114
+ // refused, and a refusal anyway is asked again twice (BUSY_WAITS). A refusal
2115
+ // of a request sent beside others of the same account lowers that account's
2116
+ // gate and waits its turn again (askBusy's requeue), as ZCode's own
2117
+ // dynamic-workflow governor cuts its cap and queues a capped subagent
2118
+ // request rather than failing it.
2119
+ //
2120
+ // The coding plan keeps no gate of the plugin's: its cap depends on its tier
2121
+ // (Z.ai serves Max more at once than Pro, and Lite fewer) and is higher
2122
+ // off-peak (https://docs.z.ai/devpack/usage-policy), so a number written here
2123
+ // would hold a Max account to a Lite one's. magpie's own queue spaces it by
2124
+ // the number declared below (DEFAULT_CONCURRENCY, on the auth hook and in
2125
+ // package.json), which a user raises on the account.
2126
+ const DEFAULT_CONCURRENCY = 3
2127
+ // No maxAccounts is declared: magpie sends requests to every ZCode account
2128
+ // of the user's, and a user still sets their own on the provider (Accounts
2129
+ // at once). 0.1.40 to 0.1.67 declared two, after 01huadalang's address was
2130
+ // refused with a 405 while three accounts took requests at once (Discord),
2131
+ // and the others sat in reserve until one ran out: a user with five gift
2132
+ // accounts saw two used (mathfournity on X). What the edge firewall counts
2133
+ // is this address's Start Plan requests in flight, not its accounts (see
2134
+ // busyHold), so that is what is held now, over every account (startGate's
2135
+ // address): as many as two accounts had in flight before, while a coding
2136
+ // plan account, on another host, is held to none of it.
2137
+ const BUSY_CODES = new Set(["3008", "3009", "3010"])
2138
+ // BUSY_WAITS are the waits before each ask again: ZCode's own client's,
2139
+ // 1s and 2s (kqo in its bundle). Past them the cap goes back to magpie,
2140
+ // which takes the request to another account or rests this one as its 429
2141
+ // says. Six asks over ten seconds, before 0.1.56, put two or three times the
2142
+ // requests a capped account could serve on the wire, and the agents' own
2143
+ // retries came on top.
2144
+ const BUSY_WAITS = [1000, 2000]
2145
+ // REQUEUE_MAX bounds how often one request is handed back to the gate by a
2146
+ // narrowing (askBusy): each narrowing lowers the gate, three to one at most
2147
+ // takes two, so more is a fault of the count, not ZCode.
2148
+ const REQUEUE_MAX = 4
2149
+ // The hint names neither "plan" nor "limit": after the vendor's "…limit
2150
+ // exceeded" either would read to magpie as a plan used up.
2151
+ const BUSY_HINT =
2152
+ "ZCode serves one account a few requests at a time and was still busy when asked again after 1s and 2s; run fewer agents or subagents on ZCode at once, or try again in a moment"
2153
+
2154
+ // startGate is the Start Plan's in-flight count per account. PR #395 measured
2155
+ // one Z.ai gift account at 3 of 12 parallel requests served in one run and 4
2156
+ // of 12 in another, so three are in flight at once, what magpie's queue sends
2157
+ // by DEFAULT_CONCURRENCY too. The gate holds them there when that queue
2158
+ // doesn't: a user who raised the account's number for the coding plan, two
2159
+ // magpie providers signed in to one account, a host that doesn't read
2160
+ // maxConcurrency. A cap the server still says now and then (a slot it lets
2161
+ // go of late, the ZCode app on the same account) the 1s re-ask gets past.
2162
+ // A request past them waits here, first come first served, until one is
2163
+ // answered to the end, up to startGate.wait; an agent that gives up leaves
2164
+ // the queue. A wait that runs out is answered startQueueAnswer's 429,
2165
+ // nothing sent. The gate lives in this process's memory alone, by account
2166
+ // (gateKey).
2167
+ //
2168
+ // An account ZCode serves fewer than that (plugins#438: one account, one
2169
+ // agent, never more than two in flight, and refused at two) is narrowed:
2170
+ // a request refused again at its 1s re-ask while others of this computer
2171
+ // were in flight beside it (busyCap) tells the cap is below the gate, and
2172
+ // the account's gate goes down to one fewer than were in flight, at least
2173
+ // one, for NARROW_FOR. Such a cap is this computer asking too much at once,
2174
+ // which the narrowed gate now stops, so it counts toward no firewall hold.
2175
+ // narrow is kept apart from lanes, which go when idle; now is its clock,
2176
+ // injectable for tests.
2177
+ const NARROW_FOR = 5 * 60_000
2178
+ const startGate = { inflight: 3, address: 6, wait: 120_000, lanes: new Map(), narrow: new Map(), now: () => Date.now() }
2179
+ // ADDRESS is the lane every account's Start Plan requests share as well as
2180
+ // their own: zcode.z.ai sees one address, and its firewall refused the whole
2181
+ // of it with 405 once ~10 were in flight (busyHold). startGate.address is
2182
+ // six, what two accounts of three each sent when the plugin declared
2183
+ // maxAccounts two, which no 405 followed. It is never narrowed.
2184
+ const ADDRESS = "\0address"
2185
+
2186
+ // limitOf is how many of the account's Start Plan requests go at once: the
2187
+ // gate's number, or less while the account is narrowed.
2188
+ function limitOf(key) {
2189
+ if (key === ADDRESS) return startGate.address
2190
+ const n = startGate.narrow.get(key)
2191
+ if (!n) return startGate.inflight
2192
+ if (startGate.now() >= n.until) {
2193
+ startGate.narrow.delete(key)
2194
+ return startGate.inflight
2195
+ }
2196
+ return Math.min(startGate.inflight, n.limit)
2197
+ }
2198
+
2199
+ // narrowed lowers the account's gate below the requests that were in flight
2200
+ // when one was refused again (busy, its own included), and says whether it
2201
+ // did: a lone request refused again is not this computer's doing.
2202
+ function narrowed(key) {
2203
+ const busy = startGate.lanes.get(key)?.busy ?? 0
2204
+ if (busy < 2) return false
2205
+ const limit = Math.max(1, Math.min(limitOf(key), busy - 1))
2206
+ startGate.narrow.set(key, { limit, until: startGate.now() + NARROW_FOR })
2207
+ return true
2208
+ }
2209
+
2210
+ // startFull says the account's Start Plan slots are all taken, or others wait.
2211
+ const startFull = (key) => {
2212
+ const l = startGate.lanes.get(key)
2213
+ return !!l && (l.busy >= limitOf(key) || l.queue.length > 0)
2214
+ }
2215
+
2216
+ // startSlot waits for one of the account's Start Plan slots: { release },
2217
+ // null when the wait (startGate.wait unless given) ran out first, or the
2218
+ // agent's abort thrown. A request handed back by a narrowing (requeued) was
2219
+ // first in line already, so it waits at the head of the queue.
2220
+ function startSlot(key, signal, { wait = startGate.wait, front = false } = {}) {
2221
+ const lanes = startGate.lanes
2222
+ let l = lanes.get(key)
2223
+ if (!l) lanes.set(key, (l = { busy: 0, queue: [] }))
2224
+ const next = () => {
2225
+ while (l.busy < limitOf(key) && l.queue.length) l.queue.shift()()
2226
+ if (!l.busy && !l.queue.length && lanes.get(key) === l) lanes.delete(key)
2227
+ }
2228
+ const take = () => {
2229
+ l.busy++
2230
+ let gone = false
2231
+ return {
2232
+ release() {
2233
+ if (gone) return
2234
+ gone = true
2235
+ l.busy--
2236
+ next()
2237
+ },
2238
+ }
2239
+ }
2240
+ if (signal?.aborted) return Promise.reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"))
2241
+ if (l.busy < limitOf(key) && !l.queue.length) return Promise.resolve(take())
2242
+ return new Promise((resolve, reject) => {
2243
+ const leave = () => {
2244
+ clearTimeout(timer)
2245
+ signal?.removeEventListener?.("abort", aborted)
2246
+ const i = l.queue.indexOf(go)
2247
+ if (i >= 0) l.queue.splice(i, 1)
2248
+ }
2249
+ const go = () => {
2250
+ leave()
2251
+ resolve(take())
2252
+ }
2253
+ const aborted = () => {
2254
+ leave()
2255
+ next()
2256
+ reject(signal.reason ?? new DOMException("The operation was aborted.", "AbortError"))
2257
+ }
2258
+ const timer = setTimeout(() => {
2259
+ leave()
2260
+ next()
2261
+ resolve(null)
2262
+ }, Math.max(0, wait))
2263
+ signal?.addEventListener?.("abort", aborted, { once: true })
2264
+ if (front) l.queue.unshift(go)
2265
+ else l.queue.push(go)
2266
+ })
2267
+ }
2268
+
2269
+ // startSlots waits for a slot of the account's, then one of the address's
2270
+ // (ADDRESS), both within the one wait: { release } letting both go, or
2271
+ // { key } naming the lane whose wait ran out, nothing held. Every request
2272
+ // takes the account's first, so one holding the address's never waits for
2273
+ // an account's.
2274
+ async function startSlots(key, signal, { wait = startGate.wait, front = false } = {}) {
2275
+ const until = Date.now() + wait
2276
+ const mine = await startSlot(key, signal, { wait, front })
2277
+ if (!mine) return { key }
2278
+ let all
2279
+ try {
2280
+ all = await startSlot(ADDRESS, signal, { wait: until - Date.now(), front })
2281
+ } catch (e) {
2282
+ mine.release()
2283
+ throw e
2284
+ }
2285
+ if (!all) {
2286
+ mine.release()
2287
+ return { key: ADDRESS }
2288
+ }
2289
+ return {
2290
+ release() {
2291
+ all.release()
2292
+ mine.release()
2293
+ },
2294
+ }
2295
+ }
2296
+
2297
+ // released hands res on and lets its slot go once ZCode's answer has come
2298
+ // to its end, failed, or been given up on (the agent's abort, the reader's
2299
+ // cancel) — the request is in flight at ZCode until then. The answer is read
2300
+ // as it comes, whether or not the agent reads it yet, so a reply read late,
2301
+ // or dropped unread, does not keep its slot past ZCode's own end of it.
2302
+ function released(res, slot, signal) {
2303
+ if (!slot) return res
2304
+ if (!res.body) {
2305
+ slot.release()
2306
+ return res
2307
+ }
2308
+ const reader = res.body.getReader()
2309
+ const stop = (why) => {
2310
+ slot.release()
2311
+ reader.cancel(why).catch(() => {})
2312
+ }
2313
+ signal?.addEventListener?.("abort", () => slot.release(), { once: true })
2314
+ const pump = async (c) => {
2315
+ try {
2316
+ for (;;) {
2317
+ const { done, value } = await reader.read()
2318
+ if (done) break
2319
+ c.enqueue(value)
2320
+ }
2321
+ slot.release()
2322
+ c.close()
2323
+ } catch (e) {
2324
+ slot.release()
2325
+ try {
2326
+ c.error(e)
2327
+ } catch {}
2328
+ }
2329
+ }
2330
+ // started, not awaited: the agent reads each chunk as it comes
2331
+ const body = new ReadableStream({ start: (c) => void pump(c), cancel: stop })
2332
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers })
2333
+ }
2334
+
2335
+ // startQueueAnswer is a request that waited its whole turn behind the
2336
+ // account's others and was never sent: a 429 magpie reads as a rate limit,
2337
+ // so it tries the next account, and a short Retry-After.
2338
+ function startQueueAnswer(key) {
2339
+ const n = limitOf(key)
2340
+ const s = n === 1 ? "" : "s"
2341
+ const error = {
2342
+ type: "rate_limit_error",
2343
+ message: key === ADDRESS
2344
+ ? `ZCode's free Start Plan is sent ${n} request${s} at a time from this computer, over all its accounts, as more get the address refused; 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`
2345
+ : `ZCode's free Start Plan serves this account ${n} request${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`,
2346
+ }
2347
+ return new Response(JSON.stringify({ type: "error", error }), {
2348
+ status: 429, statusText: STATUS_TEXT[429], headers: { "content-type": "application/json", "retry-after": "5" },
2349
+ })
2350
+ }
2351
+
2352
+ // busyHold is the firewall's countdown. Two days of logs (11-05 23:06–23:15
2353
+ // and 11-06 06:23–06:27) show the same shape: sustained ~18 requests/min on
2354
+ // the Start Plan, up to ~10 of them in flight against a cap of about three,
2355
+ // brings code-3008 caps in a run, and 3–7.5 minutes later the edge firewall
2356
+ // (errors.aliyun.com) refuses the whole IP with 405 for 1–2 hours. Re-asks
2357
+ // absorbed ~90% of those caps, so neither magpie nor the agent saw that the
2358
+ // address was saturated and nobody slowed the arrival rate down. startGate
2359
+ // now keeps this computer's own requests under the cap, so a cap is ZCode
2360
+ // busy or another client on the account; a request refused on its first ask
2361
+ // and again a second later (busyCap) is that, sustained, and BUSY_N of them
2362
+ // in one minute hold the Start Plan (zcode.z.ai only, process-wide, every
2363
+ // account) off BUSY_HOLD. A sustained cap of a request with others of the
2364
+ // same account in flight beside it counts for nothing either: it narrows the
2365
+ // account's gate (startGate), which then sends no more than ZCode serves
2366
+ // (plugins#438: an account served one at a time, two in flight from one
2367
+ // agent, held again and again at ~5 requests/min). #801's caps came with up
2368
+ // to ~10 in flight, which the gate now never sends, and an account whose
2369
+ // slots are taken elsewhere is narrowed to one within a few caps and then
2370
+ // refused alone, which counts as before. A cap the 1s re-ask got past counts for nothing:
2371
+ // on 0.1.55 every capped request counted, a lone late slot as much as a
2372
+ // saturated address, and busy afternoons held users for nothing. Replay of
2373
+ // both days: N=5, H=3min froze 2–7 minutes before the first 405 and spared
2374
+ // 37–52 requests. A held request answers 429 with Retry-After, so magpie
2375
+ // still reads a rate limit, rests the account and fails over; it is not the
2376
+ // 405/BlockedHint of an IP already refused. The coding plan, on another
2377
+ // host, is never held. The hold lives in this process's memory alone: magpie
2378
+ // restarting forgets it. Only model requests are held — balance reads, the
2379
+ // usage card and check-in still reach zcode.z.ai during it (the check-in
2380
+ // holds its own reads per account on a 429).
2381
+ const BUSY_N = 5
2382
+ const BUSY_WINDOW = 60_000
2383
+ const BUSY_HOLD = 3 * 60_000
2384
+ const busyHold = { hits: [], until: 0, now: () => Date.now() }
2385
+ // busyHold.now is the clock, injectable for tests: a hold's window, its
2386
+ // length and its expiry all read through it.
2387
+ const busyHeld = () => busyHold.now() < busyHold.until
2388
+
2389
+ // busyCap records one sustained concurrency cap of a Start Plan request.
2390
+ // Only a run arms a hold; the window is cleared on arming, and a cap that
2391
+ // lands while the hold is on counts toward nothing — the hold's own 429s and
2392
+ // the first caps after it cannot keep re-arming it. It says true when the
2393
+ // cap narrowed the account instead: the request is then requeued, not
2394
+ // failed (see askBusy).
2395
+ function busyCap(key) {
2396
+ if (key != null && narrowed(key)) return true
2397
+ if (busyHeld()) return false
2398
+ const now = busyHold.now()
2399
+ busyHold.hits.push(now)
2400
+ while (busyHold.hits.length && now - busyHold.hits[0] > BUSY_WINDOW) busyHold.hits.shift()
2401
+ if (busyHold.hits.length >= BUSY_N) {
2402
+ busyHold.until = now + BUSY_HOLD
2403
+ busyHold.hits.length = 0
2404
+ }
2405
+ return false
2406
+ }
2407
+
2408
+ // BUSY_HOLD_MARK marks an answer the hold made up: a request the gate or the
2409
+ // hold stopped locally never reached ZCode, and it says nothing about the
2410
+ // gift's quota. The gift paths (a -Trial pick, free first) read the mark
2411
+ // before they judge the answer spent, so a hold's 429 passes through as the
2412
+ // rate limit it is and arms no minute's rest (11-08: the hold's answer
2413
+ // through a -Trial entry read as "over its quota" with half the free quota
2414
+ // left).
2415
+ const BUSY_HOLD_MARK = "x-magpie-busy-hold"
2416
+
2417
+ function busyHeldAnswer() {
2418
+ const wait = Math.max(1, Math.ceil((busyHold.until - busyHold.now()) / 1000))
2419
+ const error = {
2420
+ type: "rate_limit_error",
2421
+ message: `ZCode turned away ${BUSY_N} requests in the last minute as too many requests at once, each again when asked a second later. So that ZCode's firewall does not block this network, magpie sends no free Start Plan requests for the next ${wait}s. Wait, run fewer agents or subagents on ZCode at once, or use a GLM Coding Plan model`,
2422
+ }
2423
+ return new Response(JSON.stringify({ type: "error", error }), {
2424
+ status: 429, statusText: STATUS_TEXT[429],
2425
+ headers: { "content-type": "application/json", "retry-after": String(wait), [BUSY_HOLD_MARK]: "1" },
2426
+ })
2427
+ }
2428
+
2429
+ // busy says a 429 is that in-flight cap: its own code (3008, 3009, 3010), or its
2430
+ // own words when the envelope carries no code.
2431
+ function busy(status, text) {
2432
+ if (status !== 429) return false
2433
+ let b
2434
+ try {
2435
+ b = JSON.parse(text)
2436
+ } catch {
2437
+ return false
2438
+ }
2439
+ if (!b || typeof b !== "object") return false
2440
+ const say = (v) => (v == null || typeof v === "object" ? "" : String(v))
2441
+ if (BUSY_CODES.has(say(b.code) || say(b.error?.code))) return true
2442
+ return /concurrency limit exceeded/i.test(say(b.msg) + " " + say(b.message) + " " + say(b.error?.message) + " " + say(b.error))
2443
+ }
2444
+
2445
+ // busyAnswer is the vendor's cap refusal as the agent reads it: its words,
2446
+ // then what they are and what to do, as noPlanKey says why a key has no plan.
2447
+ function busyAnswer(res, text) {
2448
+ const h = new Headers(res.headers)
2449
+ h.set("content-type", "application/json")
2450
+ let v
2451
+ try {
2452
+ v = JSON.parse(text)
2453
+ } catch {}
2454
+ if (v && typeof v === "object") {
2455
+ const said = first(v.msg, v.message, v.error?.message, typeof v.error === "string" ? v.error : "", `${res.status}`)
2456
+ const code = v.code ?? v.error?.code
2457
+ const head = code != null && !said.includes(String(code)) ? `${said} (${res.status}, code ${code})` : said
2458
+ const message = `${head} — ${BUSY_HINT}`
2459
+ const out = v.error && typeof v.error === "object" ? { ...v, error: { ...v.error, message } } : { ...v, msg: message }
2460
+ return new Response(JSON.stringify(out), { status: res.status, statusText: res.statusText, headers: h })
2461
+ }
2462
+ return new Response(JSON.stringify({ type: "error", error: { type: "rate_limit_error", message: `${res.status} ${STATUS_TEXT[res.status] ?? res.statusText} — ${BUSY_HINT}`.trim() } }), {
2463
+ status: res.status,
2464
+ statusText: res.statusText,
2465
+ headers: h,
2466
+ })
2467
+ }
2468
+
2469
+ // askBusy asks once and, when the answer is the vendor's in-flight cap
2470
+ // (3008/3009/3010, or its own words), asks again after BUSY_WAITS's waits,
2471
+ // 1s and then 2s, as ZCode's own client does. Past them the cap goes back as
2472
+ // busyAnswer's 429. A request refused again at its 1s re-ask is a sustained
2473
+ // cap, told to onCap once (the firewall hold's count); one the re-ask got
2474
+ // past is not. When onCap says the cap narrowed the account (others of this
2475
+ // computer were in flight on it), asking again in 2s would only be refused
2476
+ // beside them again: the busyAnswer goes back at once marked `requeue`, and
2477
+ // the Start Plan path waits for one of those others to end and sends it
2478
+ // again (JJLIN070414 on X: two sessions on one account, each pair's second
2479
+ // request failed 429 where ZCode's own client queues it). The plan path's
2480
+ // patience, shared with free first's replay, whose plan has a cap of its own.
2481
+ async function askBusy(u, o, hs, onCap) {
2482
+ let res = await fetch(u, { ...o, headers: hs })
2483
+ let caps = 0
2484
+ for (let i = 0; res.status === 429; i++) {
2485
+ const text = await res.text()
2486
+ const cap = busy(429, text)
2487
+ // one request's refusals are one saturation signal, not one per ask
2488
+ if (cap && ++caps === 2 && onCap?.() === true) {
2489
+ res = busyAnswer(res, text)
2490
+ res.requeue = true
2491
+ break
2492
+ }
2493
+ // the hold armed: a request already in flight stops asking too. The
2494
+ // second check catches the asks that capped before the hold armed and
2495
+ // woke from their wait after it. Keying on onCap keeps the coding plan
2496
+ // and free first's replay (no onCap) as they are.
2497
+ if (cap && onCap && busyHeld()) { res = busyHeldAnswer(); break }
2498
+ if (!cap || i >= BUSY_WAITS.length) {
2499
+ res = cap ? busyAnswer(res, text) : new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
2500
+ break
2501
+ }
2502
+ await sleep(BUSY_WAITS[i])
2503
+ if (onCap && busyHeld()) { res = busyHeldAnswer(); break }
2504
+ res = await fetch(u, { ...o, headers: hs })
2505
+ }
2506
+ return res
2507
+ }
2508
+
2509
+ function model(m, url) {
2510
+ const e = entry(m)
2511
+ return {
2512
+ id: m.id,
2513
+ providerID: PROVIDER,
2514
+ name: m.id,
2515
+ api: { id: m.id, url, npm: "@ai-sdk/anthropic" },
2516
+ status: "active",
2517
+ cost: { input: 0, output: 0, cache: { read: 0, write: 0 } },
2518
+ limit: e.limit,
2519
+ options: {},
2520
+ headers: {},
2521
+ capabilities: {
2522
+ temperature: true,
2523
+ reasoning: e.reasoning,
2524
+ attachment: e.attachment,
2525
+ toolcall: true,
2526
+ input: { text: true, image: !!m.image, audio: false, video: false, pdf: false },
2527
+ output: { text: true, image: false, audio: false, video: false, pdf: false },
2528
+ interleaved: false,
2529
+ },
2530
+ release_date: "",
2531
+ variants: e.variants,
2532
+ }
2533
+ }
2534
+
2535
+ // ---- the Start Plan's requests ----------------------------------------------------
2536
+ // zcode.z.ai answers 405 "request has been blocked due to unusual
2537
+ // activity" (code 3012) to a request that doesn't look like ZCode's own
2538
+ // (#343: the agent's system prompt as a fourth block), and to every
2539
+ // request of an account its risk control blocked, ZCode's own app's too
2540
+ // (plugins#348). A Start Plan request goes as the plugin
2541
+ // the plan serves (ARNO's "Freeflow", provider zcode-start) sends it: its
2542
+ // headers (startHeaders) and its body (dress). The texts are prompt.mjs.
2543
+
2544
+ // START_RESTRICTED is what ZCode's 3012, "request has been blocked due to
2545
+ // unusual activity", means: ZCode's risk control blocked the account
2546
+ // (ZCode's support says so, and ZCode's own app gets the same 405 on such
2547
+ // an account, plugins#348), not that the request was sent wrong. Word for
2548
+ // word magpie's provider.ZCodeRestrictedHint: the gateway reads it as the
2549
+ // account restricted, rests it and asks the group's next member, and the
2550
+ // Routing page says it in the user's language.
2551
+ const START_RESTRICTED = "ZCode's risk control blocked this account for unusual activity (code 3012); it rests, and the group's other providers are used. If the ZCode app fails on this account too, only ZCode support can lift the block"
2552
+ // START_EDGE is what a block page from ZCode's edge firewall (Aliyun's)
2553
+ // means: this network's address, not the account. Word for word magpie's
2554
+ // provider.BlockedHint.
2555
+ const START_EDGE = "the provider's network firewall blocked requests from this IP; wait a while, or switch to another network or proxy"
2556
+ const EDGE_PAGE = /errors\.aliyun\.com|<html/i
2557
+ const START_REFUSED = /unusual activity|request has been blocked|"code"\s*:\s*"?3012\b/i
2558
+
2559
+ // startRefused says a Start Plan answer is a refusal: a 405, a block page
2560
+ // or code 3012.
2561
+ const startRefused = (status, text) => status >= 400 && (status === 405 || START_REFUSED.test(text))
2562
+
2563
+ // edge is the hold a block page puts on this computer's address: zcode.z.ai
2564
+ // (the Start Plan, a gift) is not asked again until edge.until, and its
2565
+ // requests are answered here with the same 405 and START_EDGE, so magpie
2566
+ // still reads them as the network's (provider.EdgeBlocked) and asks the
2567
+ // group's next provider. Every account of this process goes out from the
2568
+ // one address, so the hold is the process's, not an account's. Asking on
2569
+ // while the address is blocked, from every account and every session, only
2570
+ // knocks again on a firewall that is counting (plugins#649: two accounts,
2571
+ // three sessions and their subagents, and ZCode's own app blocked too; a
2572
+ // block in #369 lasted about seven minutes). EDGE_HOLD is short enough that
2573
+ // a user who switched network or proxy waits little for it.
2574
+ const EDGE_HOLD = 3 * 60_000
2575
+ const edge = { until: 0 }
2576
+ const edgeHeld = () => Date.now() < edge.until
2577
+
2578
+ function hhmm(t) {
2579
+ const d = new Date(t)
2580
+ return String(d.getHours()).padStart(2, "0") + ":" + String(d.getMinutes()).padStart(2, "0") + ":" + String(d.getSeconds()).padStart(2, "0")
2581
+ }
2582
+
2583
+ // edgeHeldAnswer is a held request's answer: the block page's status and
2584
+ // meaning, and until when this computer holds off.
2585
+ function edgeHeldAnswer() {
2586
+ const error = { type: "permission_error", message: `405 ${STATUS_TEXT[405]} — ${START_EDGE} (ZCode's Start Plan is not asked again from here until ${hhmm(edge.until)}, plugins#649)` }
2587
+ return new Response(JSON.stringify({ type: "error", error }), { status: 405, statusText: STATUS_TEXT[405], headers: { "content-type": "application/json" } })
2588
+ }
2589
+
2590
+ // startBlocked is the refusal's answer: what the vendor said (its status
2591
+ // for a block page), then what it means. A block page is the network's;
2592
+ // anything else, ZCode's JSON 3012 or a bare 405, the account's.
2593
+ function startBlocked(res, text) {
2594
+ const page = EDGE_PAGE.test(text)
2595
+ let said = ""
2596
+ if (!page) {
2597
+ try {
2598
+ const v = JSON.parse(text)
2599
+ said = first(v?.error?.message, typeof v?.error === "string" ? v.error : "", v?.message, v?.msg)
2600
+ const code = v?.code ?? v?.error?.code
2601
+ if (said && code != null && !String(said).includes(String(code))) said = `${said} (${res.status}, code ${code})`
2602
+ } catch {}
2603
+ }
2604
+ said ||= `${res.status} ${STATUS_TEXT[res.status] ?? res.statusText}`.trim()
2605
+ const h = new Headers(res.headers)
2606
+ h.set("content-type", "application/json")
2607
+ const error = { type: "permission_error", message: `${said} — ${page ? START_EDGE : START_RESTRICTED}` }
2608
+ return new Response(JSON.stringify({ type: "error", error }), { status: res.status, statusText: res.statusText, headers: h })
2609
+ }
2610
+
2611
+ const osVersion = () => `${process.platform} ${release()} ${arch()}`
2612
+ const osCategory = () => (process.platform === "darwin" ? "macos" : process.platform === "win32" ? "windows" : "linux")
2613
+
2614
+ function intl() {
2615
+ try {
2616
+ return Intl.DateTimeFormat().resolvedOptions()
2617
+ } catch {
2618
+ return {}
2619
+ }
2620
+ }
2621
+
2622
+ // startHeaders is a Start Plan request's headers, jwt its key: ZCode's
2623
+ // own (3.16.3's Frn and Vdt in glm/zcode.cjs) and the body's content-type,
2624
+ // and nothing else. The agent's headers never go on: Claude Code's
2625
+ // anthropic-beta, x-app, x-stainless-*, anthropic-dangerous-direct-browser-
2626
+ // access and x-claude-code-session-id reach the plugin through magpie's
2627
+ // gateway, and ZCode sends none of them (no anthropic-beta at all on the
2628
+ // Start Plan: its tool search beta is for coding plans only). Accept and
2629
+ // accept-encoding are left to the HTTP client, as ZCode leaves them to
2630
+ // Node's.
2631
+ function startHeaders(h, jwt) {
2632
+ const out = new Headers()
2633
+ out.set("content-type", h.get("content-type") || "application/json")
2634
+ out.set("Authorization", "Bearer " + jwt)
2635
+ out.set("anthropic-version", "2023-06-01")
2636
+ out.set("HTTP-Referer", ZCODE)
2637
+ out.set("User-Agent", UA + " ai-sdk/anthropic/3.0.81")
2638
+ out.set("X-ZCode-App-Version", APP_VERSION)
2639
+ // the desktop app's agent names itself electron: 3.17.2's
2640
+ // zcode-protocol-entrypoint passes sourceTitle "electron", and a bare
2641
+ // run under app-server says the same (Mvc in glm/zcode.cjs); "cli" is
2642
+ // the zcode command line's alone, which sends no X-Device-Mid on the
2643
+ // app's calls and no desktop prompt texts, as this plugin does
2644
+ out.set("X-Title", "Z Code@electron")
2645
+ out.set("X-Release-Channel", "production")
2646
+ const o = intl()
2647
+ out.set("X-Client-Language", o.locale || "unknown")
2648
+ out.set("X-Client-Timezone", o.timeZone || "unknown")
2649
+ out.set("X-ZCode-Agent", "glm")
2650
+ out.set("X-Platform", platform())
2651
+ out.set("X-Os-Category", osCategory())
2652
+ // os.release() alone, as ZCode's buildZCodeSourceHeadersFromContext
2653
+ // has it; the prompt's OS line is osVersion()
2654
+ out.set("X-Os-Version", release())
2655
+ out.set("x-request-id", uuid())
2656
+ out.set("x-zcode-session-type", "main")
2657
+ out.set("x-zcode-trace-id", uuid())
2658
+ // 3.16's createModelRequestAttributionHeaders: what asked the model
2659
+ out.set("x-zcode-query-source", "main_turn")
2660
+ return out
2661
+ }
2662
+
2663
+ // queryOf is the request's x-query-id, as 3.17.2's
2664
+ // createModelRequestAttributionHeaders (zft in glm/zcode.cjs) sends it:
2665
+ // the user's query, "query_" + a UUID with the prefix cut, the same for
2666
+ // every request of one turn (the tool calls the model makes on the way)
2667
+ // and a new one for the next thing the user says. The agent's turns are
2668
+ // counted: a user message that carries text, not tool results alone,
2669
+ // starts a query. A body that doesn't read gives none, and none is sent.
2670
+ function queryOf(text, session) {
2671
+ let b
2672
+ try {
2673
+ b = JSON.parse(text)
2674
+ } catch {
2675
+ return ""
2676
+ }
2677
+ if (!Array.isArray(b?.messages)) return ""
2678
+ let n = 0
2679
+ for (const m of b.messages) {
2680
+ if (m?.role !== "user") continue
2681
+ const c = m.content
2682
+ if (typeof c === "string" ? c.trim() : Array.isArray(c) && c.some((x) => x && x.type !== "tool_result")) n++
2683
+ }
2684
+ return n ? uuidOf("zcode-query\0" + session + "\0" + n) : ""
2685
+ }
2686
+
2687
+ // Claude Code's tool search, as ZCode's plans take it. Claude Code
2688
+ // (2.1.310) offers a tool named ToolSearch, names its deferred tools in a
2689
+ // system turn, and sends a deferred tool's schema with defer_loading only
2690
+ // once a search loaded it (a tool_reference in a ToolSearch result), with
2691
+ // a DeferredToolPlaceholder that keeps the search on. api.z.ai's
2692
+ // Anthropic endpoint, given a tool named exactly ToolSearch, shows the
2693
+ // model none of the other tools, Bash, Read and Write among them, but
2694
+ // those a tool_reference loaded: a subagent, which hasn't searched,
2695
+ // reports only the deferred tools, and the main turn has to search for
2696
+ // Bash before it can run it (小八 on Discord, 10-24; the beta header
2697
+ // changes nothing, the name alone does). ZCode itself sends no ToolSearch
2698
+ // and no defer_loading. So the search goes as SEARCH_ALIAS, in the tools
2699
+ // and in the turns that called it, the tools Claude Code sent with their
2700
+ // schemas go as ZCode's do, without defer_loading, and the placeholder is
2701
+ // left out; the model's calls to SEARCH_ALIAS come back as ToolSearch
2702
+ // (searchNamed).
2703
+ const SEARCH = "ToolSearch"
2704
+ const SEARCH_ALIAS = "ToolSearchTool"
2705
+ const PLACEHOLDER = "DeferredToolPlaceholder"
2706
+
2707
+ // searchless is a Messages request body without Claude Code's ToolSearch
2708
+ // name, and whether it had the tool; anything else goes as it is.
2709
+ function searchless(text) {
2710
+ if (typeof text !== "string" || !text.includes(`"${SEARCH}"`)) return { text, renamed: false }
2711
+ let b
2712
+ try {
2713
+ b = JSON.parse(text)
2714
+ } catch {
2715
+ return { text, renamed: false }
2716
+ }
2717
+ if (!b || !Array.isArray(b.tools) || !b.tools.some((t) => t?.name === SEARCH)) return { text, renamed: false }
2718
+ // a tool of the alias's own name keeps it; the search can't then be renamed
2719
+ if (b.tools.some((t) => t?.name === SEARCH_ALIAS)) return { text, renamed: false }
2720
+ b.tools = b.tools
2721
+ .filter((t) => t?.name !== PLACEHOLDER)
2722
+ .map((t) => {
2723
+ if (!t || typeof t !== "object") return t
2724
+ const { defer_loading, ...rest } = t
2725
+ return t.name === SEARCH ? { ...rest, name: SEARCH_ALIAS } : rest
2726
+ })
2727
+ if (Array.isArray(b.messages))
2728
+ for (const m of b.messages)
2729
+ if (m?.role === "assistant" && Array.isArray(m.content))
2730
+ for (const x of m.content) if (x?.type === "tool_use" && x.name === SEARCH) x.name = SEARCH_ALIAS
2731
+ if (b.tool_choice?.type === "tool" && b.tool_choice.name === SEARCH) b.tool_choice.name = SEARCH_ALIAS
2732
+ return { text: JSON.stringify(b), renamed: true }
2733
+ }
2734
+
2735
+ // searchNamed is an answer to a request searchless renamed, the model's
2736
+ // calls to SEARCH_ALIAS named ToolSearch again, as Claude Code runs them:
2737
+ // a stream's content_block_start events, or a whole message's content.
2738
+ function searchNamed(res) {
2739
+ if (!res.body) return res
2740
+ const type = res.headers.get("content-type") ?? ""
2741
+ const named = (block) => {
2742
+ if (block?.type === "tool_use" && block.name === SEARCH_ALIAS) {
2743
+ block.name = SEARCH
2744
+ return true
2745
+ }
2746
+ return false
2747
+ }
2748
+ const line = (l) => {
2749
+ if (!l.startsWith("data:") || !l.includes(`"${SEARCH_ALIAS}"`)) return l
2750
+ try {
2751
+ const d = JSON.parse(l.slice(5))
2752
+ return named(d?.content_block) ? "data: " + JSON.stringify(d) : l
2753
+ } catch {
2754
+ return l
2755
+ }
2756
+ }
2757
+ if (type.includes("text/event-stream")) {
2758
+ const dec = new TextDecoder()
2759
+ const enc = new TextEncoder()
2760
+ let held = ""
2761
+ const body = res.body.pipeThrough(
2762
+ new TransformStream({
2763
+ transform(chunk, ctl) {
2764
+ held += dec.decode(chunk, { stream: true })
2765
+ const i = held.lastIndexOf("\n")
2766
+ if (i < 0) return
2767
+ ctl.enqueue(enc.encode(held.slice(0, i + 1).split("\n").map(line).join("\n")))
2768
+ held = held.slice(i + 1)
2769
+ },
2770
+ flush(ctl) {
2771
+ held += dec.decode()
2772
+ if (held) ctl.enqueue(enc.encode(line(held)))
2773
+ },
2774
+ }),
2775
+ )
2776
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: res.headers })
2777
+ }
2778
+ if (!type.includes("json")) return res
2779
+ return res.text().then((text) => {
2780
+ let out = text
2781
+ if (text.includes(`"${SEARCH_ALIAS}"`)) {
2782
+ try {
2783
+ const v = JSON.parse(text)
2784
+ if (Array.isArray(v?.content) && v.content.map(named).some(Boolean)) out = JSON.stringify(v)
2785
+ } catch {}
2786
+ }
2787
+ return new Response(out, { status: res.status, statusText: res.statusText, headers: res.headers })
2788
+ })
2789
+ }
2790
+
2791
+ // trialNamed is a gift's answer with its model said as the picker lists it
2792
+ // (GLM-5.3-Flash-Trial): the gift answers under the plain name, as the coding
2793
+ // plan does, so the Usage page, the sessions and the request log named the
2794
+ // plan's model whichever route served it, and a user with free first on
2795
+ // could not tell whether the free quota was spent (WJaunita45604 on X). A
2796
+ // failed answer, or a body that is not JSON or an event stream, goes on as it
2797
+ // came.
2798
+ function trialNamed(res, name) {
2799
+ if (!res.body || res.status >= 400) return res
2800
+ const type = res.headers.get("content-type") ?? ""
2801
+ const set = (d) => {
2802
+ if (d && typeof d === "object") {
2803
+ if (typeof d.model === "string") d.model = name
2804
+ if (typeof d.message?.model === "string") d.message.model = name
2805
+ return true
2806
+ }
2807
+ return false
2808
+ }
2809
+ const line = (l) => {
2810
+ if (!l.startsWith("data:") || !l.includes('"model"')) return l
2811
+ try {
2812
+ const d = JSON.parse(l.slice(5))
2813
+ return set(d) ? "data: " + JSON.stringify(d) : l
2814
+ } catch {
2815
+ return l
2816
+ }
2817
+ }
2818
+ const h = new Headers(res.headers)
2819
+ if (type.includes("text/event-stream")) {
2820
+ const dec = new TextDecoder()
2821
+ const enc = new TextEncoder()
2822
+ let held = ""
2823
+ const body = res.body.pipeThrough(
2824
+ new TransformStream({
2825
+ transform(chunk, ctl) {
2826
+ held += dec.decode(chunk, { stream: true })
2827
+ const i = held.lastIndexOf("\n")
2828
+ if (i < 0) return
2829
+ ctl.enqueue(enc.encode(held.slice(0, i + 1).split("\n").map(line).join("\n")))
2830
+ held = held.slice(i + 1)
2831
+ },
2832
+ flush(ctl) {
2833
+ held += dec.decode()
2834
+ if (held) ctl.enqueue(enc.encode(line(held)))
2835
+ },
2836
+ }),
2837
+ )
2838
+ return new Response(body, { status: res.status, statusText: res.statusText, headers: h })
2839
+ }
2840
+ if (!type.includes("json")) return res
2841
+ return res.text().then((text) => {
2842
+ let out = text
2843
+ if (text.includes('"model"')) {
2844
+ try {
2845
+ const v = JSON.parse(text)
2846
+ if (set(v)) out = JSON.stringify(v)
2847
+ } catch {}
2848
+ }
2849
+ h.delete("content-length")
2850
+ return new Response(out, { status: res.status, statusText: res.statusText, headers: h })
2851
+ })
2852
+ }
2853
+
2854
+ // startURL is a Start Plan request's URL without the query the agent put
2855
+ // on it: Claude Code asks /v1/messages?beta=true, which magpie passes on,
2856
+ // and ZCode asks /v1/messages alone.
2857
+ function startURL(url) {
2858
+ const i = url.indexOf("?")
2859
+ return i < 0 ? url : url.slice(0, i)
2860
+ }
2861
+
2862
+ // WORK_DIR and WORK_GIT are where magpie tells a plugin's fetch the agent
2863
+ // that asked works: the folder, percent-encoded, and "yes" or "no" for a
2864
+ // git repository, each left off when magpie doesn't know it (magpie's
2865
+ // provider.WorkDirHeader and WorkGitHeader). They are for the plugin, not
2866
+ // the vendor.
2867
+ const WORK_DIR = "x-magpie-work-dir"
2868
+ const WORK_GIT = "x-magpie-work-git"
2869
+
2870
+ // workPlace takes WORK_DIR and WORK_GIT off h: {dir?, git?}, what magpie
2871
+ // said of where the agent works.
2872
+ function workPlace(h) {
2873
+ const place = {}
2874
+ const dir = h.get(WORK_DIR)
2875
+ if (dir) {
2876
+ try {
2877
+ place.dir = decodeURIComponent(dir)
2878
+ } catch {}
2879
+ }
2880
+ const git = h.get(WORK_GIT)
2881
+ if (place.dir && (git === "yes" || git === "no")) place.git = git
2882
+ h.delete(WORK_DIR)
2883
+ h.delete(WORK_GIT)
2884
+ return place
2885
+ }
2886
+
2887
+ // environment is the prompt's environment section, as ZCode 3.17.2's
2888
+ // env-info.ts renders it, bullets one space in. The plugin runs in magpie,
2889
+ // not in the agent's folder: the working directory and whether it is a git
2890
+ // repository are the agent's, as magpie tells them (place), and each is
2891
+ // left out when it isn't told rather than said as magpie's own (#86). The
2892
+ // agent's shell isn't known here either, so it isn't said; the platform
2893
+ // and OS version are this computer's, as ZCode's X-Os-* headers say them.
2894
+ function environment(place = {}) {
2895
+ const e = PROMPT.environment
2896
+ const lines = [e.heading, e.invokedLine]
2897
+ if (place.dir) {
2898
+ lines.push(` - ${e.cwdLabel}: ${place.dir}`)
2899
+ if (place.git) lines.push(` - ${e.gitLabel}: ${place.git === "yes" ? e.gitYes : e.gitNo}`)
2900
+ }
2901
+ lines.push(` - ${e.platformLabel}: ${process.platform}`, ` - ${e.osVersionLabel}: ${osVersion()}`)
2902
+ lines.push(` - ${e.untrustedNote}`)
2903
+ return lines.join("\n")
2904
+ }
2905
+
2906
+ // today is the local date, YYYY-MM-DD.
2907
+ function today(now = new Date()) {
2908
+ const p = (n) => String(n).padStart(2, "0")
2909
+ return `${now.getFullYear()}-${p(now.getMonth() + 1)}-${p(now.getDate())}`
2910
+ }
2911
+
2912
+ // contextPrefix is the user turn ZCode puts before the agent's: the day in
2913
+ // a <system-reminder>, the tags hugging the text, as 3.17.2's current-date
2914
+ // section says it alone.
2915
+ function contextPrefix() {
2916
+ const c = PROMPT.context
2917
+ return { role: "user", content: [{ type: "text", text: "<system-reminder>" + c.currentDateLine.replace("{date}", today()) + "</system-reminder>" }] }
2918
+ }
2919
+
2920
+ // dress is a Messages request body as ZCode sends it: ZCode's three cached
2921
+ // system blocks and no more, the agent's own system text at the end of the
2922
+ // third (#343); the context
2923
+ // prefix as the first turn; no cache mark in the turns but on the last
2924
+ // block of the last; none on the tools; metadata.user_id naming the
2925
+ // sign-in's device. site names the powered-by line's provider, place where
2926
+ // the agent works (workPlace). A body that isn't a Messages request goes as
2927
+ // it is.
2928
+ function dress(text, site, device, place, session) {
2929
+ if (typeof text !== "string" || !text.includes("messages")) return text
2930
+ let b
2931
+ try {
2932
+ b = JSON.parse(text)
2933
+ } catch {
2934
+ return text
2935
+ }
2936
+ if (!b || typeof b !== "object" || !Array.isArray(b.messages)) return text
2937
+ const cached = (t) => ({ type: "text", text: t, cache_control: { type: "ephemeral" } })
2938
+ const provider = site === "bigmodel" ? "bigmodel-api" : "zai-api"
2939
+ const model = typeof b.model === "string" ? b.model : ""
2940
+ // The agent's own system text joins the third block, as ZCode's
2941
+ // ContextBuilder (3.17.2, core/src/context/builder.ts
2942
+ // assembleSystemMessages) joins every dynamic system section, an added
2943
+ // one too, with "\n\n" into that one block: ZCode never sends more than
2944
+ // three. zcode.z.ai turns a fourth block away with 405/3012 (#343), and
2945
+ // the first two must stay byte for byte ZCode's. The third's own
2946
+ // sections are 3.17.2's dynamic ones — the unheaded behavior paragraphs,
2947
+ // the slash-skill guidance when the request has a Skill tool, the
2948
+ // environment and the model, then context management.
2949
+ const own = []
2950
+ if (typeof b.system === "string") {
2951
+ if (b.system.trim()) own.push(b.system)
2952
+ } else if (Array.isArray(b.system)) {
2953
+ for (const x of b.system) if (x?.type === "text" && typeof x.text === "string" && x.text.trim()) own.push(x.text)
2954
+ }
2955
+ const skill = Array.isArray(b.tools) && b.tools.some((t) => t && typeof t === "object" && t.name === "Skill")
2956
+ const dynamic = [
2957
+ PROMPT.dynamicBehavior,
2958
+ ...(skill ? [PROMPT.sessionGuidance] : []),
2959
+ environment(place),
2960
+ ...(model ? [PROMPT.poweredBy.replace("{provider}", provider).replace("{model}", model)] : []),
2961
+ PROMPT.contextManagement,
2962
+ ...own,
2963
+ ]
2964
+ b.system = [cached(PROMPT.cliPrefix), cached(PROMPT.stableSections.join("\n\n")), cached("\n\n" + dynamic.join("\n\n"))]
2965
+ b.messages = [contextPrefix(), ...b.messages]
2966
+ let last = null
2967
+ for (const m of b.messages) {
2968
+ if (!m || m.role === "system") continue
2969
+ last = m
2970
+ if (Array.isArray(m.content)) for (const x of m.content) if (x && typeof x === "object") delete x.cache_control
2971
+ }
2972
+ if (last && typeof last.content === "string") last.content = [cached(last.content)]
2973
+ else if (last && Array.isArray(last.content) && last.content.length) {
2974
+ const x = last.content[last.content.length - 1]
2975
+ if (x && typeof x === "object" && !x.cache_control) x.cache_control = { type: "ephemeral" }
2976
+ }
2977
+ if (Array.isArray(b.tools)) for (const t of b.tools) if (t && typeof t === "object") delete t.cache_control
2978
+ const meta = b.metadata && typeof b.metadata === "object" ? b.metadata : {}
2979
+ b.metadata = { ...meta, user_id: userIdOf(device, session) }
2980
+ return JSON.stringify(b)
2981
+ }
2982
+
2983
+ // userIdOf is metadata.user_id as ZCode's client (3.14.3, glm/zcode.cjs
2984
+ // MLs and vWr) puts it on every Anthropic-format request, a coding plan's
2985
+ // too: the machine's device id, no account uuid. The plan's endpoint keeps
2986
+ // a prompt cache on the machine it picks by it, so a request without it
2987
+ // lands anywhere and its cache is mostly missed (#387). Its session_id is
2988
+ // the request's x-session-id (sessionOf), as ZCode's is.
2989
+ const userIdOf = (device, session = "") => JSON.stringify({ device_id: device, account_uuid: "", session_id: session })
2990
+
2991
+ // marked is a coding plan's Messages request body with metadata.user_id
2992
+ // as ZCode sends it, when the agent sent none of its own. Anything else,
2993
+ // a body that isn't a Messages request among them, goes as it is.
2994
+ function marked(text, device, session) {
2995
+ if (typeof text !== "string" || !device || !text.includes("messages")) return text
2996
+ let b
2997
+ try {
2998
+ b = JSON.parse(text)
2999
+ } catch {
3000
+ return text
3001
+ }
3002
+ if (!b || typeof b !== "object" || Array.isArray(b) || !Array.isArray(b.messages)) return text
3003
+ const meta = b.metadata && typeof b.metadata === "object" && !Array.isArray(b.metadata) ? b.metadata : {}
3004
+ if (typeof meta.user_id === "string" && meta.user_id.trim()) return text
3005
+ b.metadata = { ...meta, user_id: userIdOf(device, session) }
3006
+ return JSON.stringify(b)
3007
+ }
3008
+
3009
+ // sessionOf is the x-session-id a request goes with, as ZCode's client
3010
+ // (3.14.3, glm/zcode.cjs xst and Tst) sends it: a bare UUID, the same on
3011
+ // every turn of a conversation. BigModel keeps a prompt's cache for the
3012
+ // requests that name the same session and seldom for those that name none
3013
+ // (#387). The agent's session (chat.headers below) goes as it is when it is
3014
+ // a UUID, else as a UUID made from it, so the vendor sees only ZCode's
3015
+ // format, never magpie's or another agent's; with none, a UUID made from
3016
+ // the device.
3017
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i
3018
+ function sessionOf(id, device) {
3019
+ const own = typeof id === "string" ? id.trim() : ""
3020
+ if (UUID.test(own)) return own.toLowerCase()
3021
+ return uuidOf(own ? "zcode-session\0" + own : "zcode-session-device\0" + (device ?? ""))
3022
+ }
3023
+
3024
+ // ---- the plugin ------------------------------------------------------------------
3025
+
3026
+ export async function ZCodeAuthPlugin({ client, magpie } = {}, options = {}) {
3027
+ const log = (message) => {
3028
+ try {
3029
+ client?.app?.log?.({ body: { service: "zcode-auth", level: "error", message } })
3030
+ } catch {}
3031
+ }
3032
+ // freeFirst reads the option from the provider config's options first,
3033
+ // and from the plugin's own (magpie's Plugins › Options) when the
3034
+ // provider carries no freeFirst of its own. It is on unless one of them
3035
+ // says false: a gift ZCode hands out (each weekend, sgfvdsg86265 on X)
3036
+ // lapses unused behind an agent that asks the plain model, and every
3037
+ // failure of the gift is answered from the plan. magpie's switch in the
3038
+ // provider's editor (FREE_FIRST, auth.options below) turns it off too;
3039
+ // it is on by default, so a JSON freeFirst: false a user wrote before
3040
+ // the switch existed keeps it off. A key magpie doesn't report (an older
3041
+ // magpie, OpenCode) leaves it as the JSON says.
3042
+ const freeFirst = (providerOptions) =>
3043
+ magpie?.options?.(PROVIDER)?.[FREE_FIRST] !== false &&
3044
+ (providerOptions?.freeFirst !== undefined ? providerOptions.freeFirst !== false : options?.freeFirst !== false)
3045
+ const oauth = (site) => ({
3046
+ type: "oauth",
3047
+ label: `ZCode: ${SITES[site].name}${site === "bigmodel" ? " (智谱)" : ""} GLM Coding Plan`,
3048
+ authorize: () => authorize(site, log),
3049
+ })
3050
+ return {
3051
+ // the agent's session, which magpie tells the plugins here and not
3052
+ // in the request, goes on as x-session-id (sessionOf)
3053
+ "chat.headers": async (input, output) => {
3054
+ const provider = input?.model?.providerID ?? input?.provider?.info?.id
3055
+ if (provider !== PROVIDER) return
3056
+ const id = input?.sessionID
3057
+ if (typeof id === "string" && id.trim()) output.headers["x-session-id"] = sessionOf(id)
3058
+ },
3059
+ config: async (cfg) => {
3060
+ cfg.provider ??= {}
3061
+ const was = cfg.provider[PROVIDER] ?? {}
3062
+ cfg.provider[PROVIDER] = {
3063
+ name: "ZCode",
3064
+ npm: "@ai-sdk/anthropic",
3065
+ api: ZAI_BASE + "/v1",
3066
+ ...was,
3067
+ models: { ...Object.fromEntries(MODELS.map((m) => [m.id, entry(m)])), ...(was.models ?? {}) },
3068
+ }
3069
+ },
3070
+ provider: {
3071
+ id: PROVIDER,
3072
+ // the account's plan's models, as ZCode's config lists them now
3073
+ async models(provider, { auth } = {}) {
3074
+ // a ZCode 3.16 sign-in holds only where its key is: read the key
3075
+ // first, as a request does, or plansOf takes the keyless sign-in
3076
+ // for a Start Plan one and lists that plan's models (#439). A key
3077
+ // that can't be read throws, and magpie keeps the list it had.
3078
+ const s = await located(stateOf(auth))
3079
+ if (!s) return provider.models
3080
+ const { start, gift: known } = await plansOf(s).catch(() => ({ start: false, gift: null }))
3081
+ const gift = start ? await aloneGift(s) : known
3082
+ const base = start ? START_BASE : s.base
3083
+ const cfg = await zcodeConfig().catch(() => null)
3084
+ let ms = modelsOf(cfg, planID(base))
3085
+ // ZCode's config can't be had: its table stands in, and magpie keeps
3086
+ // the list it was told last, as the built-in keeps the one it fetched last
3087
+ const fell = !ms.length
3088
+ if (fell) ms = start ? START_MODELS : MODELS
3089
+ // a gift-only account serves what its balance names, as ZCode
3090
+ // offers it (resolveStartPlanBalanceAvailability): the Start
3091
+ // Plan's config models the balance lacks would only be refused
3092
+ // (young02036). A balance naming none leaves the config's list.
3093
+ if (start && giftNames(gift).length) ms = ms.filter((m) => giftNames(gift).some((x) => x.toLowerCase() === m.id.toLowerCase()))
3094
+ const url = s.base + "/v1"
3095
+ const out = Object.fromEntries(ms.map((m) => [m.id, model(m, url)]))
3096
+ const details = [...ms, ...modelsOf(cfg, planID(START_BASE)), ...modelsOf(cfg, planID(ZAI_BASE)), ...MODELS]
3097
+ const about = (raw) => details.find((m) => m.id.toLowerCase() === raw.toLowerCase()) ?? { efforts: [] }
3098
+ const has = new Set(Object.keys(out).map((id) => id.toLowerCase()))
3099
+ for (const raw of giftNames(gift)) {
3100
+ // a gift-only account's models are its gift's, by their own
3101
+ // names, as ZCode lists them (its Start Plan's GLM-5.3, which the
3102
+ // plan's config leaves out): every request of it goes to the gift
3103
+ // anyway, and the card counts them by that name too (#1261)
3104
+ if (start && !has.has(raw.toLowerCase())) {
3105
+ const plain = about(raw).id ?? raw
3106
+ has.add(raw.toLowerCase())
3107
+ out[plain] = model({ ...about(raw), id: plain }, url)
3108
+ }
3109
+ const id = giftID(raw)
3110
+ if (out[id]) continue
3111
+ // a trial entry is the gift's, which costs nothing: marked free,
3112
+ // so magpie reads a GLM Coding Plan model's weekly or monthly
3113
+ // limit (1310) as that model's, and the account's trial entries,
3114
+ // spent from the gift's own buckets, are still asked (plugins#438)
3115
+ out[id] = { ...model({ ...about(raw), id }, url), free: true }
3116
+ }
3117
+ // a fallback tells magpie to keep the list it was told last, which
3118
+ // predates the gift read just made: an account whose gift lists
3119
+ // trial entries is told this list, so ZCode's config out of reach
3120
+ // (a remote box that can't get its CDN) never hides them
3121
+ if (fell && !giftNames(gift).length) out[Symbol.for("magpie.fellBack")] = true
3122
+ return out
3123
+ },
3124
+ },
3125
+ auth: {
3126
+ provider: PROVIDER,
3127
+ // a plan serves one account a few requests at a time: magpie's own
3128
+ // field, so its queue spaces what the agents ask for before the vendor
3129
+ // sees it. For the coding plan this is a default, not a cap the plugin
3130
+ // enforces — its cap follows its tier (Max > Pro > Lite) and the time
3131
+ // of day, and a user who knows theirs can raise this on the account.
3132
+ // The Start Plan has the plugin's own gate below it (startGate)
3133
+ maxConcurrency: DEFAULT_CONCURRENCY,
3134
+ // magpie's own switches (OpenCode never reads auth.options), read at
3135
+ // each request through input.magpie
3136
+ options: [
3137
+ {
3138
+ key: FREE_FIRST,
3139
+ label: "Free quota first",
3140
+ description: "When on, the plain GLM models spend ZCode's free Start Plan quota (the -Trial entries' quota) before the GLM Coding Plan, and go to the plan when it is spent or refused. Off: only the -Trial entries use it. freeFirst: false in the options JSON turns it off too.",
3141
+ labels: { zh: "优先用免费额度", "zh-TW": "優先用免費額度", ja: "無料枠を優先", de: "Gratis-Kontingent zuerst" },
3142
+ descriptions: {
3143
+ zh: "开启后,普通的 GLM 模型先用 ZCode 的免费 Start Plan 额度(即 -Trial 条目的额度),用完或被拒时再用 GLM Coding Plan。关闭后只有 -Trial 条目会用它。选项 JSON 里的 freeFirst: false 也会关闭它。",
3144
+ "zh-TW": "開啟後,一般的 GLM 模型先用 ZCode 的免費 Start Plan 額度(即 -Trial 項目的額度),用完或被拒時再用 GLM Coding Plan。關閉後只有 -Trial 項目會用它。選項 JSON 裡的 freeFirst: false 也會關閉它。",
3145
+ ja: "オンにすると、通常の GLM モデルは GLM Coding Plan より先に ZCode の無料 Start Plan 枠(-Trial 項目の枠)を使い、使い切るか拒否されるとプランに戻ります。オフでは -Trial 項目だけが使います。オプション JSON の freeFirst: false でもオフになります。",
3146
+ de: "Ist dies an, nutzen die normalen GLM-Modelle zuerst ZCodes freies Start-Plan-Kontingent (das der -Trial-Einträge) und erst danach den GLM Coding Plan. Aus: nur die -Trial-Einträge nutzen es. freeFirst: false im Optionen-JSON schaltet es auch aus.",
3147
+ },
3148
+ default: true,
3149
+ },
3150
+ ],
3151
+ async loader(getAuth, provider) {
3152
+ const s0 = stateOf(await getAuth())
3153
+ if (!s0) return {}
3154
+ const id = provider?.id ?? PROVIDER
3155
+ return {
3156
+ baseURL: s0.base + "/v1",
3157
+ apiKey: s0.key || "zcode", // the fetch below puts the real one on
3158
+ async fetch(input, init) {
3159
+ // a Start Plan request holds one of its account's slots
3160
+ // (startSlot) until its answer has been read to the end
3161
+ const own = {}
3162
+ try {
3163
+ return released(await serve(input, init, own), own.slot, own.signal)
3164
+ } catch (e) {
3165
+ own.slot?.release()
3166
+ throw e
3167
+ }
3168
+ },
3169
+ }
3170
+ async function serve(input, init, own) {
3171
+ const auth = await getAuth()
3172
+ let s
3173
+ try {
3174
+ s = await located(stateOf(auth))
3175
+ } catch (e) {
3176
+ // the plan's key couldn't be read for the network: a wall,
3177
+ // sent once (wallAnswer), not a 502 asked again (#1020)
3178
+ if (e?.unreached) return kept(wallAnswer(e.message))
3179
+ throw e
3180
+ }
3181
+ if (!s) throw new Error("not signed in to ZCode")
3182
+ // the account a Start Plan slot belongs to: its user id, which a
3183
+ // renewed session keeps, before the key or session itself
3184
+ const gateKey = String(auth?.uid || auth?.accountId || holdKey(s))
3185
+ let url = input instanceof Request ? input.url : String(input)
3186
+ const opts = input instanceof Request ? { method: input.method, headers: input.headers, body: input.body, signal: input.signal, duplex: "half", ...init } : { ...init }
3187
+ const { start: alone, gift: known } = await plansOf(s)
3188
+ let gift = known
3189
+ let key = s.key
3190
+ if (isTeam(s) && !key) {
3191
+ key = await teamKey(s)
3192
+ if (auth?.type === "oauth") {
3193
+ const next = { ...auth, refresh: JSON.stringify({ ...s, key }), access: key }
3194
+ await client?.auth?.set?.({ path: { id }, body: next }).catch?.(() => {})
3195
+ }
3196
+ }
3197
+ // a dual account's body is read ahead of sending, so a gift that
3198
+ // says it is spent can spend nothing and replay what was asked for
3199
+ let start = alone
3200
+ let orig, forcedGift = false, freeGift = false
3201
+ // the gift's -Trial name while the gift is the route that answers
3202
+ // (a free-first request replayed on the plan clears it)
3203
+ let giftName = ""
3204
+ let asked = ""
3205
+ let renamed = false
3206
+ const done = (res) => {
3207
+ if (giftName) res = trialNamed(res, giftName)
3208
+ return renamed ? searchNamed(res) : res
3209
+ }
3210
+ if (opts.body != null) {
3211
+ orig = opts.body = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()
3212
+ delete opts.duplex
3213
+ // Claude Code's tool search goes under another name, or
3214
+ // ZCode's plans show the model no other tool (searchless)
3215
+ const plain = searchless(orig)
3216
+ if (plain.renamed) {
3217
+ orig = opts.body = plain.text
3218
+ renamed = true
3219
+ }
3220
+ let m = modelOf(orig)
3221
+ asked = m
3222
+ if (m.toLowerCase().endsWith("-trial")) {
3223
+ gift ??= await startPlan(s.jwt, s.device).catch(() => null)
3224
+ const raw = giftModel(gift, m)
3225
+ const available = raw && giftUsable(s, gift, raw)
3226
+ if (!available) {
3227
+ const held = raw ? [] : await unclaimed(s)
3228
+ 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` : ""}` }
3229
+ return kept(new Response(JSON.stringify({ type: "error", error }), { status: raw ? 429 : 400, headers: { "content-type": "application/json" } }))
3230
+ }
3231
+ orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
3232
+ m = raw
3233
+ forcedGift = true
3234
+ giftName = giftID(raw)
3235
+ } else if (!alone && !edgeHeld() && !busyHeld() && !startFull(gateKey) && !startFull(ADDRESS) && freeFirst(provider?.options) && s.jwt && known && giftUsable(s, known, m) && !giftSidelined(s, m)) {
3236
+ // free first: the plain model spends the account's own live
3237
+ // gift before it spends the coding plan, under the name the
3238
+ // gift lists. The gift is the route's cache alone (a failed
3239
+ // read cached its why), so a gift that cannot be read keeps
3240
+ // the request on the plan with no read per request; a
3241
+ // gift-only account is already on the gift and is left as
3242
+ // it was. A refusal past this check is replayed on the plan
3243
+ // in the same request (replayOnPlan below). A busy hold (or
3244
+ // a block page) keeps the plain model off the gift: the
3245
+ // coding plan is never held, and free first must not move
3246
+ // the request onto a route the hold answers 429 without
3247
+ // asking. Nor onto a gift whose slots are all taken
3248
+ // (startFull): the plan serves it now, the gift only after
3249
+ // the others.
3250
+ const raw = giftNames(known).find((x) => x.toLowerCase() === m.toLowerCase())
3251
+ orig = opts.body = JSON.stringify({ ...JSON.parse(orig), model: wireModel(raw) })
3252
+ m = raw
3253
+ freeGift = true
3254
+ giftName = giftID(raw)
3255
+ } else if (alone && /\/v1\/messages$/.test(new URL(url).pathname)) {
3256
+ // a gift-only account's Start Plan serves the models its
3257
+ // balance names, and ZCode's app offers only those
3258
+ // (resolveStartPlanBalanceAvailability). Any other model
3259
+ // spends none of the free quota, so it is not sent: an
3260
+ // agent left on another model would be billed while the
3261
+ // gift stayed unspent (bg5eau on X). The balance is the
3262
+ // one the model list read (aloneSeen); a model it doesn't
3263
+ // name has it read again before the refusal. One not read
3264
+ // yet, one that fails, or one naming none leaves the
3265
+ // request as it was.
3266
+ const named = (ns) => ns.some((x) => x.toLowerCase() === m.toLowerCase())
3267
+ const kept0 = aloneNames(s)
3268
+ const names = kept0.length && !named(kept0) ? giftNames(await aloneGift(s)) : []
3269
+ if (names.length && !named(names)) {
3270
+ const shown = uniqueModels(names.map(wireModel))
3271
+ const error = { type: "invalid_request_error", message: `ZCode's Start Plan on this account serves ${shown.join(", ")}; ${m} is not among them and would spend none of its free quota, so it was not sent. Pick ${shown.length > 1 ? "one of those" : shown[0]} for this account` }
3272
+ return kept(new Response(JSON.stringify({ type: "error", error }), { status: 400, headers: { "content-type": "application/json" } }))
3273
+ }
3274
+ }
3275
+ start = alone || forcedGift || freeGift
3276
+ }
3277
+ const swap = (base) => {
3278
+ for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
3279
+ if (url.startsWith(b)) {
3280
+ url = base + url.slice(b.length)
3281
+ break
3282
+ }
3283
+ }
3284
+ }
3285
+ let h = new Headers(opts.headers)
3286
+ const askedUrl = url
3287
+ const place = workPlace(h)
3288
+ const sid = sessionOf(h.get("x-session-id"), s.device)
3289
+ // restModel is free first's gift turning this model away: the
3290
+ // model rests a minute and the route is dropped, so the requests
3291
+ // behind it re-read the balance and go straight to the plan. A
3292
+ // quota answer rests it in blocked, which a -Trial entry obeys
3293
+ // too; any other refusal (spent false) in sidelined, which only
3294
+ // free first reads.
3295
+ const restModel = (spent) => {
3296
+ rest(spent ? blocked : sidelined, s.key + "\0" + s.jwt + "\0" + asked.toLowerCase())
3297
+ routes.delete(s.key + "\0" + s.jwt)
3298
+ }
3299
+ // replayOnPlan is free first's answer to a gift that refused
3300
+ // what its own balance read had promised: the model as the
3301
+ // agent sent it, the plan's headers, the plan's own patience
3302
+ // (askBusy).
3303
+ const replayOnPlan = async () => {
3304
+ // the gift is done with: its slot goes to the next request
3305
+ own.slot?.release()
3306
+ giftName = ""
3307
+ let u = askedUrl
3308
+ for (const b of [START_BASE, ZAI_BASE, BIGMODEL_BASE]) {
3309
+ if (u.startsWith(b)) {
3310
+ u = s.base + u.slice(b.length)
3311
+ break
3312
+ }
3313
+ }
3314
+ const h2 = new Headers(opts.headers)
3315
+ workPlace(h2)
3316
+ h2.set("x-session-id", sid)
3317
+ h2.delete("authorization")
3318
+ h2.set("x-api-key", key)
3319
+ h2.set("Authorization", "Bearer " + key)
3320
+ h2.delete("content-length")
3321
+ opts.body = marked(JSON.stringify({ ...JSON.parse(orig), model: asked }), s.device, sid)
3322
+ delete opts.duplex
3323
+ // a plan the last usage read showed full isn't sent to: it
3324
+ // would only refuse (#1020)
3325
+ const full = planFullUntil(key)
3326
+ 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`)
3327
+ try {
3328
+ return await askBusy(u, opts, h2)
3329
+ } catch (e) {
3330
+ // a plan that can't be reached is a wall too, sent once; a
3331
+ // caller's abort stays an abort
3332
+ if (opts.signal?.aborted || !unreached(e)) throw e
3333
+ return wallAnswer(`ZCode's ${SITES[s.site].name} GLM Coding Plan: ${e.message} — it could not be reached, so the request was not sent`)
3334
+ }
3335
+ }
3336
+ // a block page held this computer off zcode.z.ai (edge): the
3337
+ // Start Plan and a picked gift are answered here; free first
3338
+ // already left the gift for the plan. Checked before the busy
3339
+ // hold: an IP the firewall already refused keeps that behavior
3340
+ // (the 405 magpie reads as the network's), hold or no hold.
3341
+ if (start && edgeHeld()) return kept(edgeHeldAnswer())
3342
+ // a run of busy caps held this computer off zcode.z.ai before the
3343
+ // edge firewall could block the IP: a held request is answered
3344
+ // here, with a 429 magpie still reads as a rate limit
3345
+ if (start && busyHeld()) return kept(busyHeldAnswer())
3346
+ // the account's Start Plan slots (startGate): a request past them
3347
+ // waits here for one rather than being sent to be refused
3348
+ if (start) {
3349
+ const got = await startSlots(gateKey, opts.signal)
3350
+ own.signal = opts.signal
3351
+ if (!got.release) return kept(startQueueAnswer(got.key))
3352
+ own.slot = got
3353
+ // a hold may have armed while it waited
3354
+ if (edgeHeld()) return kept(edgeHeldAnswer())
3355
+ if (busyHeld()) return kept(busyHeldAnswer())
3356
+ }
3357
+ if (start) {
3358
+ if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
3359
+ if (!s.jwt) throw new Error("ZCode's sign-in has no key; sign in again")
3360
+ swap(START_BASE)
3361
+ // the Start Plan is served only to what looks like ZCode's own request
3362
+ url = startURL(url)
3363
+ h = startHeaders(h, s.jwt)
3364
+ h.set("x-session-id", sid)
3365
+ if (opts.body != null) {
3366
+ const text = orig ?? (typeof opts.body === "string" ? opts.body : await new Response(opts.body).text())
3367
+ opts.body = dress(text, s.site, s.device, place, sid)
3368
+ const q = queryOf(text, sid)
3369
+ if (q) h.set("x-query-id", q)
3370
+ delete opts.duplex
3371
+ h.delete("content-length")
3372
+ }
3373
+ } else {
3374
+ if (!key) throw new Error("ZCode's sign-in has no key; sign in again")
3375
+ swap(s.base)
3376
+ // a Messages request names the device, as ZCode's does (#387);
3377
+ // count_tokens and other paths ZCode never sends go as they are
3378
+ if (opts.body != null && /\/v1\/messages$/.test(new URL(url).pathname)) {
3379
+ const text = typeof opts.body === "string" ? opts.body : await new Response(opts.body).text()
3380
+ const next = marked(text, s.device, sid)
3381
+ if (next !== text) h.delete("content-length")
3382
+ opts.body = next
3383
+ delete opts.duplex
3384
+ }
3385
+ if (renamed) h.delete("content-length")
3386
+ h.set("x-session-id", sid)
3387
+ h.delete("authorization")
3388
+ h.set("x-api-key", key)
3389
+ h.set("Authorization", "Bearer " + key)
3390
+ }
3391
+ // a refusal that is the account's or the model's own in-flight
3392
+ // cap is asked again a moment later (see the plan's concurrency):
3393
+ // magpie sends every agent's and every session's requests of this
3394
+ // computer through this one process, and its queue spaces them by
3395
+ // the number declared above
3396
+ let res
3397
+ try {
3398
+ // Only Start Plan caps count toward the firewall hold: the
3399
+ // coding plan is served by another host and was never refused
3400
+ // with the IP's 405.
3401
+ res = await askBusy(url, opts, h, start ? () => busyCap(gateKey) : undefined)
3402
+ // a cap this computer brought on itself, with others of the
3403
+ // account in flight beside it, narrowed the account's gate:
3404
+ // the request gives its slot back and waits, first in line,
3405
+ // until one of those others has ended, then is sent again —
3406
+ // queued, as ZCode's own client queues its subagents' caps,
3407
+ // not failed. Free first's gift goes to the plan instead,
3408
+ // which serves it now. The waits share one startGate.wait;
3409
+ // each turn the gate is lower or the request is alone, where
3410
+ // a cap is ZCode's or another client's and goes back as it
3411
+ // did.
3412
+ const until = Date.now() + startGate.wait
3413
+ for (let turn = 0; res.requeue && !freeGift && turn < REQUEUE_MAX; turn++) {
3414
+ own.slot?.release()
3415
+ own.slot = null
3416
+ const got = await startSlots(gateKey, opts.signal, { wait: until - Date.now(), front: true })
3417
+ if (!got.release) return kept(startQueueAnswer(got.key))
3418
+ own.slot = got
3419
+ if (edgeHeld()) return kept(edgeHeldAnswer())
3420
+ if (busyHeld()) return kept(busyHeldAnswer())
3421
+ res = await askBusy(url, opts, h, () => busyCap(gateKey))
3422
+ }
3423
+ } catch (e) {
3424
+ // free first moved the request onto the gift, so a gift that
3425
+ // cannot be asked at all — the network, the host — is answered
3426
+ // from the plan; the route read is dropped, so the next
3427
+ // request learns whether the host is back. A caller's abort
3428
+ // stays an abort.
3429
+ if (!freeGift || opts.signal?.aborted || e?.name === "AbortError") throw e
3430
+ routes.delete(s.key + "\0" + s.jwt)
3431
+ res = await replayOnPlan()
3432
+ }
3433
+ // the Start Plan turning the request away says what to do about
3434
+ // it: the account blocked, or the network
3435
+ if (start && res.status >= 400) {
3436
+ const text = await res.text()
3437
+ if (startRefused(res.status, text)) {
3438
+ // a key account sent to the Start Plan (its plan list read
3439
+ // none) reads its plans again on the next request, so a
3440
+ // coding plan that is there after all is used (#369)
3441
+ // a block page holds every request off zcode.z.ai a while
3442
+ if (EDGE_PAGE.test(text)) edge.until = Date.now() + EDGE_HOLD
3443
+ if (freeGift) {
3444
+ restModel(false)
3445
+ return done(kept(await spentSaid(await replayOnPlan())))
3446
+ }
3447
+ if (s.key && !forcedGift) routes.delete(s.key + "\0" + s.jwt)
3448
+ return kept(startBlocked(res, text))
3449
+ }
3450
+ res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
3451
+ }
3452
+ // a key with no plan behind it: what Z.ai said, and why a
3453
+ // ZCode gift plan can't be had with a key (NO_PLAN_KEY)
3454
+ if (!start && !s.jwt && res.status >= 400) {
3455
+ const text = await res.text()
3456
+ const why = noPlanKey(res, text)
3457
+ if (why) return done(kept(why))
3458
+ res = new Response(text, { status: res.status, statusText: res.statusText, headers: res.headers })
3459
+ }
3460
+ // a trial entry's gift answer that can't serve the request is
3461
+ // the agent's answer, not the coding plan's: the user picked the
3462
+ // gift, so a spent bucket says 429 (its quota error inside a 200
3463
+ // among them) and anything else goes on as it came. A quota
3464
+ // answer keeps that model off the gift for a minute, so a rate
3465
+ // limit is not knocked twice. A stream's body is never read here.
3466
+ if (start && forcedGift) {
3467
+ const json = (res.headers.get("content-type") ?? "").includes("application/json")
3468
+ if (res.status >= 400 || json) {
3469
+ const text = await res.text()
3470
+ // the hold's own answer (BUSY_HOLD_MARK) is a rate limit the
3471
+ // gift never said: it passes through as it came and arms
3472
+ // no rest
3473
+ const held = res.headers.get(BUSY_HOLD_MARK) === "1"
3474
+ const spent = !held && spentUp(text, res.status)
3475
+ if (!spent && res.status < 400) return done(kept(res, text))
3476
+ if (spent) rest(blocked, s.key + "\0" + s.jwt + "\0" + modelOf(orig).toLowerCase())
3477
+ return spent && res.status < 400 ? kept(new Response(text, { status: 429, headers: res.headers })) : done(kept(res, text))
3478
+ }
3479
+ }
3480
+ // free first's gift answer: the choice was the plugin's, so the
3481
+ // plan answers what the gift would fail — a spent bucket and a
3482
+ // refusal like any other 4xx or 5xx among them, the gift's own
3483
+ // waited-out busy cap included, since the plan's cap is its own.
3484
+ // A spent answer or a block page rests the model a minute and
3485
+ // drops the route read; a 401/403 drops the read alone, so the
3486
+ // next request learns whether the session is gone. Anything
3487
+ // else — a 200 carrying the answer — goes on as it came. A
3488
+ // stream's body is never read here.
3489
+ else if (start && freeGift) {
3490
+ const json = (res.headers.get("content-type") ?? "").includes("application/json")
3491
+ if (res.status >= 400 || json) {
3492
+ const text = await res.text()
3493
+ const cap = busy(res.status, text)
3494
+ // the hold's own answer is no spent answer either (see the
3495
+ // -Trial path above)
3496
+ const spent = !cap && res.headers.get(BUSY_HOLD_MARK) !== "1" && spentUp(text, res.status)
3497
+ if (spent) {
3498
+ restModel(true)
3499
+ return done(kept(await spentSaid(await replayOnPlan())))
3500
+ }
3501
+ if (res.status >= 400) {
3502
+ if (!cap && (res.status === 401 || res.status === 403)) routes.delete(s.key + "\0" + s.jwt)
3503
+ return done(kept(await spentSaid(await replayOnPlan())))
3504
+ }
3505
+ return done(kept(res, text))
3506
+ }
3507
+ }
3508
+ // the plan's answer goes on as it came, the account kept: the
3509
+ // built-in never marked a ZCode account lapsed nor cleared one.
3510
+ // A spent bucket's 200 says 429 (spentSaid), as a trial
3511
+ // entry's does, so magpie rests the model, not the account
3512
+ return done(kept(await spentSaid(res)))
3513
+ }
3514
+ },
3515
+ // the plan's allowance, as magpie's built-in showed it. Each read
3516
+ // keeps the sign-in (signIn): the built-in's marked no account lapsed,
3517
+ // its expired Start Plan sign-in among them, and cleared none
3518
+ async usage(getAuth, provider) {
3519
+ const auth = await getAuth()
3520
+ const s = stateOf(auth)
3521
+ if (!s) return { error: "not signed in", signIn: "kept" }
3522
+ try {
3523
+ await located(s)
3524
+ } catch (e) {
3525
+ return { error: e.message, signIn: "kept" }
3526
+ }
3527
+ // every card starts from the plan the sign-in saved, as magpie's
3528
+ // built-in did: a reply without a level, a team detail that
3529
+ // failed or an error keeps it
3530
+ const saved = (out) => {
3531
+ const plan = s.plan || auth?.plan
3532
+ if (plan && !out.plan) out.plan = plan
3533
+ // MCP reads as a footnote: its window goes last on the card
3534
+ if (Array.isArray(out.windows) && out.windows.some((w) => w.name === "MCP · Month"))
3535
+ out.windows = [...out.windows.filter((w) => w.name !== "MCP · Month"), ...out.windows.filter((w) => w.name === "MCP · Month")]
3536
+ out.signIn = "kept"
3537
+ return out
3538
+ }
3539
+ try {
3540
+ // a card read is a fresh read: the route is read again with it,
3541
+ // so a plan bought, a gift claimed or a plan lapsed reaches the
3542
+ // requests when the card shows it, not ten minutes later (#379)
3543
+ routes.delete(s.key + "\0" + s.jwt)
3544
+ const { start, gift } = await plansOf(s)
3545
+ let card
3546
+ if (isTeam(s)) {
3547
+ let key = s.key
3548
+ if (!key) {
3549
+ key = await teamKey(s)
3550
+ if (auth?.type === "oauth") {
3551
+ const next = { ...auth, refresh: JSON.stringify({ ...s, key }), access: key }
3552
+ await client?.auth?.set?.({ path: { id: provider?.id ?? PROVIDER }, body: next }).catch?.(() => {})
3553
+ }
3554
+ }
3555
+ const team = await teamUsage(s, key)
3556
+ card = saved(gift || giftReadable(s) ? await dualUsage(s, team) : team)
3557
+ } else card = saved(start ? await startUsage(s) : gift || giftReadable(s) ? await dualUsage(s) : await codingUsage(s))
3558
+ // a gift plan ZCode holds for the account but has not put on it:
3559
+ // named on the card, claimed in the ZCode app (its claim needs
3560
+ // the app's captcha attestation, see claimHint). A card that is
3561
+ // an error keeps its error and asks nothing
3562
+ if (!card.error) {
3563
+ const hint = await claimHint(s)
3564
+ if (hint) card.windows = [...(card.windows ?? []), hint]
3565
+ // a key, or a ZCode session that ran out: no gift read, so no
3566
+ // -Trial models, said on the card rather than left out unsaid
3567
+ const need = start ? null : giftSignIn(s, auth?.type === "api")
3568
+ if (need) card.windows = [...(card.windows ?? []), need]
3569
+ }
3570
+ return card
3571
+ } catch (e) {
3572
+ return saved({ error: e?.message ?? String(e) })
3573
+ }
3574
+ },
3575
+ // the daily claim of ZCode's gift plans (#503): magpie runs it once a
3576
+ // day per account while Settings' Daily check-in has ZCode on (off
3577
+ // until the user turns it on), and its Check in now button asks
3578
+ // right away. See claimDaily.
3579
+ async checkin(getAuth) {
3580
+ try {
3581
+ return await claimDaily(stateOf(await getAuth()))
3582
+ } catch (e) {
3583
+ return { outcome: "failed", message: e?.message ?? String(e) }
3584
+ }
3585
+ },
3586
+ methods: [
3587
+ oauth("zai"),
3588
+ oauth("bigmodel"),
3589
+ // a team's plan beside the account's own (#285): the sign-ins above
3590
+ // take the account's own plan when it has one
3591
+ {
3592
+ type: "oauth",
3593
+ label: "ZCode: a team's GLM Coding Plan",
3594
+ prompts: [
3595
+ {
3596
+ type: "select",
3597
+ key: "site",
3598
+ message: "Where is the team's plan?",
3599
+ options: [
3600
+ { label: "Z.ai", value: "zai", hint: "z.ai" },
3601
+ { label: "BigModel (智谱)", value: "bigmodel", hint: "bigmodel.cn" },
3602
+ ],
3603
+ },
3604
+ ],
3605
+ authorize: (inputs) => authorize(inputs?.site === "bigmodel" ? "bigmodel" : "zai", log, true),
3606
+ },
3607
+ { type: "oauth", label: "ZCode app's sign-in", authorize: async () => asZCode() },
3608
+ {
3609
+ type: "api",
3610
+ label: "GLM Coding Plan API key",
3611
+ prompts: [
3612
+ {
3613
+ type: "select",
3614
+ key: "site",
3615
+ message: "Where is the key from?",
3616
+ options: [
3617
+ { label: "Z.ai", value: "zai", hint: "api.z.ai" },
3618
+ { label: "BigModel (智谱)", value: "bigmodel", hint: "open.bigmodel.cn" },
3619
+ ],
3620
+ },
3621
+ ],
3622
+ },
3623
+ ],
3624
+ },
3625
+ }
3626
+ }
3627
+
3628
+ // for tests
3629
+ // config sets what zcodeConfig has read, for tests: null is ZCode's config
3630
+ // out of reach, undefined forgets it
3631
+ const config = (cfg) => (cfgCache = cfg === undefined ? null : { cfg, at: Date.now() })
3632
+ 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, aloneGift, aloneSeen, aloneNames, claimDaily, spentUp, giftServes, modelOf, teamKeys, ownSignIn, stateOf, giftSignIn, located, dress, queryOf, PROMPT, marked, keyDevice, sessionOf, busy, BUSY_WAITS, DEFAULT_CONCURRENCY, ADDRESS, startSlots }