dsh-zcode-startplan 0.5.2 → 1.0.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (51) hide show
  1. package/CHANGELOG.md +1963 -672
  2. package/README.md +92 -472
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -1002
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +109 -11
  7. package/lib/adapter.js +476 -449
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -542
  10. package/lib/auto-claim.js +229 -0
  11. package/lib/captcha/minter.js +61 -7
  12. package/lib/distribution-keys.js +202 -0
  13. package/lib/errors.js +281 -125
  14. package/lib/fallback.js +120 -0
  15. package/lib/local-endpoint.js +367 -352
  16. package/lib/manage-routes.js +1245 -652
  17. package/lib/model-catalog.js +57 -0
  18. package/lib/openai-gateway.js +776 -0
  19. package/lib/plan-client.js +942 -532
  20. package/lib/pool.js +771 -478
  21. package/lib/sse.js +429 -317
  22. package/lib/upstream-api.js +948 -611
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -81
  26. package/scripts/analyze-grant-intervals.mjs +171 -0
  27. package/scripts/check-compat-rc3.mjs +21 -11
  28. package/scripts/debug-claimable.mjs +130 -0
  29. package/scripts/probe-marketing.mjs +203 -0
  30. package/scripts/restart-dsh.ps1 +119 -116
  31. package/scripts/test-claimed-pending.mjs +152 -0
  32. package/scripts/verify_compat.mjs +75 -64
  33. package/scripts/watch-marketing.mjs +155 -0
  34. package/tests/auto-claim.test.mjs +318 -0
  35. package/tests/claim-routes.test.mjs +438 -293
  36. package/tests/client-panel.test.mjs +1141 -356
  37. package/tests/distribution-keys.test.mjs +123 -0
  38. package/tests/e2e.test.mjs +388 -353
  39. package/tests/fallback-scrub.test.mjs +105 -0
  40. package/tests/launch-command.test.mjs +68 -0
  41. package/tests/openai-gateway.test.mjs +454 -0
  42. package/tests/pinned-models.test.mjs +505 -497
  43. package/tests/plan-client.test.mjs +582 -222
  44. package/tests/pool.test.mjs +319 -93
  45. package/tests/quota-blackhole.test.mjs +409 -0
  46. package/tests/restart-script.test.mjs +53 -0
  47. package/tests/routing-quota.test.mjs +251 -0
  48. package/tests/support/hanging-stream.mjs +48 -0
  49. package/tests/upstream-error-200.test.mjs +164 -125
  50. package/tests/upstream.test.mjs +330 -250
  51. package/tests/version-probe.test.mjs +172 -0
