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
@@ -0,0 +1,776 @@
1
+ /**
2
+ * 本地 **OpenAI 兼容端点**:`/v1/chat/completions` + `/v1/models`。
3
+ *
4
+ * ## 它是什么 / 不是什么
5
+ *
6
+ * 本文件与 `local-endpoint.js`(Anthropic 格式 `/v1/messages`)**并列**:
7
+ * 两者都是「把 DSH 的 StreamChunk 翻译成某个 HTTP 协议」的出口,回落到同一个
8
+ * `planClient.call()` —— 账号池、换号、captcha、限流全部复用,不另起一套。
9
+ *
10
+ * 用途:让**任意 OpenAI 兼容客户端**(Codex / Cline / Continue / 自写脚本)
11
+ * 直接用 `baseURL = http://127.0.0.1:<port>/v1` + `apiKey = <插件生成的 key>`
12
+ * 消耗账号池额度。
13
+ *
14
+ * ## 与 `local-endpoint.js` 的取舍
15
+ *
16
+ * 那份 Anthropic 出口是「原样转发上游 SSE」,字节级透传、零翻译,可靠但只服务
17
+ * 一类客户端。OpenAI 这边**必须真翻译**(两边 chunk 词汇完全不同),故这里
18
+ * 严格对齐参考实现 `deepseek-harness-codearts` 的 `openai-gateway/` 三件套
19
+ * (`stream.ts` / `messages.ts` / `auth.ts`)的实测结论 —— 尤其下面这几个坑:
20
+ *
21
+ * | 坑 | 症状 | 对策 |
22
+ * |---|---|---|
23
+ * | `typeof x === 'string'` vs `!== undefined` | 真实 SSE 里 `content` 与 `reasoning_content` **另一侧恒为 null** ⇒ `.length` 在 null 上崩,首帧就炸 | 一律 `typeof === 'string'` |
24
+ * | 孤儿 `tool` 消息 | 上游 400,而坏历史每轮原样重放 ⇒ **会话永久报废** | 发请求前剔除配对已坏的结果 |
25
+ * | 分片带空 `function.name` | 清空已解析的工具名 ⇒ `unknown tool ""` | 只接受非空覆盖 |
26
+ * | 上游 `{status:200}` 表业务失败 | 原样透出会让「额度用尽」在客户端眼里读成**成功** | 状态码门禁 400–599 |
27
+ */
28
+
29
+ import { createServer } from 'node:http'
30
+ import { randomUUID } from 'node:crypto'
31
+ import { checkDistributionKey } from './distribution-keys.js'
32
+ import { checkModelId } from './model-catalog.js'
33
+
34
+ /** 单次请求体上限(防止一个坏客户端把内存吃穿)。 */
35
+ const BODY_LIMIT_BYTES = 32 * 1024 * 1024
36
+
37
+ /**
38
+ * 启动 OpenAI 兼容端点。
39
+ *
40
+ * @param {{
41
+ * port?: number,
42
+ * host?: string,
43
+ * planClient: any,
44
+ * models: () => Promise<Array<any>>,
45
+ * log?: (message: string) => void,
46
+ * }} options
47
+ */
48
+ export async function startOpenAiGateway(options) {
49
+ const host = options.host ?? '127.0.0.1'
50
+ const log = options.log ?? (() => {})
51
+ const requestedPort = options.port ?? 17_900
52
+
53
+ const server = createServer((req, res) => {
54
+ void handle(req, res).catch((error) => {
55
+ log(`[openai-gateway] 未捕获错误:${String(error)}`)
56
+ try {
57
+ jsonError(res, 500, 'server_error', String(error))
58
+ } catch {
59
+ // 响应可能已开始。
60
+ }
61
+ })
62
+ })
63
+
64
+ async function handle(req, res) {
65
+ /**
66
+ * ⚠ **刻意不设 CORS**(0.10.0 审计 S5)。
67
+ *
68
+ * 旧实现有一个 `OPTIONS` 分支,回 `access-control-allow-origin: *`。问题是:
69
+ * ① 预检请求**带不了 Authorization** ⇒ 该分支必然发生在鉴权之前;
70
+ * ② 分发 key 是静态 Bearer,浏览器一旦持有它,任意网页都能跨源拿它对账号池
71
+ * 烧额度(CORS 是浏览器侧的「谁可以读响应」,不是服务端的访问控制)。
72
+ * 本网关的消费方是 Codex / Cline / Continue 这类**本地原生客户端**,它们不受
73
+ * 同源策略约束,不需要 CORS。需要浏览器端调用的用户请用服务端反代,而不是
74
+ * 在这里放开通配。
75
+ */
76
+ const url = new URL(req.url ?? '/', `http://${host}`)
77
+
78
+ /** 健康检查刻意**不需要** key(探活工具不该持凭据)。 */
79
+ if (url.pathname === '/health') {
80
+ res.writeHead(200, { 'content-type': 'application/json' })
81
+ res.end(JSON.stringify({ ok: true }))
82
+ return
83
+ }
84
+
85
+ /**
86
+ * 鉴权(0.9.5):**只认分发 key**——主 apiKey 已废除(用户决策)。
87
+ * 没创建任何分发 key 时网关拒绝所有请求;限额/禁用判定在此一并完成。
88
+ */
89
+ const presented = extractBearer(req)
90
+ const distKey = options.findDistributionKey?.(presented)
91
+ const rejection = distKey === undefined
92
+ ? (presented === null ? 'Missing API key' : '无效的分发 key')
93
+ : checkDistributionKey(distKey)
94
+ if (rejection !== null) {
95
+ jsonError(res, distKey === undefined ? 401 : 429, distKey === undefined ? 'invalid_api_key' : 'quota_exceeded', rejection)
96
+ return
97
+ }
98
+
99
+ if (url.pathname === '/v1/models' && req.method === 'GET') {
100
+ const models = await options.models().catch(() => [])
101
+ res.writeHead(200, { 'content-type': 'application/json' })
102
+ res.end(
103
+ JSON.stringify({
104
+ object: 'list',
105
+ data: models.map((model) => ({
106
+ id: model.id,
107
+ object: 'model',
108
+ created: 0,
109
+ owned_by: 'zcode-start-plan',
110
+ })),
111
+ }),
112
+ )
113
+ return
114
+ }
115
+
116
+ if (url.pathname !== '/v1/chat/completions' || req.method !== 'POST') {
117
+ jsonError(res, 404, 'not_found', `未知端点 ${url.pathname}(支持 GET /v1/models、POST /v1/chat/completions)`)
118
+ return
119
+ }
120
+
121
+ let body
122
+ try {
123
+ body = JSON.parse(await readBody(req))
124
+ } catch (error) {
125
+ jsonError(res, error?.code === 'BODY_TOO_LARGE' ? 413 : 400, 'invalid_request_error', String(error?.message ?? error))
126
+ return
127
+ }
128
+
129
+ let generateOptions
130
+ try {
131
+ generateOptions = toGenerateOptions(body)
132
+ } catch (error) {
133
+ jsonError(res, 400, 'invalid_request_error', String(error?.message ?? error))
134
+ return
135
+ }
136
+
137
+ /**
138
+ * 模型 id 准入(0.10.0 审计 S6):**必须在 `planClient.call` 之前**。
139
+ *
140
+ * `plan-client` 按模型选号;上游对不存在的模型回 200 + 零内容,而被判成
141
+ * 「该账号×模型当日用尽」⇒ 一次拼错的模型名就能把整个池子标限流到当日。
142
+ * 目录取不到(空)时不拦(见 model-catalog.js)。
143
+ */
144
+ const catalog = await options.models().catch(() => [])
145
+ const modelCheck = checkModelId(body?.model, catalog)
146
+ if (!modelCheck.ok) {
147
+ log(`[openai-gateway] 拒绝未知模型请求:${modelCheck.reason}`)
148
+ res.writeHead(400, { 'content-type': 'application/json' })
149
+ res.end(
150
+ JSON.stringify({
151
+ error: {
152
+ message: modelCheck.reason,
153
+ type: 'invalid_request_error',
154
+ code: 'model_not_found',
155
+ available: modelCheck.available,
156
+ },
157
+ }),
158
+ )
159
+ return
160
+ }
161
+
162
+ const abort = new AbortController()
163
+ res.on('close', () => {
164
+ /** 客户端断开 → 立刻取消上游(否则白耗额度)。 */
165
+ if (!res.writableEnded) abort.abort()
166
+ })
167
+
168
+ const streaming = body?.stream === true || body?.stream === 'true'
169
+ /**
170
+ * 用目录里的**规范大小写**继续(大小写不敏感匹配后的归一),并**剥掉
171
+ * `@acct:` 钉定后缀**:那个后缀是本插件的历史形态,对上游无意义,带着它
172
+ * 发出去 = 未知模型 = 零内容 = 账号被标限流。
173
+ */
174
+ const model = modelCheck.id
175
+ generateOptions = { ...generateOptions, model }
176
+ const requestId = `chatcmpl-${randomUUID()}`
177
+
178
+ /**
179
+ * 分发 key 钉定账号(0.9.4):`accountId` 非空 ⇒ 强制选号到该账号
180
+ * (plan-client 的 `pinnedAccountId` 语义:只看它、绝不换号)。
181
+ * 未绑定 = 整个账号池按 expiry 顺序选号。
182
+ * ⚠ provider 保持基础名(钉定语义由 `pinnedAccountId` 承载,不经 @acct 后缀)。
183
+ */
184
+ const pinnedOptions = distKey?.accountId
185
+ ? { ...generateOptions, provider: 'zcode-start-plan', pinnedAccountId: distKey.accountId }
186
+ : { ...generateOptions, provider: 'zcode-start-plan' }
187
+
188
+ const result = await options.planClient.call({
189
+ options: pinnedOptions,
190
+ maxTokens: generateOptions.maxTokens,
191
+ signal: abort.signal,
192
+ })
193
+
194
+ /**
195
+ * 把 head + decoder 余量合成一条异步序列。
196
+ *
197
+ * ⚠ `result.decoder` **不是**异步生成器,而是
198
+ * `{ read(): Promise<{done, value?}>, cancel? }`(见 plan-client.js 的返回
199
+ * 类型注释)。此前误当生成器 `for await` 消费,运行期报
200
+ * `result.decoder.read is not a function` —— 而它被 catch 兜住后只发一帧
201
+ * error chunk,表现为「流式回答只有一个 reasoning 帧就断了」。
202
+ *
203
+ * 分发 key 的用量记账(0.9.4/0.9.5):**在生成器内部旁路观察**每个 chunk
204
+ * 抓 `usage` 块,流收尾时回写一次。⚠ 不能另起协程 `for await` 消费同一个
205
+ * 生成器 —— 两个消费者互相抢帧(实测:记账协程把 head 里的 reasoning 帧
206
+ * 吃掉,客户端丢内容)。
207
+ */
208
+ let distUsage
209
+ const observe = (chunk) => {
210
+ if (distKey === undefined || chunk === null || typeof chunk !== 'object') return
211
+ if (chunk.type === 'usage' && chunk.usage !== undefined) distUsage = chunk.usage
212
+ }
213
+ const flushDistUsage = async () => {
214
+ if (distKey === undefined || distUsage === undefined) return
215
+ const usage = distUsage
216
+ distUsage = undefined
217
+ try {
218
+ await options.recordUsage?.(distKey.token, {
219
+ inputTokens: usage.inputTokens ?? 0,
220
+ outputTokens: usage.outputTokens ?? 0,
221
+ })
222
+ } catch {
223
+ // 记账失败不该让响应出错(响应已发出)。
224
+ }
225
+ }
226
+ const chunks = (async function* () {
227
+ for (const event of result.head ?? []) {
228
+ observe(event)
229
+ yield event
230
+ }
231
+ const decoder = result.decoder
232
+ if (decoder !== undefined && typeof decoder.read === 'function') {
233
+ for (;;) {
234
+ const next = await decoder.read()
235
+ if (next === undefined || next.done === true) break
236
+ if (next.value !== undefined) {
237
+ observe(next.value)
238
+ yield next.value
239
+ }
240
+ }
241
+ }
242
+ /** 流自然收尾 ⇒ 记账(abort 打断时消费方 break,走不到这里 = 少记优于多记)。 */
243
+ await flushDistUsage()
244
+ })()
245
+
246
+ if (!streaming) {
247
+ try {
248
+ const payload = await collectChatCompletion(chunks, requestId, model)
249
+ res.writeHead(200, { 'content-type': 'application/json' })
250
+ res.end(JSON.stringify(payload))
251
+ } catch (error) {
252
+ jsonError(res, 502, 'server_error', String(error?.message ?? error))
253
+ }
254
+ return
255
+ }
256
+
257
+ res.writeHead(200, {
258
+ 'content-type': 'text/event-stream',
259
+ 'cache-control': 'no-cache',
260
+ connection: 'keep-alive',
261
+ })
262
+ try {
263
+ for await (const line of toOpenAiSse(chunks, requestId, model)) {
264
+ if (res.destroyed || res.writableEnded) break
265
+ res.write(line)
266
+ }
267
+ } catch (error) {
268
+ /** 流已开始:只能回一帧错误 chunk(HTTP 状态码已经发出去了)。 */
269
+ if (!res.destroyed && !res.writableEnded) {
270
+ res.write(`data: ${JSON.stringify({
271
+ id: requestId,
272
+ object: 'chat.completion.chunk',
273
+ created: Math.floor(Date.now() / 1000),
274
+ model,
275
+ choices: [],
276
+ error: { message: String(error?.message ?? error), type: 'server_error', code: 'upstream_error' },
277
+ })}\n\n`)
278
+ }
279
+ }
280
+ if (!res.destroyed && !res.writableEnded) {
281
+ res.write('data: [DONE]\n\n')
282
+ res.end()
283
+ }
284
+ }
285
+
286
+ const listen = (port) =>
287
+ new Promise((resolve, reject) => {
288
+ const onError = (error) => {
289
+ server.removeListener('listening', onListening)
290
+ reject(error)
291
+ }
292
+ const onListening = () => {
293
+ server.removeListener('error', onError)
294
+ resolve()
295
+ }
296
+ server.once('error', onError)
297
+ server.once('listening', onListening)
298
+ server.listen(port, host)
299
+ })
300
+
301
+ let actualPort
302
+ try {
303
+ await listen(requestedPort)
304
+ actualPort = server.address().port
305
+ } catch (error) {
306
+ if (requestedPort === 0 || (error?.code !== 'EADDRINUSE' && error?.code !== 'EACCES')) throw error
307
+ log(`[openai-gateway] ⚠ 端口 ${requestedPort} 不可用(${error.code}),已回退随机端口`)
308
+ await listen(0)
309
+ actualPort = server.address().port
310
+ }
311
+
312
+ const baseUrl = `http://${host}:${actualPort}/v1`
313
+ log(`[openai-gateway] 已监听 ${baseUrl}`)
314
+
315
+ return {
316
+ port: actualPort,
317
+ baseUrl,
318
+ async close() {
319
+ await new Promise((resolve) => server.close(() => resolve()))
320
+ },
321
+ }
322
+ }
323
+
324
+ /** 从请求里取 presented key(Bearer 优先,x-api-key 兜底);无 = null。 */
325
+ function extractBearer(req) {
326
+ const header = req.headers['authorization']
327
+ if (typeof header === 'string' && header.startsWith('Bearer ')) {
328
+ const value = header.slice('Bearer '.length).trim()
329
+ return value.length > 0 ? value : null
330
+ }
331
+ const alt = req.headers['x-api-key']
332
+ return typeof alt === 'string' && alt.length > 0 ? alt : null
333
+ }
334
+
335
+ function jsonError(res, status, code, message) {
336
+ if (res.writableEnded) return
337
+ res.writeHead(status, { 'content-type': 'application/json' })
338
+ res.end(JSON.stringify({ error: { message, type: code, code } }))
339
+ }
340
+
341
+ function readBody(req) {
342
+ return new Promise((resolve, reject) => {
343
+ const chunks = []
344
+ let size = 0
345
+ req.on('data', (chunk) => {
346
+ size += chunk.length
347
+ if (size > BODY_LIMIT_BYTES) {
348
+ const error = new Error(`请求体超过 ${BODY_LIMIT_BYTES} 字节上限`)
349
+ error.code = 'BODY_TOO_LARGE'
350
+ reject(error)
351
+ req.destroy()
352
+ return
353
+ }
354
+ chunks.push(chunk)
355
+ })
356
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
357
+ req.on('error', reject)
358
+ })
359
+ }
360
+
361
+ // ── OpenAI 请求 → DSH GenerateOptions ───────────────────────────────────────
362
+
363
+ /**
364
+ * 把 OpenAI `/v1/chat/completions` 请求体翻成 DSH 的 GenerateOptions。
365
+ *
366
+ * ⚠ 缺 `messages` 直接报错:空 messages 到底层会变成一条奇怪的请求,不如在
367
+ * 入口就明确拒绝(与参考实现同口径)。
368
+ * ⚠ `tool_choice` 只支持 `auto` / `none`:其余取值(`required`、指名某个函数)
369
+ * DSH 侧表达不出来,静默降级会让客户端以为约束生效了。
370
+ */
371
+ export function toGenerateOptions(body) {
372
+ if (!Array.isArray(body?.messages) || body.messages.length === 0) {
373
+ throw new Error('messages must be a non-empty array')
374
+ }
375
+ if (body.tool_choice !== undefined && body.tool_choice !== 'auto' && body.tool_choice !== 'none') {
376
+ throw new Error('only tool_choice auto and none are supported')
377
+ }
378
+
379
+ const maxTokens = num(body.max_completion_tokens) ?? num(body.max_tokens)
380
+ const temperature = num(body.temperature)
381
+ const stop = typeof body.stop === 'string'
382
+ ? [body.stop]
383
+ : Array.isArray(body.stop) && body.stop.every((item) => typeof item === 'string')
384
+ ? body.stop
385
+ : undefined
386
+
387
+ const tools = convertTools(body.tools)
388
+ if (body.tool_choice === 'none' && tools !== undefined && tools.length > 0) {
389
+ throw new Error('tool_choice "none" with tools cannot be represented')
390
+ }
391
+
392
+ /**
393
+ * ⚠ 工具配对**预扫**必须在转换之前:配对的 `role:'tool'` 消息可能排在被剔除
394
+ * 的调用**后面**,逐条转换时已无从知道该剔除谁。
395
+ */
396
+ const callIds = collectCallAvailability(body.messages)
397
+ const messages = []
398
+ for (const message of body.messages) {
399
+ const converted = convertMessage(message, callIds)
400
+ /** `undefined` = 整条剔除(绝不 push 空消息充数)。 */
401
+ if (converted !== undefined) messages.push(converted)
402
+ }
403
+
404
+ return {
405
+ messages,
406
+ ...(tools === undefined ? {} : { tools }),
407
+ ...(maxTokens === undefined ? {} : { maxTokens }),
408
+ ...(temperature === undefined ? {} : { temperature }),
409
+ ...(stop === undefined ? {} : { stop }),
410
+ }
411
+ }
412
+
413
+ function num(value) {
414
+ return typeof value === 'number' && Number.isFinite(value) ? value : undefined
415
+ }
416
+
417
+ /** 把多模态/字符串 content 展平成纯文本。 */
418
+ export function contentToText(content) {
419
+ if (typeof content === 'string') return content
420
+ if (!Array.isArray(content)) return ''
421
+ return content
422
+ .filter((block) => block !== null && typeof block === 'object' && block.type === 'text')
423
+ .map((block) => (typeof block.text === 'string' ? block.text : ''))
424
+ .join('')
425
+ }
426
+
427
+ /** 工具名判据:trim 后非空(空白名上游同样拒)。**只有这一份判据。** */
428
+ function hasUsableToolName(name) {
429
+ return typeof name === 'string' && name.trim().length > 0
430
+ }
431
+
432
+ /** 工具调用 id 判据:非空字符串。⚠ 刻意**不 trim**(id 是不透明标识符)。 */
433
+ function isUsableToolCallId(value) {
434
+ return typeof value === 'string' && value.length > 0
435
+ }
436
+
437
+ /**
438
+ * 预扫历史,按 id 分出工具的可用性。
439
+ *
440
+ * ⚠ 剔除条件必须是「**该 id 上没有任何可用调用**」(`dropped && !kept`):
441
+ * 只看 dropped 会把「同 id 上还有好调用」的结果一起剔掉 ⇒ 留下孤儿 tool-call,
442
+ * 上游照样 400。
443
+ */
444
+ function collectCallAvailability(messages) {
445
+ const dropped = new Set()
446
+ const kept = new Set()
447
+ for (const message of messages) {
448
+ if (message === null || typeof message !== 'object') continue
449
+ if (message.role !== 'assistant' || !Array.isArray(message.tool_calls)) continue
450
+ for (const call of message.tool_calls) {
451
+ if (call === null || typeof call !== 'object') continue
452
+ if (!isUsableToolCallId(call.id)) continue
453
+ if (hasUsableToolName(call.function?.name)) kept.add(call.id)
454
+ else dropped.add(call.id)
455
+ }
456
+ }
457
+ return { dropped, kept }
458
+ }
459
+
460
+ /** 单条 OpenAI 消息 → DSH Message;`undefined` = 整条剔除。 */
461
+ function convertMessage(raw, callIds) {
462
+ if (raw === null || typeof raw !== 'object') throw new Error('messages entries must be objects')
463
+ const role = raw.role
464
+
465
+ if (role === 'system' || role === 'developer') {
466
+ const text = contentToText(raw.content)
467
+ if (text.length === 0) return undefined
468
+ return { role: 'system', content: [{ type: 'text', text }] }
469
+ }
470
+
471
+ if (role === 'user') {
472
+ const parts = []
473
+ if (typeof raw.content === 'string') {
474
+ parts.push({ type: 'text', text: raw.content })
475
+ } else if (Array.isArray(raw.content)) {
476
+ for (const block of raw.content) {
477
+ if (block === null || typeof block !== 'object') continue
478
+ if (block.type === 'text' && typeof block.text === 'string') {
479
+ parts.push({ type: 'text', text: block.text })
480
+ } else if (block.type === 'image_url') {
481
+ /** ⚠ 图片只在 user 角色被接受;上游只认这一种形态。 */
482
+ const url = typeof block.image_url === 'string' ? block.image_url : block.image_url?.url
483
+ if (typeof url === 'string' && url.length > 0) parts.push({ type: 'image', url })
484
+ }
485
+ }
486
+ }
487
+ if (parts.length === 0) return undefined
488
+ return { role: 'user', content: parts }
489
+ }
490
+
491
+ if (role === 'assistant') {
492
+ const content = []
493
+ const text = contentToText(raw.content)
494
+ if (text.length > 0) content.push({ type: 'text', text })
495
+ if (Array.isArray(raw.tool_calls)) {
496
+ for (const call of raw.tool_calls) {
497
+ if (call === null || typeof call !== 'object') continue
498
+ /**
499
+ * ⚠ 名字不可用的调用**剔除**而非报错:坏块会被客户端每轮原样重放,
500
+ * 网关直接 400 等于让整条会话永久不可用(参考实现 issue IKLRIK)。
501
+ * 但 `id` / `arguments` 缺失仍报错 —— 那是真形状错误,剔除会静默丢掉
502
+ * 模型真实发起的调用。
503
+ */
504
+ if (!hasUsableToolName(call.function?.name)) continue
505
+ if (!isUsableToolCallId(call.id)) throw new Error('assistant.tool_calls contains an invalid function call')
506
+ if (typeof call.function?.arguments !== 'string') {
507
+ throw new Error('assistant.tool_calls contains an invalid function call')
508
+ }
509
+ content.push({ type: 'tool-call', id: call.id, name: call.function.name, arguments: call.function.arguments })
510
+ }
511
+ }
512
+ /**
513
+ * ⚠ 调用全被剔光且正文为空 ⇒ 整条剔除。留着会变成 wire 上一条**空的开头
514
+ * assistant 发言**(实测让 OpenAI 兼容端点回 model_param_invalid)。
515
+ * ⚠ 正文非空的(模型真实发言)必须留下 —— 那是用户界面上看到的内容。
516
+ */
517
+ if (content.length === 0) return undefined
518
+ return { role: 'assistant', content }
519
+ }
520
+
521
+ if (role === 'tool') {
522
+ if (!isUsableToolCallId(raw.tool_call_id)) throw new Error('tool messages require tool_call_id')
523
+ /** 配对已坏 ⇒ 结果成孤儿,必须一并剔除(上游对孤儿结果同样 400)。 */
524
+ if (callIds.dropped.has(raw.tool_call_id) && !callIds.kept.has(raw.tool_call_id)) return undefined
525
+ const parts = typeof raw.content === 'string'
526
+ ? [{ type: 'text', text: raw.content }]
527
+ : Array.isArray(raw.content)
528
+ ? raw.content
529
+ .filter((block) => block !== null && typeof block === 'object' && block.type === 'text' && typeof block.text === 'string')
530
+ .map((block) => ({ type: 'text', text: block.text }))
531
+ : []
532
+ return {
533
+ role: 'user',
534
+ content: [{ type: 'tool-result', toolCallId: raw.tool_call_id, content: parts }],
535
+ }
536
+ }
537
+
538
+ throw new Error(`unsupported message role: ${String(role)}`)
539
+ }
540
+
541
+ /** Chat 形状的 tools → DSH ToolSchema。 */
542
+ function convertTools(raw) {
543
+ if (raw === undefined || raw === null) return undefined
544
+ if (!Array.isArray(raw)) throw new Error('tools must be an array')
545
+ const out = []
546
+ for (const tool of raw) {
547
+ if (tool === null || typeof tool !== 'object') continue
548
+ if (tool.type !== undefined && tool.type !== 'function') continue
549
+ const fn = tool.function
550
+ if (fn === null || typeof fn !== 'object' || !hasUsableToolName(fn.name)) continue
551
+ out.push({
552
+ name: fn.name,
553
+ ...(typeof fn.description === 'string' ? { description: fn.description } : {}),
554
+ /** `parameters` 原样透传:这是模型看的 schema,网关不做改写。 */
555
+ ...(fn.parameters !== undefined ? { parameters: fn.parameters } : {}),
556
+ })
557
+ }
558
+ return out.length > 0 ? out : undefined
559
+ }
560
+
561
+ // ── DSH StreamChunk → OpenAI chunk ─────────────────────────────────────────
562
+
563
+ /** DSH finish reason → OpenAI `finish_reason`。 */
564
+ function finishReason(reason) {
565
+ switch (reason?.kind) {
566
+ case 'stop': return 'stop'
567
+ case 'tool-calls': return 'tool_calls'
568
+ case 'max-tokens': return 'length'
569
+ case 'aborted': return 'error'
570
+ case 'error': return 'error'
571
+ default: return 'stop'
572
+ }
573
+ }
574
+
575
+ /**
576
+ * DSH usage → OpenAI `usage`。
577
+ *
578
+ * ⚠ `prompt_tokens` 含缓存命中(DSH 的 `inputTokens` 口径),`cached_tokens`
579
+ * 是它的**子集**;两个明细字段(官方形态)必须给 —— 标准客户端只认官方名字。
580
+ */
581
+ function usageJson(usage) {
582
+ if (usage === null || typeof usage !== 'object') return undefined
583
+ const input = num(usage.inputTokens) ?? 0
584
+ const output = num(usage.outputTokens) ?? 0
585
+ const cached = num(usage.cachedInputTokens) ?? 0
586
+ const reasoning = num(usage.reasoningTokens)
587
+ return {
588
+ prompt_tokens: input,
589
+ completion_tokens: output,
590
+ total_tokens: input + output,
591
+ prompt_tokens_details: { cached_tokens: cached },
592
+ ...(reasoning === undefined
593
+ ? {}
594
+ : { reasoning_tokens: reasoning, completion_tokens_details: { reasoning_tokens: reasoning } }),
595
+ ...(cached > 0 ? { prompt_cache_hit_tokens: cached } : {}),
596
+ }
597
+ }
598
+
599
+ function baseChunk(id, model, delta, finish) {
600
+ return {
601
+ id,
602
+ object: 'chat.completion.chunk',
603
+ created: Math.floor(Date.now() / 1000),
604
+ model,
605
+ choices: [{ index: 0, delta, finish_reason: finish ?? null }],
606
+ }
607
+ }
608
+
609
+ /**
610
+ * 单块消费:返回要发出去的 `delta`(或 `undefined` = 该块不产生帧)。
611
+ *
612
+ * ⚠ `reasoning-delta` 映射到 **`reasoning_content`**(DeepSeek 系私有名,
613
+ * 也是 Cline/qoder 等客户端读的那个);不映射 `reasoning` —— 那是另一家
614
+ * (Cline 的 `{"delta":{"reasoning":…}}`)的写法,两边同时发会让部分客户端重复渲染。
615
+ */
616
+ function consumeChunk(state, chunk) {
617
+ switch (chunk?.type) {
618
+ case 'text-delta':
619
+ state.content += typeof chunk.text === 'string' ? chunk.text : ''
620
+ return { delta: { content: chunk.text ?? '' } }
621
+ case 'reasoning-delta':
622
+ state.reasoning += typeof chunk.text === 'string' ? chunk.text : ''
623
+ return { delta: { reasoning_content: chunk.text ?? '' } }
624
+ case 'tool-call-delta': {
625
+ let tool = state.tools.get(chunk.index)
626
+ if (tool === undefined) {
627
+ tool = { id: String(chunk.id ?? ''), arguments: '' }
628
+ state.tools.set(chunk.index, tool)
629
+ }
630
+ /** ⚠ 只接受**非空**覆盖:后续分片带空串会清空已解析的工具名。 */
631
+ if (typeof chunk.id === 'string' && chunk.id.length > 0) tool.id = chunk.id
632
+ if (typeof chunk.name === 'string' && chunk.name.length > 0) tool.name = chunk.name
633
+ const argsDelta = typeof chunk.argumentsDelta === 'string' ? chunk.argumentsDelta : ''
634
+ tool.arguments += argsDelta
635
+ return {
636
+ delta: {
637
+ tool_calls: [{
638
+ index: chunk.index,
639
+ id: tool.id,
640
+ type: 'function',
641
+ function: {
642
+ ...(tool.name === undefined ? {} : { name: tool.name }),
643
+ arguments: argsDelta,
644
+ },
645
+ }],
646
+ },
647
+ }
648
+ }
649
+ case 'usage':
650
+ state.usage = chunk.usage
651
+ return undefined
652
+ case 'finish': {
653
+ const reason = chunk.reason ?? { kind: 'stop' }
654
+ if (reason.kind === 'error' || reason.kind === 'aborted') {
655
+ return { error: reason.failure ?? { message: `DSH model request ${reason.kind}` } }
656
+ }
657
+ state.finishReason = finishReason(reason)
658
+ return { delta: {}, finish: state.finishReason }
659
+ }
660
+ case 'block-start':
661
+ case 'block-end':
662
+ default:
663
+ return undefined
664
+ }
665
+ }
666
+
667
+ /**
668
+ * 上游失败 → OpenAI 错误体 + 状态码。
669
+ *
670
+ * ⚠ **门禁 400–599**:上游有时用 `{status: 200}` 表示业务失败(额度用尽),
671
+ * 原样透出会让客户端把失败读成成功。
672
+ */
673
+ function normalizeUpstreamFailure(failure) {
674
+ const raw = num(failure?.status)
675
+ const status = raw !== undefined && raw >= 400 && raw <= 599 ? raw : 502
676
+ return {
677
+ status,
678
+ type: typeof failure?.type === 'string' ? failure.type : 'server_error',
679
+ code: typeof failure?.code === 'string' ? failure.code : 'upstream_error',
680
+ message: typeof failure?.message === 'string' && failure.message.length > 0
681
+ ? failure.message
682
+ : 'upstream error',
683
+ }
684
+ }
685
+
686
+ /**
687
+ * 流式:DSH chunk 序列 → OpenAI SSE 行。
688
+ *
689
+ * ⚠ **finish 门禁**(与 `collectChatCompletion` 同口径):流结束但没收到
690
+ * `finish` chunk = 上游半截断开。此时**不得**发 usage/[DONE] —— 那会让客户端
691
+ * 把半截输出当完整结果持久化(docs/local-endpoints.md「协议陷阱」表)。
692
+ * 正确形态:发一帧 error chunk,让客户端明确知道流不完整。
693
+ */
694
+ export async function* toOpenAiSse(chunks, requestId, model) {
695
+ const state = { content: '', reasoning: '', tools: new Map(), usage: undefined, finishReason: undefined }
696
+ for await (const chunk of chunks) {
697
+ const event = consumeChunk(state, chunk)
698
+ if (event === undefined) continue
699
+ if (event.error !== undefined) {
700
+ const normalized = normalizeUpstreamFailure(event.error)
701
+ yield `data: ${JSON.stringify({
702
+ id: requestId,
703
+ object: 'chat.completion.chunk',
704
+ created: Math.floor(Date.now() / 1000),
705
+ model,
706
+ choices: [],
707
+ error: { message: normalized.message, type: normalized.type, code: normalized.code },
708
+ })}\n\n`
709
+ return
710
+ }
711
+ if (event.delta !== undefined) {
712
+ yield `data: ${JSON.stringify(baseChunk(requestId, model, event.delta, event.finish))}\n\n`
713
+ }
714
+ }
715
+ if (state.finishReason === undefined) {
716
+ yield `data: ${JSON.stringify({
717
+ id: requestId,
718
+ object: 'chat.completion.chunk',
719
+ created: Math.floor(Date.now() / 1000),
720
+ model,
721
+ choices: [],
722
+ error: { message: 'upstream stream ended before finish', type: 'server_error', code: 'upstream_error' },
723
+ })}\n\n`
724
+ return
725
+ }
726
+ /** 用量作为最后一帧(`stream_options.include_usage` 的通行形态)。 */
727
+ const usage = usageJson(state.usage)
728
+ if (usage !== undefined) {
729
+ yield `data: ${JSON.stringify({
730
+ id: requestId,
731
+ object: 'chat.completion.chunk',
732
+ created: Math.floor(Date.now() / 1000),
733
+ model,
734
+ choices: [],
735
+ usage,
736
+ })}\n\n`
737
+ }
738
+ }
739
+
740
+ /** 非流式:把整条流折叠成一个 `chat.completion`。 */
741
+ export async function collectChatCompletion(chunks, requestId, model) {
742
+ const state = { content: '', reasoning: '', tools: new Map(), usage: undefined, finishReason: undefined }
743
+ for await (const chunk of chunks) {
744
+ const event = consumeChunk(state, chunk)
745
+ if (event?.error !== undefined) {
746
+ const normalized = normalizeUpstreamFailure(event.error)
747
+ throw new Error(normalized.message)
748
+ }
749
+ }
750
+ if (state.finishReason === undefined) {
751
+ /** 流没有 finish ⇒ 上游半截断开。报错而不是假装成功(谎报会让半截输出被持久化)。 */
752
+ throw new Error('upstream stream ended before finish')
753
+ }
754
+ const toolCalls = [...state.tools.entries()]
755
+ .sort(([a], [b]) => a - b)
756
+ .map(([, tool]) => ({
757
+ id: tool.id,
758
+ type: 'function',
759
+ function: { name: tool.name ?? '', arguments: tool.arguments },
760
+ }))
761
+ const message = {
762
+ role: 'assistant',
763
+ content: state.content.length > 0 ? state.content : null,
764
+ ...(state.reasoning.length === 0 ? {} : { reasoning_content: state.reasoning }),
765
+ ...(toolCalls.length === 0 ? {} : { tool_calls: toolCalls }),
766
+ }
767
+ const usage = usageJson(state.usage)
768
+ return {
769
+ id: requestId,
770
+ object: 'chat.completion',
771
+ created: Math.floor(Date.now() / 1000),
772
+ model,
773
+ choices: [{ index: 0, message, finish_reason: state.finishReason }],
774
+ ...(usage === undefined ? {} : { usage }),
775
+ }
776
+ }