one-model-router 0.0.10 → 0.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/LICENSE +21 -21
  2. package/package.json +1 -1
  3. package/src/admin.js +941 -941
  4. package/src/balances.js +61 -61
  5. package/src/boot.js +117 -117
  6. package/src/channels/buddy.js +2031 -2031
  7. package/src/channels/cline.js +753 -753
  8. package/src/channels/codearts.js +2051 -2051
  9. package/src/channels/comate.js +830 -830
  10. package/src/channels/doubaowork.js +1784 -1784
  11. package/src/channels/freebuff.js +1316 -1316
  12. package/src/channels/gemini.js +1721 -1721
  13. package/src/channels/index.js +270 -270
  14. package/src/channels/joycode.js +936 -936
  15. package/src/channels/kimi.js +572 -572
  16. package/src/channels/lobsterai.js +1226 -1226
  17. package/src/channels/loomy.js +1032 -1032
  18. package/src/channels/miaoshou.js +1396 -1396
  19. package/src/channels/mimo.js +474 -474
  20. package/src/channels/minimax.js +1451 -1451
  21. package/src/channels/qoder-wasm.js +434 -434
  22. package/src/channels/qoder.js +1619 -1619
  23. package/src/channels/raccoon.js +1842 -1842
  24. package/src/channels/tabbit.js +1457 -1457
  25. package/src/channels/trae.js +1405 -1405
  26. package/src/channels/zcode-global.js +35 -35
  27. package/src/channels/zcode.js +2085 -2085
  28. package/src/checkin.js +496 -496
  29. package/src/credits.js +464 -464
  30. package/src/crypto.js +132 -132
  31. package/src/free-models.js +683 -683
  32. package/src/gateway.js +596 -578
  33. package/src/health.js +86 -86
  34. package/src/model-key.js +35 -35
  35. package/src/paths.js +96 -96
  36. package/src/probe.js +318 -318
  37. package/src/providers/builtin.js +626 -626
  38. package/src/providers/index.js +483 -457
  39. package/src/providers/kilo.js +111 -111
  40. package/src/providers/last-good.js +69 -69
  41. package/src/providers/modelsdev.js +242 -242
  42. package/src/providers/openai-compat.js +312 -312
  43. package/src/providers/opencode/bun-fetch.js +226 -226
  44. package/src/providers/opencode/lane.js +186 -186
  45. package/src/providers/opencode/o2a/LICENSE.dsh-our-free-model +21 -21
  46. package/src/providers/opencode/o2a/asset-source.js +43 -43
  47. package/src/providers/opencode/o2a/assets/opencode_prompt_v2.txt +96 -96
  48. package/src/providers/opencode/o2a/assets/opencode_tools.json +327 -327
  49. package/src/providers/opencode/o2a/entry.js +17 -17
  50. package/src/providers/opencode/o2a/gateway-body.js +42 -42
  51. package/src/providers/opencode/o2a/headers.js +133 -133
  52. package/src/providers/opencode/o2a/identity.js +148 -148
  53. package/src/providers/opencode/o2a/official-prompt.js +191 -191
  54. package/src/providers/opencode/o2a/official-tools.js +110 -110
  55. package/src/providers/opencode/o2a/tool-renames.js +217 -217
  56. package/src/providers/opencode/o2a/toolshape.js +418 -418
  57. package/src/providers/opencode/o2a/version.js +37 -37
  58. package/src/providers/opencode/upstream.js +403 -403
  59. package/src/providers/opencode/wire.js +496 -496
  60. package/src/providers/opencode.js +652 -652
  61. package/src/router.js +629 -629
  62. package/src/server.js +33 -33
  63. package/src/store.js +467 -467
  64. package/src/sync/index.js +1529 -1529
  65. package/src/sync/login-preload.cjs +52 -52
  66. package/src/sync/noise.js +141 -141
  67. package/src/sync/relay-http.js +176 -176
  68. package/src/sync/remote-host.js +818 -818
  69. package/src/sync/remote-http.js +112 -112
  70. package/src/sync/remote-login.js +657 -657
  71. package/src/sync/remote-pairing.js +204 -204
  72. package/src/sync/remote-protocol.js +321 -321
  73. package/src/sync/snapshot.js +211 -211
  74. package/src/util.js +334 -334
  75. package/web/app.js +3972 -3972
  76. package/web/index.html +32 -32
  77. package/web/style.css +971 -971
