dsh-zcode-startplan 0.4.5 → 1.0.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.
Files changed (58) hide show
  1. package/CHANGELOG.md +1963 -405
  2. package/README.md +88 -405
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -716
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +144 -14
  7. package/lib/adapter.js +476 -422
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -420
  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 -489
  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 -570
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -80
  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 -76
  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/anthropic-body.test.mjs +305 -0
  35. package/tests/assembler-contract.test.mjs +256 -0
  36. package/tests/auto-claim.test.mjs +318 -0
  37. package/tests/claim-routes.test.mjs +438 -0
  38. package/tests/client-panel.test.mjs +1141 -0
  39. package/tests/distribution-keys.test.mjs +123 -0
  40. package/tests/e2e.test.mjs +388 -0
  41. package/tests/fallback-scrub.test.mjs +105 -0
  42. package/tests/fixtures/quota-200.json +1 -0
  43. package/tests/launch-command.test.mjs +68 -0
  44. package/tests/login-channel.test.mjs +102 -0
  45. package/tests/openai-gateway.test.mjs +454 -0
  46. package/tests/pinned-models.test.mjs +505 -0
  47. package/tests/plan-client.test.mjs +582 -0
  48. package/tests/pool.test.mjs +319 -0
  49. package/tests/quota-blackhole.test.mjs +409 -0
  50. package/tests/restart-script.test.mjs +53 -0
  51. package/tests/routing-quota.test.mjs +251 -0
  52. package/tests/sse.test.mjs +86 -0
  53. package/tests/stream-translator.test.mjs +137 -0
  54. package/tests/support/hanging-stream.mjs +48 -0
  55. package/tests/support/resolve-profile-deps.mjs +52 -0
  56. package/tests/upstream-error-200.test.mjs +164 -0
  57. package/tests/upstream.test.mjs +330 -0
  58. package/tests/version-probe.test.mjs +172 -0
