Repository navigation
Expand file tree
/
Copy pathindex.test.mjs
More file actions
4993 lines (4636 loc) · 253 KB
/
Copy pathindex.test.mjs
File metadata and controls
4993 lines (4636 loc) · 253 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
// Unit tests for the CodeArts OAuth plugin. Run with: bun test (node --test
// runs them too).
//
// These tests exercise the pieces magpie calls (_internal helpers) and the
// hooks the plugin returns, with the network stubbed out via `options.fetch`.
import test from "node:test"
import assert from "node:assert/strict"
import fs from "node:fs"
import http from "node:http"
import net from "node:net"
import os from "node:os"
import path from "node:path"
import { CodeArtsAuthPlugin, OfficeAceAuthPlugin, _internal as x, _officeace as oa } from "./index.mjs"
// The record-key file lives beside the check-in ledger; a test must never write
// the real ~/.config (a fresh CI home hides this, a developer's does not).
process.env.MAGPIE_CODEARTS_RECORDS = path.join(os.tmpdir(), `codearts-records-test-${process.pid}.json`)
// Never the real ledger in ~/.config/magpie: every plugin made here keeps its
// check-ins in a scratch file of its own.
const ledgerDir = fs.mkdtempSync(path.join(os.tmpdir(), "codearts-ledger-"))
process.env.MAGPIE_CODEARTS_LEDGER = path.join(ledgerDir, "default.json")
test.after(() => fs.rmSync(ledgerDir, { recursive: true, force: true }))
// Never the real CodeArts Agent's state.vscdb: a plugin made here without an
// `ideStateFile` of its own looks at a file that isn't there.
process.env.MAGPIE_CODEARTS_IDE_STATE = path.join(ledgerDir, "no-ide", "state.vscdb")
const buf = (s) => new TextEncoder().encode(s)
// ---- crypto primitives -----------------------------------------------------
test("sha256Hex matches the known SHA-256 of the empty string", async () => {
assert.equal(
await x.sha256Hex(new Uint8Array()),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
)
})
test("hmacSha256Hex matches RFC 4231 test case 2", async () => {
assert.equal(
await x.hmacSha256Hex(buf("Jefe"), buf("what do ya want for nothing?")),
"5bdcc146bf60754e6a042426089575c75a003f089d2739839dec58b964ec3843",
)
})
test("generatePkcePair derives the S256 challenge from the verifier", async () => {
const pkce = await x.generatePkcePair()
assert.match(pkce.codeVerifier, /^[A-Za-z0-9_-]{64}$/)
const expected = x.b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", buf(pkce.codeVerifier))))
assert.equal(pkce.codeChallenge, expected)
})
test("signDpopJws produces a verifiable ES256 dpop+jwt", async () => {
const keyPair = await x.generateDpopKeyPair()
const jws = await x.signDpopJws(keyPair, "POST", "https://sts.example.com/tokens")
const [h, p, s] = jws.split(".")
assert.equal(jws.split(".").length, 3)
const header = JSON.parse(Buffer.from(h, "base64url").toString())
assert.equal(header.alg, "ES256")
assert.equal(header.typ, "dpop+jwt")
assert.deepEqual(header.jwk, keyPair.publicKeyJwk)
const payload = JSON.parse(Buffer.from(p, "base64url").toString())
assert.equal(payload.htm, "POST")
assert.equal(payload.htu, "https://sts.example.com/tokens")
assert.equal(typeof payload.iat, "number")
assert.equal(typeof payload.jti, "string")
const key = await crypto.subtle.importKey(
"jwk", keyPair.publicKeyJwk, { name: "ECDSA", namedCurve: "P-256" }, false, ["verify"],
)
const ok = await crypto.subtle.verify(
{ name: "ECDSA", hash: "SHA-256" }, key, Buffer.from(s, "base64url"), buf(`${h}.${p}`),
)
assert.ok(ok, "the DPoP signature must verify against the advertised public key")
})
// ---- SDK-HMAC-SHA256 signing -----------------------------------------------
test("buildCanonicalRequest lays out the canonical request exactly", () => {
const headers = new Map([
["host", "example.com"],
["x-sdk-content-sha256", "H"],
["x-sdk-date", "D"],
["x-security-token", "ST"],
])
const expected = [
"GET",
"/path/",
"",
"host:example.com",
"x-sdk-content-sha256:H",
"x-sdk-date:D",
"x-security-token:ST",
"",
"host;x-sdk-content-sha256;x-sdk-date;x-security-token",
"H",
].join("\n")
assert.equal(x.buildCanonicalRequest("GET", "/path/", "", headers, "H"), expected)
})
test("signRequestHuawei signs a GET with the expected header set", async () => {
const signed = await x.signRequestHuawei(
"AK", "SK", "ST", "GET", "https://example.com/path", new Uint8Array(), undefined, "20260101T000000Z",
)
assert.equal(signed.get("x-sdk-date"), "20260101T000000Z")
assert.equal(
signed.get("x-sdk-content-sha256"),
"e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855",
)
assert.equal(signed.get("x-security-token"), "ST")
// GET carries no content-type.
assert.equal(signed.has("content-type"), false)
assert.match(
signed.get("Authorization"),
/^SDK-HMAC-SHA256 Access=AK,SignedHeaders=host;x-sdk-content-sha256;x-sdk-date;x-security-token,Signature=[0-9a-f]{64}$/,
)
})
test("signRequestHuawei includes content-type and maas_type in a signed POST", async () => {
const signed = await x.signRequestHuawei(
"AK", "SK", "ST", "POST", "https://example.com/api/v2/chat/completions",
buf('{"model":"glm-5.3-flash"}'), { maas_type: "benefit" }, "20260101T000000Z",
)
const auth = signed.get("Authorization")
assert.match(auth, /SignedHeaders=content-type;host;maas_type;x-sdk-content-sha256;x-sdk-date;x-security-token,/)
assert.equal(signed.get("content-type"), "application/json")
assert.equal(signed.get("maas_type"), "benefit")
})
test("canonicalQuery sorts and RFC 3986-encodes the query the way the gateway checks it", () => {
assert.equal(x.canonicalQuery(new URL("https://h/p?offset=0&limit=100")), "limit=100&offset=0")
assert.equal(x.canonicalQuery(new URL("https://h/p?agent_id=a b&x=(1)*")), "agent_id=a%20b&x=%281%29%2A")
assert.equal(x.canonicalQuery(new URL("https://h/p")), "")
})
test("vendorDate reads CodeArts' dates; a zone-less one is Beijing time", () => {
assert.equal(x.vendorDate("2026-11-01"), Date.parse("2026-10-31T16:00:00Z"))
assert.equal(x.vendorDate("2026-11-01 08:30:00"), Date.parse("2026-11-01T00:30:00Z"))
assert.equal(x.vendorDate("2026-11-01T00:00:00Z"), Date.parse("2026-11-01T00:00:00Z"))
assert.equal(x.vendorDate(1793462400), 1793462400000)
assert.equal(x.vendorDate("1793462400000"), 1793462400000)
assert.equal(x.vendorDate("soon"), undefined)
assert.equal(x.vendorDate(""), undefined)
})
test("creditRateOf reads the 消耗系数 from one tier or a list of them", () => {
assert.equal(x.creditRateOf({ ratio: 2, ratio_display: "1.5" }), 1.5)
assert.equal(x.creditRateOf([{ ratio_display: 0.3 }, { ratio_display: 2 }]), 0.3)
assert.equal(x.creditRateOf(undefined), 0)
assert.equal(x.creditRateOf({ ratio_display: "0" }), 0)
})
test("signRequestHuawei is deterministic for a fixed date stamp", async () => {
const args = ["AK", "SK", "ST", "POST", "https://example.com/x", buf("body"), undefined, "20260101T000000Z"]
const a = await x.signRequestHuawei(...args)
const b = await x.signRequestHuawei(...args)
assert.equal(a.get("Authorization"), b.get("Authorization"))
})
test("signRequestHuawei matches an independent SDK-HMAC-SHA256 implementation", async () => {
// A known answer, from an independent (Python) SDK-HMAC-SHA256: an unsorted
// query, a signed extra header, a URI that needs its trailing slash. Signing
// the wrong hash, dropping the slash or the query order all change it.
const signed = await x.signRequestHuawei(
"AK", "SK", "ST", "POST", "https://example.com/api/v2/chat/completions?b=2&a=1",
buf('{"m":1}'), { maas_type: "benefit" }, "20260101T000000Z",
)
assert.equal(
signed.get("Authorization"),
"SDK-HMAC-SHA256 Access=AK,SignedHeaders=content-type;host;maas_type;x-sdk-content-sha256;x-sdk-date;x-security-token,"
+ "Signature=f33e9f9e8fa23cb4dbac42f858e310657f72cc67179a098e0b3a2fa9a693e161",
)
})
// ---- helpers ---------------------------------------------------------------
test("normalizeModelId strips only a trailing 4-digit date", () => {
assert.equal(x.normalizeModelId("deepseek-v4-flash-0731"), "deepseek-v4-flash")
assert.equal(x.normalizeModelId("glm-5.3-flash"), "glm-5.3-flash")
assert.equal(x.normalizeModelId("GLM-5.2"), "GLM-5.2")
})
test("upstreamModelId drops the host's provider prefix only", () => {
assert.equal(x.upstreamModelId("codearts/deepseek-v4.1-flash"), "deepseek-v4.1-flash")
assert.equal(x.upstreamModelId("GLM-5.2"), "GLM-5.2")
assert.equal(x.upstreamModelId("other/GLM-5.2"), "other/GLM-5.2")
})
test("parseModelInfo drops vision models, dedupes, and fills context", () => {
const seen = new Set()
assert.equal(x.parseModelInfo({ model_id: "Qwen3-VL-235B", model_name: "Qwen3-VL-235B" }, seen), undefined)
assert.equal(x.parseModelInfo({ model_id: "kimi-k2.6-vl" }, seen), undefined)
const a = x.parseModelInfo({ model_id: "GLM-5.2", model_name: "GLM-5.2" }, seen)
assert.deepEqual(a, { id: "GLM-5.2", name: "GLM-5.2", context: 202752 })
assert.equal(x.parseModelInfo({ model_id: "GLM-5.2", model_name: "GLM-5.2" }, seen), undefined)
})
test("parseModelInfo keeps the dated id, and its bare form as another model", () => {
const seen = new Set()
const dated = x.parseModelInfo({ model_id: "deepseek-v4-flash-0731", model_name: "deepseek-v4-flash-0731", max_tokens: 131072 }, seen)
assert.deepEqual(dated, { id: "deepseek-v4-flash-0731", name: "deepseek-v4-flash-0731", context: 1048576, output: x.MAX_OUTPUT_TOKENS })
const bare = x.parseModelInfo({ model_id: "deepseek-v4-flash" }, seen)
assert.equal(bare.id, "deepseek-v4-flash")
assert.notEqual(bare.name, dated.name)
})
// #677 (errorcode7): /v1/model/builtin lists deepseek-v4.1-flash and
// deepseek-v4.1-flash-1017 side by side, two models with other off-peak
// rates. Each keeps the name the vendor gives it.
test("a dated builtin model keeps its own name beside its bare form (#677)", async () => {
const builtin = {
builtinModels: [
{ model_id: "deepseek-v4.1-flash", model_name: "DeepSeek-V4.1-Flash", model_desc: "【限时体验】能力更高, 速度更快" },
{ model_id: "deepseek-v4.1-flash-1017", model_name: "DeepSeek-V4.1-Flash-1017", model_desc: "【限时体验】许愿式编程一键成真" },
],
}
const fetcher = async (url) => String(url).includes("opengw")
? new Response(JSON.stringify({ result: { models: [] } }), { status: 200 })
: new Response(JSON.stringify(builtin), { status: 200 })
const models = await x.fetchRemoteModels(signedCred, fetcher)
assert.deepEqual(models.map((m) => [m.id, m.name]), [
["deepseek-v4.1-flash", "DeepSeek-V4.1-Flash"],
["deepseek-v4.1-flash-1017", "DeepSeek-V4.1-Flash-1017"],
])
})
test("a dated model only the agent lists keeps its date, named or not (#677)", async () => {
const detail = {
gpts: {
models: [
{ model_name: "DeepSeek-V4.1-Flash-1017", model_parameters: { model_id: "deepseek-v4.1-flash-1017" }, credit: [{ ratio: 0.0486, ratio_display: "0.18" }] },
{ model_parameters: { model_id: "deepseek-v4.1-flash-0930" } },
],
},
}
const models = await x.fetchRemoteModels(signedCred, modelsFetcher([], { agents: agentList, detail }))
const names = Object.fromEntries(models.map((m) => [m.id, m.name]))
assert.equal(names["deepseek-v4.1-flash-1017"], "DeepSeek-V4.1-Flash-1017")
assert.equal(names["deepseek-v4.1-flash-0930"], "Deepseek V4.1 Flash 0930")
})
test("stop never reaches the mainland gateway, which refuses any (#1120, magpie#6342)", () => {
const stop = (v) => x.prepareChatBody({ model: "GLM-5.2", messages: [], stop: v }).body
for (const v of [["\n\n"], ["", "###", "Observation:"], "###", "x", "</block>", [], [""], [null, 3], "", null, 7])
assert.equal("stop" in stop(v), false, JSON.stringify(v))
assert.equal("stop" in x.prepareChatBody({ model: "GLM-5.2", messages: [] }).body, false)
// the international station takes a list only (#998)
const intl = (v) => x.prepareChatBody({ model: "GLM-5.1", messages: [], stop: v }, { station: "international" }).body
assert.deepEqual(intl("zzz").stop, ["zzz"])
assert.deepEqual(intl(["", "###", 3, "Observation:"]).stop, ["###", "Observation:"])
for (const v of [[], [""], [null, 3], "", null, 7]) assert.equal("stop" in intl(v), false, JSON.stringify(v))
})
test("prepareChatBody reshapes a chat into what the gateway accepts and meters", () => {
const out = x.prepareChatBody({ model: "codearts/GLM-5.2", messages: [], max_tokens: 128000 })
assert.equal(out.fold, true)
assert.deepEqual(out.body, { model: "GLM-5.2", messages: [], max_tokens: x.MAX_OUTPUT_TOKENS, thinking: { type: "enabled" }, stream: true })
const streamed = x.prepareChatBody({ model: "GLM-5.2", messages: [], stream: true, thinking: { type: "disabled" } })
assert.equal(streamed.fold, false)
assert.deepEqual(streamed.body.thinking, { type: "disabled" })
assert.equal(x.prepareChatBody({ model: "GLM-5.2", messages: [] }, { thinking: false }).body.thinking, undefined)
assert.equal(x.prepareChatBody({ model: "GLM-5.2" }), null)
assert.equal(x.prepareChatBody(null), null)
})
// GLM holds a tool call's arguments back until the call is written, and the
// gateway's 60 s idle timeout cuts a long one off; `tool_stream` streams them.
test("a GLM chat with tools asks for its tool arguments streamed", () => {
const tools = [{ type: "function", function: { name: "write_file", parameters: { type: "object", properties: {} } } }]
for (const model of ["glm-5.3-flash", "codearts/glm-5.3", "GLM-5.2", "glm-5.2-sft-harmony"]) {
const out = x.prepareChatBody({ model, messages: [], tools })
assert.equal(out.body.tool_stream, true, model)
assert.equal(out.toolStream, true, model)
}
// nothing to stream: no tools, or an empty list
assert.equal("tool_stream" in x.prepareChatBody({ model: "glm-5.3-flash", messages: [] }).body, false)
assert.equal("tool_stream" in x.prepareChatBody({ model: "glm-5.3-flash", messages: [], tools: [] }).body, false)
// not a GLM: its arguments already stream
const ds = x.prepareChatBody({ model: "deepseek-v4.1-flash-1017", messages: [], tools })
assert.equal("tool_stream" in ds.body, false)
assert.equal(ds.toolStream, false)
// the caller's own word stands
const said = x.prepareChatBody({ model: "glm-5.3-flash", messages: [], tools, tool_stream: false })
assert.equal(said.body.tool_stream, false)
assert.equal(said.toolStream, false)
// the caller's body is never changed
const parsed = { model: "glm-5.3-flash", messages: [], tools }
x.prepareChatBody(parsed)
assert.equal("tool_stream" in parsed, false)
})
// The caller's level is the gateway's own (measured 2026-11-03: none, low,
// medium, high, xhigh and max are accepted, every other value is a 400), and a
// level that was named is passed on as it is: `thinking: enabled` would
// overrule it. "No thinking" is the switch, not the level: `reasoning_effort:
// none` alone still thought (89 to 135 characters of it).
test("the caller's reasoning level is the model's own", () => {
// A level the model takes is passed on as it is: `thinking: enabled` would
// overrule it.
for (const level of ["low", "medium", "high", "xhigh", "max"]) {
const out = x.prepareChatBody({ model: "deepseek-v4.1-flash-1017", messages: [], reasoning_effort: level })
assert.equal(out.body.reasoning_effort, level)
assert.equal(out.body.thinking, undefined, level + " is the level; nothing else is asked")
}
// A host's word for no thinking is the gateway's way of not thinking.
for (const word of ["off", "disabled", "none"]) {
const out = x.prepareChatBody({ model: "deepseek-v4.1-flash-1017", messages: [], reasoning_effort: word })
assert.deepEqual(out.body.thinking, { type: "disabled" }, word + " means no thinking")
assert.equal("reasoning_effort" in out.body, false, "the level would only be a hint")
}
// A level the model does not take would turn the whole request away (a 400),
// so it is dropped and the request goes as the model serves it.
const notTaken = x.prepareChatBody({ model: "glm-5.3-flash", messages: [], reasoning_effort: "medium" })
assert.equal("reasoning_effort" in notTaken.body, false, "glm-5.3-flash takes no medium")
assert.deepEqual(x.prepareChatBody({ model: "glm-5.3-flash", messages: [], reasoning_effort: "high" }).body.reasoning_effort, "high")
// A word no model takes is dropped as well.
assert.equal("reasoning_effort" in x.prepareChatBody({ model: "deepseek-v4.1-flash-1017", messages: [], reasoning_effort: "loud" }).body, false)
// A caller that said nothing still gets the thinking, as before.
assert.deepEqual(x.prepareChatBody({ model: "deepseek-v4.1-flash-1017", messages: [] }).body.thinking, { type: "enabled" })
// A caller that said so itself is not overruled.
assert.deepEqual(x.prepareChatBody({ model: "deepseek-v4.1-flash-1017", messages: [], thinking: { type: "disabled" } }).body.thinking, { type: "disabled" })
})
// The free model's TPM limit, word for word as the gateway sent it in a 200.
const tpmEvent = 'data:{"text":"[DONE]","error_code":"InferHub.ModelArts.81111.429","error_msg":"The model TPM limit has been significantly exceeded. Please reduce the request rate and retry later."}'
test("classifyHead tells an answer from an embedded error", () => {
const role = `data: ${JSON.stringify({ choices: [{ delta: { role: "assistant" } }] })}\n\n`
const content = `data: ${JSON.stringify({ choices: [{ delta: { content: "hi" } }] })}\n\n`
const cap = `data: {"error_code":"TM.00001041","error_msg":"并发会话数已达上限(3个)"}\n\n`
assert.equal(x.classifyHead(role, false), undefined) // a role-only delta decides nothing
assert.equal(x.classifyHead(role + content, false), "answer")
assert.equal(x.classifyHead(role + cap, false), "TM.00001041")
assert.equal(x.classifyHead(`data: {"error_code":"TM.00001041"`, false), undefined) // not whole yet
assert.equal(x.classifyHead("", true), "answer")
assert.equal(x.classifyHead(JSON.stringify({ choices: [{ message: { content: "x" } }] }), true), "answer")
// The free model's TPM limit, as the gateway sends it: no space after
// `data:`, a code of several parts, and a "[DONE]" that is no end.
assert.equal(x.classifyHead(`${tpmEvent}\n\n`, false), "InferHub.ModelArts.81111.429")
assert.equal(x.classifyHead(`data: ${JSON.stringify({ text: "[DONE]" })}\n\n`, false), undefined)
assert.equal(x.classifyHead(role + "data: [DONE]\n\n", false), "answer")
})
test("errorCodeOf / errorMessageOf / isRateLimitCode read the gateway's errors", () => {
const text = '{"error_code":"InferHub.4291.200","error_msg":"insufficient \\"quota\\""}'
assert.equal(x.errorCodeOf(text), "InferHub.4291.200")
assert.equal(x.errorMessageOf(text), 'insufficient "quota"')
for (const code of ["InferHub.ModelArts.81111.429", "TM.00001041", "APIG.0602", "81114.429", "STS5.1806"]) {
assert.equal(x.errorCodeOf(`{"error_code":"${code}"}`), code)
}
assert.equal(x.errorCodeOf('{"code":"build"}'), "", "a word is no code")
assert.equal(x.isRateLimitCode("InferHub.ModelArts.81111.429"), true)
assert.equal(x.isRateLimitCode("InferHub.4291.200"), true)
assert.equal(x.isRateLimitCode("81111.429"), true)
assert.equal(x.isRateLimitCode("InferHub.002002009.404"), false)
assert.equal(x.isStaleCredential('{"error_code":"APIG.0602"}'), true)
assert.equal(x.isStaleCredential('{"error_code":"APIG.0301","error_msg":"verify ak sk signature fail"}'), true)
})
test("accountIdentityOf reads the signer from the refresh token's user_profile", () => {
const b64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url")
const profile = { principal_urn: "iam::d1:user:alice", user_name: "alice" }
const asString = `h.${b64u({ user_profile: JSON.stringify(profile) })}.s`
assert.deepEqual(x.accountIdentityOf({ refresh_token: asString }), { id: "iam::d1:user:alice", name: "alice" })
const asB64 = `h.${b64u({ user_profile: b64u(profile) })}.s`
assert.deepEqual(x.accountIdentityOf({ refresh_token: asB64 }), { id: "iam::d1:user:alice", name: "alice" })
assert.deepEqual(x.accountIdentityOf({ refresh_token: "opaque", user_name: "bob" }), { id: "bob", name: "bob" })
})
// A credential whose refresh token carries the IAM claims a real one does.
function credWithProfile(claims) {
const b64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url")
return {
access_key_id: "AK",
secret_access_key: "SK",
security_token: "ST",
refresh_token: `h.${b64u({ user_profile: JSON.stringify(claims) })}.s`,
}
}
test("maskPhone shows a number a person can tell apart, or nothing", () => {
// Huawei Cloud IAM answers `0086-13800138000`; the other magpie cards show
// `138****8000`.
assert.equal(x.maskPhone("0086-13800138000"), "138****8000")
assert.equal(x.maskPhone("+86 138 0013 8000"), "138****8000")
assert.equal(x.maskPhone("13800138000"), "138****8000")
// Too short to be a number: no name, so the caller falls back.
assert.equal(x.maskPhone(""), "")
assert.equal(x.maskPhone("12345"), "")
assert.equal(x.maskPhone(undefined), "")
})
test("accountIdentityOf names an account by its phone, never by IAM's ids", () => {
const b64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url")
const profile = { principal_urn: "iam::d1:user:hw12323", account_name: "hw12323" }
const token = `h.${b64u({ user_profile: JSON.stringify(profile) })}.s`
// The phone read from IAM stands in front of `hw12323` and of the URN.
assert.deepEqual(x.accountIdentityOf({ refresh_token: token, user_phone: "138****8000" }), {
id: "iam::d1:user:hw12323",
name: "138****8000",
})
// Without one, the account name — while `id` stays the URN magpie keys by.
assert.deepEqual(x.accountIdentityOf({ refresh_token: token }), { id: "iam::d1:user:hw12323", name: "hw12323" })
})
test("accountIdentityOf never makes an IAM id the account's name", () => {
const b64u = (o) => Buffer.from(JSON.stringify(o)).toString("base64url")
const urn = "iam::d1:user:hw123456789012345"
// The claim names the signer only by its IAM ids. With no phone read there is
// no name to show: `id` keeps the URN, `name` is empty (the host falls back
// to the provider's name) — never the URN.
for (const profile of [
{ principal_urn: urn, user_name: urn, account_name: urn, domain_name: urn },
{ principal_urn: urn, user_name: "hw123456789012345" },
]) {
const token = `h.${b64u({ user_profile: JSON.stringify(profile) })}.s`
assert.deepEqual(x.accountIdentityOf({ refresh_token: token }), { id: urn, name: "" })
}
// A credential without a `user_profile` is the same: `id` is the URN, and
// `user_name` is not a name.
assert.deepEqual(x.accountIdentityOf({ refresh_token: "opaque", user_name: urn }), { id: urn, name: "" })
})
test("looksLikeIdentifier spots the shapes IAM writes, and leaves names alone", () => {
for (const id of [
"iam::d1:user:hw123456789012345",
"urn:ietf:params:oauth:jwt",
"0123456789abcdef0123456789abcdef",
"123e4567-e89b-12d3-a456-426614174000",
"hw123456789012345",
]) {
assert.equal(x.looksLikeIdentifier(id), true, id)
}
for (const name of ["alice", "138****8000", "a@b.com", "", "hw123"]) {
assert.equal(x.looksLikeIdentifier(name), false, name)
}
})
test("fetchAccountPhone reads IAM with the account's own credentials, and only once", async () => {
const seen = []
const cred = credWithProfile({ principal_id: "uid-1" })
const fetcher = async (url, init) => {
seen.push([String(url), new Headers(init.headers).get("authorization")])
return new Response(JSON.stringify({ user: { name: "hw12323", phone: "0086-13800138000" } }), { status: 200 })
}
assert.equal(await x.fetchAccountPhone(cred, fetcher), "138****8000")
assert.equal(seen.length, 1)
assert.equal(seen[0][0], "https://iam.cn-north-4.myhuaweicloud.com/v3.0/OS-USER/users/uid-1")
assert.ok(String(seen[0][1]).startsWith("SDK-HMAC-SHA256 "), "signed, like every other call of the account")
// The number does not change: the second read is free.
assert.equal(await x.fetchAccountPhone(cred, fetcher), "138****8000")
assert.equal(seen.length, 1)
})
test('fetchAccountPhone is best effort — no claim, a refusal, or no number gives ""', async () => {
// No `principal_id` in the token: IAM is never called.
const unreadable = { access_key_id: "AK", secret_access_key: "SK", security_token: "ST", refresh_token: "R" }
assert.equal(await x.fetchAccountPhone(unreadable, async () => { throw new Error("must not be called") }), "")
const cred = credWithProfile({ principal_id: "uid-2" })
assert.equal(await x.fetchAccountPhone(cred, async () => new Response("{}", { status: 403 })), "")
assert.equal(
await x.fetchAccountPhone(cred, async () => new Response(JSON.stringify({ user: { name: "hw12323" } }), { status: 200 })),
"",
)
})
test("usage names an account by the phone its credential carries", async () => {
const cred = { ...(await makeCred()), user_phone: "138****8000" }
const plugin = await CodeArtsAuthPlugin({ client: {} }, {
fetch: async () => new Response(JSON.stringify({ metrics: [
{ name: "usageTotalPackageCredit", package_credit_amount: 500, package_credit_remain: 500 },
] }), { status: 200 }),
ledgerPath: path.join(ledgerDir, "unused.json"),
})
const usage = await plugin.auth.usage(async () => makeAuth(cred))
assert.equal(usage.user, "138****8000")
assert.equal(usage.windows.length > 0, true, "the phone must not replace the windows")
})
test("a renewal keeps the account's name and its uid, with the phone in the credential", async () => {
const saved = []
const client = { auth: { set: async ({ body }) => { saved.push(body) } } }
const cred = {
...(await makeCred()),
user_phone: "138****8000",
refresh_token: credWithProfile({ principal_urn: "iam::d:user:hw123" }).refresh_token,
}
const account = await x.persistCredential(client, { accountId: "iam::d:user:hw123", uid: "iam::d:user:hw123" }, cred)
assert.equal(saved.length, 1)
// accountId is the identity: it must not be renamed (magpie keys the user's
// own settings by it). The phone lives in the credential and is shown by usage.
assert.equal(saved[0].accountId, "iam::d:user:hw123")
assert.equal(saved[0].uid, "iam::d:user:hw123")
assert.equal(JSON.parse(saved[0].access).user_phone, "138****8000")
assert.equal(account.accountId, "iam::d:user:hw123")
})
test("accountSessionIds is stable per account and differs between accounts", async () => {
const a = await x.accountSessionIds({ session_id: "s1", access_key_id: "AK1" })
assert.deepEqual(await x.accountSessionIds({ session_id: "s1", access_key_id: "AK2" }), a)
assert.notDeepEqual(await x.accountSessionIds({ session_id: "s2", access_key_id: "AK1" }), a)
assert.match(a.sessionId, /^[0-9a-f]{32}$/)
assert.match(a.chatId, /^[0-9a-f]{32}$/)
})
test("createConcurrencyGate caps permits, admits in order, and honours abort", async () => {
const gate = x.createConcurrencyGate(2)
const r1 = await gate.acquire()
const r2 = await gate.acquire()
let third = false
const p3 = gate.acquire().then((r) => { third = true; return r })
const ctl = new AbortController()
const p4 = gate.acquire(ctl.signal)
await new Promise((r) => setTimeout(r, 5))
assert.equal(third, false)
assert.equal(gate.waiting, 2)
ctl.abort()
await assert.rejects(p4, { name: "AbortError" })
r1()
r1() // a second release is a no-op
const r3 = await p3
assert.equal(gate.active, 2)
r2()
r3()
assert.equal(gate.active, 0)
})
test("credentialOf round-trips a credential stored in the access field", async () => {
const keyPair = await x.generateDpopKeyPair()
const cred = x.credentialFromTokenResponse(
{ credentials: { access_key_id: "AK", secret_access_key: "SK", security_token: "ST", expiration: "2030-01-01T00:00:00Z" }, refresh_token: "R" },
"verifier",
keyPair,
)
const auth = { type: "oauth", access: JSON.stringify(cred), refresh: "R" }
const back = x.credentialOf(auth)
assert.equal(back.access_key_id, "AK")
assert.equal(back.refresh_token, "R")
assert.equal(back.code_verifier, "verifier")
assert.deepEqual(back.dpop_private_key_jwk, keyPair.privateKeyJwk)
assert.equal(x.credentialOf({ type: "api", key: "k" }), null)
})
test("expiresFromCredential parses the STS expiration or falls back to +1d", () => {
assert.equal(x.expiresFromCredential({ expires_at: "2030-01-01T00:00:00Z" }), Date.parse("2030-01-01T00:00:00Z"))
const soon = x.expiresFromCredential({})
assert.ok(soon > Date.now() + 86_000_000 && soon <= Date.now() + 86_400_000)
})
test("buildOAuthLoginUrl matches the real IDE parameters", () => {
const url = new URL(x.buildOAuthLoginUrl(12345, { codeChallenge: "CH" }, "TICKET"))
assert.equal(url.origin + url.pathname, "https://codearts.huaweicloud.com/portal/authorize")
const q = url.searchParams
assert.equal(q.get("client_id"), "codearts-agent")
assert.equal(q.get("uri_scheme"), "codearts-agent")
assert.equal(q.get("port"), "12345")
assert.equal(q.get("code_challenge"), "CH")
assert.equal(q.get("code_challenge_method"), "SHA-256")
assert.equal(q.get("ticket_id"), "TICKET")
assert.equal(q.get("plugin-name"), "snap_AIIDE")
// The real plugin never sends auth_callback_url (portal derives it from port).
assert.equal(q.has("auth_callback_url"), false)
assert.equal(q.get("locale"), "zh-cn")
})
test("the international sign-in opens Huawei Cloud's international login, then its portal (#1090)", () => {
const login = new URL(x.buildOAuthLoginUrl(12345, { codeChallenge: "CH" }, "TICKET", x.STATIONS.international))
assert.equal(login.origin + login.pathname, "https://auth.huaweicloud.com/authui/login")
assert.equal(login.searchParams.get("site"), "intl")
assert.equal(login.searchParams.get("locale"), "en-us")
const service = new URL(login.searchParams.get("service"))
assert.equal(service.origin + service.pathname, "https://codearts.ap-southeast-1.huaweicloud.com/portal/authorize")
assert.equal(service.searchParams.get("locale"), "en-us")
assert.equal(service.searchParams.get("port"), "12345")
assert.equal(service.searchParams.get("code_challenge"), "CH")
assert.equal(service.searchParams.get("ticket_id"), "TICKET")
assert.equal(service.searchParams.get("client_id"), "codearts-agent")
assert.equal(
x.buildPortalLoginResultUrl(true, x.STATIONS.international),
"https://codearts.ap-southeast-1.huaweicloud.com/portal/login?login_succeed=true&uri_scheme=codearts-agent&locale=en-us",
)
assert.equal(
x.buildPortalLoginResultUrl(true),
"https://codearts.huaweicloud.com/portal/login?login_succeed=true&uri_scheme=codearts-agent&locale=zh-cn",
)
})
test("usageFromStatistics maps credit metrics to windows with real numbers", () => {
const usage = x.usageFromStatistics({
package: { package_name_cn: "企业版" },
metrics: [
{ name: "usageTotalPackageCredit", package_credit_amount: 1000, package_credit_remain: 250, package_credit_used: 750 },
{ name: "usageBasicPackageCredit", package_credit_amount: 1000, package_credit_remain: 250, package_credit_used: 750 },
{ name: "usageOnDemandPackageCredit", package_credit_amount: 20000, package_credit_remain: 20000 },
],
})
assert.equal(usage.plan, "企业版")
assert.equal(usage.signIn, "kept")
// The package total is listed first, then the buckets, all with display
// numbers; only the total may pause the account, the buckets are aside.
assert.deepEqual(usage.windows, [
{ name: "总积分", used: 75, display: "750 / 1000", amount: 750, limit: 1000, unit: "credits" },
{ name: "基础积分包", used: 75, display: "750 / 1000", amount: 750, limit: 1000, unit: "credits", aside: true },
{ name: "按需积分包", used: 0, display: "0 / 2.0万", amount: 0, limit: 20000, unit: "credits", aside: true },
])
})
test("usageFromStatistics adds the free daily pool as an aside window for the free models", () => {
const usage = x.usageFromStatistics(
{ metrics: [{ name: "usageTotalPackageCredit", package_credit_amount: 1000, package_credit_remain: 1000 }] },
{ result: { daily_token_limit: 10_000_000, daily_tokens_used: 2_500_000 } },
)
const free = usage.windows.find((w) => w.name === "免费额度")
assert.equal(free.used, 25)
assert.equal(free.display, "250.0万 / 1000.0万")
assert.equal(free.unit, "tokens")
assert.equal(free.aside, true)
assert.ok(free.models.includes("glm-5.3-flash"))
assert.equal(x.benefitWindow({ result: {} }), undefined)
})
test("usageFromStatistics: the monthly buckets reset at end_date, expiring credits are said", () => {
const usage = x.usageFromStatistics({
end_date: "2026-11-01",
metrics: [
{ name: "usageTotalPackageCredit", package_credit_amount: 6500, package_credit_remain: 6000 },
{ name: "usageBasicPackageCredit", package_credit_amount: 500, package_credit_remain: 0 },
{ name: "usageBonusPackageCredit", package_credit_amount: 6000, package_credit_remain: 6000, package_credit_expiring_amount: 1000 },
],
})
const [total, basic, bonus] = usage.windows
const reset = new Date(Date.parse("2026-10-31T16:00:00Z")).toISOString()
assert.equal(total.resetsAt, reset)
assert.equal(basic.resetsAt, reset)
assert.equal(bonus.resetsAt, undefined, "given credits don't come back at the month's end")
assert.equal(bonus.display, "0 / 6000 · 1000 即将过期")
})
test("usageFromStatistics: the soonest check-in credits to lapse show on the bonus bucket", () => {
const now = Date.now()
const day = 86_400_000
const grants = [
{ at: new Date(now - 40 * day).toISOString(), credit: 1000, expiresAt: new Date(now - 10 * day).toISOString() }, // gone
{ at: new Date(now - 25 * day).toISOString(), credit: 1000, expiresAt: new Date(now + 5 * day).toISOString() },
{ at: new Date(now - 2 * day).toISOString(), credit: 1000, expiresAt: new Date(now + 28 * day).toISOString() },
]
const usage = x.usageFromStatistics({
metrics: [
{ name: "usageTotalPackageCredit", package_credit_amount: 7000, package_credit_remain: 6500 },
{ name: "usageBonusPackageCredit", package_credit_amount: 2000, package_credit_remain: 1500, package_credit_expiring_amount: 1000 },
],
}, undefined, { grants })
const bonus = usage.windows.find((w) => w.name === "赠送积分包")
assert.equal(bonus.runsOutAt, grants[1].expiresAt)
assert.equal(bonus.runsOut, 1000)
// The total loses them too.
assert.equal(usage.windows.find((w) => w.name === "总积分").runsOutAt, grants[1].expiresAt)
assert.equal(x.soonestLapse(x.grantBatches([grants[0]])), undefined)
})
// #982 (KiMelody), two accounts read 2026-11-11 in Beijing, the numbers as
// filed. B's ledger grant is the last check-in to the millisecond; the vendor
// said nothing is about to lapse on either.
const NOW_982 = Date.parse("2026-11-11T10:00:00Z")
const GRANT_982 = { at: "2026-11-10T16:01:04.916Z", credit: 100, expiresAt: "2026-11-11T16:01:03.812Z" }
test("a spent check-in leaves no lapse on the bucket or the total (#982, account A)", () => {
const stats = {
metrics: [
{ name: "usageTotalPackageCredit", package_credit_amount: 600, package_credit_remain: 82.05, package_credit_expiring_amount: 0 },
{ name: "usageBasicPackageCredit", package_credit_amount: 500, package_credit_remain: 82.05, package_credit_expiring_amount: 0 },
{ name: "usageBonusPackageCredit", package_credit_amount: 100, package_credit_remain: 0, package_credit_expiring_amount: 0 },
],
}
// The ledger's grant, and a vendor batch whose counter lags the bucket.
const ghost = [{ metric: "usageBonusPackageCredit", amount: 100, left: 100, expiresAt: Date.parse(GRANT_982.expiresAt) }]
for (const opts of [{ grants: [GRANT_982] }, { batches: ghost }]) {
const usage = x.usageFromStatistics(stats, undefined, { ...opts, now: NOW_982 })
const total = usage.windows.find((w) => w.name === "总积分")
const bonus = usage.windows.find((w) => w.name === "赠送积分包")
assert.equal(bonus.amount, 100)
assert.equal(bonus.runsOutAt, undefined)
assert.equal(total.runsOutAt, undefined, "the total has none of the bonus bucket's credits left to lose")
assert.equal(total.runsOut, undefined)
assert.equal(total.expiring, 0)
}
})
test("a check-in in the ledger is no lapse when the vendor says nothing expires (#982, account B)", () => {
const stats = (expiring) => ({
metrics: [
{ name: "usageTotalPackageCredit", package_credit_amount: 4100, package_credit_remain: 2344.81, package_credit_expiring_amount: expiring },
{ name: "usageBonusPackageCredit", package_credit_amount: 4100, package_credit_remain: 2344.81, package_credit_expiring_amount: expiring },
],
})
const read = (expiring) => {
const usage = x.usageFromStatistics(stats(expiring), undefined, { grants: [GRANT_982], now: NOW_982 })
return [usage.windows.find((w) => w.name === "总积分"), usage.windows.find((w) => w.name === "赠送积分包")]
}
const [total, bonus] = read(0)
assert.equal(bonus.amount, 1755.19)
assert.equal(bonus.used.toFixed(2), "42.81")
assert.equal(bonus.expiring, 0)
assert.equal(bonus.runsOutAt, undefined, "the ledger can't say the grant wasn't spent")
assert.equal(total.runsOutAt, undefined)
// Said by the vendor, the ledger tells when, and only that much lapses.
const [total2, bonus2] = read(40)
assert.equal(bonus2.runsOutAt, GRANT_982.expiresAt)
assert.equal(bonus2.runsOut, 40)
assert.equal(total2.runsOutAt, GRANT_982.expiresAt)
assert.equal(total2.runsOut, 40)
// Without the vendor's field nothing is known.
assert.equal(read(undefined)[1].runsOutAt, undefined)
assert.equal(x.grantBatches([GRANT_982])[0].estimated, true)
})
test("the total's lapse is the buckets' own, each held to what it has left (#982)", () => {
const at = NOW_982 + 3 * 86_400_000
const usage = x.usageFromStatistics({
metrics: [
{ name: "usageTotalPackageCredit", package_credit_amount: 3000, package_credit_remain: 2500 },
{ name: "usageOnDemandPackageCredit", package_credit_amount: 2000, package_credit_remain: 2000 },
{ name: "usageBonusPackageCredit", package_credit_amount: 1000, package_credit_remain: 30 },
],
}, undefined, {
now: NOW_982,
batches: [
{ metric: "usageBonusPackageCredit", amount: 1000, left: 400, expiresAt: at },
{ metric: "usageOnDemandPackageCredit", amount: 2000, left: 2000, expiresAt: at + 60 * 86_400_000 },
],
})
const bonus = usage.windows.find((w) => w.name === "赠送积分包")
const total = usage.windows.find((w) => w.name === "总积分")
assert.equal(bonus.runsOut, 30, "never more than the bucket has")
assert.equal(total.runsOutAt, iso(at))
assert.equal(total.runsOut, 30)
})
// Shaped as the console's own answers (personal-usage → 获取明细).
const day = 86_400_000
const iso = (ms) => new Date(ms).toISOString()
function creditFetcher(now = Date.now()) {
const planEnd = now + 31 * day
// Noon in Beijing, so the check-in a minute later is the same Beijing day
// whatever the wall clock (#322).
const signUp = Math.floor((now + 30 * day + 8 * 3600_000) / day) * day + 4 * 3600_000
const checkin = signUp + 52_000
const ok = (data) => new Response(JSON.stringify({ code: 0, message: "ok", data }), { status: 200 })
const fetcher = async (url, init) => {
const u = String(url)
const body = init?.body ? JSON.parse(new TextDecoder().decode(init.body)) : undefined
if (u === x.PACKAGE_CREDIT_PAGE_URL) {
const list = body.packageTypes.includes("basic")
? [{ packageType: "basic", creditAmount: 500.0, creditUsed: 0.0, validityPeriod: "31", expiredTime: iso(planEnd).replace("Z", "+00:00"), status: 1 }]
: []
return new Response(JSON.stringify({ list, total: list.length, pageNum: 1, pageSize: 100 }), { status: 200 })
}
if (u === x.OPS_CREDIT_OVERVIEW_URL) {
return ok({ items: [
{ campaignId: 4, campaignTitle: "新用户注册送 4000 积分", totalClaimed: 4000, totalConsumed: 0, totalExpired: 0 },
{ campaignId: 1, campaignTitle: "每日签到领1000积分", totalClaimed: 1000, totalConsumed: 0, totalExpired: 0 },
{ campaignId: 9, campaignTitle: "用完了", totalClaimed: 1000, totalConsumed: 1000, totalExpired: 0 },
] })
}
if (u === x.OPS_CREDIT_CAMPAIGN_URL(4)) {
return ok({ campaignId: 4, benefits: [{ status: "CONFIRMED", claimedAmount: 4000, consumedAmount: 0, expiredAmount: 0, claimedAt: iso(signUp - 30 * day), expireAt: iso(signUp) }] })
}
if (u === x.OPS_CREDIT_CAMPAIGN_URL(1)) {
return ok({ campaignId: 1, expirePolicy: { strategy: "DURATION", duration: 30, durationUnit: "DAYS" }, benefits: [{ status: "CONFIRMED", claimedAmount: 1000, consumedAmount: 0, expiredAmount: 0, claimedAt: iso(checkin - 30 * day), expireAt: iso(checkin) }] })
}
throw new Error(`unexpected ${u}`)
}
return { fetcher, planEnd, signUp, checkin }
}
test("the credit fixture's check-in is its sign-up's Beijing day at any hour (#322)", () => {
const bj = (ms) => new Date(ms + 8 * 3600_000).toISOString().slice(0, 10)
const midnight = Date.parse("2026-10-24T16:00:00Z") // 00:00 in Beijing
for (const now of [midnight - 30_000, midnight - 1, midnight, midnight + 12 * 3600_000]) {
const { signUp, checkin, planEnd } = creditFetcher(now)
assert.equal(bj(checkin), bj(signUp))
assert.ok(signUp > now && checkin < planEnd)
}
})
test("fetchCreditBatches reads every batch with its own expiry, signed", async () => {
const { fetcher, planEnd, signUp, checkin } = creditFetcher()
const seen = []
const batches = await x.fetchCreditBatches({ access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, async (url, init) => {
seen.push([init.method, String(url), new Headers(init.headers).get("authorization")])
return fetcher(url, init)
})
assert.deepEqual(batches, [
{ metric: "usageBasicPackageCredit", amount: 500, left: 500, expiresAt: planEnd },
{ metric: "usageBonusPackageCredit", amount: 4000, left: 4000, expiresAt: signUp },
{ metric: "usageBonusPackageCredit", amount: 1000, left: 1000, expiresAt: checkin },
])
// A spent campaign is not asked for its grants.
assert.equal(seen.some((s) => s[1] === x.OPS_CREDIT_CAMPAIGN_URL(9)), false)
assert.ok(seen.every((s) => String(s[2]).startsWith("SDK-HMAC-SHA256 ")))
// Nothing reached: no batches, so the caller falls back.
assert.equal(await x.fetchCreditBatches({ access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, async () => new Response("", { status: 401 })), undefined)
})
test("usage with the vendor's batches: the plan's end is the reset, the grants' the lapse", async () => {
const cred = await makeCred()
const { fetcher: credit, planEnd, signUp } = creditFetcher()
const fetcher = async (url, init) => {
if (String(url).endsWith("/snap-manager/v1/statistics/plugin")) {
return new Response(JSON.stringify({
end_date: "2099-01-01",
metrics: [
{ name: "usageTotalPackageCredit", package_credit_amount: 5500, package_credit_remain: 5500 },
{ name: "usageBasicPackageCredit", package_credit_amount: 500, package_credit_remain: 500 },
{ name: "usageBonusPackageCredit", package_credit_amount: 5000, package_credit_remain: 5000 },
],
}), { status: 200 })
}
if (String(url) === x.BENEFIT_BALANCE_URL) return new Response("", { status: 404 })
return credit(url, init)
}
const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher, ledgerPath: path.join(ledgerDir, "unused.json") })
const usage = await plugin.auth.usage(async () => makeAuth(cred))
const [total, basic, bonus] = usage.windows
// To the second, from the plan's batch, not end_date's day.
assert.equal(total.resetsAt, iso(planEnd))
assert.equal(basic.resetsAt, iso(planEnd))
assert.equal(basic.runsOutAt, undefined, "the plan's credits come back, they don't lapse")
// The sign-up grant and that day's check-in lapse together.
assert.equal(bonus.runsOutAt, iso(signUp))
assert.equal(bonus.runsOut, 5000)
assert.equal(total.runsOutAt, iso(signUp))
assert.equal(total.runsOut, 5000)
})
test("the free pool window comes back at the next Beijing midnight", () => {
const w = x.benefitWindow({ result: { daily_token_limit: 100, daily_tokens_used: 10 } })
const at = Date.parse(w.resetsAt)
assert.ok(at > Date.now() && at - Date.now() <= 86_400_000)
assert.equal(new Date(at + 8 * 3600 * 1000).toISOString().slice(11, 19), "00:00:00")
})
test("usageFromStatistics reports no credit plan when every bucket is empty", () => {
const usage = x.usageFromStatistics({
metrics: [{ name: "usageTotalPackageCredit", package_credit_amount: 0, package_credit_remain: 0 }],
})
assert.deepEqual(usage.windows, [])
assert.equal(usage.error, "该账号无积分额度")
})
test("usageFromStatistics surfaces a business error code", () => {
const usage = x.usageFromStatistics({ code: 500, message: "boom" })
assert.equal(usage.error, "boom")
})
test("toBytes normalizes strings and views", async () => {
assert.deepEqual(await x.toBytes("hi"), buf("hi"))
assert.deepEqual(await x.toBytes(buf("hi")), buf("hi"))
assert.equal((await x.toBytes(null)).length, 0)
})
test("isBenefitModel honours the static fallback and the host's prefix", () => {
assert.equal(x.isBenefitModel("glm-5.3-flash"), true)
assert.equal(x.isBenefitModel("codearts/glm-5.3-flash"), true)
assert.equal(x.isBenefitModel("deepseek-v4-flash-0731"), true)
// The bare id is a different, paid model.
assert.equal(x.isBenefitModel("deepseek-v4-flash"), false)
assert.equal(x.isBenefitModel("GLM-5.2"), false)
})
test("isBenefitModel / isRegularModel read the account's own lists once it has them", () => {
const state = { benefit: new Set(["glm-5.3-flash"]), regular: new Set(["GLM-5.2"]), noBenefit: new Set() }
assert.equal(x.isBenefitModel("deepseek-v4.1-flash", state), false, "the fallback no longer stands")
assert.equal(x.isBenefitModel("glm-5.3-flash", state), true)
state.noBenefit.add("glm-5.3-flash")
assert.equal(x.isBenefitModel("glm-5.3-flash", state), false)
assert.equal(x.isRegularModel("GLM-5.2", state), true)
assert.equal(x.isRegularModel("glm-5.3-flash", state), false)
assert.equal(x.isRegularModel("anything", { regular: null }), true, "not known yet")
})
// ---- remote model list -----------------------------------------------------
const gatewayBody = JSON.stringify({
result: {
models: [
{ model_id: "glm-5.3-flash", model_name: "glm-5.3-flash" },
{ model_id: "deepseek-v4-flash-0731", model_name: "deepseek-v4-flash-0731" },
{ model_id: "Qwen3-VL-235B", model_name: "Qwen3-VL-235B" },
],
},
})
const builtinBody = JSON.stringify({ builtinModels: [{ model_id: "GLM-5.2", model_name: "GLM-5.2" }] })
function modelsFetcher(seen, { claim = "0000", agents, detail } = {}) {
return async (url, init) => {
const u = String(url)
seen.push({ url: u, method: init?.method, auth: new Headers(init?.headers).get("authorization") })
if (u === x.BENEFIT_CLAIM_URL) return new Response(JSON.stringify({ error_code: claim, error_msg: claim === "0000" ? "ok" : "权益不存在" }), { status: 200 })
if (u === x.AGENT_LIST_URL) return new Response(JSON.stringify(agents ?? { total: 0, agents: [] }), { status: 200 })
if (u.startsWith(`${x.AGENT_DETAIL_URL("")}`)) return new Response(JSON.stringify(detail ?? { gpts: { models: [] } }), { status: 200 })
const body = u.includes("opengw") ? gatewayBody : builtinBody
return new Response(body, { status: 200 })
}
}
test("fetchRemoteModels merges both endpoints, filters VL, and keeps the published ids", async () => {
const seen = []
const models = await x.fetchRemoteModels(
{ access_key_id: "AK", secret_access_key: "SK", security_token: "ST" },
modelsFetcher(seen),
)
const ids = models.map((m) => m.id)
assert.deepEqual(ids, ["glm-5.3-flash", "deepseek-v4-flash-0731", "GLM-5.2"])
// Everything gateway/config publishes is a free model.
assert.deepEqual(models.map((m) => m.benefit === true), [true, true, false])
assert.ok(seen.every((s) => String(s.auth).startsWith("SDK-HMAC-SHA256")))
})
test("signedGet returns undefined on a non-2xx response", async () => {
const fetcher = async () => new Response("nope", { status: 401 })
const text = await x.signedGet(x.SNAP_MODEL_BUILTIN_URL, { access_key_id: "AK", secret_access_key: "SK", security_token: "ST" }, fetcher)
assert.equal(text, undefined)
})
// ---- plugin hooks ----------------------------------------------------------
function makeAuth(cred) {
return { type: "oauth", access: JSON.stringify(cred), refresh: cred.refresh_token, expires: x.expiresFromCredential(cred) }
}
async function makeCred() {
const keyPair = await x.generateDpopKeyPair()
return x.credentialFromTokenResponse(
{ credentials: { access_key_id: "AK", secret_access_key: "SK", security_token: "ST", expiration: "2030-01-01T00:00:00Z" }, refresh_token: "R" },
"verifier",
keyPair,
)
}
test("plugin exposes config, provider.models, and an oauth auth method", async () => {
const plugin = await CodeArtsAuthPlugin({ client: {} }, {})
assert.equal(typeof plugin.config, "function")
assert.equal(plugin.provider.id, "codearts")
assert.equal(plugin.auth.provider, "codearts")
assert.ok(plugin.auth.methods.length >= 2)
assert.equal(plugin.auth.methods[0].type, "oauth")
assert.equal(plugin.auth.methods.at(-1).type, "oauth")
assert.equal(typeof plugin.auth.checkin, "function")
assert.equal(plugin.auth.maxConcurrency, x.ACCOUNT_MAX_INFLIGHT)
const config = {}
await plugin.config(config)
const p = config.provider.codearts
assert.equal(p.npm, "@ai-sdk/openai-compatible")
assert.equal(p.api, x.CHAT_API_BASE)
assert.ok(p.models["GLM-5.2"])
assert.equal(p.models["GLM-5"], undefined)
// The output budget is declared; nothing is called free before the
// account's own list says so.
assert.equal(p.models["GLM-5.2"].limit.output, x.MAX_OUTPUT_TOKENS)
assert.equal(p.models["GLM-5.2"].free, undefined)
assert.equal(p.models["glm-5.3-flash"].free, undefined)
})
const CHAT_URL = "https://snap-access.cn-north-4.myhuaweicloud.com/api/v2/chat/completions"
const sse = (...events) => events.map((e) => `data: ${typeof e === "string" ? e : JSON.stringify(e)}\n\n`).join("")
const sseResponse = (text) => new Response(text, { status: 200, headers: { "content-type": "text/event-stream" } })
const chatInit = (body) => ({ method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) })
const okStream = sse(
{ id: "c1", model: "GLM-5.2", choices: [{ index: 0, delta: { role: "assistant" } }] },
{ id: "c1", choices: [{ index: 0, delta: { content: "你好" } }] },
{ id: "c1", choices: [{ index: 0, delta: {}, finish_reason: "stop" }] },
"[DONE]",
)
const fastRetry = { retryDelays: [1], retryBudgetMs: 2_000 }
test("loader signs each chat request with SDK-HMAC-SHA256 and sends it metered", async () => {
const cred = await makeCred()
const seen = []
const fetcher = async (url, init) => {
seen.push({ url: String(url), init })
return sseResponse(okStream)
}
const plugin = await CodeArtsAuthPlugin({ client: {} }, { fetch: fetcher })
const loaded = await plugin.auth.loader(async () => makeAuth(cred))
assert.equal(loaded.baseURL, x.CHAT_API_BASE)
const res = await loaded.fetch(CHAT_URL, chatInit({ model: "codearts/GLM-5.2", messages: [] }))