@@ -1,312 +1,312 @@
1
- /**
2
- * 自定义 OpenAI 兼容提供商:baseUrl + apiKey + 模型清单(可自动发现)。
3
- * 覆盖 OpenRouter / SiliconFlow / 自建 vLLM / 各种中转站等一切
4
- * 「POST {base}/chat/completions、GET {base}/models」形态的通道。
5
- *
6
- * 账号槽(与 opencode.js 一致的槽轮换语义):
7
- * 每个提供商持有启用槽序列,请求按模型记忆的游标轮换槽;失败时携带
8
- * rotate:true 的错误(401/403/429/quota/rate_limit)换下一个槽重试。
9
- * 旧格式单 apiKey 在读取时归一成单槽(见 listSlots)。
10
- */
11
-
12
- import { httpFetch, readSseData, readBodyText, classifyFailure, classifyThrownError, retryAfterMs } from '../util.js'
13
-
14
- /**
15
- * 组装账号槽序列(与 opencode.js listSlots 相同的归一语义):
16
- * - provider.slots 非空数组时取启用的槽(key 为空白的条目剔除);
17
- * - 否则旧格式单 apiKey 归一成单槽;
18
- * - 完全无 key(本地 vLLM 等免鉴权端点)→ 单个空 key 槽(请求不带 authorization 头)。
19
- * 因此返回值恒 ≥ 1 条。
20
- */
21
- export function listSlots(provider) {
22
- const slots = Array.isArray(provider?.slots) ? provider.slots : []
23
- const enabled = slots
24
- .filter(slot => slot && slot.enabled !== false && typeof slot.apiKey === 'string' && slot.apiKey !== '')
25
- .map(slot => ({
26
- id: typeof slot.id === 'string' && slot.id !== '' ? slot.id : 'default',
27
- label: typeof slot.label === 'string' && slot.label !== '' ? slot.label : '账号槽',
28
- apiKey: slot.apiKey,
29
- }))
30
- if (enabled.length > 0) return enabled
31
- const legacy = typeof provider?.apiKey === 'string' ? provider.apiKey : ''
32
- return [{ id: 'default', label: '默认通道', apiKey: legacy }]
33
- }
34
-
35
- /** 每 token 美元单价 → 每百万 token 单价文本(`"0.000002"` → `$2/M`)。0 视为未定价(返回空串)。 */
36
- function priceLabel(perToken) {
37
- const n = typeof perToken === 'number' ? perToken : Number.parseFloat(perToken)
38
- if (!Number.isFinite(n) || n <= 0) return ''
39
- const perMillion = n * 1_000_000
40
- const text = perMillion >= 1 ? String(Math.round(perMillion * 100) / 100) : String(Math.round(perMillion * 1000) / 1000)
41
- return `$${text}/M`
42
- }
43
-
44
- /**
45
- * 自动发现模型(GET {base}/models)。返回 [{id,name,contextWindow,price?,priceOutput?,free?}]。
46
- * 上游带 `pricing.prompt` / `pricing.completion`(USD/token 字符串,OpenRouter 形态)时
47
- * 附带每百万 token 单价;定价全 0 或 id 以 `:free` 结尾视为免费模型。
48
- */
49
- export async function discoverModels(provider, { signal } = {}) {
50
- const base = String(provider.baseUrl ?? '').replace(/\/+$/, '')
51
- const headers = { accept: 'application/json' }
52
- if (provider.apiKey) headers.authorization = `Bearer ${provider.apiKey}`
53
- const response = await httpFetch(`${base}/models`, { headers, redirect: 'error', signal }, 15000)
54
- const text = await readBodyText(response, 15000)
55
- if (!response.ok) throw classifyFailure(response.status, text)
56
- let payload
57
- try { payload = JSON.parse(text) } catch { throw classifyFailure(response.status, text) }
58
- const rows = Array.isArray(payload) ? payload : Array.isArray(payload.data) ? payload.data : []
59
- return rows
60
- .filter(row => row && typeof row.id === 'string' && row.id !== '')
61
- .map(row => {
62
- const prompt = typeof row.pricing?.prompt === 'number' ? row.pricing.prompt : Number.parseFloat(row.pricing?.prompt)
63
- const completion = typeof row.pricing?.completion === 'number' ? row.pricing.completion : Number.parseFloat(row.pricing?.completion)
64
- // 上游给了定价清单(含全 0 的免费档)才算「有定价」,缺字段 / 非数值视为无定价
65
- const hasPricing = Number.isFinite(prompt) || Number.isFinite(completion)
66
- const price = priceLabel(prompt)
67
- const priceOutput = priceLabel(completion)
68
- // 免费判定:定价全为 0(OpenRouter 免费档)或 id 带 :free 后缀(-1 等变量价不算免费)
69
- const free = hasPricing
70
- ? (prompt === 0 && completion === 0) || /:free$/i.test(row.id)
71
- : undefined
72
- return {
73
- id: row.id,
74
- name: typeof row.name === 'string' && row.name !== '' ? row.name : row.id,
75
- contextWindow: typeof row.context_length === 'number' ? row.context_length
76
- : typeof row.context_window === 'number' ? row.context_window
77
- : typeof row.context_window?.total === 'number' ? row.context_window.total
78
- : null,
79
- ...(hasPricing ? { ...(price ? { price } : {}), ...(priceOutput ? { priceOutput } : {}) } : {}),
80
- ...(free !== undefined ? { free } : {}),
81
- }
82
- })
83
- }
84
-
85
- /**
86
- * 聚合渠道识别(按 baseUrl 主机):魔搭 ModelScope / OpenRouter / NVIDIA NIM。
87
- * 这三个渠道的 /models 里混有大量海外模型,付费模型只保留国内厂商的旗舰版与 flash 版;
88
- * 免费模型不过滤、全部保留——OpenRouter 的免费池大量来自海外厂商,按国内白名单
89
- * 过滤会把它们挡在自动选用之外(免费判定见 discoverModels 的 free 字段)。
90
- */
91
- export function aggregatorKind(baseUrl) {
92
- const url = String(baseUrl ?? '').toLowerCase()
93
- if (url.includes('modelscope')) return 'modelscope'
94
- if (url.includes('openrouter')) return 'openrouter'
95
- if (url.includes('nvidia')) return 'nvidia'
96
- return ''
97
- }
98
-
99
- /** 国内模型提供商的模型 id 前缀(`/` 前一段,小写)。 */
100
- const DOMESTIC_PROVIDER_PREFIXES = new Set([
101
- 'deepseek', 'deepseek-ai', 'deepseekai',
102
- 'qwen', 'qwenlm', 'alibaba', 'aliyun', 'tongyi',
103
- 'zhipuai', 'zhipu', 'z-ai', 'thudm', 'glm',
104
- 'moonshotai', 'moonshot', 'moonshot-ai', 'kimi',
105
- 'minimax', 'minimaxai', 'minimax-ai',
106
- 'stepfun', 'stepfun-ai',
107
- '01-ai', '01ai', 'yi', 'lingyiwanwu',
108
- 'baichuan', 'internlm', 'intern-ai', 'shanghai-ai-lab', 'opengvlab',
109
- 'sensenova', 'sensetime', 'baidu', 'ernie',
110
- 'bytedance', 'bytedance-seed', 'doubao', 'seed',
111
- 'tencent', 'hunyuan', 'xiaomi', 'mimo',
112
- 'longcat', 'meituan', 'modelbest', 'openbmb', 'minicpm',
113
- 'skywork', 'kunlun', 'xverse', 'rednote', 'dots-studio', 'dots',
114
- 'inclusionai', 'inclusion-ai', 'bailing', 'antgroup', 'ant',
115
- 'huawei', 'pangu', 'iflytek', 'spark', 'xingchen-agi', 'baai', 'teleai',
116
- ])
117
-
118
- /** 非旗舰档位关键词(低配 / 嵌入 / 审核 / 多模态工具模型,命中即排除)。 */
119
- const NON_FLAGSHIP_RE = /(?:^|[-_.])(?:lite|mini|tiny|small|nano|turbo|air|light|base|micro|edge|mobile|embed|embedding|rerank|guard|safety|moderation|whisper|tts|asr|audio|image|video|ocr|diffusion)(?:[-_.]|$)/i
120
- /** 提取参数量(B):`a3b` 这类 MoE 激活量不计入。 */
121
- const PARAM_SIZE_RE = /(?<![a-z0-9.])(\d+(?:\.\d+)?)b(?![a-z0-9])/gi
122
- /** 带参数量标注的模型,达到 30B 才算旗舰(27B 等中小尺寸不算)。 */
123
- const FLAGSHIP_MIN_B = 30
124
- /** flash 档位:模型名含 flash(含 flash-lite / flash-next 等衍生)。 */
125
- const FLASH_RE = /flash/i
126
-
127
- /** 模型名部分(去掉 `提供商/` 前缀)。 */
128
- const modelBaseName = id => {
129
- const slash = id.indexOf('/')
130
- return slash > 0 ? id.slice(slash + 1) : ''
131
- }
132
-
133
- /**
134
- * 聚合渠道的单模型过滤:
135
- * - 只保留国内模型提供商的模型(id 前缀白名单);
136
- * - 旗舰版(非低配档位;带参数量标注的需 ≥30B)或 flash 版本。
137
- */
138
- export function isAggregatorModelAllowed(model) {
139
- const id = typeof model?.id === 'string' ? model.id : ''
140
- const slash = id.indexOf('/')
141
- if (slash <= 0) return false
142
- if (!DOMESTIC_PROVIDER_PREFIXES.has(id.slice(0, slash).toLowerCase())) return false
143
- const base = modelBaseName(id)
144
- if (FLASH_RE.test(base)) return true
145
- if (NON_FLAGSHIP_RE.test(base)) return false
146
- const sizes = [...base.matchAll(PARAM_SIZE_RE)].map(m => Number(m[1])).filter(Number.isFinite)
147
- return sizes.length === 0 || Math.max(...sizes) >= FLAGSHIP_MIN_B
148
- }
149
-
150
- /**
151
- * 按 baseUrl 过滤聚合渠道清单;非聚合渠道原样返回。
152
- * 免费模型(定价全 0 / :free 后缀,见 discoverModels)豁免国内白名单过滤全部保留,
153
- * 供免费模型扫描自动选用——选用清单的免费部分随每轮探测整体刷新为最新免费全集。
154
- * 三个聚合渠道里只有 OpenRouter 上游带定价,实际生效面即 OpenRouter。
155
- */
156
- export function filterAggregatorModels(baseUrl, models) {
157
- if (aggregatorKind(baseUrl) === '') return models
158
- return (Array.isArray(models) ? models : []).filter(m => m?.free === true || isAggregatorModelAllowed(m))
159
- }
160
-
161
- /**
162
- * AMD TokenFactory 网关识别(按 baseUrl 主机)。developer.amd.com.cn 的 OpenAI 兼容
163
- * 网关在 /models 里给几乎全部模型挂了极小的 per-token「pricing」(如 3.5e-8)——
164
- * 那是 TokenFactory 免费额度内的消耗速率,不是 USD 计费价(官网卡片明示
165
- * 「Free to use. Points show relative usage—not a charge.」),且模型记录的
166
- * free 布尔字段恒为 false,不能作为免费依据。
167
- */
168
- export function isAmdTokenFactory(baseUrl) {
169
- try { return new URL(String(baseUrl ?? '')).hostname === 'developer.amd.com.cn' } catch { return false }
170
- }
171
-
172
- /**
173
- * AMD TokenFactory 官网目录:public_free 区块(「Public Free Model APIs」)的模型 id 集合。
174
- * 官网 tokenfactory 页的 Free 徽标依据就是目录归属(卡片详情里
175
- * token_factory.section = "public_free" / display_status = "free_endpoint"),
176
- * 与 /models 的 pricing 无关。此处取同一接口 /radeon/api/tokenfactory/bootstrap
177
- * (SPA 内部接口,需 Origin/Referer),解析各卡片 detail_url 的 model id。
178
- * 返回 null = 目录拉不到(接口改版/风控),调用方回退整目录免费。
179
- */
180
- async function amdTokenFactoryFreeIds(provider) {
181
- try {
182
- const origin = new URL(String(provider?.baseUrl ?? '')).origin
183
- const url = `${origin}/radeon/api/tokenfactory/bootstrap?directory=true`
184
- const headers = { accept: 'application/json', origin, referer: `${origin}/radeon/tokenfactory` }
185
- const response = await httpFetch(url, { headers, redirect: 'error' }, 15000)
186
- const text = await readBodyText(response, 15000)
187
- if (!response.ok) return null
188
- const payload = JSON.parse(text)
189
- const ids = new Set()
190
- for (const card of Array.isArray(payload?.cards) ? payload.cards : []) {
191
- const detail = typeof card?.detail_url === 'string' ? card.detail_url : ''
192
- const id = new URLSearchParams(detail.includes('?') ? detail.slice(detail.indexOf('?') + 1) : '').get('id') ?? ''
193
- if (id.startsWith('model_gateway:')) ids.add(id.slice('model_gateway:'.length))
194
- }
195
- return ids.size > 0 ? ids : null
196
- } catch {
197
- return null
198
- }
199
- }
200
-
201
- /**
202
- * AMD TokenFactory 网关免费标注:官网目录 public_free 区块内的模型 → free:true
203
- * (与官网口径同源);/models 里定价全 0 的条目即便不在目录里也保留免费;
204
- * 目录拉不到时回退整目录 free:true。定价文本一律剔除——那是额度消耗速率,
205
- * 透出「$0.035/M」会与「免费」并排误导。
206
- */
207
- async function markAmdTokenFactoryFree(baseUrl, models) {
208
- const freeIds = await amdTokenFactoryFreeIds({ baseUrl })
209
- return (Array.isArray(models) ? models : []).map(m => {
210
- if (!m || typeof m.id !== 'string') return m
211
- const free = freeIds ? (freeIds.has(m.id) || m.free === true) : true
212
- const { price, priceOutput, ...rest } = m
213
- return { ...rest, free }
214
- })
215
- }
216
-
217
- /** 拉取自定义提供商清单(聚合渠道按国内厂商旗舰版 / flash 过滤、免费模型不过滤;AMD TokenFactory 按官网目录标注免费)。 */
218
- export async function discoverProviderModels(provider, options) {
219
- const models = await discoverModels(provider, options)
220
- const filtered = filterAggregatorModels(provider?.baseUrl, models)
221
- return isAmdTokenFactory(provider?.baseUrl) ? await markAmdTokenFactoryFree(provider?.baseUrl, filtered) : filtered
222
- }
223
-
224
- /** 流尾 usage 归一:个别上游省略 total_tokens,按输入+输出补齐。 */
225
- function normalizeUsage(usage) {
226
- const prompt = typeof usage.prompt_tokens === 'number' ? usage.prompt_tokens : undefined
227
- const completion = typeof usage.completion_tokens === 'number' ? usage.completion_tokens : undefined
228
- if (typeof usage.total_tokens === 'number' || (prompt === undefined && completion === undefined)) return usage
229
- return { ...usage, total_tokens: (prompt ?? 0) + (completion ?? 0) }
230
- }
231
-
232
- /**
233
- * 转发一轮对话(OpenAI chat 格式直通,不做转换)。
234
- * slot 可选:传入时用 slot.apiKey 做鉴权(槽轮换调度),未传时回落 provider.apiKey。
235
- * 流式恒注入 stream_options.include_usage(否则上游不吐流尾 usage 帧,
236
- * 最近请求记账拿不到输入/输出 token);尾帧 usage 随返回值带给记账方。
237
- */
238
- export async function openAiCompatCompletion(provider, body, { slot, signal, onData, headerTimeoutMs = 60000, idleTimeoutMs = 120000 } = {}) {
239
- const base = String(provider.baseUrl ?? '').replace(/\/+$/, '')
240
- const apiKey = slot?.apiKey ?? provider.apiKey ?? ''
241
- const stream = body.stream === true
242
- const headers = { 'content-type': 'application/json', accept: stream ? 'text/event-stream' : 'application/json' }
243
- if (apiKey) headers.authorization = `Bearer ${apiKey}`
244
- if (provider.extraHeaders && typeof provider.extraHeaders === 'object') {
245
- for (const [k, v] of Object.entries(provider.extraHeaders)) {
246
- if (typeof v === 'string' && v !== '') headers[k.toLowerCase()] = v
247
- }
248
- }
249
- // 流式注入 include_usage:调用方已带 stream_options 时保留其余字段,强制打开 usage 帧
250
- const request = stream
251
- ? {
252
- ...body,
253
- stream_options: {
254
- ...(body.stream_options !== null && typeof body.stream_options === 'object' ? body.stream_options : {}),
255
- include_usage: true,
256
- },
257
- }
258
- : body
259
-
260
- const response = await httpFetch(`${base}/chat/completions`, {
261
- method: 'POST',
262
- headers,
263
- body: JSON.stringify(request),
264
- redirect: 'error',
265
- signal,
266
- }, headerTimeoutMs)
267
-
268
- if (!response.ok) {
269
- const text = await readBodyText(response, 15000).catch(() => '')
270
- const failure = classifyFailure(response.status, text)
271
- // 换 key 可能解决的失败(认证/额度/限流)标记 rotate,由调度方换下一槽重试;
272
- // 只在响应头阶段标记 —— 流一旦开始就不再换号(避免重复推送已发出的帧)。
273
- if (failure.kind === 'auth' || failure.kind === 'quota' || failure.kind === 'rate_limit') failure.rotate = true
274
- const ra = retryAfterMs(response.headers)
275
- if (ra) failure.cooldownMs = ra
276
- throw failure
277
- }
278
- if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30000, message: '上游返回空响应体' }
279
-
280
- if (!stream) {
281
- let text
282
- try {
283
- text = await readBodyText(response, 300000, signal)
284
- } catch (error) {
285
- throw classifyThrownError(error)
286
- }
287
- let payload
288
- try { payload = JSON.parse(text) } catch {
289
- throw { kind: 'server', retryable: true, cooldownMs: 30000, message: `非 JSON 响应: ${text.slice(0, 200)}` }
290
- }
291
- if (payload.error) throw classifyFailure(response.status, text)
292
- return { status: response.status, json: payload }
293
- }
294
-
295
- // 流式:逐帧转发给客户端,同时记录流尾 usage 帧(choices 为空的收尾帧)
296
- let lastUsage = null
297
- try {
298
- await readSseData(response.body, data => {
299
- onData?.(data)
300
- try {
301
- const chunk = JSON.parse(data)
302
- if (chunk && typeof chunk === 'object' && chunk.usage) lastUsage = chunk.usage
303
- } catch { /* 非 JSON 帧忽略 */ }
304
- }, signal, { idleTimeoutMs })
305
- } catch (error) {
306
- // 上游中途关连接(terminated / ECONNRESET)或流空闲超时:归类后交给组路由冷却/换候选
307
- throw classifyThrownError(error)
308
- }
309
- return lastUsage
310
- ? { status: response.status, stream: true, usage: normalizeUsage(lastUsage) }
311
- : { status: response.status, stream: true }
312
- }
1
+ /**
2
+ * 自定义 OpenAI 兼容提供商:baseUrl + apiKey + 模型清单(可自动发现)。
3
+ * 覆盖 OpenRouter / SiliconFlow / 自建 vLLM / 各种中转站等一切
4
+ * 「POST {base}/chat/completions、GET {base}/models」形态的通道。
5
+ *
6
+ * 账号槽(与 opencode.js 一致的槽轮换语义):
7
+ * 每个提供商持有启用槽序列,请求按模型记忆的游标轮换槽;失败时携带
8
+ * rotate:true 的错误(401/403/429/quota/rate_limit)换下一个槽重试。
9
+ * 旧格式单 apiKey 在读取时归一成单槽(见 listSlots)。
10
+ */
11
+
12
+ import { httpFetch, readSseData, readBodyText, classifyFailure, classifyThrownError, retryAfterMs } from '../util.js'
13
+
14
+ /**
15
+ * 组装账号槽序列(与 opencode.js listSlots 相同的归一语义):
16
+ * - provider.slots 非空数组时取启用的槽(key 为空白的条目剔除);
17
+ * - 否则旧格式单 apiKey 归一成单槽;
18
+ * - 完全无 key(本地 vLLM 等免鉴权端点)→ 单个空 key 槽(请求不带 authorization 头)。
19
+ * 因此返回值恒 ≥ 1 条。
20
+ */
21
+ export function listSlots(provider) {
22
+ const slots = Array.isArray(provider?.slots) ? provider.slots : []
23
+ const enabled = slots
24
+ .filter(slot => slot && slot.enabled !== false && typeof slot.apiKey === 'string' && slot.apiKey !== '')
25
+ .map(slot => ({
26
+ id: typeof slot.id === 'string' && slot.id !== '' ? slot.id : 'default',
27
+ label: typeof slot.label === 'string' && slot.label !== '' ? slot.label : '账号槽',
28
+ apiKey: slot.apiKey,
29
+ }))
30
+ if (enabled.length > 0) return enabled
31
+ const legacy = typeof provider?.apiKey === 'string' ? provider.apiKey : ''
32
+ return [{ id: 'default', label: '默认通道', apiKey: legacy }]
33
+ }
34
+
35
+ /** 每 token 美元单价 → 每百万 token 单价文本(`"0.000002"` → `$2/M`)。0 视为未定价(返回空串)。 */
36
+ function priceLabel(perToken) {
37
+ const n = typeof perToken === 'number' ? perToken : Number.parseFloat(perToken)
38
+ if (!Number.isFinite(n) || n <= 0) return ''
39
+ const perMillion = n * 1_000_000
40
+ const text = perMillion >= 1 ? String(Math.round(perMillion * 100) / 100) : String(Math.round(perMillion * 1000) / 1000)
41
+ return `$${text}/M`
42
+ }
43
+
44
+ /**
45
+ * 自动发现模型(GET {base}/models)。返回 [{id,name,contextWindow,price?,priceOutput?,free?}]。
46
+ * 上游带 `pricing.prompt` / `pricing.completion`(USD/token 字符串,OpenRouter 形态)时
47
+ * 附带每百万 token 单价;定价全 0 或 id 以 `:free` 结尾视为免费模型。
48
+ */
49
+ export async function discoverModels(provider, { signal } = {}) {
50
+ const base = String(provider.baseUrl ?? '').replace(/\/+$/, '')
51
+ const headers = { accept: 'application/json' }
52
+ if (provider.apiKey) headers.authorization = `Bearer ${provider.apiKey}`
53
+ const response = await httpFetch(`${base}/models`, { headers, redirect: 'error', signal }, 15000)
54
+ const text = await readBodyText(response, 15000)
55
+ if (!response.ok) throw classifyFailure(response.status, text)
56
+ let payload
57
+ try { payload = JSON.parse(text) } catch { throw classifyFailure(response.status, text) }
58
+ const rows = Array.isArray(payload) ? payload : Array.isArray(payload.data) ? payload.data : []
59
+ return rows
60
+ .filter(row => row && typeof row.id === 'string' && row.id !== '')
61
+ .map(row => {
62
+ const prompt = typeof row.pricing?.prompt === 'number' ? row.pricing.prompt : Number.parseFloat(row.pricing?.prompt)
63
+ const completion = typeof row.pricing?.completion === 'number' ? row.pricing.completion : Number.parseFloat(row.pricing?.completion)
64
+ // 上游给了定价清单(含全 0 的免费档)才算「有定价」,缺字段 / 非数值视为无定价
65
+ const hasPricing = Number.isFinite(prompt) || Number.isFinite(completion)
66
+ const price = priceLabel(prompt)
67
+ const priceOutput = priceLabel(completion)
68
+ // 免费判定:定价全为 0(OpenRouter 免费档)或 id 带 :free 后缀(-1 等变量价不算免费)
69
+ const free = hasPricing
70
+ ? (prompt === 0 && completion === 0) || /:free$/i.test(row.id)
71
+ : undefined
72
+ return {
73
+ id: row.id,
74
+ name: typeof row.name === 'string' && row.name !== '' ? row.name : row.id,
75
+ contextWindow: typeof row.context_length === 'number' ? row.context_length
76
+ : typeof row.context_window === 'number' ? row.context_window
77
+ : typeof row.context_window?.total === 'number' ? row.context_window.total
78
+ : null,
79
+ ...(hasPricing ? { ...(price ? { price } : {}), ...(priceOutput ? { priceOutput } : {}) } : {}),
80
+ ...(free !== undefined ? { free } : {}),
81
+ }
82
+ })
83
+ }
84
+
85
+ /**
86
+ * 聚合渠道识别(按 baseUrl 主机):魔搭 ModelScope / OpenRouter / NVIDIA NIM。
87
+ * 这三个渠道的 /models 里混有大量海外模型,付费模型只保留国内厂商的旗舰版与 flash 版;
88
+ * 免费模型不过滤、全部保留——OpenRouter 的免费池大量来自海外厂商,按国内白名单
89
+ * 过滤会把它们挡在自动选用之外(免费判定见 discoverModels 的 free 字段)。
90
+ */
91
+ export function aggregatorKind(baseUrl) {
92
+ const url = String(baseUrl ?? '').toLowerCase()
93
+ if (url.includes('modelscope')) return 'modelscope'
94
+ if (url.includes('openrouter')) return 'openrouter'
95
+ if (url.includes('nvidia')) return 'nvidia'
96
+ return ''
97
+ }
98
+
99
+ /** 国内模型提供商的模型 id 前缀(`/` 前一段,小写)。 */
100
+ const DOMESTIC_PROVIDER_PREFIXES = new Set([
101
+ 'deepseek', 'deepseek-ai', 'deepseekai',
102
+ 'qwen', 'qwenlm', 'alibaba', 'aliyun', 'tongyi',
103
+ 'zhipuai', 'zhipu', 'z-ai', 'thudm', 'glm',
104
+ 'moonshotai', 'moonshot', 'moonshot-ai', 'kimi',
105
+ 'minimax', 'minimaxai', 'minimax-ai',
106
+ 'stepfun', 'stepfun-ai',
107
+ '01-ai', '01ai', 'yi', 'lingyiwanwu',
108
+ 'baichuan', 'internlm', 'intern-ai', 'shanghai-ai-lab', 'opengvlab',
109
+ 'sensenova', 'sensetime', 'baidu', 'ernie',
110
+ 'bytedance', 'bytedance-seed', 'doubao', 'seed',
111
+ 'tencent', 'hunyuan', 'xiaomi', 'mimo',
112
+ 'longcat', 'meituan', 'modelbest', 'openbmb', 'minicpm',
113
+ 'skywork', 'kunlun', 'xverse', 'rednote', 'dots-studio', 'dots',
114
+ 'inclusionai', 'inclusion-ai', 'bailing', 'antgroup', 'ant',
115
+ 'huawei', 'pangu', 'iflytek', 'spark', 'xingchen-agi', 'baai', 'teleai',
116
+ ])
117
+
118
+ /** 非旗舰档位关键词(低配 / 嵌入 / 审核 / 多模态工具模型,命中即排除)。 */
119
+ const NON_FLAGSHIP_RE = /(?:^|[-_.])(?:lite|mini|tiny|small|nano|turbo|air|light|base|micro|edge|mobile|embed|embedding|rerank|guard|safety|moderation|whisper|tts|asr|audio|image|video|ocr|diffusion)(?:[-_.]|$)/i
120
+ /** 提取参数量(B):`a3b` 这类 MoE 激活量不计入。 */
121
+ const PARAM_SIZE_RE = /(?<![a-z0-9.])(\d+(?:\.\d+)?)b(?![a-z0-9])/gi
122
+ /** 带参数量标注的模型,达到 30B 才算旗舰(27B 等中小尺寸不算)。 */
123
+ const FLAGSHIP_MIN_B = 30
124
+ /** flash 档位:模型名含 flash(含 flash-lite / flash-next 等衍生)。 */
125
+ const FLASH_RE = /flash/i
126
+
127
+ /** 模型名部分(去掉 `提供商/` 前缀)。 */
128
+ const modelBaseName = id => {
129
+ const slash = id.indexOf('/')
130
+ return slash > 0 ? id.slice(slash + 1) : ''
131
+ }
132
+
133
+ /**
134
+ * 聚合渠道的单模型过滤:
135
+ * - 只保留国内模型提供商的模型(id 前缀白名单);
136
+ * - 旗舰版(非低配档位;带参数量标注的需 ≥30B)或 flash 版本。
137
+ */
138
+ export function isAggregatorModelAllowed(model) {
139
+ const id = typeof model?.id === 'string' ? model.id : ''
140
+ const slash = id.indexOf('/')
141
+ if (slash <= 0) return false
142
+ if (!DOMESTIC_PROVIDER_PREFIXES.has(id.slice(0, slash).toLowerCase())) return false
143
+ const base = modelBaseName(id)
144
+ if (FLASH_RE.test(base)) return true
145
+ if (NON_FLAGSHIP_RE.test(base)) return false
146
+ const sizes = [...base.matchAll(PARAM_SIZE_RE)].map(m => Number(m[1])).filter(Number.isFinite)
147
+ return sizes.length === 0 || Math.max(...sizes) >= FLAGSHIP_MIN_B
148
+ }
149
+
150
+ /**
151
+ * 按 baseUrl 过滤聚合渠道清单;非聚合渠道原样返回。
152
+ * 免费模型(定价全 0 / :free 后缀,见 discoverModels)豁免国内白名单过滤全部保留,
153
+ * 供免费模型扫描自动选用——选用清单的免费部分随每轮探测整体刷新为最新免费全集。
154
+ * 三个聚合渠道里只有 OpenRouter 上游带定价,实际生效面即 OpenRouter。
155
+ */
156
+ export function filterAggregatorModels(baseUrl, models) {
157
+ if (aggregatorKind(baseUrl) === '') return models
158
+ return (Array.isArray(models) ? models : []).filter(m => m?.free === true || isAggregatorModelAllowed(m))
159
+ }
160
+
161
+ /**
162
+ * AMD TokenFactory 网关识别(按 baseUrl 主机)。developer.amd.com.cn 的 OpenAI 兼容
163
+ * 网关在 /models 里给几乎全部模型挂了极小的 per-token「pricing」(如 3.5e-8)——
164
+ * 那是 TokenFactory 免费额度内的消耗速率,不是 USD 计费价(官网卡片明示
165
+ * 「Free to use. Points show relative usage—not a charge.」),且模型记录的
166
+ * free 布尔字段恒为 false,不能作为免费依据。
167
+ */
168
+ export function isAmdTokenFactory(baseUrl) {
169
+ try { return new URL(String(baseUrl ?? '')).hostname === 'developer.amd.com.cn' } catch { return false }
170
+ }
171
+
172
+ /**
173
+ * AMD TokenFactory 官网目录:public_free 区块(「Public Free Model APIs」)的模型 id 集合。
174
+ * 官网 tokenfactory 页的 Free 徽标依据就是目录归属(卡片详情里
175
+ * token_factory.section = "public_free" / display_status = "free_endpoint"),
176
+ * 与 /models 的 pricing 无关。此处取同一接口 /radeon/api/tokenfactory/bootstrap
177
+ * (SPA 内部接口,需 Origin/Referer),解析各卡片 detail_url 的 model id。
178
+ * 返回 null = 目录拉不到(接口改版/风控),调用方回退整目录免费。
179
+ */
180
+ async function amdTokenFactoryFreeIds(provider) {
181
+ try {
182
+ const origin = new URL(String(provider?.baseUrl ?? '')).origin
183
+ const url = `${origin}/radeon/api/tokenfactory/bootstrap?directory=true`
184
+ const headers = { accept: 'application/json', origin, referer: `${origin}/radeon/tokenfactory` }
185
+ const response = await httpFetch(url, { headers, redirect: 'error' }, 15000)
186
+ const text = await readBodyText(response, 15000)
187
+ if (!response.ok) return null
188
+ const payload = JSON.parse(text)
189
+ const ids = new Set()
190
+ for (const card of Array.isArray(payload?.cards) ? payload.cards : []) {
191
+ const detail = typeof card?.detail_url === 'string' ? card.detail_url : ''
192
+ const id = new URLSearchParams(detail.includes('?') ? detail.slice(detail.indexOf('?') + 1) : '').get('id') ?? ''
193
+ if (id.startsWith('model_gateway:')) ids.add(id.slice('model_gateway:'.length))
194
+ }
195
+ return ids.size > 0 ? ids : null
196
+ } catch {
197
+ return null
198
+ }
199
+ }
200
+
201
+ /**
202
+ * AMD TokenFactory 网关免费标注:官网目录 public_free 区块内的模型 → free:true
203
+ * (与官网口径同源);/models 里定价全 0 的条目即便不在目录里也保留免费;
204
+ * 目录拉不到时回退整目录 free:true。定价文本一律剔除——那是额度消耗速率,
205
+ * 透出「$0.035/M」会与「免费」并排误导。
206
+ */
207
+ async function markAmdTokenFactoryFree(baseUrl, models) {
208
+ const freeIds = await amdTokenFactoryFreeIds({ baseUrl })
209
+ return (Array.isArray(models) ? models : []).map(m => {
210
+ if (!m || typeof m.id !== 'string') return m
211
+ const free = freeIds ? (freeIds.has(m.id) || m.free === true) : true
212
+ const { price, priceOutput, ...rest } = m
213
+ return { ...rest, free }
214
+ })
215
+ }
216
+
217
+ /** 拉取自定义提供商清单(聚合渠道按国内厂商旗舰版 / flash 过滤、免费模型不过滤;AMD TokenFactory 按官网目录标注免费)。 */
218
+ export async function discoverProviderModels(provider, options) {
219
+ const models = await discoverModels(provider, options)
220
+ const filtered = filterAggregatorModels(provider?.baseUrl, models)
221
+ return isAmdTokenFactory(provider?.baseUrl) ? await markAmdTokenFactoryFree(provider?.baseUrl, filtered) : filtered
222
+ }
223
+
224
+ /** 流尾 usage 归一:个别上游省略 total_tokens,按输入+输出补齐。 */
225
+ function normalizeUsage(usage) {
226
+ const prompt = typeof usage.prompt_tokens === 'number' ? usage.prompt_tokens : undefined
227
+ const completion = typeof usage.completion_tokens === 'number' ? usage.completion_tokens : undefined
228
+ if (typeof usage.total_tokens === 'number' || (prompt === undefined && completion === undefined)) return usage
229
+ return { ...usage, total_tokens: (prompt ?? 0) + (completion ?? 0) }
230
+ }
231
+
232
+ /**
233
+ * 转发一轮对话(OpenAI chat 格式直通,不做转换)。
234
+ * slot 可选:传入时用 slot.apiKey 做鉴权(槽轮换调度),未传时回落 provider.apiKey。
235
+ * 流式恒注入 stream_options.include_usage(否则上游不吐流尾 usage 帧,
236
+ * 最近请求记账拿不到输入/输出 token);尾帧 usage 随返回值带给记账方。
237
+ */
238
+ export async function openAiCompatCompletion(provider, body, { slot, signal, onData, headerTimeoutMs = 60000, idleTimeoutMs = 120000 } = {}) {
239
+ const base = String(provider.baseUrl ?? '').replace(/\/+$/, '')
240
+ const apiKey = slot?.apiKey ?? provider.apiKey ?? ''
241
+ const stream = body.stream === true
242
+ const headers = { 'content-type': 'application/json', accept: stream ? 'text/event-stream' : 'application/json' }
243
+ if (apiKey) headers.authorization = `Bearer ${apiKey}`
244
+ if (provider.extraHeaders && typeof provider.extraHeaders === 'object') {
245
+ for (const [k, v] of Object.entries(provider.extraHeaders)) {
246
+ if (typeof v === 'string' && v !== '') headers[k.toLowerCase()] = v
247
+ }
248
+ }
249
+ // 流式注入 include_usage:调用方已带 stream_options 时保留其余字段,强制打开 usage 帧
250
+ const request = stream
251
+ ? {
252
+ ...body,
253
+ stream_options: {
254
+ ...(body.stream_options !== null && typeof body.stream_options === 'object' ? body.stream_options : {}),
255
+ include_usage: true,
256
+ },
257
+ }
258
+ : body
259
+
260
+ const response = await httpFetch(`${base}/chat/completions`, {
261
+ method: 'POST',
262
+ headers,
263
+ body: JSON.stringify(request),
264
+ redirect: 'error',
265
+ signal,
266
+ }, headerTimeoutMs)
267
+
268
+ if (!response.ok) {
269
+ const text = await readBodyText(response, 15000).catch(() => '')
270
+ const failure = classifyFailure(response.status, text)
271
+ // 换 key 可能解决的失败(认证/额度/限流)标记 rotate,由调度方换下一槽重试;
272
+ // 只在响应头阶段标记 —— 流一旦开始就不再换号(避免重复推送已发出的帧)。
273
+ if (failure.kind === 'auth' || failure.kind === 'quota' || failure.kind === 'rate_limit') failure.rotate = true
274
+ const ra = retryAfterMs(response.headers)
275
+ if (ra) failure.cooldownMs = ra
276
+ throw failure
277
+ }
278
+ if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30000, message: '上游返回空响应体' }
279
+
280
+ if (!stream) {
281
+ let text
282
+ try {
283
+ text = await readBodyText(response, 300000, signal)
284
+ } catch (error) {
285
+ throw classifyThrownError(error)
286
+ }
287
+ let payload
288
+ try { payload = JSON.parse(text) } catch {
289
+ throw { kind: 'server', retryable: true, cooldownMs: 30000, message: `非 JSON 响应: ${text.slice(0, 200)}` }
290
+ }
291
+ if (payload.error) throw classifyFailure(response.status, text)
292
+ return { status: response.status, json: payload }
293
+ }
294
+
295
+ // 流式:逐帧转发给客户端,同时记录流尾 usage 帧(choices 为空的收尾帧)
296
+ let lastUsage = null
297
+ try {
298
+ await readSseData(response.body, data => {
299
+ onData?.(data)
300
+ try {
301
+ const chunk = JSON.parse(data)
302
+ if (chunk && typeof chunk === 'object' && chunk.usage) lastUsage = chunk.usage
303
+ } catch { /* 非 JSON 帧忽略 */ }
304
+ }, signal, { idleTimeoutMs })
305
+ } catch (error) {
306
+ // 上游中途关连接(terminated / ECONNRESET)或流空闲超时:归类后交给组路由冷却/换候选
307
+ throw classifyThrownError(error)
308
+ }
309
+ return lastUsage
310
+ ? { status: response.status, stream: true, usage: normalizeUsage(lastUsage) }
311
+ : { status: response.status, stream: true }
312
+ }