dsh-zcode-startplan 0.0.0-stage → 0.4.5
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 +405 -0
- package/LICENSE +674 -0
- package/README.md +404 -2
- package/bin/cli.mjs +450 -0
- package/client.js +716 -0
- package/cordis.patch.yml +32 -0
- package/icon.svg +18 -0
- package/index.js +335 -0
- package/lib/adapter.js +422 -0
- package/lib/anthropic-body.js +469 -0
- package/lib/assemble.js +420 -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 +352 -0
- package/lib/manage-routes.js +489 -0
- package/lib/pinned-model.js +56 -0
- package/lib/plan-client.js +532 -0
- package/lib/pool.js +478 -0
- package/lib/sse.js +317 -0
- package/lib/stream-translator.js +301 -0
- package/lib/text-heuristics.js +35 -0
- package/lib/upstream-api.js +570 -0
- package/lib/upstream.js +134 -0
- package/locale/en.json +6 -0
- package/locale/zh.json +6 -0
- package/package.json +78 -4
- package/scripts/_cdp-inspect.mjs +54 -0
- package/scripts/asar-list.mjs +66 -0
- package/scripts/bench-toks.mjs +138 -0
- package/scripts/check-compat-rc3.mjs +11 -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,532 @@
|
|
|
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 }
|