one-model-router 0.0.10 → 0.0.11

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 (77) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/src/admin.js +941 -941
  4. package/src/balances.js +61 -61
  5. package/src/boot.js +117 -117
  6. package/src/channels/buddy.js +2031 -2031
  7. package/src/channels/cline.js +753 -753
  8. package/src/channels/codearts.js +2051 -2051
  9. package/src/channels/comate.js +830 -830
  10. package/src/channels/doubaowork.js +1784 -1784
  11. package/src/channels/freebuff.js +1316 -1316
  12. package/src/channels/gemini.js +1721 -1721
  13. package/src/channels/index.js +270 -270
  14. package/src/channels/joycode.js +936 -936
  15. package/src/channels/kimi.js +572 -572
  16. package/src/channels/lobsterai.js +1226 -1226
  17. package/src/channels/loomy.js +1032 -1032
  18. package/src/channels/miaoshou.js +1396 -1396
  19. package/src/channels/mimo.js +474 -474
  20. package/src/channels/minimax.js +1451 -1451
  21. package/src/channels/qoder-wasm.js +434 -434
  22. package/src/channels/qoder.js +1619 -1619
  23. package/src/channels/raccoon.js +1842 -1842
  24. package/src/channels/tabbit.js +1457 -1457
  25. package/src/channels/trae.js +1405 -1405
  26. package/src/channels/zcode-global.js +35 -35
  27. package/src/channels/zcode.js +2085 -2085
  28. package/src/checkin.js +496 -496
  29. package/src/credits.js +464 -464
  30. package/src/crypto.js +132 -132
  31. package/src/free-models.js +683 -683
  32. package/src/gateway.js +596 -578
  33. package/src/health.js +86 -86
  34. package/src/model-key.js +35 -35
  35. package/src/paths.js +96 -96
  36. package/src/probe.js +318 -318
  37. package/src/providers/builtin.js +626 -626
  38. package/src/providers/index.js +483 -457
  39. package/src/providers/kilo.js +111 -111
  40. package/src/providers/last-good.js +69 -69
  41. package/src/providers/modelsdev.js +242 -242
  42. package/src/providers/openai-compat.js +312 -312
  43. package/src/providers/opencode/bun-fetch.js +226 -226
  44. package/src/providers/opencode/lane.js +186 -186
  45. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  46. package/src/providers/opencode/o2a/asset-source.js +43 -43
  47. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  48. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  49. package/src/providers/opencode/o2a/entry.js +17 -17
  50. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  51. package/src/providers/opencode/o2a/headers.js +133 -133
  52. package/src/providers/opencode/o2a/identity.js +148 -148
  53. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  54. package/src/providers/opencode/o2a/official-tools.js +110 -110
  55. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  56. package/src/providers/opencode/o2a/toolshape.js +418 -418
  57. package/src/providers/opencode/o2a/version.js +37 -37
  58. package/src/providers/opencode/upstream.js +403 -403
  59. package/src/providers/opencode/wire.js +496 -496
  60. package/src/providers/opencode.js +652 -652
  61. package/src/router.js +629 -629
  62. package/src/server.js +33 -33
  63. package/src/store.js +467 -467
  64. package/src/sync/index.js +1529 -1529
  65. package/src/sync/login-preload.cjs +52 -52
  66. package/src/sync/noise.js +141 -141
  67. package/src/sync/relay-http.js +176 -176
  68. package/src/sync/remote-host.js +818 -818
  69. package/src/sync/remote-http.js +112 -112
  70. package/src/sync/remote-login.js +657 -657
  71. package/src/sync/remote-pairing.js +204 -204
  72. package/src/sync/remote-protocol.js +321 -321
  73. package/src/sync/snapshot.js +211 -211
  74. package/src/util.js +334 -334
  75. package/web/app.js +3972 -3972
  76. package/web/index.html +32 -32
  77. package/web/style.css +971 -971
