one-model-router 0.0.10 → 0.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -21
- package/package.json +1 -1
- package/src/admin.js +941 -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 +33 -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/util.js +334 -334
- package/web/app.js +3972 -3972
- package/web/index.html +32 -32
- package/web/style.css +971 -971
package/src/probe.js
CHANGED
|
@@ -1,318 +1,318 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* 后台可用性探测:
|
|
3
|
-
* - 周期对目录里的通道模型发最小流式请求(prompt='ping',max_tokens=16),记录延迟
|
|
4
|
-
* - 并发压 5,防 429 自伤;整轮跑完不截断
|
|
5
|
-
* - 全轮 rate_limit → 指数退避(30→60→120 分钟封顶),退避期跳过普通轮
|
|
6
|
-
* - 保守判据:探测失败只记录状态,不进请求冷却(网关抖动/限流 ≠ 模型死亡);
|
|
7
|
-
* 探测成功 → 清除该模型现有冷却,尽快回到路由链头
|
|
8
|
-
* - omr/ 虚拟组不探测(没有自己的端点)
|
|
9
|
-
* - 停用渠道不探测:目录缓存可能滞后(启动预热快照 / SWR 旧目录),探测前按
|
|
10
|
-
* 实时启用状态过滤(免密渠道看 settings、转发渠道看 channels.json、自定义提供商看 enabled)
|
|
11
|
-
* 单轮结果(延迟/状态)在内存;lastProbeAt 持久化到 settings.json,
|
|
12
|
-
* 重启不自动探测:按上次探测时间与间隔对比,不足间隔则等剩余毫秒,从未探测则不排自动轮。
|
|
13
|
-
*/
|
|
14
|
-
|
|
15
|
-
import { completeOnModel, buildCatalog } from './providers/index.js'
|
|
16
|
-
import { loadSettings, saveSettings, emitRuntimeEvent, DATA_DIR, loadChannels, loadProviders } from './store.js'
|
|
17
|
-
import { slugify } from './util.js'
|
|
18
|
-
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
19
|
-
import { join } from 'node:path'
|
|
20
|
-
import * as health from './health.js'
|
|
21
|
-
|
|
22
|
-
const PROBE_TIMEOUT_MS = 45_000
|
|
23
|
-
const CONCURRENCY = 5
|
|
24
|
-
const BOOT_DELAY_MS = 5_000
|
|
25
|
-
|
|
26
|
-
/** 探测状态:modelId -> { state, detail, latencyMs, probedAt } */
|
|
27
|
-
const probeState = new Map()
|
|
28
|
-
/** 正在被探测的模型 ID 集合(探测轮进行中,供 UI 显示「探测中」)。 */
|
|
29
|
-
const probing = new Set()
|
|
30
|
-
|
|
31
|
-
/** 探测快照落盘:重启后组路由仍能按「已验证可用」排序,不会又撞到整条挂死通道。 */
|
|
32
|
-
const PROBE_CACHE_FILE = join(DATA_DIR, 'probe-cache.json')
|
|
33
|
-
|
|
34
|
-
function saveProbeCache() {
|
|
35
|
-
try {
|
|
36
|
-
mkdirSync(DATA_DIR, { recursive: true })
|
|
37
|
-
const entries = {}
|
|
38
|
-
for (const [id, entry] of probeState) {
|
|
39
|
-
if (!entry || entry.state === 'probing') continue
|
|
40
|
-
entries[id] = entry
|
|
41
|
-
}
|
|
42
|
-
const tmp = `${PROBE_CACHE_FILE}.tmp`
|
|
43
|
-
writeFileSync(tmp, JSON.stringify({ at: Date.now(), entries }), 'utf8')
|
|
44
|
-
renameSync(tmp, PROBE_CACHE_FILE)
|
|
45
|
-
} catch { /* 落盘失败不影响探测 */ }
|
|
46
|
-
}
|
|
47
|
-
|
|
48
|
-
/** 启动预热:把上次落盘的探测快照读回内存(供 rankByEvidence 使用)。 */
|
|
49
|
-
export function primeProbeState() {
|
|
50
|
-
if (probeState.size > 0 || !existsSync(PROBE_CACHE_FILE)) return
|
|
51
|
-
try {
|
|
52
|
-
const doc = JSON.parse(readFileSync(PROBE_CACHE_FILE, 'utf8'))
|
|
53
|
-
for (const [id, entry] of Object.entries(doc?.entries ?? {})) {
|
|
54
|
-
if (entry && typeof entry === 'object' && typeof entry.probedAt === 'number') probeState.set(id, entry)
|
|
55
|
-
}
|
|
56
|
-
} catch { /* 快照损坏:正常冷启动 */ }
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
let timer = null
|
|
60
|
-
/** 全局探测轮进行中(「探测全部」/周期轮)。单渠道测试不占用此标记,避免影响 UI 的探测提示。 */
|
|
61
|
-
let running = false
|
|
62
|
-
/** 正在测试的渠道键集合:各渠道互不阻塞,可并行执行。 */
|
|
63
|
-
const channelRunning = new Set()
|
|
64
|
-
let throttleStreak = 0
|
|
65
|
-
let backoffUntil = 0
|
|
66
|
-
let log = () => {}
|
|
67
|
-
/** 每轮自动探测结束后的回调(桌面端用于顺带检查新版本),由 startProber 注入。 */
|
|
68
|
-
let onRoundDone = null
|
|
69
|
-
|
|
70
|
-
/** UI 快照(含探测中标记,state='probing' 时保留上一次结果数据)。 */
|
|
71
|
-
export function probeSnapshot() {
|
|
72
|
-
const out = Object.fromEntries(probeState)
|
|
73
|
-
for (const id of probing) out[id] = { ...(out[id] ?? {}), state: 'probing' }
|
|
74
|
-
return out
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
export function probeMeta() {
|
|
78
|
-
const settings = loadSettings()
|
|
79
|
-
return {
|
|
80
|
-
running,
|
|
81
|
-
throttleStreak,
|
|
82
|
-
backoffUntil,
|
|
83
|
-
inBackoff: Date.now() < backoffUntil,
|
|
84
|
-
/** 上次探测完成时间(毫秒),0 = 从未探测。 */
|
|
85
|
-
lastProbeAt: Number(settings.probe?.lastProbeAt) || 0,
|
|
86
|
-
}
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
/** 记录本次探测完成时间并落盘(settings.probe.lastProbeAt),重启后据此排程。 */
|
|
90
|
-
function recordLastProbeAt() {
|
|
91
|
-
const settings = loadSettings()
|
|
92
|
-
settings.probe ??= { enabled: false, intervalMinutes: 15, lastProbeAt: 0 }
|
|
93
|
-
settings.probe.lastProbeAt = Date.now()
|
|
94
|
-
saveSettings(settings)
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** 写探测状态并推送给管理面(SSE)。 */
|
|
98
|
-
function publish(id, entry) {
|
|
99
|
-
probeState.set(id, entry)
|
|
100
|
-
emitRuntimeEvent('probe', { id, ...entry })
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
/** 单模型探针:最小流式请求,收到任何内容帧即算可用。 */
|
|
104
|
-
async function probeOne(row) {
|
|
105
|
-
const started = Date.now()
|
|
106
|
-
const controller = new AbortController()
|
|
107
|
-
const timer = setTimeout(() => controller.abort(new Error('probe timeout')), PROBE_TIMEOUT_MS)
|
|
108
|
-
let gotFrame = false
|
|
109
|
-
probing.add(row.id)
|
|
110
|
-
emitRuntimeEvent('probe', { id: row.id, state: 'probing' })
|
|
111
|
-
try {
|
|
112
|
-
await completeOnModel(row, {
|
|
113
|
-
messages: [{ role: 'user', content: 'ping' }],
|
|
114
|
-
max_tokens: 16,
|
|
115
|
-
stream: true,
|
|
116
|
-
}, {
|
|
117
|
-
signal: controller.signal,
|
|
118
|
-
onData: () => { gotFrame = true },
|
|
119
|
-
})
|
|
120
|
-
if (!gotFrame) throw { kind: 'server', retryable: true, cooldownMs: 0, message: '流结束但没有收到内容帧' }
|
|
121
|
-
const latencyMs = Date.now() - started
|
|
122
|
-
publish(row.id, { state: 'available', detail: '', latencyMs, probedAt: Date.now() })
|
|
123
|
-
// 探测通过 → 清请求冷却(模型恢复后尽快回到链头)
|
|
124
|
-
health.markSuccess(row.id)
|
|
125
|
-
return { ok: true, kind: '' }
|
|
126
|
-
} catch (error) {
|
|
127
|
-
const kind = error?.kind ?? 'unknown'
|
|
128
|
-
const message = String(error?.message ?? error).slice(0, 300)
|
|
129
|
-
// 保守判据:只有「上游点名拒绝该模型」才算判死;
|
|
130
|
-
// 限流/额度/网关 5xx/网络抖动一律 unknown,不动路由。
|
|
131
|
-
const namedRefusal = /not supported|no such model|unknown model|invalid model|does not exist|model not found/i.test(message)
|
|
132
|
-
const dead = kind === 'not_found' || namedRefusal
|
|
133
|
-
publish(row.id, {
|
|
134
|
-
state: dead ? 'unavailable' : 'unknown',
|
|
135
|
-
detail: message,
|
|
136
|
-
latencyMs: Date.now() - started,
|
|
137
|
-
probedAt: Date.now(),
|
|
138
|
-
})
|
|
139
|
-
// 判死 → 长冷却殿后(组路由自动跳过);其余失败不进冷却,防探针误伤
|
|
140
|
-
if (dead) health.markFailure(row.id, 30 * 60_000)
|
|
141
|
-
return { ok: false, kind }
|
|
142
|
-
} finally {
|
|
143
|
-
probing.delete(row.id)
|
|
144
|
-
clearTimeout(timer)
|
|
145
|
-
}
|
|
146
|
-
}
|
|
147
|
-
|
|
148
|
-
/** 固定并发车道。 */
|
|
149
|
-
async function pool(items, limit, worker) {
|
|
150
|
-
const results = new Array(items.length)
|
|
151
|
-
let next = 0
|
|
152
|
-
async function lane() {
|
|
153
|
-
while (next < items.length) {
|
|
154
|
-
const i = next++
|
|
155
|
-
results[i] = await worker(items[i])
|
|
156
|
-
}
|
|
157
|
-
}
|
|
158
|
-
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, lane))
|
|
159
|
-
return results
|
|
160
|
-
}
|
|
161
|
-
|
|
162
|
-
/**
|
|
163
|
-
* 探测目标的启用过滤:目录只收启用渠道的模型,但缓存可能滞后(启动预热的磁盘
|
|
164
|
-
* 快照、SWR 旧目录),停用渠道的模型行可能还短暂留在目录里;探测前按实时配置
|
|
165
|
-
* 再兜一道,保证不为停用渠道出网。口径与 rebuildCatalog 一致:
|
|
166
|
-
* - 免密渠道(kilo / opencode)看 settings 开关;
|
|
167
|
-
* - 转发渠道(channels.json)看渠道段 enabled;
|
|
168
|
-
* - 自定义提供商(providers.json,含内置合并结果)看 provider.enabled。
|
|
169
|
-
*/
|
|
170
|
-
function collectEnabledKeys(settings) {
|
|
171
|
-
const enabled = new Set()
|
|
172
|
-
if (settings.kilo?.enabled !== false) enabled.add('kilo')
|
|
173
|
-
if (settings.opencode?.enabled !== false) enabled.add('opencode')
|
|
174
|
-
for (const [id, seg] of Object.entries(loadChannels().channels ?? {})) {
|
|
175
|
-
if (seg && seg.enabled === true) enabled.add(id)
|
|
176
|
-
}
|
|
177
|
-
for (const p of loadProviders().custom ?? []) {
|
|
178
|
-
if (!p || p.enabled === false) continue
|
|
179
|
-
enabled.add(typeof p.id === 'string' && p.id !== '' ? p.id : slugify(p.name))
|
|
180
|
-
}
|
|
181
|
-
return enabled
|
|
182
|
-
}
|
|
183
|
-
|
|
184
|
-
/**
|
|
185
|
-
* 跑一轮探测。force=true 穿透退避与开关(UI 手动按钮)。
|
|
186
|
-
* channel 非空时只探测该渠道下的模型(UI 分组标题行的「测试本渠道」):
|
|
187
|
-
* - 不同渠道可并行跑,互不阻塞(同一渠道单飞);
|
|
188
|
-
* - 不写 running / 不写 lastProbeAt / 不牵动退避,因此不影响「探测全部」旁的全局探测提示。
|
|
189
|
-
* 全局轮与渠道轮之间仍互斥(全局轮本来就会覆盖所有渠道)。
|
|
190
|
-
* 未启用的渠道一律不探测(手动「测试本渠道」对停用渠道同样返回无可探测模型)。
|
|
191
|
-
* 返回 { skipped?, reason?, total, ok, throttled }。
|
|
192
|
-
*/
|
|
193
|
-
export async function runProbeRound({ force = false, channel = '' } = {}) {
|
|
194
|
-
const isChannel = channel !== ''
|
|
195
|
-
if (isChannel) {
|
|
196
|
-
if (running) return { skipped: true, reason: '全局探测进行中' }
|
|
197
|
-
if (channelRunning.has(channel)) return { skipped: true, reason: `渠道「${channel}」测试进行中` }
|
|
198
|
-
} else if (running || channelRunning.size > 0) {
|
|
199
|
-
return { skipped: true, reason: '上一轮仍在进行' }
|
|
200
|
-
}
|
|
201
|
-
if (!force && Date.now() < backoffUntil) return { skipped: true, reason: '限流退避中' }
|
|
202
|
-
const settings = loadSettings()
|
|
203
|
-
if (settings.probe?.enabled === false && !force) return { skipped: true, reason: '探测已关闭' }
|
|
204
|
-
|
|
205
|
-
if (isChannel) {
|
|
206
|
-
channelRunning.add(channel)
|
|
207
|
-
} else {
|
|
208
|
-
running = true
|
|
209
|
-
emitRuntimeEvent('probe-meta', probeMeta())
|
|
210
|
-
}
|
|
211
|
-
try {
|
|
212
|
-
const catalog = await buildCatalog()
|
|
213
|
-
// 停用渠道不探测:目录缓存可能滞后,按实时启用状态过滤(row.channelId 为转发渠道键,
|
|
214
|
-
// 其余(免密渠道 / 自定义提供商)用 provider 键,与 collectEnabledKeys 口径对应)
|
|
215
|
-
const enabledKeys = collectEnabledKeys(settings)
|
|
216
|
-
const targets = catalog.filter(r =>
|
|
217
|
-
!r.offline
|
|
218
|
-
&& (channel === '' || r.channel === channel)
|
|
219
|
-
&& enabledKeys.has(r.channelId ?? r.provider))
|
|
220
|
-
if (targets.length === 0) {
|
|
221
|
-
return { skipped: true, reason: channel === '' ? '目录为空' : `渠道「${channel}」没有可探测的模型` }
|
|
222
|
-
}
|
|
223
|
-
log(`探测开始:${targets.length} 个模型(并发 ${CONCURRENCY})${channel === '' ? '' : ` · 渠道 ${channel}`}`)
|
|
224
|
-
|
|
225
|
-
const results = await pool(targets, CONCURRENCY, probeOne)
|
|
226
|
-
const ok = results.filter(r => r.ok).length
|
|
227
|
-
const throttled = results.filter(r => !r.ok && r.kind === 'rate_limit').length
|
|
228
|
-
|
|
229
|
-
// 全轮限流 → 指数退避(30→60→120 分钟封顶);单渠道测试不牵动全局退避与「上次探测」时间
|
|
230
|
-
if (channel === '') {
|
|
231
|
-
if (results.length > 0 && throttled === results.length) {
|
|
232
|
-
throttleStreak += 1
|
|
233
|
-
const minutes = Math.min(30 * 2 ** (throttleStreak - 1), 120)
|
|
234
|
-
backoffUntil = Date.now() + minutes * 60_000
|
|
235
|
-
log(`探测全轮限流,退避 ${minutes} 分钟`)
|
|
236
|
-
} else {
|
|
237
|
-
throttleStreak = 0
|
|
238
|
-
backoffUntil = 0
|
|
239
|
-
}
|
|
240
|
-
// 本轮确实跑了探测 → 记录完成时间落盘
|
|
241
|
-
recordLastProbeAt()
|
|
242
|
-
}
|
|
243
|
-
log(`探测完成:${ok}/${results.length} 可用`)
|
|
244
|
-
saveProbeCache()
|
|
245
|
-
return { total: results.length, ok, throttled, channel }
|
|
246
|
-
} finally {
|
|
247
|
-
if (isChannel) {
|
|
248
|
-
channelRunning.delete(channel)
|
|
249
|
-
} else {
|
|
250
|
-
running = false
|
|
251
|
-
emitRuntimeEvent('probe-meta', probeMeta())
|
|
252
|
-
}
|
|
253
|
-
}
|
|
254
|
-
}
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
/**
|
|
258
|
-
* 启动周期探测:setTimeout 链,每轮重读配置(间隔/开关热更新生效)。
|
|
259
|
-
* 重启不立即探测:按 settings.probe.lastProbeAt 与 intervalMinutes 对比——
|
|
260
|
-
* - 从未探测(lastProbeAt <= 0)→ 不排自动轮,仅等手动触发(runNow force=true 穿透)。
|
|
261
|
-
* - 距上次不足间隔 → 排满剩余毫秒后再跑。
|
|
262
|
-
* - 距上次已超间隔 → 排短延迟尽快补一轮。
|
|
263
|
-
* @param {{ log?: Function, onRound?: () => void }} [options] onRound:每轮自动探测结束后回调(桌面端用于顺带检查新版本)。
|
|
264
|
-
*/
|
|
265
|
-
export function startProber({ log: logFn = () => {}, onRound: roundDone = null } = {}) {
|
|
266
|
-
log = logFn
|
|
267
|
-
onRoundDone = typeof roundDone === 'function' ? roundDone : null
|
|
268
|
-
const settings = loadSettings()
|
|
269
|
-
const baseMin = Math.max(1, Math.trunc(Number(settings.probe?.intervalMinutes) || 15))
|
|
270
|
-
const intervalMs = baseMin * 60_000
|
|
271
|
-
const lastProbeAt = Number(settings.probe?.lastProbeAt) || 0
|
|
272
|
-
let firstDelay
|
|
273
|
-
if (lastProbeAt <= 0) {
|
|
274
|
-
firstDelay = null // 从未探测过 → 不排自动轮,手动触发才跑
|
|
275
|
-
} else {
|
|
276
|
-
const remain = lastProbeAt + intervalMs - Date.now()
|
|
277
|
-
firstDelay = remain > 0 ? remain : Math.min(BOOT_DELAY_MS, intervalMs)
|
|
278
|
-
}
|
|
279
|
-
// 启动时一点探测证据都没有(首次部署 / 升级后首启):探测已开启就尽快补一轮,
|
|
280
|
-
// 否则模型组只能按配置顺序盲打(可能先撞上整条挂死通道)。
|
|
281
|
-
if (settings.probe?.enabled !== false && probeState.size === 0) {
|
|
282
|
-
firstDelay = firstDelay == null ? BOOT_DELAY_MS : Math.min(firstDelay, BOOT_DELAY_MS)
|
|
283
|
-
}
|
|
284
|
-
if (firstDelay != null) schedule(firstDelay)
|
|
285
|
-
return {
|
|
286
|
-
stop: () => { clearTimeout(timer); timer = null },
|
|
287
|
-
runNow: () => runProbeRound({ force: true }),
|
|
288
|
-
}
|
|
289
|
-
}
|
|
290
|
-
|
|
291
|
-
/** 排下一轮;delayMs <= 0 时视为"从未探测",不排自动轮(保持手动可用)。 */
|
|
292
|
-
function schedule(delayMs) {
|
|
293
|
-
if (delayMs <= 0) {
|
|
294
|
-
clearTimeout(timer)
|
|
295
|
-
timer = null
|
|
296
|
-
return
|
|
297
|
-
}
|
|
298
|
-
clearTimeout(timer)
|
|
299
|
-
timer = setTimeout(async () => {
|
|
300
|
-
try {
|
|
301
|
-
await runProbeRound()
|
|
302
|
-
} catch (error) {
|
|
303
|
-
log(`探测轮异常: ${error?.message ?? error}`)
|
|
304
|
-
}
|
|
305
|
-
// 顺带钩子(如桌面端检查新版本):异常只记日志,不影响探测排程
|
|
306
|
-
try {
|
|
307
|
-
onRoundDone?.()
|
|
308
|
-
} catch (error) {
|
|
309
|
-
log(`探测轮回调失败: ${error?.message ?? error}`)
|
|
310
|
-
}
|
|
311
|
-
const settings = loadSettings()
|
|
312
|
-
const baseMin = Math.max(1, Math.trunc(Number(settings.probe?.intervalMinutes) || 15))
|
|
313
|
-
const remainBackoff = Math.max(0, backoffUntil - Date.now())
|
|
314
|
-
// 轮间正常按满间隔排程(lastProbeAt 已刷新,退避期叠加其上)
|
|
315
|
-
schedule(Math.max(baseMin * 60_000, remainBackoff))
|
|
316
|
-
}, delayMs)
|
|
317
|
-
timer.unref?.()
|
|
318
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* 后台可用性探测:
|
|
3
|
+
* - 周期对目录里的通道模型发最小流式请求(prompt='ping',max_tokens=16),记录延迟
|
|
4
|
+
* - 并发压 5,防 429 自伤;整轮跑完不截断
|
|
5
|
+
* - 全轮 rate_limit → 指数退避(30→60→120 分钟封顶),退避期跳过普通轮
|
|
6
|
+
* - 保守判据:探测失败只记录状态,不进请求冷却(网关抖动/限流 ≠ 模型死亡);
|
|
7
|
+
* 探测成功 → 清除该模型现有冷却,尽快回到路由链头
|
|
8
|
+
* - omr/ 虚拟组不探测(没有自己的端点)
|
|
9
|
+
* - 停用渠道不探测:目录缓存可能滞后(启动预热快照 / SWR 旧目录),探测前按
|
|
10
|
+
* 实时启用状态过滤(免密渠道看 settings、转发渠道看 channels.json、自定义提供商看 enabled)
|
|
11
|
+
* 单轮结果(延迟/状态)在内存;lastProbeAt 持久化到 settings.json,
|
|
12
|
+
* 重启不自动探测:按上次探测时间与间隔对比,不足间隔则等剩余毫秒,从未探测则不排自动轮。
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import { completeOnModel, buildCatalog } from './providers/index.js'
|
|
16
|
+
import { loadSettings, saveSettings, emitRuntimeEvent, DATA_DIR, loadChannels, loadProviders } from './store.js'
|
|
17
|
+
import { slugify } from './util.js'
|
|
18
|
+
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs'
|
|
19
|
+
import { join } from 'node:path'
|
|
20
|
+
import * as health from './health.js'
|
|
21
|
+
|
|
22
|
+
const PROBE_TIMEOUT_MS = 45_000
|
|
23
|
+
const CONCURRENCY = 5
|
|
24
|
+
const BOOT_DELAY_MS = 5_000
|
|
25
|
+
|
|
26
|
+
/** 探测状态:modelId -> { state, detail, latencyMs, probedAt } */
|
|
27
|
+
const probeState = new Map()
|
|
28
|
+
/** 正在被探测的模型 ID 集合(探测轮进行中,供 UI 显示「探测中」)。 */
|
|
29
|
+
const probing = new Set()
|
|
30
|
+
|
|
31
|
+
/** 探测快照落盘:重启后组路由仍能按「已验证可用」排序,不会又撞到整条挂死通道。 */
|
|
32
|
+
const PROBE_CACHE_FILE = join(DATA_DIR, 'probe-cache.json')
|
|
33
|
+
|
|
34
|
+
function saveProbeCache() {
|
|
35
|
+
try {
|
|
36
|
+
mkdirSync(DATA_DIR, { recursive: true })
|
|
37
|
+
const entries = {}
|
|
38
|
+
for (const [id, entry] of probeState) {
|
|
39
|
+
if (!entry || entry.state === 'probing') continue
|
|
40
|
+
entries[id] = entry
|
|
41
|
+
}
|
|
42
|
+
const tmp = `${PROBE_CACHE_FILE}.tmp`
|
|
43
|
+
writeFileSync(tmp, JSON.stringify({ at: Date.now(), entries }), 'utf8')
|
|
44
|
+
renameSync(tmp, PROBE_CACHE_FILE)
|
|
45
|
+
} catch { /* 落盘失败不影响探测 */ }
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** 启动预热:把上次落盘的探测快照读回内存(供 rankByEvidence 使用)。 */
|
|
49
|
+
export function primeProbeState() {
|
|
50
|
+
if (probeState.size > 0 || !existsSync(PROBE_CACHE_FILE)) return
|
|
51
|
+
try {
|
|
52
|
+
const doc = JSON.parse(readFileSync(PROBE_CACHE_FILE, 'utf8'))
|
|
53
|
+
for (const [id, entry] of Object.entries(doc?.entries ?? {})) {
|
|
54
|
+
if (entry && typeof entry === 'object' && typeof entry.probedAt === 'number') probeState.set(id, entry)
|
|
55
|
+
}
|
|
56
|
+
} catch { /* 快照损坏:正常冷启动 */ }
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
let timer = null
|
|
60
|
+
/** 全局探测轮进行中(「探测全部」/周期轮)。单渠道测试不占用此标记,避免影响 UI 的探测提示。 */
|
|
61
|
+
let running = false
|
|
62
|
+
/** 正在测试的渠道键集合:各渠道互不阻塞,可并行执行。 */
|
|
63
|
+
const channelRunning = new Set()
|
|
64
|
+
let throttleStreak = 0
|
|
65
|
+
let backoffUntil = 0
|
|
66
|
+
let log = () => {}
|
|
67
|
+
/** 每轮自动探测结束后的回调(桌面端用于顺带检查新版本),由 startProber 注入。 */
|
|
68
|
+
let onRoundDone = null
|
|
69
|
+
|
|
70
|
+
/** UI 快照(含探测中标记,state='probing' 时保留上一次结果数据)。 */
|
|
71
|
+
export function probeSnapshot() {
|
|
72
|
+
const out = Object.fromEntries(probeState)
|
|
73
|
+
for (const id of probing) out[id] = { ...(out[id] ?? {}), state: 'probing' }
|
|
74
|
+
return out
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function probeMeta() {
|
|
78
|
+
const settings = loadSettings()
|
|
79
|
+
return {
|
|
80
|
+
running,
|
|
81
|
+
throttleStreak,
|
|
82
|
+
backoffUntil,
|
|
83
|
+
inBackoff: Date.now() < backoffUntil,
|
|
84
|
+
/** 上次探测完成时间(毫秒),0 = 从未探测。 */
|
|
85
|
+
lastProbeAt: Number(settings.probe?.lastProbeAt) || 0,
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** 记录本次探测完成时间并落盘(settings.probe.lastProbeAt),重启后据此排程。 */
|
|
90
|
+
function recordLastProbeAt() {
|
|
91
|
+
const settings = loadSettings()
|
|
92
|
+
settings.probe ??= { enabled: false, intervalMinutes: 15, lastProbeAt: 0 }
|
|
93
|
+
settings.probe.lastProbeAt = Date.now()
|
|
94
|
+
saveSettings(settings)
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** 写探测状态并推送给管理面(SSE)。 */
|
|
98
|
+
function publish(id, entry) {
|
|
99
|
+
probeState.set(id, entry)
|
|
100
|
+
emitRuntimeEvent('probe', { id, ...entry })
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** 单模型探针:最小流式请求,收到任何内容帧即算可用。 */
|
|
104
|
+
async function probeOne(row) {
|
|
105
|
+
const started = Date.now()
|
|
106
|
+
const controller = new AbortController()
|
|
107
|
+
const timer = setTimeout(() => controller.abort(new Error('probe timeout')), PROBE_TIMEOUT_MS)
|
|
108
|
+
let gotFrame = false
|
|
109
|
+
probing.add(row.id)
|
|
110
|
+
emitRuntimeEvent('probe', { id: row.id, state: 'probing' })
|
|
111
|
+
try {
|
|
112
|
+
await completeOnModel(row, {
|
|
113
|
+
messages: [{ role: 'user', content: 'ping' }],
|
|
114
|
+
max_tokens: 16,
|
|
115
|
+
stream: true,
|
|
116
|
+
}, {
|
|
117
|
+
signal: controller.signal,
|
|
118
|
+
onData: () => { gotFrame = true },
|
|
119
|
+
})
|
|
120
|
+
if (!gotFrame) throw { kind: 'server', retryable: true, cooldownMs: 0, message: '流结束但没有收到内容帧' }
|
|
121
|
+
const latencyMs = Date.now() - started
|
|
122
|
+
publish(row.id, { state: 'available', detail: '', latencyMs, probedAt: Date.now() })
|
|
123
|
+
// 探测通过 → 清请求冷却(模型恢复后尽快回到链头)
|
|
124
|
+
health.markSuccess(row.id)
|
|
125
|
+
return { ok: true, kind: '' }
|
|
126
|
+
} catch (error) {
|
|
127
|
+
const kind = error?.kind ?? 'unknown'
|
|
128
|
+
const message = String(error?.message ?? error).slice(0, 300)
|
|
129
|
+
// 保守判据:只有「上游点名拒绝该模型」才算判死;
|
|
130
|
+
// 限流/额度/网关 5xx/网络抖动一律 unknown,不动路由。
|
|
131
|
+
const namedRefusal = /not supported|no such model|unknown model|invalid model|does not exist|model not found/i.test(message)
|
|
132
|
+
const dead = kind === 'not_found' || namedRefusal
|
|
133
|
+
publish(row.id, {
|
|
134
|
+
state: dead ? 'unavailable' : 'unknown',
|
|
135
|
+
detail: message,
|
|
136
|
+
latencyMs: Date.now() - started,
|
|
137
|
+
probedAt: Date.now(),
|
|
138
|
+
})
|
|
139
|
+
// 判死 → 长冷却殿后(组路由自动跳过);其余失败不进冷却,防探针误伤
|
|
140
|
+
if (dead) health.markFailure(row.id, 30 * 60_000)
|
|
141
|
+
return { ok: false, kind }
|
|
142
|
+
} finally {
|
|
143
|
+
probing.delete(row.id)
|
|
144
|
+
clearTimeout(timer)
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** 固定并发车道。 */
|
|
149
|
+
async function pool(items, limit, worker) {
|
|
150
|
+
const results = new Array(items.length)
|
|
151
|
+
let next = 0
|
|
152
|
+
async function lane() {
|
|
153
|
+
while (next < items.length) {
|
|
154
|
+
const i = next++
|
|
155
|
+
results[i] = await worker(items[i])
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, lane))
|
|
159
|
+
return results
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* 探测目标的启用过滤:目录只收启用渠道的模型,但缓存可能滞后(启动预热的磁盘
|
|
164
|
+
* 快照、SWR 旧目录),停用渠道的模型行可能还短暂留在目录里;探测前按实时配置
|
|
165
|
+
* 再兜一道,保证不为停用渠道出网。口径与 rebuildCatalog 一致:
|
|
166
|
+
* - 免密渠道(kilo / opencode)看 settings 开关;
|
|
167
|
+
* - 转发渠道(channels.json)看渠道段 enabled;
|
|
168
|
+
* - 自定义提供商(providers.json,含内置合并结果)看 provider.enabled。
|
|
169
|
+
*/
|
|
170
|
+
function collectEnabledKeys(settings) {
|
|
171
|
+
const enabled = new Set()
|
|
172
|
+
if (settings.kilo?.enabled !== false) enabled.add('kilo')
|
|
173
|
+
if (settings.opencode?.enabled !== false) enabled.add('opencode')
|
|
174
|
+
for (const [id, seg] of Object.entries(loadChannels().channels ?? {})) {
|
|
175
|
+
if (seg && seg.enabled === true) enabled.add(id)
|
|
176
|
+
}
|
|
177
|
+
for (const p of loadProviders().custom ?? []) {
|
|
178
|
+
if (!p || p.enabled === false) continue
|
|
179
|
+
enabled.add(typeof p.id === 'string' && p.id !== '' ? p.id : slugify(p.name))
|
|
180
|
+
}
|
|
181
|
+
return enabled
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
/**
|
|
185
|
+
* 跑一轮探测。force=true 穿透退避与开关(UI 手动按钮)。
|
|
186
|
+
* channel 非空时只探测该渠道下的模型(UI 分组标题行的「测试本渠道」):
|
|
187
|
+
* - 不同渠道可并行跑,互不阻塞(同一渠道单飞);
|
|
188
|
+
* - 不写 running / 不写 lastProbeAt / 不牵动退避,因此不影响「探测全部」旁的全局探测提示。
|
|
189
|
+
* 全局轮与渠道轮之间仍互斥(全局轮本来就会覆盖所有渠道)。
|
|
190
|
+
* 未启用的渠道一律不探测(手动「测试本渠道」对停用渠道同样返回无可探测模型)。
|
|
191
|
+
* 返回 { skipped?, reason?, total, ok, throttled }。
|
|
192
|
+
*/
|
|
193
|
+
export async function runProbeRound({ force = false, channel = '' } = {}) {
|
|
194
|
+
const isChannel = channel !== ''
|
|
195
|
+
if (isChannel) {
|
|
196
|
+
if (running) return { skipped: true, reason: '全局探测进行中' }
|
|
197
|
+
if (channelRunning.has(channel)) return { skipped: true, reason: `渠道「${channel}」测试进行中` }
|
|
198
|
+
} else if (running || channelRunning.size > 0) {
|
|
199
|
+
return { skipped: true, reason: '上一轮仍在进行' }
|
|
200
|
+
}
|
|
201
|
+
if (!force && Date.now() < backoffUntil) return { skipped: true, reason: '限流退避中' }
|
|
202
|
+
const settings = loadSettings()
|
|
203
|
+
if (settings.probe?.enabled === false && !force) return { skipped: true, reason: '探测已关闭' }
|
|
204
|
+
|
|
205
|
+
if (isChannel) {
|
|
206
|
+
channelRunning.add(channel)
|
|
207
|
+
} else {
|
|
208
|
+
running = true
|
|
209
|
+
emitRuntimeEvent('probe-meta', probeMeta())
|
|
210
|
+
}
|
|
211
|
+
try {
|
|
212
|
+
const catalog = await buildCatalog()
|
|
213
|
+
// 停用渠道不探测:目录缓存可能滞后,按实时启用状态过滤(row.channelId 为转发渠道键,
|
|
214
|
+
// 其余(免密渠道 / 自定义提供商)用 provider 键,与 collectEnabledKeys 口径对应)
|
|
215
|
+
const enabledKeys = collectEnabledKeys(settings)
|
|
216
|
+
const targets = catalog.filter(r =>
|
|
217
|
+
!r.offline
|
|
218
|
+
&& (channel === '' || r.channel === channel)
|
|
219
|
+
&& enabledKeys.has(r.channelId ?? r.provider))
|
|
220
|
+
if (targets.length === 0) {
|
|
221
|
+
return { skipped: true, reason: channel === '' ? '目录为空' : `渠道「${channel}」没有可探测的模型` }
|
|
222
|
+
}
|
|
223
|
+
log(`探测开始:${targets.length} 个模型(并发 ${CONCURRENCY})${channel === '' ? '' : ` · 渠道 ${channel}`}`)
|
|
224
|
+
|
|
225
|
+
const results = await pool(targets, CONCURRENCY, probeOne)
|
|
226
|
+
const ok = results.filter(r => r.ok).length
|
|
227
|
+
const throttled = results.filter(r => !r.ok && r.kind === 'rate_limit').length
|
|
228
|
+
|
|
229
|
+
// 全轮限流 → 指数退避(30→60→120 分钟封顶);单渠道测试不牵动全局退避与「上次探测」时间
|
|
230
|
+
if (channel === '') {
|
|
231
|
+
if (results.length > 0 && throttled === results.length) {
|
|
232
|
+
throttleStreak += 1
|
|
233
|
+
const minutes = Math.min(30 * 2 ** (throttleStreak - 1), 120)
|
|
234
|
+
backoffUntil = Date.now() + minutes * 60_000
|
|
235
|
+
log(`探测全轮限流,退避 ${minutes} 分钟`)
|
|
236
|
+
} else {
|
|
237
|
+
throttleStreak = 0
|
|
238
|
+
backoffUntil = 0
|
|
239
|
+
}
|
|
240
|
+
// 本轮确实跑了探测 → 记录完成时间落盘
|
|
241
|
+
recordLastProbeAt()
|
|
242
|
+
}
|
|
243
|
+
log(`探测完成:${ok}/${results.length} 可用`)
|
|
244
|
+
saveProbeCache()
|
|
245
|
+
return { total: results.length, ok, throttled, channel }
|
|
246
|
+
} finally {
|
|
247
|
+
if (isChannel) {
|
|
248
|
+
channelRunning.delete(channel)
|
|
249
|
+
} else {
|
|
250
|
+
running = false
|
|
251
|
+
emitRuntimeEvent('probe-meta', probeMeta())
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* 启动周期探测:setTimeout 链,每轮重读配置(间隔/开关热更新生效)。
|
|
259
|
+
* 重启不立即探测:按 settings.probe.lastProbeAt 与 intervalMinutes 对比——
|
|
260
|
+
* - 从未探测(lastProbeAt <= 0)→ 不排自动轮,仅等手动触发(runNow force=true 穿透)。
|
|
261
|
+
* - 距上次不足间隔 → 排满剩余毫秒后再跑。
|
|
262
|
+
* - 距上次已超间隔 → 排短延迟尽快补一轮。
|
|
263
|
+
* @param {{ log?: Function, onRound?: () => void }} [options] onRound:每轮自动探测结束后回调(桌面端用于顺带检查新版本)。
|
|
264
|
+
*/
|
|
265
|
+
export function startProber({ log: logFn = () => {}, onRound: roundDone = null } = {}) {
|
|
266
|
+
log = logFn
|
|
267
|
+
onRoundDone = typeof roundDone === 'function' ? roundDone : null
|
|
268
|
+
const settings = loadSettings()
|
|
269
|
+
const baseMin = Math.max(1, Math.trunc(Number(settings.probe?.intervalMinutes) || 15))
|
|
270
|
+
const intervalMs = baseMin * 60_000
|
|
271
|
+
const lastProbeAt = Number(settings.probe?.lastProbeAt) || 0
|
|
272
|
+
let firstDelay
|
|
273
|
+
if (lastProbeAt <= 0) {
|
|
274
|
+
firstDelay = null // 从未探测过 → 不排自动轮,手动触发才跑
|
|
275
|
+
} else {
|
|
276
|
+
const remain = lastProbeAt + intervalMs - Date.now()
|
|
277
|
+
firstDelay = remain > 0 ? remain : Math.min(BOOT_DELAY_MS, intervalMs)
|
|
278
|
+
}
|
|
279
|
+
// 启动时一点探测证据都没有(首次部署 / 升级后首启):探测已开启就尽快补一轮,
|
|
280
|
+
// 否则模型组只能按配置顺序盲打(可能先撞上整条挂死通道)。
|
|
281
|
+
if (settings.probe?.enabled !== false && probeState.size === 0) {
|
|
282
|
+
firstDelay = firstDelay == null ? BOOT_DELAY_MS : Math.min(firstDelay, BOOT_DELAY_MS)
|
|
283
|
+
}
|
|
284
|
+
if (firstDelay != null) schedule(firstDelay)
|
|
285
|
+
return {
|
|
286
|
+
stop: () => { clearTimeout(timer); timer = null },
|
|
287
|
+
runNow: () => runProbeRound({ force: true }),
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
/** 排下一轮;delayMs <= 0 时视为"从未探测",不排自动轮(保持手动可用)。 */
|
|
292
|
+
function schedule(delayMs) {
|
|
293
|
+
if (delayMs <= 0) {
|
|
294
|
+
clearTimeout(timer)
|
|
295
|
+
timer = null
|
|
296
|
+
return
|
|
297
|
+
}
|
|
298
|
+
clearTimeout(timer)
|
|
299
|
+
timer = setTimeout(async () => {
|
|
300
|
+
try {
|
|
301
|
+
await runProbeRound()
|
|
302
|
+
} catch (error) {
|
|
303
|
+
log(`探测轮异常: ${error?.message ?? error}`)
|
|
304
|
+
}
|
|
305
|
+
// 顺带钩子(如桌面端检查新版本):异常只记日志,不影响探测排程
|
|
306
|
+
try {
|
|
307
|
+
onRoundDone?.()
|
|
308
|
+
} catch (error) {
|
|
309
|
+
log(`探测轮回调失败: ${error?.message ?? error}`)
|
|
310
|
+
}
|
|
311
|
+
const settings = loadSettings()
|
|
312
|
+
const baseMin = Math.max(1, Math.trunc(Number(settings.probe?.intervalMinutes) || 15))
|
|
313
|
+
const remainBackoff = Math.max(0, backoffUntil - Date.now())
|
|
314
|
+
// 轮间正常按满间隔排程(lastProbeAt 已刷新,退避期叠加其上)
|
|
315
|
+
schedule(Math.max(baseMin * 60_000, remainBackoff))
|
|
316
|
+
}, delayMs)
|
|
317
|
+
timer.unref?.()
|
|
318
|
+
}
|