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

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