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.
Files changed (80) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +32 -5
  3. package/bin/omr.js +46 -0
  4. package/package.json +3 -2
  5. package/src/admin.js +965 -941
  6. package/src/balances.js +61 -61
  7. package/src/boot.js +117 -117
  8. package/src/channels/buddy.js +2031 -2031
  9. package/src/channels/cline.js +753 -753
  10. package/src/channels/codearts.js +2051 -2051
  11. package/src/channels/comate.js +830 -830
  12. package/src/channels/doubaowork.js +1784 -1784
  13. package/src/channels/freebuff.js +1316 -1316
  14. package/src/channels/gemini.js +1721 -1721
  15. package/src/channels/index.js +270 -270
  16. package/src/channels/joycode.js +936 -936
  17. package/src/channels/kimi.js +572 -572
  18. package/src/channels/lobsterai.js +1226 -1226
  19. package/src/channels/loomy.js +1032 -1032
  20. package/src/channels/miaoshou.js +1396 -1396
  21. package/src/channels/mimo.js +474 -474
  22. package/src/channels/minimax.js +1451 -1451
  23. package/src/channels/qoder-wasm.js +434 -434
  24. package/src/channels/qoder.js +1619 -1619
  25. package/src/channels/raccoon.js +1842 -1842
  26. package/src/channels/tabbit.js +1457 -1457
  27. package/src/channels/trae.js +1405 -1405
  28. package/src/channels/zcode-global.js +35 -35
  29. package/src/channels/zcode.js +2085 -2085
  30. package/src/checkin.js +496 -496
  31. package/src/credits.js +464 -464
  32. package/src/crypto.js +132 -132
  33. package/src/free-models.js +683 -683
  34. package/src/gateway.js +596 -578
  35. package/src/health.js +86 -86
  36. package/src/model-key.js +35 -35
  37. package/src/paths.js +96 -96
  38. package/src/probe.js +318 -318
  39. package/src/providers/builtin.js +626 -626
  40. package/src/providers/index.js +483 -457
  41. package/src/providers/kilo.js +111 -111
  42. package/src/providers/last-good.js +69 -69
  43. package/src/providers/modelsdev.js +242 -242
  44. package/src/providers/openai-compat.js +312 -312
  45. package/src/providers/opencode/bun-fetch.js +226 -226
  46. package/src/providers/opencode/lane.js +186 -186
  47. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  48. package/src/providers/opencode/o2a/asset-source.js +43 -43
  49. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  50. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  51. package/src/providers/opencode/o2a/entry.js +17 -17
  52. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  53. package/src/providers/opencode/o2a/headers.js +133 -133
  54. package/src/providers/opencode/o2a/identity.js +148 -148
  55. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  56. package/src/providers/opencode/o2a/official-tools.js +110 -110
  57. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  58. package/src/providers/opencode/o2a/toolshape.js +418 -418
  59. package/src/providers/opencode/o2a/version.js +37 -37
  60. package/src/providers/opencode/upstream.js +403 -403
  61. package/src/providers/opencode/wire.js +496 -496
  62. package/src/providers/opencode.js +652 -652
  63. package/src/router.js +629 -629
  64. package/src/server.js +49 -33
  65. package/src/store.js +467 -467
  66. package/src/sync/index.js +1529 -1529
  67. package/src/sync/login-preload.cjs +52 -52
  68. package/src/sync/noise.js +141 -141
  69. package/src/sync/relay-http.js +176 -176
  70. package/src/sync/remote-host.js +818 -818
  71. package/src/sync/remote-http.js +112 -112
  72. package/src/sync/remote-login.js +657 -657
  73. package/src/sync/remote-pairing.js +204 -204
  74. package/src/sync/remote-protocol.js +321 -321
  75. package/src/sync/snapshot.js +211 -211
  76. package/src/update.js +458 -0
  77. package/src/util.js +334 -334
  78. package/web/app.js +4010 -3972
  79. package/web/index.html +32 -32
  80. package/web/style.css +971 -971
