dsh-zcode-startplan 0.2.0 → 0.5.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,125 @@
1
+ /**
2
+ * 「HTTP 200 里包裹业务错误」的识别。
3
+ *
4
+ * 实测(2026-10-23,本渠道):额度用尽时上游返回
5
+ * `200 + application/json + {"code":1005,"msg":"exceed quota limit"}`。
6
+ *
7
+ * 若把它当成「空响应」处理,会:
8
+ * ① 丢掉真正的错误码,用户只看到误导性的「200 但零内容」;
9
+ * ② 无法据此正确决策(1005 该标号换号;3012 该直接失败不重试)。
10
+ */
11
+
12
+ import test from 'node:test'
13
+ import assert from 'node:assert/strict'
14
+ import { readFileSync } from 'node:fs'
15
+ import { fileURLToPath } from 'node:url'
16
+ import { dirname, join } from 'node:path'
17
+
18
+ import { extractUpstreamError, readContentHead } from '../lib/sse.js'
19
+ import { classifyUpstreamError } from '../lib/errors.js'
20
+ import { ZcodePlanClient } from '../lib/plan-client.js'
21
+
22
+ const here = dirname(fileURLToPath(import.meta.url))
23
+ const fixture = (file) => readFileSync(join(here, 'fixtures', file))
24
+
25
+ test('extractUpstreamError: 200 + {code:1005} 被识别为业务错误', () => {
26
+ const error = extractUpstreamError({ code: 1005, msg: 'exceed quota limit' }, '')
27
+ assert.notEqual(error, undefined)
28
+ assert.match(error.text, /1005/)
29
+ assert.match(error.text, /exceed quota limit/)
30
+ /** 交给错误表后应判成 quota(而不是 other / 无权益)。 */
31
+ assert.equal(classifyUpstreamError(200, error.text), 'quota')
32
+ })
33
+
34
+ test('extractUpstreamError: 3012 风控与 3009 并发同样能从 200 里认出来', () => {
35
+ assert.equal(
36
+ classifyUpstreamError(200, extractUpstreamError({ code: 3012, msg: 'unusual activity' }, '').text),
37
+ 'risk',
38
+ )
39
+ assert.equal(
40
+ classifyUpstreamError(200, extractUpstreamError({ code: 3009, msg: 'concurrency limit' }, '').text),
41
+ 'concurrency',
42
+ )
43
+ })
44
+
45
+ test('extractUpstreamError: 成功码 0 与正常 message 不算错误', () => {
46
+ assert.equal(extractUpstreamError({ code: 0, msg: '' }, ''), undefined)
47
+ assert.equal(extractUpstreamError({ id: 'msg_1', type: 'message', content: [] }, ''), undefined)
48
+ })
49
+
50
+ test('extractUpstreamError: Anthropic 标准错误载荷与裸 error 字段', () => {
51
+ const standard = extractUpstreamError({ type: 'error', error: { type: 'api_error', message: 'boom' } }, '')
52
+ assert.notEqual(standard, undefined)
53
+ assert.match(standard.text, /api_error/)
54
+ const bare = extractUpstreamError({ error: { message: 'boom' } }, '')
55
+ assert.notEqual(bare, undefined)
56
+ })
57
+
58
+ test('readContentHead: 200 + 业务错误的 JSON 不再被当成「零内容」', async () => {
59
+ const body = new ReadableStream({
60
+ start(controller) {
61
+ controller.enqueue(fixture('quota-200.json'))
62
+ controller.close()
63
+ },
64
+ })
65
+ const head = await readContentHead(body, { contentType: 'application/json; charset=utf-8' })
66
+ assert.equal(head.hasContent, false)
67
+ assert.notEqual(head.upstreamError, undefined)
68
+ assert.match(head.upstreamError.text, /1005/)
69
+ })
70
+
71
+ test('plan-client: 200 里的 1005 标记该账号当日用尽并换号(而不是「零内容」)', async () => {
72
+ const quotaBody = () =>
73
+ new ReadableStream({
74
+ start(controller) {
75
+ controller.enqueue(fixture('quota-200.json'))
76
+ controller.close()
77
+ },
78
+ })
79
+ const pool = {
80
+ state: [
81
+ { id: 'acct-a', enabled: true, model_rate_limits: {}, credential: { zcode_jwt: 'jwt-a', device_mid: 'dev-a' } },
82
+ { id: 'acct-b', enabled: true, model_rate_limits: {}, credential: { zcode_jwt: 'jwt-b', device_mid: 'dev-b' } },
83
+ ],
84
+ list() {
85
+ return this.state
86
+ },
87
+ pick(_model, exclude) {
88
+ const hit = this.state.find((entry) => entry.enabled && !(exclude?.has(entry.id) ?? false))
89
+ return hit === undefined ? null : { entry: hit, credential: hit.credential }
90
+ },
91
+ markModelRateLimited(id, model) {
92
+ const hit = this.state.find((entry) => entry.id === id)
93
+ if (hit !== undefined) hit.model_rate_limits[model] = Date.now() + 60_000
94
+ },
95
+ noteError() {},
96
+ }
97
+ const marks = []
98
+ const originalMark = pool.markModelRateLimited.bind(pool)
99
+ pool.markModelRateLimited = (id, model, at) => {
100
+ marks.push({ id, code: 'quota' })
101
+ originalMark(id, model, at)
102
+ }
103
+
104
+ const client = new ZcodePlanClient({
105
+ pool,
106
+ minter: { async mint() { return { param: 'p', interactive: false } }, async fetchConfig() { return undefined } },
107
+ fetchImpl: async () => ({
108
+ ok: true,
109
+ status: 200,
110
+ headers: new Headers({ 'content-type': 'application/json; charset=utf-8' }),
111
+ body: quotaBody(),
112
+ }),
113
+ })
114
+
115
+ await assert.rejects(
116
+ () => client.call({ options: { model: 'GLM-5.3-Flash', messages: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }] } }),
117
+ (error) => {
118
+ assert.equal(error.code, 'QUOTA')
119
+ assert.match(error.message, /1005/)
120
+ return true
121
+ },
122
+ )
123
+ /** 两个账号都被按「额度用尽」标记过(而不是被当成无权益)。 */
124
+ assert.deepEqual(marks.map((mark) => mark.id), ['acct-a', 'acct-b'])
125
+ })
@@ -0,0 +1,250 @@
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { buildZcodeHeaders, nextUtc8DayStartMs, toEpochMs } from '../lib/upstream.js'
5
+ import {
6
+ classifyUpstreamError,
7
+ concurrencyRetryDelayMs,
8
+ describeUpstreamError,
9
+ isZcodeQuotaExhausted,
10
+ } from '../lib/errors.js'
11
+
12
+ test('buildZcodeHeaders: X-Device-Mid 与 anthropic-version 必定下发', () => {
13
+ const headers = buildZcodeHeaders({ device_mid: 'dev-1', app_version: '3.14.3' })
14
+ assert.equal(headers['X-Device-Mid'], 'dev-1')
15
+ assert.equal(headers['anthropic-version'], '2023-06-01')
16
+ assert.equal(headers['User-Agent'], 'ZCode/3.14.3')
17
+ assert.equal(headers['Authorization'], undefined)
18
+ assert.equal(headers['x-aliyun-captcha-verify-param'], undefined)
19
+ })
20
+
21
+ test('buildZcodeHeaders: captcha 与 authorization 只在传入时出现', () => {
22
+ const headers = buildZcodeHeaders(
23
+ { device_mid: 'dev-1' },
24
+ { authorization: 'Bearer jwt', captcha: { param: 'p', region: 'cn' } },
25
+ )
26
+ assert.equal(headers['Authorization'], 'Bearer jwt')
27
+ assert.equal(headers['x-aliyun-captcha-verify-param'], 'p')
28
+ assert.equal(headers['x-aliyun-captcha-verify-region'], 'cn')
29
+ })
30
+
31
+ test('classifyUpstreamError: 3009 是并发限流,不是额度用尽', () => {
32
+ const body = '{"code":3009,"msg":"model concurrency limit exceeded"}'
33
+ assert.equal(classifyUpstreamError(429, body), 'concurrency')
34
+ assert.equal(isZcodeQuotaExhausted(body), false)
35
+ })
36
+
37
+ test('classifyUpstreamError: 1005 / 1113 都算额度用尽', () => {
38
+ assert.equal(classifyUpstreamError(429, '{"code":1005,"msg":"exceed quota limit"}'), 'quota')
39
+ assert.equal(classifyUpstreamError(200, '{"code":1113,"msg":"余额不足"}'), 'quota')
40
+ })
41
+
42
+ test('classifyUpstreamError: 3007 换 captcha,3012 不重试,401 需重新登录', () => {
43
+ assert.equal(classifyUpstreamError(403, '{"code":3007,"msg":"captcha verify failed"}'), 'captcha')
44
+ assert.equal(classifyUpstreamError(403, '{"code":3012,"msg":"request has been blocked due to unusual activity."}'), 'risk')
45
+ assert.equal(classifyUpstreamError(401, ''), 'auth')
46
+ assert.equal(classifyUpstreamError(500, 'boom'), 'other')
47
+ })
48
+
49
+ test('describeUpstreamError: 3012 必须带冷却惩罚告警', () => {
50
+ const text = describeUpstreamError(403, '{"code":3012,"msg":"unusual activity"}')
51
+ assert.match(text, /3012/)
52
+ assert.match(text, /请勿连续重试/)
53
+ })
54
+
55
+ test('concurrencyRetryDelayMs: 线性退避 1500 / 3000', () => {
56
+ assert.equal(concurrencyRetryDelayMs(0), 1500)
57
+ assert.equal(concurrencyRetryDelayMs(1), 3000)
58
+ })
59
+
60
+ test('toEpochMs: 秒级时间戳归一成毫秒(否则刚登录就报超时)', () => {
61
+ assert.equal(toEpochMs(1_790_746_234), 1_790_746_234_000)
62
+ assert.equal(toEpochMs(1_790_746_234_000), 1_790_746_234_000)
63
+ assert.equal(toEpochMs(0), 0)
64
+ })
65
+
66
+ test('nextUtc8DayStartMs: 返回下一个 UTC+8 零点', () => {
67
+ const at = new Date('2026-10-23T12:00:00Z') // = 2026-10-23 20:00 +08
68
+ const next = nextUtc8DayStartMs(at)
69
+ assert.equal(new Date(next).toISOString(), '2026-10-23T16:00:00.000Z')
70
+ })
71
+
72
+ /** fetchBalance 的假 fetch(固定响应)。 */
73
+ function fakeFetch(payload, status = 200) {
74
+ return async () => ({
75
+ ok: status >= 200 && status < 300,
76
+ status,
77
+ json: async () => payload,
78
+ })
79
+ }
80
+
81
+ test('fetchBalance: balances 汇总剩余/总量(现行行为不变)', async () => {
82
+ const { fetchBalance } = await import('../lib/upstream-api.js')
83
+ const balance = await fetchBalance({ zcode_jwt: 'j', device_mid: 'd' }, fakeFetch({
84
+ code: 0,
85
+ data: {
86
+ server_time: 1_793_021_836,
87
+ plans: [],
88
+ balances: [
89
+ { show_name: 'GLM-5.3', unit_type: 'token', total_units: 8_000_000, used_units: 123_956, remaining_units: 7_876_044, available_units: 7_876_044 },
90
+ ],
91
+ },
92
+ }))
93
+ assert.equal(balance.remaining, 7_876_044)
94
+ assert.equal(balance.total, 8_000_000)
95
+ assert.equal(balance.planName, 'GLM-5.3')
96
+ assert.equal(balance.pending, undefined, '无未生效权益时不下发 pending 键')
97
+ })
98
+
99
+ test('fetchBalance: 未生效的 plan entitlement 进 pending(23 点启用 3 亿包实测形状)', async () => {
100
+ const { fetchBalance } = await import('../lib/upstream-api.js')
101
+ // 2026-10-26 21:37 实测响应:balances 为空,额度在 plans[].entitlements 里,
102
+ // effective_at = 1793026800(23:00:00 +08)晚于 server_time。
103
+ const balance = await fetchBalance({ zcode_jwt: 'j', device_mid: 'd' }, fakeFetch({
104
+ code: 0,
105
+ data: {
106
+ server_time: 1_793_021_836,
107
+ plans: [
108
+ {
109
+ plan_id: 'zcode-v3-start-plan-nt-1026',
110
+ name: 'ZCODE GLOBAL BUILD',
111
+ status: 'active',
112
+ starts_at: 1_793_019_869,
113
+ ends_at: 1_793_062_800,
114
+ entitlements: [
115
+ {
116
+ entitlement_id: 'ent-1',
117
+ show_name: 'GLM-5.3-Flash',
118
+ meter: 'model_usage',
119
+ unit_type: 'token',
120
+ capabilities: ['model:glm-5.3-flash'],
121
+ grant_units: 300_000_000,
122
+ period: 'one_time',
123
+ priority: 101,
124
+ effective_at: 1_793_026_800,
125
+ },
126
+ ],
127
+ },
128
+ ],
129
+ balances: [],
130
+ },
131
+ }))
132
+ assert.equal(balance.remaining, 0)
133
+ assert.equal(balance.total, 0)
134
+ assert.equal(balance.pending?.length, 1)
135
+ assert.equal(balance.pending[0].showName, 'GLM-5.3-Flash')
136
+ assert.equal(balance.pending[0].grantUnits, 300_000_000)
137
+ assert.equal(balance.pending[0].effectiveAt, 1_793_026_800_000, '秒级时间戳必须归一成毫秒')
138
+ assert.equal(balance.pending[0].planId, 'zcode-v3-start-plan-nt-1026')
139
+ })
140
+
141
+ test('fetchBalance: 已生效的 entitlement 不进 pending(balances 已覆盖)', async () => {
142
+ const { fetchBalance } = await import('../lib/upstream-api.js')
143
+ const balance = await fetchBalance({ zcode_jwt: 'j', device_mid: 'd' }, fakeFetch({
144
+ code: 0,
145
+ data: {
146
+ server_time: 1_793_026_800, // 恰好等于 effective_at
147
+ plans: [
148
+ {
149
+ plan_id: 'p',
150
+ entitlements: [{ show_name: 'X', grant_units: 100, effective_at: 1_793_026_800 }],
151
+ },
152
+ ],
153
+ balances: [{ show_name: 'X', total_units: 100, remaining_units: 100 }],
154
+ },
155
+ }))
156
+ assert.equal(balance.pending, undefined)
157
+ assert.equal(balance.remaining, 100)
158
+ })
159
+
160
+ test('fetchBalance: grant_units 非正数 / 缺 effective_at 的条目跳过,多条按到点时间排序', async () => {
161
+ const { fetchBalance } = await import('../lib/upstream-api.js')
162
+ const balance = await fetchBalance({ zcode_jwt: 'j', device_mid: 'd' }, fakeFetch({
163
+ code: 0,
164
+ data: {
165
+ server_time: 1_000,
166
+ plans: [
167
+ {
168
+ plan_id: 'p',
169
+ entitlements: [
170
+ { show_name: 'later', grant_units: 50, effective_at: 3_000 },
171
+ { show_name: 'zero', grant_units: 0, effective_at: 2_000 },
172
+ { show_name: 'no-time', grant_units: 70 },
173
+ { show_name: 'earlier', grant_units: 10, effective_at: 2_000 },
174
+ ],
175
+ },
176
+ ],
177
+ balances: [],
178
+ },
179
+ }))
180
+ assert.equal(balance.pending?.length, 2, '零额度与缺时间的要跳过')
181
+ assert.deepEqual(balance.pending.map((item) => item.showName), ['earlier', 'later'])
182
+ })
183
+
184
+ test('fetchBalance: 企业版形态不变(不解析 pending)', async () => {
185
+ const { fetchBalance } = await import('../lib/upstream-api.js')
186
+ const balance = await fetchBalance({ zcode_jwt: 'j', device_mid: 'd' }, fakeFetch({
187
+ code: 0,
188
+ data: { displayMode: 'enterprise', plans: [{ entitlements: [{ grant_units: 5, effective_at: 9_999 }] }] },
189
+ }))
190
+ assert.equal(balance.enterprise, true)
191
+ assert.equal(balance.pending, undefined)
192
+ })
193
+
194
+ test('fetchBalance: expires_at 秒级归一成毫秒,且只汇总还有余额的桶', async () => {
195
+ const { fetchBalance } = await import('../lib/upstream-api.js')
196
+ // 2026-10-26 实测:两个桶的 expires_at 都是 1793030399(当天 23:59:59 +08)
197
+ const balance = await fetchBalance({ zcode_jwt: 'j', device_mid: 'd' }, fakeFetch({
198
+ code: 0,
199
+ data: {
200
+ server_time: 1_793_022_000,
201
+ plans: [],
202
+ balances: [
203
+ { show_name: 'GLM-5.3', total_units: 3_000_000, used_units: 0, remaining_units: 3_000_000, available_units: 3_000_000, expires_at: 1_793_030_399 },
204
+ { show_name: 'GLM-5.3-Flash', total_units: 5_000_000, used_units: 5_000_000, remaining_units: 0, available_units: 0, expires_at: 1_800_000_000 },
205
+ ],
206
+ },
207
+ }))
208
+ assert.equal(balance.expiresAt, 1_793_030_399_000, '秒级必须归一成毫秒(否则界面显示 1970)')
209
+ /**
210
+ * 已用光的 Flash 桶(expires_at 更晚)不能参与顶层汇总 —— 否则会给出
211
+ * 「一个空桶的到期时间」,误导用户以为还有额度。
212
+ */
213
+ assert.notEqual(balance.expiresAt, 1_800_000_000_000)
214
+ assert.equal(balance.buckets[1].expiresAt, 1_800_000_000_000, '每个桶仍保留自己的到期时间')
215
+ })
216
+
217
+ test('fetchBalance: 所有桶都用光时不给顶层 expiresAt', async () => {
218
+ const { fetchBalance } = await import('../lib/upstream-api.js')
219
+ const balance = await fetchBalance({ zcode_jwt: 'j', device_mid: 'd' }, fakeFetch({
220
+ code: 0,
221
+ data: {
222
+ server_time: 1_793_022_000,
223
+ plans: [],
224
+ balances: [
225
+ { show_name: 'X', total_units: 100, used_units: 100, remaining_units: 0, available_units: 0, expires_at: 1_793_030_399 },
226
+ ],
227
+ },
228
+ }))
229
+ assert.equal(balance.expiresAt, undefined)
230
+ assert.equal(balance.remaining, 0)
231
+ })
232
+
233
+ test('fetchBalance: 未生效权益带上 plan 的 ends_at 作为到期时间', async () => {
234
+ const { fetchBalance } = await import('../lib/upstream-api.js')
235
+ const balance = await fetchBalance({ zcode_jwt: 'j', device_mid: 'd' }, fakeFetch({
236
+ code: 0,
237
+ data: {
238
+ server_time: 1_793_021_836,
239
+ plans: [
240
+ {
241
+ plan_id: 'p1',
242
+ ends_at: 1_793_062_800,
243
+ entitlements: [{ show_name: 'GLM-5.3-Flash', grant_units: 300_000_000, effective_at: 1_793_026_800 }],
244
+ },
245
+ ],
246
+ balances: [],
247
+ },
248
+ }))
249
+ assert.equal(balance.pending[0].expiresAt, 1_793_062_800_000)
250
+ })