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
@@ -1,474 +1,474 @@
1
- /**
2
- * MiMo (小米) 渠道 —— oauth-callback 浏览器授权登录。
3
- *
4
- * 协议要点:
5
- * - 对话:{baseUrl}/chat/completions(OpenAI 兼容,baseUrl 默认 https://api.xiaomimimo.com/v1)
6
- * 认证:`Bearer {sk}`,附加 `X-Mimo-Source: mimocode-cli`(客户端来源标识)
7
- * - 登录:浏览器授权 + 本地回调(X25519 + AES-256-GCM 混合加密)
8
- * ① 本地生成 X25519 密钥对(spki/pkcs8 der),公钥 base64url 作为 `pk`
9
- * ② 起本地 http 服务(随机端口)→ redirect_uri = http://localhost:{port}/
10
- * ③ 授权页:{platform}/authorize?pk=&redirect_uri=&kn=mimocode&key_name=
11
- * ④ 授权完成后浏览器跳回本地回调,query `u` 即密文:
12
- * ephemeralPub(32) + nonce(12) + ciphertext + tag(16)
13
- * 用私钥 ECDH → sha256(sharedSecret) → AES-256-GCM 解密 → { sk?, uid, url? }
14
- * ⑤ 手工兜底:redirect_uri 换成 {platform}/authorize/code/callback,
15
- * 页面展示一段 code,用户粘贴回 OMR(同样用 `u` 解密)
16
- * - 凭据:{ sk, uid, base_url? };sk 为空时说明该账号无 API key(仅 uid)
17
- * - 模型:只认远端 {base}/models 实时清单(拉不到即报错,不使用内置兜底表);
18
- * 上游只返回 id/object/owned_by,倍率按官方定价文档口径本地折算
19
- * - TTS(mimo-v2.5-tts*):复用 /chat/completions,但必须带 assistant 消息承载待合成文本
20
- * 并传 audio 参数;这里自动把普通聊天请求改写为合法 TTS 请求(非流式返回完整音频)
21
- */
22
-
23
- import { createServer } from 'node:http'
24
- import { createHash, createPrivateKey, createPublicKey, diffieHellman, generateKeyPairSync, randomBytes, createDecipheriv } from 'node:crypto'
25
- import { httpFetch, readBodyText, readSseData, mergeSseChunks } from '../util.js'
26
-
27
- // ── 产品常量 ────────────────────────────────────────────────────────────────
28
-
29
- const DEFAULT_PLATFORM_URL = 'https://platform.xiaomimimo.com'
30
- const DEFAULT_BASE_URL = 'https://api.xiaomimimo.com/v1'
31
-
32
- const AUTHORIZE_PATH = '/authorize'
33
- const CODE_CALLBACK_PATH = '/authorize/code/callback'
34
- const CHAT_PATH = '/chat/completions'
35
- const MODELS_PATH = '/models'
36
-
37
- const KEY_NAME = 'mimocode'
38
- const SOURCE_HEADER = 'mimocode-cli'
39
-
40
- const LOGIN_TIMEOUT_MS = 5 * 60_000 // 5 分钟
41
- const REQUEST_TIMEOUT_MS = 30_000
42
- const MODELS_TIMEOUT_MS = 20_000
43
- const BODY_READ_TIMEOUT_MS = 15_000
44
- const MAX_OUTPUT_TOKENS = 131_072 // 输出 token 上限(官方 128k 级)
45
- const SERVER_SHUTDOWN_GRACE_MS = 500
46
-
47
- /**
48
- * 模型消耗倍率(官方按量计费单价折算,基准 mimo-v2.6-flash 输入未命中 ¥1.00 = 1):
49
- * mimo-v2.6-flash ¥1.00 / ¥2.00 → 1
50
- * mimo-v2.6-pro ¥3.00 / ¥6.00 → 3
51
- * mimo-v2.6-pro-ultraspeed ¥30.00 / ¥60.00 → 30
52
- * TTS 系列限时免费(不消耗 Credits)→ 0
53
- * 上游 /models 只返回 id/object/owned_by,不含价格/倍率/上下文/模态字段,
54
- * 因此倍率只能按文档口径折算;只补 rate,不参与模型清单,清单仍只认实时 /models。
55
- * ASR 按音频时长计费(¥0.5/小时),没有 token 倍率,不补 rate。
56
- */
57
- const MODEL_RATES = {
58
- 'mimo-v2.6-flash': 1,
59
- 'mimo-v2.6-pro': 3,
60
- 'mimo-v2.6-pro-ultraspeed': 30,
61
- 'mimo-v2.5-tts': 0,
62
- 'mimo-v2.5-tts-voiceclone': 0,
63
- 'mimo-v2.5-tts-voicedesign': 0,
64
- }
65
-
66
- export const meta = { id: 'mimo', label: 'MiMo (小米)', loginMode: 'oauth-callback' }
67
-
68
- // ── 小工具 ──────────────────────────────────────────────────────────────────
69
-
70
- function readStringField(source, key) {
71
- const value = source?.[key]
72
- if (typeof value === 'string' && value.trim().length > 0) return value.trim()
73
- return ''
74
- }
75
-
76
- function platformUrl() {
77
- const override = readStringField(process.env, 'MIMO_PLATFORM_URL')
78
- return (override || DEFAULT_PLATFORM_URL).replace(/\/+$/, '')
79
- }
80
-
81
- /** 由凭据推导 API 基址(登录返回的 url 可覆盖默认)。 */
82
- function resolveBaseUrl(credential) {
83
- const candidate = readStringField(credential, 'base_url') || readStringField(credential, 'baseUrl')
84
- const base = candidate || DEFAULT_BASE_URL
85
- return base.replace(/\/+$/, '')
86
- }
87
-
88
- // ── 登录加密(X25519 + AES-256-GCM)────────────────────────────────────────
89
-
90
- /** 生成 X25519 密钥对:公钥 base64url(SPKI der),私钥 PKCS8 der。 */
91
- function generateKeyPair() {
92
- const pair = generateKeyPairSync('x25519', {
93
- publicKeyEncoding: { type: 'spki', format: 'der' },
94
- privateKeyEncoding: { type: 'pkcs8', format: 'der' },
95
- })
96
- return { publicKey: Buffer.from(pair.publicKey).toString('base64url'), privateKeyDer: pair.privateKey }
97
- }
98
-
99
- /** X25519 SPKI der 前缀:SEQUENCE(42) + SEQUENCE(5, id-X25519) + BIT STRING(33, 0x00 + 32字节)。 */
100
- const X25519_SPKI_PREFIX = Buffer.from('302a300506032b656e032100', 'hex')
101
-
102
- /**
103
- * 解密授权回调密文:
104
- * ephemeralPublicKey(32) + nonce(12) + ciphertext + tag(16)
105
- * 返回 { sk?, uid, url? }。
106
- */
107
- function decrypt(privateKeyDer, encryptedBase64Url) {
108
- const encrypted = Buffer.from(String(encryptedBase64Url).trim(), 'base64url')
109
- if (encrypted.length < 32 + 12 + 16) throw new Error('授权数据长度不足')
110
- const ephemeralPub = encrypted.subarray(0, 32)
111
- const nonce = encrypted.subarray(32, 44)
112
- const ciphertextAndTag = encrypted.subarray(44)
113
- const tag = ciphertextAndTag.subarray(ciphertextAndTag.length - 16)
114
- const ciphertext = ciphertextAndTag.subarray(0, ciphertextAndTag.length - 16)
115
-
116
- const privateKey = createPrivateKey({ key: privateKeyDer, format: 'der', type: 'pkcs8' })
117
- // 只需 32 字节裸公钥,手工拼成 SPKI der 后交给 createPublicKey
118
- const ephemeralPublicKey = createPublicKey({
119
- key: Buffer.concat([X25519_SPKI_PREFIX, ephemeralPub]),
120
- format: 'der',
121
- type: 'spki',
122
- })
123
- const sharedSecret = diffieHellman({ privateKey, publicKey: ephemeralPublicKey })
124
- const derivedKey = createHash('sha256').update(sharedSecret).digest()
125
-
126
- const decipher = createDecipheriv('aes-256-gcm', derivedKey, nonce)
127
- decipher.setAuthTag(tag)
128
- const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()])
129
- const result = JSON.parse(decrypted.toString('utf-8'))
130
- if (result === null || typeof result !== 'object') throw new Error('授权数据格式错误')
131
- return result
132
- }
133
-
134
- /** 授权页 URL。key_name 仅用于平台侧展示密钥名。 */
135
- function buildAuthorizeUrl(publicKey, redirectUri) {
136
- const params = new URLSearchParams({
137
- pk: publicKey,
138
- redirect_uri: redirectUri,
139
- kn: KEY_NAME,
140
- key_name: `omr-${randomBytes(4).toString('hex')}`,
141
- })
142
- return `${platformUrl()}${AUTHORIZE_PATH}?${params.toString()}`
143
- }
144
-
145
- /** 解密结果 → 持久化凭据。 */
146
- function credentialFromResult(result) {
147
- const uid = readStringField(result, 'uid')
148
- const sk = readStringField(result, 'sk')
149
- const url = readStringField(result, 'url')
150
- if (!sk) throw new Error('授权结果缺少 API key(sk),该小米账号可能未开通 MiMo 服务')
151
- return {
152
- sk,
153
- uid,
154
- ...(url ? { base_url: url.replace(/\/+$/, '') } : {}),
155
- }
156
- }
157
-
158
- // ── 登录(浏览器授权 + 本地回调)───────────────────────────────────────────
159
-
160
- /**
161
- * 启动登录。返回 `{ loginUrl, manualUrl, loginUrlReady, promise, cancel }`:
162
- * - loginUrl:带本地回调的授权页(浏览器授权完成后自动回到本机)
163
- * - manualUrl:手工兜底授权页(页面展示 code,用户粘贴到 OMR)
164
- * - promise:解析为凭据对象;失败/取消 reject
165
- */
166
- export function startLogin({ port } = {}) {
167
- const { publicKey, privateKeyDer } = generateKeyPair()
168
-
169
- // 回调端口在 listen 后才确定,授权 URL 异步就绪
170
- let resolveLoginUrl
171
- let rejectLoginUrl
172
- const loginUrlReady = new Promise((resolve, reject) => { resolveLoginUrl = resolve; rejectLoginUrl = reject })
173
- loginUrlReady.catch(() => {})
174
-
175
- let settle
176
- let settled = false
177
- const promise = new Promise((resolve, reject) => {
178
- const finish = (fn, value) => {
179
- if (settled) return
180
- settled = true
181
- clearTimeout(timer)
182
- try { server.close() } catch { /* 已关闭 */ }
183
- try { server.closeAllConnections?.() } catch { /* 旧版本 Node 无此方法 */ }
184
- fn(value)
185
- }
186
- settle = { resolve: v => finish(resolve, v), reject: e => finish(reject, e) }
187
-
188
- const timer = setTimeout(() => {
189
- rejectLoginUrl?.(new Error('登录等待已超时'))
190
- settle.reject(new Error('登录等待已超时,请重新发起登录'))
191
- }, LOGIN_TIMEOUT_MS)
192
- timer.unref?.()
193
-
194
- const server = createServer((request, response) => {
195
- const url = new URL(request.url ?? '/', 'http://localhost')
196
- const encrypted = url.searchParams.get('u')
197
- if (!encrypted) {
198
- response.writeHead(302, { Location: `${platformUrl()}${AUTHORIZE_PATH}/callback?status=error&message=missing_data` }).end()
199
- return
200
- }
201
- let credential
202
- try {
203
- credential = credentialFromResult(decrypt(privateKeyDer, encrypted))
204
- } catch (error) {
205
- response.writeHead(302, { Location: `${platformUrl()}${AUTHORIZE_PATH}/callback?status=error&message=decrypt_failed` }).end()
206
- settle.reject(error instanceof Error ? error : new Error(String(error)))
207
- return
208
- }
209
- response.writeHead(302, { Location: `${platformUrl()}${AUTHORIZE_PATH}/callback?status=success` }).end()
210
- // 先让响应写完再关闭监听,避免浏览器看到连接被重置
211
- setTimeout(() => settle.resolve(credential), SERVER_SHUTDOWN_GRACE_MS)
212
- })
213
- server.on('error', error => settle.reject(error))
214
-
215
- server.listen(port || 0, '127.0.0.1', () => {
216
- const address = server.address()
217
- const assigned = typeof address === 'object' && address ? address.port : 0
218
- if (assigned > 0) resolveLoginUrl?.(buildAuthorizeUrl(publicKey, `http://localhost:${assigned}/`))
219
- else rejectLoginUrl?.(new Error('无法获取本地回调端口'))
220
- })
221
- })
222
- promise.catch(() => {})
223
-
224
- return {
225
- loginUrl: '',
226
- loginUrlReady,
227
- manualUrl: buildAuthorizeUrl(publicKey, `${platformUrl()}${CODE_CALLBACK_PATH}`),
228
- promise,
229
- cancel: () => settle?.reject(new Error('登录已取消')),
230
- }
231
- }
232
-
233
- /**
234
- * 手动粘贴凭据的规范化。
235
- * 授权密文只能由 startLogin 持有的私钥解密,所以这里只接受凭据 JSON
236
- * ({ sk, uid, base_url? },例如从别处导出的 ~/.mimo/auth.json 内容)。
237
- */
238
- export function normalizeCredential(raw) {
239
- let value = raw
240
- if (typeof value === 'string') {
241
- const text = raw.trim()
242
- if (text === '') throw new Error('凭据不能为空')
243
- if (text.startsWith('{')) {
244
- try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
245
- } else {
246
- throw new Error('请粘贴凭据 JSON({ sk, uid }),或点「添加账号」走浏览器授权')
247
- }
248
- }
249
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
250
- throw new Error('凭据必须是 JSON 对象')
251
- }
252
- const sk = readStringField(value, 'sk') || readStringField(value, 'key') || readStringField(value, 'api_key')
253
- if (!sk) throw new Error('凭据缺少 sk(API key)')
254
- const uid = readStringField(value, 'uid')
255
- const baseUrl = readStringField(value, 'base_url') || readStringField(value, 'baseUrl')
256
- return {
257
- sk,
258
- ...(uid ? { uid } : {}),
259
- ...(baseUrl ? { base_url: baseUrl.replace(/\/+$/, '') } : {}),
260
- }
261
- }
262
-
263
- /** MiMo 的 sk 长期有效,无续期接口。 */
264
- export function needsRefresh() {
265
- return false
266
- }
267
-
268
- export async function refreshCredential() {
269
- throw { kind: 'auth', retryable: false, terminal: true, message: 'MiMo 凭据不支持续期,请重新登录' }
270
- }
271
-
272
- export function describeCredential(credential) {
273
- const uid = readStringField(credential, 'uid')
274
- const sk = readStringField(credential, 'sk')
275
- return {
276
- label: uid ? `MiMo 账号 ${uid.slice(0, 8)}` : (sk ? `MiMo key ${sk.slice(0, 6)}…` : 'MiMo 账号'),
277
- expiresAt: 0,
278
- refreshable: false,
279
- }
280
- }
281
-
282
- export function credentialIdentity(credential) {
283
- return readStringField(credential, 'uid')
284
- }
285
-
286
- // ── 模型清单 ───────────────────────────────────────────────────────────────
287
-
288
- /** 由 id 推导展示名(上游 /models 不返回 name):mimo-v2.6-pro → MiMo-V2.6-Pro。 */
289
- const NAME_WORDS = { mimo: 'MiMo', tts: 'TTS', asr: 'ASR', ultraspeed: 'UltraSpeed', voiceclone: 'VoiceClone', voicedesign: 'VoiceDesign' }
290
-
291
- function nameFromId(id) {
292
- return id
293
- .split('-')
294
- .map(part => NAME_WORDS[part.toLowerCase()] ?? (part.charAt(0).toUpperCase() + part.slice(1)))
295
- .join('-')
296
- }
297
-
298
- function positiveNumber(value) {
299
- const num = typeof value === 'string' ? Number(value) : value
300
- return typeof num === 'number' && Number.isFinite(num) && num > 0 ? Math.floor(num) : undefined
301
- }
302
-
303
- /** 查询 MiMo 实时模型清单;拉不到一律抛错(不回落任何内置兜底清单)。 */
304
- export async function fetchModels(credential) {
305
- const base = resolveBaseUrl(credential)
306
- const response = await httpFetch(`${base}${MODELS_PATH}`, {
307
- method: 'GET',
308
- headers: {
309
- Authorization: `Bearer ${credential?.sk ?? ''}`,
310
- Accept: 'application/json',
311
- },
312
- }, MODELS_TIMEOUT_MS)
313
- if (!response.ok) {
314
- const text = await response.text().catch(() => '')
315
- throw new Error(`MiMo 模型清单请求失败(HTTP ${response.status}):${extractMessage(text) || text.slice(0, 200) || '无响应体'}`)
316
- }
317
- const data = await response.json().catch(() => null)
318
- if (!Array.isArray(data?.data)) throw new Error('MiMo 模型清单响应缺少 data 数组')
319
- const models = data.data
320
- .filter(item => item && typeof item === 'object' && typeof item.id === 'string' && item.id.trim() !== '')
321
- .map(item => {
322
- const id = item.id.trim()
323
- const entry = { id, name: readStringField(item, 'name') || nameFromId(id) }
324
- // 上游若补了上下文/输出上限就带上,缺了留空(不编造)
325
- const contextWindow = positiveNumber(item.context_window ?? item.context_length)
326
- if (contextWindow !== undefined) entry.contextWindow = contextWindow
327
- const maxTokens = positiveNumber(item.max_output_tokens ?? item.max_tokens)
328
- if (maxTokens !== undefined) entry.maxTokens = maxTokens
329
- const rate = MODEL_RATES[id]
330
- if (typeof rate === 'number' && Number.isFinite(rate)) {
331
- entry.rate = rate
332
- entry.isFree = rate === 0
333
- } else {
334
- entry.isFree = false
335
- }
336
- return entry
337
- })
338
- if (models.length === 0) throw new Error('MiMo 未返回任何模型(账号无权益或上游清单为空)')
339
- return models
340
- }
341
-
342
- // ── 对话 ───────────────────────────────────────────────────────────────────
343
-
344
- /** 错误分类 → OMR 失败对象。 */
345
- function failureFrom(status, bodyText) {
346
- const lower = String(bodyText ?? '').toLowerCase()
347
- const message = extractMessage(bodyText) || `MiMo HTTP ${status}`
348
- if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
349
- if (status === 402 || /insufficient|quota|额度|余额|exceeded/.test(lower)) {
350
- return { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message }
351
- }
352
- if (status === 401 || status === 403) {
353
- return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
354
- }
355
- if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
356
- if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
357
- if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
358
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
359
- }
360
-
361
- function extractMessage(bodyText) {
362
- const text = String(bodyText ?? '').trim()
363
- if (text === '') return ''
364
- try {
365
- const parsed = JSON.parse(text)
366
- const found = [
367
- typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
368
- typeof parsed?.message === 'string' ? parsed.message : '',
369
- typeof parsed?.error === 'string' ? parsed.error : '',
370
- typeof parsed?.msg === 'string' ? parsed.msg : '',
371
- ].filter(v => v.length > 0)
372
- if (found.length > 0) return found.join(' ').slice(0, 300)
373
- } catch { /* 非 JSON */ }
374
- return text.slice(0, 300)
375
- }
376
-
377
- const TTS_MODEL_PREFIX = 'mimo-v2.5-tts'
378
- const TTS_DEFAULT_TEXT = '你好,这是 MiMo 语音合成测试。'
379
-
380
- function buildChatBody(openaiBody) {
381
- const body = { ...openaiBody, stream: true } // 恒流式,本地聚合
382
- if (typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0) {
383
- body.max_tokens = Math.min(Math.floor(body.max_tokens), MAX_OUTPUT_TOKENS)
384
- } else {
385
- delete body.max_tokens
386
- }
387
- return body
388
- }
389
-
390
- /**
391
- * TTS 模型(mimo-v2.5-tts*)复用 /chat/completions,但协议不同:
392
- * - 必须有一条 assistant 消息承载待合成文本(缺了上游报 "messages must contain an assistant role for TTS model")
393
- * - 音频参数放 audio(format/voice),voicedesign 还要求 user 消息描述音色
394
- * 因此把普通聊天请求改写成合法 TTS 请求:丢掉 system 消息,缺 assistant 时用最后一条 user 文本补上。
395
- */
396
- function buildTtsBody(openaiBody) {
397
- const model = typeof openaiBody.model === 'string' ? openaiBody.model : ''
398
- const messages = (Array.isArray(openaiBody.messages) ? openaiBody.messages : [])
399
- .filter(m => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string')
400
- .map(m => ({ role: m.role, content: m.content }))
401
- const text = [...messages].reverse().find(m => m.role === 'user')?.content || TTS_DEFAULT_TEXT
402
- if (!messages.some(m => m.role === 'assistant')) messages.push({ role: 'assistant', content: text })
403
- const audio = openaiBody.audio && typeof openaiBody.audio === 'object' ? { ...openaiBody.audio } : {}
404
- if (typeof audio.format !== 'string' || audio.format === '') audio.format = 'wav'
405
- if (model === `${TTS_MODEL_PREFIX}-voiceclone` && (typeof audio.voice !== 'string' || audio.voice === '')) {
406
- throw { kind: 'request', retryable: false, message: 'MiMo 音色克隆需要在请求里带 audio.voice(音频样本 base64,仅支持 mp3/wav)' }
407
- }
408
- if (model === `${TTS_MODEL_PREFIX}-voicedesign`) delete audio.voice
409
- // TTS 走非流式:一次拿到完整 base64 音频,避免 SSE 分段拼接损坏音频
410
- return { model, messages, audio, stream: false }
411
- }
412
-
413
- /** TTS 合成(非流式),返回与聊天一致的 choices 结构(音频在 choices[0].message.audio)。 */
414
- async function completeTts(credential, body, { signal, headerTimeoutMs }) {
415
- const base = resolveBaseUrl(credential)
416
- const response = await httpFetch(`${base}${CHAT_PATH}`, {
417
- method: 'POST',
418
- headers: {
419
- Authorization: `Bearer ${credential?.sk ?? ''}`,
420
- 'Content-Type': 'application/json',
421
- Accept: 'application/json',
422
- 'X-Mimo-Source': SOURCE_HEADER,
423
- },
424
- body: JSON.stringify(buildTtsBody(body)),
425
- signal,
426
- }, headerTimeoutMs)
427
- if (!response.ok) {
428
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
429
- throw failureFrom(response.status, text)
430
- }
431
- const json = await response.json().catch(() => null)
432
- if (!json?.choices?.[0]) {
433
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'MiMo TTS 响应缺少 choices' }
434
- }
435
- if (json.model !== undefined) json.model = body.model
436
- return { status: response.status, json }
437
- }
438
-
439
- /** 单账号一轮对话。 */
440
- export async function complete(credential, body, { signal, onData, headerTimeoutMs = 60_000 } = {}) {
441
- const model = typeof body.model === 'string' ? body.model : ''
442
- const base = resolveBaseUrl(credential)
443
- if (model.startsWith(TTS_MODEL_PREFIX)) return completeTts(credential, body, { signal, headerTimeoutMs })
444
-
445
- const response = await httpFetch(`${base}${CHAT_PATH}`, {
446
- method: 'POST',
447
- headers: {
448
- Authorization: `Bearer ${credential?.sk ?? ''}`,
449
- 'Content-Type': 'application/json',
450
- Accept: 'text/event-stream',
451
- 'X-Mimo-Source': SOURCE_HEADER,
452
- },
453
- body: JSON.stringify(buildChatBody(body)),
454
- signal,
455
- }, headerTimeoutMs)
456
-
457
- if (!response.ok) {
458
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
459
- throw failureFrom(response.status, text)
460
- }
461
- if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'MiMo 返回空响应体' }
462
-
463
- const chunks = []
464
- await readSseData(response.body, data => {
465
- chunks.push(data)
466
- onData?.(data)
467
- }, signal)
468
- const merged = mergeSseChunks(chunks)
469
- if (!merged || !merged.choices?.[0]) {
470
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'MiMo 流结束但没有内容帧' }
471
- }
472
- if (merged.model !== undefined) merged.model = model
473
- return { status: response.status, json: merged }
474
- }
1
+ /**
2
+ * MiMo (小米) 渠道 —— oauth-callback 浏览器授权登录。
3
+ *
4
+ * 协议要点:
5
+ * - 对话:{baseUrl}/chat/completions(OpenAI 兼容,baseUrl 默认 https://api.xiaomimimo.com/v1)
6
+ * 认证:`Bearer {sk}`,附加 `X-Mimo-Source: mimocode-cli`(客户端来源标识)
7
+ * - 登录:浏览器授权 + 本地回调(X25519 + AES-256-GCM 混合加密)
8
+ * ① 本地生成 X25519 密钥对(spki/pkcs8 der),公钥 base64url 作为 `pk`
9
+ * ② 起本地 http 服务(随机端口)→ redirect_uri = http://localhost:{port}/
10
+ * ③ 授权页:{platform}/authorize?pk=&redirect_uri=&kn=mimocode&key_name=
11
+ * ④ 授权完成后浏览器跳回本地回调,query `u` 即密文:
12
+ * ephemeralPub(32) + nonce(12) + ciphertext + tag(16)
13
+ * 用私钥 ECDH → sha256(sharedSecret) → AES-256-GCM 解密 → { sk?, uid, url? }
14
+ * ⑤ 手工兜底:redirect_uri 换成 {platform}/authorize/code/callback,
15
+ * 页面展示一段 code,用户粘贴回 OMR(同样用 `u` 解密)
16
+ * - 凭据:{ sk, uid, base_url? };sk 为空时说明该账号无 API key(仅 uid)
17
+ * - 模型:只认远端 {base}/models 实时清单(拉不到即报错,不使用内置兜底表);
18
+ * 上游只返回 id/object/owned_by,倍率按官方定价文档口径本地折算
19
+ * - TTS(mimo-v2.5-tts*):复用 /chat/completions,但必须带 assistant 消息承载待合成文本
20
+ * 并传 audio 参数;这里自动把普通聊天请求改写为合法 TTS 请求(非流式返回完整音频)
21
+ */
22
+
23
+ import { createServer } from 'node:http'
24
+ import { createHash, createPrivateKey, createPublicKey, diffieHellman, generateKeyPairSync, randomBytes, createDecipheriv } from 'node:crypto'
25
+ import { httpFetch, readBodyText, readSseData, mergeSseChunks } from '../util.js'
26
+
27
+ // ── 产品常量 ────────────────────────────────────────────────────────────────
28
+
29
+ const DEFAULT_PLATFORM_URL = 'https://platform.xiaomimimo.com'
30
+ const DEFAULT_BASE_URL = 'https://api.xiaomimimo.com/v1'
31
+
32
+ const AUTHORIZE_PATH = '/authorize'
33
+ const CODE_CALLBACK_PATH = '/authorize/code/callback'
34
+ const CHAT_PATH = '/chat/completions'
35
+ const MODELS_PATH = '/models'
36
+
37
+ const KEY_NAME = 'mimocode'
38
+ const SOURCE_HEADER = 'mimocode-cli'
39
+
40
+ const LOGIN_TIMEOUT_MS = 5 * 60_000 // 5 分钟
41
+ const REQUEST_TIMEOUT_MS = 30_000
42
+ const MODELS_TIMEOUT_MS = 20_000
43
+ const BODY_READ_TIMEOUT_MS = 15_000
44
+ const MAX_OUTPUT_TOKENS = 131_072 // 输出 token 上限(官方 128k 级)
45
+ const SERVER_SHUTDOWN_GRACE_MS = 500
46
+
47
+ /**
48
+ * 模型消耗倍率(官方按量计费单价折算,基准 mimo-v2.6-flash 输入未命中 ¥1.00 = 1):
49
+ * mimo-v2.6-flash ¥1.00 / ¥2.00 → 1
50
+ * mimo-v2.6-pro ¥3.00 / ¥6.00 → 3
51
+ * mimo-v2.6-pro-ultraspeed ¥30.00 / ¥60.00 → 30
52
+ * TTS 系列限时免费(不消耗 Credits)→ 0
53
+ * 上游 /models 只返回 id/object/owned_by,不含价格/倍率/上下文/模态字段,
54
+ * 因此倍率只能按文档口径折算;只补 rate,不参与模型清单,清单仍只认实时 /models。
55
+ * ASR 按音频时长计费(¥0.5/小时),没有 token 倍率,不补 rate。
56
+ */
57
+ const MODEL_RATES = {
58
+ 'mimo-v2.6-flash': 1,
59
+ 'mimo-v2.6-pro': 3,
60
+ 'mimo-v2.6-pro-ultraspeed': 30,
61
+ 'mimo-v2.5-tts': 0,
62
+ 'mimo-v2.5-tts-voiceclone': 0,
63
+ 'mimo-v2.5-tts-voicedesign': 0,
64
+ }
65
+
66
+ export const meta = { id: 'mimo', label: 'MiMo (小米)', loginMode: 'oauth-callback' }
67
+
68
+ // ── 小工具 ──────────────────────────────────────────────────────────────────
69
+
70
+ function readStringField(source, key) {
71
+ const value = source?.[key]
72
+ if (typeof value === 'string' && value.trim().length > 0) return value.trim()
73
+ return ''
74
+ }
75
+
76
+ function platformUrl() {
77
+ const override = readStringField(process.env, 'MIMO_PLATFORM_URL')
78
+ return (override || DEFAULT_PLATFORM_URL).replace(/\/+$/, '')
79
+ }
80
+
81
+ /** 由凭据推导 API 基址(登录返回的 url 可覆盖默认)。 */
82
+ function resolveBaseUrl(credential) {
83
+ const candidate = readStringField(credential, 'base_url') || readStringField(credential, 'baseUrl')
84
+ const base = candidate || DEFAULT_BASE_URL
85
+ return base.replace(/\/+$/, '')
86
+ }
87
+
88
+ // ── 登录加密(X25519 + AES-256-GCM)────────────────────────────────────────
89
+
90
+ /** 生成 X25519 密钥对:公钥 base64url(SPKI der),私钥 PKCS8 der。 */
91
+ function generateKeyPair() {
92
+ const pair = generateKeyPairSync('x25519', {
93
+ publicKeyEncoding: { type: 'spki', format: 'der' },
94
+ privateKeyEncoding: { type: 'pkcs8', format: 'der' },
95
+ })
96
+ return { publicKey: Buffer.from(pair.publicKey).toString('base64url'), privateKeyDer: pair.privateKey }
97
+ }
98
+
99
+ /** X25519 SPKI der 前缀:SEQUENCE(42) + SEQUENCE(5, id-X25519) + BIT STRING(33, 0x00 + 32字节)。 */
100
+ const X25519_SPKI_PREFIX = Buffer.from('302a300506032b656e032100', 'hex')
101
+
102
+ /**
103
+ * 解密授权回调密文:
104
+ * ephemeralPublicKey(32) + nonce(12) + ciphertext + tag(16)
105
+ * 返回 { sk?, uid, url? }。
106
+ */
107
+ function decrypt(privateKeyDer, encryptedBase64Url) {
108
+ const encrypted = Buffer.from(String(encryptedBase64Url).trim(), 'base64url')
109
+ if (encrypted.length < 32 + 12 + 16) throw new Error('授权数据长度不足')
110
+ const ephemeralPub = encrypted.subarray(0, 32)
111
+ const nonce = encrypted.subarray(32, 44)
112
+ const ciphertextAndTag = encrypted.subarray(44)
113
+ const tag = ciphertextAndTag.subarray(ciphertextAndTag.length - 16)
114
+ const ciphertext = ciphertextAndTag.subarray(0, ciphertextAndTag.length - 16)
115
+
116
+ const privateKey = createPrivateKey({ key: privateKeyDer, format: 'der', type: 'pkcs8' })
117
+ // 只需 32 字节裸公钥,手工拼成 SPKI der 后交给 createPublicKey
118
+ const ephemeralPublicKey = createPublicKey({
119
+ key: Buffer.concat([X25519_SPKI_PREFIX, ephemeralPub]),
120
+ format: 'der',
121
+ type: 'spki',
122
+ })
123
+ const sharedSecret = diffieHellman({ privateKey, publicKey: ephemeralPublicKey })
124
+ const derivedKey = createHash('sha256').update(sharedSecret).digest()
125
+
126
+ const decipher = createDecipheriv('aes-256-gcm', derivedKey, nonce)
127
+ decipher.setAuthTag(tag)
128
+ const decrypted = Buffer.concat([decipher.update(ciphertext), decipher.final()])
129
+ const result = JSON.parse(decrypted.toString('utf-8'))
130
+ if (result === null || typeof result !== 'object') throw new Error('授权数据格式错误')
131
+ return result
132
+ }
133
+
134
+ /** 授权页 URL。key_name 仅用于平台侧展示密钥名。 */
135
+ function buildAuthorizeUrl(publicKey, redirectUri) {
136
+ const params = new URLSearchParams({
137
+ pk: publicKey,
138
+ redirect_uri: redirectUri,
139
+ kn: KEY_NAME,
140
+ key_name: `omr-${randomBytes(4).toString('hex')}`,
141
+ })
142
+ return `${platformUrl()}${AUTHORIZE_PATH}?${params.toString()}`
143
+ }
144
+
145
+ /** 解密结果 → 持久化凭据。 */
146
+ function credentialFromResult(result) {
147
+ const uid = readStringField(result, 'uid')
148
+ const sk = readStringField(result, 'sk')
149
+ const url = readStringField(result, 'url')
150
+ if (!sk) throw new Error('授权结果缺少 API key(sk),该小米账号可能未开通 MiMo 服务')
151
+ return {
152
+ sk,
153
+ uid,
154
+ ...(url ? { base_url: url.replace(/\/+$/, '') } : {}),
155
+ }
156
+ }
157
+
158
+ // ── 登录(浏览器授权 + 本地回调)───────────────────────────────────────────
159
+
160
+ /**
161
+ * 启动登录。返回 `{ loginUrl, manualUrl, loginUrlReady, promise, cancel }`:
162
+ * - loginUrl:带本地回调的授权页(浏览器授权完成后自动回到本机)
163
+ * - manualUrl:手工兜底授权页(页面展示 code,用户粘贴到 OMR)
164
+ * - promise:解析为凭据对象;失败/取消 reject
165
+ */
166
+ export function startLogin({ port } = {}) {
167
+ const { publicKey, privateKeyDer } = generateKeyPair()
168
+
169
+ // 回调端口在 listen 后才确定,授权 URL 异步就绪
170
+ let resolveLoginUrl
171
+ let rejectLoginUrl
172
+ const loginUrlReady = new Promise((resolve, reject) => { resolveLoginUrl = resolve; rejectLoginUrl = reject })
173
+ loginUrlReady.catch(() => {})
174
+
175
+ let settle
176
+ let settled = false
177
+ const promise = new Promise((resolve, reject) => {
178
+ const finish = (fn, value) => {
179
+ if (settled) return
180
+ settled = true
181
+ clearTimeout(timer)
182
+ try { server.close() } catch { /* 已关闭 */ }
183
+ try { server.closeAllConnections?.() } catch { /* 旧版本 Node 无此方法 */ }
184
+ fn(value)
185
+ }
186
+ settle = { resolve: v => finish(resolve, v), reject: e => finish(reject, e) }
187
+
188
+ const timer = setTimeout(() => {
189
+ rejectLoginUrl?.(new Error('登录等待已超时'))
190
+ settle.reject(new Error('登录等待已超时,请重新发起登录'))
191
+ }, LOGIN_TIMEOUT_MS)
192
+ timer.unref?.()
193
+
194
+ const server = createServer((request, response) => {
195
+ const url = new URL(request.url ?? '/', 'http://localhost')
196
+ const encrypted = url.searchParams.get('u')
197
+ if (!encrypted) {
198
+ response.writeHead(302, { Location: `${platformUrl()}${AUTHORIZE_PATH}/callback?status=error&message=missing_data` }).end()
199
+ return
200
+ }
201
+ let credential
202
+ try {
203
+ credential = credentialFromResult(decrypt(privateKeyDer, encrypted))
204
+ } catch (error) {
205
+ response.writeHead(302, { Location: `${platformUrl()}${AUTHORIZE_PATH}/callback?status=error&message=decrypt_failed` }).end()
206
+ settle.reject(error instanceof Error ? error : new Error(String(error)))
207
+ return
208
+ }
209
+ response.writeHead(302, { Location: `${platformUrl()}${AUTHORIZE_PATH}/callback?status=success` }).end()
210
+ // 先让响应写完再关闭监听,避免浏览器看到连接被重置
211
+ setTimeout(() => settle.resolve(credential), SERVER_SHUTDOWN_GRACE_MS)
212
+ })
213
+ server.on('error', error => settle.reject(error))
214
+
215
+ server.listen(port || 0, '127.0.0.1', () => {
216
+ const address = server.address()
217
+ const assigned = typeof address === 'object' && address ? address.port : 0
218
+ if (assigned > 0) resolveLoginUrl?.(buildAuthorizeUrl(publicKey, `http://localhost:${assigned}/`))
219
+ else rejectLoginUrl?.(new Error('无法获取本地回调端口'))
220
+ })
221
+ })
222
+ promise.catch(() => {})
223
+
224
+ return {
225
+ loginUrl: '',
226
+ loginUrlReady,
227
+ manualUrl: buildAuthorizeUrl(publicKey, `${platformUrl()}${CODE_CALLBACK_PATH}`),
228
+ promise,
229
+ cancel: () => settle?.reject(new Error('登录已取消')),
230
+ }
231
+ }
232
+
233
+ /**
234
+ * 手动粘贴凭据的规范化。
235
+ * 授权密文只能由 startLogin 持有的私钥解密,所以这里只接受凭据 JSON
236
+ * ({ sk, uid, base_url? },例如从别处导出的 ~/.mimo/auth.json 内容)。
237
+ */
238
+ export function normalizeCredential(raw) {
239
+ let value = raw
240
+ if (typeof value === 'string') {
241
+ const text = raw.trim()
242
+ if (text === '') throw new Error('凭据不能为空')
243
+ if (text.startsWith('{')) {
244
+ try { value = JSON.parse(text) } catch { throw new Error('凭据不是合法 JSON') }
245
+ } else {
246
+ throw new Error('请粘贴凭据 JSON({ sk, uid }),或点「添加账号」走浏览器授权')
247
+ }
248
+ }
249
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
250
+ throw new Error('凭据必须是 JSON 对象')
251
+ }
252
+ const sk = readStringField(value, 'sk') || readStringField(value, 'key') || readStringField(value, 'api_key')
253
+ if (!sk) throw new Error('凭据缺少 sk(API key)')
254
+ const uid = readStringField(value, 'uid')
255
+ const baseUrl = readStringField(value, 'base_url') || readStringField(value, 'baseUrl')
256
+ return {
257
+ sk,
258
+ ...(uid ? { uid } : {}),
259
+ ...(baseUrl ? { base_url: baseUrl.replace(/\/+$/, '') } : {}),
260
+ }
261
+ }
262
+
263
+ /** MiMo 的 sk 长期有效,无续期接口。 */
264
+ export function needsRefresh() {
265
+ return false
266
+ }
267
+
268
+ export async function refreshCredential() {
269
+ throw { kind: 'auth', retryable: false, terminal: true, message: 'MiMo 凭据不支持续期,请重新登录' }
270
+ }
271
+
272
+ export function describeCredential(credential) {
273
+ const uid = readStringField(credential, 'uid')
274
+ const sk = readStringField(credential, 'sk')
275
+ return {
276
+ label: uid ? `MiMo 账号 ${uid.slice(0, 8)}` : (sk ? `MiMo key ${sk.slice(0, 6)}…` : 'MiMo 账号'),
277
+ expiresAt: 0,
278
+ refreshable: false,
279
+ }
280
+ }
281
+
282
+ export function credentialIdentity(credential) {
283
+ return readStringField(credential, 'uid')
284
+ }
285
+
286
+ // ── 模型清单 ───────────────────────────────────────────────────────────────
287
+
288
+ /** 由 id 推导展示名(上游 /models 不返回 name):mimo-v2.6-pro → MiMo-V2.6-Pro。 */
289
+ const NAME_WORDS = { mimo: 'MiMo', tts: 'TTS', asr: 'ASR', ultraspeed: 'UltraSpeed', voiceclone: 'VoiceClone', voicedesign: 'VoiceDesign' }
290
+
291
+ function nameFromId(id) {
292
+ return id
293
+ .split('-')
294
+ .map(part => NAME_WORDS[part.toLowerCase()] ?? (part.charAt(0).toUpperCase() + part.slice(1)))
295
+ .join('-')
296
+ }
297
+
298
+ function positiveNumber(value) {
299
+ const num = typeof value === 'string' ? Number(value) : value
300
+ return typeof num === 'number' && Number.isFinite(num) && num > 0 ? Math.floor(num) : undefined
301
+ }
302
+
303
+ /** 查询 MiMo 实时模型清单;拉不到一律抛错(不回落任何内置兜底清单)。 */
304
+ export async function fetchModels(credential) {
305
+ const base = resolveBaseUrl(credential)
306
+ const response = await httpFetch(`${base}${MODELS_PATH}`, {
307
+ method: 'GET',
308
+ headers: {
309
+ Authorization: `Bearer ${credential?.sk ?? ''}`,
310
+ Accept: 'application/json',
311
+ },
312
+ }, MODELS_TIMEOUT_MS)
313
+ if (!response.ok) {
314
+ const text = await response.text().catch(() => '')
315
+ throw new Error(`MiMo 模型清单请求失败(HTTP ${response.status}):${extractMessage(text) || text.slice(0, 200) || '无响应体'}`)
316
+ }
317
+ const data = await response.json().catch(() => null)
318
+ if (!Array.isArray(data?.data)) throw new Error('MiMo 模型清单响应缺少 data 数组')
319
+ const models = data.data
320
+ .filter(item => item && typeof item === 'object' && typeof item.id === 'string' && item.id.trim() !== '')
321
+ .map(item => {
322
+ const id = item.id.trim()
323
+ const entry = { id, name: readStringField(item, 'name') || nameFromId(id) }
324
+ // 上游若补了上下文/输出上限就带上,缺了留空(不编造)
325
+ const contextWindow = positiveNumber(item.context_window ?? item.context_length)
326
+ if (contextWindow !== undefined) entry.contextWindow = contextWindow
327
+ const maxTokens = positiveNumber(item.max_output_tokens ?? item.max_tokens)
328
+ if (maxTokens !== undefined) entry.maxTokens = maxTokens
329
+ const rate = MODEL_RATES[id]
330
+ if (typeof rate === 'number' && Number.isFinite(rate)) {
331
+ entry.rate = rate
332
+ entry.isFree = rate === 0
333
+ } else {
334
+ entry.isFree = false
335
+ }
336
+ return entry
337
+ })
338
+ if (models.length === 0) throw new Error('MiMo 未返回任何模型(账号无权益或上游清单为空)')
339
+ return models
340
+ }
341
+
342
+ // ── 对话 ───────────────────────────────────────────────────────────────────
343
+
344
+ /** 错误分类 → OMR 失败对象。 */
345
+ function failureFrom(status, bodyText) {
346
+ const lower = String(bodyText ?? '').toLowerCase()
347
+ const message = extractMessage(bodyText) || `MiMo HTTP ${status}`
348
+ if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
349
+ if (status === 402 || /insufficient|quota|额度|余额|exceeded/.test(lower)) {
350
+ return { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message }
351
+ }
352
+ if (status === 401 || status === 403) {
353
+ return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
354
+ }
355
+ if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
356
+ if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
357
+ if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
358
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
359
+ }
360
+
361
+ function extractMessage(bodyText) {
362
+ const text = String(bodyText ?? '').trim()
363
+ if (text === '') return ''
364
+ try {
365
+ const parsed = JSON.parse(text)
366
+ const found = [
367
+ typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
368
+ typeof parsed?.message === 'string' ? parsed.message : '',
369
+ typeof parsed?.error === 'string' ? parsed.error : '',
370
+ typeof parsed?.msg === 'string' ? parsed.msg : '',
371
+ ].filter(v => v.length > 0)
372
+ if (found.length > 0) return found.join(' ').slice(0, 300)
373
+ } catch { /* 非 JSON */ }
374
+ return text.slice(0, 300)
375
+ }
376
+
377
+ const TTS_MODEL_PREFIX = 'mimo-v2.5-tts'
378
+ const TTS_DEFAULT_TEXT = '你好,这是 MiMo 语音合成测试。'
379
+
380
+ function buildChatBody(openaiBody) {
381
+ const body = { ...openaiBody, stream: true } // 恒流式,本地聚合
382
+ if (typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0) {
383
+ body.max_tokens = Math.min(Math.floor(body.max_tokens), MAX_OUTPUT_TOKENS)
384
+ } else {
385
+ delete body.max_tokens
386
+ }
387
+ return body
388
+ }
389
+
390
+ /**
391
+ * TTS 模型(mimo-v2.5-tts*)复用 /chat/completions,但协议不同:
392
+ * - 必须有一条 assistant 消息承载待合成文本(缺了上游报 "messages must contain an assistant role for TTS model")
393
+ * - 音频参数放 audio(format/voice),voicedesign 还要求 user 消息描述音色
394
+ * 因此把普通聊天请求改写成合法 TTS 请求:丢掉 system 消息,缺 assistant 时用最后一条 user 文本补上。
395
+ */
396
+ function buildTtsBody(openaiBody) {
397
+ const model = typeof openaiBody.model === 'string' ? openaiBody.model : ''
398
+ const messages = (Array.isArray(openaiBody.messages) ? openaiBody.messages : [])
399
+ .filter(m => m && (m.role === 'user' || m.role === 'assistant') && typeof m.content === 'string')
400
+ .map(m => ({ role: m.role, content: m.content }))
401
+ const text = [...messages].reverse().find(m => m.role === 'user')?.content || TTS_DEFAULT_TEXT
402
+ if (!messages.some(m => m.role === 'assistant')) messages.push({ role: 'assistant', content: text })
403
+ const audio = openaiBody.audio && typeof openaiBody.audio === 'object' ? { ...openaiBody.audio } : {}
404
+ if (typeof audio.format !== 'string' || audio.format === '') audio.format = 'wav'
405
+ if (model === `${TTS_MODEL_PREFIX}-voiceclone` && (typeof audio.voice !== 'string' || audio.voice === '')) {
406
+ throw { kind: 'request', retryable: false, message: 'MiMo 音色克隆需要在请求里带 audio.voice(音频样本 base64,仅支持 mp3/wav)' }
407
+ }
408
+ if (model === `${TTS_MODEL_PREFIX}-voicedesign`) delete audio.voice
409
+ // TTS 走非流式:一次拿到完整 base64 音频,避免 SSE 分段拼接损坏音频
410
+ return { model, messages, audio, stream: false }
411
+ }
412
+
413
+ /** TTS 合成(非流式),返回与聊天一致的 choices 结构(音频在 choices[0].message.audio)。 */
414
+ async function completeTts(credential, body, { signal, headerTimeoutMs }) {
415
+ const base = resolveBaseUrl(credential)
416
+ const response = await httpFetch(`${base}${CHAT_PATH}`, {
417
+ method: 'POST',
418
+ headers: {
419
+ Authorization: `Bearer ${credential?.sk ?? ''}`,
420
+ 'Content-Type': 'application/json',
421
+ Accept: 'application/json',
422
+ 'X-Mimo-Source': SOURCE_HEADER,
423
+ },
424
+ body: JSON.stringify(buildTtsBody(body)),
425
+ signal,
426
+ }, headerTimeoutMs)
427
+ if (!response.ok) {
428
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
429
+ throw failureFrom(response.status, text)
430
+ }
431
+ const json = await response.json().catch(() => null)
432
+ if (!json?.choices?.[0]) {
433
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'MiMo TTS 响应缺少 choices' }
434
+ }
435
+ if (json.model !== undefined) json.model = body.model
436
+ return { status: response.status, json }
437
+ }
438
+
439
+ /** 单账号一轮对话。 */
440
+ export async function complete(credential, body, { signal, onData, headerTimeoutMs = 60_000 } = {}) {
441
+ const model = typeof body.model === 'string' ? body.model : ''
442
+ const base = resolveBaseUrl(credential)
443
+ if (model.startsWith(TTS_MODEL_PREFIX)) return completeTts(credential, body, { signal, headerTimeoutMs })
444
+
445
+ const response = await httpFetch(`${base}${CHAT_PATH}`, {
446
+ method: 'POST',
447
+ headers: {
448
+ Authorization: `Bearer ${credential?.sk ?? ''}`,
449
+ 'Content-Type': 'application/json',
450
+ Accept: 'text/event-stream',
451
+ 'X-Mimo-Source': SOURCE_HEADER,
452
+ },
453
+ body: JSON.stringify(buildChatBody(body)),
454
+ signal,
455
+ }, headerTimeoutMs)
456
+
457
+ if (!response.ok) {
458
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
459
+ throw failureFrom(response.status, text)
460
+ }
461
+ if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'MiMo 返回空响应体' }
462
+
463
+ const chunks = []
464
+ await readSseData(response.body, data => {
465
+ chunks.push(data)
466
+ onData?.(data)
467
+ }, signal)
468
+ const merged = mergeSseChunks(chunks)
469
+ if (!merged || !merged.choices?.[0]) {
470
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'MiMo 流结束但没有内容帧' }
471
+ }
472
+ if (merged.model !== undefined) merged.model = model
473
+ return { status: response.status, json: merged }
474
+ }