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.
- package/CHANGELOG.md +1963 -405
- package/README.md +88 -405
- package/bin/cli.mjs +509 -450
- package/client.js +2459 -716
- package/cordis.patch.yml +4 -2
- package/index.js +144 -14
- package/lib/adapter.js +476 -422
- package/lib/anthropic-body.js +513 -469
- package/lib/assemble.js +808 -420
- package/lib/auto-claim.js +229 -0
- package/lib/captcha/minter.js +61 -7
- package/lib/distribution-keys.js +202 -0
- package/lib/errors.js +281 -125
- package/lib/fallback.js +120 -0
- package/lib/local-endpoint.js +367 -352
- package/lib/manage-routes.js +1245 -489
- package/lib/model-catalog.js +57 -0
- package/lib/openai-gateway.js +776 -0
- package/lib/plan-client.js +942 -532
- package/lib/pool.js +771 -478
- package/lib/sse.js +429 -317
- package/lib/upstream-api.js +948 -570
- package/lib/upstream.js +294 -134
- package/lib/version-probe.js +110 -0
- package/package.json +84 -80
- package/scripts/analyze-grant-intervals.mjs +171 -0
- package/scripts/check-compat-rc3.mjs +21 -11
- package/scripts/debug-claimable.mjs +130 -0
- package/scripts/probe-marketing.mjs +203 -0
- package/scripts/restart-dsh.ps1 +119 -76
- package/scripts/test-claimed-pending.mjs +152 -0
- package/scripts/verify_compat.mjs +75 -64
- package/scripts/watch-marketing.mjs +155 -0
- package/tests/anthropic-body.test.mjs +305 -0
- package/tests/assembler-contract.test.mjs +256 -0
- package/tests/auto-claim.test.mjs +318 -0
- package/tests/claim-routes.test.mjs +438 -0
- package/tests/client-panel.test.mjs +1141 -0
- package/tests/distribution-keys.test.mjs +123 -0
- package/tests/e2e.test.mjs +388 -0
- package/tests/fallback-scrub.test.mjs +105 -0
- package/tests/fixtures/quota-200.json +1 -0
- package/tests/launch-command.test.mjs +68 -0
- package/tests/login-channel.test.mjs +102 -0
- package/tests/openai-gateway.test.mjs +454 -0
- package/tests/pinned-models.test.mjs +505 -0
- package/tests/plan-client.test.mjs +582 -0
- package/tests/pool.test.mjs +319 -0
- package/tests/quota-blackhole.test.mjs +409 -0
- package/tests/restart-script.test.mjs +53 -0
- package/tests/routing-quota.test.mjs +251 -0
- package/tests/sse.test.mjs +86 -0
- package/tests/stream-translator.test.mjs +137 -0
- package/tests/support/hanging-stream.mjs +48 -0
- package/tests/support/resolve-profile-deps.mjs +52 -0
- package/tests/upstream-error-200.test.mjs +164 -0
- package/tests/upstream.test.mjs +330 -0
- package/tests/version-probe.test.mjs +172 -0
package/lib/sse.js
CHANGED
|
@@ -1,317 +1,429 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* SSE / JSON 响应首部判定(**「秒回空」检测**)。
|
|
3
|
-
*
|
|
4
|
-
* 上游在「该账号对该模型无权益」时会返回 **HTTP 200 + 一个没有任何内容帧的 SSE 流**。
|
|
5
|
-
* 若直接当正文消费,用户看到的是「模型返回了空响应」;正确处理是**换账号重试**。
|
|
6
|
-
*
|
|
7
|
-
* 透传与重试天然冲突:一旦把内容交给调用方就不能再重试(会出现两份输出)。
|
|
8
|
-
* 故这里**先读到出现内容再决定**:
|
|
9
|
-
* - 见到内容 → 把缓冲的事件原样交给调用方,后续继续流式解析;
|
|
10
|
-
* - 流结束仍无内容 → 判定为无权益,调用方换号重试(调用方**一个 chunk 都没收到**)。
|
|
11
|
-
*
|
|
12
|
-
* ⚠ 判定必须按媒体类型分流:上游对**不带 `stream` 的请求返回单个 JSON message**;
|
|
13
|
-
* 若只用 SSE 特征串去扫,一个正常有内容的 JSON 会被判成「零内容」,
|
|
14
|
-
* 于是①客户端拿到空响应 ②**该账号被错误标记限流到当日结束**。
|
|
15
|
-
*/
|
|
16
|
-
|
|
17
|
-
/** SSE 内容帧的特征串(覆盖文本、思考、工具调用三类)。 */
|
|
18
|
-
const CONTENT_MARKERS = [
|
|
19
|
-
'content_block_delta',
|
|
20
|
-
'text_delta',
|
|
21
|
-
'thinking_delta',
|
|
22
|
-
'input_json_delta',
|
|
23
|
-
'"type":"tool_use"',
|
|
24
|
-
'"type": "tool_use"',
|
|
25
|
-
]
|
|
26
|
-
|
|
27
|
-
/** 缓冲上限(异常大的首帧不能无限缓冲;超限即按「有内容」放行,宁可让它自己失败也不要 OOM)。 */
|
|
28
|
-
export const DEFAULT_MAX_BUFFER_BYTES = 256 * 1024
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
*/
|
|
41
|
-
export function
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
}
|
|
64
|
-
return false
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
*
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
const
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
1
|
+
/**
|
|
2
|
+
* SSE / JSON 响应首部判定(**「秒回空」检测**)。
|
|
3
|
+
*
|
|
4
|
+
* 上游在「该账号对该模型无权益」时会返回 **HTTP 200 + 一个没有任何内容帧的 SSE 流**。
|
|
5
|
+
* 若直接当正文消费,用户看到的是「模型返回了空响应」;正确处理是**换账号重试**。
|
|
6
|
+
*
|
|
7
|
+
* 透传与重试天然冲突:一旦把内容交给调用方就不能再重试(会出现两份输出)。
|
|
8
|
+
* 故这里**先读到出现内容再决定**:
|
|
9
|
+
* - 见到内容 → 把缓冲的事件原样交给调用方,后续继续流式解析;
|
|
10
|
+
* - 流结束仍无内容 → 判定为无权益,调用方换号重试(调用方**一个 chunk 都没收到**)。
|
|
11
|
+
*
|
|
12
|
+
* ⚠ 判定必须按媒体类型分流:上游对**不带 `stream` 的请求返回单个 JSON message**;
|
|
13
|
+
* 若只用 SSE 特征串去扫,一个正常有内容的 JSON 会被判成「零内容」,
|
|
14
|
+
* 于是①客户端拿到空响应 ②**该账号被错误标记限流到当日结束**。
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
/** SSE 内容帧的特征串(覆盖文本、思考、工具调用三类)。 */
|
|
18
|
+
const CONTENT_MARKERS = [
|
|
19
|
+
'content_block_delta',
|
|
20
|
+
'text_delta',
|
|
21
|
+
'thinking_delta',
|
|
22
|
+
'input_json_delta',
|
|
23
|
+
'"type":"tool_use"',
|
|
24
|
+
'"type": "tool_use"',
|
|
25
|
+
]
|
|
26
|
+
|
|
27
|
+
/** 缓冲上限(异常大的首帧不能无限缓冲;超限即按「有内容」放行,宁可让它自己失败也不要 OOM)。 */
|
|
28
|
+
export const DEFAULT_MAX_BUFFER_BYTES = 256 * 1024
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 首内容超时的错误标记(`error.code === HEAD_TIMEOUT_CODE`)。
|
|
32
|
+
*
|
|
33
|
+
* 为什么需要一个可识别的码:额度用尽(1005)之后,本渠道的上游**不再出流** ——
|
|
34
|
+
* HTTP 200 + 永不产出事件的 SSE 流。这类「黑洞」与真网络故障在用户侧观感相同,
|
|
35
|
+
* 但处置完全不同:前者该立刻改道(回退通道 / 换模型),后者该重试网络。
|
|
36
|
+
* 调用方据此落 `TIMEOUT` 而不是笼统的 `PROVIDER_ERROR`。
|
|
37
|
+
*/
|
|
38
|
+
export const HEAD_TIMEOUT_CODE = 'ZCODE_HEAD_TIMEOUT'
|
|
39
|
+
|
|
40
|
+
/** 这是不是一次「首内容超时」(而非流内静默 / 网络错误)。 */
|
|
41
|
+
export function isHeadTimeoutError(error) {
|
|
42
|
+
return error?.code === HEAD_TIMEOUT_CODE
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** 是否按 JSON(非流式)形态判定。 */
|
|
46
|
+
export function isJsonContentType(contentType) {
|
|
47
|
+
if (contentType === undefined) return false
|
|
48
|
+
const lower = String(contentType).toLowerCase()
|
|
49
|
+
return lower.includes('application/json') && !lower.includes('event-stream')
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* 从**已解析的 JSON message** 判断是否真有内容。
|
|
54
|
+
* 只认「有实际产物的块」:文本非空 / 思考非空 / 工具调用块本身即内容。
|
|
55
|
+
*/
|
|
56
|
+
export function jsonHasContent(text) {
|
|
57
|
+
let parsed
|
|
58
|
+
try {
|
|
59
|
+
parsed = JSON.parse(text)
|
|
60
|
+
} catch {
|
|
61
|
+
// 解析不动就保守按「有内容」:不要冤枉账号。
|
|
62
|
+
return true
|
|
63
|
+
}
|
|
64
|
+
if (typeof parsed !== 'object' || parsed === null) return false
|
|
65
|
+
/** 错误载荷算「有响应」,由调用方的错误处理负责 —— 不能当成额度耗尽去换号。 */
|
|
66
|
+
if (parsed.type === 'error' || parsed.error !== undefined) return true
|
|
67
|
+
const content = parsed.content
|
|
68
|
+
if (!Array.isArray(content)) {
|
|
69
|
+
const output = parsed.usage?.output_tokens
|
|
70
|
+
return typeof output === 'number' && output > 0
|
|
71
|
+
}
|
|
72
|
+
for (const raw of content) {
|
|
73
|
+
if (typeof raw !== 'object' || raw === null) continue
|
|
74
|
+
if (raw.type === 'tool_use') return true
|
|
75
|
+
if (raw.type === 'text' && typeof raw.text === 'string' && raw.text.length > 0) return true
|
|
76
|
+
if (raw.type === 'thinking' && typeof raw.thinking === 'string' && raw.thinking.length > 0) return true
|
|
77
|
+
if (raw.type === 'redacted_thinking') return true
|
|
78
|
+
}
|
|
79
|
+
return false
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* 把字节流切成 SSE 事件(`data:` 行拼装)。返回 async generator(产出原始事件对象)。
|
|
84
|
+
*
|
|
85
|
+
* 解析同时保留**原始字节**,以便调用方在「判定有内容」后能原样重放首部。
|
|
86
|
+
*/
|
|
87
|
+
export async function* readSseEvents(body, options = {}) {
|
|
88
|
+
const decode = makeSseDecoder(body, options)
|
|
89
|
+
try {
|
|
90
|
+
for (;;) {
|
|
91
|
+
const next = await decode.read()
|
|
92
|
+
if (next.done === true) return
|
|
93
|
+
yield next.value
|
|
94
|
+
}
|
|
95
|
+
} finally {
|
|
96
|
+
await decode.cancel()
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* 构造一个「可交接」的 SSE 解码器。
|
|
102
|
+
*
|
|
103
|
+
* ⚠ 为什么不是 `async function*`:`readContentHead` 判定出「有内容」后要**继续**用同一个
|
|
104
|
+
* 读取器消费剩余事件(首部事件已缓冲)。生成器无法把内部 `reader` 交出去而不丢失已读字节,
|
|
105
|
+
* 所以这里显式暴露 `read()` / `cancel()`,由两处共享。
|
|
106
|
+
*
|
|
107
|
+
* @param {ReadableStream<Uint8Array>} body
|
|
108
|
+
* @param {{ timeoutMs?: number }} [options]
|
|
109
|
+
*/
|
|
110
|
+
export function makeSseDecoder(body, options = {}) {
|
|
111
|
+
const decoder = new TextDecoder()
|
|
112
|
+
const reader = body.getReader()
|
|
113
|
+
const timeoutMs = options.timeoutMs ?? 180_000
|
|
114
|
+
/**
|
|
115
|
+
* 首内容超时的独立预算(缺省 = 同 `timeoutMs`)。
|
|
116
|
+
*
|
|
117
|
+
* ⚠ 与 `timeoutMs` 拆开的原因(issue #4):`timeoutMs` 是**流内静默**上限,
|
|
118
|
+
* 长思考/长工具参数需要宽裕;而「首内容」等的是上游**会不会出流**,
|
|
119
|
+
* 宽裕只会把用户钉在黑洞里等宿主的 ~300s 超时。给首内容一个更短的预算,
|
|
120
|
+
* 命中即抛可识别的 `HEAD_TIMEOUT_CODE`,让上层落 TIMEOUT 而不是 PROVIDER_ERROR。
|
|
121
|
+
*/
|
|
122
|
+
const headTimeoutMs = options.headTimeoutMs ?? timeoutMs
|
|
123
|
+
/** 是否已产出过内容(由 `readContentHead` 在交出解码器时置位)。 */
|
|
124
|
+
let sawContent = false
|
|
125
|
+
let buffer = ''
|
|
126
|
+
let finished = false
|
|
127
|
+
/** 已读到但还没返回的完整事件(`\n\n` 分隔)。 */
|
|
128
|
+
const ready = []
|
|
129
|
+
|
|
130
|
+
const pump = async () => {
|
|
131
|
+
const budgetMs = sawContent ? timeoutMs : headTimeoutMs
|
|
132
|
+
const headPhase = !sawContent
|
|
133
|
+
/**
|
|
134
|
+
* ⚠ **不要** `timer.unref()`(本仓库曾在这里踩过两次):
|
|
135
|
+
* 一旦 `unref`,在「读操作把事件循环占满」的场景里这个定时器**永远不会触发**,
|
|
136
|
+
* 超时保护形同虚设 —— 正是 issue #4 里「挂满宿主 300s」的成因之一。
|
|
137
|
+
* 所以这里显式 `clearTimeout`:读到数据就取消,绝不留悬空定时器拖住进程。
|
|
138
|
+
*/
|
|
139
|
+
let timer
|
|
140
|
+
const chunk = await Promise.race([
|
|
141
|
+
reader.read(),
|
|
142
|
+
new Promise((_resolve, reject) => {
|
|
143
|
+
timer = setTimeout(
|
|
144
|
+
() =>
|
|
145
|
+
reject(
|
|
146
|
+
Object.assign(new Error(`读取上游响应超时(${budgetMs}ms,${headPhase ? '未收到首内容' : '流内静默'})`), {
|
|
147
|
+
...(headPhase ? { code: HEAD_TIMEOUT_CODE } : {}),
|
|
148
|
+
phase: headPhase ? 'head' : 'body',
|
|
149
|
+
timeoutMs: budgetMs,
|
|
150
|
+
}),
|
|
151
|
+
),
|
|
152
|
+
budgetMs,
|
|
153
|
+
)
|
|
154
|
+
}),
|
|
155
|
+
]).finally(() => clearTimeout(timer))
|
|
156
|
+
if (chunk.done === true) {
|
|
157
|
+
finished = true
|
|
158
|
+
/**
|
|
159
|
+
* ⚠ 必须先 flush `TextDecoder`(多字节字符可能被拆在 chunk 边界):
|
|
160
|
+
* 不 flush 会让同一个网络包里到达的**最后一个事件**在 EOF 时被吞掉——
|
|
161
|
+
* 表现为「只收到第一个 text-delta,后面全丢」(实测抓到的真实缺陷)。
|
|
162
|
+
*/
|
|
163
|
+
buffer += decoder.decode()
|
|
164
|
+
const tail = buffer.trim()
|
|
165
|
+
buffer = ''
|
|
166
|
+
if (tail.length > 0) {
|
|
167
|
+
const event = parseSseEvent(tail)
|
|
168
|
+
if (event !== undefined) ready.push(event)
|
|
169
|
+
}
|
|
170
|
+
return
|
|
171
|
+
}
|
|
172
|
+
if (chunk.value === undefined) return
|
|
173
|
+
buffer += decoder.decode(chunk.value, { stream: true })
|
|
174
|
+
for (;;) {
|
|
175
|
+
const match = /\r?\n\r?\n/.exec(buffer)
|
|
176
|
+
if (match === null) break
|
|
177
|
+
const raw = buffer.slice(0, match.index)
|
|
178
|
+
buffer = buffer.slice(match.index + match[0].length)
|
|
179
|
+
const event = parseSseEvent(raw)
|
|
180
|
+
if (event !== undefined) ready.push(event)
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
/** 读下一个事件;流结束返回 `{ done: true }`。 */
|
|
186
|
+
async read() {
|
|
187
|
+
for (;;) {
|
|
188
|
+
const queued = ready.shift()
|
|
189
|
+
if (queued !== undefined) {
|
|
190
|
+
sawContent = true
|
|
191
|
+
return { done: false, value: queued }
|
|
192
|
+
}
|
|
193
|
+
if (finished) return { done: true }
|
|
194
|
+
await pump()
|
|
195
|
+
/** 空事件块(`: keep-alive` 注释)不产出任何东西,继续读。 */
|
|
196
|
+
}
|
|
197
|
+
},
|
|
198
|
+
/**
|
|
199
|
+
* 调用方判定「确实有内容」后调用:此后读预算切到流内静默 `timeoutMs`。
|
|
200
|
+
* 不调用也不会死锁 —— 首个真正产出的事件同样会置位。
|
|
201
|
+
*/
|
|
202
|
+
markContent() {
|
|
203
|
+
sawContent = true
|
|
204
|
+
},
|
|
205
|
+
/** 取消读取(客户端断开 / 换号重试时立刻释放上游连接)。 */
|
|
206
|
+
async cancel() {
|
|
207
|
+
if (finished) return
|
|
208
|
+
finished = true
|
|
209
|
+
try {
|
|
210
|
+
await reader.cancel()
|
|
211
|
+
} catch {
|
|
212
|
+
// 已结束。
|
|
213
|
+
}
|
|
214
|
+
},
|
|
215
|
+
/** 是否已读完。 */
|
|
216
|
+
get done() {
|
|
217
|
+
return finished && ready.length === 0
|
|
218
|
+
},
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
/** 解析一个 SSE 事件块;无 `data:` 行返回 undefined。 */
|
|
223
|
+
export function parseSseEvent(raw) {
|
|
224
|
+
const lines = raw.split(/\r?\n/)
|
|
225
|
+
let eventName
|
|
226
|
+
const dataLines = []
|
|
227
|
+
for (const line of lines) {
|
|
228
|
+
if (line.length === 0 || line.startsWith(':')) continue
|
|
229
|
+
const colon = line.indexOf(':')
|
|
230
|
+
const field = colon === -1 ? line : line.slice(0, colon)
|
|
231
|
+
let value = colon === -1 ? '' : line.slice(colon + 1)
|
|
232
|
+
if (value.startsWith(' ')) value = value.slice(1)
|
|
233
|
+
if (field === 'event') eventName = value
|
|
234
|
+
else if (field === 'data') dataLines.push(value)
|
|
235
|
+
}
|
|
236
|
+
if (dataLines.length === 0) return undefined
|
|
237
|
+
const data = dataLines.join('\n')
|
|
238
|
+
if (data === '[DONE]') return { event: eventName, data: '[DONE]' }
|
|
239
|
+
try {
|
|
240
|
+
return { event: eventName, data: JSON.parse(data), raw: data }
|
|
241
|
+
} catch {
|
|
242
|
+
return { event: eventName, data: undefined, raw: data, unparsed: true }
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
/**
|
|
247
|
+
* 「先读到出现内容或流结束」——返回 `{ hasContent, head, elapsedMs, decoder, upstreamError, timeoutError }`。
|
|
248
|
+
*
|
|
249
|
+
* `head` 是**已解析但尚未交给调用方**的初始事件(含内容帧),调用方在决定「确实有内容」
|
|
250
|
+
* 后按序消费它,再接续后面的流。
|
|
251
|
+
*
|
|
252
|
+
* `timeoutError` 出现即代表**上游黑洞**(首内容超时 / 流内静默):此时 `hasContent=false`,
|
|
253
|
+
* 调用方应按 TIMEOUT 处置(而不是零内容 / PROVIDER_ERROR)。见 `HEAD_TIMEOUT_CODE`。
|
|
254
|
+
*
|
|
255
|
+
* ⚠ **上游会把业务错误塞进 HTTP 200**(实测:`{"code":1005,"msg":"exceed quota limit"}`
|
|
256
|
+
* 配 `200 + application/json`)。若不识别,就会被当成「无权益的空响应」,
|
|
257
|
+
* 于是丢掉真正的错误码(`1005` 额度用尽 / `3012` 风控 / `3009` 并发限流),
|
|
258
|
+
* 排查时只看到误导性的「200 但零内容」。故这里先做业务错误识别。
|
|
259
|
+
*/
|
|
260
|
+
export async function readContentHead(body, options = {}) {
|
|
261
|
+
const startedAt = Date.now()
|
|
262
|
+
const maxBufferBytes = options.maxBufferBytes ?? DEFAULT_MAX_BUFFER_BYTES
|
|
263
|
+
const jsonMode = isJsonContentType(options.contentType)
|
|
264
|
+
const head = []
|
|
265
|
+
let scannedBytes = 0
|
|
266
|
+
|
|
267
|
+
if (jsonMode) {
|
|
268
|
+
/**
|
|
269
|
+
* 非流式 JSON 同样会黑洞:`await text()` 没有预算,上游不出字节就一直挂着,
|
|
270
|
+
* 最后被宿主的 ~300s 超时收成 PROVIDER_ERROR。这里给首内容同样的预算。
|
|
271
|
+
*/
|
|
272
|
+
const budgetMs = options.headTimeoutMs ?? options.timeoutMs ?? 180_000
|
|
273
|
+
let text
|
|
274
|
+
try {
|
|
275
|
+
/** 同 `pump()`:显式 `clearTimeout`,绝不用 `unref`(见那里的说明)。 */
|
|
276
|
+
let timer
|
|
277
|
+
text = await Promise.race([
|
|
278
|
+
new Response(body).text(),
|
|
279
|
+
new Promise((_resolve, reject) => {
|
|
280
|
+
timer = setTimeout(
|
|
281
|
+
() =>
|
|
282
|
+
reject(
|
|
283
|
+
Object.assign(new Error(`读取上游响应超时(${budgetMs}ms,未收到首内容)`), {
|
|
284
|
+
code: HEAD_TIMEOUT_CODE,
|
|
285
|
+
phase: 'head',
|
|
286
|
+
timeoutMs: budgetMs,
|
|
287
|
+
}),
|
|
288
|
+
),
|
|
289
|
+
budgetMs,
|
|
290
|
+
)
|
|
291
|
+
}),
|
|
292
|
+
]).finally(() => clearTimeout(timer))
|
|
293
|
+
} catch (error) {
|
|
294
|
+
return {
|
|
295
|
+
hasContent: false,
|
|
296
|
+
head,
|
|
297
|
+
elapsedMs: Date.now() - startedAt,
|
|
298
|
+
jsonMode: true,
|
|
299
|
+
decoder: undefined,
|
|
300
|
+
timeoutError: error,
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
let parsed
|
|
304
|
+
try {
|
|
305
|
+
parsed = JSON.parse(text)
|
|
306
|
+
} catch {
|
|
307
|
+
parsed = undefined
|
|
308
|
+
}
|
|
309
|
+
/** 业务错误(HTTP 200 + `{code,msg}`):先于「有没有内容」判定。 */
|
|
310
|
+
const upstreamError = extractUpstreamError(parsed, text)
|
|
311
|
+
if (upstreamError !== undefined) {
|
|
312
|
+
return {
|
|
313
|
+
hasContent: false,
|
|
314
|
+
head,
|
|
315
|
+
elapsedMs: Date.now() - startedAt,
|
|
316
|
+
jsonMode: true,
|
|
317
|
+
decoder: undefined,
|
|
318
|
+
upstreamError,
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const hasContent = jsonHasContent(text)
|
|
322
|
+
if (hasContent) head.push({ data: parsed, raw: text })
|
|
323
|
+
return { hasContent, head, elapsedMs: Date.now() - startedAt, jsonMode: true, decoder: undefined }
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
const decoder = makeSseDecoder(body, { timeoutMs: options.timeoutMs, headTimeoutMs: options.headTimeoutMs })
|
|
327
|
+
for (;;) {
|
|
328
|
+
let next
|
|
329
|
+
try {
|
|
330
|
+
next = await decoder.read()
|
|
331
|
+
} catch (error) {
|
|
332
|
+
/**
|
|
333
|
+
* 上游黑洞(HTTP 200 却不让出内容 —— 额度用尽后的典型表现)。
|
|
334
|
+
*
|
|
335
|
+
* 不能把异常直接抛给宿主:宿主只会把它翻成笼统的 `PROVIDER_ERROR`
|
|
336
|
+
* (超时或不可用),回退链路与用户提示都没机会拿到真因。这里把它
|
|
337
|
+
* **收窄成本次请求的一次失败**,由调用方按 TIMEOUT 处置。
|
|
338
|
+
*/
|
|
339
|
+
await decoder.cancel()
|
|
340
|
+
return {
|
|
341
|
+
hasContent: false,
|
|
342
|
+
head,
|
|
343
|
+
elapsedMs: Date.now() - startedAt,
|
|
344
|
+
jsonMode: false,
|
|
345
|
+
decoder,
|
|
346
|
+
timeoutError: error,
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
if (next.done === true) {
|
|
350
|
+
await decoder.cancel()
|
|
351
|
+
return { hasContent: false, head, elapsedMs: Date.now() - startedAt, jsonMode: false, decoder }
|
|
352
|
+
}
|
|
353
|
+
const event = next.value
|
|
354
|
+
head.push(event)
|
|
355
|
+
scannedBytes += (event.raw ?? '').length
|
|
356
|
+
/** 流内错误事件(Anthropic `{"type":"error"}`)也算业务错误,交给调用方按错误表处置。 */
|
|
357
|
+
const upstreamError = extractUpstreamError(event.data, event.raw ?? '')
|
|
358
|
+
if (upstreamError !== undefined) {
|
|
359
|
+
await decoder.cancel()
|
|
360
|
+
return {
|
|
361
|
+
hasContent: false,
|
|
362
|
+
head,
|
|
363
|
+
elapsedMs: Date.now() - startedAt,
|
|
364
|
+
jsonMode: false,
|
|
365
|
+
decoder,
|
|
366
|
+
upstreamError,
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
const marker = CONTENT_MARKERS.some((needle) => (event.raw ?? '').includes(needle)) || hasVisibleBlock(event.data)
|
|
370
|
+
if (marker || scannedBytes >= maxBufferBytes) {
|
|
371
|
+
/** 把解码器交给调用方继续消费(而非丢弃剩余事件);此后预算切到流内静默。 */
|
|
372
|
+
decoder.markContent()
|
|
373
|
+
return { hasContent: true, head, elapsedMs: Date.now() - startedAt, jsonMode: false, decoder }
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
/**
|
|
379
|
+
* 从已解析的载荷里识别**上游业务错误**。
|
|
380
|
+
*
|
|
381
|
+
* 认三种形态:
|
|
382
|
+
* - `{"code":1005,"msg":"..."}`(本渠道实测形态,状态码仍是 200)
|
|
383
|
+
* - `{"type":"error","error":{...}}`(Anthropic 标准错误)
|
|
384
|
+
* - `{"error":{"code":1005,...}}`(个别网关的包裹形态)
|
|
385
|
+
*
|
|
386
|
+
* @param {unknown} parsed
|
|
387
|
+
* @param {string} raw
|
|
388
|
+
* @returns {{ status: number, text: string } | undefined}
|
|
389
|
+
*/
|
|
390
|
+
export function extractUpstreamError(parsed, raw) {
|
|
391
|
+
if (typeof parsed === 'object' && parsed !== null) {
|
|
392
|
+
const record = /** @type {Record<string, any>} */ (parsed)
|
|
393
|
+
/** Anthropic 标准错误载荷。 */
|
|
394
|
+
if (record.type === 'error' && record.error !== undefined) {
|
|
395
|
+
return { status: 200, text: JSON.stringify(record) }
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* 业务码形态:`code` 非 0 且不是字符串型成功码。
|
|
399
|
+
* 注意 `code: 0` = 成功,不能被当成错误。
|
|
400
|
+
*/
|
|
401
|
+
const code = record.code ?? record.error?.code
|
|
402
|
+
if (typeof code === 'number' && code !== 0) {
|
|
403
|
+
return { status: 200, text: JSON.stringify({ code, msg: record.msg ?? record.message ?? record.error?.message ?? '' }) }
|
|
404
|
+
}
|
|
405
|
+
/** 裸 `error` 字段(无 code)。 */
|
|
406
|
+
if (record.error !== undefined && typeof record.error === 'object') {
|
|
407
|
+
return { status: 200, text: JSON.stringify(record) }
|
|
408
|
+
}
|
|
409
|
+
}
|
|
410
|
+
return undefined
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
/** 事件里是否出现了可见块(结构性判定,比扫特征串更稳)。 */
|
|
414
|
+
function hasVisibleBlock(data) {
|
|
415
|
+
if (typeof data !== 'object' || data === null) return false
|
|
416
|
+
if (data.type === 'content_block_start') {
|
|
417
|
+
const block = data.content_block
|
|
418
|
+
if (block?.type === 'tool_use') return true
|
|
419
|
+
if (block?.type === 'text' && typeof block.text === 'string' && block.text.length > 0) return true
|
|
420
|
+
if (block?.type === 'thinking' && typeof block.thinking === 'string' && block.thinking.length > 0) return true
|
|
421
|
+
}
|
|
422
|
+
if (data.type === 'content_block_delta') {
|
|
423
|
+
const delta = data.delta
|
|
424
|
+
if (delta?.type === 'text_delta' && typeof delta.text === 'string' && delta.text.length > 0) return true
|
|
425
|
+
if (delta?.type === 'thinking_delta' && typeof delta.thinking === 'string' && delta.thinking.length > 0) return true
|
|
426
|
+
if (delta?.type === 'input_json_delta') return true
|
|
427
|
+
}
|
|
428
|
+
return false
|
|
429
|
+
}
|