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/router.js CHANGED
@@ -1,629 +1,629 @@
1
- /**
2
- * 模型组路由:一个 omr/<slug> 虚拟模型 = 有序候选链。
3
- *
4
- * 两种策略:
5
- * fallback 每轮都从链头开始,第一个产出结果的候选胜出(质量阶梯)。
6
- * 支持会话粘性(sticky):带 sessionKey 的请求会尽量锁定同一候选,
7
- * 只有被锁候选不可用(冷却/dead)才故障切换并更新绑定。
8
- * round-robin 从下一个候选开始(stickyLimit 轮内保持粘性,兼顾 prompt 缓存),
9
- * 均衡分摊负载。游标在内存,重启丢失只是换起点。
10
- * 不启用会话粘性(避免与轮转语义冲突)。
11
- *
12
- * 故障切换:冷却中的候选跳过(全冷却时仍按序尝试,不给用户 503 优先);
13
- * 失败按 classifyFailure 冷却并换下一个候选;全链失败才向客户端报错。
14
- *
15
- * 低延迟调度(2026-10 优化):
16
- * 1) 内容直通:客户端要流式时,胜出候选的 chunk 边生成边下发,不再等整轮聚合;
17
- * 2) 对冲并发:当前候选 hedgeDelayMs 内没吐字,就并行启动下一个;谁先出内容谁胜出,
18
- * 其余 abort —— 挂死的免费候选不再让用户干等满 headerTimeout;
19
- * 3) 空响应换候选:候选返回「无正文 / 无工具调用」的空响应(客户端侧的
20
- * Empty response data)按失败处理,继续走下一个候选。
21
- */
22
-
23
- import { completeOnModel, resolveModel, buildCatalog } from './providers/index.js'
24
- import { probeSnapshot } from './probe.js'
25
- import * as health from './health.js'
26
- import { utc8Date, shortId, classifyThrownError } from './util.js'
27
-
28
- /** 组轮换游标:groupId -> { index, used }。 */
29
- const rotation = new Map()
30
-
31
- /** 会话粘性绑定:groupId -> Map<sessionKey, { modelId, boundAt, lastOkAt }>。 */
32
- const sessionSticky = new Map()
33
- /** 粘性 TTL(毫秒):超过后该会话的绑定失效,重新选择。 */
34
- const SESSION_STICKY_TTL_MS = 30 * 60_000
35
-
36
- /** 清理已消失的组与过期的粘性会话(惰性,在每次写入后调用)。 */
37
- function pruneSessions(liveGroupIds, nowMs = Date.now()) {
38
- const live = new Set(liveGroupIds)
39
- for (const key of sessionSticky.keys()) {
40
- if (!live.has(key)) sessionSticky.delete(key)
41
- else {
42
- const map = sessionSticky.get(key)
43
- for (const [sid, e] of map) if (nowMs - e.lastOkAt > SESSION_STICKY_TTL_MS) map.delete(sid)
44
- if (map.size === 0) sessionSticky.delete(key)
45
- }
46
- }
47
- }
48
-
49
- /**
50
- * 写入或刷新粘性绑定。返回值:当前会话的有序候选链。
51
- * - 已有绑定且该候选在 fresh 中 → 提到链头
52
- * - 已有绑定但候选冷却/dead → 重选 fresh[0],并更新绑定
53
- * - 无绑定 → 取 fresh[0],建立绑定
54
- */
55
- function applySessionSticky(groupId, sessionKey, candidates, fresh, cooling, nowMs, demoted = null) {
56
- if (typeof sessionKey !== 'string' || sessionKey === '') return candidates
57
- let map = sessionSticky.get(groupId)
58
- if (!map) { map = new Map(); sessionSticky.set(groupId, map) }
59
- pruneSessions([groupId], nowMs)
60
-
61
- const bound = map.get(sessionKey)
62
- let chosen = null
63
- if (bound) {
64
- // 绑定仍可用:把 bound 提到链头(证据变差则重选:冷却 / 探测判死)
65
- const inFresh = fresh.find(r => r.id === bound.modelId)
66
- const inCooling = cooling.find(r => r.id === bound.modelId)
67
- const stale = demoted?.has(bound.modelId) === true
68
- if (inFresh && !stale) {
69
- chosen = inFresh
70
- map.set(sessionKey, { ...bound, lastOkAt: nowMs })
71
- } else if (inCooling || stale) {
72
- // 冷却/判死的绑定 → 重选,等模型恢复后再切回
73
- chosen = fresh[0] ?? null
74
- if (chosen) map.set(sessionKey, { modelId: chosen.id, boundAt: nowMs, lastOkAt: nowMs })
75
- } else {
76
- // 候选已不存在(disabled 等)→ 重选
77
- chosen = fresh[0] ?? null
78
- if (chosen) map.set(sessionKey, { modelId: chosen.id, boundAt: nowMs, lastOkAt: nowMs })
79
- }
80
- } else {
81
- // 首次绑定
82
- chosen = fresh[0] ?? null
83
- if (chosen) map.set(sessionKey, { modelId: chosen.id, boundAt: nowMs, lastOkAt: nowMs })
84
- }
85
-
86
- if (!chosen) return [...fresh, ...cooling] // 全冷却:保持原序
87
- const rest = [...fresh, ...cooling].filter(r => r.id !== chosen.id)
88
- return [chosen, ...rest]
89
- }
90
-
91
- /** 会话粘性命中/失效统计(供 trace 记录)。 */
92
- export function peekStickyStats(groupId, sessionKey) {
93
- const map = sessionSticky.get(groupId)
94
- if (!map) return null
95
- const e = map.get(sessionKey)
96
- return e ? { hit: true, modelId: e.modelId, boundAt: e.boundAt, lastOkAt: e.lastOkAt } : { hit: false }
97
- }
98
-
99
- /**
100
- * 解析组为有序候选目录行。
101
- * 成员写法:暴露模型 ID(kilo/xxx、opencode/yyy、自定义 pid/zzz)或成员组(omr/slug,禁止套娃)。
102
- * 返回 { ok, candidates, missing };候选不足时 ok=false。
103
- */
104
- export async function resolveGroupChain(groupEntry) {
105
- const ids = Array.isArray(groupEntry.models) ? groupEntry.models : []
106
- const disabled = new Set(Array.isArray(groupEntry.disabled) ? groupEntry.disabled : [])
107
- const missing = []
108
- // 并行解析成员(resolveModel 命中目录缓存时零出网,冷启动时共用同一次重建 Promise)
109
- const rows = await Promise.all(ids.map(async id => {
110
- if (typeof id !== 'string' || id === '') return null
111
- if (disabled.has(id)) return null // 组内停用:保留在组里,但不参与轮询/故障切换
112
- if (id.startsWith('omr/')) { missing.push(id); return null }
113
- const row = await resolveModel(id)
114
- if (row && !row.group) return row
115
- missing.push(id)
116
- return null
117
- }))
118
- return { candidates: rows.filter(Boolean), missing }
119
- }
120
-
121
- /** 对冲默认值:候选久不出字时提前并行下一个,避免挂死候选把延迟拖成头超时。 */
122
- const DEFAULT_HEDGE_DELAY_MS = 6000
123
- const DEFAULT_HEDGE_MAX_PARALLEL = 2
124
- const DEFAULT_CANDIDATE_TIMEOUT_MS = 45_000
125
- /** 提交前最多缓存多少帧(只存 role 帧等无内容帧,正常只有 1 帧)。 */
126
- const MAX_PRE_COMMIT_FRAMES = 64
127
-
128
- /** 一帧 chunk 是否携带可见内容(正文 / 思考 / 工具调用)—— 提交点判据。 */
129
- function hasVisibleContent(chunk) {
130
- for (const c of Array.isArray(chunk?.choices) ? chunk.choices : []) {
131
- const d = c?.delta ?? c?.message ?? {}
132
- if (typeof d.content === 'string' && d.content !== '') return true
133
- if (typeof d.reasoning_content === 'string' && d.reasoning_content !== '') return true
134
- if (typeof d.reasoning === 'string' && d.reasoning !== '') return true
135
- if (Array.isArray(d.tool_calls) && d.tool_calls.length > 0) return true
136
- }
137
- return false
138
- }
139
-
140
- /** 归一化上游 chunk:补齐 id / object / created / model(统一对外模型名)。 */
141
- function normalizeChunk(raw, modelId, meta) {
142
- let obj
143
- try { obj = JSON.parse(raw) } catch { return '' }
144
- if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) return ''
145
- if (Array.isArray(obj.choices)) {
146
- obj.object = 'chat.completion.chunk'
147
- if (typeof obj.id !== 'string' || obj.id === '') obj.id = meta.id
148
- if (typeof obj.created !== 'number') obj.created = meta.created
149
- obj.model = modelId
150
- }
151
- return JSON.stringify(obj)
152
- }
153
-
154
- /** 完整响应是否为空(无正文、无思考、无工具调用、无音频):空响应要换候选。 */
155
- function isEmptyPayload(payload) {
156
- const message = payload?.choices?.[0]?.message ?? null
157
- if (!message) return true
158
- const content = message.content
159
- if (typeof content === 'string' && content.trim() !== '') return false
160
- if (Array.isArray(content) && content.length > 0) return false // 多模态内容块
161
- if (typeof message.reasoning_content === 'string' && message.reasoning_content.trim() !== '') return false
162
- if (typeof message.reasoning === 'string' && message.reasoning.trim() !== '') return false
163
- if (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) return false
164
- if (message.audio != null) return false
165
- return true
166
- }
167
-
168
- /** 探测结果的新鲜度窗口:超过即视为没有证据。 */
169
- const PROBE_EVIDENCE_TTL_MS = 45 * 60_000
170
-
171
- /**
172
- * 证据化排序(稳定):探测已验证可用的候选优先,判死/请求冷却的候选殿后,
173
- * 其余保持管理页配置的链序(fallback 质量阶梯不被改写)。
174
- * 目的:组里常有整条通道挂死(如 qoder 0/2 可用),不能让它们在链头反复吃满超时。
175
- * 返回 { ordered, tiers }(tiers 供会话粘性判断「绑定是否已不可信」)。
176
- */
177
- function rankByEvidence(ordered, nowMs = Date.now(), probe = probeSnapshot()) {
178
- const tierOf = row => {
179
- if (health.isCooling(row.id, nowMs)) return 3
180
- const p = probe[row.id]
181
- const fresh = p && typeof p.probedAt === 'number' && nowMs - p.probedAt < PROBE_EVIDENCE_TTL_MS
182
- if (!fresh) return 1 // 无证据:保持原顺序
183
- if (p.state === 'available') return 0 // 探测已验证可用:优先
184
- if (p.state === 'unavailable') return 3 // 探测判死:殿后
185
- if (p.state === 'unknown') return 2 // 探测失败但未判死(限流/5xx):谨慎殿后
186
- return 1 // probing 等中间态
187
- }
188
- const tiers = new Map(ordered.map(row => [row.id, tierOf(row)]))
189
- const sorted = ordered
190
- .map((row, index) => ({ row, index, tier: tiers.get(row.id) }))
191
- .sort((a, b) => a.tier - b.tier || a.index - b.index)
192
- .map(item => item.row)
193
- return { ordered: sorted, tiers }
194
- }
195
-
196
- /** 计算 round-robin 起始位置(peek 不消耗轮次)。 */
197
- function rotateStart(groupId, length, stickyLimit, peek) {
198
- if (length <= 1) return 0
199
- const limit = Number.isFinite(stickyLimit) && stickyLimit > 0 ? Math.trunc(stickyLimit) : 1
200
- const cursor = rotation.get(groupId) ?? { index: 0, used: 0 }
201
- const index = Math.min(Math.max(cursor.index, 0), length - 1)
202
- if (peek !== true) {
203
- const used = cursor.used + 1
204
- rotation.set(groupId, used >= limit ? { index: (index + 1) % length, used: 0 } : { index, used })
205
- }
206
- return index
207
- }
208
-
209
- export function pruneRotation(liveGroupIds) {
210
- const live = new Set(liveGroupIds)
211
- for (const key of rotation.keys()) if (!live.has(key)) rotation.delete(key)
212
- }
213
-
214
- /**
215
- * 对一个组执行一轮对话(含故障切换、内容直通与对冲并发)。
216
- *
217
- * options.onData:传入即「流式直通」模式 —— 胜出候选的 chunk 实时回传客户端;
218
- * 首个内容帧才算锁定候选(已下发内容后再失败无法回退,直接报错)。
219
- * 不传则为聚合模式:候选必须返回非空完整响应。
220
- * options.timeouts:{ headerTimeoutMs, idleTimeoutMs, turnTimeoutMs,
221
- * candidateTimeoutMs, hedgeDelayMs, hedgeMaxParallel }
222
- *
223
- * 返回 { result, tried, winner, streamed, sticky? };全链失败 throw 最后一个错误。
224
- * tried 按启动顺序列出真正尝试过的候选(被对冲放弃的不计)。
225
- */
226
- export async function completeOnGroup(groupEntry, body, options = {}) {
227
- const { candidates } = await resolveGroupChain(groupEntry)
228
- if (candidates.length === 0) {
229
- throw { kind: 'request', retryable: false, cooldownMs: 0, message: `模型组 ${groupEntry.id} 没有可用候选(成员不存在或通道停用)` }
230
- }
231
-
232
- let ordered = candidates
233
- if (groupEntry.strategy === 'round-robin') {
234
- const start = rotateStart(groupEntry.id, candidates.length, groupEntry.stickyLimit, false)
235
- ordered = [...candidates.slice(start), ...candidates.slice(0, start)]
236
- }
237
-
238
- const nowMs = Date.now()
239
- // 证据化排序:探测已验证可用 → 无证据 → 探测可疑 → 判死/冷却;
240
- // 同档内部保持管理页配置的链序,所以「质量阶梯」只被证据提升/殿后改写。
241
- const ranked = rankByEvidence(ordered, nowMs)
242
- ordered = ranked.ordered
243
- const cooling = ordered.filter(row => health.isCooling(row.id, nowMs))
244
- const fresh = ordered.filter(row => !health.isCooling(row.id, nowMs))
245
-
246
- // 会话粘性:仅 fallback 组 + 带 sessionKey 时启用
247
- const sessionKey = typeof options.sessionKey === 'string' ? options.sessionKey : ''
248
- const stickyEligible = sessionKey !== '' && groupEntry.strategy !== 'round-robin'
249
- if (stickyEligible) {
250
- // 被证据降级的候选(探测可疑/判死)不再作为粘性绑定,让下一轮重选
251
- const demoted = new Set(ordered.filter(row => (ranked.tiers.get(row.id) ?? 1) >= 2).map(row => row.id))
252
- ordered = applySessionSticky(groupEntry.id, sessionKey, ordered, fresh, cooling, nowMs, demoted)
253
- }
254
-
255
- const timeouts = options.timeouts ?? {}
256
- const streaming = typeof options.onData === 'function'
257
- const outerSignal = options.signal
258
- const turnTimeoutMs = typeof timeouts.turnTimeoutMs === 'number' ? timeouts.turnTimeoutMs : 0
259
- // 流式空闲预算:每收到一帧就续期。已向客户端下发内容的候选不再受首字预算/整组兜底
260
- // 约束,但「上游彻底不再吐帧」必须能被打断,否则挂死连接会一直占着客户端。
261
- const idleTimeoutMs = typeof timeouts.idleTimeoutMs === 'number' && timeouts.idleTimeoutMs > 0
262
- ? timeouts.idleTimeoutMs
263
- : 0
264
- const hedgeDelayMs = Math.max(0, Math.trunc(Number(timeouts.hedgeDelayMs ?? DEFAULT_HEDGE_DELAY_MS) || 0))
265
- // 对冲关闭(hedgeDelayMs=0)时并发恒为 1:回到串行 fallback 语义
266
- const maxParallel = hedgeDelayMs > 0
267
- ? Math.max(1, Math.trunc(Number(timeouts.hedgeMaxParallel ?? DEFAULT_HEDGE_MAX_PARALLEL) || 1))
268
- : 1
269
- // 组内单候选首字预算:硬墙钟(0 = 不限制)。只约束「迟迟不出字」的候选,
270
- // 已提交(已向客户端下发首个内容帧)的候选不再受它约束。
271
- const rawCandidateTimeout = Number(timeouts.candidateTimeoutMs ?? DEFAULT_CANDIDATE_TIMEOUT_MS)
272
- const candidateTimeoutMs = Number.isFinite(rawCandidateTimeout) && rawCandidateTimeout > 0
273
- ? Math.min(rawCandidateTimeout, 10 * 60_000)
274
- : 0
275
-
276
- const deadlineAt = turnTimeoutMs > 0 ? Date.now() + turnTimeoutMs : 0
277
- const chunkMeta = { id: `chatcmpl-${shortId()}`, created: Math.floor(Date.now() / 1000) }
278
-
279
- // 候选尝试表:entries 按序启动,running 为在跑集合,outcomeQueue 供主循环等待事件
280
- const entries = ordered.map(row => ({
281
- row,
282
- controller: null,
283
- state: 'idle', // idle | running | ok | failed | cancelled
284
- committed: false,
285
- committedAt: 0, // 首个内容帧时刻(流式锁定候选的时刻)
286
- buffered: [],
287
- result: null,
288
- error: null,
289
- abortReason: '', // candidate = 首字预算到点;turn = 整组到点;idle = 流式空闲超时
290
- cooldownMs: 0,
291
- startedAt: 0,
292
- finishedAt: 0,
293
- stallTimer: null,
294
- }))
295
- const running = new Set()
296
- const outcomeQueue = []
297
- let waiter = null
298
- let cursor = 0
299
- let committedEntry = null
300
- let lastError = null
301
- let stopped = false
302
- let hedgeTimer = null
303
- let deadlineTimer = null
304
-
305
- const pushOutcome = event => {
306
- outcomeQueue.push(event)
307
- const resume = waiter
308
- waiter = null
309
- if (resume) resume(outcomeQueue.shift())
310
- }
311
- const nextOutcome = () => {
312
- if (outcomeQueue.length > 0) return Promise.resolve(outcomeQueue.shift())
313
- return new Promise(resolve => { waiter = resolve })
314
- }
315
- const later = (ms, fn) => {
316
- const timer = setTimeout(() => { if (fn) fn() }, ms)
317
- timer.unref?.()
318
- return timer
319
- }
320
-
321
- /** 流式空闲看门狗:同一候选 idleTimeoutMs 内没有任何帧就主动放弃(每帧续期)。
322
- * 只在流式直通模式生效——聚合模式没有帧,不能按空闲时间掐断正常的长请求。 */
323
- const armStall = entry => {
324
- if (!streaming || idleTimeoutMs <= 0) return
325
- if (entry.stallTimer) clearTimeout(entry.stallTimer)
326
- entry.stallTimer = later(idleTimeoutMs, () => {
327
- if (entry.state !== 'running' || entry.abortReason) return
328
- entry.abortReason = 'idle'
329
- entry.controller?.abort()
330
- })
331
- }
332
- const disarmStall = entry => {
333
- if (entry.stallTimer) {
334
- clearTimeout(entry.stallTimer)
335
- entry.stallTimer = null
336
- }
337
- }
338
-
339
- /** 放弃除 keep 之外的在跑候选(对冲输家 / 收尾)。 */
340
- const cancelOthers = keep => {
341
- for (const entry of running) {
342
- if (entry === keep) continue
343
- entry.state = 'cancelled'
344
- entry.controller?.abort()
345
- }
346
- }
347
-
348
- const emit = text => {
349
- try { options.onData(text) } catch { /* 客户端已断开:由 abort 流程收尾 */ }
350
- }
351
-
352
- /** 候选吐出的原始帧:提交前只缓存 role 帧,首个内容帧到达才下发并锁定该候选。 */
353
- const handleChunk = (entry, raw) => {
354
- if (entry.state === 'cancelled') return
355
- if (entry.state === 'running') armStall(entry)
356
- const text = normalizeChunk(raw, typeof body.model === 'string' && body.model !== '' ? body.model : groupEntry.id, chunkMeta)
357
- if (text === '') return
358
- if (entry.committed) { emit(text); return }
359
- let chunk = null
360
- try { chunk = JSON.parse(text) } catch { /* 非对象帧:丢弃 */ }
361
- if (!chunk || !hasVisibleContent(chunk)) {
362
- if (entry.buffered.length < MAX_PRE_COMMIT_FRAMES) entry.buffered.push(text)
363
- return
364
- }
365
- // 首个内容帧:本候选胜出,其它并行尝试立即放弃
366
- entry.committed = true
367
- entry.committedAt = Date.now()
368
- committedEntry = entry
369
- cancelOthers(entry)
370
- for (const frame of entry.buffered) emit(frame)
371
- entry.buffered = []
372
- emit(text)
373
- }
374
-
375
- const tried = () => entries
376
- .filter(entry => entry.startedAt > 0 && entry.state !== 'cancelled')
377
- .map(entry => (entry.state === 'ok'
378
- ? { id: entry.row.id, ok: true, ms: entry.finishedAt - entry.startedAt }
379
- : {
380
- id: entry.row.id,
381
- ok: false,
382
- kind: entry.error?.kind,
383
- message: entry.error?.message,
384
- cooldownMs: entry.cooldownMs,
385
- ms: entry.finishedAt ? entry.finishedAt - entry.startedAt : 0,
386
- // 已向客户端下发过内容后失败(半截回复):排查时据此区分「没出字就换候选」与「出字后断流」
387
- ...(entry.committed ? { committed: true } : {}),
388
- }))
389
-
390
- /** 被我们主动 abort 的尝试按超时归类:没吐出任何内容就放弃的候选要长冷却。 */
391
- const abortFailure = entry => {
392
- if (entry.abortReason === 'candidate') {
393
- return { kind: 'timeout', retryable: true, cooldownMs: 5 * 60_000, message: `超过首字预算 ${candidateTimeoutMs}ms 未吐出内容,已放弃并换下一个候选` }
394
- }
395
- if (entry.abortReason === 'turn') {
396
- return { kind: 'timeout', retryable: true, cooldownMs: 5 * 60_000, message: `整组超过 turnTimeoutMs(${turnTimeoutMs}ms) 仍未吐出内容` }
397
- }
398
- if (entry.abortReason === 'idle') {
399
- return {
400
- kind: 'timeout',
401
- retryable: true,
402
- cooldownMs: 5 * 60_000,
403
- message: `流式响应空闲超时:${idleTimeoutMs >= 1000 ? `${Math.round(idleTimeoutMs / 1000)}s` : `${idleTimeoutMs}ms`} 内没有收到任何数据帧`,
404
- }
405
- }
406
- return null
407
- }
408
-
409
- const launch = () => {
410
- if (stopped || committedEntry || cursor >= entries.length) return false
411
- if (deadlineAt > 0 && Date.now() >= deadlineAt) {
412
- lastError ??= { kind: 'timeout', retryable: true, cooldownMs: 0, message: `模型组 ${groupEntry.id} 整组超过 turnTimeoutMs(${turnTimeoutMs}ms) 上限,停止切换候选` }
413
- return false
414
- }
415
- const entry = entries[cursor++]
416
- entry.state = 'running'
417
- entry.startedAt = Date.now()
418
- const controller = new AbortController()
419
- entry.controller = controller
420
- const onOuterAbort = () => controller.abort()
421
- outerSignal?.addEventListener?.('abort', onOuterAbort, { once: true })
422
- running.add(entry)
423
- armStall(entry)
424
-
425
- const attemptTimeouts = { ...timeouts }
426
- delete attemptTimeouts.candidateTimeoutMs
427
- delete attemptTimeouts.hedgeDelayMs
428
- delete attemptTimeouts.hedgeMaxParallel
429
- if (candidateTimeoutMs > 0) {
430
- // 首字预算:不覆盖更短的全局首字节超时
431
- attemptTimeouts.headerTimeoutMs = typeof attemptTimeouts.headerTimeoutMs === 'number'
432
- ? Math.min(attemptTimeouts.headerTimeoutMs, candidateTimeoutMs)
433
- : candidateTimeoutMs
434
- }
435
-
436
- // 硬墙钟:渠道内部可能自己排队/重试(如 qoder 排队预算 120s),
437
- // headerTimeout 完全挡不住,必须整次尝试到点即 abort,否则首字预算形同虚设。
438
- // ⚠ 只掐「还没吐字」的候选:一旦首个内容帧已下发给客户端(entry.committed),
439
- // 中途 abort 只会得到半截回复(客户端表现为「回一句就停、任务不动」),
440
- // 后续生成长度交给 idleTimeoutMs / turnTimeoutMs 兜底。
441
- let budgetTimer = null
442
- if (candidateTimeoutMs > 0) {
443
- budgetTimer = later(candidateTimeoutMs, () => {
444
- if (entry.state !== 'running' || entry.abortReason) return
445
- if (entry.committed) return
446
- entry.abortReason = 'candidate'
447
- entry.controller?.abort()
448
- })
449
- }
450
-
451
- // 流式直通需 body.stream=true 才会让 kilo/opencode/自定义提供商逐帧回调 onData
452
- const attemptBody = streaming ? { ...body, stream: true } : body
453
- completeOnModel(entry.row, attemptBody, {
454
- signal: controller.signal,
455
- settings: options.settings,
456
- timeouts: attemptTimeouts,
457
- sessionKey,
458
- onData: streaming ? chunk => handleChunk(entry, chunk) : undefined,
459
- }).then(
460
- result => {
461
- if (entry.state === 'cancelled') return
462
- entry.state = 'ok'
463
- entry.result = result
464
- },
465
- error => {
466
- if (entry.state === 'cancelled') return
467
- entry.state = 'failed'
468
- // 渠道抛出的裸异常(如 undici `TypeError: terminated`)统一归类,
469
- // 保证 kind/cooldown 齐全,最近请求与日志里能看到可读原因。
470
- entry.error = abortFailure(entry) ?? classifyThrownError(error ?? { kind: 'unknown', message: 'unknown error' })
471
- },
472
- ).catch(() => {}).finally(() => {
473
- entry.finishedAt = Date.now()
474
- if (budgetTimer) clearTimeout(budgetTimer)
475
- disarmStall(entry)
476
- running.delete(entry)
477
- outerSignal?.removeEventListener?.('abort', onOuterAbort)
478
- pushOutcome({ type: 'settled', entry })
479
- })
480
- return true
481
- }
482
-
483
- /** 失败即补位:把并行槽填满,不再等对冲计时(失败说明这一梯队的可靠度低)。 */
484
- const fill = () => {
485
- while (running.size < maxParallel && launch()) { /* 填到并行上限 */ }
486
- }
487
-
488
- /** 对冲计时:还有未启动候选且未锁定胜者时,隔 hedgeDelayMs 补启一个。 */
489
- const armHedge = () => {
490
- if (hedgeTimer) clearTimeout(hedgeTimer)
491
- hedgeTimer = null
492
- if (hedgeDelayMs <= 0) return // 0 = 关闭对冲(回到串行 fallback,失败才补位)
493
- if (stopped || committedEntry || cursor >= entries.length || running.size >= maxParallel) return
494
- if (deadlineAt > 0 && Date.now() >= deadlineAt) return // 截止后不再启动新候选
495
- hedgeTimer = later(hedgeDelayMs, () => { hedgeTimer = null; pushOutcome({ type: 'hedge' }) })
496
- }
497
-
498
- if (deadlineAt > 0) {
499
- deadlineTimer = later(Math.max(0, deadlineAt - Date.now()), () => pushOutcome({ type: 'deadline' }))
500
- }
501
- launch()
502
- armHedge()
503
-
504
- try {
505
- while (true) {
506
- const event = await nextOutcome()
507
-
508
- if (event.type === 'hedge') {
509
- launch()
510
- } else if (event.type === 'deadline') {
511
- // 已有候选在吐内容:不打断生成,只停止再启新候选
512
- if (committedEntry) continue
513
- // 整组到点仍未吐出任何内容:把在跑的尝试全部放弃(记为超时并冷却),不再启新候选
514
- lastError ??= { kind: 'timeout', retryable: true, cooldownMs: 0, message: `模型组 ${groupEntry.id} 整组超过 turnTimeoutMs(${turnTimeoutMs}ms) 上限,停止切换候选` }
515
- for (const entry of running) {
516
- if (entry.abortReason) continue
517
- entry.abortReason = 'turn'
518
- entry.controller?.abort()
519
- }
520
- continue
521
- } else {
522
- const entry = event.entry
523
- if (entry.state !== 'cancelled') {
524
- if (entry.state === 'ok') {
525
- // 空响应按失败处理:客户端侧表现为 Empty response data,换下一个候选更有意义
526
- if (streaming && !entry.committed) {
527
- entry.state = 'failed'
528
- entry.error = { kind: 'empty', retryable: true, cooldownMs: 30_000, message: `${entry.row.id} 未返回任何内容帧` }
529
- } else if (!streaming && isEmptyPayload(entry.result?.json ?? entry.result)) {
530
- entry.state = 'failed'
531
- entry.error = { kind: 'empty', retryable: true, cooldownMs: 30_000, message: `${entry.row.id} 返回空响应(无正文/工具调用)` }
532
- }
533
- }
534
-
535
- if (entry.state === 'ok') {
536
- health.markSuccess(entry.row.id)
537
- if (stickyEligible) {
538
- // 胜出者写回绑定(可能是原粘性候选,也可能是故障切换后的新候选)
539
- const map = sessionSticky.get(groupEntry.id)
540
- if (map) map.set(sessionKey, { modelId: entry.row.id, boundAt: map.get(sessionKey)?.boundAt ?? Date.now(), lastOkAt: Date.now() })
541
- }
542
- return {
543
- result: entry.result,
544
- tried: tried(),
545
- winner: entry.row,
546
- winnerTiming: { startedAt: entry.startedAt, committedAt: entry.committedAt, finishedAt: entry.finishedAt },
547
- streamed: streaming && entry.committed,
548
- sticky: stickyEligible ? { sessionKey, modelId: entry.row.id, hit: true } : undefined,
549
- }
550
- }
551
-
552
- // 失败:冷却并记录,未下发内容就补位下一个候选
553
- if (outerSignal?.aborted) break // 客户端断开:不算候选失败,不写冷却
554
- lastError = entry.error ?? { kind: 'unknown', message: 'unknown error' }
555
- entry.cooldownMs = health.markFailure(entry.row.id, lastError.cooldownMs)
556
- if (entry.committed) {
557
- // 内容已下发给客户端:无法回退换候选,直接向上抛(网关用数据帧告知客户端)
558
- lastError = { ...lastError, committed: true }
559
- break
560
- }
561
- // 失败即补位:把并行槽填满(失败说明这一梯队不可靠,不必再等对冲计时)
562
- fill()
563
- }
564
- }
565
-
566
- armHedge()
567
- // 终态:没有在跑的、也启动不了新的 → 结束本组尝试
568
- const exhausted = cursor >= entries.length || (deadlineAt > 0 && Date.now() >= deadlineAt)
569
- if (running.size === 0 && (committedEntry || exhausted)) break
570
- }
571
- } finally {
572
- stopped = true
573
- if (hedgeTimer) clearTimeout(hedgeTimer)
574
- if (deadlineTimer) clearTimeout(deadlineTimer)
575
- cancelOthers(null)
576
- for (const entry of entries) disarmStall(entry)
577
- }
578
-
579
- // 全失败:清除该会话的粘性绑定,让下一轮重新选择
580
- if (stickyEligible && lastError) {
581
- sessionSticky.get(groupEntry.id)?.delete(sessionKey)
582
- }
583
- const failure = lastError ?? { kind: 'request', retryable: false, cooldownMs: 0, message: `模型组 ${groupEntry.id} 全部候选失败` }
584
- // 失败路径同样带上已尝试链路:上层(gateway 日志 / recent-requests / 管理端测试)
585
- // 才能看到「到底打过哪些候选、各自报了什么」,否则只显示 tried: -
586
- failure.tried = tried()
587
- throw failure
588
- }
589
-
590
- /** 组的聚合能力 = 成员交集(视觉),上下文取最小(交集非并集)。 */
591
- export function groupCapabilities(candidates) {
592
- const withCtx = candidates.map(c => c.contextWindow).filter(v => typeof v === 'number' && v > 0)
593
- return {
594
- vision: candidates.length > 0 && candidates.every(c => c.vision === true),
595
- contextWindow: withCtx.length > 0 ? Math.min(...withCtx) : null,
596
- }
597
- }
598
-
599
- /** 暴露给 /v1/models 的组条目行。 */
600
- export async function buildGroupCatalogRows() {
601
- const { loadGroups } = await import('./store.js')
602
- const groupsDoc = loadGroups()
603
- const catalog = await buildCatalog()
604
- const byId = new Map(catalog.filter(r => !r.offline).map(r => [r.id, r]))
605
- const rows = []
606
- for (const group of Array.isArray(groupsDoc.groups) ? groupsDoc.groups : []) {
607
- if (!group || group.enabled === false) continue
608
- const disabled = new Set(Array.isArray(group.disabled) ? group.disabled : [])
609
- const members = (Array.isArray(group.models) ? group.models : []).filter(id => !disabled.has(id)).map(id => byId.get(id)).filter(Boolean)
610
- if (members.length === 0) continue
611
- const cap = groupCapabilities(members)
612
- rows.push({
613
- id: `omr/${group.id}`,
614
- provider: 'omr',
615
- upstreamId: group.id,
616
- name: `组 · ${group.name ?? group.id}(${members.length} 候选 / ${group.strategy ?? 'fallback'})`,
617
- channel: 'omr',
618
- contextWindow: cap.contextWindow,
619
- vision: cap.vision,
620
- free: members.every(m => m.free === true),
621
- })
622
- }
623
- return rows
624
- }
625
-
626
- /** 请求日志条目(供 gateway 记录使用)。 */
627
- export function newTrace(modelId) {
628
- return { model: modelId, date: utc8Date(), outcome: 'pending', tried: [] }
629
- }
1
+ /**
2
+ * 模型组路由:一个 omr/<slug> 虚拟模型 = 有序候选链。
3
+ *
4
+ * 两种策略:
5
+ * fallback 每轮都从链头开始,第一个产出结果的候选胜出(质量阶梯)。
6
+ * 支持会话粘性(sticky):带 sessionKey 的请求会尽量锁定同一候选,
7
+ * 只有被锁候选不可用(冷却/dead)才故障切换并更新绑定。
8
+ * round-robin 从下一个候选开始(stickyLimit 轮内保持粘性,兼顾 prompt 缓存),
9
+ * 均衡分摊负载。游标在内存,重启丢失只是换起点。
10
+ * 不启用会话粘性(避免与轮转语义冲突)。
11
+ *
12
+ * 故障切换:冷却中的候选跳过(全冷却时仍按序尝试,不给用户 503 优先);
13
+ * 失败按 classifyFailure 冷却并换下一个候选;全链失败才向客户端报错。
14
+ *
15
+ * 低延迟调度(2026-10 优化):
16
+ * 1) 内容直通:客户端要流式时,胜出候选的 chunk 边生成边下发,不再等整轮聚合;
17
+ * 2) 对冲并发:当前候选 hedgeDelayMs 内没吐字,就并行启动下一个;谁先出内容谁胜出,
18
+ * 其余 abort —— 挂死的免费候选不再让用户干等满 headerTimeout;
19
+ * 3) 空响应换候选:候选返回「无正文 / 无工具调用」的空响应(客户端侧的
20
+ * Empty response data)按失败处理,继续走下一个候选。
21
+ */
22
+
23
+ import { completeOnModel, resolveModel, buildCatalog } from './providers/index.js'
24
+ import { probeSnapshot } from './probe.js'
25
+ import * as health from './health.js'
26
+ import { utc8Date, shortId, classifyThrownError } from './util.js'
27
+
28
+ /** 组轮换游标:groupId -> { index, used }。 */
29
+ const rotation = new Map()
30
+
31
+ /** 会话粘性绑定:groupId -> Map<sessionKey, { modelId, boundAt, lastOkAt }>。 */
32
+ const sessionSticky = new Map()
33
+ /** 粘性 TTL(毫秒):超过后该会话的绑定失效,重新选择。 */
34
+ const SESSION_STICKY_TTL_MS = 30 * 60_000
35
+
36
+ /** 清理已消失的组与过期的粘性会话(惰性,在每次写入后调用)。 */
37
+ function pruneSessions(liveGroupIds, nowMs = Date.now()) {
38
+ const live = new Set(liveGroupIds)
39
+ for (const key of sessionSticky.keys()) {
40
+ if (!live.has(key)) sessionSticky.delete(key)
41
+ else {
42
+ const map = sessionSticky.get(key)
43
+ for (const [sid, e] of map) if (nowMs - e.lastOkAt > SESSION_STICKY_TTL_MS) map.delete(sid)
44
+ if (map.size === 0) sessionSticky.delete(key)
45
+ }
46
+ }
47
+ }
48
+
49
+ /**
50
+ * 写入或刷新粘性绑定。返回值:当前会话的有序候选链。
51
+ * - 已有绑定且该候选在 fresh 中 → 提到链头
52
+ * - 已有绑定但候选冷却/dead → 重选 fresh[0],并更新绑定
53
+ * - 无绑定 → 取 fresh[0],建立绑定
54
+ */
55
+ function applySessionSticky(groupId, sessionKey, candidates, fresh, cooling, nowMs, demoted = null) {
56
+ if (typeof sessionKey !== 'string' || sessionKey === '') return candidates
57
+ let map = sessionSticky.get(groupId)
58
+ if (!map) { map = new Map(); sessionSticky.set(groupId, map) }
59
+ pruneSessions([groupId], nowMs)
60
+
61
+ const bound = map.get(sessionKey)
62
+ let chosen = null
63
+ if (bound) {
64
+ // 绑定仍可用:把 bound 提到链头(证据变差则重选:冷却 / 探测判死)
65
+ const inFresh = fresh.find(r => r.id === bound.modelId)
66
+ const inCooling = cooling.find(r => r.id === bound.modelId)
67
+ const stale = demoted?.has(bound.modelId) === true
68
+ if (inFresh && !stale) {
69
+ chosen = inFresh
70
+ map.set(sessionKey, { ...bound, lastOkAt: nowMs })
71
+ } else if (inCooling || stale) {
72
+ // 冷却/判死的绑定 → 重选,等模型恢复后再切回
73
+ chosen = fresh[0] ?? null
74
+ if (chosen) map.set(sessionKey, { modelId: chosen.id, boundAt: nowMs, lastOkAt: nowMs })
75
+ } else {
76
+ // 候选已不存在(disabled 等)→ 重选
77
+ chosen = fresh[0] ?? null
78
+ if (chosen) map.set(sessionKey, { modelId: chosen.id, boundAt: nowMs, lastOkAt: nowMs })
79
+ }
80
+ } else {
81
+ // 首次绑定
82
+ chosen = fresh[0] ?? null
83
+ if (chosen) map.set(sessionKey, { modelId: chosen.id, boundAt: nowMs, lastOkAt: nowMs })
84
+ }
85
+
86
+ if (!chosen) return [...fresh, ...cooling] // 全冷却:保持原序
87
+ const rest = [...fresh, ...cooling].filter(r => r.id !== chosen.id)
88
+ return [chosen, ...rest]
89
+ }
90
+
91
+ /** 会话粘性命中/失效统计(供 trace 记录)。 */
92
+ export function peekStickyStats(groupId, sessionKey) {
93
+ const map = sessionSticky.get(groupId)
94
+ if (!map) return null
95
+ const e = map.get(sessionKey)
96
+ return e ? { hit: true, modelId: e.modelId, boundAt: e.boundAt, lastOkAt: e.lastOkAt } : { hit: false }
97
+ }
98
+
99
+ /**
100
+ * 解析组为有序候选目录行。
101
+ * 成员写法:暴露模型 ID(kilo/xxx、opencode/yyy、自定义 pid/zzz)或成员组(omr/slug,禁止套娃)。
102
+ * 返回 { ok, candidates, missing };候选不足时 ok=false。
103
+ */
104
+ export async function resolveGroupChain(groupEntry) {
105
+ const ids = Array.isArray(groupEntry.models) ? groupEntry.models : []
106
+ const disabled = new Set(Array.isArray(groupEntry.disabled) ? groupEntry.disabled : [])
107
+ const missing = []
108
+ // 并行解析成员(resolveModel 命中目录缓存时零出网,冷启动时共用同一次重建 Promise)
109
+ const rows = await Promise.all(ids.map(async id => {
110
+ if (typeof id !== 'string' || id === '') return null
111
+ if (disabled.has(id)) return null // 组内停用:保留在组里,但不参与轮询/故障切换
112
+ if (id.startsWith('omr/')) { missing.push(id); return null }
113
+ const row = await resolveModel(id)
114
+ if (row && !row.group) return row
115
+ missing.push(id)
116
+ return null
117
+ }))
118
+ return { candidates: rows.filter(Boolean), missing }
119
+ }
120
+
121
+ /** 对冲默认值:候选久不出字时提前并行下一个,避免挂死候选把延迟拖成头超时。 */
122
+ const DEFAULT_HEDGE_DELAY_MS = 6000
123
+ const DEFAULT_HEDGE_MAX_PARALLEL = 2
124
+ const DEFAULT_CANDIDATE_TIMEOUT_MS = 45_000
125
+ /** 提交前最多缓存多少帧(只存 role 帧等无内容帧,正常只有 1 帧)。 */
126
+ const MAX_PRE_COMMIT_FRAMES = 64
127
+
128
+ /** 一帧 chunk 是否携带可见内容(正文 / 思考 / 工具调用)—— 提交点判据。 */
129
+ function hasVisibleContent(chunk) {
130
+ for (const c of Array.isArray(chunk?.choices) ? chunk.choices : []) {
131
+ const d = c?.delta ?? c?.message ?? {}
132
+ if (typeof d.content === 'string' && d.content !== '') return true
133
+ if (typeof d.reasoning_content === 'string' && d.reasoning_content !== '') return true
134
+ if (typeof d.reasoning === 'string' && d.reasoning !== '') return true
135
+ if (Array.isArray(d.tool_calls) && d.tool_calls.length > 0) return true
136
+ }
137
+ return false
138
+ }
139
+
140
+ /** 归一化上游 chunk:补齐 id / object / created / model(统一对外模型名)。 */
141
+ function normalizeChunk(raw, modelId, meta) {
142
+ let obj
143
+ try { obj = JSON.parse(raw) } catch { return '' }
144
+ if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) return ''
145
+ if (Array.isArray(obj.choices)) {
146
+ obj.object = 'chat.completion.chunk'
147
+ if (typeof obj.id !== 'string' || obj.id === '') obj.id = meta.id
148
+ if (typeof obj.created !== 'number') obj.created = meta.created
149
+ obj.model = modelId
150
+ }
151
+ return JSON.stringify(obj)
152
+ }
153
+
154
+ /** 完整响应是否为空(无正文、无思考、无工具调用、无音频):空响应要换候选。 */
155
+ function isEmptyPayload(payload) {
156
+ const message = payload?.choices?.[0]?.message ?? null
157
+ if (!message) return true
158
+ const content = message.content
159
+ if (typeof content === 'string' && content.trim() !== '') return false
160
+ if (Array.isArray(content) && content.length > 0) return false // 多模态内容块
161
+ if (typeof message.reasoning_content === 'string' && message.reasoning_content.trim() !== '') return false
162
+ if (typeof message.reasoning === 'string' && message.reasoning.trim() !== '') return false
163
+ if (Array.isArray(message.tool_calls) && message.tool_calls.length > 0) return false
164
+ if (message.audio != null) return false
165
+ return true
166
+ }
167
+
168
+ /** 探测结果的新鲜度窗口:超过即视为没有证据。 */
169
+ const PROBE_EVIDENCE_TTL_MS = 45 * 60_000
170
+
171
+ /**
172
+ * 证据化排序(稳定):探测已验证可用的候选优先,判死/请求冷却的候选殿后,
173
+ * 其余保持管理页配置的链序(fallback 质量阶梯不被改写)。
174
+ * 目的:组里常有整条通道挂死(如 qoder 0/2 可用),不能让它们在链头反复吃满超时。
175
+ * 返回 { ordered, tiers }(tiers 供会话粘性判断「绑定是否已不可信」)。
176
+ */
177
+ function rankByEvidence(ordered, nowMs = Date.now(), probe = probeSnapshot()) {
178
+ const tierOf = row => {
179
+ if (health.isCooling(row.id, nowMs)) return 3
180
+ const p = probe[row.id]
181
+ const fresh = p && typeof p.probedAt === 'number' && nowMs - p.probedAt < PROBE_EVIDENCE_TTL_MS
182
+ if (!fresh) return 1 // 无证据:保持原顺序
183
+ if (p.state === 'available') return 0 // 探测已验证可用:优先
184
+ if (p.state === 'unavailable') return 3 // 探测判死:殿后
185
+ if (p.state === 'unknown') return 2 // 探测失败但未判死(限流/5xx):谨慎殿后
186
+ return 1 // probing 等中间态
187
+ }
188
+ const tiers = new Map(ordered.map(row => [row.id, tierOf(row)]))
189
+ const sorted = ordered
190
+ .map((row, index) => ({ row, index, tier: tiers.get(row.id) }))
191
+ .sort((a, b) => a.tier - b.tier || a.index - b.index)
192
+ .map(item => item.row)
193
+ return { ordered: sorted, tiers }
194
+ }
195
+
196
+ /** 计算 round-robin 起始位置(peek 不消耗轮次)。 */
197
+ function rotateStart(groupId, length, stickyLimit, peek) {
198
+ if (length <= 1) return 0
199
+ const limit = Number.isFinite(stickyLimit) && stickyLimit > 0 ? Math.trunc(stickyLimit) : 1
200
+ const cursor = rotation.get(groupId) ?? { index: 0, used: 0 }
201
+ const index = Math.min(Math.max(cursor.index, 0), length - 1)
202
+ if (peek !== true) {
203
+ const used = cursor.used + 1
204
+ rotation.set(groupId, used >= limit ? { index: (index + 1) % length, used: 0 } : { index, used })
205
+ }
206
+ return index
207
+ }
208
+
209
+ export function pruneRotation(liveGroupIds) {
210
+ const live = new Set(liveGroupIds)
211
+ for (const key of rotation.keys()) if (!live.has(key)) rotation.delete(key)
212
+ }
213
+
214
+ /**
215
+ * 对一个组执行一轮对话(含故障切换、内容直通与对冲并发)。
216
+ *
217
+ * options.onData:传入即「流式直通」模式 —— 胜出候选的 chunk 实时回传客户端;
218
+ * 首个内容帧才算锁定候选(已下发内容后再失败无法回退,直接报错)。
219
+ * 不传则为聚合模式:候选必须返回非空完整响应。
220
+ * options.timeouts:{ headerTimeoutMs, idleTimeoutMs, turnTimeoutMs,
221
+ * candidateTimeoutMs, hedgeDelayMs, hedgeMaxParallel }
222
+ *
223
+ * 返回 { result, tried, winner, streamed, sticky? };全链失败 throw 最后一个错误。
224
+ * tried 按启动顺序列出真正尝试过的候选(被对冲放弃的不计)。
225
+ */
226
+ export async function completeOnGroup(groupEntry, body, options = {}) {
227
+ const { candidates } = await resolveGroupChain(groupEntry)
228
+ if (candidates.length === 0) {
229
+ throw { kind: 'request', retryable: false, cooldownMs: 0, message: `模型组 ${groupEntry.id} 没有可用候选(成员不存在或通道停用)` }
230
+ }
231
+
232
+ let ordered = candidates
233
+ if (groupEntry.strategy === 'round-robin') {
234
+ const start = rotateStart(groupEntry.id, candidates.length, groupEntry.stickyLimit, false)
235
+ ordered = [...candidates.slice(start), ...candidates.slice(0, start)]
236
+ }
237
+
238
+ const nowMs = Date.now()
239
+ // 证据化排序:探测已验证可用 → 无证据 → 探测可疑 → 判死/冷却;
240
+ // 同档内部保持管理页配置的链序,所以「质量阶梯」只被证据提升/殿后改写。
241
+ const ranked = rankByEvidence(ordered, nowMs)
242
+ ordered = ranked.ordered
243
+ const cooling = ordered.filter(row => health.isCooling(row.id, nowMs))
244
+ const fresh = ordered.filter(row => !health.isCooling(row.id, nowMs))
245
+
246
+ // 会话粘性:仅 fallback 组 + 带 sessionKey 时启用
247
+ const sessionKey = typeof options.sessionKey === 'string' ? options.sessionKey : ''
248
+ const stickyEligible = sessionKey !== '' && groupEntry.strategy !== 'round-robin'
249
+ if (stickyEligible) {
250
+ // 被证据降级的候选(探测可疑/判死)不再作为粘性绑定,让下一轮重选
251
+ const demoted = new Set(ordered.filter(row => (ranked.tiers.get(row.id) ?? 1) >= 2).map(row => row.id))
252
+ ordered = applySessionSticky(groupEntry.id, sessionKey, ordered, fresh, cooling, nowMs, demoted)
253
+ }
254
+
255
+ const timeouts = options.timeouts ?? {}
256
+ const streaming = typeof options.onData === 'function'
257
+ const outerSignal = options.signal
258
+ const turnTimeoutMs = typeof timeouts.turnTimeoutMs === 'number' ? timeouts.turnTimeoutMs : 0
259
+ // 流式空闲预算:每收到一帧就续期。已向客户端下发内容的候选不再受首字预算/整组兜底
260
+ // 约束,但「上游彻底不再吐帧」必须能被打断,否则挂死连接会一直占着客户端。
261
+ const idleTimeoutMs = typeof timeouts.idleTimeoutMs === 'number' && timeouts.idleTimeoutMs > 0
262
+ ? timeouts.idleTimeoutMs
263
+ : 0
264
+ const hedgeDelayMs = Math.max(0, Math.trunc(Number(timeouts.hedgeDelayMs ?? DEFAULT_HEDGE_DELAY_MS) || 0))
265
+ // 对冲关闭(hedgeDelayMs=0)时并发恒为 1:回到串行 fallback 语义
266
+ const maxParallel = hedgeDelayMs > 0
267
+ ? Math.max(1, Math.trunc(Number(timeouts.hedgeMaxParallel ?? DEFAULT_HEDGE_MAX_PARALLEL) || 1))
268
+ : 1
269
+ // 组内单候选首字预算:硬墙钟(0 = 不限制)。只约束「迟迟不出字」的候选,
270
+ // 已提交(已向客户端下发首个内容帧)的候选不再受它约束。
271
+ const rawCandidateTimeout = Number(timeouts.candidateTimeoutMs ?? DEFAULT_CANDIDATE_TIMEOUT_MS)
272
+ const candidateTimeoutMs = Number.isFinite(rawCandidateTimeout) && rawCandidateTimeout > 0
273
+ ? Math.min(rawCandidateTimeout, 10 * 60_000)
274
+ : 0
275
+
276
+ const deadlineAt = turnTimeoutMs > 0 ? Date.now() + turnTimeoutMs : 0
277
+ const chunkMeta = { id: `chatcmpl-${shortId()}`, created: Math.floor(Date.now() / 1000) }
278
+
279
+ // 候选尝试表:entries 按序启动,running 为在跑集合,outcomeQueue 供主循环等待事件
280
+ const entries = ordered.map(row => ({
281
+ row,
282
+ controller: null,
283
+ state: 'idle', // idle | running | ok | failed | cancelled
284
+ committed: false,
285
+ committedAt: 0, // 首个内容帧时刻(流式锁定候选的时刻)
286
+ buffered: [],
287
+ result: null,
288
+ error: null,
289
+ abortReason: '', // candidate = 首字预算到点;turn = 整组到点;idle = 流式空闲超时
290
+ cooldownMs: 0,
291
+ startedAt: 0,
292
+ finishedAt: 0,
293
+ stallTimer: null,
294
+ }))
295
+ const running = new Set()
296
+ const outcomeQueue = []
297
+ let waiter = null
298
+ let cursor = 0
299
+ let committedEntry = null
300
+ let lastError = null
301
+ let stopped = false
302
+ let hedgeTimer = null
303
+ let deadlineTimer = null
304
+
305
+ const pushOutcome = event => {
306
+ outcomeQueue.push(event)
307
+ const resume = waiter
308
+ waiter = null
309
+ if (resume) resume(outcomeQueue.shift())
310
+ }
311
+ const nextOutcome = () => {
312
+ if (outcomeQueue.length > 0) return Promise.resolve(outcomeQueue.shift())
313
+ return new Promise(resolve => { waiter = resolve })
314
+ }
315
+ const later = (ms, fn) => {
316
+ const timer = setTimeout(() => { if (fn) fn() }, ms)
317
+ timer.unref?.()
318
+ return timer
319
+ }
320
+
321
+ /** 流式空闲看门狗:同一候选 idleTimeoutMs 内没有任何帧就主动放弃(每帧续期)。
322
+ * 只在流式直通模式生效——聚合模式没有帧,不能按空闲时间掐断正常的长请求。 */
323
+ const armStall = entry => {
324
+ if (!streaming || idleTimeoutMs <= 0) return
325
+ if (entry.stallTimer) clearTimeout(entry.stallTimer)
326
+ entry.stallTimer = later(idleTimeoutMs, () => {
327
+ if (entry.state !== 'running' || entry.abortReason) return
328
+ entry.abortReason = 'idle'
329
+ entry.controller?.abort()
330
+ })
331
+ }
332
+ const disarmStall = entry => {
333
+ if (entry.stallTimer) {
334
+ clearTimeout(entry.stallTimer)
335
+ entry.stallTimer = null
336
+ }
337
+ }
338
+
339
+ /** 放弃除 keep 之外的在跑候选(对冲输家 / 收尾)。 */
340
+ const cancelOthers = keep => {
341
+ for (const entry of running) {
342
+ if (entry === keep) continue
343
+ entry.state = 'cancelled'
344
+ entry.controller?.abort()
345
+ }
346
+ }
347
+
348
+ const emit = text => {
349
+ try { options.onData(text) } catch { /* 客户端已断开:由 abort 流程收尾 */ }
350
+ }
351
+
352
+ /** 候选吐出的原始帧:提交前只缓存 role 帧,首个内容帧到达才下发并锁定该候选。 */
353
+ const handleChunk = (entry, raw) => {
354
+ if (entry.state === 'cancelled') return
355
+ if (entry.state === 'running') armStall(entry)
356
+ const text = normalizeChunk(raw, typeof body.model === 'string' && body.model !== '' ? body.model : groupEntry.id, chunkMeta)
357
+ if (text === '') return
358
+ if (entry.committed) { emit(text); return }
359
+ let chunk = null
360
+ try { chunk = JSON.parse(text) } catch { /* 非对象帧:丢弃 */ }
361
+ if (!chunk || !hasVisibleContent(chunk)) {
362
+ if (entry.buffered.length < MAX_PRE_COMMIT_FRAMES) entry.buffered.push(text)
363
+ return
364
+ }
365
+ // 首个内容帧:本候选胜出,其它并行尝试立即放弃
366
+ entry.committed = true
367
+ entry.committedAt = Date.now()
368
+ committedEntry = entry
369
+ cancelOthers(entry)
370
+ for (const frame of entry.buffered) emit(frame)
371
+ entry.buffered = []
372
+ emit(text)
373
+ }
374
+
375
+ const tried = () => entries
376
+ .filter(entry => entry.startedAt > 0 && entry.state !== 'cancelled')
377
+ .map(entry => (entry.state === 'ok'
378
+ ? { id: entry.row.id, ok: true, ms: entry.finishedAt - entry.startedAt }
379
+ : {
380
+ id: entry.row.id,
381
+ ok: false,
382
+ kind: entry.error?.kind,
383
+ message: entry.error?.message,
384
+ cooldownMs: entry.cooldownMs,
385
+ ms: entry.finishedAt ? entry.finishedAt - entry.startedAt : 0,
386
+ // 已向客户端下发过内容后失败(半截回复):排查时据此区分「没出字就换候选」与「出字后断流」
387
+ ...(entry.committed ? { committed: true } : {}),
388
+ }))
389
+
390
+ /** 被我们主动 abort 的尝试按超时归类:没吐出任何内容就放弃的候选要长冷却。 */
391
+ const abortFailure = entry => {
392
+ if (entry.abortReason === 'candidate') {
393
+ return { kind: 'timeout', retryable: true, cooldownMs: 5 * 60_000, message: `超过首字预算 ${candidateTimeoutMs}ms 未吐出内容,已放弃并换下一个候选` }
394
+ }
395
+ if (entry.abortReason === 'turn') {
396
+ return { kind: 'timeout', retryable: true, cooldownMs: 5 * 60_000, message: `整组超过 turnTimeoutMs(${turnTimeoutMs}ms) 仍未吐出内容` }
397
+ }
398
+ if (entry.abortReason === 'idle') {
399
+ return {
400
+ kind: 'timeout',
401
+ retryable: true,
402
+ cooldownMs: 5 * 60_000,
403
+ message: `流式响应空闲超时:${idleTimeoutMs >= 1000 ? `${Math.round(idleTimeoutMs / 1000)}s` : `${idleTimeoutMs}ms`} 内没有收到任何数据帧`,
404
+ }
405
+ }
406
+ return null
407
+ }
408
+
409
+ const launch = () => {
410
+ if (stopped || committedEntry || cursor >= entries.length) return false
411
+ if (deadlineAt > 0 && Date.now() >= deadlineAt) {
412
+ lastError ??= { kind: 'timeout', retryable: true, cooldownMs: 0, message: `模型组 ${groupEntry.id} 整组超过 turnTimeoutMs(${turnTimeoutMs}ms) 上限,停止切换候选` }
413
+ return false
414
+ }
415
+ const entry = entries[cursor++]
416
+ entry.state = 'running'
417
+ entry.startedAt = Date.now()
418
+ const controller = new AbortController()
419
+ entry.controller = controller
420
+ const onOuterAbort = () => controller.abort()
421
+ outerSignal?.addEventListener?.('abort', onOuterAbort, { once: true })
422
+ running.add(entry)
423
+ armStall(entry)
424
+
425
+ const attemptTimeouts = { ...timeouts }
426
+ delete attemptTimeouts.candidateTimeoutMs
427
+ delete attemptTimeouts.hedgeDelayMs
428
+ delete attemptTimeouts.hedgeMaxParallel
429
+ if (candidateTimeoutMs > 0) {
430
+ // 首字预算:不覆盖更短的全局首字节超时
431
+ attemptTimeouts.headerTimeoutMs = typeof attemptTimeouts.headerTimeoutMs === 'number'
432
+ ? Math.min(attemptTimeouts.headerTimeoutMs, candidateTimeoutMs)
433
+ : candidateTimeoutMs
434
+ }
435
+
436
+ // 硬墙钟:渠道内部可能自己排队/重试(如 qoder 排队预算 120s),
437
+ // headerTimeout 完全挡不住,必须整次尝试到点即 abort,否则首字预算形同虚设。
438
+ // ⚠ 只掐「还没吐字」的候选:一旦首个内容帧已下发给客户端(entry.committed),
439
+ // 中途 abort 只会得到半截回复(客户端表现为「回一句就停、任务不动」),
440
+ // 后续生成长度交给 idleTimeoutMs / turnTimeoutMs 兜底。
441
+ let budgetTimer = null
442
+ if (candidateTimeoutMs > 0) {
443
+ budgetTimer = later(candidateTimeoutMs, () => {
444
+ if (entry.state !== 'running' || entry.abortReason) return
445
+ if (entry.committed) return
446
+ entry.abortReason = 'candidate'
447
+ entry.controller?.abort()
448
+ })
449
+ }
450
+
451
+ // 流式直通需 body.stream=true 才会让 kilo/opencode/自定义提供商逐帧回调 onData
452
+ const attemptBody = streaming ? { ...body, stream: true } : body
453
+ completeOnModel(entry.row, attemptBody, {
454
+ signal: controller.signal,
455
+ settings: options.settings,
456
+ timeouts: attemptTimeouts,
457
+ sessionKey,
458
+ onData: streaming ? chunk => handleChunk(entry, chunk) : undefined,
459
+ }).then(
460
+ result => {
461
+ if (entry.state === 'cancelled') return
462
+ entry.state = 'ok'
463
+ entry.result = result
464
+ },
465
+ error => {
466
+ if (entry.state === 'cancelled') return
467
+ entry.state = 'failed'
468
+ // 渠道抛出的裸异常(如 undici `TypeError: terminated`)统一归类,
469
+ // 保证 kind/cooldown 齐全,最近请求与日志里能看到可读原因。
470
+ entry.error = abortFailure(entry) ?? classifyThrownError(error ?? { kind: 'unknown', message: 'unknown error' })
471
+ },
472
+ ).catch(() => {}).finally(() => {
473
+ entry.finishedAt = Date.now()
474
+ if (budgetTimer) clearTimeout(budgetTimer)
475
+ disarmStall(entry)
476
+ running.delete(entry)
477
+ outerSignal?.removeEventListener?.('abort', onOuterAbort)
478
+ pushOutcome({ type: 'settled', entry })
479
+ })
480
+ return true
481
+ }
482
+
483
+ /** 失败即补位:把并行槽填满,不再等对冲计时(失败说明这一梯队的可靠度低)。 */
484
+ const fill = () => {
485
+ while (running.size < maxParallel && launch()) { /* 填到并行上限 */ }
486
+ }
487
+
488
+ /** 对冲计时:还有未启动候选且未锁定胜者时,隔 hedgeDelayMs 补启一个。 */
489
+ const armHedge = () => {
490
+ if (hedgeTimer) clearTimeout(hedgeTimer)
491
+ hedgeTimer = null
492
+ if (hedgeDelayMs <= 0) return // 0 = 关闭对冲(回到串行 fallback,失败才补位)
493
+ if (stopped || committedEntry || cursor >= entries.length || running.size >= maxParallel) return
494
+ if (deadlineAt > 0 && Date.now() >= deadlineAt) return // 截止后不再启动新候选
495
+ hedgeTimer = later(hedgeDelayMs, () => { hedgeTimer = null; pushOutcome({ type: 'hedge' }) })
496
+ }
497
+
498
+ if (deadlineAt > 0) {
499
+ deadlineTimer = later(Math.max(0, deadlineAt - Date.now()), () => pushOutcome({ type: 'deadline' }))
500
+ }
501
+ launch()
502
+ armHedge()
503
+
504
+ try {
505
+ while (true) {
506
+ const event = await nextOutcome()
507
+
508
+ if (event.type === 'hedge') {
509
+ launch()
510
+ } else if (event.type === 'deadline') {
511
+ // 已有候选在吐内容:不打断生成,只停止再启新候选
512
+ if (committedEntry) continue
513
+ // 整组到点仍未吐出任何内容:把在跑的尝试全部放弃(记为超时并冷却),不再启新候选
514
+ lastError ??= { kind: 'timeout', retryable: true, cooldownMs: 0, message: `模型组 ${groupEntry.id} 整组超过 turnTimeoutMs(${turnTimeoutMs}ms) 上限,停止切换候选` }
515
+ for (const entry of running) {
516
+ if (entry.abortReason) continue
517
+ entry.abortReason = 'turn'
518
+ entry.controller?.abort()
519
+ }
520
+ continue
521
+ } else {
522
+ const entry = event.entry
523
+ if (entry.state !== 'cancelled') {
524
+ if (entry.state === 'ok') {
525
+ // 空响应按失败处理:客户端侧表现为 Empty response data,换下一个候选更有意义
526
+ if (streaming && !entry.committed) {
527
+ entry.state = 'failed'
528
+ entry.error = { kind: 'empty', retryable: true, cooldownMs: 30_000, message: `${entry.row.id} 未返回任何内容帧` }
529
+ } else if (!streaming && isEmptyPayload(entry.result?.json ?? entry.result)) {
530
+ entry.state = 'failed'
531
+ entry.error = { kind: 'empty', retryable: true, cooldownMs: 30_000, message: `${entry.row.id} 返回空响应(无正文/工具调用)` }
532
+ }
533
+ }
534
+
535
+ if (entry.state === 'ok') {
536
+ health.markSuccess(entry.row.id)
537
+ if (stickyEligible) {
538
+ // 胜出者写回绑定(可能是原粘性候选,也可能是故障切换后的新候选)
539
+ const map = sessionSticky.get(groupEntry.id)
540
+ if (map) map.set(sessionKey, { modelId: entry.row.id, boundAt: map.get(sessionKey)?.boundAt ?? Date.now(), lastOkAt: Date.now() })
541
+ }
542
+ return {
543
+ result: entry.result,
544
+ tried: tried(),
545
+ winner: entry.row,
546
+ winnerTiming: { startedAt: entry.startedAt, committedAt: entry.committedAt, finishedAt: entry.finishedAt },
547
+ streamed: streaming && entry.committed,
548
+ sticky: stickyEligible ? { sessionKey, modelId: entry.row.id, hit: true } : undefined,
549
+ }
550
+ }
551
+
552
+ // 失败:冷却并记录,未下发内容就补位下一个候选
553
+ if (outerSignal?.aborted) break // 客户端断开:不算候选失败,不写冷却
554
+ lastError = entry.error ?? { kind: 'unknown', message: 'unknown error' }
555
+ entry.cooldownMs = health.markFailure(entry.row.id, lastError.cooldownMs)
556
+ if (entry.committed) {
557
+ // 内容已下发给客户端:无法回退换候选,直接向上抛(网关用数据帧告知客户端)
558
+ lastError = { ...lastError, committed: true }
559
+ break
560
+ }
561
+ // 失败即补位:把并行槽填满(失败说明这一梯队不可靠,不必再等对冲计时)
562
+ fill()
563
+ }
564
+ }
565
+
566
+ armHedge()
567
+ // 终态:没有在跑的、也启动不了新的 → 结束本组尝试
568
+ const exhausted = cursor >= entries.length || (deadlineAt > 0 && Date.now() >= deadlineAt)
569
+ if (running.size === 0 && (committedEntry || exhausted)) break
570
+ }
571
+ } finally {
572
+ stopped = true
573
+ if (hedgeTimer) clearTimeout(hedgeTimer)
574
+ if (deadlineTimer) clearTimeout(deadlineTimer)
575
+ cancelOthers(null)
576
+ for (const entry of entries) disarmStall(entry)
577
+ }
578
+
579
+ // 全失败:清除该会话的粘性绑定,让下一轮重新选择
580
+ if (stickyEligible && lastError) {
581
+ sessionSticky.get(groupEntry.id)?.delete(sessionKey)
582
+ }
583
+ const failure = lastError ?? { kind: 'request', retryable: false, cooldownMs: 0, message: `模型组 ${groupEntry.id} 全部候选失败` }
584
+ // 失败路径同样带上已尝试链路:上层(gateway 日志 / recent-requests / 管理端测试)
585
+ // 才能看到「到底打过哪些候选、各自报了什么」,否则只显示 tried: -
586
+ failure.tried = tried()
587
+ throw failure
588
+ }
589
+
590
+ /** 组的聚合能力 = 成员交集(视觉),上下文取最小(交集非并集)。 */
591
+ export function groupCapabilities(candidates) {
592
+ const withCtx = candidates.map(c => c.contextWindow).filter(v => typeof v === 'number' && v > 0)
593
+ return {
594
+ vision: candidates.length > 0 && candidates.every(c => c.vision === true),
595
+ contextWindow: withCtx.length > 0 ? Math.min(...withCtx) : null,
596
+ }
597
+ }
598
+
599
+ /** 暴露给 /v1/models 的组条目行。 */
600
+ export async function buildGroupCatalogRows() {
601
+ const { loadGroups } = await import('./store.js')
602
+ const groupsDoc = loadGroups()
603
+ const catalog = await buildCatalog()
604
+ const byId = new Map(catalog.filter(r => !r.offline).map(r => [r.id, r]))
605
+ const rows = []
606
+ for (const group of Array.isArray(groupsDoc.groups) ? groupsDoc.groups : []) {
607
+ if (!group || group.enabled === false) continue
608
+ const disabled = new Set(Array.isArray(group.disabled) ? group.disabled : [])
609
+ const members = (Array.isArray(group.models) ? group.models : []).filter(id => !disabled.has(id)).map(id => byId.get(id)).filter(Boolean)
610
+ if (members.length === 0) continue
611
+ const cap = groupCapabilities(members)
612
+ rows.push({
613
+ id: `omr/${group.id}`,
614
+ provider: 'omr',
615
+ upstreamId: group.id,
616
+ name: `组 · ${group.name ?? group.id}(${members.length} 候选 / ${group.strategy ?? 'fallback'})`,
617
+ channel: 'omr',
618
+ contextWindow: cap.contextWindow,
619
+ vision: cap.vision,
620
+ free: members.every(m => m.free === true),
621
+ })
622
+ }
623
+ return rows
624
+ }
625
+
626
+ /** 请求日志条目(供 gateway 记录使用)。 */
627
+ export function newTrace(modelId) {
628
+ return { model: modelId, date: utc8Date(), outcome: 'pending', tried: [] }
629
+ }