package/lib/errors.js CHANGED
@@ -1,125 +1,281 @@
1
- /**
2
- * 上游错误判定与翻译(**切号策略的唯一判据来源**)。
3
- *
4
- * 判据必须窄:
5
- * - 「额度用尽」在 wire 上有多种形态,而「并发限流」**同样返回 429**;
6
- * 只按状态码分类会把 3009 误判成额度用尽 → 误伤一个完全可用的账号。
7
- * - 文案兜底只认 `exceed quota limit` / `quota exhausted` 这类**窄**关键词;
8
- * 用 `quota` / `balance` 泛词会误伤模型正文里恰好讨论额度的内容。
9
- *
10
- * 处置表(全部来自参考实现的实测):
11
- *
12
- * | 形态 | 处置 |
13
- * |---|---|
14
- * | `1005` / `1113` / HTTP 200 但零内容 | 标记该账号×模型当日用尽 → **换号** |
15
- * | `3009` 并发限流 | 线性退避重试,**不换号** |
16
- * | `3007` captcha 失败 | **换新 captcha** 重试(param 一次性) |
17
- * | `3012` 风控 | **不重试**(有账号冷却惩罚:30 分钟;24h 内第 3 次起 24 小时;5 次停用) |
18
- * | `401` / `1002` 凭据失效 | **不重试**,需重新登录该账号 |
19
- */
20
-
21
- /** 上游并发限流的业务码。 */
22
- export const ZCODE_CONCURRENCY_CODE = '3009'
23
-
24
- /** 并发限流重试次数上限。 */
25
- export const CONCURRENCY_RETRY_MAX = 2
26
-
27
- /** 换号次数上限。 */
28
- export const QUOTA_SWITCH_MAX = 3
29
-
30
- /** 并发限流重试的退避基数(实测 900ms 仍撞 429,故用 1500ms 起步)。 */
31
- export const CONCURRENCY_RETRY_BASE_MS = 1_500
32
-
33
- /** 判断是否是并发限流(3009)—— 等一下就能过,故重试且**不换号**。 */
34
- export function isZcodeConcurrencyLimited(body) {
35
- return body.includes(ZCODE_CONCURRENCY_CODE) || /concurrency\s+limit/i.test(body)
36
- }
37
-
38
- /** 判断是否是额度用尽(确定性:等账期重置才恢复)。 */
39
- export function isZcodeQuotaExhausted(body) {
40
- if (isZcodeConcurrencyLimited(body)) return false
41
- if (body.includes('1113') || body.includes('余额不足')) return true
42
- if (body.includes('1005')) return true
43
- return /exceed\s+quota\s+limit|quota\s+(?:has\s+been\s+)?exhausted/i.test(body)
44
- }
45
-
46
- /** 判断是否是 captcha 校验失败(3007)—— 换新 param 即可重试。 */
47
- export function isZcodeCaptchaRejected(body) {
48
- return body.includes('3007') || /captcha\s+verify\s+failed/i.test(body)
49
- }
50
-
51
- /** 判断是否是风控拦截(3012)—— **不要重试**。 */
52
- export function isZcodeRiskBlocked(body) {
53
- return body.includes('3012') || /unusual\s+activity/i.test(body)
54
- }
55
-
56
- /** 判断是否是鉴权失败(401 / 1002)—— 需用户重新登录该账号。 */
57
- export function isZcodeAuthFailed(status, body) {
58
- if (status === 401) return true
59
- return body.includes('1002') || /invalid\s+token|token\s+expired/i.test(body)
60
- }
61
-
62
- /**
63
- * 把上游错误翻成人能看懂的一句话。
64
- * 两个业务码必须单独说清,因为用户该做的事完全不同:3007 可重试,3012 不可重试。
65
- */
66
- export function describeUpstreamError(status, body) {
67
- const trimmed = String(body ?? '').trim()
68
- let code
69
- let message
70
- try {
71
- const parsed = JSON.parse(trimmed)
72
- code = parsed.code
73
- message = parsed.msg ?? parsed.message
74
- } catch {
75
- // 非 JSON:原样截断。
76
- }
77
- const suffix = typeof message === 'string' && message.length > 0 ? message : trimmed.slice(0, 200)
78
-
79
- if (code === 3009 || trimmed.includes('3009')) {
80
- return `上游并发限流(3009 model concurrency limit exceeded)——已按退避重试仍未通过,请稍后重试。原始响应:${suffix}`
81
- }
82
- if (code === 1005 || trimmed.includes('1005')) {
83
- return `额度用尽(1005 exceed quota limit)——该账号在这个模型上的免费额度已用完,请等待额度重置或更换账号。原始响应:${suffix}`
84
- }
85
- if (code === 3007 || trimmed.includes('3007')) {
86
- return '阿里云 captcha 校验失败(3007)。请重试;若持续失败,检查 ZCode 桌面端是否在运行(captcha 载体)。'
87
- }
88
- if (code === 3012 || trimmed.includes('3012')) {
89
- return `上游风控拦截(3012 unusual activity)。⚠ 该错误有账号冷却惩罚(30 分钟,反复触发会升级到 24 小时乃至停用),请勿连续重试。原始响应:${suffix}`
90
- }
91
- if (code === 1113 || trimmed.includes('1113')) {
92
- return `余额不足或无可用资源包(1113)。原始响应:${suffix}`
93
- }
94
- if (code === 1002 || status === 401) {
95
- return `凭据失效(${status})。请用 \`zcode-start-plan login\` 重新登录该账号。${suffix}`
96
- }
97
- return `HTTP ${status}:${suffix}`
98
- }
99
-
100
- /**
101
- * 上游错误分类(供重试循环直接路由)。
102
- *
103
- * @param {number} status HTTP 状态码
104
- * @param {string} body 响应正文
105
- * @returns {'quota' | 'concurrency' | 'captcha' | 'risk' | 'auth' | 'other'}
106
- */
107
- export function classifyUpstreamError(status, body) {
108
- if (isZcodeRiskBlocked(body)) return 'risk'
109
- if (isZcodeAuthFailed(status, body)) return 'auth'
110
- if (isZcodeConcurrencyLimited(body)) return 'concurrency'
111
- if (isZcodeQuotaExhausted(body)) return 'quota'
112
- if (isZcodeCaptchaRejected(body)) return 'captcha'
113
- return 'other'
114
- }
115
-
116
- /** 并发限流重试的退避时长(线性:base、2×base、…)。 */
117
- export function concurrencyRetryDelayMs(attempt, baseMs = CONCURRENCY_RETRY_BASE_MS) {
118
- const base = baseMs > 0 ? baseMs : CONCURRENCY_RETRY_BASE_MS
119
- return base * (Math.max(0, Math.floor(attempt)) + 1)
120
- }
121
-
122
- /** 构造 Anthropic 形态的错误体(DSH 侧只读 message,但保持形态一致)。 */
123
- export function anthropicErrorPayload(message, type = 'api_error') {
124
- return { type: 'error', error: { type, message } }
125
- }
1
+ /**
2
+ * 上游错误判定与翻译(**切号策略的唯一判据来源**)。
3
+ *
4
+ * 判据必须窄:
5
+ * - 「额度用尽」在 wire 上有多种形态,而「并发限流」**同样返回 429**;
6
+ * 只按状态码分类会把 3009 误判成额度用尽 → 误伤一个完全可用的账号。
7
+ * - 文案兜底只认 `exceed quota limit` / `quota exhausted` 这类**窄**关键词;
8
+ * 用 `quota` / `balance` 泛词会误伤模型正文里恰好讨论额度的内容。
9
+ *
10
+ * 处置表(全部来自参考实现的实测):
11
+ *
12
+ * | 形态 | 处置 |
13
+ * |---|---|
14
+ * | `1005` / `1113` / HTTP 200 但零内容 | 标记该账号×模型当日用尽 → **换号** |
15
+ * | `3009` 并发限流 | 打 60s 忙标记 + 线性退避重试;穷尽后**换号**(钉定模式除外)→ 抛 `RATE_LIMIT` |
16
+ * | `3007` captcha 失败 | **换新 captcha** 重试(param 一次性),不换号 |
17
+ * | `3012` 风控 | **不重试**(有账号冷却惩罚:30 分钟;24h 内第 3 次起 24 小时;5 次停用);抛出独立码 `RISK_BLOCKED`,**不参与回退**,但会自动清除该账号×模型的限流标记 |
18
+ * | `401` / `1002` 凭据失效 | **不重试**,需重新登录该账号 |
19
+ */
20
+
21
+ /**
22
+ * 「账号×模型」忙标记(3009 并发限流)的窗口时长。
23
+ *
24
+ * ⚠ 忙标记是**软优先级**不是硬过滤:选号先避开忙账号,全部忙时仍回落排队。
25
+ * 窗口取 60 秒 —— 3009 是秒级瞬态(退避 1.5/3s 内通常自愈),打 longer 只会
26
+ * 在账号早已空闲后还绕着走;真正的持续占用由「额度用尽」的当日标记兜底。
27
+ */
28
+ export const MODEL_BUSY_TTL_MS = 60_000
29
+
30
+ /** 上游并发限流的业务码。 */
31
+ export const ZCODE_CONCURRENCY_CODE = '3009'
32
+
33
+ /** 并发限流重试次数上限。 */
34
+ export const CONCURRENCY_RETRY_MAX = 2
35
+
36
+ /** 换号次数上限。 */
37
+ export const QUOTA_SWITCH_MAX = 3
38
+
39
+ /**
40
+ * 风控拦截(3012 unusual activity)对应的**抛出码**。
41
+ *
42
+ * ⚠ 为什么必须是独立码、而不是复用 `RATE_LIMIT`:
43
+ * - 语义不同:`RATE_LIMIT` 只表示 3009 并发限流(秒级瞬态,退了就好);3012 是
44
+ * 账号级风控,重试有**累积惩罚**(30 分钟 → 24 小时 → 停用)。
45
+ * - 处置不同:宿主侧按码路由,若混同会让宿主对它做指数退避重试,等于帮倒忙。
46
+ * - 回退不同:见 `isFallbackWorthyCode` —— 风控**不**触发插件回退(换通道常常还是
47
+ * 同一批账号,冷却惩罚落在账号上,绕道反而更容易继续撞风控)。
48
+ */
49
+ export const RISK_BLOCKED_CODE = 'RISK_BLOCKED'
50
+
51
+ /** 并发限流重试的退避基数(实测 900ms 仍撞 429,故用 1500ms 起步)。 */
52
+ export const CONCURRENCY_RETRY_BASE_MS = 1_500
53
+
54
+ /**
55
+ * 从响应正文里取出**结构化业务码**(数字或纯数字字符串),取不到返回 undefined。
56
+ *
57
+ * ⚠ 为什么不能只看 `body.includes('1005')`:非 JSON 错误体(网关 HTML 500 页、
58
+ * Request ID、甚至被回显的正文)里恰好含同一个数字串时会误分类 —— 实测
59
+ * `<html>…Request ID 3f8a-1005-b27c…</html>` 被判成「额度用尽」,于是把一个健康
60
+ * 账号标限流到**当日结束**。判据的优先级是:
61
+ *
62
+ * 1. 整体 `JSON.parse` 取 `code` / `error.code`(上游实测形态);
63
+ * 2. 正文里出现 `"code":NNNN` 这类**带 JSON 结构的片段**(被包裹的 JSON-safe 文本);
64
+ * 3. 都不是(`undefined`)→ 才允许第四步的「独立数字 token」兜底。
65
+ *
66
+ * @param {string} body
67
+ * @returns {number | undefined}
68
+ */
69
+ export function extractBusinessCode(body) {
70
+ const text = String(body ?? '').trim()
71
+ if (text.length === 0) return undefined
72
+ try {
73
+ const parsed = JSON.parse(text)
74
+ return toCode(parsed?.code ?? parsed?.error?.code)
75
+ } catch {
76
+ // 不是完整 JSON:退到结构化片段匹配(仍然要求 JSON 键的引号与冒号)。
77
+ }
78
+ const match = /"code"\s*:\s*"?(\d+)"?/.exec(text)
79
+ return match === null ? undefined : Number(match[1])
80
+ }
81
+
82
+ /** 业务码归一化:数字或纯数字字符串 → number,其余 undefined。 */
83
+ function toCode(value) {
84
+ if (typeof value === 'number' && Number.isFinite(value)) return value
85
+ if (typeof value === 'string' && /^\d+$/.test(value.trim())) return Number(value.trim())
86
+ return undefined
87
+ }
88
+
89
+ /**
90
+ * 判断正文是否带某个业务码。
91
+ *
92
+ * 结构化业务码**存在时以它为准**(出现别的 code = 不是这个错误);不存在时才允许
93
+ * 「独立数字 token」兜底 —— 且要求数字两侧都不是字母数字(`1005-b27c`、`3009x`、
94
+ * `a1005` 都不算),把 Request ID / 十六进制片段这类误命中挡在外面。
95
+ * ⚠ 兜底只对**短正文**生效:超过 8KB 的 HTML 错误页等不再猜(宁可归到 other)。
96
+ */
97
+ export function hasBusinessCode(body, code) {
98
+ const text = String(body ?? '')
99
+ const structured = extractBusinessCode(text)
100
+ if (structured !== undefined) return structured === Number(code)
101
+ if (text.length > 8_192) return false
102
+ /**
103
+ * ⚠ 兜底只在**长得不像 HTML 文档**时生效:网关错误页/反代 502 页里常带
104
+ * `Request ID 3f8a-1005-b27c` 这类片段,而这类页面结构上永远不是上游业务错误。
105
+ * 用「是否存在 HTML 标签结构 + JSON 键」判定,比窄化数字边界更贴近真实形态。
106
+ */
107
+ if (/<\s*(?:!doctype|html|head|body|title|p|div|pre|center|h[1-6])\b/i.test(text)) return false
108
+ /** 连 JSON 键都不出现的纯文本里,业务码只可能是裸串(`1005 exceed quota limit`)。 */
109
+ return new RegExp(`(?<![0-9A-Za-z])${code}(?![0-9A-Za-z])`).test(text)
110
+ }
111
+
112
+ /** 判断是否是并发限流(3009)—— 等一下就能过,故重试且**不换号**。 */
113
+ export function isZcodeConcurrencyLimited(body) {
114
+ return hasBusinessCode(body, ZCODE_CONCURRENCY_CODE) || /concurrency\s+limit/i.test(body)
115
+ }
116
+
117
+ /** 判断是否是额度用尽(确定性:等账期重置才恢复)。 */
118
+ export function isZcodeQuotaExhausted(body) {
119
+ if (isZcodeConcurrencyLimited(body)) return false
120
+ if (hasBusinessCode(body, 1113) || body.includes('余额不足')) return true
121
+ if (hasBusinessCode(body, 1005)) return true
122
+ return /exceed\s+quota\s+limit|quota\s+(?:has\s+been\s+)?exhausted/i.test(body)
123
+ }
124
+
125
+ /** 判断是否是 captcha 校验失败(3007)—— 换新 param 即可重试。 */
126
+ export function isZcodeCaptchaRejected(body) {
127
+ return hasBusinessCode(body, 3007) || /captcha\s+verify\s+failed/i.test(body)
128
+ }
129
+
130
+ /** 判断是否是风控拦截(3012)—— **不要重试**。 */
131
+ export function isZcodeRiskBlocked(body) {
132
+ return hasBusinessCode(body, 3012) || /unusual\s+activity/i.test(body)
133
+ }
134
+
135
+ /** 判断是否是鉴权失败(401 / 1002)—— 需用户重新登录该账号。 */
136
+ export function isZcodeAuthFailed(status, body) {
137
+ if (status === 401) return true
138
+ return hasBusinessCode(body, 1002) || /invalid\s+token|token\s+expired/i.test(body)
139
+ }
140
+
141
+ /**
142
+ * 把上游错误翻成人能看懂的一句话。
143
+ * 两个业务码必须单独说清,因为用户该做的事完全不同:3007 可重试,3012 不可重试。
144
+ *
145
+ * ⚠ 一律走 `hasBusinessCode`(结构化判据),不再用裸 `includes` —— 网关 HTML
146
+ * 错误页里恰好含同一个数字串时不至于把用户引向错误的排查方向。
147
+ */
148
+ export function describeUpstreamError(status, body) {
149
+ const trimmed = String(body ?? '').trim()
150
+ let message
151
+ try {
152
+ const parsed = JSON.parse(trimmed)
153
+ message = parsed.msg ?? parsed.message ?? parsed.error?.message
154
+ } catch {
155
+ // 非 JSON:原样截断。
156
+ }
157
+ const suffix = typeof message === 'string' && message.length > 0 ? message : trimmed.slice(0, 200)
158
+ const has = (code) => hasBusinessCode(trimmed, code)
159
+
160
+ if (has(3009)) {
161
+ return `上游并发限流(3009 model concurrency limit exceeded)——已按退避重试仍未通过,请稍后重试。原始响应:${suffix}`
162
+ }
163
+ if (has(1005)) {
164
+ return `额度用尽(1005 exceed quota limit)——该账号在这个模型上的免费额度已用完,请等待额度重置或更换账号。原始响应:${suffix}`
165
+ }
166
+ if (has(3007)) {
167
+ return '阿里云 captcha 校验失败(3007)。请重试;若持续失败,检查 ZCode 桌面端是否在运行(captcha 载体)。'
168
+ }
169
+ if (has(3012)) {
170
+ return `上游风控拦截(3012 unusual activity)——这是**风控**不是额度问题,也可能是一次误判;本账号该模型的限流标记已自动清除,可稍后重试,但请勿连续重试。原始响应:${suffix}`
171
+ }
172
+ if (has(1113)) {
173
+ return `余额不足或无可用资源包(1113)。原始响应:${suffix}`
174
+ }
175
+ if (has(1002) || status === 401) {
176
+ return `凭据失效(${status})。请用 \`zcode-start-plan login\` 重新登录该账号。${suffix}`
177
+ }
178
+ return `HTTP ${status}:${suffix}`
179
+ }
180
+
181
+ /**
182
+ * 上游错误分类(供重试循环直接路由)。
183
+ *
184
+ * @param {number} status HTTP 状态码
185
+ * @param {string} body 响应正文
186
+ * @returns {'quota' | 'concurrency' | 'captcha' | 'risk' | 'auth' | 'other'}
187
+ */
188
+ export function classifyUpstreamError(status, body) {
189
+ if (isZcodeRiskBlocked(body)) return 'risk'
190
+ if (isZcodeAuthFailed(status, body)) return 'auth'
191
+ if (isZcodeConcurrencyLimited(body)) return 'concurrency'
192
+ if (isZcodeQuotaExhausted(body)) return 'quota'
193
+ if (isZcodeCaptchaRejected(body)) return 'captcha'
194
+ return 'other'
195
+ }
196
+
197
+ /**
198
+ * 黑洞阈值的缺省值(毫秒)。
199
+ *
200
+ * - `DEFAULT_HEAD_TIMEOUT_MS`:**首内容超时**。请求发出后这么久还没见到
201
+ * 第一个内容事件,就认为上游「不再出流」(额度用尽后本渠道的典型表现:
202
+ * HTTP 200 + 一个永不产出内容的 SSE 流),中止并按 TIMEOUT 分类。
203
+ * ⚠ 必须显著小于宿主的单次超时(实测 ~300s):否则宿主的超时先落地,
204
+ * 分类变成笼统的 `PROVIDER_ERROR`,回退链路连判断的机会都没有。
205
+ * - `DEFAULT_READ_TIMEOUT_MS`:**流内**读超时。已经有内容之后,两个事件之间
206
+ * 允许的最大静默 —— 长思考/长工具参数不该被首内容超时误杀。
207
+ */
208
+ export const DEFAULT_HEAD_TIMEOUT_MS = 90_000
209
+ export const DEFAULT_READ_TIMEOUT_MS = 180_000
210
+
211
+ /**
212
+ * 把 `classifyUpstreamError` 的分类结果映射成**抛给宿主的错误码**。
213
+ *
214
+ * 这是分类 → 码的唯一映射点:调用方(plan-client 等)直接用它,别再各自写一份
215
+ * 三元链 —— 两份映射迟早分叉,而宿主只认 code。
216
+ *
217
+ * | kind | code |
218
+ * |---|---|
219
+ * | `risk`(3012 风控) | `RISK_BLOCKED`(不重试、不参与回退) |
220
+ * | `concurrency`(3009) | `RATE_LIMIT`(瞬态,可重试可回退) |
221
+ * | `quota` | `QUOTA` |
222
+ * | `auth` | `AUTH` |
223
+ * | `captcha` | `CAPTCHA_FAILED` |
224
+ * | `timeout`(上游黑洞 / 不出流,**不是** `classifyUpstreamError` 的产物) | `TIMEOUT` |
225
+ * | `other` / 未知 kind | `PROVIDER_ERROR` |
226
+ *
227
+ * ⚠ `timeout` 这一档是为编排层补的:`classifyUpstreamError` 只看 HTTP 状态与正文,
228
+ * 看不到「200 但永不出流」;那是 plan-client 用 `readContentHead` 判出来的,
229
+ * 它同样需要一个**唯一**的分类 → 码映射点(TIMEOUT 在回退名单里,落成
230
+ * PROVIDER_ERROR 会让宿主不去改道)。
231
+ *
232
+ * @param {'quota' | 'concurrency' | 'captcha' | 'risk' | 'auth' | 'timeout' | 'other' | string | undefined | null} kind
233
+ * @returns {string}
234
+ */
235
+ export function codeForUpstreamKind(kind) {
236
+ switch (kind) {
237
+ case 'risk':
238
+ return RISK_BLOCKED_CODE
239
+ case 'concurrency':
240
+ return 'RATE_LIMIT'
241
+ case 'quota':
242
+ return 'QUOTA'
243
+ case 'auth':
244
+ return 'AUTH'
245
+ case 'captcha':
246
+ return 'CAPTCHA_FAILED'
247
+ case 'timeout':
248
+ return 'TIMEOUT'
249
+ default:
250
+ return 'PROVIDER_ERROR'
251
+ }
252
+ }
253
+
254
+ /**
255
+ * 这次失败是否值得**先回退到别的通道**再报错(`fallback.js` 的默认回退码)。
256
+ *
257
+ * QUOTA / TIMEOUT / RATE_LIMIT 都是「本通道此刻给不出结果,但别的通道也许行」
258
+ * 的瞬态或额度级失败;AUTH / CAPTCHA_FAILED / PROVIDER_ERROR / ABORTED 不是。
259
+ * 宿主自己又有一套 `llm-retry` —— 这里只决定本插件是否**立刻**改道。
260
+ *
261
+ * ⚠ `RISK_BLOCKED`(3012 风控)**刻意不在此列**:
262
+ * - 风控是**账号级**惩罚,回退只是换一条通道、常常仍是同一批账号,绕过去只会继续
263
+ * 撞风控、把冷却从 30 分钟推到 24 小时乃至停用;
264
+ * - 用户可操作的补救是「等一会 / 换账号」,不是「插件偷偷换通道」。
265
+ * 代码侧改为自动清除该账号×模型的限流标记(见 plan-client 的 risk 分支),
266
+ * 让账号能立刻重试,而不是靠回退掩盖问题。
267
+ */
268
+ export function isFallbackWorthyCode(code) {
269
+ return code === 'QUOTA' || code === 'TIMEOUT' || code === 'RATE_LIMIT'
270
+ }
271
+
272
+ /** 并发限流重试的退避时长(线性:base、2×base、…)。 */
273
+ export function concurrencyRetryDelayMs(attempt, baseMs = CONCURRENCY_RETRY_BASE_MS) {
274
+ const base = baseMs > 0 ? baseMs : CONCURRENCY_RETRY_BASE_MS
275
+ return base * (Math.max(0, Math.floor(attempt)) + 1)
276
+ }
277
+
278
+ /** 构造 Anthropic 形态的错误体(DSH 侧只读 message,但保持形态一致)。 */
279
+ export function anthropicErrorPayload(message, type = 'api_error') {
280
+ return { type: 'error', error: { type, message } }
281
+ }
@@ -0,0 +1,120 @@
1
+ /**
2
+ * 终止失败的**统一出口**:把任何上游原文收窄成「用户该看到的那一句」,code 保真。
3
+ *
4
+ * ## 为什么需要它
5
+ *
6
+ * issue #2:用户选的是 A 通道,界面里出现的却是 **B 通道**的上游原文
7
+ * (`429: {"message":"... soft_rate ...","code":"soft_rate"}`)—— 排查方向当场被带偏。
8
+ * 根因是「原样透出上游失败块」;只要某条链路(回退、翻译、兜底)把上游 chunk
9
+ * 直接 yield 给宿主,这个洞就会换个地方复现。
10
+ *
11
+ * 所以本模块提供两个原语,供**所有**失败收尾路径共用:
12
+ * - `sanitizeFailure()`:错误对象 → `{ code, message }`,message 只说人话;
13
+ * - `scrubFailureChunk()`:上游 chunk → 同样的 chunk 形状,但失败块已被脱敏。
14
+ *
15
+ * ## 约定
16
+ *
17
+ * - **code 保留**:宿主的重试策略 / 错误上报 / 回退判定都只认 code,脱敏绝不能改它;
18
+ * - **文案中性**:不出现上游厂商名、业务码、原始 JSON、URL、账号昵称以外的隐私;
19
+ * - **完整原因只进日志**:调用方拿到 `{ code, message }` 后自己决定 `log()` 什么。
20
+ */
21
+
22
+ import { isFallbackWorthyCode } from './errors.js'
23
+
24
+ /** 各类失败码面向用户的中性短句(不含任何上游原文)。 */
25
+ const FRIENDLY = Object.freeze({
26
+ QUOTA: '模型通道额度已用尽,请等待额度重置或切换模型 / 通道。',
27
+ TIMEOUT: '模型通道超时(上游未在预期时间内返回内容),请稍后重试或切换通道。',
28
+ RATE_LIMIT: '模型通道当前并发限流,请稍后重试,不要连续重试。',
29
+ /**
30
+ * 风控拦截是**账号级**的,文案必须与额度 / 并发区分开,否则用户会去等额度重置、
31
+ * 或反复点重试把冷却从 30 分钟推到 24 小时。这里只承诺「已自动清除限流标记」,
32
+ * 不承诺「马上一定成功」。
33
+ */
34
+ RISK_BLOCKED: '模型通道触发了上游风控拦截(非额度问题),已自动清除本账号的限流标记,可稍后重试,请勿连续重试。',
35
+ AUTH: '模型通道凭据失效,请重新登录该通道的账号。',
36
+ CAPTCHA_FAILED: '模型通道验证码(captcha)产出失败,请检查验证码载体是否可用。',
37
+ ABORTED: '请求已取消。',
38
+ PROVIDER_ERROR: '模型通道暂时不可用,请稍后重试。',
39
+ })
40
+
41
+ /** 未知码的兜底短句(同样不给上游原文)。 */
42
+ const GENERIC = '模型通道暂时不可用,请稍后重试。'
43
+
44
+ /**
45
+ * 把失败收窄成 `{ code, message }`。
46
+ *
47
+ * @param {{ code?: unknown, message?: unknown } | string | undefined | null} failure
48
+ * 上游失败载荷、插件自己的 Error、或裸字符串。
49
+ * @returns {{ code: string, message: string }} code 必定是非空字符串
50
+ */
51
+ export function sanitizeFailure(failure) {
52
+ if (failure === undefined || failure === null) return { code: 'PROVIDER_ERROR', message: GENERIC }
53
+ if (typeof failure === 'string') {
54
+ /** 裸字符串:上游原文不能直接给用户 —— 只保留其 code 语境(未知即 PROVIDER_ERROR)。 */
55
+ return { code: 'PROVIDER_ERROR', message: GENERIC }
56
+ }
57
+ const code = typeof failure.code === 'string' && failure.code.length > 0 ? failure.code : 'PROVIDER_ERROR'
58
+ return { code, message: FRIENDLY[code] ?? GENERIC }
59
+ }
60
+
61
+ /**
62
+ * 这次失败是否该由**回退链路**接手(而不是直接把它抛给宿主)。
63
+ *
64
+ * @param {unknown} failure 失败载荷 / Error
65
+ * @returns {boolean}
66
+ */
67
+ export function shouldFallback(failure) {
68
+ if (failure === undefined || failure === null) return false
69
+ const code = typeof failure === 'object' ? failure.code : undefined
70
+ return typeof code === 'string' && isFallbackWorthyCode(code)
71
+ }
72
+
73
+ /**
74
+ * 脱敏一个上游 chunk(失败块才动,其余原样返回**同一引用**)。
75
+ *
76
+ * 认两种形状:
77
+ * - `{ type: 'finish', reason: { kind: 'error', failure } }` —— DSH 协议终止块;
78
+ * - `{ type: 'error', code?, message }` —— 流内错误事件。
79
+ *
80
+ * @template T
81
+ * @param {T} chunk
82
+ * @returns {T}
83
+ */
84
+ export function scrubFailureChunk(chunk) {
85
+ if (chunk === null || typeof chunk !== 'object') return chunk
86
+ if (chunk.type === 'finish') {
87
+ const reason = chunk.reason
88
+ if (reason === null || typeof reason !== 'object' || reason.kind !== 'error') return chunk
89
+ const failure = reason.failure
90
+ if (failure === undefined || failure === null) return chunk
91
+ return { ...chunk, reason: { ...reason, failure: sanitizeFailure(failure) } }
92
+ }
93
+ if (chunk.type === 'error') {
94
+ const message = typeof chunk.message === 'string' ? chunk.message : undefined
95
+ if (message === undefined || message.length === 0) return chunk
96
+ const code = typeof chunk.code === 'string' && chunk.code.length > 0 ? chunk.code : 'PROVIDER_ERROR'
97
+ return { ...chunk, code, message: sanitizeFailure({ code, message }).message }
98
+ }
99
+ return chunk
100
+ }
101
+
102
+ /** 失败码的中性短句(供调用方拼自己的上下文,如「额度用尽 → 已于 … 重置」)。 */
103
+ export function friendlyFailureMessage(code) {
104
+ return FRIENDLY[code] ?? GENERIC
105
+ }
106
+
107
+ /**
108
+ * 把一次**已经落定**的失败块统一脱敏后交给宿主。
109
+ *
110
+ * 这是所有失败收尾路径(本通道、回退通道、端点转发、错误翻译)应该用的唯一出口:
111
+ * 调用方只负责搞清「code 是什么」,文案一律从这里出。
112
+ *
113
+ * @param {{ code?: string, message?: string } | undefined | null} failure
114
+ * @returns {{ type: 'finish', reason: { kind: 'error', failure: { code: string, message: string } } }}
115
+ */
116
+ export function terminalFailureChunk(failure) {
117
+ return { type: 'finish', reason: { kind: 'error', failure: sanitizeFailure(failure) } }
118
+ }
119
+
120
+ export { FRIENDLY as FRIENDLY_FAILURE_MESSAGES }