@@ -1,532 +1,942 @@
1
- /**
2
- * ZCode 免费 plan 通道的一次请求编排(切号 / captcha / 退避的唯一实现)。
3
- *
4
- * ```
5
- * 选号(手动顺序,跳过该模型限流中的账号)
6
- * → 本轮是否需要 captcha("要了才取":被 3007 拒过才产出)
7
- * → 组 body(官方身份块 + 日期块 + tools 断点)
8
- * → 直发上游
9
- * → 200:先读「是否真的产出了内容」
10
- * ├─ 有内容 → 交给调用方流式消费(此后禁止换号)
11
- * └─ 无内容 → 标记该账号×模型 → 换号重试(调用方零 chunk)
12
- * → 非 200:按错误表处置
13
- * ├─ 额度用尽 → 标号 + 换号
14
- * ├─ 并发限流 → 退避重试(不换号)
15
- * ├─ captcha 失败 → 换新 captcha 重试
16
- * └─ 风控 / 鉴权 / 其它 → 如实报错(不重试)
17
- * ```
18
- *
19
- * ## 两条不可动摇的约定
20
- *
21
- * 1. **`emitted` 闸**:一旦把 chunk 交给调用方,绝不再换号/重试(防两份输出)。
22
- * 2. **每轮重试都必须重新 mint captcha**:param 一次性,复用必 3007。
23
- */
24
-
25
- import { buildUpstreamBody, resolveImages } from './anthropic-body.js'
26
- import {
27
- CONCURRENCY_RETRY_MAX,
28
- QUOTA_SWITCH_MAX,
29
- classifyUpstreamError,
30
- concurrencyRetryDelayMs,
31
- describeUpstreamError,
32
- } from './errors.js'
33
- import { readContentHead } from './sse.js'
34
- import { buildZcodeHeaders, ZCODE_PLAN_MESSAGES_URL, ZCODE_FALLBACK_MODELS, nextUtc8DayStartMs } from './upstream.js'
35
- import { ZCODE_CAPTCHA_FALLBACK } from './captcha/sdk-page.js'
36
- import { parsePinnedModelId } from './pinned-model.js'
37
- import { isUsableCredential } from './pool.js'
38
-
39
- /** 「该账号×模型当前需要 captcha」的记忆时长(避免每条消息都白吃一次 3007)。 */
40
- const CAPTCHA_REQUIRED_TTL_MS = 2 * 60_000
41
-
42
- /** 串行队列:captcha 产出是设备级的,并发无益且会互相踩页面。 */
43
- class SerialQueue {
44
- #tail = Promise.resolve()
45
- run(task) {
46
- const next = this.#tail.then(task, task)
47
- /** 队列本身不因一次失败而卡死。 */
48
- this.#tail = next.catch(() => {})
49
- return next
50
- }
51
- }
52
-
53
- /** captcha 产出失败的指数退避闸门(保护设备信誉)。 */
54
- class CaptchaBackoff {
55
- #streak = 0
56
- #until = 0
57
- noteFailure(now = Date.now()) {
58
- this.#streak += 1
59
- const cooldown = Math.min(60_000 * 2 ** (this.#streak - 1), 30 * 60_000)
60
- this.#until = now + cooldown
61
- return cooldown
62
- }
63
- noteSuccess() {
64
- this.#streak = 0
65
- this.#until = 0
66
- }
67
- remainingMs(now = Date.now()) {
68
- return Math.max(0, this.#until - now)
69
- }
70
- get failureStreak() {
71
- return this.#streak
72
- }
73
- }
74
-
75
- /** 发车闸门:全局串行 + 按模型间隔(GLM-5.3 需 350ms,Flash 不需要)。 */
76
- class ModelGate {
77
- #chain = Promise.resolve()
78
- #lastVerdict = { model: '', at: 0 }
79
- #gaps
80
- constructor(gaps) {
81
- this.#gaps = gaps
82
- }
83
- async run(model, task) {
84
- const previous = this.#chain
85
- let release
86
- this.#chain = new Promise((resolve) => {
87
- release = resolve
88
- })
89
- try {
90
- await previous
91
- const gap = this.#gaps[String(model).toLowerCase()] ?? 0
92
- if (gap > 0 && this.#lastVerdict.model === model) {
93
- const wait = gap - (Date.now() - this.#lastVerdict.at)
94
- if (wait > 0) await sleep(wait)
95
- }
96
- try {
97
- return await task()
98
- } finally {
99
- this.#lastVerdict = { model, at: Date.now() }
100
- }
101
- } finally {
102
- release()
103
- }
104
- }
105
- }
106
-
107
- function sleep(ms) {
108
- return new Promise((resolve) => {
109
- const timer = setTimeout(resolve, ms)
110
- timer.unref?.()
111
- })
112
- }
113
-
114
- /**
115
- * 一次「zcode-plan」调用的可复用客户端。
116
- *
117
- * 进程内应是**单实例**(captcha 产出、闸门、需求记忆都是设备级/全局状态)。
118
- */
119
- export class ZcodePlanClient {
120
- #pool
121
- #minter
122
- #fetchImpl
123
- #log
124
- #now
125
- #cwd
126
- #queue = new SerialQueue()
127
- #backoff = new CaptchaBackoff()
128
- #gate = new ModelGate({ 'glm-5.3': 350 })
129
- #captchaRequiredUntil = new Map()
130
- #captchaConfig
131
- #captchaConfigAt = 0
132
- /** 附件服务回调(`() => ctx.get('attachments')`,可选):图片引用 → 请求字节。 */
133
- #resolveDeps
134
-
135
- constructor(options) {
136
- this.#pool = options.pool
137
- this.#minter = options.minter
138
- this.#fetchImpl = options.fetchImpl ?? globalThis.fetch
139
- this.#log = options.log ?? (() => {})
140
- this.#now = options.now ?? (() => Date.now())
141
- this.#cwd = options.cwd ?? process.cwd()
142
- this.#captchaConfig = options.captchaConfig
143
- this.#resolveDeps = options
144
- }
145
-
146
- /** 供状态工具读取观测值。 */
147
- observability() {
148
- return {
149
- captchaFailureStreak: this.#backoff.failureStreak,
150
- captchaCooldownRemainingMs: this.#backoff.remainingMs(this.#now()),
151
- captchaRequiredAccounts: [...this.#captchaRequiredUntil.keys()].length,
152
- }
153
- }
154
-
155
- /**
156
- * 钉定模式选号:只取指定账号,**绝不换号**。
157
- *
158
- * 与 `pool.pick` 的差异:不按手动顺序、不看其他账号;但同样跳过「该模型
159
- * 限流中」的账号 —— 限流标记意味着额度已尽,硬发只会吃一个 1005。
160
- * 账号缺失 / 停用 / 凭据不可用 / 限流中都以**明确报错**收场(各自给出路),
161
- * 不静默回退到别的账号 —— 那会让「钉定」名存实亡。
162
- */
163
- #pickPinned(accountId, modelId) {
164
- const entry = this.#pool.get(accountId, { withCredentials: true })
165
- if (entry === undefined) {
166
- throw Object.assign(
167
- new Error(`钉定的账号已不存在(可能已被删除)。请重新登录添加,或改选不带账号后缀的自动选号条目。`),
168
- { code: 'QUOTA' },
169
- )
170
- }
171
- if (entry.enabled !== true) {
172
- throw Object.assign(
173
- new Error(`钉定的账号「${entry.nickname}」已被停用。请在插件面板重新启用,或改选自动选号条目。`),
174
- { code: 'QUOTA' },
175
- )
176
- }
177
- const resetAt = entry.model_rate_limits?.[modelId]
178
- if (typeof resetAt === 'number' && resetAt > 0 && this.#now() < resetAt) {
179
- const at = new Date(resetAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
180
- throw Object.assign(
181
- new Error(
182
- `钉定的账号「${entry.nickname}」在模型「${modelId}」上处于限流期(至 ${at})。` +
183
- '可等待重置、在面板「清除限流」后重试,或改选自动选号条目换用其它账号。',
184
- ),
185
- { code: 'QUOTA' },
186
- )
187
- }
188
- if (!isUsableCredential(entry.credential)) {
189
- throw Object.assign(
190
- new Error(`钉定的账号「${entry.nickname}」凭据不可用,请重新登录。`),
191
- { code: 'AUTH' },
192
- )
193
- }
194
- return { entry, credential: entry.credential }
195
- }
196
-
197
- /** 拉 captcha 配置(60 秒 TTL;失败不缓存 —— 一次网络抖动不该让 sceneId 永久固化)。 */
198
- async #resolveCaptchaConfig() {
199
- const now = this.#now()
200
- if (this.#captchaConfig !== undefined && now - this.#captchaConfigAt < 60_000) return this.#captchaConfig
201
- try {
202
- const first = this.#pool.list({ withCredentials: true })[0]
203
- if (first?.credential !== undefined && typeof this.#minter.fetchConfig === 'function') {
204
- const fetched = await this.#minter.fetchConfig(first.credential)
205
- if (fetched !== undefined) {
206
- this.#captchaConfig = fetched
207
- this.#captchaConfigAt = now
208
- return fetched
209
- }
210
- }
211
- } catch {
212
- // 回退兜底值。
213
- }
214
- return ZCODE_CAPTCHA_FALLBACK
215
- }
216
-
217
- /** 产出一个 captcha param(串行 + 退避闸门)。 */
218
- async mintCaptcha(signal) {
219
- const cooldown = this.#backoff.remainingMs(this.#now())
220
- if (cooldown > 0) {
221
- throw new Error(
222
- `captcha 产出处于冷却中(连续 ${this.#backoff.failureStreak} 次失败),约 ${Math.ceil(cooldown / 1000)} 秒后可重试。` +
223
- '这通常意味着设备信誉不足(上游把无感验证降级为滑块),继续重试只会让信誉更差。',
224
- )
225
- }
226
- const config = await this.#resolveCaptchaConfig()
227
- try {
228
- const outcome = await this.#queue.run(() => this.#minter.mint(config, { signal }))
229
- this.#backoff.noteSuccess()
230
- if (outcome.interactive === true) {
231
- this.#log('[zcode] ⚠ captcha 被要求交互式验证(滑块/拼图)—— 设备信誉可能已下降')
232
- }
233
- return { param: outcome.param, region: config.region ?? 'cn' }
234
- } catch (error) {
235
- this.#backoff.noteFailure(this.#now())
236
- throw error
237
- }
238
- }
239
-
240
- /**
241
- * 执行一次模型调用。
242
- *
243
- * @param {{
244
- * options: any,
245
- * model?: any,
246
- * maxTokens?: number,
247
- * signal?: AbortSignal,
248
- * onRetry?: (info: { reason: string, attempt: number, message: string }) => void,
249
- * }} request
250
- * @returns {Promise<{
251
- * head: Array<any>,
252
- * decoder: { read(): Promise<{ done: boolean, value?: any }>, cancel(): Promise<void> } | undefined,
253
- * accountId: string,
254
- * model: string,
255
- * credential: any,
256
- * body: any,
257
- * }>}
258
- */
259
- async call(request) {
260
- let options = request.options
261
- /**
262
- * 钉定账号的两个来源(优先级:provider 路由 > 模型 id 后缀):
263
- *
264
- * 1. **provider 路由**(`request.pinnedAccountId`):每个账号一个独立
265
- * provider 栏位(`zcode-start-plan-acct-<id>`,像 workbuddy 一样),
266
- * 路由本身就把「哪个账号出额度」钉死;
267
- * 2. **模型 id 后缀**(`<base>@acct:<账号id>`,0.3.0 形态):保留兼容 ——
268
- * 旧会话里保存的钉定模型继续可用。
269
- *
270
- * 上游永远只见基础模型 id;选号不再按手动顺序轮换,只走钉定账号。
271
- */
272
- const routePin =
273
- typeof request.pinnedAccountId === 'string' && request.pinnedAccountId.trim().length > 0
274
- ? request.pinnedAccountId.trim()
275
- : null
276
- const idPin = parsePinnedModelId(options.model)
277
- const pinned = routePin !== null ? { accountId: routePin } : idPin
278
- const model = idPin === null ? options.model : idPin.baseModelId
279
- if (pinned !== null) {
280
- options = { ...options, model }
281
- if (typeof request.model?.id === 'string') {
282
- request = { ...request, model: { ...request.model, id: model } }
283
- }
284
- }
285
- const tried = new Set()
286
- let lastFailure = '所有账号在模型「' + model + '」上都已用尽或无可用权益'
287
- /**
288
- * 最近一次**额度类**失败的上游原文(含业务码)。
289
- *
290
- * ⚠ 必须带到最终报错里:否则用户只看到笼统的「已用尽」,而真正的原因
291
- * (`1005 exceed quota limit` / `1113 余额不足` / `200 但零内容`)被吞掉,
292
- * 排查时会误以为是插件 bug。
293
- */
294
- let lastQuotaDetail = ''
295
-
296
- for (let quotaRound = 0; quotaRound < QUOTA_SWITCH_MAX; quotaRound += 1) {
297
- /**
298
- * 选号:钉定模式只看指定账号(选不到直接报错,见 `#pickPinned`);
299
- * 自动模式按手动顺序取第一个可用账号,逐个试到有产出为止。
300
- */
301
- const picked = pinned === null ? this.#pool.pick(model, tried) : this.#pickPinned(pinned.accountId, model)
302
- if (picked === null) {
303
- const detail = lastQuotaDetail.length > 0 ? `最后一次上游响应:${lastQuotaDetail}。` : ''
304
- /**
305
- * 区分三种「选不到号」的情况 —— 用户该做的事完全不同:
306
- * ① 池子真的空 → 去登录
307
- * ② 池子有号但本模型都限流 → 等重置 / 换模型 / 领额度
308
- * ③ 本次请求已逐个试完 → 汇报试了几个
309
- * 统一报「账号池为空」会把人带去错误的排查方向(实测踩过)。
310
- */
311
- const total = this.#pool.list()
312
- const enabledCount = total.filter((entry) => entry.enabled).length
313
- let message
314
- if (total.length === 0) {
315
- message = '账号池为空。请先运行 `zcode-start-plan login` 添加 ZCode 账号。'
316
- } else if (tried.size === 0) {
317
- message = enabledCount === 0
318
- ? `账号池里有 ${total.length} 个账号,但全部被停用。用 \`zcode-start-plan enable <序号>\` 启用,或登录新账号。`
319
- : `模型「${model}」在 ${enabledCount} 个启用账号上都已限流(免费额度按自然日 UTC+8 结算)。` +
320
- `${detail}可等次日重置、换一个模型(config.models),或用 \`zcode-start-plan claim\` 领取当日额度。`
321
- } else {
322
- message = `${lastFailure}(本次已逐个尝试 ${tried.size} 个账号)。${detail}` +
323
- '免费额度按自然日结算,请等待重置、领取当日额度(node bin/cli.mjs claim)或用 `zcode-start-plan login` 添加新账号。'
324
- }
325
- throw Object.assign(new Error(message), { code: 'QUOTA' })
326
- }
327
- const accountId = picked.entry.id
328
- const credential = picked.credential
329
- /**
330
- * 钉定模式下额度耗尽:如实报错而不是换号 —— 换号会让「钉定」名存实亡
331
- * (用户选了「GLM-5.3 · 主号」就该知道失败意味着主号的额度尽了)。
332
- */
333
- const failPinnedQuota = (upstreamText) => {
334
- const detail = upstreamText.length > 0 ? `上游响应:${upstreamText}。` : ''
335
- throw Object.assign(
336
- new Error(
337
- `钉定的账号「${picked.entry.nickname}」在模型「${model}」上的额度已用尽(免费额度按自然日 UTC+8 结算)。` +
338
- `${detail}可等次日重置、在面板把其它账号置顶后改选,或改选不带账号后缀的自动选号条目。`,
339
- ),
340
- { code: 'QUOTA' },
341
- )
342
- }
343
- const captchaKey = `${accountId}|${model}`
344
- let probeRejected = false
345
- let switched = false
346
-
347
- const supportsImages = request.model?.inputModalities?.includes?.('image') ?? true
348
- /**
349
- * 宿主契约:DSH 的 image 块是持久引用(`{ type: 'image', attachment: ref }`),
350
- * 字节须经附件服务 `readImageRequest` 解析(官方 `dsh-llm-deepseek` 同款链路)。
351
- * 附件服务不可用 / 解析失败时 `resolvedImages` 缺项,`convertContent` 用
352
- * 占位文本替换 —— 不再静默丢弃。
353
- */
354
- const resolvedImages = await resolveImages(options.messages, {
355
- resolveAttachments: this.#resolveDeps?.resolveAttachments,
356
- signal: request.signal,
357
- })
358
-
359
- const body = buildUpstreamBody({
360
- options,
361
- cwd: this.#cwd,
362
- provider: 'zcode-start-plan',
363
- supportsImages,
364
- resolvedImages,
365
- maxTokens: request.maxTokens,
366
- })
367
-
368
- for (let attempt = 0; ; attempt += 1) {
369
- if (request.signal?.aborted === true) {
370
- throw Object.assign(new Error('请求已取消'), { code: 'ABORTED' })
371
- }
372
- const knownRequired = (this.#captchaRequiredUntil.get(captchaKey) ?? 0) > this.#now()
373
- const needCaptcha = knownRequired || probeRejected
374
- let captcha
375
- if (needCaptcha) {
376
- try {
377
- captcha = await this.mintCaptcha(request.signal)
378
- } catch (error) {
379
- throw Object.assign(
380
- new Error(
381
- `captcha 产出失败:${error instanceof Error ? error.message : String(error)}。` +
382
- '请以 --remote-debugging-port 启动宿主(DSH 桌面端),或把 config.captcha.mode 设为 "manual"。',
383
- ),
384
- { code: 'CAPTCHA_FAILED' },
385
- )
386
- }
387
- }
388
-
389
- const headers = buildZcodeHeaders(credential, {
390
- authorization: `Bearer ${credential.zcode_jwt}`,
391
- ...(captcha !== undefined ? { captcha: { param: captcha.param, region: captcha.region } } : {}),
392
- })
393
-
394
- let response
395
- try {
396
- response = await this.#gate.run(model, () =>
397
- this.#fetchImpl(ZCODE_PLAN_MESSAGES_URL, {
398
- method: 'POST',
399
- headers,
400
- body: JSON.stringify(body),
401
- signal: request.signal,
402
- }),
403
- )
404
- } catch (error) {
405
- if (request.signal?.aborted === true) throw Object.assign(new Error('请求已取消'), { code: 'ABORTED' })
406
- throw Object.assign(new Error(`上游请求失败:${error instanceof Error ? error.message : String(error)}`), {
407
- code: 'PROVIDER_ERROR',
408
- })
409
- }
410
-
411
- if (!response.ok) {
412
- const text = await response.text().catch(() => '')
413
- const kind = classifyUpstreamError(response.status, text)
414
- this.#log(`[zcode] 账号 ${accountId} 上游 ${response.status}(${kind}):${text.slice(0, 200)}`)
415
-
416
- if (kind === 'quota') {
417
- this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
418
- this.#pool.noteError(accountId, describeUpstreamError(response.status, text))
419
- if (pinned !== null) failPinnedQuota(text.slice(0, 200))
420
- tried.add(accountId)
421
- switched = true
422
- break
423
- }
424
- if (kind === 'concurrency' && attempt < CONCURRENCY_RETRY_MAX) {
425
- const waitMs = concurrencyRetryDelayMs(attempt)
426
- this.#log(`[zcode] 并发限流(3009),退避 ${waitMs}ms 后重试(不换号)`)
427
- request.onRetry?.({ reason: 'concurrency', attempt, message: describeUpstreamError(response.status, text) })
428
- await sleep(waitMs)
429
- continue
430
- }
431
- if (kind === 'captcha' && attempt < 2) {
432
- if (captcha === undefined) {
433
- this.#captchaRequiredUntil.set(captchaKey, this.#now() + CAPTCHA_REQUIRED_TTL_MS)
434
- this.#log('[zcode] 上游要求 captcha(3007)→ 本轮才产出并重试')
435
- } else {
436
- this.#log('[zcode] captcha 被拒(3007),换新 param 重试')
437
- }
438
- probeRejected = true
439
- request.onRetry?.({ reason: 'captcha', attempt, message: describeUpstreamError(response.status, text) })
440
- continue
441
- }
442
- if (kind === 'risk') {
443
- throw Object.assign(new Error(describeUpstreamError(response.status, text)), { code: 'RATE_LIMIT' })
444
- }
445
- if (kind === 'auth') {
446
- this.#pool.noteError(accountId, describeUpstreamError(response.status, text))
447
- throw Object.assign(new Error(describeUpstreamError(response.status, text)), { code: 'AUTH' })
448
- }
449
- throw Object.assign(new Error(describeUpstreamError(response.status, text)), { code: 'PROVIDER_ERROR' })
450
- }
451
-
452
- if (response.body === null) {
453
- this.#log(`[zcode] 账号 ${accountId} 返回 200 但 body 为空 → 视为无权益,换号`)
454
- this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
455
- if (pinned !== null) failPinnedQuota('HTTP 200 但响应体为空')
456
- tried.add(accountId)
457
- switched = true
458
- break
459
- }
460
-
461
- const head = await readContentHead(response.body, {
462
- contentType: response.headers.get('content-type') ?? undefined,
463
- })
464
- /**
465
- * ⚠ **HTTP 200 里的业务错误**:本渠道实测会返回
466
- * `200 + application/json + {"code":1005,"msg":"exceed quota limit"}`。
467
- * 必须先按错误表处置(该换号就换号、该报错就报错),否则会被当成
468
- * 「零内容 → 无权益」,既丢掉真正的原因,也无法据此做正确决策。
469
- */
470
- if (head.upstreamError !== undefined) {
471
- const text = head.upstreamError.text
472
- const kind = classifyUpstreamError(200, text)
473
- this.#log(`[zcode] 账号 ${accountId} 在 HTTP 200 里返回业务错误(${kind}):${text.slice(0, 200)}`)
474
-
475
- if (kind === 'quota') {
476
- lastQuotaDetail = text.slice(0, 200)
477
- this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
478
- this.#pool.noteError(accountId, describeUpstreamError(200, text))
479
- if (pinned !== null) failPinnedQuota(text.slice(0, 200))
480
- tried.add(accountId)
481
- switched = true
482
- break
483
- }
484
- if (kind === 'concurrency' && attempt < CONCURRENCY_RETRY_MAX) {
485
- const waitMs = concurrencyRetryDelayMs(attempt)
486
- this.#log(`[zcode] 并发限流(3009,HTTP 200),退避 ${waitMs}ms 后重试(不换号)`)
487
- request.onRetry?.({ reason: 'concurrency', attempt, message: describeUpstreamError(200, text) })
488
- await sleep(waitMs)
489
- continue
490
- }
491
- if (kind === 'captcha' && attempt < 2) {
492
- if (captcha === undefined) this.#captchaRequiredUntil.set(captchaKey, this.#now() + CAPTCHA_REQUIRED_TTL_MS)
493
- probeRejected = true
494
- request.onRetry?.({ reason: 'captcha', attempt, message: describeUpstreamError(200, text) })
495
- continue
496
- }
497
- /** 风控 / 鉴权 / 其它:如实报错,不重试。 */
498
- const code = kind === 'risk' ? 'RATE_LIMIT' : kind === 'auth' ? 'AUTH' : 'PROVIDER_ERROR'
499
- this.#pool.noteError(accountId, describeUpstreamError(200, text))
500
- throw Object.assign(new Error(describeUpstreamError(200, text)), { code })
501
- }
502
-
503
- if (!head.hasContent) {
504
- this.#log(`[zcode] 账号 ${accountId} 在模型 ${model} 上返回 200 但零内容(${head.elapsedMs}ms)→ 视为无权益,换号`)
505
- this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
506
- this.#pool.noteError(accountId, `200 但零内容(${head.elapsedMs}ms)`)
507
- if (pinned !== null) failPinnedQuota(`HTTP 200 但零内容(${head.elapsedMs}ms)`)
508
- tried.add(accountId)
509
- switched = true
510
- break
511
- }
512
-
513
- if (captcha === undefined) {
514
- /** 没带 captcha 就成功 ⇒ 上游当前不要验证,清掉记忆回到最省路径。 */
515
- this.#captchaRequiredUntil.delete(captchaKey)
516
- }
517
- this.#log(
518
- `[zcode] ${accountId} × ${model} 命中(首帧 ${head.elapsedMs}ms,${captcha === undefined ? '未带 captcha' : '带 captcha'})`,
519
- )
520
- return { head: head.head, decoder: head.decoder, accountId, model, credential, body }
521
- }
522
-
523
- if (!switched) throw Object.assign(new Error('请求编排内部状态异常:内层循环意外退出'), { code: 'PROVIDER_ERROR' })
524
- lastFailure = `模型「${model}」的可用账号已用尽`
525
- }
526
-
527
- throw Object.assign(new Error(`${lastFailure}(已尝试 ${tried.size} 个账号,上限 ${QUOTA_SWITCH_MAX})。`), { code: 'QUOTA' })
528
- }
529
- }
530
-
531
- /** 兜底模型表(面板/工具在拉不到上游目录时用)。 */
532
- export { ZCODE_FALLBACK_MODELS }
1
+ /**
2
+ * ZCode 免费 plan 通道的一次请求编排(切号 / captcha / 退避的唯一实现)。
3
+ *
4
+ * ```
5
+ * 选号(手动顺序,跳过该模型限流中的账号)
6
+ * → 本轮是否需要 captcha("要了才取":被 3007 拒过才产出)
7
+ * → 组 body(官方身份块 + 日期块 + tools 断点)
8
+ * → 直发上游
9
+ * → 200:先读「是否真的产出了内容」
10
+ * ├─ 有内容 → 交给调用方流式消费(此后禁止换号)
11
+ * └─ 无内容 → 标记该账号×模型 → 换号重试(调用方零 chunk)
12
+ * → 非 200:按错误表处置
13
+ * ├─ 额度用尽 → 标号 + 换号
14
+ * ├─ 并发限流 → 打忙标记 + 退避重试(穷尽后换号,钉定模式除外)
15
+ * ├─ captcha 失败 → 换新 captcha 重试
16
+ * └─ 风控 / 鉴权 / 其它 → 如实报错(不重试)
17
+ * ```
18
+ *
19
+ * ## 两条不可动摇的约定
20
+ *
21
+ * 1. **`emitted` 闸**:一旦把 chunk 交给调用方,绝不再换号/重试(防两份输出)。
22
+ * 2. **每轮重试都必须重新 mint captcha**:param 一次性,复用必 3007。
23
+ */
24
+
25
+ import { buildUpstreamBody, resolveImages } from './anthropic-body.js'
26
+ import {
27
+ CONCURRENCY_RETRY_BASE_MS,
28
+ CONCURRENCY_RETRY_MAX,
29
+ DEFAULT_HEAD_TIMEOUT_MS,
30
+ DEFAULT_READ_TIMEOUT_MS,
31
+ RISK_BLOCKED_CODE,
32
+ QUOTA_SWITCH_MAX,
33
+ classifyUpstreamError,
34
+ codeForUpstreamKind,
35
+ concurrencyRetryDelayMs,
36
+ describeUpstreamError,
37
+ } from './errors.js'
38
+ import { isHeadTimeoutError, readContentHead } from './sse.js'
39
+ import { buildZcodeHeaders, ZCODE_PLAN_MESSAGES_URL, ZCODE_FALLBACK_MODELS, nextUtc8DayStartMs } from './upstream.js'
40
+ import { ZCODE_CAPTCHA_FALLBACK } from './captcha/sdk-page.js'
41
+ import { launchCommand } from './captcha/minter.js'
42
+ import { parsePinnedModelId } from './pinned-model.js'
43
+ import { isUsableCredential } from './pool.js'
44
+
45
+ /** 「该账号×模型当前需要 captcha」的记忆时长(避免每条消息都白吃一次 3007)。 */
46
+ const CAPTCHA_REQUIRED_TTL_MS = 2 * 60_000
47
+
48
+ /**
49
+ * 零内容短窗(1.0.1 审计修复):首次 `200 + 零内容` 只打这个时长的限流标记,
50
+ * 过期自动恢复。窗口内再吃一次零内容才升级为「当日用尽」。
51
+ * 10 分钟 = 上游瞬时抖动的典型恢复尺度,远小于误判一整天的代价。
52
+ */
53
+ const EMPTY_CONTENT_WINDOW_MS = 10 * 60_000
54
+
55
+ /**
56
+ * 上游黑洞的默认分类(issue #4)。
57
+ *
58
+ * 额度用尽之后,本渠道的上游对该账号**不再出流**:既不回 4xx,也不产出任何事件。
59
+ * 这类失败必须落成 `TIMEOUT` 而不是 `PROVIDER_ERROR`:
60
+ * - `TIMEOUT` 在 `fallback.js` 的回退名单里,回退链路才有机会**静默改道**;
61
+ * - 文案能说清是「没拿到内容」,而不是笼统的「超时或不可用」。
62
+ *
63
+ * 可在 config 里经 `headTimeoutMs` / `readTimeoutMs` 覆盖(见 index.js 的 config schema)。
64
+ */
65
+ const TIMEOUT_CODE = 'TIMEOUT'
66
+
67
+ /** 串行队列:captcha 产出是设备级的,并发无益且会互相踩页面。 */
68
+ class SerialQueue {
69
+ #tail = Promise.resolve()
70
+ run(task) {
71
+ const next = this.#tail.then(task, task)
72
+ /** 队列本身不因一次失败而卡死。 */
73
+ this.#tail = next.catch(() => {})
74
+ return next
75
+ }
76
+ }
77
+
78
+ /** captcha 产出失败的指数退避闸门(保护设备信誉)。 */
79
+ class CaptchaBackoff {
80
+ #streak = 0
81
+ #until = 0
82
+ noteFailure(now = Date.now()) {
83
+ this.#streak += 1
84
+ const cooldown = Math.min(60_000 * 2 ** (this.#streak - 1), 30 * 60_000)
85
+ this.#until = now + cooldown
86
+ return cooldown
87
+ }
88
+ noteSuccess() {
89
+ this.#streak = 0
90
+ this.#until = 0
91
+ }
92
+ remainingMs(now = Date.now()) {
93
+ return Math.max(0, this.#until - now)
94
+ }
95
+ get failureStreak() {
96
+ return this.#streak
97
+ }
98
+ }
99
+
100
+ /** 发车闸门:全局串行 + 按模型间隔(GLM-5.3 需 350ms,Flash 不需要)。 */
101
+ class ModelGate {
102
+ #chain = Promise.resolve()
103
+ #lastVerdict = { model: '', at: 0 }
104
+ #gaps
105
+ constructor(gaps) {
106
+ this.#gaps = gaps
107
+ }
108
+ async run(model, task) {
109
+ const previous = this.#chain
110
+ let release
111
+ this.#chain = new Promise((resolve) => {
112
+ release = resolve
113
+ })
114
+ try {
115
+ await previous
116
+ const gap = this.#gaps[String(model).toLowerCase()] ?? 0
117
+ if (gap > 0 && this.#lastVerdict.model === model) {
118
+ const wait = gap - (Date.now() - this.#lastVerdict.at)
119
+ if (wait > 0) await sleep(wait)
120
+ }
121
+ try {
122
+ return await task()
123
+ } finally {
124
+ this.#lastVerdict = { model, at: Date.now() }
125
+ }
126
+ } finally {
127
+ release()
128
+ }
129
+ }
130
+ }
131
+
132
+ function sleep(ms) {
133
+ return new Promise((resolve) => setTimeout(resolve, ms))
134
+ }
135
+
136
+ /** 正数就用它,其余一律回落缺省(`0` / `NaN` / 负值 / 非数字都算「没配」)。 */
137
+ function positiveOr(value, fallback) {
138
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : fallback
139
+ }
140
+
141
+ /**
142
+ * 一次「zcode-plan」调用的可复用客户端。
143
+ *
144
+ * 进程内应是**单实例**(captcha 产出、闸门、需求记忆都是设备级/全局状态)。
145
+ */
146
+ export class ZcodePlanClient {
147
+ #pool
148
+ #minter
149
+ #fetchImpl
150
+ #log
151
+ #now
152
+ #cwd
153
+ #queue = new SerialQueue()
154
+ #backoff = new CaptchaBackoff()
155
+ #gate = new ModelGate({ 'glm-5.3': 350 })
156
+ #captchaRequiredUntil = new Map()
157
+ #captchaConfig
158
+ #captchaConfigAt = 0
159
+ /** 附件服务回调(`() => ctx.get('attachments')`,可选):图片引用 → 请求字节。 */
160
+ #resolveDeps
161
+ /** 并发限流退避基数(生产 1500ms;测试可注入小值,避免用例跑 4.5 秒真实退避)。 */
162
+ #concurrencyBaseMs
163
+ /** 首内容超时 / 流内静默超时(issue #4;缺省 90s / 180s,生产远小于宿主 ~300s)。 */
164
+ #headTimeoutMs
165
+ #readTimeoutMs
166
+ // 零内容两级证据的计数**不在本类**:1.0.1 修复把它挪进了 pool 的
167
+ // `noteEmptyContentWatch / isEmptyContentWatched`(软优先观察窗)。
168
+ // 原因:放进 `model_rate_limits`(当日硬过滤表)会让唯一账号在短窗内
169
+ // 被 pick 硬过滤掉 → 第二次零内容永远发生不了 → 升级逻辑形同虚设。
170
+
171
+ constructor(options) {
172
+ this.#pool = options.pool
173
+ this.#minter = options.minter
174
+ this.#fetchImpl = options.fetchImpl ?? globalThis.fetch
175
+ this.#log = options.log ?? (() => {})
176
+ this.#now = options.now ?? (() => Date.now())
177
+ this.#cwd = options.cwd ?? process.cwd()
178
+ this.#captchaConfig = options.captchaConfig
179
+ this.#resolveDeps = options
180
+ this.#concurrencyBaseMs =
181
+ typeof options.concurrencyRetryBaseMs === 'number' && options.concurrencyRetryBaseMs >= 0
182
+ ? options.concurrencyRetryBaseMs
183
+ : CONCURRENCY_RETRY_BASE_MS
184
+ this.#headTimeoutMs = positiveOr(options.headTimeoutMs, DEFAULT_HEAD_TIMEOUT_MS)
185
+ this.#readTimeoutMs = positiveOr(options.readTimeoutMs, DEFAULT_READ_TIMEOUT_MS)
186
+ }
187
+
188
+ /** 供状态工具读取观测值。 */
189
+ observability() {
190
+ return {
191
+ captchaFailureStreak: this.#backoff.failureStreak,
192
+ captchaCooldownRemainingMs: this.#backoff.remainingMs(this.#now()),
193
+ captchaRequiredAccounts: [...this.#captchaRequiredUntil.keys()].length,
194
+ }
195
+ }
196
+
197
+ /**
198
+ * 钉定模式选号:只取指定账号,**绝不换号**。
199
+ *
200
+ * 与 `pool.pick` 的差异:不按手动顺序、不看其他账号;但同样跳过「该模型
201
+ * 限流中」的账号 —— 限流标记意味着额度已尽,硬发只会吃一个 1005。
202
+ * 账号缺失 / 停用 / 凭据不可用 / 限流中都以**明确报错**收场(各自给出路),
203
+ * 不静默回退到别的账号 —— 那会让「钉定」名存实亡。
204
+ */
205
+ #pickPinned(accountId, modelId) {
206
+ const entry = this.#pool.get(accountId, { withCredentials: true })
207
+ if (entry === undefined) {
208
+ throw Object.assign(
209
+ new Error(`钉定的账号已不存在(可能已被删除)。请重新登录添加,或改选不带账号后缀的自动选号条目。`),
210
+ { code: 'QUOTA' },
211
+ )
212
+ }
213
+ if (entry.enabled !== true) {
214
+ throw Object.assign(
215
+ new Error(`钉定的账号「${entry.nickname}」已被停用。请在插件面板重新启用,或改选自动选号条目。`),
216
+ { code: 'QUOTA' },
217
+ )
218
+ }
219
+ const resetAt = entry.model_rate_limits?.[modelId]
220
+ if (typeof resetAt === 'number' && resetAt > 0 && this.#now() < resetAt) {
221
+ const at = new Date(resetAt).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit' })
222
+ throw Object.assign(
223
+ new Error(
224
+ `钉定的账号「${entry.nickname}」在模型「${modelId}」上处于限流期(至 ${at})。` +
225
+ '可等待重置、在面板「清除限流」后重试,或改选自动选号条目换用其它账号。',
226
+ ),
227
+ { code: 'QUOTA' },
228
+ )
229
+ }
230
+ /**
231
+ * ⚠ **刻意不看 `last_error`**(2026-11-10 与 pool.candidates 同步删除该判据)。
232
+ *
233
+ * `last_error` 是历史文本、无时间戳:额度次日恢复后那行仍写着 1005,
234
+ * 于是钉定会**永久**卡在「已判额度用尽」上,直到用户手动清除。
235
+ * 权威判据是上游本次响应(真耗尽 → 1005 → 写入当日硬标记,由上面
236
+ * `model_rate_limits` 那段挡住),代价只是多付一次往返。
237
+ */
238
+ if (!isUsableCredential(entry.credential)) {
239
+ throw Object.assign(
240
+ new Error(`钉定的账号「${entry.nickname}」凭据不可用,请重新登录。`),
241
+ { code: 'AUTH' },
242
+ )
243
+ }
244
+ return { entry, credential: entry.credential }
245
+ }
246
+
247
+ /**
248
+ * 3009 并发限流的统一处置(非 200 与 HTTP-200 业务错误两条路径共用)。
249
+ *
250
+ * 流程:立刻打 60s 忙标记(让**并行发起**的其它统一选号请求直接路由到空闲
251
+ * 账号,而不是跟着一起撞这个忙账号)→ 未穷尽退避则休眠后原地重试 →
252
+ * 穷尽后换号;钉定模式绝不换号,如实报错。
253
+ *
254
+ * @returns {Promise<'retry'|'switch'|Error>} retry=已休眠,原地重试;
255
+ * switch=换号;Error=钉定模式下的终态异常(调用方直接 throw)。
256
+ */
257
+ async #handleConcurrency({ accountId, model, attempt, pinned, picked, status, text, onRetry, fromHttp200 = false }) {
258
+ const where = fromHttp200 ? ',HTTP 200' : ''
259
+ this.#pool.markModelBusy?.(accountId, model)
260
+ if (attempt < CONCURRENCY_RETRY_MAX) {
261
+ const waitMs = concurrencyRetryDelayMs(attempt, this.#concurrencyBaseMs)
262
+ this.#log(`[zcode] 并发限流(3009${where}),退避 ${waitMs}ms 后重试(穷尽后换号)`)
263
+ onRetry?.({ reason: 'concurrency', attempt, message: describeUpstreamError(status, text) })
264
+ await sleep(waitMs)
265
+ return 'retry'
266
+ }
267
+ /** 退避穷尽仍 3009 → 换下一个账号(钉定模式绝不换号,如实报错)。 */
268
+ this.#pool.noteError(accountId, describeUpstreamError(status, text))
269
+ if (pinned !== null) {
270
+ return Object.assign(
271
+ new Error(
272
+ `钉定的账号「${picked.entry.nickname}」在模型「${model}」上持续并发限流(3009)。` +
273
+ '该账号可能正被其它会话占用:可稍后重试,或改选自动选号条目换用其它账号。',
274
+ ),
275
+ { code: 'RATE_LIMIT' },
276
+ )
277
+ }
278
+ this.#log(`[zcode] 账号 ${accountId} 退避穷尽仍 3009${where} → 换号`)
279
+ return 'switch'
280
+ }
281
+
282
+ /**
283
+ * 3012 风控的**自动清除限流**(用户明确要求的误判救济)。
284
+ *
285
+ * 3012 常常是一次误判 —— 该账号×模型未必真的耗尽额度,但此前可能已经被
286
+ * 打过 `model_rate_limits` 硬标记(零内容升级 / 早前的 1005)。若不清掉,
287
+ * 用户「稍后重试」时会在选号阶段就被自己的标记挡住,看起来像额度问题,
288
+ * 而真正的原因是风控 —— 面板文案与对话结论再次互相矛盾。
289
+ *
290
+ * 所以拿到 3012 就立刻调面板「清除限流」的**同一个入口**
291
+ * (`pool.clearModelRateLimits`),对该账号、**该模型**清标记,让账号能立刻
292
+ * 重试,而不是等用户去点按钮。
293
+ *
294
+ * ⚠ 只清该模型、只清该账号;**不**清除其它账号或其它模型的标记 ——
295
+ * 那些标记各自有其上游依据。
296
+ * ⚠ 依旧**不重试**(在抛错之前调用):风控有账号级累积惩罚
297
+ * (30 分钟 → 24 小时 → 停用),清除标记是为了「用户手动重试时不被自己挡住」,
298
+ * 不是为了自动再撞一次。
299
+ *
300
+ * 任何一步失败都只记日志,绝不让「救济动作」变成新的报错源。
301
+ */
302
+ #clearRateLimitOnRisk(accountId, modelId, status, text) {
303
+ const message = describeUpstreamError(status, text)
304
+ try {
305
+ const removed = this.#pool.clearModelRateLimits?.(accountId, [modelId]) ?? 0
306
+ this.#pool.noteError?.(accountId, message)
307
+ this.#pool.noteRouted?.(accountId, modelId, { outcome: 'attempting', reason: '3012 风控拦截' })
308
+ this.#log(
309
+ `[zcode] 账号 ${accountId} × ${modelId} 触发 3012 风控视为误判,已自动清除限流标记(${removed} 项);` +
310
+ '本次仍不重试(连续触发有账号冷却惩罚)',
311
+ )
312
+ } catch (error) {
313
+ this.#log(`[zcode] 3012 风控后自动清除限流标记失败(忽略):${error instanceof Error ? error.message : String(error)}`)
314
+ }
315
+ return message
316
+ }
317
+
318
+ /** 拉 captcha 配置(60 秒 TTL;失败不缓存 —— 一次网络抖动不该让 sceneId 永久固化)。 */
319
+ async #resolveCaptchaConfig() {
320
+ const now = this.#now()
321
+ if (this.#captchaConfig !== undefined && now - this.#captchaConfigAt < 60_000) return this.#captchaConfig
322
+ try {
323
+ const first = this.#pool.list({ withCredentials: true })[0]
324
+ if (first?.credential !== undefined && typeof this.#minter.fetchConfig === 'function') {
325
+ const fetched = await this.#minter.fetchConfig(first.credential)
326
+ if (fetched !== undefined) {
327
+ this.#captchaConfig = fetched
328
+ this.#captchaConfigAt = now
329
+ return fetched
330
+ }
331
+ }
332
+ } catch {
333
+ // 回退兜底值。
334
+ }
335
+ return ZCODE_CAPTCHA_FALLBACK
336
+ }
337
+
338
+ /** 产出一个 captcha param(串行 + 退避闸门)。 */
339
+ async mintCaptcha(signal) {
340
+ const cooldown = this.#backoff.remainingMs(this.#now())
341
+ if (cooldown > 0) {
342
+ throw new Error(
343
+ `captcha 产出处于冷却中(连续 ${this.#backoff.failureStreak} 次失败),约 ${Math.ceil(cooldown / 1000)} 秒后可重试。` +
344
+ '这通常意味着设备信誉不足(上游把无感验证降级为滑块),继续重试只会让信誉更差。',
345
+ )
346
+ }
347
+ const config = await this.#resolveCaptchaConfig()
348
+ try {
349
+ const outcome = await this.#queue.run(() => this.#minter.mint(config, { signal }))
350
+ this.#backoff.noteSuccess()
351
+ if (outcome.interactive === true) {
352
+ this.#log('[zcode] ⚠ captcha 被要求交互式验证(滑块/拼图)—— 设备信誉可能已下降')
353
+ }
354
+ return { param: outcome.param, region: config.region ?? 'cn' }
355
+ } catch (error) {
356
+ this.#backoff.noteFailure(this.#now())
357
+ throw error
358
+ }
359
+ }
360
+
361
+ /**
362
+ * 执行一次模型调用。
363
+ *
364
+ * @param {{
365
+ * options: any,
366
+ * model?: any,
367
+ * maxTokens?: number,
368
+ * signal?: AbortSignal,
369
+ * onRetry?: (info: { reason: string, attempt: number, message: string }) => void,
370
+ * }} request
371
+ * @returns {Promise<{
372
+ * head: Array<any>,
373
+ * decoder: { read(): Promise<{ done: boolean, value?: any }>, cancel(): Promise<void> } | undefined,
374
+ * accountId: string,
375
+ * model: string,
376
+ * credential: any,
377
+ * body: any,
378
+ * }>}
379
+ */
380
+ async call(request) {
381
+ let options = request.options
382
+ /**
383
+ * 钉定账号的两个来源(优先级:provider 路由 > 模型 id 后缀):
384
+ *
385
+ * 1. **provider 路由**(`request.pinnedAccountId`):每个账号一个独立
386
+ * provider 栏位(`zcode-start-plan-acct-<id>`,像 workbuddy 一样),
387
+ * 路由本身就把「哪个账号出额度」钉死;
388
+ * 2. **模型 id 后缀**(`<base>@acct:<账号id>`,0.3.0 形态):保留兼容 ——
389
+ * 旧会话里保存的钉定模型继续可用。
390
+ *
391
+ * 上游永远只见基础模型 id;选号不再按手动顺序轮换,只走钉定账号。
392
+ */
393
+ const routePin =
394
+ typeof request.pinnedAccountId === 'string' && request.pinnedAccountId.trim().length > 0
395
+ ? request.pinnedAccountId.trim()
396
+ : null
397
+ const idPin = parsePinnedModelId(options.model)
398
+ const pinned = routePin !== null ? { accountId: routePin } : idPin
399
+ const model = idPin === null ? options.model : idPin.baseModelId
400
+ if (pinned !== null) {
401
+ options = { ...options, model }
402
+ if (typeof request.model?.id === 'string') {
403
+ request = { ...request, model: { ...request.model, id: model } }
404
+ }
405
+ }
406
+ const tried = new Set()
407
+ let lastFailure = '所有账号在模型「' + model + '」上都已用尽或无可用权益'
408
+ /**
409
+ * 本轮编排里每个账号的失败计数(key = 账号 id)。
410
+ *
411
+ * ⚠ 0.9.9 韧性语义:统一选号下,**同一账号连续失败 2 次(无论错误类)就
412
+ * 换下一个账号**。此前只有 quota/concurrency/captcha 会换号,`other`
413
+ * (500、网络抖动、上游临时故障)与 `auth` 当场 throw —— 而宿主压缩
414
+ * (compaction)的摘要是**一次性直调**(不走 agent-loop 重试瀑布,失败仅
415
+ * warn 后继续主请求),同一坏账号会被压缩与主请求各撞一次,两次都不换号
416
+ * ⇒ 整轮失败、对话被阻断(真实报障:压缩时额度恰好用完)。
417
+ * 钉定模式不受影响:钉定本来就只有一个账号,失败如实报错。
418
+ */
419
+ const accountFailCounts = new Map()
420
+ /**
421
+ * 换轮原因(决定「选不到号」与最终报错的**错误码**与出路提示):
422
+ * `'quota'` 额度用尽 / `'concurrency'` 并发限流 3009 / `'timeout'` 上游黑洞(不出流)/
423
+ * `'other'` 其它(500、凭据失效、网络抖动)。
424
+ *
425
+ * ⚠ 初值 `'none'`:以前是 `'quota'`,结果「一次都没换过轮就选不到号」
426
+ * (池子空 / 账号已被额度前置检查挡掉)会被**误标**成 quota —— 文案与
427
+ * 错误码都跟着错。初值必须表达「上一轮没发生过失败」。
428
+ */
429
+ let lastSwitchReason = 'none'
430
+ /**
431
+ * 统一选号下同一账号的失败容忍次数(无论错误类;见 accountFailCounts 注释)。
432
+ * 2 = 同一账号撞两次就换下一个 —— 第一次可能是该账号的偶发问题,
433
+ * 第二次还在它身上失败就不再给它机会(凭据类 401/1002 换号也无妨:
434
+ * 下次轮到它时依旧失败,只是不再阻断其它账号)。
435
+ */
436
+ const PER_ACCOUNT_FAIL_MAX = 2
437
+ /**
438
+ * 最近一次**额度类**失败的上游原文(含业务码)。
439
+ *
440
+ * ⚠ 必须带到最终报错里:否则用户只看到笼统的「已用尽」,而真正的原因
441
+ * (`1005 exceed quota limit` / `1113 余额不足` / `200 但零内容`)被吞掉,
442
+ * 排查时会误以为是插件 bug。
443
+ */
444
+ let lastQuotaDetail = ''
445
+
446
+ for (let quotaRound = 0; quotaRound < QUOTA_SWITCH_MAX; quotaRound += 1) {
447
+ /**
448
+ * 选号:钉定模式只看指定账号(选不到直接报错,见 `#pickPinned`);
449
+ * 自动模式按选号顺序(默认 `expiry`,快过期先用)逐个试到有产出为止。
450
+ */
451
+ const picked =
452
+ pinned === null ? this.#pool.pick(model, tried) : this.#pickPinned(pinned.accountId, model)
453
+ if (picked === null) {
454
+ const detail = lastQuotaDetail.length > 0 ? `最后一次上游响应:${lastQuotaDetail}。` : ''
455
+ /**
456
+ * 区分三种「选不到号」的情况 —— 用户该做的事完全不同:
457
+ * ① 池子真的空 → 去登录
458
+ * ② 池子有号但本模型都限流 → 等重置 / 换模型 / 领额度
459
+ * ③ 本次请求已逐个试完 → 汇报试了几个
460
+ * 统一报「账号池为空」会把人带去错误的排查方向(实测踩过)。
461
+ */
462
+ const total = this.#pool.list().length
463
+ const enabledCount = this.#pool.list().filter((entry) => entry.enabled).length
464
+ let message
465
+ if (total === 0) {
466
+ message = '账号池为空。请先运行 `zcode-start-plan login` 添加 ZCode 账号。'
467
+ } else if (tried.size === 0) {
468
+ if (enabledCount === 0) {
469
+ message = `账号池里有 ${total} 个账号,但全部被停用。用 \`zcode-start-plan enable <序号>\` 启用,或登录新账号。`
470
+ } else if (lastSwitchReason === 'concurrency') {
471
+ message =
472
+ `模型「${model}」的 ${enabledCount} 个启用账号当前都在并发限流中(3009,忙标记 60s 内自动过期)。` +
473
+ `${detail}稍等片刻重试即可,无需等待额度重置。`
474
+ } else {
475
+ message = `模型「${model}」在 ${enabledCount} 个启用账号上都已限流(免费额度按自然日 UTC+8 结算)。` +
476
+ `${detail}可等次日重置、换一个模型(config.models),或用 \`zcode-start-plan claim\` 领取当日额度。`
477
+ }
478
+ } else {
479
+ const guidance = lastSwitchReason === 'concurrency'
480
+ ? '并发限流是瞬态的,请稍后重试;或登录新账号。'
481
+ : lastSwitchReason === 'auth'
482
+ ? '凭据失效需重新登录该账号(`zcode-start-plan login`),等待额度重置不会解决它。'
483
+ : lastSwitchReason === 'timeout'
484
+ ? '上游没给出任何内容(可能额度用尽,也可能是上游临时故障):可稍后重试、换一个模型,或领取当日额度。'
485
+ : '免费额度按自然日结算,请等待重置、领取当日额度(node bin/cli.mjs claim)或用 `zcode-start-plan login` 添加新账号。'
486
+ message = `${lastFailure}(本次已逐个尝试 ${tried.size} 个账号)。${detail}${guidance}`
487
+ }
488
+ /**
489
+ * 选不到号的错误码必须**保真**:3009 是瞬态、黑洞是 TIMEOUT(两者都在
490
+ * 回退名单里),风控 / 凭据失效则各有独立码。`'none'`(一次都没换过轮,
491
+ * 例如池子空或被停用)沿用历史的 QUOTA —— 它代表「权益层面不可用」。
492
+ */
493
+ const pickFailureCode = codeForUpstreamKind(lastSwitchReason === 'none' ? 'quota' : lastSwitchReason)
494
+ throw Object.assign(new Error(message), { code: pickFailureCode })
495
+ }
496
+ const accountId = picked.entry.id
497
+ const credential = picked.credential
498
+ /**
499
+ * 钉定模式下额度耗尽:如实报错而不是换号 —— 换号会让「钉定」名存实亡
500
+ * (用户选了「GLM-5.3 · 主号」就该知道失败意味着主号的额度尽了)。
501
+ */
502
+ const failPinnedQuota = (upstreamText) => {
503
+ const detail = upstreamText.length > 0 ? `上游响应:${upstreamText}。` : ''
504
+ throw Object.assign(
505
+ new Error(
506
+ `钉定的账号「${picked.entry.nickname}」在模型「${model}」上的额度已用尽(免费额度按自然日 UTC+8 结算)。` +
507
+ `${detail}可等次日重置、在面板把其它账号置顶后改选,或改选不带账号后缀的自动选号条目。`,
508
+ ),
509
+ { code: 'QUOTA' },
510
+ )
511
+ }
512
+ /**
513
+ * 钉定模式吃零内容时的如实文案(1.0.1):模型实际可用时,零内容大概率是
514
+ * 瞬时异常 —— 报「额度已用尽」会把人带去错误的方向。这里给可操作的出路。
515
+ */
516
+ const failPinnedEmptyContent = (upstreamText) => {
517
+ const isSecond = previousZeroContentMark !== undefined
518
+ throw Object.assign(
519
+ new Error(
520
+ `钉定的账号「${picked.entry.nickname}」在模型「${model}」上返回了空响应(${upstreamText})。` +
521
+ (isSecond
522
+ ? '短时间内连续两次,已按当日无权益处理:可等额度重置、在面板「清除限流」后重试,或改选自动选号条目换用其它账号。'
523
+ : '这通常是一次瞬时异常(账号额度未必用尽):稍等几分钟重试即可;若反复出现,可在面板「清除限流」后重试,或改选自动选号条目。'),
524
+ ),
525
+ { code: 'QUOTA' },
526
+ )
527
+ }
528
+ const captchaKey = `${accountId}|${model}`
529
+ let probeRejected = false
530
+ let switched = false
531
+ /**
532
+ * 零内容两级证据(1.0.1):进入这个账号前它是否已在零内容观察窗内。
533
+ * 在 = 本次再吃零内容就是第二次 → 升级当日硬标记;不在 = 首次 → 只打观察窗。
534
+ * 计数由 pool 持有(软优先,pick 第一档避开但不硬过滤)。
535
+ */
536
+ const wasWatched = this.#pool.isEmptyContentWatched?.(accountId, model) ?? false
537
+
538
+ const supportsImages = request.model?.inputModalities?.includes?.('image') ?? true
539
+ /**
540
+ * 宿主契约:DSH 的 image 块是持久引用(`{ type: 'image', attachment: ref }`),
541
+ * 字节须经附件服务 `readImageRequest` 解析(官方 `dsh-llm-deepseek` 同款链路)。
542
+ * 附件服务不可用 / 解析失败时 `resolvedImages` 缺项,`convertContent` 用
543
+ * 占位文本替换 —— 不再静默丢弃。
544
+ */
545
+ const resolvedImages = await resolveImages(options.messages, {
546
+ resolveAttachments: this.#resolveDeps?.resolveAttachments,
547
+ signal: request.signal,
548
+ })
549
+
550
+ const body = buildUpstreamBody({
551
+ options,
552
+ cwd: this.#cwd,
553
+ provider: 'zcode-start-plan',
554
+ supportsImages,
555
+ resolvedImages,
556
+ maxTokens: request.maxTokens,
557
+ })
558
+
559
+ for (let attempt = 0; ; attempt += 1) {
560
+ if (request.signal?.aborted === true) {
561
+ throw Object.assign(new Error('请求已取消'), { code: 'ABORTED' })
562
+ }
563
+ const knownRequired = (this.#captchaRequiredUntil.get(captchaKey) ?? 0) > this.#now()
564
+ const needCaptcha = knownRequired || probeRejected
565
+ let captcha
566
+ if (needCaptcha) {
567
+ try {
568
+ captcha = await this.mintCaptcha(request.signal)
569
+ } catch (error) {
570
+ throw Object.assign(
571
+ new Error(
572
+ `captcha 产出失败:${error instanceof Error ? error.message : String(error)}。` +
573
+ '需要宿主带调试端口启动:先彻底退出 DSH,再用 ' +
574
+ `${launchCommand(9229)} 重新打开,` +
575
+ '或把 config.captcha.mode 设为 "manual"。',
576
+ ),
577
+ { code: 'CAPTCHA_FAILED' },
578
+ )
579
+ }
580
+ }
581
+
582
+ const headers = buildZcodeHeaders(credential, {
583
+ authorization: `Bearer ${credential.zcode_jwt}`,
584
+ ...(captcha !== undefined ? { captcha: { param: captcha.param, region: captcha.region } } : {}),
585
+ })
586
+
587
+ let response
588
+ /**
589
+ * 实时路由记录(1.0.0 / 审计修复 1.0.1):**紧贴真正发出去的这次调用**,
590
+ * 且每次重试都覆盖 —— 放在账号轮次入口只能反映「打算用谁」,
591
+ * 换号、同账号重试、钉定失败都会让它停在错误的人身上。
592
+ */
593
+ this.#pool.noteRouted?.(accountId, model, { outcome: 'attempting' })
594
+ try {
595
+ response = await this.#gate.run(model, () =>
596
+ this.#fetchImpl(ZCODE_PLAN_MESSAGES_URL, {
597
+ method: 'POST',
598
+ headers,
599
+ body: JSON.stringify(body),
600
+ signal: request.signal,
601
+ }),
602
+ )
603
+ } catch (error) {
604
+ if (request.signal?.aborted === true) throw Object.assign(new Error('请求已取消'), { code: 'ABORTED' })
605
+ /**
606
+ * 网络层异常的分流(issue #4):`AbortError` / `TimeoutError`(fetch 自行超时、
607
+ * 宿主 signal 超时、连接被上游静默掐断)一律落 TIMEOUT —— 它在回退名单里,
608
+ * 回退链路与用户文案都能给出「没拿到响应」,而不是笼统的 PROVIDER_ERROR。
609
+ */
610
+ const timedOut = error?.name === 'AbortError' || error?.name === 'TimeoutError'
611
+ const networkError = Object.assign(
612
+ new Error(
613
+ timedOut
614
+ ? `上游在 ${Math.round(this.#readTimeoutMs / 1000)}s 内没有返回任何响应(可能已被上游限流 / 不再出流)。`
615
+ : `上游请求失败:${error instanceof Error ? error.message : String(error)}`,
616
+ ),
617
+ { code: timedOut ? TIMEOUT_CODE : 'PROVIDER_ERROR' },
618
+ )
619
+ if (pinned !== null) throw networkError
620
+ const fails = (accountFailCounts.get(accountId) ?? 0) + 1
621
+ accountFailCounts.set(accountId, fails)
622
+ lastSwitchReason = timedOut ? 'timeout' : 'other'
623
+ lastFailure = networkError.message.slice(0, 200)
624
+ if (fails >= PER_ACCOUNT_FAIL_MAX) {
625
+ this.#log(`[zcode] 账号 ${accountId} 连续 ${fails} 次第${timedOut ? '超时' : '网络失败'} → 换下一个账号`)
626
+ tried.add(accountId)
627
+ switched = true
628
+ break
629
+ }
630
+ this.#log(`[zcode] 账号 ${accountId} ${timedOut ? '超时' : '网络失败'} ${fails}/${PER_ACCOUNT_FAIL_MAX},同账号重试`)
631
+ continue
632
+ }
633
+
634
+ if (!response.ok) {
635
+ const text = await response.text().catch(() => '')
636
+ const kind = classifyUpstreamError(response.status, text)
637
+ this.#log(`[zcode] 账号 ${accountId} 上游 ${response.status}(${kind}):${text.slice(0, 200)}`)
638
+
639
+ if (kind === 'quota') {
640
+ this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
641
+ this.#pool.noteError(accountId, describeUpstreamError(response.status, text))
642
+ /** 徽标要能说「这个号已耗尽」,而不是继续显示它像在服务。 */
643
+ this.#pool.noteRouted?.(accountId, model, { outcome: 'exhausted', reason: '上游额度用尽' })
644
+ if (pinned !== null) failPinnedQuota(text.slice(0, 200))
645
+ tried.add(accountId)
646
+ switched = true
647
+ break
648
+ }
649
+ if (kind === 'concurrency') {
650
+ const action = await this.#handleConcurrency({
651
+ accountId,
652
+ model,
653
+ attempt,
654
+ pinned,
655
+ picked,
656
+ status: response.status,
657
+ text,
658
+ onRetry: request.onRetry,
659
+ })
660
+ if (action === 'retry') continue
661
+ if (action === 'switch') {
662
+ tried.add(accountId)
663
+ switched = true
664
+ lastSwitchReason = 'concurrency'
665
+ lastFailure = `模型「${model}」的可用账号都处于并发限流(3009)`
666
+ break
667
+ }
668
+ throw action
669
+ }
670
+ if (kind === 'captcha' && attempt < 2) {
671
+ if (captcha === undefined) {
672
+ this.#captchaRequiredUntil.set(captchaKey, this.#now() + CAPTCHA_REQUIRED_TTL_MS)
673
+ this.#log('[zcode] 上游要求 captcha(3007)→ 本轮才产出并重试')
674
+ } else {
675
+ this.#log('[zcode] captcha 被拒(3007),换新 param 重试')
676
+ }
677
+ probeRejected = true
678
+ request.onRetry?.({ reason: 'captcha', attempt, message: describeUpstreamError(response.status, text) })
679
+ continue
680
+ }
681
+ if (kind === 'risk') {
682
+ this.#clearRateLimitOnRisk(accountId, model, response.status, text)
683
+ throw Object.assign(new Error(describeUpstreamError(response.status, text)), { code: RISK_BLOCKED_CODE })
684
+ }
685
+ if (kind === 'auth') {
686
+ this.#pool.noteError(accountId, describeUpstreamError(response.status, text))
687
+ }
688
+ /**
689
+ * 统一选号的韧性兜底(0.9.9):auth / other 不再当场 throw ——
690
+ * 记失败计数,同账号连续 PER_ACCOUNT_FAIL_MAX 次失败就换下一个。
691
+ * 宿主压缩摘要是一次性直调(不走重试瀑布),同一坏账号会被压缩与
692
+ * 主请求各撞一次:此前两次都当场 throw,对话被直接阻断。
693
+ * auth 换号合理(凭据失效不影响其它账号);3012 风控已在上方
694
+ * 绝不重试地抛出(连续触发有账号冷却惩罚)。
695
+ */
696
+ if (pinned !== null) {
697
+ throw Object.assign(new Error(describeUpstreamError(response.status, text)), {
698
+ code: codeForUpstreamKind(kind),
699
+ })
700
+ }
701
+ const fails = (accountFailCounts.get(accountId) ?? 0) + 1
702
+ accountFailCounts.set(accountId, fails)
703
+ /**
704
+ * 换轮原因要**保真**:auth 与 other 的终态码不同(AUTH / PROVIDER_ERROR),
705
+ * 记成笼统的 'other' 会让「全部账号凭据失效」被误报成额度问题。
706
+ */
707
+ lastSwitchReason = kind === 'auth' ? 'auth' : 'other'
708
+ lastFailure = describeUpstreamError(response.status, text).slice(0, 200)
709
+ if (fails >= PER_ACCOUNT_FAIL_MAX) {
710
+ this.#log(`[zcode] 账号 ${accountId} 连续 ${fails} 次失败(${kind})→ 换下一个账号`)
711
+ tried.add(accountId)
712
+ switched = true
713
+ break
714
+ }
715
+ this.#log(`[zcode] 账号 ${accountId} 失败 ${fails}/${PER_ACCOUNT_FAIL_MAX}(${kind}),同账号重试`)
716
+ continue
717
+ }
718
+
719
+ if (response.body === null) {
720
+ this.#log(`[zcode] 账号 ${accountId} 返回 200 但 body 为空 → 视为无权益,换号`)
721
+ this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
722
+ this.#pool.noteRouted?.(accountId, model, { outcome: 'exhausted', reason: 'HTTP 200 但响应体为空' })
723
+ if (pinned !== null) failPinnedQuota('HTTP 200 但响应体为空')
724
+ tried.add(accountId)
725
+ switched = true
726
+ break
727
+ }
728
+ const head = await readContentHead(response.body, {
729
+ contentType: response.headers.get('content-type') ?? undefined,
730
+ headTimeoutMs: this.#headTimeoutMs,
731
+ timeoutMs: this.#readTimeoutMs,
732
+ })
733
+ /**
734
+ * 🕳 **上游黑洞**(issue #4):HTTP 200 拿到了响应头,但流里**一个事件都没出来**。
735
+ * 额度用尽后本渠道就是这个形态,宿主侧只会在 ~300s × 重试次数后报「超时或不可用」。
736
+ *
737
+ * 处置顺序故意如此:
738
+ * 1. 先记一次 TIMEOUT 级失败(账号级,不写 model_rate_limits —— 黑洞**不证明**额度用尽,
739
+ * 上游抖动也是这个形态);
740
+ * 2. 同账号撞满 `PER_ACCOUNT_FAIL_MAX` 次才换号/报错 —— 也就是最多等 `2 × headTimeoutMs`
741
+ * (默认 180s,仍小于宿主一次 ~300s 超时);
742
+ * 3. 钉定模式如实报 TIMEOUT(不换号,钉定只有一个号)。
743
+ */
744
+ if (head.timeoutError !== undefined) {
745
+ const detail = isHeadTimeoutError(head.timeoutError)
746
+ ? `上游在 ${Math.round(this.#headTimeoutMs / 1000)}s 内没有产出任何内容`
747
+ : `读取上游响应中断(${head.timeoutError?.message ?? '未知原因'})`
748
+ this.#log(`[zcode] 账号 ${accountId} 黑洞:${detail}(已等 ${head.elapsedMs}ms)`)
749
+ this.#pool.noteRouted?.(accountId, model, { outcome: 'attempting', reason: detail })
750
+ /**
751
+ * ⚠ 刻意**不写** `noteError`:`last_error` 是「最近一次失败原因」面板字段。
752
+ * 黑洞的成因未定(额度用尽 / 上游抖动都是这个形态),写进去只会让面板
753
+ * 说一个未经证实的结论;真因由下方 `lastFailure` 与日志给出。
754
+ */
755
+ const failure = Object.assign(
756
+ new Error(
757
+ `${detail}。这通常意味着该账号在该模型上已无可用的出流(额度用尽)或上游临时故障:` +
758
+ `可稍后重试、换一个模型,或 \`zcode-start-plan claim\` 领取当日额度。`,
759
+ ),
760
+ { code: TIMEOUT_CODE },
761
+ )
762
+ if (pinned !== null) throw failure
763
+ const fails = (accountFailCounts.get(accountId) ?? 0) + 1
764
+ accountFailCounts.set(accountId, fails)
765
+ lastSwitchReason = 'timeout'
766
+ lastFailure = failure.message.slice(0, 200)
767
+ if (fails >= PER_ACCOUNT_FAIL_MAX) {
768
+ this.#log(`[zcode] 账号 ${accountId} 连续 ${fails} 次黑洞 → 换下一个账号`)
769
+ tried.add(accountId)
770
+ switched = true
771
+ break
772
+ }
773
+ this.#log(`[zcode] 账号 ${accountId} 黑洞 ${fails}/${PER_ACCOUNT_FAIL_MAX},同账号重试`)
774
+ continue
775
+ }
776
+ /**
777
+ * ⚠ **HTTP 200 里的业务错误**:本渠道实测会返回
778
+ * `200 + application/json + {"code":1005,"msg":"exceed quota limit"}`。
779
+ * 必须先按错误表处置(该换号就换号、该报错就报错),否则会被当成
780
+ * 「零内容 → 无权益」,既丢掉真正的原因,也无法据此做正确决策。
781
+ */
782
+ if (head.upstreamError !== undefined) {
783
+ const text = head.upstreamError.text
784
+ const kind = classifyUpstreamError(200, text)
785
+ this.#log(`[zcode] 账号 ${accountId} 在 HTTP 200 里返回业务错误(${kind}):${text.slice(0, 200)}`)
786
+
787
+ if (kind === 'quota') {
788
+ lastQuotaDetail = text.slice(0, 200)
789
+ this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
790
+ this.#pool.noteError(accountId, describeUpstreamError(200, text))
791
+ this.#pool.noteRouted?.(accountId, model, { outcome: 'exhausted', reason: '上游额度用尽(HTTP 200 包裹)' })
792
+ if (pinned !== null) failPinnedQuota(text.slice(0, 200))
793
+ tried.add(accountId)
794
+ switched = true
795
+ break
796
+ }
797
+ if (kind === 'concurrency') {
798
+ const action = await this.#handleConcurrency({
799
+ accountId,
800
+ model,
801
+ attempt,
802
+ pinned,
803
+ picked,
804
+ status: 200,
805
+ text,
806
+ onRetry: request.onRetry,
807
+ fromHttp200: true,
808
+ })
809
+ if (action === 'retry') continue
810
+ if (action === 'switch') {
811
+ tried.add(accountId)
812
+ switched = true
813
+ lastSwitchReason = 'concurrency'
814
+ lastFailure = `模型「${model}」的可用账号都处于并发限流(3009)`
815
+ break
816
+ }
817
+ throw action
818
+ }
819
+ if (kind === 'captcha' && attempt < 2) {
820
+ if (captcha === undefined) this.#captchaRequiredUntil.set(captchaKey, this.#now() + CAPTCHA_REQUIRED_TTL_MS)
821
+ probeRejected = true
822
+ request.onRetry?.({ reason: 'captcha', attempt, message: describeUpstreamError(200, text) })
823
+ continue
824
+ }
825
+ /** HTTP 200 包裹的风控:同样绝不重试(账号冷却惩罚)。 */
826
+ /** HTTP 200 包裹的风控:同样绝不重试(账号冷却惩罚),并自动清除限流标记。 */
827
+ if (kind === 'risk') {
828
+ this.#clearRateLimitOnRisk(accountId, model, 200, text)
829
+ throw Object.assign(new Error(describeUpstreamError(200, text)), { code: RISK_BLOCKED_CODE })
830
+ }
831
+ /**
832
+ * 统一选号的韧性兜底(0.9.9,与非 200 路径同口径):auth / other
833
+ * 计失败数,同账号连续 PER_ACCOUNT_FAIL_MAX 次失败换下一个,
834
+ * 不再当场 throw(宿主压缩摘要一次性直调,两次 throw = 对话阻断)。
835
+ */
836
+ this.#pool.noteError(accountId, describeUpstreamError(200, text))
837
+ if (pinned !== null) {
838
+ throw Object.assign(new Error(describeUpstreamError(200, text)), {
839
+ code: codeForUpstreamKind(kind),
840
+ })
841
+ }
842
+ const fails = (accountFailCounts.get(accountId) ?? 0) + 1
843
+ accountFailCounts.set(accountId, fails)
844
+ lastSwitchReason = kind === 'auth' ? 'auth' : 'other'
845
+ lastFailure = describeUpstreamError(200, text).slice(0, 200)
846
+ if (fails >= PER_ACCOUNT_FAIL_MAX) {
847
+ this.#log(`[zcode] 账号 ${accountId} 连续 ${fails} 次失败(${kind},HTTP 200)→ 换下一个账号`)
848
+ tried.add(accountId)
849
+ switched = true
850
+ break
851
+ }
852
+ this.#log(`[zcode] 账号 ${accountId} 失败 ${fails}/${PER_ACCOUNT_FAIL_MAX}(${kind},HTTP 200),同账号重试`)
853
+ continue
854
+ }
855
+
856
+ if (!head.hasContent) {
857
+ /**
858
+ * ⚠ 「模型实际在 ZCode 可用,对话却报额度耗尽」的根因修复(1.0.1):
859
+ *
860
+ * 零内容是多义的 —— 真无权益,**或**上游瞬时异常(抖动 / captcha
861
+ * 边缘情况)。此前首次零内容就把账号×模型标限流到**次日零点**
862
+ * (落库),一次抖动 = 一整天不可用,且面板余额与对话结论永远矛盾。
863
+ *
864
+ * 两级证据:首次 → 只打观察窗(pool 软优先,10 分钟自动过期);
865
+ * 窗口内同一账号×模型再吃一次零内容 → 才升级为当日硬标记。
866
+ * 无论哪一级,本次请求都换号(拿到的是坏响应,交给别的账号是安全的)。
867
+ */
868
+ const escalate = wasWatched
869
+ if (escalate) {
870
+ this.#log(`[zcode] 账号 ${accountId} 在模型 ${model} 上观察窗内第二次零内容 → 升级为当日标记`)
871
+ this.#pool.clearEmptyContentWatch?.(accountId, model)
872
+ this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
873
+ } else {
874
+ this.#log(
875
+ `[zcode] 账号 ${accountId} 在模型 ${model} 上返回 200 但零内容(${head.elapsedMs}ms)→ 观察窗 ${EMPTY_CONTENT_WINDOW_MS / 1000}s(软优先),本次换号`,
876
+ )
877
+ this.#pool.noteEmptyContentWatch?.(accountId, model, this.#now() + EMPTY_CONTENT_WINDOW_MS)
878
+ }
879
+ this.#pool.noteError(accountId, `200 但零内容(${head.elapsedMs}ms${escalate ? ',观察窗内第二次 → 当日' : ',观察窗'})`)
880
+ this.#pool.noteRouted?.(accountId, model, {
881
+ outcome: escalate ? 'exhausted' : 'attempting',
882
+ reason: escalate ? '观察窗内连续两次零内容' : 'HTTP 200 但零内容(首次,观察窗)',
883
+ })
884
+ if (pinned !== null) failPinnedEmptyContent(`HTTP 200 但零内容(${head.elapsedMs}ms)`)
885
+ tried.add(accountId)
886
+ switched = true
887
+ break
888
+ }
889
+
890
+ /** 有产出 = 账号×模型健康,清掉观察窗。 */
891
+ this.#pool.clearEmptyContentWatch?.(accountId, model)
892
+
893
+ if (captcha === undefined) {
894
+ /** 没带 captcha 就成功 ⇒ 上游当前不要验证,清掉记忆回到最省路径。 */
895
+ this.#captchaRequiredUntil.delete(captchaKey)
896
+ }
897
+ /** 命中即清忙标记:退避期间账号已空闲,别让后续请求白白绕开它。 */
898
+ this.#pool.clearModelBusy?.(accountId, model)
899
+ /** 真实命中的账号 = 徽标该显示的人(覆盖之前所有 attempt 记录)。 */
900
+ this.#pool.noteRouted?.(accountId, model, { outcome: 'ok' })
901
+ this.#log(
902
+ `[zcode] ${accountId} × ${model} 命中(首帧 ${head.elapsedMs}ms,${captcha === undefined ? '未带 captcha' : '带 captcha'})`,
903
+ )
904
+ return { head: head.head, decoder: head.decoder, accountId, model, credential, body }
905
+ }
906
+
907
+ if (!switched) throw Object.assign(new Error('请求编排内部状态异常:内层循环意外退出'), { code: 'PROVIDER_ERROR' })
908
+ /**
909
+ * 换轮时的失败文案:
910
+ * - 3009 换轮保留并发限流文案(上方按 lastSwitchReason 已写好);
911
+ * - 0.9.9 起 `other` / auth / **timeout** 换轮保留真实上游错误(lastFailure 已在
912
+ * 失败处写好)——覆盖成泛化的「已用尽」会把凭据失效 / 上游 500 / 黑洞
913
+ * 这类真正原因抹掉,用户会被带去「等额度重置」的错误排查方向;
914
+ * - 只有 quota 换轮(原因就是额度)才换成「已用尽」的标准文案。
915
+ */
916
+ if (lastSwitchReason === 'quota') {
917
+ lastFailure = `模型「${model}」的可用账号已用尽`
918
+ }
919
+ }
920
+
921
+ /**
922
+ * 终态错误码(issue #4):**保真**,不再一律落 QUOTA。
923
+ *
924
+ * 唯一映射点是 `codeForUpstreamKind`(errors.js),这里只补两条本文件的
925
+ * 局部语义:
926
+ * - `'none'`(一次都没换过轮就选不到号)→ 按 quota 处理(权益层面不可用);
927
+ * - `'timeout'`(上游黑洞 / 不出流)→ `TIMEOUT_CODE`(在回退名单里,宿主可改道)。
928
+ *
929
+ * 其余(concurrency → RATE_LIMIT、quota → QUOTA、auth → AUTH、
930
+ * other → PROVIDER_ERROR)全部由那张表决定,**不再各写一份三元链**。
931
+ *
932
+ * 错误码直接决定宿主的重试策略与回退判定,混用会把用户带去错误的排查方向。
933
+ */
934
+ const exhaustedCode = lastSwitchReason === 'timeout'
935
+ ? TIMEOUT_CODE
936
+ : codeForUpstreamKind(lastSwitchReason === 'none' ? 'quota' : lastSwitchReason)
937
+ throw Object.assign(new Error(`${lastFailure}(已尝试 ${tried.size} 个账号,上限 ${QUOTA_SWITCH_MAX})。`), { code: exhaustedCode })
938
+ }
939
+ }
940
+
941
+ /** 兜底模型表(面板/工具在拉不到上游目录时用)。 */
942
+ export { ZCODE_FALLBACK_MODELS }