dsh-zcode-startplan 0.0.0-stage → 0.2.0
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.
- package/CHANGELOG.md +108 -0
- package/LICENSE +674 -0
- package/README.md +345 -2
- package/bin/cli.mjs +450 -0
- package/client.js +659 -0
- package/cordis.patch.yml +30 -0
- package/icon.svg +18 -0
- package/index.js +313 -0
- package/lib/adapter.js +286 -0
- package/lib/anthropic-body.js +304 -0
- package/lib/assemble.js +309 -0
- package/lib/captcha/minter.js +654 -0
- package/lib/captcha/sdk-page.js +20 -0
- package/lib/errors.js +125 -0
- package/lib/local-endpoint.js +338 -0
- package/lib/manage-routes.js +414 -0
- package/lib/plan-client.js +427 -0
- package/lib/pool.js +467 -0
- package/lib/sse.js +317 -0
- package/lib/stream-translator.js +279 -0
- package/lib/text-heuristics.js +35 -0
- package/lib/upstream-api.js +544 -0
- package/lib/upstream.js +123 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +80 -6
- package/scripts/bench-toks.mjs +138 -0
- package/scripts/check-data-dir.mjs +31 -0
- package/scripts/restart-dsh.ps1 +76 -0
- package/scripts/run-tests.mjs +68 -0
- package/scripts/smoke-install.mjs +204 -0
- package/scripts/verify_compat.mjs +64 -0
|
@@ -0,0 +1,427 @@
|
|
|
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 } 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
|
+
|
|
37
|
+
/** 「该账号×模型当前需要 captcha」的记忆时长(避免每条消息都白吃一次 3007)。 */
|
|
38
|
+
const CAPTCHA_REQUIRED_TTL_MS = 2 * 60_000
|
|
39
|
+
|
|
40
|
+
/** 串行队列:captcha 产出是设备级的,并发无益且会互相踩页面。 */
|
|
41
|
+
class SerialQueue {
|
|
42
|
+
#tail = Promise.resolve()
|
|
43
|
+
run(task) {
|
|
44
|
+
const next = this.#tail.then(task, task)
|
|
45
|
+
/** 队列本身不因一次失败而卡死。 */
|
|
46
|
+
this.#tail = next.catch(() => {})
|
|
47
|
+
return next
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** captcha 产出失败的指数退避闸门(保护设备信誉)。 */
|
|
52
|
+
class CaptchaBackoff {
|
|
53
|
+
#streak = 0
|
|
54
|
+
#until = 0
|
|
55
|
+
noteFailure(now = Date.now()) {
|
|
56
|
+
this.#streak += 1
|
|
57
|
+
const cooldown = Math.min(60_000 * 2 ** (this.#streak - 1), 30 * 60_000)
|
|
58
|
+
this.#until = now + cooldown
|
|
59
|
+
return cooldown
|
|
60
|
+
}
|
|
61
|
+
noteSuccess() {
|
|
62
|
+
this.#streak = 0
|
|
63
|
+
this.#until = 0
|
|
64
|
+
}
|
|
65
|
+
remainingMs(now = Date.now()) {
|
|
66
|
+
return Math.max(0, this.#until - now)
|
|
67
|
+
}
|
|
68
|
+
get failureStreak() {
|
|
69
|
+
return this.#streak
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 发车闸门:全局串行 + 按模型间隔(GLM-5.3 需 350ms,Flash 不需要)。 */
|
|
74
|
+
class ModelGate {
|
|
75
|
+
#chain = Promise.resolve()
|
|
76
|
+
#lastVerdict = { model: '', at: 0 }
|
|
77
|
+
#gaps
|
|
78
|
+
constructor(gaps) {
|
|
79
|
+
this.#gaps = gaps
|
|
80
|
+
}
|
|
81
|
+
async run(model, task) {
|
|
82
|
+
const previous = this.#chain
|
|
83
|
+
let release
|
|
84
|
+
this.#chain = new Promise((resolve) => {
|
|
85
|
+
release = resolve
|
|
86
|
+
})
|
|
87
|
+
try {
|
|
88
|
+
await previous
|
|
89
|
+
const gap = this.#gaps[String(model).toLowerCase()] ?? 0
|
|
90
|
+
if (gap > 0 && this.#lastVerdict.model === model) {
|
|
91
|
+
const wait = gap - (Date.now() - this.#lastVerdict.at)
|
|
92
|
+
if (wait > 0) await sleep(wait)
|
|
93
|
+
}
|
|
94
|
+
try {
|
|
95
|
+
return await task()
|
|
96
|
+
} finally {
|
|
97
|
+
this.#lastVerdict = { model, at: Date.now() }
|
|
98
|
+
}
|
|
99
|
+
} finally {
|
|
100
|
+
release()
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function sleep(ms) {
|
|
106
|
+
return new Promise((resolve) => {
|
|
107
|
+
const timer = setTimeout(resolve, ms)
|
|
108
|
+
timer.unref?.()
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* 一次「zcode-plan」调用的可复用客户端。
|
|
114
|
+
*
|
|
115
|
+
* 进程内应是**单实例**(captcha 产出、闸门、需求记忆都是设备级/全局状态)。
|
|
116
|
+
*/
|
|
117
|
+
export class ZcodePlanClient {
|
|
118
|
+
#pool
|
|
119
|
+
#minter
|
|
120
|
+
#fetchImpl
|
|
121
|
+
#log
|
|
122
|
+
#now
|
|
123
|
+
#cwd
|
|
124
|
+
#queue = new SerialQueue()
|
|
125
|
+
#backoff = new CaptchaBackoff()
|
|
126
|
+
#gate = new ModelGate({ 'glm-5.3': 350 })
|
|
127
|
+
#captchaRequiredUntil = new Map()
|
|
128
|
+
#captchaConfig
|
|
129
|
+
#captchaConfigAt = 0
|
|
130
|
+
|
|
131
|
+
constructor(options) {
|
|
132
|
+
this.#pool = options.pool
|
|
133
|
+
this.#minter = options.minter
|
|
134
|
+
this.#fetchImpl = options.fetchImpl ?? globalThis.fetch
|
|
135
|
+
this.#log = options.log ?? (() => {})
|
|
136
|
+
this.#now = options.now ?? (() => Date.now())
|
|
137
|
+
this.#cwd = options.cwd ?? process.cwd()
|
|
138
|
+
this.#captchaConfig = options.captchaConfig
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** 供状态工具读取观测值。 */
|
|
142
|
+
observability() {
|
|
143
|
+
return {
|
|
144
|
+
captchaFailureStreak: this.#backoff.failureStreak,
|
|
145
|
+
captchaCooldownRemainingMs: this.#backoff.remainingMs(this.#now()),
|
|
146
|
+
captchaRequiredAccounts: [...this.#captchaRequiredUntil.keys()].length,
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 拉 captcha 配置(60 秒 TTL;失败不缓存 —— 一次网络抖动不该让 sceneId 永久固化)。 */
|
|
151
|
+
async #resolveCaptchaConfig() {
|
|
152
|
+
const now = this.#now()
|
|
153
|
+
if (this.#captchaConfig !== undefined && now - this.#captchaConfigAt < 60_000) return this.#captchaConfig
|
|
154
|
+
try {
|
|
155
|
+
const first = this.#pool.list({ withCredentials: true })[0]
|
|
156
|
+
if (first?.credential !== undefined && typeof this.#minter.fetchConfig === 'function') {
|
|
157
|
+
const fetched = await this.#minter.fetchConfig(first.credential)
|
|
158
|
+
if (fetched !== undefined) {
|
|
159
|
+
this.#captchaConfig = fetched
|
|
160
|
+
this.#captchaConfigAt = now
|
|
161
|
+
return fetched
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
} catch {
|
|
165
|
+
// 回退兜底值。
|
|
166
|
+
}
|
|
167
|
+
return ZCODE_CAPTCHA_FALLBACK
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/** 产出一个 captcha param(串行 + 退避闸门)。 */
|
|
171
|
+
async mintCaptcha(signal) {
|
|
172
|
+
const cooldown = this.#backoff.remainingMs(this.#now())
|
|
173
|
+
if (cooldown > 0) {
|
|
174
|
+
throw new Error(
|
|
175
|
+
`captcha 产出处于冷却中(连续 ${this.#backoff.failureStreak} 次失败),约 ${Math.ceil(cooldown / 1000)} 秒后可重试。` +
|
|
176
|
+
'这通常意味着设备信誉不足(上游把无感验证降级为滑块),继续重试只会让信誉更差。',
|
|
177
|
+
)
|
|
178
|
+
}
|
|
179
|
+
const config = await this.#resolveCaptchaConfig()
|
|
180
|
+
try {
|
|
181
|
+
const outcome = await this.#queue.run(() => this.#minter.mint(config, { signal }))
|
|
182
|
+
this.#backoff.noteSuccess()
|
|
183
|
+
if (outcome.interactive === true) {
|
|
184
|
+
this.#log('[zcode] ⚠ captcha 被要求交互式验证(滑块/拼图)—— 设备信誉可能已下降')
|
|
185
|
+
}
|
|
186
|
+
return { param: outcome.param, region: config.region ?? 'cn' }
|
|
187
|
+
} catch (error) {
|
|
188
|
+
this.#backoff.noteFailure(this.#now())
|
|
189
|
+
throw error
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/**
|
|
194
|
+
* 执行一次模型调用。
|
|
195
|
+
*
|
|
196
|
+
* @param {{
|
|
197
|
+
* options: any,
|
|
198
|
+
* model?: any,
|
|
199
|
+
* maxTokens?: number,
|
|
200
|
+
* signal?: AbortSignal,
|
|
201
|
+
* onRetry?: (info: { reason: string, attempt: number, message: string }) => void,
|
|
202
|
+
* }} request
|
|
203
|
+
* @returns {Promise<{
|
|
204
|
+
* head: Array<any>,
|
|
205
|
+
* decoder: { read(): Promise<{ done: boolean, value?: any }>, cancel(): Promise<void> } | undefined,
|
|
206
|
+
* accountId: string,
|
|
207
|
+
* model: string,
|
|
208
|
+
* credential: any,
|
|
209
|
+
* body: any,
|
|
210
|
+
* }>}
|
|
211
|
+
*/
|
|
212
|
+
async call(request) {
|
|
213
|
+
const options = request.options
|
|
214
|
+
const model = options.model
|
|
215
|
+
const tried = new Set()
|
|
216
|
+
let lastFailure = '所有账号在模型「' + model + '」上都已用尽或无可用权益'
|
|
217
|
+
/**
|
|
218
|
+
* 最近一次**额度类**失败的上游原文(含业务码)。
|
|
219
|
+
*
|
|
220
|
+
* ⚠ 必须带到最终报错里:否则用户只看到笼统的「已用尽」,而真正的原因
|
|
221
|
+
* (`1005 exceed quota limit` / `1113 余额不足` / `200 但零内容`)被吞掉,
|
|
222
|
+
* 排查时会误以为是插件 bug。
|
|
223
|
+
*/
|
|
224
|
+
let lastQuotaDetail = ''
|
|
225
|
+
|
|
226
|
+
for (let quotaRound = 0; quotaRound < QUOTA_SWITCH_MAX; quotaRound += 1) {
|
|
227
|
+
const picked = this.#pool.pick(model, tried)
|
|
228
|
+
if (picked === null) {
|
|
229
|
+
const detail = lastQuotaDetail.length > 0 ? `最后一次上游响应:${lastQuotaDetail}。` : ''
|
|
230
|
+
/**
|
|
231
|
+
* 区分三种「选不到号」的情况 —— 用户该做的事完全不同:
|
|
232
|
+
* ① 池子真的空 → 去登录
|
|
233
|
+
* ② 池子有号但本模型都限流 → 等重置 / 换模型 / 领额度
|
|
234
|
+
* ③ 本次请求已逐个试完 → 汇报试了几个
|
|
235
|
+
* 统一报「账号池为空」会把人带去错误的排查方向(实测踩过)。
|
|
236
|
+
*/
|
|
237
|
+
const total = this.#pool.list().length
|
|
238
|
+
const enabledCount = this.#pool.list().filter((entry) => entry.enabled).length
|
|
239
|
+
let message
|
|
240
|
+
if (total === 0) {
|
|
241
|
+
message = '账号池为空。请先运行 `zcode-start-plan login` 添加 ZCode 账号。'
|
|
242
|
+
} else if (tried.size === 0) {
|
|
243
|
+
message = enabledCount === 0
|
|
244
|
+
? `账号池里有 ${total} 个账号,但全部被停用。用 \`zcode-start-plan enable <序号>\` 启用,或登录新账号。`
|
|
245
|
+
: `模型「${model}」在 ${enabledCount} 个启用账号上都已限流(免费额度按自然日 UTC+8 结算)。` +
|
|
246
|
+
`${detail}可等次日重置、换一个模型(config.models),或用 \`zcode-start-plan claim\` 领取当日额度。`
|
|
247
|
+
} else {
|
|
248
|
+
message = `${lastFailure}(本次已逐个尝试 ${tried.size} 个账号)。${detail}` +
|
|
249
|
+
'免费额度按自然日结算,请等待重置、领取当日额度(node bin/cli.mjs claim)或用 `zcode-start-plan login` 添加新账号。'
|
|
250
|
+
}
|
|
251
|
+
throw Object.assign(new Error(message), { code: 'QUOTA' })
|
|
252
|
+
}
|
|
253
|
+
const accountId = picked.entry.id
|
|
254
|
+
const credential = picked.credential
|
|
255
|
+
const captchaKey = `${accountId}|${model}`
|
|
256
|
+
let probeRejected = false
|
|
257
|
+
let switched = false
|
|
258
|
+
|
|
259
|
+
const body = buildUpstreamBody({
|
|
260
|
+
options,
|
|
261
|
+
cwd: this.#cwd,
|
|
262
|
+
provider: 'zcode-start-plan',
|
|
263
|
+
supportsImages: request.model?.inputModalities?.includes?.('image') ?? true,
|
|
264
|
+
maxTokens: request.maxTokens,
|
|
265
|
+
})
|
|
266
|
+
|
|
267
|
+
for (let attempt = 0; ; attempt += 1) {
|
|
268
|
+
if (request.signal?.aborted === true) {
|
|
269
|
+
throw Object.assign(new Error('请求已取消'), { code: 'ABORTED' })
|
|
270
|
+
}
|
|
271
|
+
const knownRequired = (this.#captchaRequiredUntil.get(captchaKey) ?? 0) > this.#now()
|
|
272
|
+
const needCaptcha = knownRequired || probeRejected
|
|
273
|
+
let captcha
|
|
274
|
+
if (needCaptcha) {
|
|
275
|
+
try {
|
|
276
|
+
captcha = await this.mintCaptcha(request.signal)
|
|
277
|
+
} catch (error) {
|
|
278
|
+
throw Object.assign(
|
|
279
|
+
new Error(
|
|
280
|
+
`captcha 产出失败:${error instanceof Error ? error.message : String(error)}。` +
|
|
281
|
+
'请以 --remote-debugging-port 启动宿主(DSH 桌面端),或把 config.captcha.mode 设为 "manual"。',
|
|
282
|
+
),
|
|
283
|
+
{ code: 'CAPTCHA_FAILED' },
|
|
284
|
+
)
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const headers = buildZcodeHeaders(credential, {
|
|
289
|
+
authorization: `Bearer ${credential.zcode_jwt}`,
|
|
290
|
+
...(captcha !== undefined ? { captcha: { param: captcha.param, region: captcha.region } } : {}),
|
|
291
|
+
})
|
|
292
|
+
|
|
293
|
+
let response
|
|
294
|
+
try {
|
|
295
|
+
response = await this.#gate.run(model, () =>
|
|
296
|
+
this.#fetchImpl(ZCODE_PLAN_MESSAGES_URL, {
|
|
297
|
+
method: 'POST',
|
|
298
|
+
headers,
|
|
299
|
+
body: JSON.stringify(body),
|
|
300
|
+
signal: request.signal,
|
|
301
|
+
}),
|
|
302
|
+
)
|
|
303
|
+
} catch (error) {
|
|
304
|
+
if (request.signal?.aborted === true) throw Object.assign(new Error('请求已取消'), { code: 'ABORTED' })
|
|
305
|
+
throw Object.assign(new Error(`上游请求失败:${error instanceof Error ? error.message : String(error)}`), {
|
|
306
|
+
code: 'PROVIDER_ERROR',
|
|
307
|
+
})
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
if (!response.ok) {
|
|
311
|
+
const text = await response.text().catch(() => '')
|
|
312
|
+
const kind = classifyUpstreamError(response.status, text)
|
|
313
|
+
this.#log(`[zcode] 账号 ${accountId} 上游 ${response.status}(${kind}):${text.slice(0, 200)}`)
|
|
314
|
+
|
|
315
|
+
if (kind === 'quota') {
|
|
316
|
+
this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
|
|
317
|
+
this.#pool.noteError(accountId, describeUpstreamError(response.status, text))
|
|
318
|
+
tried.add(accountId)
|
|
319
|
+
switched = true
|
|
320
|
+
break
|
|
321
|
+
}
|
|
322
|
+
if (kind === 'concurrency' && attempt < CONCURRENCY_RETRY_MAX) {
|
|
323
|
+
const waitMs = concurrencyRetryDelayMs(attempt)
|
|
324
|
+
this.#log(`[zcode] 并发限流(3009),退避 ${waitMs}ms 后重试(不换号)`)
|
|
325
|
+
request.onRetry?.({ reason: 'concurrency', attempt, message: describeUpstreamError(response.status, text) })
|
|
326
|
+
await sleep(waitMs)
|
|
327
|
+
continue
|
|
328
|
+
}
|
|
329
|
+
if (kind === 'captcha' && attempt < 2) {
|
|
330
|
+
if (captcha === undefined) {
|
|
331
|
+
this.#captchaRequiredUntil.set(captchaKey, this.#now() + CAPTCHA_REQUIRED_TTL_MS)
|
|
332
|
+
this.#log('[zcode] 上游要求 captcha(3007)→ 本轮才产出并重试')
|
|
333
|
+
} else {
|
|
334
|
+
this.#log('[zcode] captcha 被拒(3007),换新 param 重试')
|
|
335
|
+
}
|
|
336
|
+
probeRejected = true
|
|
337
|
+
request.onRetry?.({ reason: 'captcha', attempt, message: describeUpstreamError(response.status, text) })
|
|
338
|
+
continue
|
|
339
|
+
}
|
|
340
|
+
if (kind === 'risk') {
|
|
341
|
+
throw Object.assign(new Error(describeUpstreamError(response.status, text)), { code: 'RATE_LIMIT' })
|
|
342
|
+
}
|
|
343
|
+
if (kind === 'auth') {
|
|
344
|
+
this.#pool.noteError(accountId, describeUpstreamError(response.status, text))
|
|
345
|
+
throw Object.assign(new Error(describeUpstreamError(response.status, text)), { code: 'AUTH' })
|
|
346
|
+
}
|
|
347
|
+
throw Object.assign(new Error(describeUpstreamError(response.status, text)), { code: 'PROVIDER_ERROR' })
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
if (response.body === null) {
|
|
351
|
+
this.#log(`[zcode] 账号 ${accountId} 返回 200 但 body 为空 → 视为无权益,换号`)
|
|
352
|
+
this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
|
|
353
|
+
tried.add(accountId)
|
|
354
|
+
switched = true
|
|
355
|
+
break
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
const head = await readContentHead(response.body, {
|
|
359
|
+
contentType: response.headers.get('content-type') ?? undefined,
|
|
360
|
+
})
|
|
361
|
+
/**
|
|
362
|
+
* ⚠ **HTTP 200 里的业务错误**:本渠道实测会返回
|
|
363
|
+
* `200 + application/json + {"code":1005,"msg":"exceed quota limit"}`。
|
|
364
|
+
* 必须先按错误表处置(该换号就换号、该报错就报错),否则会被当成
|
|
365
|
+
* 「零内容 → 无权益」,既丢掉真正的原因,也无法据此做正确决策。
|
|
366
|
+
*/
|
|
367
|
+
if (head.upstreamError !== undefined) {
|
|
368
|
+
const text = head.upstreamError.text
|
|
369
|
+
const kind = classifyUpstreamError(200, text)
|
|
370
|
+
this.#log(`[zcode] 账号 ${accountId} 在 HTTP 200 里返回业务错误(${kind}):${text.slice(0, 200)}`)
|
|
371
|
+
|
|
372
|
+
if (kind === 'quota') {
|
|
373
|
+
lastQuotaDetail = text.slice(0, 200)
|
|
374
|
+
this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
|
|
375
|
+
this.#pool.noteError(accountId, describeUpstreamError(200, text))
|
|
376
|
+
tried.add(accountId)
|
|
377
|
+
switched = true
|
|
378
|
+
break
|
|
379
|
+
}
|
|
380
|
+
if (kind === 'concurrency' && attempt < CONCURRENCY_RETRY_MAX) {
|
|
381
|
+
const waitMs = concurrencyRetryDelayMs(attempt)
|
|
382
|
+
this.#log(`[zcode] 并发限流(3009,HTTP 200),退避 ${waitMs}ms 后重试(不换号)`)
|
|
383
|
+
request.onRetry?.({ reason: 'concurrency', attempt, message: describeUpstreamError(200, text) })
|
|
384
|
+
await sleep(waitMs)
|
|
385
|
+
continue
|
|
386
|
+
}
|
|
387
|
+
if (kind === 'captcha' && attempt < 2) {
|
|
388
|
+
if (captcha === undefined) this.#captchaRequiredUntil.set(captchaKey, this.#now() + CAPTCHA_REQUIRED_TTL_MS)
|
|
389
|
+
probeRejected = true
|
|
390
|
+
request.onRetry?.({ reason: 'captcha', attempt, message: describeUpstreamError(200, text) })
|
|
391
|
+
continue
|
|
392
|
+
}
|
|
393
|
+
/** 风控 / 鉴权 / 其它:如实报错,不重试。 */
|
|
394
|
+
const code = kind === 'risk' ? 'RATE_LIMIT' : kind === 'auth' ? 'AUTH' : 'PROVIDER_ERROR'
|
|
395
|
+
this.#pool.noteError(accountId, describeUpstreamError(200, text))
|
|
396
|
+
throw Object.assign(new Error(describeUpstreamError(200, text)), { code })
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
if (!head.hasContent) {
|
|
400
|
+
this.#log(`[zcode] 账号 ${accountId} 在模型 ${model} 上返回 200 但零内容(${head.elapsedMs}ms)→ 视为无权益,换号`)
|
|
401
|
+
this.#pool.markModelRateLimited(accountId, model, nextUtc8DayStartMs(new Date(this.#now())))
|
|
402
|
+
this.#pool.noteError(accountId, `200 但零内容(${head.elapsedMs}ms)`)
|
|
403
|
+
tried.add(accountId)
|
|
404
|
+
switched = true
|
|
405
|
+
break
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
if (captcha === undefined) {
|
|
409
|
+
/** 没带 captcha 就成功 ⇒ 上游当前不要验证,清掉记忆回到最省路径。 */
|
|
410
|
+
this.#captchaRequiredUntil.delete(captchaKey)
|
|
411
|
+
}
|
|
412
|
+
this.#log(
|
|
413
|
+
`[zcode] ${accountId} × ${model} 命中(首帧 ${head.elapsedMs}ms,${captcha === undefined ? '未带 captcha' : '带 captcha'})`,
|
|
414
|
+
)
|
|
415
|
+
return { head: head.head, decoder: head.decoder, accountId, model, credential, body }
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
if (!switched) throw Object.assign(new Error('请求编排内部状态异常:内层循环意外退出'), { code: 'PROVIDER_ERROR' })
|
|
419
|
+
lastFailure = `模型「${model}」的可用账号已用尽`
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
throw Object.assign(new Error(`${lastFailure}(已尝试 ${tried.size} 个账号,上限 ${QUOTA_SWITCH_MAX})。`), { code: 'QUOTA' })
|
|
423
|
+
}
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
/** 兜底模型表(面板/工具在拉不到上游目录时用)。 */
|
|
427
|
+
export { ZCODE_FALLBACK_MODELS }
|