package/src/gateway.js CHANGED
@@ -1,578 +1,596 @@
1
- /**
2
- * 本地网关:OpenAI 兼容转发。
3
- *
4
- * 路由:
5
- * GET /health 存活探针(无需鉴权)
6
- * GET /v1/models 合并目录(通道模型 + 模型组)
7
- * POST /v1/chat/completions OpenAI chat(流式 SSE / 非流式)
8
- * POST /v1/messages Anthropic messages(文本 + 基础工具转换)
9
- *
10
- * 鉴权:Bearer 本地 key;CORS 预开放。agent 只需把 baseURL 指到
11
- * http://127.0.0.1:<port>/v1 并填本地 key。
12
- */
13
-
14
- import http from 'node:http'
15
- import { loadSettings, recordRequest } from './store.js'
16
- import { buildCatalog, resolveModel, completeOnModel } from './providers/index.js'
17
- import { completeOnGroup, buildGroupCatalogRows } from './router.js'
18
- import * as health from './health.js'
19
- import { json, openAiError, slugify, generateApiKey, errorText } from './util.js'
20
-
21
- const SSE_HEARTBEAT_MS = 15_000
22
-
23
- export function createGatewayServer({ log = () => {} } = {}) {
24
- const server = http.createServer((req, res) => {
25
- void handle(req, res).catch(error => {
26
- log(`gateway request failed: ${errorText(error)}`)
27
- if (!res.headersSent) openAiError(res, 502, 'upstream_error', errorText(error))
28
- else res.end()
29
- })
30
- })
31
-
32
- async function handle(req, res) {
33
- const url = new URL(req.url ?? '/', 'http://localhost')
34
- const path = url.pathname.replace(/\/+$/, '') || '/'
35
- const settings = loadSettings()
36
- const gw = settings.gateway ?? {}
37
-
38
- if (req.method === 'OPTIONS') {
39
- res.writeHead(204, corsHeaders())
40
- res.end()
41
- return
42
- }
43
- if (path === '/' || path === '/health') {
44
- json(res, 200, { ok: true, service: 'OneModelRouter', version: '1.0.0' })
45
- return
46
- }
47
- if (gw.enabled === false) {
48
- openAiError(res, 503, 'service_unavailable', '网关已在设置中关闭')
49
- return
50
- }
51
- if (!authorized(req, gw.apiKey)) {
52
- openAiError(res, 401, 'invalid_request_error', 'missing or invalid API key(请到管理界面总览页复制完整 Key;带 … 的缩略形式不是有效 Key)')
53
- return
54
- }
55
-
56
- if (req.method === 'GET' && (path === '/v1/models' || path === '/models')) {
57
- const rows = await buildCatalog()
58
- const groups = await buildGroupCatalogRows()
59
- const data = [...rows.filter(r => !r.offline), ...groups].map(row => ({
60
- id: row.id,
61
- object: 'model',
62
- created: Math.floor(Date.now() / 1000),
63
- owned_by: row.provider,
64
- context_window: row.contextWindow ?? undefined,
65
- free: row.free === true,
66
- }))
67
- json(res, 200, { object: 'list', data })
68
- return
69
- }
70
-
71
- if (req.method === 'POST' && (path === '/v1/chat/completions' || path === '/chat/completions')) {
72
- await serveChatCompletions(req, res, settings, log)
73
- return
74
- }
75
-
76
- if (req.method === 'POST' && (path === '/v1/messages' || path === '/messages')) {
77
- await serveAnthropicMessages(req, res, settings, log)
78
- return
79
- }
80
-
81
- openAiError(res, 404, 'not_found_error', `no route for ${req.method} ${path}`)
82
- }
83
-
84
- return server
85
- }
86
-
87
- function corsHeaders() {
88
- return {
89
- 'access-control-allow-origin': '*',
90
- 'access-control-allow-methods': 'GET, POST, OPTIONS',
91
- 'access-control-allow-headers': 'authorization, content-type, x-api-key, anthropic-version',
92
- 'access-control-max-age': '86400',
93
- }
94
- }
95
-
96
- function authorized(req, apiKey) {
97
- if (typeof apiKey !== 'string' || apiKey === '') return true
98
- const header = req.headers['authorization'] ?? ''
99
- if (header.startsWith('Bearer ') && header.slice(7).trim() === apiKey) return true
100
- const alt = req.headers['x-api-key']
101
- return typeof alt === 'string' && alt.trim() === apiKey
102
- }
103
-
104
- /** 从 User-Agent 识别客户端名称(agent 名等);识别不出返回空串(UI 显示 --)。 */
105
- function clientNameFromUa(ua) {
106
- if (!ua) return ''
107
- const rules = [
108
- [/opencode/i, 'opencode'],
109
- [/claude-cli|claude-code/i, 'Claude Code'],
110
- [/cline/i, 'Cline'],
111
- [/roo-?code/i, 'Roo Code'],
112
- [/cursor/i, 'Cursor'],
113
- [/trae/i, 'Trae'],
114
- [/codex/i, 'Codex'],
115
- [/gemini-cli/i, 'Gemini CLI'],
116
- [/aider/i, 'aider'],
117
- [/continue/i, 'Continue'],
118
- [/deepseek-harness/i, 'dsh'],
119
- [/^workbuddy\//i, 'WorkBuddy'],
120
- [/curl/i, 'curl'],
121
- [/wget/i, 'wget'],
122
- [/httpx|python-requests|aiohttp/i, 'python'],
123
- [/^node(\/|\s|$)|axios|undici|node-fetch/i, 'node'],
124
- [/go-http-client/i, 'go'],
125
- [/java\//i, 'java'],
126
- [/PowerShell/i, 'PowerShell'],
127
- [/^hertz$/i, 'Trae CN'],
128
- ]
129
- for (const [re, name] of rules) if (re.test(ua)) return name
130
- if (/Edg\//.test(ua)) return 'Edge'
131
- if (/OPR\/|Opera/.test(ua)) return 'Opera'
132
- if (/Firefox\//.test(ua)) return 'Firefox'
133
- if (/Chrome\//.test(ua)) return 'Chrome'
134
- if (/Safari\//.test(ua)) return 'Safari'
135
-
136
- // 兜底:长度 <30 → 直接返回 UA;否则取首个 / 前 30 字符,无 / 则前 30 字符
137
- if (ua.length < 30) return ua
138
- const slashIdx = ua.indexOf('/')
139
- const base = slashIdx === -1 ? ua.slice(0, 30) : ua.slice(0, Math.min(slashIdx, 30))
140
- return base.length > 30 ? base.slice(0, 30) : base
141
- }
142
-
143
- /** 请求来源:客户端名称 + IP/UA 原文(原始信息进 tooltip,便于排查)。 */
144
- function requestSource(req) {
145
- const ua = typeof req.headers['user-agent'] === 'string' ? req.headers['user-agent'] : ''
146
- return {
147
- ip: String(req.socket?.remoteAddress ?? '').replace(/^::ffff:/, ''),
148
- ua,
149
- client: clientNameFromUa(ua),
150
- }
151
- }
152
-
153
- /**
154
- * 网关超时/组调度参数(设置页可调)。
155
- * candidateTimeoutMs:组内单候选首字预算;hedgeDelayMs/hedgeMaxParallel:对冲并发。
156
- */
157
- function gatewayTimeouts(settings) {
158
- const gw = settings.gateway ?? {}
159
- return {
160
- headerTimeoutMs: gw.headerTimeoutMs ?? 60000,
161
- idleTimeoutMs: gw.idleTimeoutMs ?? 120000,
162
- turnTimeoutMs: gw.turnTimeoutMs ?? 300000,
163
- candidateTimeoutMs: gw.candidateTimeoutMs ?? 45000,
164
- hedgeDelayMs: gw.hedgeDelayMs ?? 6000,
165
- hedgeMaxParallel: gw.hedgeMaxParallel ?? 2,
166
- }
167
- }
168
-
169
- async function readJsonBody(req, limit = 20 * 1024 * 1024) {
170
- const chunks = []
171
- let size = 0
172
- for await (const chunk of req) {
173
- size += chunk.length
174
- if (size > limit) throw new Error('request body too large')
175
- chunks.push(chunk)
176
- }
177
- const text = Buffer.concat(chunks).toString('utf8')
178
- if (text === '') return {}
179
- return JSON.parse(text)
180
- }
181
-
182
- /** 提取会话标识:X-Session-Id 请求头(调用方显式声明会话边界),缺失返回空串。 */
183
- function sessionKeyFromRequest(req) {
184
- const v = req.headers['x-session-id']
185
- return typeof v === 'string' ? v.trim() : ''
186
- }
187
-
188
- // ── OpenAI chat completions ─────────────────────────────────────────────────
189
-
190
- async function serveChatCompletions(req, res, settings, log) {
191
- let body
192
- try {
193
- body = await readJsonBody(req)
194
- } catch (error) {
195
- openAiError(res, 400, 'invalid_request_error', `invalid JSON body: ${error.message}`)
196
- return
197
- }
198
- const modelId = typeof body.model === 'string' ? body.model.trim() : ''
199
- if (modelId === '') {
200
- openAiError(res, 400, 'invalid_request_error', 'model is required')
201
- return
202
- }
203
- const resolved = await resolveModel(modelId)
204
- if (!resolved) {
205
- openAiError(res, 404, 'not_found_error', `unknown model: ${modelId}(见 /v1/models)`)
206
- return
207
- }
208
-
209
- const abortController = new AbortController()
210
- req.on('close', () => abortController.abort())
211
- const timeouts = gatewayTimeouts(settings)
212
- const startedAt = Date.now()
213
- const source = requestSource(req)
214
- const sessionKey = sessionKeyFromRequest(req)
215
- const trace = { model: modelId, outcome: 'failed', fallbackFrom: null, tried: [], sticky: null }
216
- const wantStream = body.stream === true
217
-
218
- // 客户端要流式:立即下发 SSE 响应头并周期发心跳注释行(: ping),
219
- // 让等待首帧的连接上始终有字节流动 —— 否则 Trae hertz 等前置网关
220
- // 因长时间收不到首字节直接判 Connection timeout (HTTP 500, 4028)。
221
- // 内容帧边到边下发(不再等整轮聚合),首帧到达后停掉心跳。
222
- let heartbeatTimer = null
223
- let wroteAnyChunk = false
224
- // 首字延迟(TTFT):首个「携带可见内容」的数据帧下发时刻(正文/思考/工具调用;
225
- // 纯 role 空帧不算,避免上游早回 role 帧把 TTFT 拉假)。0 = 尚未出内容帧。
226
- let firstContentAt = 0
227
- const stopHeartbeat = () => { if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null } }
228
- const frameHasVisibleContent = text => {
229
- let chunk = null
230
- try { chunk = JSON.parse(text) } catch { return false }
231
- for (const c of Array.isArray(chunk?.choices) ? chunk.choices : []) {
232
- const d = c?.delta ?? c?.message ?? {}
233
- if (typeof d.content === 'string' && d.content !== '') return true
234
- if (typeof d.reasoning_content === 'string' && d.reasoning_content !== '') return true
235
- if (typeof d.reasoning === 'string' && d.reasoning !== '') return true
236
- if (Array.isArray(d.tool_calls) && d.tool_calls.length > 0) return true
237
- }
238
- return false
239
- }
240
- const writeChunk = chunk => {
241
- stopHeartbeat()
242
- if (firstContentAt === 0 && frameHasVisibleContent(chunk)) firstContentAt = Date.now()
243
- wroteAnyChunk = true
244
- if (res.writableEnded) return
245
- try { res.write(`data: ${chunk}\n\n`) } catch { /* 客户端已断开,交由 abort 流程 */ }
246
- }
247
- if (wantStream) {
248
- res.writeHead(200, {
249
- 'content-type': 'text/event-stream; charset=utf-8',
250
- 'cache-control': 'no-cache',
251
- connection: 'keep-alive',
252
- ...corsHeaders(),
253
- })
254
- res.on('error', () => {}) // 客户端中途断开时吞掉 EPIPE,避免未处理 error 事件
255
- res.flushHeaders() // 立即把 SSE 响应头推出缓冲区(writeHead 本身不发包)
256
- heartbeatTimer = setInterval(() => {
257
- if (!res.writableEnded) res.write(': ping\n\n')
258
- }, SSE_HEARTBEAT_MS)
259
- res.on('close', stopHeartbeat)
260
- }
261
-
262
- try {
263
- let payload
264
- let streamed = false
265
- let winnerTiming = null
266
- if (resolved.group) {
267
- // 组内:流式直通(胜出候选的 chunk 实时下发),非流式仍聚合
268
- body.stream = wantStream
269
- const result = await completeOnGroup(resolved.entry, { ...body }, {
270
- signal: abortController.signal,
271
- timeouts,
272
- sessionKey,
273
- onData: wantStream ? writeChunk : undefined,
274
- })
275
- trace.tried = result.tried
276
- if (result.tried.length > 1) trace.fallbackFrom = result.tried[0].id
277
- if (result.sticky) trace.sticky = result.sticky
278
- streamed = wantStream && (result.streamed === true || wroteAnyChunk)
279
- winnerTiming = result.winnerTiming ?? null
280
- payload = result.result?.json ?? result.result
281
- } else {
282
- const result = await completeOnModel(resolved, { ...body, stream: wantStream }, {
283
- signal: abortController.signal,
284
- timeouts,
285
- sessionKey,
286
- onData: wantStream ? writeChunk : undefined,
287
- })
288
- trace.tried = [{ id: resolved.id, ok: true }]
289
- streamed = wantStream && (result?.stream === true || wroteAnyChunk)
290
- payload = result.json ?? result
291
- }
292
- // 已逐帧下发过内容时不再校验聚合结果(kilo/opencode/自定义提供商流式不返回聚合体)
293
- if (!streamed && !payload?.choices) throw { kind: 'server', retryable: true, cooldownMs: 0, message: '上游响应缺少 choices' }
294
- trace.outcome = 'success'
295
- // ttftMs:只记录「最后实际调用成功的模型」的首字延迟(TTFT):
296
- // 组内 = 胜出候选(首个内容帧锁定的那个)从它被调用到首帧的时刻;
297
- // 单模型直连 = 该模型自身;流式但未出内容(即将整体重放)按响应到达时刻计;
298
- // 纯非流式请求没有"首字"概念,不记录。
299
- const endedAt = Date.now()
300
- let ttftMs
301
- if (wantStream) {
302
- const winStart = winnerTiming?.startedAt ?? startedAt
303
- const winFirst = winnerTiming?.committedAt ?? firstContentAt
304
- ttftMs = winFirst > 0 ? Math.max(0, winFirst - winStart) : endedAt - startedAt
305
- }
306
- recordRequest({ model: modelId, outcome: 'success', source, durationMs: endedAt - startedAt, ttftMs, fallbackFrom: trace.fallbackFrom, tried: trace.tried, usage: payload?.usage ?? null, sticky: trace.sticky })
307
- if (wantStream) {
308
- stopHeartbeat() // 数据帧即将下发,心跳完成使命
309
- if (streamed) {
310
- if (!res.writableEnded) res.write('data: [DONE]\n\n')
311
- res.end()
312
- } else {
313
- await streamOpenAiResponse(res, payload, resolved, { headed: true })
314
- }
315
- } else {
316
- json(res, 200, payload)
317
- }
318
- } catch (error) {
319
- // 组路径失败时 tried 在 router 抛出的错误上(成功路径才走 result.tried)
320
- if (Array.isArray(error?.tried)) trace.tried = error.tried
321
- if (abortController.signal.aborted) {
322
- trace.outcome = 'aborted'
323
- recordRequest({ model: modelId, outcome: 'aborted', source, durationMs: Date.now() - startedAt, tried: trace.tried, sticky: trace.sticky })
324
- // 客户端主动断开(Trae hertz 网关超时断开):用 499 正常结束而非 res.destroy(),
325
- // 避免上游网关把半开连接渲染成 "Connection timeout (HTTP Status: 500)"。
326
- if (!res.headersSent) openAiError(res, 499, 'client_aborted', 'client disconnected')
327
- else if (!res.writableEnded) res.end()
328
- return
329
- }
330
- trace.outcome = 'failed'
331
- recordRequest({
332
- model: modelId,
333
- outcome: 'failed',
334
- source,
335
- durationMs: Date.now() - startedAt,
336
- // 已下发过内容后失败(半截回复)也记首字延迟,便于判断是「早断开」还是「生成很久后断开」
337
- ttftMs: firstContentAt > 0 ? firstContentAt - startedAt : undefined,
338
- fallbackFrom: trace.fallbackFrom,
339
- tried: trace.tried,
340
- sticky: trace.sticky,
341
- })
342
- log(`completion failed for ${modelId}: ${errorText(error)} (tried: ${trace.tried.map(t => t.id).join(' -> ') || '-'})`)
343
- const status = error?.kind === 'auth' ? 502 : error?.kind === 'quota' ? 429 : error?.kind === 'not_found' ? 404 : 502
344
- const detail = trace.tried.length > 1
345
- ? `${trace.tried.map(t => `${t.id}: ${t.message ?? 'ok'}`).join(';')}`
346
- : errorText(error)
347
- stopHeartbeat()
348
- if (!res.headersSent) {
349
- openAiError(res, status, error?.kind ?? 'upstream_error', `所有候选均失败 —— ${detail}`)
350
- } else {
351
- // SSE 已开流(心跳路径):以数据帧下发真实失败原因后收尾,
352
- // 客户端拿到的是明确错误而非误导性的连接超时。
353
- try {
354
- res.write(`data: ${JSON.stringify({ error: { message: `所有候选均失败 —— ${detail}`, type: error?.kind ?? 'upstream_error', code: error?.kind ?? 'upstream_error' } })}\n\n`)
355
- } catch { /* socket 已坏,忽略 */ }
356
- res.end()
357
- }
358
- }
359
- }
360
-
361
- /**
362
- * 把一个完整 OpenAI 响应重放为 SSE 流(组内非流式采集后的重放路径)。
363
- * headed=true:SSE 响应头已由心跳路径提前下发(采集期保活),这里只重放帧。
364
- */
365
- async function streamOpenAiResponse(res, payload, resolved, { headed = false } = {}) {
366
- if (!headed) {
367
- res.writeHead(200, {
368
- 'content-type': 'text/event-stream; charset=utf-8',
369
- 'cache-control': 'no-cache',
370
- connection: 'keep-alive',
371
- ...corsHeaders(),
372
- })
373
- }
374
- const id = payload.id ?? 'chatcmpl-omr'
375
- const created = payload.created ?? Math.floor(Date.now() / 1000)
376
- const model = payload.model ?? resolved?.id ?? ''
377
- const choice = payload.choices?.[0]
378
- const message = choice?.message ?? { role: 'assistant', content: '' }
379
- const content = typeof message.content === 'string' ? message.content : ''
380
- const reasoning = message.reasoning_content ?? message.reasoning ?? null
381
-
382
- const send = (obj) => res.write(`data: ${JSON.stringify(obj)}\n\n`)
383
- const base = { id, object: 'chat.completion.chunk', created, model }
384
- if (reasoning) {
385
- send({ ...base, choices: [{ index: 0, delta: { reasoning_content: reasoning }, finish_reason: null }] })
386
- }
387
- if (content !== '') {
388
- send({ ...base, choices: [{ index: 0, delta: { role: 'assistant', content }, finish_reason: null }] })
389
- }
390
- if (Array.isArray(message.tool_calls)) {
391
- for (const [i, tc] of message.tool_calls.entries()) {
392
- send({ ...base, choices: [{ index: 0, delta: { tool_calls: [{ index: i, ...tc }] }, finish_reason: null }] })
393
- }
394
- }
395
- send({ ...base, choices: [{ index: 0, delta: {}, finish_reason: choice?.finish_reason ?? 'stop' }] })
396
- if (payload.usage) send({ ...base, choices: [], usage: payload.usage })
397
- res.write('data: [DONE]\n\n')
398
- res.end()
399
- }
400
-
401
- // ── Anthropic /v1/messages(文本 + 基础工具转换)────────────────────────────
402
-
403
- function anthropicToOpenAi(body) {
404
- const messages = []
405
- if (typeof body.system === 'string' && body.system !== '') {
406
- messages.push({ role: 'system', content: body.system })
407
- } else if (Array.isArray(body.system)) {
408
- const text = body.system.filter(b => b?.type === 'text').map(b => b.text).join('\n')
409
- if (text !== '') messages.push({ role: 'system', content: text })
410
- }
411
- for (const msg of Array.isArray(body.messages) ? body.messages : []) {
412
- const role = msg.role === 'assistant' ? 'assistant' : 'user'
413
- if (typeof msg.content === 'string') {
414
- messages.push({ role, content: msg.content })
415
- continue
416
- }
417
- const toolResults = []
418
- const parts = []
419
- for (const block of Array.isArray(msg.content) ? msg.content : []) {
420
- if (block?.type === 'text') parts.push({ type: 'text', text: block.text ?? '' })
421
- else if (block?.type === 'tool_result') {
422
- toolResults.push(block)
423
- } else if (block?.type === 'image') {
424
- parts.push({ type: 'text', text: '[image omitted: upstream conversion does not carry images]' })
425
- }
426
- }
427
- if (toolResults.length > 0) {
428
- // tool_result 作为 user 消息里的 tool 响应
429
- for (const tr of toolResults) {
430
- const contentText = typeof tr.content === 'string'
431
- ? tr.content
432
- : Array.isArray(tr.content) ? tr.content.filter(b => b?.type === 'text').map(b => b.text).join('\n') : ''
433
- messages.push({ role: 'user', content: `tool_use_id ${tr.tool_use_id} result: ${contentText}` })
434
- }
435
- }
436
- if (parts.length > 0) {
437
- messages.push({ role, content: parts.map(p => p.text).join('\n') })
438
- }
439
- if (role === 'assistant' && Array.isArray(msg.content)) {
440
- const toolUses = msg.content.filter(b => b?.type === 'tool_use')
441
- if (toolUses.length > 0) {
442
- // assistant 的 tool_use 以文本形式提示上游(简单透传转换)
443
- const desc = toolUses.map(t => `[calls tool ${t.name} with ${JSON.stringify(t.input ?? {})}]`).join('\n')
444
- messages.push({ role: 'assistant', content: desc })
445
- }
446
- }
447
- }
448
- const out = { model: body.model, messages, max_tokens: body.max_tokens ?? 4096, stream: false }
449
- if (Array.isArray(body.tools) && body.tools.length > 0) {
450
- out.tools = body.tools.map(t => ({
451
- type: 'function',
452
- function: { name: t.name, description: t.description ?? '', parameters: t.input_schema ?? { type: 'object' } },
453
- }))
454
- }
455
- if (Array.isArray(body.stop_sequences) && body.stop_sequences.length > 0) out.stop = body.stop_sequences
456
- return out
457
- }
458
-
459
- function openAiToAnthropic(payload, requestId, model) {
460
- const choice = payload?.choices?.[0]
461
- const text = choice?.message?.content ?? ''
462
- const content = []
463
- if (typeof text === 'string' && text !== '') content.push({ type: 'text', text })
464
- let stopReason = choice?.finish_reason === 'length' ? 'max_tokens' : choice?.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn'
465
- return {
466
- id: requestId,
467
- type: 'message',
468
- role: 'assistant',
469
- model,
470
- content,
471
- stop_reason: stopReason,
472
- stop_sequence: null,
473
- usage: {
474
- input_tokens: payload?.usage?.prompt_tokens ?? 0,
475
- output_tokens: payload?.usage?.completion_tokens ?? 0,
476
- },
477
- }
478
- }
479
-
480
- async function serveAnthropicMessages(req, res, settings, log) {
481
- let body
482
- try {
483
- body = await readJsonBody(req)
484
- } catch (error) {
485
- json(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: `invalid JSON body: ${error.message}` } })
486
- return
487
- }
488
- const modelId = typeof body.model === 'string' ? body.model.trim() : ''
489
- if (modelId === '') {
490
- json(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: 'model is required' } })
491
- return
492
- }
493
- const resolved = await resolveModel(modelId)
494
- if (!resolved) {
495
- json(res, 404, { type: 'error', error: { type: 'not_found_error', message: `unknown model: ${modelId}` } })
496
- return
497
- }
498
-
499
- const abortController = new AbortController()
500
- req.on('close', () => abortController.abort())
501
- const openaiBody = anthropicToOpenAi(body)
502
- delete openaiBody.model // completeOn* 会注入上游模型名
503
- const startedAt = Date.now()
504
- const source = requestSource(req)
505
- const sessionKey = sessionKeyFromRequest(req)
506
- const trace = { model: modelId, tried: [], sticky: null }
507
-
508
- try {
509
- let payload
510
- if (resolved.group) {
511
- const result = await completeOnGroup(resolved.entry, openaiBody, {
512
- signal: abortController.signal,
513
- timeouts: gatewayTimeouts(settings),
514
- sessionKey,
515
- })
516
- payload = result.result.json ?? result.result
517
- trace.tried = result.tried
518
- if (result.sticky) trace.sticky = result.sticky
519
- } else {
520
- const result = await completeOnModel(resolved, openaiBody, { signal: abortController.signal, timeouts: gatewayTimeouts(settings) })
521
- payload = result.json ?? result
522
- trace.tried = [{ id: resolved.id, ok: true }]
523
- }
524
- const payloadObj = payload?.choices ? payload : null
525
- if (!payloadObj) throw { kind: 'server', retryable: true, cooldownMs: 0, message: '上游响应缺少 choices' }
526
- recordRequest({ model: modelId, outcome: 'success', source, durationMs: Date.now() - startedAt, tried: trace.tried, usage: payloadObj?.usage ?? null, sticky: trace.sticky })
527
- const requestId = `msg_omr_${Date.now().toString(36)}`
528
- const response = openAiToAnthropic(payloadObj, requestId, modelId)
529
- if (body.stream === true) {
530
- res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache', ...corsHeaders() })
531
- const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
532
- send('message_start', { type: 'message_start', message: { ...response, content: [] } })
533
- for (const block of response.content) {
534
- send('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } })
535
- send('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: block.text } })
536
- send('content_block_stop', { type: 'content_block_stop', index: 0 })
537
- }
538
- send('message_delta', { type: 'message_delta', delta: { stop_reason: response.stop_reason, stop_sequence: null }, usage: { output_tokens: response.usage.output_tokens } })
539
- send('message_stop', { type: 'message_stop' })
540
- res.end()
541
- } else {
542
- json(res, 200, response)
543
- }
544
- } catch (error) {
545
- if (Array.isArray(error?.tried)) trace.tried = error.tried
546
- if (abortController.signal.aborted) {
547
- recordRequest({ model: modelId, outcome: 'aborted', source, durationMs: Date.now() - startedAt, tried: trace.tried })
548
- // 客户端主动断开:正常结束而非 res.destroy(),避免上游网关把半开连接渲染成超时/500。
549
- if (!res.headersSent) json(res, 499, { type: 'error', error: { type: 'client_aborted', message: 'client disconnected' } })
550
- return
551
- }
552
- recordRequest({ model: modelId, outcome: 'failed', source, durationMs: Date.now() - startedAt, tried: trace.tried })
553
- log(`anthropic completion failed for ${modelId}: ${errorText(error)}`)
554
- if (!res.headersSent) {
555
- json(res, 502, { type: 'error', error: { type: 'upstream_error', message: `所有候选均失败 —— ${errorText(error)}` } })
556
- } else {
557
- res.end()
558
- }
559
- }
560
- }
561
-
562
- // ── 启动 ────────────────────────────────────────────────────────────────────
563
-
564
- export async function startGateway({ log = () => {}, port, host } = {}) {
565
- const settings = loadSettings()
566
- const gw = settings.gateway ?? {}
567
- const server = createGatewayServer({ log })
568
- return new Promise((resolve, reject) => {
569
- server.once('error', reject)
570
- const listenPort = Number.isFinite(Number(port)) && port > 0 ? Number(port) : Number.isFinite(Number(gw.port)) ? Number(gw.port) : 18682
571
- const listenHost = typeof host === 'string' && host !== '' ? host : typeof gw.host === 'string' && gw.host !== '' ? gw.host : '127.0.0.1'
572
- server.listen(listenPort, listenHost, () => {
573
- server.off('error', reject)
574
- log(`gateway listening on http://${listenHost}:${listenPort}/v1 (key: ${gw.apiKey ? gw.apiKey.slice(0, 8) + '…' : '无'})`)
575
- resolve({ server, port: listenPort, host: listenHost })
576
- })
577
- })
578
- }
1
+ /**
2
+ * 本地网关:OpenAI 兼容转发。
3
+ *
4
+ * 路由:
5
+ * GET /health 存活探针(无需鉴权)
6
+ * GET /v1/models 合并目录(通道模型 + 模型组)
7
+ * POST /v1/chat/completions OpenAI chat(流式 SSE / 非流式)
8
+ * POST /v1/messages Anthropic messages(文本 + 基础工具转换)
9
+ *
10
+ * 鉴权:Bearer 本地 key;CORS 预开放。agent 只需把 baseURL 指到
11
+ * http://127.0.0.1:<port>/v1 并填本地 key。
12
+ */
13
+
14
+ import http from 'node:http'
15
+ import { loadSettings, recordRequest } from './store.js'
16
+ import { buildCatalog, resolveModel, completeOnModel } from './providers/index.js'
17
+ import { completeOnGroup, buildGroupCatalogRows } from './router.js'
18
+ import * as health from './health.js'
19
+ import { json, openAiError, slugify, generateApiKey, errorText } from './util.js'
20
+
21
+ const SSE_HEARTBEAT_MS = 15_000
22
+
23
+ export function createGatewayServer({ log = () => {} } = {}) {
24
+ const server = http.createServer((req, res) => {
25
+ void handle(req, res).catch(error => {
26
+ log(`gateway request failed: ${errorText(error)}`)
27
+ if (!res.headersSent) openAiError(res, 502, 'upstream_error', errorText(error))
28
+ else res.end()
29
+ })
30
+ })
31
+
32
+ async function handle(req, res) {
33
+ const url = new URL(req.url ?? '/', 'http://localhost')
34
+ const path = url.pathname.replace(/\/+$/, '') || '/'
35
+ const settings = loadSettings()
36
+ const gw = settings.gateway ?? {}
37
+
38
+ if (req.method === 'OPTIONS') {
39
+ res.writeHead(204, corsHeaders())
40
+ res.end()
41
+ return
42
+ }
43
+ if (path === '/' || path === '/health') {
44
+ json(res, 200, { ok: true, service: 'OneModelRouter', version: '1.0.0' })
45
+ return
46
+ }
47
+ if (gw.enabled === false) {
48
+ openAiError(res, 503, 'service_unavailable', '网关已在设置中关闭')
49
+ return
50
+ }
51
+ if (!authorized(req, gw.apiKey)) {
52
+ openAiError(res, 401, 'invalid_request_error', 'missing or invalid API key(请到管理界面总览页复制完整 Key;带 … 的缩略形式不是有效 Key)')
53
+ return
54
+ }
55
+
56
+ if (req.method === 'GET' && (path === '/v1/models' || path === '/models')) {
57
+ const rows = await buildCatalog()
58
+ const groups = await buildGroupCatalogRows()
59
+ const data = [...rows.filter(r => !r.offline), ...groups].map(row => ({
60
+ id: row.id,
61
+ object: 'model',
62
+ created: Math.floor(Date.now() / 1000),
63
+ owned_by: row.provider,
64
+ context_window: row.contextWindow ?? undefined,
65
+ free: row.free === true,
66
+ }))
67
+ json(res, 200, { object: 'list', data })
68
+ return
69
+ }
70
+
71
+ if (req.method === 'POST' && (path === '/v1/chat/completions' || path === '/chat/completions')) {
72
+ await serveChatCompletions(req, res, settings, log)
73
+ return
74
+ }
75
+
76
+ if (req.method === 'POST' && (path === '/v1/messages' || path === '/messages')) {
77
+ await serveAnthropicMessages(req, res, settings, log)
78
+ return
79
+ }
80
+
81
+ openAiError(res, 404, 'not_found_error', `no route for ${req.method} ${path}`)
82
+ }
83
+
84
+ return server
85
+ }
86
+
87
+ function corsHeaders() {
88
+ return {
89
+ 'access-control-allow-origin': '*',
90
+ 'access-control-allow-methods': 'GET, POST, OPTIONS',
91
+ 'access-control-allow-headers': 'authorization, content-type, x-api-key, anthropic-version',
92
+ 'access-control-max-age': '86400',
93
+ }
94
+ }
95
+
96
+ function authorized(req, apiKey) {
97
+ if (typeof apiKey !== 'string' || apiKey === '') return true
98
+ const header = req.headers['authorization'] ?? ''
99
+ if (header.startsWith('Bearer ') && header.slice(7).trim() === apiKey) return true
100
+ const alt = req.headers['x-api-key']
101
+ return typeof alt === 'string' && alt.trim() === apiKey
102
+ }
103
+
104
+ /** 从 User-Agent 识别客户端名称(agent 名等);识别不出返回空串(UI 显示 --)。 */
105
+ function clientNameFromUa(ua) {
106
+ if (!ua) return ''
107
+ const rules = [
108
+ [/opencode/i, 'opencode'],
109
+ [/claude-cli|claude-code/i, 'Claude Code'],
110
+ [/cline/i, 'Cline'],
111
+ [/roo-?code/i, 'Roo Code'],
112
+ [/cursor/i, 'Cursor'],
113
+ [/trae/i, 'Trae'],
114
+ [/codex/i, 'Codex'],
115
+ [/gemini-cli/i, 'Gemini CLI'],
116
+ [/aider/i, 'aider'],
117
+ [/continue/i, 'Continue'],
118
+ [/deepseek-harness/i, 'dsh'],
119
+ [/^workbuddy\//i, 'WorkBuddy'],
120
+ [/curl/i, 'curl'],
121
+ [/wget/i, 'wget'],
122
+ [/httpx|python-requests|aiohttp/i, 'python'],
123
+ [/^node(\/|\s|$)|axios|undici|node-fetch/i, 'node'],
124
+ [/go-http-client/i, 'go'],
125
+ [/java\//i, 'java'],
126
+ [/PowerShell/i, 'PowerShell'],
127
+ [/^hertz$/i, 'Trae CN'],
128
+ ]
129
+ for (const [re, name] of rules) if (re.test(ua)) return name
130
+ if (/Edg\//.test(ua)) return 'Edge'
131
+ if (/OPR\/|Opera/.test(ua)) return 'Opera'
132
+ if (/Firefox\//.test(ua)) return 'Firefox'
133
+ if (/Chrome\//.test(ua)) return 'Chrome'
134
+ if (/Safari\//.test(ua)) return 'Safari'
135
+
136
+ // 兜底:长度 <30 → 直接返回 UA;否则取首个 / 前 30 字符,无 / 则前 30 字符
137
+ if (ua.length < 30) return ua
138
+ const slashIdx = ua.indexOf('/')
139
+ const base = slashIdx === -1 ? ua.slice(0, 30) : ua.slice(0, Math.min(slashIdx, 30))
140
+ return base.length > 30 ? base.slice(0, 30) : base
141
+ }
142
+
143
+ /** 请求来源:客户端名称 + IP/UA 原文(原始信息进 tooltip,便于排查)。 */
144
+ function requestSource(req) {
145
+ const ua = typeof req.headers['user-agent'] === 'string' ? req.headers['user-agent'] : ''
146
+ return {
147
+ ip: String(req.socket?.remoteAddress ?? '').replace(/^::ffff:/, ''),
148
+ ua,
149
+ client: clientNameFromUa(ua),
150
+ }
151
+ }
152
+
153
+ /**
154
+ * 网关超时/组调度参数(设置页可调)。
155
+ * candidateTimeoutMs:组内单候选首字预算;hedgeDelayMs/hedgeMaxParallel:对冲并发。
156
+ */
157
+ function gatewayTimeouts(settings) {
158
+ const gw = settings.gateway ?? {}
159
+ return {
160
+ headerTimeoutMs: gw.headerTimeoutMs ?? 60000,
161
+ idleTimeoutMs: gw.idleTimeoutMs ?? 120000,
162
+ turnTimeoutMs: gw.turnTimeoutMs ?? 300000,
163
+ candidateTimeoutMs: gw.candidateTimeoutMs ?? 45000,
164
+ hedgeDelayMs: gw.hedgeDelayMs ?? 6000,
165
+ hedgeMaxParallel: gw.hedgeMaxParallel ?? 2,
166
+ }
167
+ }
168
+
169
+ async function readJsonBody(req, limit = 20 * 1024 * 1024) {
170
+ const chunks = []
171
+ let size = 0
172
+ for await (const chunk of req) {
173
+ size += chunk.length
174
+ if (size > limit) throw new Error('request body too large')
175
+ chunks.push(chunk)
176
+ }
177
+ const text = Buffer.concat(chunks).toString('utf8')
178
+ if (text === '') return {}
179
+ return JSON.parse(text)
180
+ }
181
+
182
+ /** 提取会话标识:X-Session-Id 请求头(调用方显式声明会话边界),缺失返回空串。 */
183
+ function sessionKeyFromRequest(req) {
184
+ const v = req.headers['x-session-id']
185
+ return typeof v === 'string' ? v.trim() : ''
186
+ }
187
+
188
+ // ── OpenAI chat completions ─────────────────────────────────────────────────
189
+
190
+ async function serveChatCompletions(req, res, settings, log) {
191
+ let body
192
+ try {
193
+ body = await readJsonBody(req)
194
+ } catch (error) {
195
+ // 解析阶段失败同样要留痕:否则「最近请求」里什么都看不到,
196
+ // 面板只能看到「没请求」,无法把客户端报错和网关侧对上。
197
+ recordRequest({
198
+ model: '(unparsed)',
199
+ outcome: 'failed',
200
+ source: requestSource(req),
201
+ durationMs: 0,
202
+ tried: [{ id: '(unparsed)', ok: false, kind: 'invalid_request_error', message: `invalid JSON body: ${error.message}` }],
203
+ })
204
+ openAiError(res, 400, 'invalid_request_error', `invalid JSON body: ${error.message}`)
205
+ return
206
+ }
207
+ const modelId = typeof body.model === 'string' ? body.model.trim() : ''
208
+ if (modelId === '') {
209
+ openAiError(res, 400, 'invalid_request_error', 'model is required')
210
+ return
211
+ }
212
+ const resolved = await resolveModel(modelId)
213
+ if (!resolved) {
214
+ const message = `unknown model: ${modelId}(见 /v1/models)`
215
+ recordRequest({
216
+ model: modelId,
217
+ outcome: 'failed',
218
+ source: requestSource(req),
219
+ durationMs: 0,
220
+ tried: [{ id: modelId, ok: false, kind: 'not_found', message }],
221
+ })
222
+ log(`completion failed for ${modelId}: ${message}`)
223
+ openAiError(res, 404, 'not_found_error', message)
224
+ return
225
+ }
226
+
227
+ const abortController = new AbortController()
228
+ req.on('close', () => abortController.abort())
229
+ const timeouts = gatewayTimeouts(settings)
230
+ const startedAt = Date.now()
231
+ const source = requestSource(req)
232
+ const sessionKey = sessionKeyFromRequest(req)
233
+ const trace = { model: modelId, outcome: 'failed', fallbackFrom: null, tried: [], sticky: null }
234
+ const wantStream = body.stream === true
235
+
236
+ // 客户端要流式:立即下发 SSE 响应头并周期发心跳注释行(: ping),
237
+ // 让等待首帧的连接上始终有字节流动 —— 否则 Trae hertz 等前置网关
238
+ // 因长时间收不到首字节直接判 Connection timeout (HTTP 500, 4028)。
239
+ // 内容帧边到边下发(不再等整轮聚合),首帧到达后停掉心跳。
240
+ let heartbeatTimer = null
241
+ let wroteAnyChunk = false
242
+ // 首字延迟(TTFT):首个「携带可见内容」的数据帧下发时刻(正文/思考/工具调用;
243
+ // 纯 role 空帧不算,避免上游早回 role 帧把 TTFT 拉假)。0 = 尚未出内容帧。
244
+ let firstContentAt = 0
245
+ const stopHeartbeat = () => { if (heartbeatTimer) { clearInterval(heartbeatTimer); heartbeatTimer = null } }
246
+ const frameHasVisibleContent = text => {
247
+ let chunk = null
248
+ try { chunk = JSON.parse(text) } catch { return false }
249
+ for (const c of Array.isArray(chunk?.choices) ? chunk.choices : []) {
250
+ const d = c?.delta ?? c?.message ?? {}
251
+ if (typeof d.content === 'string' && d.content !== '') return true
252
+ if (typeof d.reasoning_content === 'string' && d.reasoning_content !== '') return true
253
+ if (typeof d.reasoning === 'string' && d.reasoning !== '') return true
254
+ if (Array.isArray(d.tool_calls) && d.tool_calls.length > 0) return true
255
+ }
256
+ return false
257
+ }
258
+ const writeChunk = chunk => {
259
+ stopHeartbeat()
260
+ if (firstContentAt === 0 && frameHasVisibleContent(chunk)) firstContentAt = Date.now()
261
+ wroteAnyChunk = true
262
+ if (res.writableEnded) return
263
+ try { res.write(`data: ${chunk}\n\n`) } catch { /* 客户端已断开,交由 abort 流程 */ }
264
+ }
265
+ if (wantStream) {
266
+ res.writeHead(200, {
267
+ 'content-type': 'text/event-stream; charset=utf-8',
268
+ 'cache-control': 'no-cache',
269
+ connection: 'keep-alive',
270
+ ...corsHeaders(),
271
+ })
272
+ res.on('error', () => {}) // 客户端中途断开时吞掉 EPIPE,避免未处理 error 事件
273
+ res.flushHeaders() // 立即把 SSE 响应头推出缓冲区(writeHead 本身不发包)
274
+ heartbeatTimer = setInterval(() => {
275
+ if (!res.writableEnded) res.write(': ping\n\n')
276
+ }, SSE_HEARTBEAT_MS)
277
+ res.on('close', stopHeartbeat)
278
+ }
279
+
280
+ try {
281
+ let payload
282
+ let streamed = false
283
+ let winnerTiming = null
284
+ if (resolved.group) {
285
+ // 组内:流式直通(胜出候选的 chunk 实时下发),非流式仍聚合
286
+ body.stream = wantStream
287
+ const result = await completeOnGroup(resolved.entry, { ...body }, {
288
+ signal: abortController.signal,
289
+ timeouts,
290
+ sessionKey,
291
+ onData: wantStream ? writeChunk : undefined,
292
+ })
293
+ trace.tried = result.tried
294
+ if (result.tried.length > 1) trace.fallbackFrom = result.tried[0].id
295
+ if (result.sticky) trace.sticky = result.sticky
296
+ streamed = wantStream && (result.streamed === true || wroteAnyChunk)
297
+ winnerTiming = result.winnerTiming ?? null
298
+ payload = result.result?.json ?? result.result
299
+ } else {
300
+ const result = await completeOnModel(resolved, { ...body, stream: wantStream }, {
301
+ signal: abortController.signal,
302
+ timeouts,
303
+ sessionKey,
304
+ onData: wantStream ? writeChunk : undefined,
305
+ })
306
+ trace.tried = [{ id: resolved.id, ok: true }]
307
+ streamed = wantStream && (result?.stream === true || wroteAnyChunk)
308
+ payload = result.json ?? result
309
+ }
310
+ // 已逐帧下发过内容时不再校验聚合结果(kilo/opencode/自定义提供商流式不返回聚合体)
311
+ if (!streamed && !payload?.choices) throw { kind: 'server', retryable: true, cooldownMs: 0, message: '上游响应缺少 choices' }
312
+ trace.outcome = 'success'
313
+ // ttftMs:只记录「最后实际调用成功的模型」的首字延迟(TTFT):
314
+ // 组内 = 胜出候选(首个内容帧锁定的那个)从它被调用到首帧的时刻;
315
+ // 单模型直连 = 该模型自身;流式但未出内容(即将整体重放)按响应到达时刻计;
316
+ // 纯非流式请求没有"首字"概念,不记录。
317
+ const endedAt = Date.now()
318
+ let ttftMs
319
+ if (wantStream) {
320
+ const winStart = winnerTiming?.startedAt ?? startedAt
321
+ const winFirst = winnerTiming?.committedAt ?? firstContentAt
322
+ ttftMs = winFirst > 0 ? Math.max(0, winFirst - winStart) : endedAt - startedAt
323
+ }
324
+ recordRequest({ model: modelId, outcome: 'success', source, durationMs: endedAt - startedAt, ttftMs, fallbackFrom: trace.fallbackFrom, tried: trace.tried, usage: payload?.usage ?? null, sticky: trace.sticky })
325
+ if (wantStream) {
326
+ stopHeartbeat() // 数据帧即将下发,心跳完成使命
327
+ if (streamed) {
328
+ if (!res.writableEnded) res.write('data: [DONE]\n\n')
329
+ res.end()
330
+ } else {
331
+ await streamOpenAiResponse(res, payload, resolved, { headed: true })
332
+ }
333
+ } else {
334
+ json(res, 200, payload)
335
+ }
336
+ } catch (error) {
337
+ // 组路径失败时 tried 在 router 抛出的错误上(成功路径才走 result.tried)
338
+ if (Array.isArray(error?.tried)) trace.tried = error.tried
339
+ if (abortController.signal.aborted) {
340
+ trace.outcome = 'aborted'
341
+ recordRequest({ model: modelId, outcome: 'aborted', source, durationMs: Date.now() - startedAt, tried: trace.tried, sticky: trace.sticky })
342
+ // 客户端主动断开(Trae hertz 网关超时断开):用 499 正常结束而非 res.destroy(),
343
+ // 避免上游网关把半开连接渲染成 "Connection timeout (HTTP Status: 500)"。
344
+ if (!res.headersSent) openAiError(res, 499, 'client_aborted', 'client disconnected')
345
+ else if (!res.writableEnded) res.end()
346
+ return
347
+ }
348
+ trace.outcome = 'failed'
349
+ recordRequest({
350
+ model: modelId,
351
+ outcome: 'failed',
352
+ source,
353
+ durationMs: Date.now() - startedAt,
354
+ // 已下发过内容后失败(半截回复)也记首字延迟,便于判断是「早断开」还是「生成很久后断开」
355
+ ttftMs: firstContentAt > 0 ? firstContentAt - startedAt : undefined,
356
+ fallbackFrom: trace.fallbackFrom,
357
+ tried: trace.tried,
358
+ sticky: trace.sticky,
359
+ })
360
+ log(`completion failed for ${modelId}: ${errorText(error)} (tried: ${trace.tried.map(t => t.id).join(' -> ') || '-'})`)
361
+ const status = error?.kind === 'auth' ? 502 : error?.kind === 'quota' ? 429 : error?.kind === 'not_found' ? 404 : 502
362
+ const detail = trace.tried.length > 1
363
+ ? `${trace.tried.map(t => `${t.id}: ${t.message ?? 'ok'}`).join(';')}`
364
+ : errorText(error)
365
+ stopHeartbeat()
366
+ if (!res.headersSent) {
367
+ openAiError(res, status, error?.kind ?? 'upstream_error', `所有候选均失败 —— ${detail}`)
368
+ } else {
369
+ // SSE 已开流(心跳路径):以数据帧下发真实失败原因后收尾,
370
+ // 客户端拿到的是明确错误而非误导性的连接超时。
371
+ try {
372
+ res.write(`data: ${JSON.stringify({ error: { message: `所有候选均失败 —— ${detail}`, type: error?.kind ?? 'upstream_error', code: error?.kind ?? 'upstream_error' } })}\n\n`)
373
+ } catch { /* socket 已坏,忽略 */ }
374
+ res.end()
375
+ }
376
+ }
377
+ }
378
+
379
+ /**
380
+ * 把一个完整 OpenAI 响应重放为 SSE 流(组内非流式采集后的重放路径)。
381
+ * headed=true:SSE 响应头已由心跳路径提前下发(采集期保活),这里只重放帧。
382
+ */
383
+ async function streamOpenAiResponse(res, payload, resolved, { headed = false } = {}) {
384
+ if (!headed) {
385
+ res.writeHead(200, {
386
+ 'content-type': 'text/event-stream; charset=utf-8',
387
+ 'cache-control': 'no-cache',
388
+ connection: 'keep-alive',
389
+ ...corsHeaders(),
390
+ })
391
+ }
392
+ const id = payload.id ?? 'chatcmpl-omr'
393
+ const created = payload.created ?? Math.floor(Date.now() / 1000)
394
+ const model = payload.model ?? resolved?.id ?? ''
395
+ const choice = payload.choices?.[0]
396
+ const message = choice?.message ?? { role: 'assistant', content: '' }
397
+ const content = typeof message.content === 'string' ? message.content : ''
398
+ const reasoning = message.reasoning_content ?? message.reasoning ?? null
399
+
400
+ const send = (obj) => res.write(`data: ${JSON.stringify(obj)}\n\n`)
401
+ const base = { id, object: 'chat.completion.chunk', created, model }
402
+ if (reasoning) {
403
+ send({ ...base, choices: [{ index: 0, delta: { reasoning_content: reasoning }, finish_reason: null }] })
404
+ }
405
+ if (content !== '') {
406
+ send({ ...base, choices: [{ index: 0, delta: { role: 'assistant', content }, finish_reason: null }] })
407
+ }
408
+ if (Array.isArray(message.tool_calls)) {
409
+ for (const [i, tc] of message.tool_calls.entries()) {
410
+ send({ ...base, choices: [{ index: 0, delta: { tool_calls: [{ index: i, ...tc }] }, finish_reason: null }] })
411
+ }
412
+ }
413
+ send({ ...base, choices: [{ index: 0, delta: {}, finish_reason: choice?.finish_reason ?? 'stop' }] })
414
+ if (payload.usage) send({ ...base, choices: [], usage: payload.usage })
415
+ res.write('data: [DONE]\n\n')
416
+ res.end()
417
+ }
418
+
419
+ // ── Anthropic /v1/messages(文本 + 基础工具转换)────────────────────────────
420
+
421
+ function anthropicToOpenAi(body) {
422
+ const messages = []
423
+ if (typeof body.system === 'string' && body.system !== '') {
424
+ messages.push({ role: 'system', content: body.system })
425
+ } else if (Array.isArray(body.system)) {
426
+ const text = body.system.filter(b => b?.type === 'text').map(b => b.text).join('\n')
427
+ if (text !== '') messages.push({ role: 'system', content: text })
428
+ }
429
+ for (const msg of Array.isArray(body.messages) ? body.messages : []) {
430
+ const role = msg.role === 'assistant' ? 'assistant' : 'user'
431
+ if (typeof msg.content === 'string') {
432
+ messages.push({ role, content: msg.content })
433
+ continue
434
+ }
435
+ const toolResults = []
436
+ const parts = []
437
+ for (const block of Array.isArray(msg.content) ? msg.content : []) {
438
+ if (block?.type === 'text') parts.push({ type: 'text', text: block.text ?? '' })
439
+ else if (block?.type === 'tool_result') {
440
+ toolResults.push(block)
441
+ } else if (block?.type === 'image') {
442
+ parts.push({ type: 'text', text: '[image omitted: upstream conversion does not carry images]' })
443
+ }
444
+ }
445
+ if (toolResults.length > 0) {
446
+ // tool_result 作为 user 消息里的 tool 响应
447
+ for (const tr of toolResults) {
448
+ const contentText = typeof tr.content === 'string'
449
+ ? tr.content
450
+ : Array.isArray(tr.content) ? tr.content.filter(b => b?.type === 'text').map(b => b.text).join('\n') : ''
451
+ messages.push({ role: 'user', content: `tool_use_id ${tr.tool_use_id} result: ${contentText}` })
452
+ }
453
+ }
454
+ if (parts.length > 0) {
455
+ messages.push({ role, content: parts.map(p => p.text).join('\n') })
456
+ }
457
+ if (role === 'assistant' && Array.isArray(msg.content)) {
458
+ const toolUses = msg.content.filter(b => b?.type === 'tool_use')
459
+ if (toolUses.length > 0) {
460
+ // assistant 的 tool_use 以文本形式提示上游(简单透传转换)
461
+ const desc = toolUses.map(t => `[calls tool ${t.name} with ${JSON.stringify(t.input ?? {})}]`).join('\n')
462
+ messages.push({ role: 'assistant', content: desc })
463
+ }
464
+ }
465
+ }
466
+ const out = { model: body.model, messages, max_tokens: body.max_tokens ?? 4096, stream: false }
467
+ if (Array.isArray(body.tools) && body.tools.length > 0) {
468
+ out.tools = body.tools.map(t => ({
469
+ type: 'function',
470
+ function: { name: t.name, description: t.description ?? '', parameters: t.input_schema ?? { type: 'object' } },
471
+ }))
472
+ }
473
+ if (Array.isArray(body.stop_sequences) && body.stop_sequences.length > 0) out.stop = body.stop_sequences
474
+ return out
475
+ }
476
+
477
+ function openAiToAnthropic(payload, requestId, model) {
478
+ const choice = payload?.choices?.[0]
479
+ const text = choice?.message?.content ?? ''
480
+ const content = []
481
+ if (typeof text === 'string' && text !== '') content.push({ type: 'text', text })
482
+ let stopReason = choice?.finish_reason === 'length' ? 'max_tokens' : choice?.finish_reason === 'tool_calls' ? 'tool_use' : 'end_turn'
483
+ return {
484
+ id: requestId,
485
+ type: 'message',
486
+ role: 'assistant',
487
+ model,
488
+ content,
489
+ stop_reason: stopReason,
490
+ stop_sequence: null,
491
+ usage: {
492
+ input_tokens: payload?.usage?.prompt_tokens ?? 0,
493
+ output_tokens: payload?.usage?.completion_tokens ?? 0,
494
+ },
495
+ }
496
+ }
497
+
498
+ async function serveAnthropicMessages(req, res, settings, log) {
499
+ let body
500
+ try {
501
+ body = await readJsonBody(req)
502
+ } catch (error) {
503
+ json(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: `invalid JSON body: ${error.message}` } })
504
+ return
505
+ }
506
+ const modelId = typeof body.model === 'string' ? body.model.trim() : ''
507
+ if (modelId === '') {
508
+ json(res, 400, { type: 'error', error: { type: 'invalid_request_error', message: 'model is required' } })
509
+ return
510
+ }
511
+ const resolved = await resolveModel(modelId)
512
+ if (!resolved) {
513
+ json(res, 404, { type: 'error', error: { type: 'not_found_error', message: `unknown model: ${modelId}` } })
514
+ return
515
+ }
516
+
517
+ const abortController = new AbortController()
518
+ req.on('close', () => abortController.abort())
519
+ const openaiBody = anthropicToOpenAi(body)
520
+ delete openaiBody.model // completeOn* 会注入上游模型名
521
+ const startedAt = Date.now()
522
+ const source = requestSource(req)
523
+ const sessionKey = sessionKeyFromRequest(req)
524
+ const trace = { model: modelId, tried: [], sticky: null }
525
+
526
+ try {
527
+ let payload
528
+ if (resolved.group) {
529
+ const result = await completeOnGroup(resolved.entry, openaiBody, {
530
+ signal: abortController.signal,
531
+ timeouts: gatewayTimeouts(settings),
532
+ sessionKey,
533
+ })
534
+ payload = result.result.json ?? result.result
535
+ trace.tried = result.tried
536
+ if (result.sticky) trace.sticky = result.sticky
537
+ } else {
538
+ const result = await completeOnModel(resolved, openaiBody, { signal: abortController.signal, timeouts: gatewayTimeouts(settings) })
539
+ payload = result.json ?? result
540
+ trace.tried = [{ id: resolved.id, ok: true }]
541
+ }
542
+ const payloadObj = payload?.choices ? payload : null
543
+ if (!payloadObj) throw { kind: 'server', retryable: true, cooldownMs: 0, message: '上游响应缺少 choices' }
544
+ recordRequest({ model: modelId, outcome: 'success', source, durationMs: Date.now() - startedAt, tried: trace.tried, usage: payloadObj?.usage ?? null, sticky: trace.sticky })
545
+ const requestId = `msg_omr_${Date.now().toString(36)}`
546
+ const response = openAiToAnthropic(payloadObj, requestId, modelId)
547
+ if (body.stream === true) {
548
+ res.writeHead(200, { 'content-type': 'text/event-stream; charset=utf-8', 'cache-control': 'no-cache', ...corsHeaders() })
549
+ const send = (event, data) => res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`)
550
+ send('message_start', { type: 'message_start', message: { ...response, content: [] } })
551
+ for (const block of response.content) {
552
+ send('content_block_start', { type: 'content_block_start', index: 0, content_block: { type: 'text', text: '' } })
553
+ send('content_block_delta', { type: 'content_block_delta', index: 0, delta: { type: 'text_delta', text: block.text } })
554
+ send('content_block_stop', { type: 'content_block_stop', index: 0 })
555
+ }
556
+ send('message_delta', { type: 'message_delta', delta: { stop_reason: response.stop_reason, stop_sequence: null }, usage: { output_tokens: response.usage.output_tokens } })
557
+ send('message_stop', { type: 'message_stop' })
558
+ res.end()
559
+ } else {
560
+ json(res, 200, response)
561
+ }
562
+ } catch (error) {
563
+ if (Array.isArray(error?.tried)) trace.tried = error.tried
564
+ if (abortController.signal.aborted) {
565
+ recordRequest({ model: modelId, outcome: 'aborted', source, durationMs: Date.now() - startedAt, tried: trace.tried })
566
+ // 客户端主动断开:正常结束而非 res.destroy(),避免上游网关把半开连接渲染成超时/500。
567
+ if (!res.headersSent) json(res, 499, { type: 'error', error: { type: 'client_aborted', message: 'client disconnected' } })
568
+ return
569
+ }
570
+ recordRequest({ model: modelId, outcome: 'failed', source, durationMs: Date.now() - startedAt, tried: trace.tried })
571
+ log(`anthropic completion failed for ${modelId}: ${errorText(error)}`)
572
+ if (!res.headersSent) {
573
+ json(res, 502, { type: 'error', error: { type: 'upstream_error', message: `所有候选均失败 —— ${errorText(error)}` } })
574
+ } else {
575
+ res.end()
576
+ }
577
+ }
578
+ }
579
+
580
+ // ── 启动 ────────────────────────────────────────────────────────────────────
581
+
582
+ export async function startGateway({ log = () => {}, port, host } = {}) {
583
+ const settings = loadSettings()
584
+ const gw = settings.gateway ?? {}
585
+ const server = createGatewayServer({ log })
586
+ return new Promise((resolve, reject) => {
587
+ server.once('error', reject)
588
+ const listenPort = Number.isFinite(Number(port)) && port > 0 ? Number(port) : Number.isFinite(Number(gw.port)) ? Number(gw.port) : 18682
589
+ const listenHost = typeof host === 'string' && host !== '' ? host : typeof gw.host === 'string' && gw.host !== '' ? gw.host : '127.0.0.1'
590
+ server.listen(listenPort, listenHost, () => {
591
+ server.off('error', reject)
592
+ log(`gateway listening on http://${listenHost}:${listenPort}/v1 (key: ${gw.apiKey ? gw.apiKey.slice(0, 8) + '…' : '无'})`)
593
+ resolve({ server, port: listenPort, host: listenHost })
594
+ })
595
+ })
596
+ }