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.
- package/CHANGELOG.md +1963 -672
- package/README.md +92 -472
- package/bin/cli.mjs +509 -450
- package/client.js +2459 -1002
- package/cordis.patch.yml +4 -2
- package/index.js +109 -11
- package/lib/adapter.js +476 -449
- package/lib/anthropic-body.js +513 -469
- package/lib/assemble.js +808 -542
- 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 -652
- 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 -611
- package/lib/upstream.js +294 -134
- package/lib/version-probe.js +110 -0
- package/package.json +84 -81
- 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 -116
- package/scripts/test-claimed-pending.mjs +152 -0
- package/scripts/verify_compat.mjs +75 -64
- package/scripts/watch-marketing.mjs +155 -0
- package/tests/auto-claim.test.mjs +318 -0
- package/tests/claim-routes.test.mjs +438 -293
- package/tests/client-panel.test.mjs +1141 -356
- package/tests/distribution-keys.test.mjs +123 -0
- package/tests/e2e.test.mjs +388 -353
- package/tests/fallback-scrub.test.mjs +105 -0
- package/tests/launch-command.test.mjs +68 -0
- package/tests/openai-gateway.test.mjs +454 -0
- package/tests/pinned-models.test.mjs +505 -497
- package/tests/plan-client.test.mjs +582 -222
- package/tests/pool.test.mjs +319 -93
- 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/support/hanging-stream.mjs +48 -0
- package/tests/upstream-error-200.test.mjs +164 -125
- package/tests/upstream.test.mjs +330 -250
- package/tests/version-probe.test.mjs +172 -0
package/lib/local-endpoint.js
CHANGED
|
@@ -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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
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
|
+
}
|