package/src/util.js CHANGED
@@ -1,334 +1,334 @@
1
- /**
2
- * 通用工具:HTTP 请求、SSE 解析、JSON 响应、ID 生成。
3
- * 零依赖,全部基于 node 内置模块。
4
- */
5
-
6
- import { randomBytes } from 'node:crypto'
7
-
8
- /** 生成短 ID(前缀-8位hex)。 */
9
- export function shortId(prefix = '') {
10
- const id = randomBytes(5).toString('hex')
11
- return prefix ? `${prefix}-${id}` : id
12
- }
13
-
14
- /** 生成随机 API key。 */
15
- export function generateApiKey() {
16
- return `omr-${randomBytes(24).toString('base64url')}`
17
- }
18
-
19
- /** slug 化:'My 组 A' -> 'my-a' */
20
- export function slugify(name) {
21
- return String(name ?? '')
22
- .trim()
23
- .toLowerCase()
24
- .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
25
- .replace(/^-+|-+$/g, '')
26
- .slice(0, 48)
27
- }
28
-
29
- /** 带超时 + 可选代理透传的 fetch 封装。 */
30
- export async function httpFetch(url, init = {}, timeoutMs = 30000) {
31
- const controller = new AbortController()
32
- const timer = setTimeout(() => controller.abort(new Error(`timeout after ${timeoutMs}ms`)), timeoutMs)
33
- const onCallerAbort = () => controller.abort()
34
- init.signal?.addEventListener('abort', onCallerAbort, { once: true })
35
- try {
36
- return await fetch(url, { ...init, signal: controller.signal })
37
- } catch (error) {
38
- // 把 undici 笼统的 "fetch failed" 展开成可诊断的原因(连接超时 / DNS / 拒绝连接)
39
- const code = error?.cause?.code ?? error.code
40
- const rawMessage = String(error?.cause?.message ?? error?.message ?? error)
41
- if (error?.message === 'fetch failed' || code === 'ENOTFOUND' || code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ETIMEDOUT' || code === 'UND_ERR_CONNECT_TIMEOUT') {
42
- let host = ''
43
- try { host = new URL(url).hostname } catch { /* url 非法时忽略 */ }
44
- throw new Error(`无法连接${host ? ` ${host}` : ''}:${rawMessage}${code ? `(${code})` : ''};请检查网络连接/代理,或该域名是否在当前网络不可达`)
45
- }
46
- throw error
47
- } finally {
48
- clearTimeout(timer)
49
- init.signal?.removeEventListener?.('abort', onCallerAbort)
50
- }
51
- }
52
-
53
- /** 读完整响应体为文本(带超时 + 可选 abort 唤醒)。
54
- * 挂起的 reader.read() 不会被 abort 信号唤醒,必须主动 cancel,否则上游
55
- * 建连后不吐数据时这里会永久阻塞(超时形同虚设)。 */
56
- export async function readBodyText(response, timeoutMs = 30000, signal) {
57
- if (!response.body) return ''
58
- const reader = response.body.getReader()
59
- const decoder = new TextDecoder()
60
- let text = ''
61
- const deadline = Date.now() + timeoutMs
62
- const onAbort = () => { reader.cancel().catch(() => {}) }
63
- signal?.addEventListener?.('abort', onAbort, { once: true })
64
- if (signal?.aborted) onAbort()
65
- try {
66
- while (true) {
67
- const remain = deadline - Date.now()
68
- if (remain <= 0) throw new Error('read body timeout')
69
- const { done, value } = await reader.read()
70
- if (done) break
71
- if (value !== undefined) text += decoder.decode(value, { stream: true })
72
- }
73
- } finally {
74
- signal?.removeEventListener?.('abort', onAbort)
75
- reader.cancel().catch(() => {})
76
- }
77
- return text + decoder.decode()
78
- }
79
-
80
- /**
81
- * 从流式响应里逐帧读 SSE `data:` 负载。
82
- * 跳过注释行(如 Kilo 的 `: KILO PROCESSING`);`[DONE]` 以 {done:true} 上报。
83
- * abort 时主动 cancel reader:挂起的 read() 不会被信号唤醒,否则挂死上游会一直占着候选。
84
- *
85
- * idleTimeoutMs:空闲看门狗(毫秒,每收到一块数据即续期,0 = 关闭)。
86
- * 上游建连后长时间不吐任何字节(半开连接 / 服务端挂死)时主动断开,
87
- * 否则挂起的 read() 只能等 TCP 超时(可能数分钟),期间客户端干等且无法故障切换。
88
- * 超时后抛 { kind: 'timeout', ... },由上层按失败候选处理。
89
- */
90
- export async function readSseData(body, onData, signal, { idleTimeoutMs = 0 } = {}) {
91
- const reader = body.getReader()
92
- const decoder = new TextDecoder()
93
- let buffer = ''
94
- const onAbort = () => { reader.cancel().catch(() => {}) }
95
- signal?.addEventListener?.('abort', onAbort, { once: true })
96
- if (signal?.aborted) onAbort()
97
- let idleTimer = null
98
- let idleFired = false
99
- // cancel 会唤醒挂起的 read()(以 {done:true} 结束),随后在收尾处按空闲超时抛错。
100
- const armIdle = () => {
101
- if (!(idleTimeoutMs > 0)) return
102
- if (idleTimer) clearTimeout(idleTimer)
103
- idleTimer = setTimeout(() => {
104
- idleFired = true
105
- reader.cancel().catch(() => {})
106
- }, idleTimeoutMs)
107
- idleTimer.unref?.()
108
- }
109
- const disarmIdle = () => { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null } }
110
- armIdle()
111
- try {
112
- while (true) {
113
- if (signal?.aborted) throw new DOMException('aborted', 'AbortError')
114
- const { done, value } = await reader.read()
115
- if (done) break
116
- armIdle()
117
- buffer += decoder.decode(value, { stream: true })
118
- let sep
119
- while ((sep = buffer.indexOf('\n')) !== -1) {
120
- const line = buffer.slice(0, sep).replace(/\r$/, '')
121
- buffer = buffer.slice(sep + 1)
122
- if (line.startsWith(':')) continue
123
- if (!line.startsWith('data:')) continue
124
- const payload = line.slice(5).trim()
125
- if (payload === '') continue
126
- if (payload === '[DONE]') return { done: true }
127
- onData(payload)
128
- }
129
- }
130
- if (signal?.aborted) throw new DOMException('aborted', 'AbortError')
131
- if (idleFired) {
132
- throw {
133
- kind: 'timeout',
134
- retryable: true,
135
- cooldownMs: 30_000,
136
- message: `上游流式响应空闲超时(${idleTimeoutMs >= 1000 ? `${Math.round(idleTimeoutMs / 1000)}s` : `${idleTimeoutMs}ms`} 内未收到任何数据帧)`,
137
- }
138
- }
139
- } finally {
140
- disarmIdle()
141
- signal?.removeEventListener?.('abort', onAbort)
142
- reader.cancel().catch(() => {})
143
- }
144
- return { done: false }
145
- }
146
-
147
- /** 把一组 OpenAI 风格 SSE chunk 文本帧合并成一个完整响应对象(非流式回退用)。 */
148
- export function mergeSseChunks(chunks) {
149
- let result = null
150
- let usage = null
151
- for (const raw of chunks) {
152
- let chunk
153
- try { chunk = JSON.parse(raw) } catch { continue }
154
- if (chunk.usage) usage = chunk.usage
155
- if (!chunk.choices || chunk.choices.length === 0) continue
156
- const choice = chunk.choices[0]
157
- if (!result) {
158
- result = {
159
- id: chunk.id ?? '',
160
- object: 'chat.completion',
161
- created: chunk.created ?? Math.floor(Date.now() / 1000),
162
- model: chunk.model ?? '',
163
- choices: [{
164
- index: 0,
165
- message: { role: 'assistant', content: '' },
166
- finish_reason: null,
167
- }],
168
- }
169
- }
170
- const delta = choice.delta ?? {}
171
- if (typeof delta.content === 'string') result.choices[0].message.content += delta.content
172
- if (delta.reasoning_content != null) {
173
- result.choices[0].message.reasoning_content ??= ''
174
- result.choices[0].message.reasoning_content += delta.reasoning_content
175
- }
176
- if (Array.isArray(delta.tool_calls)) {
177
- const target = (result.choices[0].message.tool_calls ??= [])
178
- for (const tc of delta.tool_calls) {
179
- const at = target[tc.index ?? target.length]
180
- if (!at) target[tc.index ?? target.length] = { ...tc, function: { ...tc.function, arguments: tc.function?.arguments ?? '' } }
181
- else if (tc.function?.arguments) at.function.arguments += tc.function.arguments
182
- }
183
- }
184
- if (choice.finish_reason) result.choices[0].finish_reason = choice.finish_reason
185
- }
186
- // 循环结束后,将最后收集的 usage 赋值给 result(处理 usage 只在最后一帧出现的情况)
187
- if (usage && result) {
188
- result.usage = usage
189
- }
190
- return result
191
- }
192
-
193
- /** 把上游错误响应归类成 { kind, retryable, cooldownMs, message }。 */
194
- export function classifyFailure(status, bodyText) {
195
- const lower = String(bodyText ?? '').toLowerCase()
196
- const message = extractErrorMessage(bodyText) || `HTTP ${status}`
197
- // 额度/用量类错误优先于状态码判断(额度错误常带 401/403)
198
- if (/FreeUsageLimitError|GoUsageLimitError|usage.?limit|insufficient|quota|余额不足|额度/.test(bodyText ?? '')) {
199
- return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, message }
200
- }
201
- if (status === 429 || lower.includes('rate limit') || lower.includes('too many requests')) {
202
- return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, message }
203
- }
204
- // OpenRouter 对「管理/Provisioning Key」「过期 Key」一律返回误导性的 401 "User not found."
205
- // (Key 鉴权端点 /key 反而返回 200),这里补一句可操作提示,避免误判成账号问题。
206
- if (lower.includes('user not found')) {
207
- return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, message: `${message}(OpenRouter:请确认使用的是普通推理 Key;管理/Provisioning Key 与已过期 Key 都会报此错,到 openrouter.ai/settings/keys 重新签发即可)` }
208
- }
209
- if (status === 401 || status === 403) {
210
- return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, message }
211
- }
212
- if (status === 402) {
213
- return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, message }
214
- }
215
- if (status === 404) {
216
- return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, message }
217
- }
218
- if (status >= 500) {
219
- return { kind: 'server', retryable: true, cooldownMs: 30_000, message }
220
- }
221
- if (status === 0) {
222
- return { kind: 'transport', retryable: true, cooldownMs: 30_000, message }
223
- }
224
- return { kind: 'request', retryable: false, cooldownMs: 60_000, message }
225
- }
226
-
227
- /**
228
- * 把运行时抛出的原始异常(TypeError / DOMException / Error)归类成
229
- * { kind, retryable, cooldownMs, message },供故障切换、冷却与日志复用。
230
- *
231
- * 典型场景:流式响应读到一半上游关连接,undici 抛 `TypeError: terminated`
232
- * (cause = SocketError / UND_ERR_SOCKET)。不归类就会变成 kind 缺失、
233
- * 默认冷却、日志里只剩一句 `terminated` 的不可诊断失败。
234
- * 已经是归类结果的错误原样返回(幂等)。
235
- */
236
- export function classifyThrownError(error) {
237
- if (error && typeof error === 'object' && typeof error.kind === 'string') return error
238
- const code = String(error?.cause?.code ?? error?.code ?? '')
239
- const outer = typeof error?.message === 'string' ? error.message : ''
240
- const causeMessage = typeof error?.cause?.message === 'string' ? error.cause.message : ''
241
- const detail = [outer, causeMessage].filter((v, i, arr) => v !== '' && arr.indexOf(v) === i).join(' / ')
242
- const text = detail || 'unknown error'
243
- if (error?.name === 'AbortError' || /\b(aborted|abort)\b/i.test(text)) {
244
- return { kind: 'timeout', retryable: true, cooldownMs: 30_000, message: `上游请求被中止(超时或主动放弃):${text}` }
245
- }
246
- if (/terminated|other side closed|socket|ECONNRESET|ECONNREFUSED|EPIPE|ENOTFOUND|ETIMEDOUT|UND_ERR_|fetch failed|network/i.test(`${code} ${text}`)) {
247
- return {
248
- kind: 'transport',
249
- retryable: true,
250
- cooldownMs: 60_000,
251
- message: `上游连接中断:${text}${code ? `(${code})` : ''}`,
252
- }
253
- }
254
- return { kind: 'server', retryable: true, cooldownMs: 30_000, message: text }
255
- }
256
-
257
- /** 日志/错误展示用的可读文本:message 可能是对象,避免打印成 `[object Object]`。 */
258
- export function errorText(error) {
259
- const message = error?.message
260
- if (typeof message === 'string' && message !== '') return message
261
- if (typeof error === 'string' && error !== '') return error
262
- try {
263
- const text = JSON.stringify(error)
264
- return text && text !== '{}' ? text : String(error)
265
- } catch {
266
- return String(error)
267
- }
268
- }
269
-
270
- /** 从错误体里抽人可读消息。 */
271
- export function extractErrorMessage(bodyText) {
272
- const text = String(bodyText ?? '').trim()
273
- if (text === '') return ''
274
- // HTML 错误页(网关/CDN 5xx、路径写错等)没有可读信息,交给调用方回落到 HTTP 状态码
275
- if (text.startsWith('<')) return ''
276
- try {
277
- const data = JSON.parse(text)
278
- const parts = [data.message, data.error?.message ?? data.error, data.msg]
279
- const found = parts.filter(v => typeof v === 'string' && v.length > 0)
280
- if (found.length > 0) return found.join(' ').slice(0, 400)
281
- } catch { /* 非 JSON */ }
282
- return text.slice(0, 300)
283
- }
284
-
285
- /** 按秒解析 Retry-After 头。 */
286
- export function retryAfterMs(headers) {
287
- const raw = headers?.get?.('retry-after')
288
- const seconds = Number(raw)
289
- if (Number.isFinite(seconds) && seconds > 0) return Math.trunc(seconds * 1000)
290
- const date = raw ? Date.parse(raw) : NaN
291
- if (!Number.isNaN(date)) return Math.max(0, date - Date.now())
292
- return undefined
293
- }
294
-
295
- /** JSON 响应。 */
296
- export function json(res, status, payload) {
297
- const body = JSON.stringify(payload)
298
- res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) })
299
- res.end(body)
300
- }
301
-
302
- /** OpenAI 风格错误响应。 */
303
- export function openAiError(res, status, code, message) {
304
- json(res, status, { error: { message, type: code, code } })
305
- }
306
-
307
- /** UTC+8 日期字符串(YYYY-MM-DD)。 */
308
- export function utc8Date(nowMs = Date.now()) {
309
- return new Date(nowMs + 8 * 3600_000).toISOString().slice(0, 10)
310
- }
311
-
312
- /** UTC+8 当天的小时数。 */
313
- export function utc8Hour(nowMs = Date.now()) {
314
- return new Date(nowMs + 8 * 3600_000).getUTCHours()
315
- }
316
-
317
- /** UTC+8 时间戳(YYYY-MM-DD HH:mm:ss.SSS)。 */
318
- export function utc8Stamp(nowMs = Date.now()) {
319
- return new Date(nowMs + 8 * 3600_000).toISOString().slice(0, -1).replace('T', ' ')
320
- }
321
-
322
- /** 按 a.b.0.c 路径从对象取值;'0' 视为数组下标。 */
323
- export function getPath(obj, path) {
324
- if (path === '' || path == null) return obj
325
- return String(path).split('.').reduce((acc, key) => {
326
- if (acc == null) return undefined
327
- return acc[key]
328
- }, obj)
329
- }
330
-
331
- /** 把额度规整为两位小数(多包相加的浮点尾数噪声)。渠道模块可直接复用。 */
332
- export function roundCredits(value) {
333
- return Math.round(value * 100) / 100
334
- }
1
+ /**
2
+ * 通用工具:HTTP 请求、SSE 解析、JSON 响应、ID 生成。
3
+ * 零依赖,全部基于 node 内置模块。
4
+ */
5
+
6
+ import { randomBytes } from 'node:crypto'
7
+
8
+ /** 生成短 ID(前缀-8位hex)。 */
9
+ export function shortId(prefix = '') {
10
+ const id = randomBytes(5).toString('hex')
11
+ return prefix ? `${prefix}-${id}` : id
12
+ }
13
+
14
+ /** 生成随机 API key。 */
15
+ export function generateApiKey() {
16
+ return `omr-${randomBytes(24).toString('base64url')}`
17
+ }
18
+
19
+ /** slug 化:'My 组 A' -> 'my-a' */
20
+ export function slugify(name) {
21
+ return String(name ?? '')
22
+ .trim()
23
+ .toLowerCase()
24
+ .replace(/[^a-z0-9\u4e00-\u9fa5]+/g, '-')
25
+ .replace(/^-+|-+$/g, '')
26
+ .slice(0, 48)
27
+ }
28
+
29
+ /** 带超时 + 可选代理透传的 fetch 封装。 */
30
+ export async function httpFetch(url, init = {}, timeoutMs = 30000) {
31
+ const controller = new AbortController()
32
+ const timer = setTimeout(() => controller.abort(new Error(`timeout after ${timeoutMs}ms`)), timeoutMs)
33
+ const onCallerAbort = () => controller.abort()
34
+ init.signal?.addEventListener('abort', onCallerAbort, { once: true })
35
+ try {
36
+ return await fetch(url, { ...init, signal: controller.signal })
37
+ } catch (error) {
38
+ // 把 undici 笼统的 "fetch failed" 展开成可诊断的原因(连接超时 / DNS / 拒绝连接)
39
+ const code = error?.cause?.code ?? error.code
40
+ const rawMessage = String(error?.cause?.message ?? error?.message ?? error)
41
+ if (error?.message === 'fetch failed' || code === 'ENOTFOUND' || code === 'ECONNREFUSED' || code === 'ECONNRESET' || code === 'ETIMEDOUT' || code === 'UND_ERR_CONNECT_TIMEOUT') {
42
+ let host = ''
43
+ try { host = new URL(url).hostname } catch { /* url 非法时忽略 */ }
44
+ throw new Error(`无法连接${host ? ` ${host}` : ''}:${rawMessage}${code ? `(${code})` : ''};请检查网络连接/代理,或该域名是否在当前网络不可达`)
45
+ }
46
+ throw error
47
+ } finally {
48
+ clearTimeout(timer)
49
+ init.signal?.removeEventListener?.('abort', onCallerAbort)
50
+ }
51
+ }
52
+
53
+ /** 读完整响应体为文本(带超时 + 可选 abort 唤醒)。
54
+ * 挂起的 reader.read() 不会被 abort 信号唤醒,必须主动 cancel,否则上游
55
+ * 建连后不吐数据时这里会永久阻塞(超时形同虚设)。 */
56
+ export async function readBodyText(response, timeoutMs = 30000, signal) {
57
+ if (!response.body) return ''
58
+ const reader = response.body.getReader()
59
+ const decoder = new TextDecoder()
60
+ let text = ''
61
+ const deadline = Date.now() + timeoutMs
62
+ const onAbort = () => { reader.cancel().catch(() => {}) }
63
+ signal?.addEventListener?.('abort', onAbort, { once: true })
64
+ if (signal?.aborted) onAbort()
65
+ try {
66
+ while (true) {
67
+ const remain = deadline - Date.now()
68
+ if (remain <= 0) throw new Error('read body timeout')
69
+ const { done, value } = await reader.read()
70
+ if (done) break
71
+ if (value !== undefined) text += decoder.decode(value, { stream: true })
72
+ }
73
+ } finally {
74
+ signal?.removeEventListener?.('abort', onAbort)
75
+ reader.cancel().catch(() => {})
76
+ }
77
+ return text + decoder.decode()
78
+ }
79
+
80
+ /**
81
+ * 从流式响应里逐帧读 SSE `data:` 负载。
82
+ * 跳过注释行(如 Kilo 的 `: KILO PROCESSING`);`[DONE]` 以 {done:true} 上报。
83
+ * abort 时主动 cancel reader:挂起的 read() 不会被信号唤醒,否则挂死上游会一直占着候选。
84
+ *
85
+ * idleTimeoutMs:空闲看门狗(毫秒,每收到一块数据即续期,0 = 关闭)。
86
+ * 上游建连后长时间不吐任何字节(半开连接 / 服务端挂死)时主动断开,
87
+ * 否则挂起的 read() 只能等 TCP 超时(可能数分钟),期间客户端干等且无法故障切换。
88
+ * 超时后抛 { kind: 'timeout', ... },由上层按失败候选处理。
89
+ */
90
+ export async function readSseData(body, onData, signal, { idleTimeoutMs = 0 } = {}) {
91
+ const reader = body.getReader()
92
+ const decoder = new TextDecoder()
93
+ let buffer = ''
94
+ const onAbort = () => { reader.cancel().catch(() => {}) }
95
+ signal?.addEventListener?.('abort', onAbort, { once: true })
96
+ if (signal?.aborted) onAbort()
97
+ let idleTimer = null
98
+ let idleFired = false
99
+ // cancel 会唤醒挂起的 read()(以 {done:true} 结束),随后在收尾处按空闲超时抛错。
100
+ const armIdle = () => {
101
+ if (!(idleTimeoutMs > 0)) return
102
+ if (idleTimer) clearTimeout(idleTimer)
103
+ idleTimer = setTimeout(() => {
104
+ idleFired = true
105
+ reader.cancel().catch(() => {})
106
+ }, idleTimeoutMs)
107
+ idleTimer.unref?.()
108
+ }
109
+ const disarmIdle = () => { if (idleTimer) { clearTimeout(idleTimer); idleTimer = null } }
110
+ armIdle()
111
+ try {
112
+ while (true) {
113
+ if (signal?.aborted) throw new DOMException('aborted', 'AbortError')
114
+ const { done, value } = await reader.read()
115
+ if (done) break
116
+ armIdle()
117
+ buffer += decoder.decode(value, { stream: true })
118
+ let sep
119
+ while ((sep = buffer.indexOf('\n')) !== -1) {
120
+ const line = buffer.slice(0, sep).replace(/\r$/, '')
121
+ buffer = buffer.slice(sep + 1)
122
+ if (line.startsWith(':')) continue
123
+ if (!line.startsWith('data:')) continue
124
+ const payload = line.slice(5).trim()
125
+ if (payload === '') continue
126
+ if (payload === '[DONE]') return { done: true }
127
+ onData(payload)
128
+ }
129
+ }
130
+ if (signal?.aborted) throw new DOMException('aborted', 'AbortError')
131
+ if (idleFired) {
132
+ throw {
133
+ kind: 'timeout',
134
+ retryable: true,
135
+ cooldownMs: 30_000,
136
+ message: `上游流式响应空闲超时(${idleTimeoutMs >= 1000 ? `${Math.round(idleTimeoutMs / 1000)}s` : `${idleTimeoutMs}ms`} 内未收到任何数据帧)`,
137
+ }
138
+ }
139
+ } finally {
140
+ disarmIdle()
141
+ signal?.removeEventListener?.('abort', onAbort)
142
+ reader.cancel().catch(() => {})
143
+ }
144
+ return { done: false }
145
+ }
146
+
147
+ /** 把一组 OpenAI 风格 SSE chunk 文本帧合并成一个完整响应对象(非流式回退用)。 */
148
+ export function mergeSseChunks(chunks) {
149
+ let result = null
150
+ let usage = null
151
+ for (const raw of chunks) {
152
+ let chunk
153
+ try { chunk = JSON.parse(raw) } catch { continue }
154
+ if (chunk.usage) usage = chunk.usage
155
+ if (!chunk.choices || chunk.choices.length === 0) continue
156
+ const choice = chunk.choices[0]
157
+ if (!result) {
158
+ result = {
159
+ id: chunk.id ?? '',
160
+ object: 'chat.completion',
161
+ created: chunk.created ?? Math.floor(Date.now() / 1000),
162
+ model: chunk.model ?? '',
163
+ choices: [{
164
+ index: 0,
165
+ message: { role: 'assistant', content: '' },
166
+ finish_reason: null,
167
+ }],
168
+ }
169
+ }
170
+ const delta = choice.delta ?? {}
171
+ if (typeof delta.content === 'string') result.choices[0].message.content += delta.content
172
+ if (delta.reasoning_content != null) {
173
+ result.choices[0].message.reasoning_content ??= ''
174
+ result.choices[0].message.reasoning_content += delta.reasoning_content
175
+ }
176
+ if (Array.isArray(delta.tool_calls)) {
177
+ const target = (result.choices[0].message.tool_calls ??= [])
178
+ for (const tc of delta.tool_calls) {
179
+ const at = target[tc.index ?? target.length]
180
+ if (!at) target[tc.index ?? target.length] = { ...tc, function: { ...tc.function, arguments: tc.function?.arguments ?? '' } }
181
+ else if (tc.function?.arguments) at.function.arguments += tc.function.arguments
182
+ }
183
+ }
184
+ if (choice.finish_reason) result.choices[0].finish_reason = choice.finish_reason
185
+ }
186
+ // 循环结束后,将最后收集的 usage 赋值给 result(处理 usage 只在最后一帧出现的情况)
187
+ if (usage && result) {
188
+ result.usage = usage
189
+ }
190
+ return result
191
+ }
192
+
193
+ /** 把上游错误响应归类成 { kind, retryable, cooldownMs, message }。 */
194
+ export function classifyFailure(status, bodyText) {
195
+ const lower = String(bodyText ?? '').toLowerCase()
196
+ const message = extractErrorMessage(bodyText) || `HTTP ${status}`
197
+ // 额度/用量类错误优先于状态码判断(额度错误常带 401/403)
198
+ if (/FreeUsageLimitError|GoUsageLimitError|usage.?limit|insufficient|quota|余额不足|额度/.test(bodyText ?? '')) {
199
+ return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, message }
200
+ }
201
+ if (status === 429 || lower.includes('rate limit') || lower.includes('too many requests')) {
202
+ return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, message }
203
+ }
204
+ // OpenRouter 对「管理/Provisioning Key」「过期 Key」一律返回误导性的 401 "User not found."
205
+ // (Key 鉴权端点 /key 反而返回 200),这里补一句可操作提示,避免误判成账号问题。
206
+ if (lower.includes('user not found')) {
207
+ return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, message: `${message}(OpenRouter:请确认使用的是普通推理 Key;管理/Provisioning Key 与已过期 Key 都会报此错,到 openrouter.ai/settings/keys 重新签发即可)` }
208
+ }
209
+ if (status === 401 || status === 403) {
210
+ return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, message }
211
+ }
212
+ if (status === 402) {
213
+ return { kind: 'quota', retryable: false, cooldownMs: 10 * 60_000, message }
214
+ }
215
+ if (status === 404) {
216
+ return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, message }
217
+ }
218
+ if (status >= 500) {
219
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, message }
220
+ }
221
+ if (status === 0) {
222
+ return { kind: 'transport', retryable: true, cooldownMs: 30_000, message }
223
+ }
224
+ return { kind: 'request', retryable: false, cooldownMs: 60_000, message }
225
+ }
226
+
227
+ /**
228
+ * 把运行时抛出的原始异常(TypeError / DOMException / Error)归类成
229
+ * { kind, retryable, cooldownMs, message },供故障切换、冷却与日志复用。
230
+ *
231
+ * 典型场景:流式响应读到一半上游关连接,undici 抛 `TypeError: terminated`
232
+ * (cause = SocketError / UND_ERR_SOCKET)。不归类就会变成 kind 缺失、
233
+ * 默认冷却、日志里只剩一句 `terminated` 的不可诊断失败。
234
+ * 已经是归类结果的错误原样返回(幂等)。
235
+ */
236
+ export function classifyThrownError(error) {
237
+ if (error && typeof error === 'object' && typeof error.kind === 'string') return error
238
+ const code = String(error?.cause?.code ?? error?.code ?? '')
239
+ const outer = typeof error?.message === 'string' ? error.message : ''
240
+ const causeMessage = typeof error?.cause?.message === 'string' ? error.cause.message : ''
241
+ const detail = [outer, causeMessage].filter((v, i, arr) => v !== '' && arr.indexOf(v) === i).join(' / ')
242
+ const text = detail || 'unknown error'
243
+ if (error?.name === 'AbortError' || /\b(aborted|abort)\b/i.test(text)) {
244
+ return { kind: 'timeout', retryable: true, cooldownMs: 30_000, message: `上游请求被中止(超时或主动放弃):${text}` }
245
+ }
246
+ if (/terminated|other side closed|socket|ECONNRESET|ECONNREFUSED|EPIPE|ENOTFOUND|ETIMEDOUT|UND_ERR_|fetch failed|network/i.test(`${code} ${text}`)) {
247
+ return {
248
+ kind: 'transport',
249
+ retryable: true,
250
+ cooldownMs: 60_000,
251
+ message: `上游连接中断:${text}${code ? `(${code})` : ''}`,
252
+ }
253
+ }
254
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, message: text }
255
+ }
256
+
257
+ /** 日志/错误展示用的可读文本:message 可能是对象,避免打印成 `[object Object]`。 */
258
+ export function errorText(error) {
259
+ const message = error?.message
260
+ if (typeof message === 'string' && message !== '') return message
261
+ if (typeof error === 'string' && error !== '') return error
262
+ try {
263
+ const text = JSON.stringify(error)
264
+ return text && text !== '{}' ? text : String(error)
265
+ } catch {
266
+ return String(error)
267
+ }
268
+ }
269
+
270
+ /** 从错误体里抽人可读消息。 */
271
+ export function extractErrorMessage(bodyText) {
272
+ const text = String(bodyText ?? '').trim()
273
+ if (text === '') return ''
274
+ // HTML 错误页(网关/CDN 5xx、路径写错等)没有可读信息,交给调用方回落到 HTTP 状态码
275
+ if (text.startsWith('<')) return ''
276
+ try {
277
+ const data = JSON.parse(text)
278
+ const parts = [data.message, data.error?.message ?? data.error, data.msg]
279
+ const found = parts.filter(v => typeof v === 'string' && v.length > 0)
280
+ if (found.length > 0) return found.join(' ').slice(0, 400)
281
+ } catch { /* 非 JSON */ }
282
+ return text.slice(0, 300)
283
+ }
284
+
285
+ /** 按秒解析 Retry-After 头。 */
286
+ export function retryAfterMs(headers) {
287
+ const raw = headers?.get?.('retry-after')
288
+ const seconds = Number(raw)
289
+ if (Number.isFinite(seconds) && seconds > 0) return Math.trunc(seconds * 1000)
290
+ const date = raw ? Date.parse(raw) : NaN
291
+ if (!Number.isNaN(date)) return Math.max(0, date - Date.now())
292
+ return undefined
293
+ }
294
+
295
+ /** JSON 响应。 */
296
+ export function json(res, status, payload) {
297
+ const body = JSON.stringify(payload)
298
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'content-length': Buffer.byteLength(body) })
299
+ res.end(body)
300
+ }
301
+
302
+ /** OpenAI 风格错误响应。 */
303
+ export function openAiError(res, status, code, message) {
304
+ json(res, status, { error: { message, type: code, code } })
305
+ }
306
+
307
+ /** UTC+8 日期字符串(YYYY-MM-DD)。 */
308
+ export function utc8Date(nowMs = Date.now()) {
309
+ return new Date(nowMs + 8 * 3600_000).toISOString().slice(0, 10)
310
+ }
311
+
312
+ /** UTC+8 当天的小时数。 */
313
+ export function utc8Hour(nowMs = Date.now()) {
314
+ return new Date(nowMs + 8 * 3600_000).getUTCHours()
315
+ }
316
+
317
+ /** UTC+8 时间戳(YYYY-MM-DD HH:mm:ss.SSS)。 */
318
+ export function utc8Stamp(nowMs = Date.now()) {
319
+ return new Date(nowMs + 8 * 3600_000).toISOString().slice(0, -1).replace('T', ' ')
320
+ }
321
+
322
+ /** 按 a.b.0.c 路径从对象取值;'0' 视为数组下标。 */
323
+ export function getPath(obj, path) {
324
+ if (path === '' || path == null) return obj
325
+ return String(path).split('.').reduce((acc, key) => {
326
+ if (acc == null) return undefined
327
+ return acc[key]
328
+ }, obj)
329
+ }
330
+
331
+ /** 把额度规整为两位小数(多包相加的浮点尾数噪声)。渠道模块可直接复用。 */
332
+ export function roundCredits(value) {
333
+ return Math.round(value * 100) / 100
334
+ }