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.
Files changed (58) hide show
  1. package/CHANGELOG.md +1963 -405
  2. package/README.md +88 -405
  3. package/bin/cli.mjs +509 -450
  4. package/client.js +2459 -716
  5. package/cordis.patch.yml +4 -2
  6. package/index.js +144 -14
  7. package/lib/adapter.js +476 -422
  8. package/lib/anthropic-body.js +513 -469
  9. package/lib/assemble.js +808 -420
  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 -489
  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 -570
  23. package/lib/upstream.js +294 -134
  24. package/lib/version-probe.js +110 -0
  25. package/package.json +84 -80
  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 -76
  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/anthropic-body.test.mjs +305 -0
  35. package/tests/assembler-contract.test.mjs +256 -0
  36. package/tests/auto-claim.test.mjs +318 -0
  37. package/tests/claim-routes.test.mjs +438 -0
  38. package/tests/client-panel.test.mjs +1141 -0
  39. package/tests/distribution-keys.test.mjs +123 -0
  40. package/tests/e2e.test.mjs +388 -0
  41. package/tests/fallback-scrub.test.mjs +105 -0
  42. package/tests/fixtures/quota-200.json +1 -0
  43. package/tests/launch-command.test.mjs +68 -0
  44. package/tests/login-channel.test.mjs +102 -0
  45. package/tests/openai-gateway.test.mjs +454 -0
  46. package/tests/pinned-models.test.mjs +505 -0
  47. package/tests/plan-client.test.mjs +582 -0
  48. package/tests/pool.test.mjs +319 -0
  49. package/tests/quota-blackhole.test.mjs +409 -0
  50. package/tests/restart-script.test.mjs +53 -0
  51. package/tests/routing-quota.test.mjs +251 -0
  52. package/tests/sse.test.mjs +86 -0
  53. package/tests/stream-translator.test.mjs +137 -0
  54. package/tests/support/hanging-stream.mjs +48 -0
  55. package/tests/support/resolve-profile-deps.mjs +52 -0
  56. package/tests/upstream-error-200.test.mjs +164 -0
  57. package/tests/upstream.test.mjs +330 -0
  58. package/tests/version-probe.test.mjs +172 -0
