dsh-zcode-startplan 0.5.2 → 1.0.3

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.
Files changed (51) hide show
  1. package/CHANGELOG.md +1963 -672
  2. package/README.md +92 -472
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -1002
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +109 -11
  7. package/lib/adapter.js +476 -449
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -542
  10. package/lib/auto-claim.js +229 -0
  11. package/lib/captcha/minter.js +61 -7
  12. package/lib/distribution-keys.js +202 -0
  13. package/lib/errors.js +281 -125
  14. package/lib/fallback.js +120 -0
  15. package/lib/local-endpoint.js +367 -352
  16. package/lib/manage-routes.js +1245 -652
  17. package/lib/model-catalog.js +57 -0
  18. package/lib/openai-gateway.js +776 -0
  19. package/lib/plan-client.js +942 -532
  20. package/lib/pool.js +771 -478
  21. package/lib/sse.js +429 -317
  22. package/lib/upstream-api.js +948 -611
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -81
  26. package/scripts/analyze-grant-intervals.mjs +171 -0
  27. package/scripts/check-compat-rc3.mjs +21 -11
  28. package/scripts/debug-claimable.mjs +130 -0
  29. package/scripts/probe-marketing.mjs +203 -0
  30. package/scripts/restart-dsh.ps1 +119 -116
  31. package/scripts/test-claimed-pending.mjs +152 -0
  32. package/scripts/verify_compat.mjs +75 -64
  33. package/scripts/watch-marketing.mjs +155 -0
  34. package/tests/auto-claim.test.mjs +318 -0
  35. package/tests/claim-routes.test.mjs +438 -293
  36. package/tests/client-panel.test.mjs +1141 -356
  37. package/tests/distribution-keys.test.mjs +123 -0
  38. package/tests/e2e.test.mjs +388 -353
  39. package/tests/fallback-scrub.test.mjs +105 -0
  40. package/tests/launch-command.test.mjs +68 -0
  41. package/tests/openai-gateway.test.mjs +454 -0
  42. package/tests/pinned-models.test.mjs +505 -497
  43. package/tests/plan-client.test.mjs +582 -222
  44. package/tests/pool.test.mjs +319 -93
  45. package/tests/quota-blackhole.test.mjs +409 -0
  46. package/tests/restart-script.test.mjs +53 -0
  47. package/tests/routing-quota.test.mjs +251 -0
  48. package/tests/support/hanging-stream.mjs +48 -0
  49. package/tests/upstream-error-200.test.mjs +164 -125
  50. package/tests/upstream.test.mjs +330 -250
  51. package/tests/version-probe.test.mjs +172 -0
