one-model-router 0.0.10 → 0.0.12
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/LICENSE +21 -21
- package/README.md +32 -5
- package/bin/omr.js +46 -0
- package/package.json +3 -2
- package/src/admin.js +965 -941
- package/src/balances.js +61 -61
- package/src/boot.js +117 -117
- package/src/channels/buddy.js +2031 -2031
- package/src/channels/cline.js +753 -753
- package/src/channels/codearts.js +2051 -2051
- package/src/channels/comate.js +830 -830
- package/src/channels/doubaowork.js +1784 -1784
- package/src/channels/freebuff.js +1316 -1316
- package/src/channels/gemini.js +1721 -1721
- package/src/channels/index.js +270 -270
- package/src/channels/joycode.js +936 -936
- package/src/channels/kimi.js +572 -572
- package/src/channels/lobsterai.js +1226 -1226
- package/src/channels/loomy.js +1032 -1032
- package/src/channels/miaoshou.js +1396 -1396
- package/src/channels/mimo.js +474 -474
- package/src/channels/minimax.js +1451 -1451
- package/src/channels/qoder-wasm.js +434 -434
- package/src/channels/qoder.js +1619 -1619
- package/src/channels/raccoon.js +1842 -1842
- package/src/channels/tabbit.js +1457 -1457
- package/src/channels/trae.js +1405 -1405
- package/src/channels/zcode-global.js +35 -35
- package/src/channels/zcode.js +2085 -2085
- package/src/checkin.js +496 -496
- package/src/credits.js +464 -464
- package/src/crypto.js +132 -132
- package/src/free-models.js +683 -683
- package/src/gateway.js +596 -578
- package/src/health.js +86 -86
- package/src/model-key.js +35 -35
- package/src/paths.js +96 -96
- package/src/probe.js +318 -318
- package/src/providers/builtin.js +626 -626
- package/src/providers/index.js +483 -457
- package/src/providers/kilo.js +111 -111
- package/src/providers/last-good.js +69 -69
- package/src/providers/modelsdev.js +242 -242
- package/src/providers/openai-compat.js +312 -312
- package/src/providers/opencode/bun-fetch.js +226 -226
- package/src/providers/opencode/lane.js +186 -186
- package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
- package/src/providers/opencode/o2a/asset-source.js +43 -43
- package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
- package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
- package/src/providers/opencode/o2a/entry.js +17 -17
- package/src/providers/opencode/o2a/gateway-body.js +42 -42
- package/src/providers/opencode/o2a/headers.js +133 -133
- package/src/providers/opencode/o2a/identity.js +148 -148
- package/src/providers/opencode/o2a/official-prompt.js +191 -191
- package/src/providers/opencode/o2a/official-tools.js +110 -110
- package/src/providers/opencode/o2a/tool-renames.js +217 -217
- package/src/providers/opencode/o2a/toolshape.js +418 -418
- package/src/providers/opencode/o2a/version.js +37 -37
- package/src/providers/opencode/upstream.js +403 -403
- package/src/providers/opencode/wire.js +496 -496
- package/src/providers/opencode.js +652 -652
- package/src/router.js +629 -629
- package/src/server.js +49 -33
- package/src/store.js +467 -467
- package/src/sync/index.js +1529 -1529
- package/src/sync/login-preload.cjs +52 -52
- package/src/sync/noise.js +141 -141
- package/src/sync/relay-http.js +176 -176
- package/src/sync/remote-host.js +818 -818
- package/src/sync/remote-http.js +112 -112
- package/src/sync/remote-login.js +657 -657
- package/src/sync/remote-pairing.js +204 -204
- package/src/sync/remote-protocol.js +321 -321
- package/src/sync/snapshot.js +211 -211
- package/src/update.js +458 -0
- package/src/util.js +334 -334
- package/web/app.js +4010 -3972
- package/web/index.html +32 -32
- 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
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
const
|
|
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
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
if (
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
if (
|
|
406
|
-
|
|
407
|
-
}
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
if (
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
if (
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
const
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
}
|
|
542
|
-
|
|
543
|
-
}
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
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
|
+
}
|