Repository navigation
Expand file tree
/
Copy pathindex.mjs
More file actions
3674 lines (3520 loc) · 176 KB
/
Copy pathindex.mjs
File metadata and controls
3674 lines (3520 loc) · 176 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// ZCode's GLM Coding Plan, as an OpenCode provider plugin.
//
// ZCode (zcode.z.ai) signs in to a Z.ai account, or a BigModel (智谱,
// bigmodel.cn) one, through a flow zcode.z.ai opens and is polled for. With
// the account's sign-in it finds or makes the coding plan key it uses (the
// key named zcode-api-key in the account's default project) and sends the
// models' requests, Anthropic's Messages, to the plan's endpoint:
// api.z.ai/api/anthropic or open.bigmodel.cn/api/anthropic.
//
// An account with no plan of its own may have a seat on a team's plan (a
// project of type 2, and its zcode-team-api-key), or ZCode's free Start
// Plan, served by zcode.z.ai itself to ZCode's own session token (a JWT
// that can't be refreshed: when it runs out, sign in again).
//
// The sign-in is kept as OpenCode keeps an OAuth one: `access` is the key,
// `refresh` the rest of it as JSON (site, base, key, jwt, team project,
// plan, device id), `accountId` the account's email.
import { createDecipheriv, createHash } from "node:crypto"
import { existsSync, readFileSync, readdirSync } from "node:fs"
import { arch, homedir, release, userInfo } from "node:os"
import { isAbsolute, join } from "node:path"
import PROMPT from "./prompt.mjs"
const PROVIDER = "zcode"
// FREE_FIRST is magpie's switch for free first in the provider's editor
const FREE_FIRST = "free_first"
const ZCODE = "https://zcode.z.ai"
const ZAI_API = "https://api.z.ai"
const BIGMODEL_API = "https://bigmodel.cn" // BigModel's business API, where ZCode asks it
const ZAI_BASE = "https://api.z.ai/api/anthropic"
const BIGMODEL_BASE = "https://open.bigmodel.cn/api/anthropic"
const START_BASE = ZCODE + "/api/v1/zcode-plan/anthropic"
// APP_VERSION is the ZCode this signs in and asks as, on every call. ZCode
// gates by it: its marketing feed answers empty to an older one (#678),
// and its Start Plan balance "judges capability by the real app_version"
// (zaiStartPlanBilling.ts in zai-org/ZCode@a9fe401, 3.17.2).
const APP_VERSION = "3.17.2"
const UA = "ZCode/" + APP_VERSION
// ZCode's models before its config is read; the Start Plan has all but GLM-5.3.
const MODELS = [
{ id: "GLM-5.3", context: 1_000_000, output: 128_000, efforts: ["low", "high", "max"] },
{ id: "GLM-5.3-Flash", context: 1_000_000, output: 128_000, efforts: ["low", "high", "max"] },
{ id: "GLM-5.2", context: 1_000_000, output: 128_000, efforts: ["none", "high", "max"] },
{ id: "GLM-5-Turbo", context: 200_000, output: 64_000, efforts: ["none", "high"] },
]
const START_MODELS = MODELS.filter((m) => m.id !== "GLM-5.3")
const SITES = {
zai: { name: "Z.ai", api: ZAI_API, base: ZAI_BASE, subscribe: "z.ai/subscribe" },
bigmodel: { name: "BigModel", api: BIGMODEL_API, base: BIGMODEL_BASE, subscribe: "bigmodel.cn/glm-coding" },
}
const siteOf = (s) => (s === "bigmodel" ? "bigmodel" : "zai")
const platform = () => `${process.platform}-${process.arch}` // darwin-arm64, win32-x64, linux-x64, as ZCode names them
const uuid = () => crypto.randomUUID()
const anyDevice = uuid() // X-Device-Mid for calls made signed out (the model list)
// uuidOf is a version 4 shaped UUID made from a seed: the same seed gives
// the same UUID every time
const uuidOf = (seed) => {
const h = createHash("sha256").update(seed).digest("hex")
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)}`
}
// keyDevice is a device id for an account known only by its key: the same
// key gives the same id on every start, as a sign-in's saved device does
const keyDevice = (key) => uuidOf("zcode-device\0" + key)
const first = (...ss) => ss.map((s) => (typeof s === "string" ? s.trim() : "")).find((s) => s) ?? ""
// STATUS_TEXT is Go's http.StatusText, which magpie's built-in said a
// refusal with no message in.
const STATUS_TEXT = { 400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 405: "Method Not Allowed",
408: "Request Timeout", 429: "Too Many Requests", 500: "Internal Server Error", 502: "Bad Gateway", 503: "Service Unavailable",
504: "Gateway Timeout" }
class ZError extends Error {
constructor(message, status) {
super(message)
this.status = status
}
}
// call asks one of Z.ai's JSON endpoints, which wrap what they say in
// {code, msg, data}: a code of 0 or 200 is a success. zcode.z.ai is told
// the machine's id (X-Device-Mid), as ZCode tells it.
async function call(method, url, { auth, body, headers, device, signal } = {}) {
const h = { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA }
if (auth) h.Authorization = auth
if (url.startsWith(ZCODE + "/")) h["X-Device-Mid"] = device || anyDevice
Object.assign(h, headers ?? {})
const res = await fetch(url, { method, headers: h, body: body === undefined ? undefined : JSON.stringify(body), signal })
const text = await res.text()
let env
try {
env = JSON.parse(text)
} catch {}
const code = env?.code == null ? "" : String(env.code)
if (!res.ok) {
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())
const err = new ZError(said, res.status)
err.code = Number(code) || 0 // 3002 and the like: so a caller can tell a rate limit from a failure
err.retryAfterMs = retryAfterMs(res) // 0 unless the reply carried a Retry-After
throw err
}
if (!env || typeof env !== "object") throw new ZError("not JSON", res.status)
if (code && code !== "0" && code !== "200") throw new ZError(env.msg || `error ${code}`, res.status)
return env.data ?? null
}
// ---- the account's plan ----------------------------------------------------------
const rootOf = (base) => {
try {
const u = new URL(base)
return `${u.protocol}//${u.host}`
} catch {
return ZAI_API
}
}
const isTeam = (s) => !!(s.org && s.project)
// plan names the coding plan a key has, "" for none.
async function plan(s) {
const subs = (await call("GET", rootOf(s.base) + "/api/biz/subscription/list", { auth: s.key })) ?? []
return (Array.isArray(subs) ? subs : []).find((x) => String(x.status).toUpperCase() === "VALID")?.productName ?? ""
}
function jwtExpiry(jwt) {
const p = String(jwt ?? "").split(".")
if (p.length !== 3) return 0
try {
const claims = JSON.parse(Buffer.from(p[1], "base64url").toString("utf8"))
return Number(claims.exp) > 0 ? Number(claims.exp) * 1000 : 0
} catch {
return 0
}
}
const jwtExpired = (jwt) => {
const t = jwtExpiry(jwt)
return t > 0 && Date.now() > t
}
// EXPIRED is the built-in's words (errZCodeExpired) for a Start Plan
// sign-in past its end.
const EXPIRED = "ZCode's sign-in has expired; sign in to ZCode again (or add the account again in magpie)"
const num = (v) => {
const n = typeof v === "string" ? parseFloat(v) : v
return typeof n === "number" && Number.isFinite(n) ? n : undefined
}
// the alias is the catalog spelling of the model plus -trial, so the picker
// reads GLM-5.3-Trial while the loader strips it back to the raw name
const giftID = (m) => (MODELS.find((x) => x.id.toLowerCase() === String(m).toLowerCase())?.id ?? m) + "-Trial"
const uniqueModels = (names) => {
const byName = new Map()
for (const m of names) if (!byName.has(m.toLowerCase())) byName.set(m.toLowerCase(), m)
return [...byName.values()]
}
const giftNames = (g) => g?.allModels ?? g?.models ?? []
// wireModel is a gift model as ZCode sends it: the buckets name it lowercased
// ("glm-5.3-flash"), the app's request carries its registry id
// ("GLM-5.3-Flash"; normalizeOfficialGlmModelId's spelling). Names ZCode
// does not know go as the bucket wrote them.
const wireModel = (m) => MODELS.find((x) => x.id.toLowerCase() === String(m).toLowerCase())?.id ?? m
const giftModel = (g, id) => giftNames(g).find((m) => giftID(m).toLowerCase() === id.toLowerCase())
const bucketModels = (x) => (Array.isArray(x.capabilities) ? x.capabilities : [])
.map((c) => String(c ?? "").trim()).filter((c) => c.startsWith("model:") || !c.includes(":"))
.map((c) => c.replace(/^model:/, "").trim()).filter(Boolean)
// Both the card and the request route use the same test for a spent bucket.
// Older balances may omit remaining_units but still tell used and total.
const giftSpent = (x) => {
const left = num(x.remaining_units)
if (left !== undefined) return left <= 0
const total = num(x.total_units), used = num(x.used_units)
return total !== undefined && used !== undefined && used >= total
}
// startPlan is the gift an account can spend now ({models}), as ZCode reads
// its balance: several plans can be active at once, and a model routes to
// the gift when any of them has a live bucket serving it — a bucket past
// its plan's own end, or one whose remaining_units says none, is skipped
// rather than asked and refused. models are those live buckets' names.
//
// coming (sign-in only) also takes a plan that has not started yet, as
// ZCode's own check does (resolveStartPlanBalanceAvailability's "pending"
// counts as entitled): {name, models: [], coming: true}. Requests and the
// card never ask for it: a plan not started serves nothing yet.
async function startPlan(jwt, device, coming = false) {
if (!jwt) throw new Error("not signed in to ZCode")
if (jwtExpired(jwt)) throw new Error(EXPIRED)
const b = (await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/balance?app_version=${APP_VERSION}`, { auth: "Bearer " + jwt, device })) ?? {}
const now = num(b.server_time) > 0 ? num(b.server_time) : Date.now() / 1000
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 ?? ""))
const plans = Array.isArray(b.plans) ? b.plans : []
const balances = Array.isArray(b.balances) ? b.balances : []
const ms = new Set(), all = new Map()
let ttl = 600_000
let any = false
let name = ""
for (const p of plans) {
const st = String(p?.status ?? "").trim().toLowerCase()
const end = num(p?.ends_at)
if (st !== "active" || (end > 0 && end <= now) || notStarted(p, now)) continue
any = true
if (end > 0) ttl = Math.min(ttl, (end - now) * 1000)
if (!name) name = String(p?.name ?? "").trim()
for (const x of balances) {
if (!same(x, p)) continue
const exp = num(x.expires_at)
if (exp > 0 && exp <= now) continue
if (exp > 0) ttl = Math.min(ttl, (exp - now) * 1000)
// Spent buckets still declare models; only live ones can spend now.
for (const m of bucketModels(x)) {
if (!all.has(m.toLowerCase())) all.set(m.toLowerCase(), m)
if (!giftSpent(x)) ms.add(m)
}
}
}
if (any) return { name: name || "Start Plan", models: [...ms], allModels: [...all.values()], ttl }
if (!coming) return null
const next = plans.filter((p) => notStarted(p, now) && !(num(p?.ends_at) > 0 && num(p?.ends_at) <= now))
.sort((a, b) => startNum(a.starts_at) - startNum(b.starts_at))[0]
return next ? { name: String(next.name ?? "").trim() || "Start Plan", models: [], allModels: [], ttl, coming: true } : null
}
// plansOf says where an account's requests go and what more it can spend:
// {start, gift}. start is what onStart said: an account with no coding plan
// sends every request to the gift and reads no balance to do it; a
// sign-in with no ZCode token and a key whose plan-list read found
// no gift stay on the coding plan. gift is what a coding account also holds:
// the gift plans ({models}), and its requests spend the gift for a model it
// serves, until it says it is spent (see blocked). Asked again after 10
// minutes (a minute when unsure — a plan-list read that failed is retried
// sooner; a gift read that failed simply leaves gift null until the next
// ask).
const routes = new Map()
async function plansOf(s) {
if (!s.jwt) return { start: false, gift: null }
if (!s.key && !isTeam(s)) return { start: true, gift: null }
const id = s.key + "\0" + s.jwt
const r = routes.get(id)
if (r && Date.now() - r.at < r.ttl) return r
let start = false
let gift = null
let sure = false
try {
// A team seat stays on its team even when its personal plan list is
// empty. Its ZCode session still holds the person's gift plans.
if (!isTeam(s) && !(await plan(s))) start = true
else {
// a gift read that failed is unknown, not "no gift": asked again in
// a minute, so its trial entries come back with the next list (an
// expired session is known: the card says to sign in again)
let failed = false
gift = await startPlan(s.jwt, s.device).catch(() => ((failed = !jwtExpired(s.jwt)), null))
sure = !failed
}
// a key whose plan list read no plan, where the last read found one,
// is asked again in a minute rather than sent to the Start Plan for
// ten: one list without the plan (a renewal's boundary, a hiccup)
// turned a GLM Coding Plan account's every request into the Start
// Plan's 405 until the route was read again (#369)
if (start) sure = !(s.key && r && !r.start)
} catch {
// the plan list could not be read. An account the last read found with
// no coding plan stays on the Start Plan for the minute: the dual route
// would send its key to the coding plan's host, which bills a key with
// no plan pay-as-you-go while the free quota sits unspent (bg5eau on
// X). Any other key account takes the dual route (start stays false,
// the gift is kept, a minute's ttl), so a gift refusal still replays to
// the coding plan rather than blacking out
if (r?.start) start = true
else {
try {
gift = await startPlan(s.jwt, s.device)
} catch {}
}
sure = false
}
const out = { start, gift, at: Date.now(), ttl: Math.min(sure ? 600_000 : 60_000, gift?.ttl ?? 600_000) }
routes.set(id, out)
return out
}
// blocked remembers the models a gift said it has none left for: a key+jwt+
// model for a minute, so one turn that is refused does not ask again.
const blocked = new Map()
// sidelined remembers, the same way, the models whose gift turned free
// first away for another reason (a 405/3012, a block page): free first
// leaves them on the plan for the minute, but a -Trial entry, the user's
// own pick of the gift, still asks ZCode and gets its real answer. Once
// one rest served both, and a refusal under free first answered the
// Trial entry locally as a quota "exhausted" it never was (Can4ry_ on X).
const sidelined = new Map()
const rest = (map, k) => {
for (const [x, until] of map) if (Date.now() >= until) map.delete(x)
map.set(k, Date.now() + 60_000)
}
// giftServes: the gift's buckets name their models lowercased ("glm-5.3-
// flash"); what is asked for arrives as the plan lists it ("GLM-5.3-Flash").
const giftServes = (gift, m) => (gift.models ?? []).some((x) => x.toLowerCase() === m.toLowerCase())
const giftRested = (s, m) => Date.now() < (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
const giftUsable = (s, gift, m) => !jwtExpired(s.jwt) && giftServes(gift, m) &&
Date.now() >= (blocked.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
const giftSidelined = (s, m) => Date.now() < (sidelined.get(s.key + "\0" + s.jwt + "\0" + m.toLowerCase()) ?? 0)
// spentUp is the gift saying it has nothing left to spend: its own no-
// resource-package code 1113, its "exceed quota limit" 1005 — a spent gift
// can answer a 200 with a JSON body carrying one of those codes. Every other
// 429 counts as spent, Z.ai's 1302/1303 rate limits among them; the plan's
// own in-flight cap (3008/3009) does not, since it is a turn not yet come.
function spentUp(text, status) {
if (busy(status, text)) return false
if (status === 429) return true
let b
try { b = JSON.parse(text) } catch { return false }
if (!b || typeof b !== "object") return false
const code = (v) => String(v ?? "")
const c1 = code(b.code), c2 = code(b.error?.code)
return c1 === "1113" || c1 === "1005" || c2 === "1113" || c2 === "1005"
}
// spentSaid is an answer that carries spentUp's code inside a 200, as a
// spent bucket's can, said as the 429 it is (plugins#817: a Start Plan
// account's GLM-5.3 out for the day answered 200 "exceed quota limit",
// which magpie took for a reply that did not stream and rested the whole
// account, GLM-5.3-Flash's own bucket with it). Any other answer goes on
// as it came; a stream's body is never read here.
async function spentSaid(res) {
if (res.status >= 400 || !(res.headers.get("content-type") ?? "").includes("application/json")) return res
const text = await res.text()
const status = spentUp(text, res.status) ? 429 : res.status
return new Response(text, { status, statusText: status === 429 ? "Too Many Requests" : res.statusText, headers: res.headers })
}
// ---- keys ------------------------------------------------------------------------
function teamHeaders(base, org, project) {
return {
"Bigmodel-Organization": org,
"Bigmodel-Project": project,
"Set-Language": base.includes("bigmodel.cn") ? "zh" : "en",
"Accept-Language": "en-US,en",
}
}
const keysURL = (root, org, project) =>
`${root}/api/biz/v1/organization/${encodeURIComponent(org)}/projects/${encodeURIComponent(project)}/api_keys`
// projectKey finds the project's key named want.name (of want.keyType, when
// given), makes it when it isn't there and reads its secret: `<id>.<secret>`.
async function projectKey(site, keys, auth, headers, want) {
const name = SITES[site].name
let list
try {
list = (await call("GET", keys, { auth, headers })) ?? []
} catch (e) {
throw new Error(`${name} API keys: ${e.message}`)
}
const typed = "keyType" in want
let id = ""
for (const k of Array.isArray(list) ? list : []) {
if (k.name === want.name && (!typed || String(k.keyType) === String(want.keyType)) && first(k.apiKey)) id = first(k.apiKey)
}
if (!id) {
try {
id = first((await call("POST", keys, { auth, headers, body: want }))?.apiKey)
} catch (e) {
throw new Error(`${name} API key: ${e.message}`)
}
}
let secret = ""
if (id) {
try {
secret = first((await call("GET", `${keys}/copy/${encodeURIComponent(id)}`, { auth, headers }))?.secretKey)
} catch (e) {
throw new Error(`${name} API key: ${e.message}`)
}
}
if (id && !secret && typed) return id // a team's key with no secret goes as it is
if (!id || !secret) throw new Error(`${name} gave no API key`)
return `${id}.${secret}`
}
// teamKey is a team seat's key when the sign-in kept none.
const teamKeys = new Map()
async function teamKey(s) {
if (s.key) return s.key
const id = [s.token, s.org, s.project].join("\0")
const got = teamKeys.get(id)
if (got && (!got.err || Date.now() - got.at < 60_000)) {
if (got.err) throw got.err
return got.key
}
const site = s.base.includes("bigmodel.cn") ? "bigmodel" : "zai"
try {
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 })
teamKeys.set(id, { key, at: Date.now() })
return key
} catch (e) {
const err = new Error(`ZCode's team plan: ${e.message} — sign in to ZCode again`)
teamKeys.set(id, { err, at: Date.now() })
throw err
}
}
// ---- allowance ---------------------------------------------------------------------
// As magpie's built-in told it (internal/provider zcode.go, zcode_start.go,
// zcode_team.go): the Coding Plan's windows and term, the Start Plan's
// buckets, or a team seat's windows and its plan's end.
// bizRoot is the business API of the site a plan is served from.
function bizRoot(base) {
let h = ""
try {
h = new URL(base).host.toLowerCase()
} catch {}
return h === new URL(BIGMODEL_BASE).host || h.endsWith("bigmodel.cn") ? BIGMODEL_API : rootOf(base)
}
// spanOf reads a limit's window, in seconds: unit 3 counts hours, 6 weeks
// (and 1, 4, 5 minutes, days and months by the same count). A team's five
// hours come with no count.
function spanOf(unit, n) {
n = Math.trunc(Number(n) || 0)
if (unit === 3 && n <= 0) n = 5
n = Math.max(n, 1)
return { 1: 60, 3: 3600, 4: 86400, 5: 30 * 86400, 6: 7 * 86400 }[unit] * n || 0
}
function windowName(span) {
if (span === 0) return "Credits"
if (span < 86400) return `${Math.trunc(span / 3600)} hours`
if (span === 7 * 86400) return "Weekly"
if (span >= 28 * 86400) return "Monthly"
return `${Math.trunc(span / 86400)} days`
}
// compact is a count as magpie says one: whole, else to two places.
const compact = (n) => (Number.isInteger(n) ? String(n) : n.toFixed(2).replace(/0+$/, "").replace(/\.$/, ""))
const isNum = (v) => typeof v === "number" && Number.isFinite(v)
// limitWindows are /api/monitor/usage/quota/limit's limits as windows: what
// is used of the whole when both are told (the whole less what remains, or
// the current value), else the percentage given. TIME_LIMIT is the month's
// MCP tool calls, which ZCode shows but never stops the models on, so it is
// set aside, as is a limit whose whole is told as 0: no cap (an older
// plan's), which the vendor may still give as 100% used. A window whose
// count is told carries it as amount of limit, so magpie's card says the
// count as used or as left, as it says the share beside it (#659).
function limitWindows(d) {
const out = []
for (const x of d?.limits ?? []) {
const span = spanOf(Math.trunc(Number(x?.unit) || 0), x?.number)
const w = { name: windowName(span), used: 0 }
if (String(x?.type ?? "").toUpperCase() === "TIME_LIMIT") (w.name = "MCP · Month"), (w.aside = true)
if (isNum(x?.percentage)) w.used = x.percentage
if (x?.usage === 0) (w.used = 0), (w.aside = true)
if (isNum(x?.usage) && x.usage > 0) {
const total = x.usage
if (isNum(x.remaining)) {
const used = total - x.remaining
w.used = (100 * used) / total
w.amount = used
w.limit = total
w.display = `${compact(used)} / ${compact(total)}`
} else if (isNum(x.currentValue)) {
if (!isNum(x.percentage)) w.used = (100 * x.currentValue) / total
w.amount = x.currentValue
w.limit = total
w.display = `${compact(x.currentValue)} / ${compact(total)}`
}
}
const reset = Math.trunc(Number(x?.nextResetTime) || 0)
if (reset > 0) w.resetsAt = new Date(reset).toISOString()
if (span) w.span = span
out.push(w)
}
return out
}
// beijing reads the plan's times, "2026-10-18 12:00:00" in Beijing: ms, or 0.
function beijing(s) {
s = String(s ?? "").trim().replace(" ", "T")
if (!/^\d{4}-\d{2}-\d{2}(T\d{2}:\d{2}:\d{2})?$/.test(s)) return 0
const t = Date.parse(s + (s.length === 10 ? "T00:00:00" : "") + "+08:00")
return Number.isFinite(t) ? t : 0
}
// termOf is how long a GLM Coding plan is paid for: the valid
// subscription's next renewal, a charge when it renews itself, else the
// end of its time, the last date its "valid" span names.
function termOf(subs) {
for (const x of Array.isArray(subs) ? subs : []) {
if (String(x?.status ?? "").toUpperCase() !== "VALID") continue
const auto = x.autoRenew === true || x.autoRenew === 1
const t = beijing(typeof x.nextRenewTime === "string" ? x.nextRenewTime : "")
if (t) return { until: new Date(t).toISOString(), renew: auto ? "auto" : "off" }
const ds = String(typeof x.valid === "string" ? x.valid : "").match(/\d{4}-\d{2}-\d{2}(?:[ T]\d{2}:\d{2}:\d{2})?/g) ?? []
if (ds.length && !auto) {
const end = beijing(ds[ds.length - 1])
if (end) return { until: new Date(end).toISOString(), renew: "off" }
}
return {}
}
return {}
}
// codingUsage is a Coding Plan key's allowance: credits per five hours and
// per week, the plan's level and its term.
async function codingUsage(s) {
const root = rootOf(s.base)
const d = (await call("GET", root + "/api/monitor/usage/quota/limit", { auth: s.key })) ?? {}
const out = {}
const level = typeof d.level === "string" ? d.level : ""
if (level) out.plan = "GLM Coding " + level[0].toUpperCase() + level.slice(1)
out.windows = limitWindows(d)
notePlan(s.key, out.windows)
const resets = personalResets(root, s.key)
let subs = null
try {
subs = await call("GET", root + "/api/biz/subscription/list", { auth: s.key })
Object.assign(out, termOf(subs))
} catch {}
const r = await resets
if (r) out.resets = r
// a key whose account has no plan in force, read as such, says so
// rather than showing an empty card: what a key can spend is a GLM
// Coding Plan alone (a ZCode gift plan is never one, see NO_PLAN_KEY).
// A list that couldn't be read, a level, a counted window or a plan
// the sign-in saved keeps the card as it was.
const valid = (Array.isArray(subs) ? subs : []).some((x) => String(x?.status ?? "").toUpperCase() === "VALID")
if (subs !== null && !valid && !level && !s.plan && !out.windows.some((w) => !w.aside)) return { error: NO_PLAN_KEY }
return out
}
// NO_PLAN_KEY is a key with no GLM Coding Plan behind it. ZCode's gift
// plans (its Start Plan, ZCode 1024 Dev Day) are served by zcode.z.ai
// to ZCode's own session token, which a sign-in with ZCode (the app's,
// or Z.ai's or BigModel's in the browser) carries and a key never does:
// with a key, a gift-only account has nothing to spend, and Z.ai answers
// each request 1113 (rtbeilin on X, 10-24).
const NO_PLAN_KEY =
"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"
// noPlanKey is a coding plan's 1113 refusal (no plan, no resource
// package) to a sign-in with no ZCode session, its message followed by
// NO_PLAN_KEY; anything else goes on as it came. Read only once the
// answer has failed.
function noPlanKey(res, text) {
let v
try {
v = JSON.parse(text)
} catch {
return null
}
// Z.ai names the code in error.code ("1113", as magpie's
// zhipu_coding_test has it) or error.type (its 401's "1000"), BigModel's
// envelope in code
if (![v?.error?.code, v?.error?.type, v?.code].some((c) => String(c ?? "") === "1113")) return null
const said = first(v?.error?.message, v?.msg, v?.message)
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 }
const h = new Headers(res.headers)
h.set("content-type", "application/json")
return new Response(JSON.stringify(out), { status: res.status, statusText: res.statusText, headers: h })
}
// startNum reads a number the balance gives as a number or a string.
function startNum(v) {
if (isNum(v)) return v
if (typeof v === "string" && v.trim() !== "") {
const n = Number(v.trim())
if (!Number.isNaN(n)) return n
}
return undefined
}
// notStarted is a plan whose starts_at is still to come (a Start Plan
// that takes effect at 23:00 today, windy on Discord): it serves nothing
// yet, so no request is routed to it and its buckets don't count, but the
// card names it with its start. ZCode's balance gives every plan a
// starts_at in Unix seconds; which status a plan not started yet carries
// is not known, so any but "expired" is taken.
function notStarted(p, now) {
const at = startNum(p?.starts_at)
return at > now && String(p?.status ?? "").trim().toLowerCase() !== "expired"
}
// PENDING is the card's line for a gift plan that has not started yet: a
// fixed sentence, so magpie translates it; the plan's name and its start,
// in this computer's time, are the display. Set aside: it stops nothing.
const PENDING = "ZCode gift plan not started yet"
const two = (n) => String(n).padStart(2, "0")
const localTime = (sec) => {
const d = new Date(Math.trunc(sec) * 1000)
return `${d.getFullYear()}-${two(d.getMonth() + 1)}-${two(d.getDate())} ${two(d.getHours())}:${two(d.getMinutes())}`
}
const pendingLines = (g) => (g?.pending ?? []).map((p) => ({ name: PENDING, used: 0, aside: true, display: `${p.name} · ${localTime(p.start)}` }))
// giftOf reads the balance and returns the gift's card fields: its plans and
// windows. Several plans can be active at once, so every live plan's buckets
// show, each keeping its own models and end; the plan and end put on the
// card (for a gift-only account) are the soonest-ending live plan's. null
// when there is no live plan to show.
async function giftOf(s) {
if (!s.jwt) throw new Error("not signed in to ZCode")
if (jwtExpired(s.jwt)) throw new Error(EXPIRED)
const b = (await call("GET", `${ZCODE}/api/v1/zcode-plan/billing/balance?app_version=${APP_VERSION}`, { auth: "Bearer " + s.jwt, device: s.device })) ?? {}
const str = (v) => (typeof v === "string" ? v : "")
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) }))
const now = startNum(b.server_time) > 0 ? startNum(b.server_time) : Math.trunc(Date.now() / 1000)
const over = new Set()
for (const p of plans) {
const end = startNum(p.ends_at)
if (end > 0 && end <= now && p.status.trim().toLowerCase() === "active") p.status = "expired"
if (p.status.trim().toLowerCase() === "expired") over.add(p.user_plan_id + "\0" + p.plan_id)
}
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 ?? ""))
const balances = (Array.isArray(b.balances) ? b.balances : [])
.map((x) => ({ ...x, user_plan_id: str(x?.user_plan_id), plan_id: str(x?.plan_id) }))
.filter((x) => {
let keep = true
for (const p of plans) {
if (!same(x, p)) continue
keep = !over.has(p.user_plan_id + "\0" + p.plan_id)
if (keep) break
}
return keep
})
// a plan not started yet is named with its start, soonest first; its
// buckets, if the balance lists any, wait for it
const pending = plans.filter((p) => notStarted(p, now))
.map((p) => ({ name: first(str(p.name), "Start Plan"), start: startNum(p.starts_at) }))
.sort((a, b) => a.start - b.start)
// every live plan counts as the gift: no plan-name filter decides it,
// the balance says what the session can spend
let active = null
for (const p of plans) {
if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) continue
const end = startNum(p.ends_at)
if (end > 0 && end <= now) continue
if (active && !(end > 0 && (!startNum(active.end) || end < startNum(active.end)))) continue
active = { name: first(str(p.name), "Start Plan"), end, until: end > 0 ? new Date(Math.trunc(end) * 1000).toISOString() : "" }
}
if (!active && !pending.length) return null
// with no live plan, the one starting soonest names the card
const out = { plan: active?.name ?? pending[0].name, windows: [], live: !!active, pending }
if (active?.until) Object.assign(out, { until: active.until, renew: "off" })
const live = plans.filter((p) => {
if (p.status.trim().toLowerCase() !== "active" || notStarted(p, now)) return false
const end = startNum(p.ends_at)
return !(end > 0 && end <= now)
})
for (const x of balances) {
const owner = live.find((p) => same(x, p))
if (!owner) continue
const exp = startNum(x.expires_at)
if (exp > 0 && exp <= now) continue // a bucket past its own end is over
const total = startNum(x.total_units), left = startNum(x.remaining_units)
let used = startNum(x.used_units)
if (total === undefined && used === undefined && left === undefined) continue
const models = bucketModels(x)
const base = first(str(x.show_name), models.join(", "), "Credits")
const w = { name: base, used: 0, _plan: str(owner.name), _spent: giftSpent(x) }
if (used === undefined) used = total !== undefined && left !== undefined ? total - left : 0
if (total > 0) {
// the bucket's count as amount of limit, as the Coding windows' is
// (#659): magpie says it as used or as left, as it says the share
w.used = (100 * used) / total
w.amount = used
w.limit = total
w.display = `${compact(used)} / ${compact(total)}`
}
if (w._spent) w.used = Math.max(100, w.used)
if (exp > 0) w.resetsAt = new Date(Math.trunc(exp) * 1000).toISOString()
let span = 0
for (const p of plans) {
if (!same(x, p)) continue
for (const e of Array.isArray(p.entitlements) ? p.entitlements : []) {
if (str(e?.entitlement_id) === str(x.entitlement_id)) span = periodOf(str(e?.period))
}
}
if (!span) {
const a = startNum(x.period_start), z = startNum(x.period_end)
if (a !== undefined && z !== undefined && z > a) span = Math.trunc(z - a)
}
if (span) w.span = span
if (models.length) w.models = models
out.windows.push(w)
}
return out
}
// CLAIM_HINT is the claim line's name: a fixed sentence, so magpie
// translates it with the interface's own language (the plan's name and
// the count are data, and go in the display, which is shown as it came).
const CLAIM_HINT = "Gift plans to claim in the ZCode app"
// claimHint is the card's line for gift plans ZCode is holding for the
// account but has not put on it: the app's banners (marketing/touch)
// list them (toClaim). The
// card only names them: they are claimed in the ZCode app, or by the
// daily claim (claimDaily) when the user turned it on; on 10-06 a claim
// without the app's Aliyun captcha attestation was refused (3007). A window, set aside (it is no
// allowance: using it up stops nothing), so the card shows it and
// routing, caps and the menu bar pass it over. The window's name is a
// fixed sentence, so magpie can translate it (a display is shown as it
// came); the count and the plan's own name go in the display. null when
// there is nothing to claim, the preview failing or listing none among
// it: a failed read is no line at all, never a card or a refusal of its
// own.
async function claimHint(s) {
if (!s.jwt || jwtExpired(s.jwt)) return null
const { plans } = await toClaim(s)
if (!plans.length) return null
const n = plans.length
const plan = first(...plans.map((p) => p.name), "ZCode gift plan")
return { name: CLAIM_HINT, used: 0, aside: true, display: `${n} · ${plan}` }
}
// unclaimed names the gift plans ZCode holds for the account but has not
// put on it (toClaim), for a -Trial pick that finds no gift: the weekend
// plan (ZCODE WEEKEND BUILD) comes only by a claim, and the claim needs
// the ZCode app's captcha (claimDaily posts none), so until it is
// claimed in the app the pick's quota does not exist yet (heduian and
// bg5eau on X, 11-14). The refusal says where the quota is rather than
// only that there is none. Kept ten minutes per session, so an agent
// retrying the pick doesn't read the feed each time; a read that fails
// names none and is not kept.
// aloneSeen is a gift-only account's balance as last read (the model list
// reads it), kept ten minutes. A request reads no balance on its own: only
// a model the kept balance doesn't name has it read again (aloneGift), so
// a gift claimed since is not refused. A read that fails is not kept.
const aloneSeen = new Map()
const aloneNames = (s) => {
const c = aloneSeen.get(s.jwt)
return c && Date.now() - c.at < 600_000 ? giftNames(c.gift) : []
}
async function aloneGift(s) {
let gift
try {
gift = await startPlan(s.jwt, s.device)
} catch {
return null
}
aloneSeen.set(s.jwt, { at: Date.now(), gift })
return gift
}
const unclaimedSeen = new Map()
async function unclaimed(s) {
if (!s.jwt || jwtExpired(s.jwt)) return []
const k = s.jwt
const c = unclaimedSeen.get(k)
if (c && Date.now() - c.at < 600_000) return c.names
const got = await toClaim(s).catch(() => null)
if (!got || got.unread.length) return []
const names = uniqueModels(got.plans.map((p) => first(p.name, p.plan_id)).filter(Boolean))
unclaimedSeen.set(k, { at: Date.now(), names })
return names
}
// ---- the daily claim ---------------------------------------------------------------
// CLAIMED_ALREADY is /billing/claim's body code for a plan the account
// has claimed before: HTTP 200 {"code":1003,"msg":"target already
// exists"} (magpie-community/plugins#503, a real reply), the desktop
// app's manualClaimPlan.claim.failure.alreadyClaimed. CAPTCHA is its
// answer to a claim without the Aliyun captcha attestation the ZCode app's
// renderer makes: HTTP 400 {"code":3007,"msg":"captcha verify failed"}
// (seen 10-06, #30).
const CLAIMED_ALREADY = 1003
const CAPTCHA = 3007
// NOT_ELIGIBLE is /billing/claim's body code for a plan the account is not
// offered at that moment: HTTP 400 {"code":1004,…}. A stale APP_VERSION
// answers it for every account at once (11-04: six accounts all answered
// 1004 under 3.16.3's header, and four of them claimed with code 0 under
// 3.17.2's, one night, with nothing else changed).
const NOT_ELIGIBLE = 1004
// RATE_LIMITED is Z.ai's "请求过于频繁" body code, its answer (with HTTP
// 429) to a client that asked too often. #503 (MiniFullC, 11-04) read 180
// "gift plans to claim: Too Many Requests" over four days at magpie's
// 30-minute retry, so asking again the same half hour keeps the limit on.
// magpie asks a failed again once retryAfter() has passed, whatever the
// answer's `until` says (the contract reads `until` as when an answer
// stops standing, not as the earliest time to ask again), so the account
// is held here instead: while the wait lasts, claimDaily answers the same
// failed again, `until` and all, and asks ZCode nothing. A Retry-After
// ZCode sent is honored up to RATE_LIMIT_MAX_MS; without one the
// account's own wait doubles from RECHECK_MS, and a read that comes
// through forgets it.
const RATE_LIMITED = 3002
const RATE_LIMIT_MAX_MS = 6 * 60 * 60_000
const rateWait = new Map() // s.key -> { ms, until, message }: the hold this account is under
// resetRateWait is for tests: it forgets the holds, and with `expire` it
// back-dates them, standing where the wait has passed. The plugin itself
// forgets a hold by reading through or by waiting it out, never by calling
// this.
export function resetRateWait(expire = false) {
if (!expire) {
rateWait.clear()
return
}
for (const [k, h] of rateWait) rateWait.set(k, { ...h, until: new Date(Date.now() - 1).toISOString() })
}
// holdKey names the account a wait belongs to. stateOf gives key: "" to a
// sign-in that has a jwt and no API key — the Start-Plan-only sign-ins
// that claim gift plans, #503's case — so the key alone would put every
// one of them under a single hold, and one account's 429 would answer for
// all of them. The jwt tells them apart; a renewed token starting its own
// wait is fine.
const holdKey = (s) => s.key || s.jwt
// retryAfterMs is a Retry-After header, in seconds or as an HTTP date, in
// ms; 0 when there is none or it doesn't read.
function retryAfterMs(res) {
const v = first(res?.headers?.get?.("retry-after"))
if (!v) return 0
const secs = Number(v)
if (Number.isFinite(secs) && secs > 0) return secs * 1000
const at = Date.parse(v)
return Number.isFinite(at) ? Math.max(0, at - Date.now()) : 0
}
// noteRateLimit remembers the wait this account is under, with the failed
// that wait answers with, and says when it ends: a Retry-After ZCode sent
// is taken as it is, up to the cap; without one the wait doubles from
// RECHECK_MS (and never falls below it), so a client ZCode keeps turning
// away asks less and less.
function noteRateLimit(key, saidMs, message) {
const last = rateWait.get(key)?.ms ?? 0
const want = saidMs > 0 ? saidMs : Math.max(RECHECK_MS, last * 2)
const ms = Math.min(RATE_LIMIT_MAX_MS, want)
const until = new Date(Date.now() + ms).toISOString()
rateWait.set(key, { ms, until, message })
return until
}
const CAPTCHA_WORDS = /captcha/i
// claimNeedsCaptcha says whether ZCode's claims want its security check
// now, from what client/configs says: its captcha (Aliyun's, which the
// ZCode app passes before every claim, invisibly as a rule, and sends as
// X-Aliyun-Captcha-Verify-Param, 3.17.2's requestVerificationClaimHeaders)
// switched on. No captcha in the configs is no check, as the app reads it
// (readRequestVerificationConfig gives null, and the claim goes without
// the header); one that isn't an object is unknown, null.
// skip_model_request is the same check for Start Plan requests, which it
// spares (true on 11-07); it is not read here.
function claimNeedsCaptcha(c) {
const k = c?.configs?.captcha
if (k == null) return false
if (typeof k !== "object" || Array.isArray(k)) return null
return k.enabled !== false
}
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"
// The marketing feed and the claim are gated on the client's version:
// under an older version's header the feed answers empty (11-03, #678:
// the day's banner showed for 3.17.2 and for no older one), so they go,
// as every call does, as the current client (APP_VERSION) sends them.
const marketingHeaders = () => ({ "X-ZCode-App-Version": APP_VERSION, "X-Platform": platform(), "X-Client-Language": clientLanguage() })
// claimOne asks /billing/claim for one plan and says what its body says:
// "claimed" (code 0), "done" (code 1003, claimed before), "captcha" (the
// claim wants the app's captcha), else "failed" with why. Only a body
// that reads decides: an HTTP error without one, or text that isn't
// JSON, is failed (unknown), never claimed. Only the code is read (#503
// has a real code 0 reply, "Plan claimed successfully.").
async function claimOne(s, planID) {
let res, text
try {
res = await fetch(`${ZCODE}/api/v1/zcode-plan/billing/claim`, {
method: "POST",
headers: { "Content-Type": "application/json", Accept: "application/json", "User-Agent": UA, Authorization: "Bearer " + s.jwt, "X-Device-Mid": s.device || anyDevice, ...marketingHeaders() },
body: JSON.stringify({ plan_id: planID }),
})
text = await res.text()
} catch (e) {
return { outcome: "failed", why: e?.message ?? String(e) }
}
let env
try {
env = JSON.parse(text)
} catch {}
const code = env && typeof env === "object" && env.code != null && String(env.code).trim() !== "" ? Number(env.code) : NaN
const msg = typeof env?.msg === "string" ? env.msg : ""
// a rate limit is no claim: it is said as one, and carries how long to wait
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) }
if (code === CAPTCHA || CAPTCHA_WORDS.test(msg)) return { outcome: "captcha", why: msg || `code ${code}` }
if (code === CLAIMED_ALREADY) return { outcome: "done" }
if (code === NOT_ELIGIBLE) return { outcome: "ineligible", why: msg || `code ${code}` }
if (code === 0 && res.ok) return { outcome: "claimed" }
if (!Number.isFinite(code)) return { outcome: "failed", why: `HTTP ${res.status}, unreadable reply ${String(text ?? "").trim().slice(0, 120) || "(empty)"}` }
return { outcome: "failed", why: `${msg || "error"} (HTTP ${res.status}, code ${code})` }
}
// TOUCH is ZCode's marketing feed: the ZCode app's claim banners come
// from it. A banner plan ("ZCODE WEEKEND BUILD", 10-30) is served only
// while the app shows its banner, and the app claims it through the same
// /billing/claim (#503's capture of 10-30, kongbai01203: GET
// /api/v1/marketing/touch?seq=<n, counting up from 0> with the session,
// X-Device-Mid, X-Client-Language and X-ZCode-App-Version, answered
// data.deliveries[].banner.buttons[].action = {"type":"claim_zcode_plan",
// "args":{"plan_id":…}} and the plan's name in
// banner.background.args.zcode_plan.name). The v3.17 client reads this
// feed alone: the old preview polling is gone, and the rewards center's
// gifts are the rewards website's, claimed in the client.
const TOUCH = "/api/v1/marketing/touch"
const CLAIM_ACTION = "claim_zcode_plan"
// touchSeq is the feed's seq: ZCode's own count of its feed requests
// since the process started, from 0, one GET per refresh. It is not a
// page: "仅供服务端日志定位,不改变投放判断" (docs/marketing-touch-client.md,
// marketingTouchService.ts's bootRequestSeq, zai-org/ZCode@a9fe401), so a
// check-in asks once, never seq 0..8 in a row (plugins#676), and a banner
// seen at one seq and not another is a delivery arriving later.
let touchSeq = 0
// clientLanguage is the language ZCode names to marketing/touch: zh-CN or
// en-US, its two UI languages, never another (marketingTouchService's
// localeSchema), so a computer set to zh-Hans-CN or en-GB asks as ZCode does.
const clientLanguage = () => {
let l = ""
try {
l = Intl.DateTimeFormat().resolvedOptions().locale || ""
} catch {}
return /^zh\b/i.test(l) ? "zh-CN" : "en-US"
}
// touchPlans is the plans marketing/touch's deliveries offer to claim:
// [{plan_id, name}], [] for a feed with no deliveries, null for one that
// doesn't read. Each delivery is searched for its claim_zcode_plan
// actions and its zcode_plan's name, wherever the banner keeps them, so
// a button moved inside the banner is still found.
function touchPlans(d) {
if (d == null) return []
if (typeof d !== "object" || Array.isArray(d)) return null
if (d.deliveries == null) return []
if (!Array.isArray(d.deliveries)) return null
const out = []
for (const dv of d.deliveries) {
const ids = [], names = []
const walk = (v, depth) => {
if (!v || typeof v !== "object" || depth > 12) return
if (Array.isArray(v)) return v.forEach((x) => walk(x, depth + 1))
if (v.type === CLAIM_ACTION && typeof v.args?.plan_id === "string" && v.args.plan_id.trim()) ids.push(v.args.plan_id.trim())
if (v.zcode_plan && typeof v.zcode_plan === "object" && typeof v.zcode_plan.name === "string") names.push(v.zcode_plan.name)
for (const k of Object.keys(v)) walk(v[k], depth + 1)
}
walk(dv, 0)
for (const id of ids) out.push({ plan_id: id, name: first(names[0] ?? "", id) })
}
return out
}
// toClaim is every gift plan the account can claim: what the app's
// marketing feed offers (its banners). The v3.17 client replaced the old
// preview polling with the feed alone (docs/marketing-touch-client.md in
// zai-org/ZCode), so the preview is read no more; a rewards center's gift
// lives on the rewards website, outside this API, and is claimed in the
// client. unread names a feed that didn't read: its plans are unknown,
// never none.
async function toClaim(s) {
const plans = [], unread = []
const add = (p) => {
if (!plans.some((q) => q.plan_id === p.plan_id)) plans.push(p)
}
let d
try {
d = await call("GET", `${ZCODE}${TOUCH}?seq=${touchSeq++}`, { auth: "Bearer " + s.jwt, device: s.device, headers: marketingHeaders() })
} catch (e) {
unread.push(`gift plans to claim: ${e?.message ?? String(e)}`)
// rate is the ms ZCode asked to wait (0 when it sent no Retry-After),
// null when this was not a rate limit at all
return { plans, unread, rate: e?.status === 429 || e?.code === RATE_LIMITED ? (e.retryAfterMs || 0) : null }
}
const got = touchPlans(d)
if (!got) unread.push("gift plans to claim: the plan list doesn't read")
else got.forEach(add)
return { plans, unread, rate: null }
}
// RECHECK is how long an answer that leaves the day open stands before
// magpie's loop asks again: ZCode drops gift plans into the feed during
// the day on its own schedule (the weekend plan of
// testdata/touch-1030-wk.json starts 19:00 Beijing; @aaron0x10 on X,
// 11-22: a second one follows at 19:30), and the day's ask may have run
// hours before, so an answer settled for the day lets a plan sit
// unclaimed past its short life. `until` wakes the loop again in half an
// hour, and it asks again all day — one GET each time. That holds after a
// claim too (claimed, done): the recheck posts only plans this account
// has no answer for today (dayAnswers), so a plan claimed, answered 1003
// or held for the captcha is never posted again, and one that has left
// the feed is still the day's claim — answered done, so the card keeps
// "Checked in today" instead of flipping to "No check-in event now". A
// captcha needs no until: magpie leaves it for the day, as it waits on
// the user. A failed needs none either: magpie asks a failed again after
// 30 minutes of its own. The same shape as Qoder's campaign that opens
// mid-day, asked again on magpie's side there (yetone/magpie#2696).
const RECHECK_MS = 30 * 60_000