@@ -1,352 +1,367 @@
1
- /**
2
- * 本地 Anthropic 兼容端点(**可选**,默认关闭)。
3
- *
4
- * 只有当用户想走 `dsh-llm-pi-ai` 路由(`api: anthropic-messages` + `baseURL`)时才需要它:
5
- * 此时请求从 DSH 的 pi-ai 适配器打到 `127.0.0.1:<port>/v1/messages`,本文件把它复用
6
- * 成一次 `ZcodePlanClient.call()`,再把上游事件以 Anthropic SSE 原样写回。
7
- *
8
- * ## 为什么端口与 token 必须固定/持久化
9
- *
10
- * profile 里配好的 `baseURL` 与 `apiKeyEnv` 指向它们;端口每次变、token 每次重新随机,
11
- * 那份配置就每次重启都失效(表现为 404 或 401)。故:
12
- * - 端口默认 17899(`config.endpoint.port`),被占用时回退随机并在日志/状态里如实告知;
13
- * - token 首次生成后落盘到数据目录(`endpoint-token.txt`,600)。
14
- */
15
-
16
- import { createServer } from 'node:http'
17
- import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
18
- import { join } from 'node:path'
19
-
20
- /**
21
- * 解析配置端口(`0` = 随机)。
22
- * @param {unknown} raw
23
- * @param {number} fallback
24
- */
25
- export function resolvePort(raw, fallback = 17_899) {
26
- if (raw === undefined || raw === null || String(raw).trim().length === 0) return fallback
27
- const value = Number(raw)
28
- if (!Number.isFinite(value) || value < 0 || value > 65_535) return fallback
29
- return Math.floor(value)
30
- }
31
-
32
- /** 解析访问 token:环境变量 → 数据目录文件 → 新生成后落盘。 */
33
- export function resolveEndpointToken(dataDir, env = process.env) {
34
- const fromEnv = env['ZCODE_START_PLAN_TOKEN']?.trim()
35
- if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv
36
- const file = join(dataDir, 'endpoint-token.txt')
37
- try {
38
- if (existsSync(file)) {
39
- const saved = readFileSync(file, 'utf8').trim()
40
- if (saved.length >= 16) return saved
41
- }
42
- } catch {
43
- // 读不到就当没有(下面重新生成)。
44
- }
45
- const token = globalThis.crypto.randomUUID().replace(/-/g, '') + globalThis.crypto.randomUUID().replace(/-/g, '')
46
- try {
47
- mkdirSync(dataDir, { recursive: true })
48
- writeFileSync(file, token, { mode: 0o600 })
49
- } catch {
50
- // 落盘失败不阻塞(只是下次会换一个 token)。
51
- }
52
- return token
53
- }
54
-
55
- /**
56
- * 启动本地端点。
57
- *
58
- * @param {{
59
- * port?: number,
60
- * host?: string,
61
- * token: string,
62
- * planClient: import('./plan-client.js').ZcodePlanClient,
63
- * models: () => Promise<Array<any>>,
64
- * log?: (message: string) => void,
65
- * }} options
66
- */
67
- export async function startLocalEndpoint(options) {
68
- const host = options.host ?? '127.0.0.1'
69
- const token = options.token
70
- const log = options.log ?? (() => {})
71
- const requestedPort = options.port ?? 17_899
72
-
73
- const server = createServer((req, res) => {
74
- void handle(req, res).catch((error) => {
75
- log(`[endpoint] 未捕获错误:${String(error)}`)
76
- try {
77
- res.writeHead(500, { 'content-type': 'application/json' })
78
- res.end(JSON.stringify({ type: 'error', error: { type: 'api_error', message: String(error) } }))
79
- } catch {
80
- // 响应可能已开始。
81
- }
82
- })
83
- })
84
-
85
- async function handle(req, res) {
86
- const url = new URL(req.url ?? '/', `http://${host}`)
87
- if (url.pathname === '/health') {
88
- res.writeHead(200, { 'content-type': 'application/json' })
89
- res.end(JSON.stringify({ ok: true }))
90
- return
91
- }
92
- if (url.pathname === '/v1/models') {
93
- const models = await options.models()
94
- res.writeHead(200, { 'content-type': 'application/json' })
95
- res.end(
96
- JSON.stringify({
97
- data: models.map((model) => ({
98
- id: model.id,
99
- type: 'model',
100
- display_name: model.name ?? model.id,
101
- created_at: new Date(0).toISOString(),
102
- })),
103
- has_more: false,
104
- }),
105
- )
106
- return
107
- }
108
- if (url.pathname !== '/v1/messages' || req.method !== 'POST') {
109
- res.writeHead(404, { 'content-type': 'application/json' })
110
- res.end(JSON.stringify({ type: 'error', error: { type: 'not_found_error', message: `未知端点 ${url.pathname}` } }))
111
- return
112
- }
113
- if (req.headers['authorization'] !== `Bearer ${token}` && req.headers['x-api-key'] !== token) {
114
- res.writeHead(401, { 'content-type': 'application/json' })
115
- res.end(JSON.stringify({ type: 'error', error: { type: 'authentication_error', message: '本地端点访问令牌无效' } }))
116
- return
117
- }
118
-
119
- const raw = await readBody(req)
120
- let body
121
- try {
122
- body = JSON.parse(raw)
123
- } catch {
124
- res.writeHead(400, { 'content-type': 'application/json' })
125
- res.end(JSON.stringify({ type: 'error', error: { type: 'invalid_request_error', message: '请求体不是合法 JSON' } }))
126
- return
127
- }
128
-
129
- const streaming = body.stream === true || body.stream === 'true'
130
- const abort = new AbortController()
131
- res.on('close', () => {
132
- /** 客户端断开 → 立刻取消上游(否则白耗额度)。 */
133
- if (!res.writableEnded) abort.abort()
134
- })
135
-
136
- const result = await options.planClient.call({
137
- options: {
138
- ...toGenerateOptions(body),
139
- provider: 'zcode-start-plan',
140
- signal: abort.signal,
141
- },
142
- maxTokens: body.max_tokens,
143
- signal: abort.signal,
144
- })
145
-
146
- if (!streaming) {
147
- /**
148
- * 非流式:先读干 decoder 余量再折叠。
149
- * ⚠ `result.head` 只是「首帧切片」(plan-client 读到首帧就返回,好尽早判定
150
- * 零内容/业务错误);正文增量全在 `result.decoder` 里。只折叠 head 会把回答
151
- * 截成开头几个字 —— 流式分支有读 decoder,这里此前漏了(pi-ai 路线几乎总走
152
- * 流式所以没暴露;ZCode CLI 冒烟实测踩中)。
153
- */
154
- const events = [...result.head]
155
- if (result.decoder !== undefined) {
156
- for (;;) {
157
- const next = await result.decoder.read()
158
- if (next.done === true) break
159
- events.push(next.value)
160
- }
161
- }
162
- const message = await collapseToMessage(events)
163
- res.writeHead(200, { 'content-type': 'application/json' })
164
- res.end(JSON.stringify(message))
165
- return
166
- }
167
-
168
- res.writeHead(200, {
169
- 'content-type': 'text/event-stream',
170
- 'cache-control': 'no-cache',
171
- connection: 'keep-alive',
172
- })
173
- const writeEvent = (eventName, data) => {
174
- if (res.destroyed || res.writableEnded) return
175
- try {
176
- res.write(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`)
177
- } catch {
178
- // 客户端已断开。
179
- }
180
- }
181
- for (const event of result.head) {
182
- if (event.data === undefined) continue
183
- writeEvent(event.event ?? event.data?.type ?? 'message', event.data)
184
- }
185
- if (result.decoder !== undefined) {
186
- for (;;) {
187
- const next = await result.decoder.read()
188
- if (next.done === true) break
189
- if (next.value.data === undefined) continue
190
- writeEvent(next.value.event ?? next.value.data?.type ?? 'message', next.value.data)
191
- }
192
- }
193
- if (!res.destroyed) res.end()
194
- }
195
-
196
- const listen = (port) =>
197
- new Promise((resolve, reject) => {
198
- const onError = (error) => {
199
- server.removeListener('listening', onListening)
200
- reject(error)
201
- }
202
- const onListening = () => {
203
- server.removeListener('error', onError)
204
- resolve()
205
- }
206
- server.once('error', onError)
207
- server.once('listening', onListening)
208
- server.listen(port, host)
209
- })
210
-
211
- let actualPort
212
- try {
213
- await listen(requestedPort)
214
- actualPort = server.address().port
215
- } catch (error) {
216
- if (requestedPort === 0 || (error?.code !== 'EADDRINUSE' && error?.code !== 'EACCES')) throw error
217
- log(`[endpoint] ⚠ 端口 ${requestedPort} 不可用(${error.code}),已回退随机端口`)
218
- await listen(0)
219
- actualPort = server.address().port
220
- }
221
-
222
- const baseUrl = `http://${host}:${actualPort}`
223
- log(`[endpoint] 已监听 ${baseUrl}`)
224
-
225
- return {
226
- port: actualPort,
227
- baseUrl,
228
- token,
229
- async close() {
230
- await new Promise((resolve) => server.close(() => resolve()))
231
- },
232
- }
233
- }
234
-
235
- /** 读完整请求体。 */
236
- function readBody(req) {
237
- return new Promise((resolve, reject) => {
238
- const chunks = []
239
- req.on('data', (chunk) => chunks.push(chunk))
240
- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
241
- req.on('error', reject)
242
- })
243
- }
244
-
245
- /**
246
- * 把 Anthropic Messages 请求体翻成 DSH 的 GenerateOptions。
247
- *
248
- * pi-ai 发来的 body 已经是 Anthropic 形态(`system` / `messages` / `tools`),
249
- * 这里逆变换回 DSH 词汇,好让 `buildUpstreamBody` 再统一注入身份块与日期块。
250
- */
251
- export function toGenerateOptions(body) {
252
- const systemText = Array.isArray(body.system)
253
- ? body.system.filter((block) => block?.type === 'text').map((block) => block.text).join('\n\n')
254
- : typeof body.system === 'string'
255
- ? body.system
256
- : undefined
257
-
258
- const messages = (Array.isArray(body.messages) ? body.messages : []).map((message) => ({
259
- role: message.role === 'assistant' ? 'assistant' : 'user',
260
- content: toDshContent(message.content),
261
- }))
262
-
263
- const tools = (Array.isArray(body.tools) ? body.tools : []).map((tool) => ({
264
- name: tool.name,
265
- description: tool.description,
266
- parameters: tool.input_schema ?? tool.parameters,
267
- }))
268
-
269
- return {
270
- model: body.model,
271
- ...(systemText !== undefined ? { system: [{ type: 'text', text: systemText }] } : {}),
272
- messages,
273
- ...(tools.length > 0 ? { tools } : {}),
274
- ...(typeof body.temperature === 'number' ? { temperature: body.temperature } : {}),
275
- }
276
- }
277
-
278
- /** Anthropic content → DSH content blocks。 */
279
- function toDshContent(content) {
280
- if (typeof content === 'string') return [{ type: 'text', text: content }]
281
- if (!Array.isArray(content)) return []
282
- const out = []
283
- for (const block of content) {
284
- if (block?.type === 'text' && typeof block.text === 'string') out.push({ type: 'text', text: block.text })
285
- else if (block?.type === 'tool_use') {
286
- out.push({ type: 'tool-call', id: block.id, name: block.name, arguments: block.input ?? {} })
287
- } else if (block?.type === 'tool_result') {
288
- out.push({
289
- type: 'tool-result',
290
- toolCallId: block.tool_use_id,
291
- output: typeof block.content === 'string' ? block.content : JSON.stringify(block.content ?? ''),
292
- isError: block.is_error === true,
293
- })
294
- } else if (block?.type === 'image' && block.source?.type === 'base64') {
295
- out.push({
296
- type: 'image',
297
- source: { type: 'base64', media_type: block.source.media_type, data: block.source.data },
298
- })
299
- }
300
- }
301
- return out
302
- }
303
-
304
- /** 把一段流事件折叠成一个 Anthropic message(非流式请求用)。 */
305
- async function collapseToMessage(head) {
306
- const content = []
307
- let usage = { input_tokens: 0, output_tokens: 0 }
308
- let stopReason = 'end_turn'
309
- const partialJson = new Map()
310
- for (const event of head) {
311
- const data = event.data
312
- if (data === undefined) continue
313
- if (data.type === 'message_start') {
314
- usage = { ...usage, ...(data.message?.usage ?? {}) }
315
- } else if (data.type === 'content_block_start') {
316
- content[data.index] = { ...data.content_block }
317
- if (data.content_block?.type === 'tool_use') partialJson.set(data.index, data.content_block.input ?? '')
318
- } else if (data.type === 'content_block_delta') {
319
- const block = content[data.index]
320
- if (block === undefined) continue
321
- const delta = data.delta ?? {}
322
- if (delta.type === 'text_delta') block.text = (block.text ?? '') + delta.text
323
- else if (delta.type === 'thinking_delta') block.thinking = (block.thinking ?? '') + delta.thinking
324
- else if (delta.type === 'input_json_delta') {
325
- const current = partialJson.get(data.index) ?? ''
326
- partialJson.set(data.index, current + delta.partial_json)
327
- }
328
- } else if (data.type === 'message_delta') {
329
- if (typeof data.delta?.stop_reason === 'string') stopReason = data.delta.stop_reason
330
- usage = { ...usage, ...(data.usage ?? {}) }
331
- }
332
- }
333
- for (const [index, raw] of partialJson) {
334
- const block = content[index]
335
- if (block === undefined) continue
336
- try {
337
- block.input = typeof raw === 'string' ? JSON.parse(raw || '{}') : raw
338
- } catch {
339
- block.input = {}
340
- }
341
- }
342
- return {
343
- id: `msg_${Math.random().toString(36).slice(2)}`,
344
- type: 'message',
345
- role: 'assistant',
346
- model: 'zcode-start-plan',
347
- content: content.filter(Boolean),
348
- stop_reason: stopReason,
349
- stop_sequence: null,
350
- usage,
351
- }
352
- }
1
+ /**
2
+ * 本地 Anthropic 兼容端点(**可选**,默认关闭)。
3
+ *
4
+ * 只有当用户想走 `dsh-llm-pi-ai` 路由(`api: anthropic-messages` + `baseURL`)时才需要它:
5
+ * 此时请求从 DSH 的 pi-ai 适配器打到 `127.0.0.1:<port>/v1/messages`,本文件把它复用
6
+ * 成一次 `ZcodePlanClient.call()`,再把上游事件以 Anthropic SSE 原样写回。
7
+ *
8
+ * ## 为什么端口与 token 必须固定/持久化
9
+ *
10
+ * profile 里配好的 `baseURL` 与 `apiKeyEnv` 指向它们;端口每次变、token 每次重新随机,
11
+ * 那份配置就每次重启都失效(表现为 404 或 401)。故:
12
+ * - 端口默认 17899(`config.endpoint.port`),被占用时回退随机并在日志/状态里如实告知;
13
+ * - token 首次生成后落盘到数据目录(`endpoint-token.txt`,600)。
14
+ */
15
+
16
+ import { createServer } from 'node:http'
17
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs'
18
+ import { join } from 'node:path'
19
+
20
+ /**
21
+ * 解析配置端口(`0` = 随机)。
22
+ * @param {unknown} raw
23
+ * @param {number} fallback
24
+ */
25
+ export function resolvePort(raw, fallback = 17_899) {
26
+ if (raw === undefined || raw === null || String(raw).trim().length === 0) return fallback
27
+ const value = Number(raw)
28
+ if (!Number.isFinite(value) || value < 0 || value > 65_535) return fallback
29
+ return Math.floor(value)
30
+ }
31
+
32
+ /** 解析访问 token:环境变量 → 数据目录文件 → 新生成后落盘。 */
33
+ export function resolveEndpointToken(dataDir, env = process.env) {
34
+ const fromEnv = env['ZCODE_START_PLAN_TOKEN']?.trim()
35
+ if (typeof fromEnv === 'string' && fromEnv.length > 0) return fromEnv
36
+ const file = join(dataDir, 'endpoint-token.txt')
37
+ try {
38
+ if (existsSync(file)) {
39
+ const saved = readFileSync(file, 'utf8').trim()
40
+ if (saved.length >= 16) return saved
41
+ }
42
+ } catch {
43
+ // 读不到就当没有(下面重新生成)。
44
+ }
45
+ const token = globalThis.crypto.randomUUID().replace(/-/g, '') + globalThis.crypto.randomUUID().replace(/-/g, '')
46
+ try {
47
+ mkdirSync(dataDir, { recursive: true })
48
+ writeFileSync(file, token, { mode: 0o600 })
49
+ } catch {
50
+ // 落盘失败不阻塞(只是下次会换一个 token)。
51
+ }
52
+ return token
53
+ }
54
+
55
+ /**
56
+ * 启动本地端点。
57
+ *
58
+ * @param {{
59
+ * port?: number,
60
+ * host?: string,
61
+ * token: string,
62
+ * planClient: import('./plan-client.js').ZcodePlanClient,
63
+ * models: () => Promise<Array<any>>,
64
+ * log?: (message: string) => void,
65
+ * }} options
66
+ */
67
+ export async function startLocalEndpoint(options) {
68
+ const host = options.host ?? '127.0.0.1'
69
+ const token = options.token
70
+ const log = options.log ?? (() => {})
71
+ const requestedPort = options.port ?? 17_899
72
+
73
+ const server = createServer((req, res) => {
74
+ void handle(req, res).catch((error) => {
75
+ log(`[endpoint] 未捕获错误:${String(error)}`)
76
+ try {
77
+ res.writeHead(500, { 'content-type': 'application/json' })
78
+ res.end(JSON.stringify({ type: 'error', error: { type: 'api_error', message: String(error) } }))
79
+ } catch {
80
+ // 响应可能已开始。
81
+ }
82
+ })
83
+ })
84
+
85
+ async function handle(req, res) {
86
+ const url = new URL(req.url ?? '/', `http://${host}`)
87
+ if (url.pathname === '/health') {
88
+ res.writeHead(200, { 'content-type': 'application/json' })
89
+ res.end(JSON.stringify({ ok: true }))
90
+ return
91
+ }
92
+ if (url.pathname === '/v1/models') {
93
+ const models = await options.models()
94
+ res.writeHead(200, { 'content-type': 'application/json' })
95
+ res.end(
96
+ JSON.stringify({
97
+ data: models.map((model) => ({
98
+ id: model.id,
99
+ type: 'model',
100
+ display_name: model.name ?? model.id,
101
+ created_at: new Date(0).toISOString(),
102
+ })),
103
+ has_more: false,
104
+ }),
105
+ )
106
+ return
107
+ }
108
+ if (url.pathname !== '/v1/messages' || req.method !== 'POST') {
109
+ res.writeHead(404, { 'content-type': 'application/json' })
110
+ res.end(JSON.stringify({ type: 'error', error: { type: 'not_found_error', message: `未知端点 ${url.pathname}` } }))
111
+ return
112
+ }
113
+ if (req.headers['authorization'] !== `Bearer ${token}` && req.headers['x-api-key'] !== token) {
114
+ res.writeHead(401, { 'content-type': 'application/json' })
115
+ res.end(JSON.stringify({ type: 'error', error: { type: 'authentication_error', message: '本地端点访问令牌无效' } }))
116
+ return
117
+ }
118
+
119
+ const raw = await readBody(req)
120
+ let body
121
+ try {
122
+ body = JSON.parse(raw)
123
+ } catch {
124
+ res.writeHead(400, { 'content-type': 'application/json' })
125
+ res.end(JSON.stringify({ type: 'error', error: { type: 'invalid_request_error', message: '请求体不是合法 JSON' } }))
126
+ return
127
+ }
128
+
129
+ const streaming = body.stream === true || body.stream === 'true'
130
+ const abort = new AbortController()
131
+ res.on('close', () => {
132
+ /** 客户端断开 → 立刻取消上游(否则白耗额度)。 */
133
+ if (!res.writableEnded) abort.abort()
134
+ })
135
+
136
+ const result = await options.planClient.call({
137
+ options: {
138
+ ...toGenerateOptions(body),
139
+ provider: 'zcode-start-plan',
140
+ signal: abort.signal,
141
+ },
142
+ maxTokens: body.max_tokens,
143
+ signal: abort.signal,
144
+ })
145
+
146
+ if (!streaming) {
147
+ /**
148
+ * 非流式:先读干 decoder 余量再折叠。
149
+ * ⚠ `result.head` 只是「首帧切片」(plan-client 读到首帧就返回,好尽早判定
150
+ * 零内容/业务错误);正文增量全在 `result.decoder` 里。只折叠 head 会把回答
151
+ * 截成开头几个字 —— 流式分支有读 decoder,这里此前漏了(pi-ai 路线几乎总走
152
+ * 流式所以没暴露;ZCode CLI 冒烟实测踩中)。
153
+ */
154
+ const events = [...result.head]
155
+ if (result.decoder !== undefined) {
156
+ for (;;) {
157
+ const next = await result.decoder.read()
158
+ if (next.done === true) break
159
+ events.push(next.value)
160
+ }
161
+ }
162
+ const message = await collapseToMessage(events)
163
+ res.writeHead(200, { 'content-type': 'application/json' })
164
+ res.end(JSON.stringify(message))
165
+ return
166
+ }
167
+
168
+ /**
169
+ * 流式转发。
170
+ *
171
+ * ⚠ **finish 门禁**(0.10.0 审计 P5,与 openai-gateway 同口径):
172
+ * 流结束但从未出现 `message_delta`(没有 stop_reason)/ `message_stop` /
173
+ * 流内 `error` = 上游半截断开。此时**不得**安静 `res.end()` —— Anthropic 客户端
174
+ * 会把半截输出当完整结果持久化(docs/local-endpoints.md「协议陷阱」表)。
175
+ * 正确形态:补发一帧 `event: error`,让客户端明确知道流不完整。
176
+ */
177
+ const writeEvent = (eventName, data) => {
178
+ if (res.destroyed || res.writableEnded) return
179
+ try {
180
+ res.write(`event: ${eventName}\ndata: ${JSON.stringify(data)}\n\n`)
181
+ } catch {
182
+ // 客户端已断开。
183
+ }
184
+ }
185
+ /** 见过的「终止信号」:任一出现即视为上游正常收尾。 */
186
+ let terminated = false
187
+ const forward = (event) => {
188
+ if (event.data === undefined) return
189
+ const type = event.data?.type
190
+ if (type === 'message_delta' || type === 'message_stop' || type === 'error') terminated = true
191
+ writeEvent(event.event ?? type ?? 'message', event.data)
192
+ }
193
+ for (const event of result.head) forward(event)
194
+ if (result.decoder !== undefined) {
195
+ for (;;) {
196
+ const next = await result.decoder.read()
197
+ if (next.done === true) break
198
+ forward(next.value)
199
+ }
200
+ }
201
+ if (!terminated && !res.destroyed) {
202
+ log('[endpoint] ⚠ 上游流在 finish 之前结束(半截响应):向客户端补发 error 帧')
203
+ writeEvent('error', {
204
+ type: 'error',
205
+ error: { type: 'api_error', message: 'upstream stream ended before finish' },
206
+ })
207
+ }
208
+ if (!res.destroyed) res.end()
209
+ }
210
+
211
+ const listen = (port) =>
212
+ new Promise((resolve, reject) => {
213
+ const onError = (error) => {
214
+ server.removeListener('listening', onListening)
215
+ reject(error)
216
+ }
217
+ const onListening = () => {
218
+ server.removeListener('error', onError)
219
+ resolve()
220
+ }
221
+ server.once('error', onError)
222
+ server.once('listening', onListening)
223
+ server.listen(port, host)
224
+ })
225
+
226
+ let actualPort
227
+ try {
228
+ await listen(requestedPort)
229
+ actualPort = server.address().port
230
+ } catch (error) {
231
+ if (requestedPort === 0 || (error?.code !== 'EADDRINUSE' && error?.code !== 'EACCES')) throw error
232
+ log(`[endpoint] ⚠ 端口 ${requestedPort} 不可用(${error.code}),已回退随机端口`)
233
+ await listen(0)
234
+ actualPort = server.address().port
235
+ }
236
+
237
+ const baseUrl = `http://${host}:${actualPort}`
238
+ log(`[endpoint] 已监听 ${baseUrl}`)
239
+
240
+ return {
241
+ port: actualPort,
242
+ baseUrl,
243
+ token,
244
+ async close() {
245
+ await new Promise((resolve) => server.close(() => resolve()))
246
+ },
247
+ }
248
+ }
249
+
250
+ /** 读完整请求体。 */
251
+ function readBody(req) {
252
+ return new Promise((resolve, reject) => {
253
+ const chunks = []
254
+ req.on('data', (chunk) => chunks.push(chunk))
255
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')))
256
+ req.on('error', reject)
257
+ })
258
+ }
259
+
260
+ /**
261
+ * 把 Anthropic Messages 请求体翻成 DSH 的 GenerateOptions。
262
+ *
263
+ * pi-ai 发来的 body 已经是 Anthropic 形态(`system` / `messages` / `tools`),
264
+ * 这里逆变换回 DSH 词汇,好让 `buildUpstreamBody` 再统一注入身份块与日期块。
265
+ */
266
+ export function toGenerateOptions(body) {
267
+ const systemText = Array.isArray(body.system)
268
+ ? body.system.filter((block) => block?.type === 'text').map((block) => block.text).join('\n\n')
269
+ : typeof body.system === 'string'
270
+ ? body.system
271
+ : undefined
272
+
273
+ const messages = (Array.isArray(body.messages) ? body.messages : []).map((message) => ({
274
+ role: message.role === 'assistant' ? 'assistant' : 'user',
275
+ content: toDshContent(message.content),
276
+ }))
277
+
278
+ const tools = (Array.isArray(body.tools) ? body.tools : []).map((tool) => ({
279
+ name: tool.name,
280
+ description: tool.description,
281
+ parameters: tool.input_schema ?? tool.parameters,
282
+ }))
283
+
284
+ return {
285
+ model: body.model,
286
+ ...(systemText !== undefined ? { system: [{ type: 'text', text: systemText }] } : {}),
287
+ messages,
288
+ ...(tools.length > 0 ? { tools } : {}),
289
+ ...(typeof body.temperature === 'number' ? { temperature: body.temperature } : {}),
290
+ }
291
+ }
292
+
293
+ /** Anthropic content → DSH content blocks。 */
294
+ function toDshContent(content) {
295
+ if (typeof content === 'string') return [{ type: 'text', text: content }]
296
+ if (!Array.isArray(content)) return []
297
+ const out = []
298
+ for (const block of content) {
299
+ if (block?.type === 'text' && typeof block.text === 'string') out.push({ type: 'text', text: block.text })
300
+ else if (block?.type === 'tool_use') {
301
+ out.push({ type: 'tool-call', id: block.id, name: block.name, arguments: block.input ?? {} })
302
+ } else if (block?.type === 'tool_result') {
303
+ out.push({
304
+ type: 'tool-result',
305
+ toolCallId: block.tool_use_id,
306
+ output: typeof block.content === 'string' ? block.content : JSON.stringify(block.content ?? ''),
307
+ isError: block.is_error === true,
308
+ })
309
+ } else if (block?.type === 'image' && block.source?.type === 'base64') {
310
+ out.push({
311
+ type: 'image',
312
+ source: { type: 'base64', media_type: block.source.media_type, data: block.source.data },
313
+ })
314
+ }
315
+ }
316
+ return out
317
+ }
318
+
319
+ /** 把一段流事件折叠成一个 Anthropic message(非流式请求用)。 */
320
+ async function collapseToMessage(head) {
321
+ const content = []
322
+ let usage = { input_tokens: 0, output_tokens: 0 }
323
+ let stopReason = 'end_turn'
324
+ const partialJson = new Map()
325
+ for (const event of head) {
326
+ const data = event.data
327
+ if (data === undefined) continue
328
+ if (data.type === 'message_start') {
329
+ usage = { ...usage, ...(data.message?.usage ?? {}) }
330
+ } else if (data.type === 'content_block_start') {
331
+ content[data.index] = { ...data.content_block }
332
+ if (data.content_block?.type === 'tool_use') partialJson.set(data.index, data.content_block.input ?? '')
333
+ } else if (data.type === 'content_block_delta') {
334
+ const block = content[data.index]
335
+ if (block === undefined) continue
336
+ const delta = data.delta ?? {}
337
+ if (delta.type === 'text_delta') block.text = (block.text ?? '') + delta.text
338
+ else if (delta.type === 'thinking_delta') block.thinking = (block.thinking ?? '') + delta.thinking
339
+ else if (delta.type === 'input_json_delta') {
340
+ const current = partialJson.get(data.index) ?? ''
341
+ partialJson.set(data.index, current + delta.partial_json)
342
+ }
343
+ } else if (data.type === 'message_delta') {
344
+ if (typeof data.delta?.stop_reason === 'string') stopReason = data.delta.stop_reason
345
+ usage = { ...usage, ...(data.usage ?? {}) }
346
+ }
347
+ }
348
+ for (const [index, raw] of partialJson) {
349
+ const block = content[index]
350
+ if (block === undefined) continue
351
+ try {
352
+ block.input = typeof raw === 'string' ? JSON.parse(raw || '{}') : raw
353
+ } catch {
354
+ block.input = {}
355
+ }
356
+ }
357
+ return {
358
+ id: `msg_${Math.random().toString(36).slice(2)}`,
359
+ type: 'message',
360
+ role: 'assistant',
361
+ model: 'zcode-start-plan',
362
+ content: content.filter(Boolean),
363
+ stop_reason: stopReason,
364
+ stop_sequence: null,
365
+ usage,
366
+ }
367
+ }