@@ -1,222 +1,582 @@
1
- import test from 'node:test'
2
- import assert from 'node:assert/strict'
3
-
4
- import { ZcodePlanClient } from '../lib/plan-client.js'
5
-
6
- const CREDENTIAL = { zcode_jwt: 'jwt-1', device_mid: 'dev-1', user_id: 'u-1' }
7
-
8
- /** 内存版账号池(只实现 plan-client 用到的三个方法)。 */
9
- function fakePool(credentials = [{ id: 'acct-a', credential: CREDENTIAL }]) {
10
- const state = credentials.map((entry) => ({ nickname: entry.id, enabled: true, model_rate_limits: {}, ...entry }))
11
- return {
12
- list: () => state,
13
- pick(model, exclude) {
14
- const excluded = exclude ?? new Set()
15
- const hit = state.find((entry) => entry.enabled && !excluded.has(entry.id))
16
- return hit === undefined ? null : { entry: hit, credential: hit.credential }
17
- },
18
- markModelRateLimited(accountId, modelId, resetAt) {
19
- const hit = state.find((entry) => entry.id === accountId)
20
- if (hit !== undefined) hit.model_rate_limits[modelId] = resetAt
21
- },
22
- noteError() {},
23
- }
24
- }
25
-
26
- const fakeMinter = (params = ['param-1', 'param-2', 'param-3']) => {
27
- let index = 0
28
- return {
29
- calls: 0,
30
- async mint() {
31
- this.calls += 1
32
- return { param: params[Math.min(index++, params.length - 1)], interactive: false }
33
- },
34
- async fetchConfig() {
35
- return { region: 'cn', prefix: 'no8xfe', sceneId: 'scene' }
36
- },
37
- }
38
- }
39
-
40
- const sseStream = (events) =>
41
- new ReadableStream({
42
- start(controller) {
43
- const encoder = new TextEncoder()
44
- for (const event of events) controller.enqueue(encoder.encode(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`))
45
- controller.close()
46
- },
47
- })
48
-
49
- const textStream = () =>
50
- sseStream([
51
- { type: 'message_start', message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 1 } } },
52
- { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
53
- { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'ok' } },
54
- { type: 'message_stop' },
55
- ])
56
-
57
- const emptyStream = () =>
58
- sseStream([
59
- { type: 'message_start', message: { model: 'GLM-5.3-Flash' } },
60
- { type: 'message_stop' },
61
- ])
62
-
63
- const response = (status, body, contentType = 'text/event-stream') => ({
64
- ok: status >= 200 && status < 300,
65
- status,
66
- headers: new Headers({ 'content-type': contentType }),
67
- body,
68
- text: async () => (typeof body === 'string' ? body : ''),
69
- })
70
-
71
- const baseOptions = { model: 'GLM-5.3-Flash', messages: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }] }
72
-
73
- test('先不带 captcha 探测;被 3007 拒后才产出并重试', async () => {
74
- const seen = []
75
- const fetchImpl = async (_url, init) => {
76
- seen.push(init.headers)
77
- if (seen.length === 1) return response(403, JSON.stringify({ code: 3007, msg: 'captcha verify failed' }), 'application/json')
78
- return response(200, textStream())
79
- }
80
- const minter = fakeMinter()
81
- const client = new ZcodePlanClient({ pool: fakePool(), minter, fetchImpl })
82
-
83
- const result = await client.call({ options: baseOptions })
84
- assert.equal(seen.length, 2)
85
- assert.equal(seen[0]['x-aliyun-captcha-verify-param'], undefined, '第一次不带 captcha')
86
- assert.equal(seen[1]['x-aliyun-captcha-verify-param'], 'param-1', '被拒后才产出')
87
- assert.equal(minter.calls, 1)
88
- assert.equal(result.accountId, 'acct-a')
89
- })
90
-
91
- test('已知需要 captcha 时直接带上(省掉一次 3007 往返)', async () => {
92
- const seen = []
93
- let call = 0
94
- const fetchImpl = async (_url, init) => {
95
- seen.push(init.headers)
96
- call += 1
97
- if (call === 1) return response(403, '{"code":3007}', 'application/json')
98
- return response(200, textStream())
99
- }
100
- const minter = fakeMinter()
101
- const client = new ZcodePlanClient({ pool: fakePool(), minter, fetchImpl })
102
-
103
- /** 第一次:探测被拒 → 产出并重试成功(2 次尝试)。 */
104
- await client.call({ options: baseOptions })
105
- assert.equal(seen.length, 2)
106
- assert.equal(seen[0]['x-aliyun-captcha-verify-param'], undefined)
107
- assert.equal(seen[1]['x-aliyun-captcha-verify-param'], 'param-1')
108
-
109
- /** 第二次(同一 client、2 分钟窗口内):直接带头,只发一次。 */
110
- const result = await client.call({ options: baseOptions })
111
- assert.equal(seen.length, 3, '第二次请求不应再吃 3007')
112
- assert.equal(seen[2]['x-aliyun-captcha-verify-param'], 'param-2')
113
- assert.equal(result.accountId, 'acct-a')
114
- })
115
-
116
- test('200 但零内容 → 标记该账号并换号(调用方零 chunk)', async () => {
117
- const pool = fakePool([
118
- { id: 'acct-a', credential: CREDENTIAL },
119
- { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
120
- ])
121
- let call = 0
122
- const fetchImpl = async () => {
123
- call += 1
124
- return response(200, call === 1 ? emptyStream() : textStream())
125
- }
126
- const client = new ZcodePlanClient({ pool, minter: fakeMinter(), fetchImpl })
127
- const picked = []
128
- const originalPick = pool.pick.bind(pool)
129
- pool.pick = (model, exclude) => {
130
- const hit = originalPick(model, exclude)
131
- if (hit !== null) picked.push(hit.entry.id)
132
- return hit
133
- }
134
-
135
- const result = await client.call({ options: baseOptions })
136
- assert.equal(result.accountId, 'acct-b')
137
- assert.deepEqual(picked, ['acct-a', 'acct-b'])
138
- assert.equal(pool.list()[0].model_rate_limits['GLM-5.3-Flash'] > Date.now(), true, 'acct-a 被标记到当日结束')
139
- })
140
-
141
- test('额度用尽(1005)→ 换号;两个号都用尽 → QUOTA 失败', async () => {
142
- const pool = fakePool([
143
- { id: 'acct-a', credential: CREDENTIAL },
144
- { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
145
- ])
146
- const client = new ZcodePlanClient({
147
- pool,
148
- minter: fakeMinter(),
149
- fetchImpl: async () => response(429, '{"code":1005,"msg":"exceed quota limit"}', 'application/json'),
150
- })
151
- await assert.rejects(
152
- () => client.call({ options: baseOptions }),
153
- (error) => {
154
- assert.equal(error.code, 'QUOTA')
155
- return true
156
- },
157
- )
158
- assert.equal(pool.list().every((entry) => entry.model_rate_limits['GLM-5.3-Flash'] > Date.now()), true)
159
- })
160
-
161
- test('风控 3012 不重试、不换号,直接失败', async () => {
162
- let calls = 0
163
- const client = new ZcodePlanClient({
164
- pool: fakePool(),
165
- minter: fakeMinter(),
166
- fetchImpl: async () => {
167
- calls += 1
168
- return response(403, '{"code":3012,"msg":"unusual activity"}', 'application/json')
169
- },
170
- })
171
- await assert.rejects(
172
- () => client.call({ options: baseOptions }),
173
- (error) => {
174
- assert.equal(error.code, 'RATE_LIMIT')
175
- assert.match(error.message, /3012/)
176
- return true
177
- },
178
- )
179
- assert.equal(calls, 1, '3012 有冷却惩罚:绝不能连续重试')
180
- })
181
-
182
- test('并发限流 3009 退避重试但不换号', async () => {
183
- let calls = 0
184
- const client = new ZcodePlanClient({
185
- pool: fakePool(),
186
- minter: fakeMinter(),
187
- fetchImpl: async () => {
188
- calls += 1
189
- return calls === 1 ? response(429, '{"code":3009}', 'application/json') : response(200, textStream())
190
- },
191
- })
192
- const result = await client.call({ options: baseOptions })
193
- assert.equal(calls, 2)
194
- assert.equal(result.accountId, 'acct-a')
195
- })
196
-
197
- test('账号池为空 → QUOTA 并提示登录命令', async () => {
198
- const client = new ZcodePlanClient({ pool: fakePool([]), minter: fakeMinter(), fetchImpl: async () => response(200, textStream()) })
199
- await assert.rejects(
200
- () => client.call({ options: baseOptions }),
201
- (error) => {
202
- assert.equal(error.code, 'QUOTA')
203
- assert.match(error.message, /zcode-start-plan login/)
204
- return true
205
- },
206
- )
207
- })
208
-
209
- test('401 凭据失效 → AUTH,不换号', async () => {
210
- const client = new ZcodePlanClient({
211
- pool: fakePool(),
212
- minter: fakeMinter(),
213
- fetchImpl: async () => response(401, '{"code":1002}', 'application/json'),
214
- })
215
- await assert.rejects(
216
- () => client.call({ options: baseOptions }),
217
- (error) => {
218
- assert.equal(error.code, 'AUTH')
219
- return true
220
- },
221
- )
222
- })
1
+ import test from 'node:test'
2
+ import assert from 'node:assert/strict'
3
+
4
+ import { ZcodePlanClient } from '../lib/plan-client.js'
5
+ import { nextUtc8DayStartMs } from '../lib/upstream.js'
6
+
7
+ const CREDENTIAL = { zcode_jwt: 'jwt-1', device_mid: 'dev-1', user_id: 'u-1' }
8
+
9
+ /** 内存版账号池(只实现 plan-client 用到的方法)。 */
10
+ function fakePool(credentials = [{ id: 'acct-a', credential: CREDENTIAL }]) {
11
+ const state = credentials.map((entry) => ({ nickname: entry.id, enabled: true, model_rate_limits: {}, ...entry }))
12
+ /** 进程内零内容观察窗(与真池同语义:软优先,不进 model_rate_limits)。 */
13
+ const watch = new Map()
14
+ return {
15
+ list: () => state,
16
+ get(id) {
17
+ return state.find((entry) => entry.id === id)
18
+ },
19
+ /** 与真池一致:限流中的账号×模型被硬过滤(当日级);观察窗只是软优先不在这判。 */
20
+ pick(model, exclude) {
21
+ const excluded = exclude ?? new Set()
22
+ const now = Date.now()
23
+ const hit = state.find(
24
+ (entry) =>
25
+ entry.enabled &&
26
+ !excluded.has(entry.id) &&
27
+ !((entry.model_rate_limits[model] ?? 0) > now),
28
+ )
29
+ return hit === undefined ? null : { entry: hit, credential: hit.credential }
30
+ },
31
+ markModelRateLimited(accountId, modelId, resetAt) {
32
+ const hit = state.find((entry) => entry.id === accountId)
33
+ if (hit !== undefined) hit.model_rate_limits[modelId] = resetAt
34
+ },
35
+ /**
36
+ * 面板「清除限流」的**同一个入口**(3012 风控后 plan-client 会自动调它)。
37
+ * 与真池(`AccountPool.clearModelRateLimits`)同语义:只清选中项,返回清掉几项。
38
+ */
39
+ clearModelRateLimits(accountId, modelIds) {
40
+ const hit = state.find((entry) => entry.id === accountId)
41
+ if (hit === undefined) return 0
42
+ let removed = 0
43
+ for (const modelId of modelIds ?? Object.keys(hit.model_rate_limits)) {
44
+ if (Object.prototype.hasOwnProperty.call(hit.model_rate_limits, modelId)) {
45
+ delete hit.model_rate_limits[modelId]
46
+ removed += 1
47
+ }
48
+ }
49
+ return removed
50
+ },
51
+ noteEmptyContentWatch(accountId, modelId, until) {
52
+ watch.set(`${accountId}|${modelId}`, until)
53
+ },
54
+ isEmptyContentWatched(accountId, modelId) {
55
+ return (watch.get(`${accountId}|${modelId}`) ?? 0) > Date.now()
56
+ },
57
+ clearEmptyContentWatch(accountId, modelId) {
58
+ watch.delete(`${accountId}|${modelId}`)
59
+ },
60
+ noteError() {},
61
+ }
62
+ }
63
+
64
+ const fakeMinter = (params = ['param-1', 'param-2', 'param-3']) => {
65
+ let index = 0
66
+ return {
67
+ calls: 0,
68
+ async mint() {
69
+ this.calls += 1
70
+ return { param: params[Math.min(index++, params.length - 1)], interactive: false }
71
+ },
72
+ async fetchConfig() {
73
+ return { region: 'cn', prefix: 'no8xfe', sceneId: 'scene' }
74
+ },
75
+ }
76
+ }
77
+
78
+ const sseStream = (events) =>
79
+ new ReadableStream({
80
+ start(controller) {
81
+ const encoder = new TextEncoder()
82
+ for (const event of events) controller.enqueue(encoder.encode(`event: ${event.type}\ndata: ${JSON.stringify(event)}\n\n`))
83
+ controller.close()
84
+ },
85
+ })
86
+
87
+ const textStream = () =>
88
+ sseStream([
89
+ { type: 'message_start', message: { model: 'GLM-5.3-Flash', usage: { input_tokens: 1 } } },
90
+ { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } },
91
+ { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: 'ok' } },
92
+ { type: 'message_stop' },
93
+ ])
94
+
95
+ const emptyStream = () =>
96
+ sseStream([
97
+ { type: 'message_start', message: { model: 'GLM-5.3-Flash' } },
98
+ { type: 'message_stop' },
99
+ ])
100
+
101
+ const response = (status, body, contentType = 'text/event-stream') => ({
102
+ ok: status >= 200 && status < 300,
103
+ status,
104
+ headers: new Headers({ 'content-type': contentType }),
105
+ body,
106
+ text: async () => (typeof body === 'string' ? body : ''),
107
+ })
108
+
109
+ const baseOptions = { model: 'GLM-5.3-Flash', messages: [{ role: 'user', content: [{ type: 'text', text: 'hi' }] }] }
110
+
111
+ test('先不带 captcha 探测;被 3007 拒后才产出并重试', async () => {
112
+ const seen = []
113
+ const fetchImpl = async (_url, init) => {
114
+ seen.push(init.headers)
115
+ if (seen.length === 1) return response(403, JSON.stringify({ code: 3007, msg: 'captcha verify failed' }), 'application/json')
116
+ return response(200, textStream())
117
+ }
118
+ const minter = fakeMinter()
119
+ const client = new ZcodePlanClient({ pool: fakePool(), minter, fetchImpl })
120
+
121
+ const result = await client.call({ options: baseOptions })
122
+ assert.equal(seen.length, 2)
123
+ assert.equal(seen[0]['x-aliyun-captcha-verify-param'], undefined, '第一次不带 captcha')
124
+ assert.equal(seen[1]['x-aliyun-captcha-verify-param'], 'param-1', '被拒后才产出')
125
+ assert.equal(minter.calls, 1)
126
+ assert.equal(result.accountId, 'acct-a')
127
+ })
128
+
129
+ test('已知需要 captcha 时直接带上(省掉一次 3007 往返)', async () => {
130
+ const seen = []
131
+ let call = 0
132
+ const fetchImpl = async (_url, init) => {
133
+ seen.push(init.headers)
134
+ call += 1
135
+ if (call === 1) return response(403, '{"code":3007}', 'application/json')
136
+ return response(200, textStream())
137
+ }
138
+ const minter = fakeMinter()
139
+ const client = new ZcodePlanClient({ pool: fakePool(), minter, fetchImpl })
140
+
141
+ /** 第一次:探测被拒 → 产出并重试成功(2 次尝试)。 */
142
+ await client.call({ options: baseOptions })
143
+ assert.equal(seen.length, 2)
144
+ assert.equal(seen[0]['x-aliyun-captcha-verify-param'], undefined)
145
+ assert.equal(seen[1]['x-aliyun-captcha-verify-param'], 'param-1')
146
+
147
+ /** 第二次(同一 client、2 分钟窗口内):直接带头,只发一次。 */
148
+ const result = await client.call({ options: baseOptions })
149
+ assert.equal(seen.length, 3, '第二次请求不应再吃 3007')
150
+ assert.equal(seen[2]['x-aliyun-captcha-verify-param'], 'param-2')
151
+ assert.equal(result.accountId, 'acct-a')
152
+ })
153
+
154
+ test('200 但零内容 → 标记该账号并换号(调用方零 chunk)', async () => {
155
+ const pool = fakePool([
156
+ { id: 'acct-a', credential: CREDENTIAL },
157
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
158
+ ])
159
+ let call = 0
160
+ const fetchImpl = async () => {
161
+ call += 1
162
+ return response(200, call === 1 ? emptyStream() : textStream())
163
+ }
164
+ const client = new ZcodePlanClient({ pool, minter: fakeMinter(), fetchImpl })
165
+ const picked = []
166
+ const originalPick = pool.pick.bind(pool)
167
+ pool.pick = (model, exclude) => {
168
+ const hit = originalPick(model, exclude)
169
+ if (hit !== null) picked.push(hit.entry.id)
170
+ return hit
171
+ }
172
+
173
+ const result = await client.call({ options: baseOptions })
174
+ assert.equal(result.accountId, 'acct-b')
175
+ assert.deepEqual(picked, ['acct-a', 'acct-b'])
176
+ /**
177
+ * 1.0.1 两级证据:**首次**零内容只打观察窗(pool 软优先,10 分钟自动过期),
178
+ * 绝不写进 model_rate_limits(那是当日硬过滤表)—— 模型实际可用时一次
179
+ * 上游抖动不该判死刑。
180
+ */
181
+ assert.equal(
182
+ pool.list()[0].model_rate_limits['GLM-5.3-Flash'] === undefined,
183
+ true,
184
+ '首次零内容不落当日硬标记',
185
+ )
186
+ assert.equal(pool.isEmptyContentWatched('acct-a', 'GLM-5.3-Flash'), true, '但进观察窗(软优先)')
187
+ })
188
+
189
+ test('零内容两级证据:观察窗内第二次(跨请求)才升级为当日标记', async () => {
190
+ const pool = fakePool([{ id: 'acct-a', credential: CREDENTIAL }])
191
+ const fetchImpl = async () => response(200, emptyStream())
192
+ const client = new ZcodePlanClient({ pool, minter: fakeMinter(), fetchImpl })
193
+ /**
194
+ * 唯一账号场景(最坏情况):请求 1 零内容(首次)→ 观察窗 + 换号;
195
+ * 观察窗是软优先,pick 第二档仍会选回 A —— 第二次零内容升级当日。
196
+ */
197
+ await assert.rejects(() => client.call({ options: baseOptions }), (error) => error.code === 'QUOTA')
198
+ assert.equal(
199
+ pool.list()[0].model_rate_limits['GLM-5.3-Flash'] === undefined,
200
+ true,
201
+ '首次零内容不落当日硬标记',
202
+ )
203
+ await assert.rejects(() => client.call({ options: baseOptions }), (error) => error.code === 'QUOTA')
204
+ const mark = pool.list()[0].model_rate_limits['GLM-5.3-Flash']
205
+ assert.equal(mark, nextUtc8DayStartMs(new Date()), '观察窗内第二次零内容 → 升级为当日标记(= 下一个 UTC+8 零点)')
206
+ })
207
+
208
+ test('额度用尽(1005)→ 换号;两个号都用尽 → QUOTA 失败', async () => {
209
+ const pool = fakePool([
210
+ { id: 'acct-a', credential: CREDENTIAL },
211
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
212
+ ])
213
+ const client = new ZcodePlanClient({
214
+ pool,
215
+ minter: fakeMinter(),
216
+ fetchImpl: async () => response(429, '{"code":1005,"msg":"exceed quota limit"}', 'application/json'),
217
+ })
218
+ await assert.rejects(
219
+ () => client.call({ options: baseOptions }),
220
+ (error) => {
221
+ assert.equal(error.code, 'QUOTA')
222
+ return true
223
+ },
224
+ )
225
+ assert.equal(pool.list().every((entry) => entry.model_rate_limits['GLM-5.3-Flash'] > Date.now()), true)
226
+ })
227
+
228
+ test('风控 3012 不重试、不换号,直接失败(独立码 RISK_BLOCKED)', async () => {
229
+ let calls = 0
230
+ const client = new ZcodePlanClient({
231
+ pool: fakePool(),
232
+ minter: fakeMinter(),
233
+ fetchImpl: async () => {
234
+ calls += 1
235
+ return response(403, '{"code":3012,"msg":"unusual activity"}', 'application/json')
236
+ },
237
+ })
238
+ await assert.rejects(
239
+ () => client.call({ options: baseOptions }),
240
+ (error) => {
241
+ /**
242
+ * ⚠ 必须是 **RISK_BLOCKED**,不是 RATE_LIMIT(3012 的语义收窄后的契约):
243
+ * - RATE_LIMIT 只表示 3009 并发限流(秒级瞬态,可重试可回退);
244
+ * - 3012 是账号级风控,重试有累积惩罚(30 分钟 → 24 小时 → 停用),
245
+ * 宿主要能按码分流出「不许自动重试」。
246
+ */
247
+ assert.equal(error.code, 'RISK_BLOCKED')
248
+ assert.match(error.message, /3012/)
249
+ assert.match(error.message, /风控/, '文案要说清这是风控,不是额度问题')
250
+ return true
251
+ },
252
+ )
253
+ assert.equal(calls, 1, '3012 有冷却惩罚:绝不能连续重试')
254
+ })
255
+
256
+ test('风控 3012 后**自动清除**该账号×模型的限流标记(不必等用户点面板按钮)', async () => {
257
+ /**
258
+ * 3012 常常是一次误判:该账号×模型未必真的耗尽额度,但此前可能已被打过
259
+ * `model_rate_limits` 硬标记(零内容升级 / 早前的 1005)。若不清掉,用户
260
+ * 「稍后重试」时会在**选号阶段**就被自己的标记挡住 —— 看起来还像额度问题,
261
+ * 而真正的原因是风控。
262
+ */
263
+ const pool = fakePool([
264
+ { id: 'acct-a', credential: CREDENTIAL },
265
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
266
+ ])
267
+ const MODEL = 'GLM-5.3-Flash'
268
+ /**
269
+ * 两个「别人的上游依据」标记:**别的账号**、**别的模型**。
270
+ * 3012 只允许清「该账号 × 该模型」,这两条必须原样留着。
271
+ */
272
+ pool.markModelRateLimited('acct-a', 'GLM-5.3', Date.now() + 3_600_000)
273
+ pool.markModelRateLimited('acct-b', 'GLM-4.6', Date.now() + 3_600_000)
274
+ /**
275
+ * 本次要验的核心:该账号 × 该模型**原本带着当日硬标记**(早前的零内容升级 /
276
+ * 1005 留下的),随后这一次请求撞上 3012 —— 标记必须被自动清除。
277
+ *
278
+ * ⚠ 用**自动选号**(不钉定)而不是钉定:钉定会先按限流把账号拒掉,根本发不出请求。
279
+ * 这里让选号第一步就把 acct-a 选出来(acct-b 也带标记 → 一并排除),
280
+ * 于是 3012 分支能走到,清除动作可观测。
281
+ */
282
+ pool.pick = (model, exclude) => {
283
+ const excluded = exclude ?? new Set()
284
+ const hit = pool.list().find((entry) => entry.enabled && !excluded.has(entry.id))
285
+ return hit === undefined ? null : { entry: hit, credential: hit.credential }
286
+ }
287
+
288
+ let calls = 0
289
+ const client = new ZcodePlanClient({
290
+ pool,
291
+ minter: fakeMinter(),
292
+ fetchImpl: async () => {
293
+ calls += 1
294
+ return response(403, '{"code":3012,"msg":"unusual activity"}', 'application/json')
295
+ },
296
+ })
297
+
298
+ await assert.rejects(
299
+ () => client.call({ options: baseOptions }),
300
+ (error) => {
301
+ assert.equal(error.code, 'RISK_BLOCKED')
302
+ return true
303
+ },
304
+ )
305
+ assert.equal(calls, 1, '清除标记是为了「用户手动重试时不被自己挡住」,不是为了自动再撞一次')
306
+ assert.equal(
307
+ pool.list()[0].model_rate_limits[MODEL],
308
+ undefined,
309
+ '3012 之后该账号该模型的限流标记必须已被自动清除(本轮核心需求)',
310
+ )
311
+ assert.notEqual(
312
+ pool.list()[0].model_rate_limits['GLM-5.3'],
313
+ undefined,
314
+ '只清该模型:同一账号的其它模型标记各有上游依据',
315
+ )
316
+ assert.notEqual(
317
+ pool.list()[1].model_rate_limits['GLM-4.6'],
318
+ undefined,
319
+ '只清该账号:别的账号的标记各有上游依据,绝不能顺手清掉',
320
+ )
321
+ })
322
+
323
+ test('并发限流 3009 退避重试但不换号', async () => {
324
+ let calls = 0
325
+ const client = new ZcodePlanClient({
326
+ pool: fakePool(),
327
+ minter: fakeMinter(),
328
+ concurrencyRetryBaseMs: 1,
329
+ fetchImpl: async () => {
330
+ calls += 1
331
+ return calls === 1 ? response(429, '{"code":3009}', 'application/json') : response(200, textStream())
332
+ },
333
+ })
334
+ const result = await client.call({ options: baseOptions })
335
+ assert.equal(calls, 2)
336
+ assert.equal(result.accountId, 'acct-a')
337
+ })
338
+
339
+ test('3009 打忙标记:并行请求直接路由到空闲账号', async () => {
340
+ const pool = fakePool([
341
+ { id: 'acct-a', credential: CREDENTIAL },
342
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
343
+ ])
344
+ /** 固定时钟:忙标记 60s 窗口内第二个请求必须绕开 acct-a。 */
345
+ let now = Date.now()
346
+ const markBusy = []
347
+ let clearBusy = 0
348
+ const realPool = new Map()
349
+ for (const entry of pool.list()) realPool.set(entry.id, entry)
350
+ const busy = new Map()
351
+ pool.markModelBusy = (accountId, modelId) => {
352
+ markBusy.push(`${accountId}|${modelId}`)
353
+ busy.set(`${accountId}|${modelId}`, now + 60_000)
354
+ }
355
+ pool.isModelBusy = (accountId, modelId) => (busy.get(`${accountId}|${modelId}`) ?? 0) > now
356
+ pool.clearModelBusy = (accountId, modelId) => {
357
+ const key = `${accountId}|${modelId}`
358
+ if (busy.has(key)) {
359
+ busy.delete(key)
360
+ clearBusy += 1
361
+ }
362
+ }
363
+ pool.pick = (model, exclude) => {
364
+ const excluded = exclude ?? new Set()
365
+ const byModel = (entry) => entry.enabled && !excluded.has(entry.id)
366
+ let hit = [...realPool.values()].find((entry) => byModel(entry) && !pool.isModelBusy(entry.id, model))
367
+ if (hit === undefined) hit = [...realPool.values()].find((entry) => byModel(entry))
368
+ return hit === undefined ? null : { entry: hit, credential: hit.credential }
369
+ }
370
+
371
+ /** 请求 1:acct-a 撞 3009,退避穷尽(上限 2 次)后换到 acct-b 成功。 */
372
+ let calls = 0
373
+ const client = new ZcodePlanClient({
374
+ pool,
375
+ minter: fakeMinter(),
376
+ concurrencyRetryBaseMs: 1,
377
+ now: () => now,
378
+ fetchImpl: async () => {
379
+ calls += 1
380
+ return calls <= 3 ? response(429, '{"code":3009}', 'application/json') : response(200, textStream())
381
+ },
382
+ })
383
+ const first = await client.call({ options: baseOptions })
384
+ assert.equal(first.accountId, 'acct-b', '退避穷尽后换号到 acct-b')
385
+ assert.deepEqual(
386
+ [...new Set(markBusy)],
387
+ ['acct-a|GLM-5.3-Flash'],
388
+ '3009 命中即打忙标记(每次尝试都刷新,key 集合不变)',
389
+ )
390
+ assert.equal(calls, 4)
391
+
392
+ /** 请求 2(同一 60s 窗口内):选号第一档就跳过忙的 acct-a,直接用 acct-b。 */
393
+ let secondCalls = 0
394
+ const client2 = new ZcodePlanClient({
395
+ pool,
396
+ minter: fakeMinter(),
397
+ concurrencyRetryBaseMs: 1,
398
+ now: () => now,
399
+ fetchImpl: async () => {
400
+ secondCalls += 1
401
+ return response(200, textStream())
402
+ },
403
+ })
404
+ const second = await client2.call({ options: baseOptions })
405
+ assert.equal(second.accountId, 'acct-b', '忙标记让并行请求直接路由到空闲账号')
406
+ assert.equal(secondCalls, 1, '不再先撞忙账号')
407
+ assert.equal(clearBusy, 0)
408
+ })
409
+
410
+ test('3009 换号后全部忙尽 → RATE_LIMIT(而非 QUOTA),提示稍后重试', async () => {
411
+ const pool = fakePool([
412
+ { id: 'acct-a', credential: CREDENTIAL },
413
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
414
+ ])
415
+ const client = new ZcodePlanClient({
416
+ pool,
417
+ minter: fakeMinter(),
418
+ concurrencyRetryBaseMs: 1,
419
+ fetchImpl: async () => response(429, '{"code":3009,"msg":"model concurrency limit exceeded"}', 'application/json'),
420
+ })
421
+ await assert.rejects(
422
+ () => client.call({ options: baseOptions }),
423
+ (error) => {
424
+ assert.equal(error.code, 'RATE_LIMIT')
425
+ assert.match(error.message, /3009/)
426
+ assert.match(error.message, /稍后重试/)
427
+ return true
428
+ },
429
+ )
430
+ /** 3009 绝不能打成「额度用尽」标记(那会把账号冤枉到当日结束)。 */
431
+ assert.equal(
432
+ pool.list().every((entry) => Object.keys(entry.model_rate_limits).length === 0),
433
+ true,
434
+ '忙账号只打软标记,model_rate_limits 保持干净',
435
+ )
436
+ })
437
+
438
+ test('3009 成功命中后清忙标记,不再绕开该账号', async () => {
439
+ const pool = fakePool([{ id: 'acct-a', credential: CREDENTIAL }])
440
+ let busy = false
441
+ pool.markModelBusy = () => {
442
+ busy = true
443
+ }
444
+ pool.isModelBusy = () => busy
445
+ pool.clearModelBusy = () => {
446
+ busy = false
447
+ }
448
+ let calls = 0
449
+ const client = new ZcodePlanClient({
450
+ pool,
451
+ minter: fakeMinter(),
452
+ concurrencyRetryBaseMs: 1,
453
+ fetchImpl: async () => {
454
+ calls += 1
455
+ return calls === 1 ? response(429, '{"code":3009}', 'application/json') : response(200, textStream())
456
+ },
457
+ })
458
+ const result = await client.call({ options: baseOptions })
459
+ assert.equal(result.accountId, 'acct-a')
460
+ assert.equal(busy, false, '命中成功 = 账号已空闲,忙标记立即清除')
461
+ })
462
+
463
+ test('钉定账号持续 3009 → RATE_LIMIT 报错,绝不换号', async () => {
464
+ let calls = 0
465
+ const client = new ZcodePlanClient({
466
+ pool: fakePool(),
467
+ minter: fakeMinter(),
468
+ concurrencyRetryBaseMs: 1,
469
+ fetchImpl: async () => {
470
+ calls += 1
471
+ return response(429, '{"code":3009}', 'application/json')
472
+ },
473
+ })
474
+ await assert.rejects(
475
+ () => client.call({ options: { ...baseOptions, model: 'GLM-5.3-Flash@acct:acct-a' } }),
476
+ (error) => {
477
+ assert.equal(error.code, 'RATE_LIMIT')
478
+ assert.match(error.message, /钉定的账号/)
479
+ assert.match(error.message, /3009/)
480
+ return true
481
+ },
482
+ )
483
+ /** 1 次请求 = 退避上限 2 次重试 + 1 = 3 发,全打在钉定账号上,无第二发选号。 */
484
+ assert.equal(calls, 3, '钉定模式只打指定账号,绝不换号')
485
+ })
486
+
487
+ test('账号池为空 → QUOTA 并提示登录命令', async () => {
488
+ const client = new ZcodePlanClient({ pool: fakePool([]), minter: fakeMinter(), fetchImpl: async () => response(200, textStream()) })
489
+ await assert.rejects(
490
+ () => client.call({ options: baseOptions }),
491
+ (error) => {
492
+ assert.equal(error.code, 'QUOTA')
493
+ assert.match(error.message, /zcode-start-plan login/)
494
+ return true
495
+ },
496
+ )
497
+ })
498
+
499
+ test('401 凭据失效 → 同账号撞满 2 次后换号;单账号池 → 终态 AUTH', async () => {
500
+ let calls = 0
501
+ const client = new ZcodePlanClient({
502
+ pool: fakePool(),
503
+ minter: fakeMinter(),
504
+ fetchImpl: async () => {
505
+ calls += 1
506
+ return response(401, '{"code":1002}', 'application/json')
507
+ },
508
+ })
509
+ await assert.rejects(
510
+ () => client.call({ options: baseOptions }),
511
+ (error) => {
512
+ /**
513
+ * 0.9.9 韧性语义:auth 不再当场 throw —— 撞满 2 次换号;单账号池
514
+ * 选不到下一个号,按**真实失败原因**(auth)归 `AUTH` 终态。
515
+ *
516
+ * ⚠ 不再归 QUOTA:凭据失效需要重新登录,等额度重置永远不会解决它;
517
+ * 报成额度问题会把用户带去错误的排查方向(且 AUTH 不在回退名单里)。
518
+ */
519
+ assert.equal(error.code, 'AUTH')
520
+ assert.match(error.message, /凭据失效|1002/)
521
+ return true
522
+ },
523
+ )
524
+ assert.equal(calls, 2, '同账号失败两次(1 < 2 不换,第 2 次触发换号)')
525
+ })
526
+
527
+ test('0.9.9 韧性:统一选号下 any-error 两连败自动换号(压缩调用 + 主请求各撞一次也能活)', async () => {
528
+ const pool = fakePool([
529
+ { id: 'acct-a', credential: CREDENTIAL },
530
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
531
+ ])
532
+ /** acct-a 永远 500(other 类);acct-b 正常 —— 模拟压缩调用 + 主请求
533
+ * 两次都先撞上坏账号的真实形态。 */
534
+ let call = 0
535
+ const client = new ZcodePlanClient({
536
+ pool,
537
+ minter: fakeMinter(),
538
+ fetchImpl: async () => {
539
+ call += 1
540
+ return call <= 2 ? response(500, 'upstream boom', 'text/plain') : response(200, textStream())
541
+ },
542
+ })
543
+ const result = await client.call({ options: baseOptions })
544
+ assert.equal(result.accountId, 'acct-b', '第 3 发落到健康账号')
545
+ assert.equal(call, 3, 'acct-a 恰好两连败后换号')
546
+ })
547
+
548
+ test('0.9.9 韧性:3012 风控仍然绝不重试、绝不换号(冷却惩罚优先于韧性)', async () => {
549
+ let calls = 0
550
+ const pool = fakePool([
551
+ { id: 'acct-a', credential: CREDENTIAL },
552
+ { id: 'acct-b', credential: { ...CREDENTIAL, user_id: 'u-2' } },
553
+ ])
554
+ const client = new ZcodePlanClient({
555
+ pool,
556
+ minter: fakeMinter(),
557
+ fetchImpl: async () => {
558
+ calls += 1
559
+ return response(403, '{"code":3012,"msg":"unusual activity"}', 'application/json')
560
+ },
561
+ })
562
+ await assert.rejects(
563
+ () => client.call({ options: baseOptions }),
564
+ (error) => {
565
+ /** 独立码:风控不是并发限流,宿主要能分流出「不许自动重试」。 */
566
+ assert.equal(error.code, 'RISK_BLOCKED')
567
+ assert.match(error.message, /3012/)
568
+ return true
569
+ },
570
+ )
571
+ assert.equal(calls, 1, '3012 有账号冷却惩罚:一次即停,韧性兜底不覆盖它')
572
+ })
573
+
574
+ test('3012 的 RISK_BLOCKED 刻意**不在**回退名单里(换通道常常还是同一批账号)', async () => {
575
+ const { isFallbackWorthyCode } = await import('../lib/errors.js')
576
+ assert.equal(isFallbackWorthyCode('RISK_BLOCKED'), false, '风控不触发插件回退:冷却惩罚是账号级的')
577
+ /** 语义收窄后的对照:RATE_LIMIT 只表示 3009 并发限流(瞬态,可回退)。 */
578
+ assert.equal(isFallbackWorthyCode('RATE_LIMIT'), true)
579
+ assert.equal(isFallbackWorthyCode('QUOTA'), true)
580
+ assert.equal(isFallbackWorthyCode('TIMEOUT'), true)
581
+ assert.equal(isFallbackWorthyCode('AUTH'), false)
582
+ })