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,572 +1,572 @@
1
- /**
2
- * Kimi (Moonshot) 直连渠道 —— oauth 设备码登录。
3
- *
4
- * 协议要点:
5
- * - 认证:`Bearer {accessToken}`
6
- * - 登录:设备码 OAuth(无本地端口回调)
7
- * ① POST {oauthHost}/api/oauth/device_authorization (body: client_id)
8
- * ② 轮询 POST {oauthHost}/api/oauth/token (body: client_id + device_code + grant_type=urn:ietf:params:oauth:grant-type:device_code)
9
- * - 401/403 或 200 缺 token → 终态失效需重新登录
10
- * ③ 续期:POST {oauthHost}/api/oauth/token (body: client_id + grant_type=refresh_token + refresh_token)
11
- * - 宿主:大陆 https://auth.kimi.com + https://api.kimi.com/coding/v1
12
- * 全球 https://auth.kimi.ai + https://api.kimi.ai/coding/v1
13
- * - 对话:{baseUrl}/chat/completions(OpenAI 兼容)
14
- * - 配额:{baseUrl}/usages(返回 limit5h, limit7d, monthTotal, monthCode)
15
- * - 错误:429/402/额度文案 → 可换号;403+地域文案 → 地域限制判死
16
- */
17
-
18
- import { httpFetch, readBodyText, readSseData, mergeSseChunks } from '../util.js'
19
-
20
- // ── 产品常量 ────────────────────────────────────────────────────────────────
21
-
22
- const CLIENT_ID = '17e5f671-d194-4dfb-9706-5516cb48c098'
23
- const DEFAULT_OAUTH_HOST_MAINLAND = 'https://auth.kimi.com'
24
- const DEFAULT_OAUTH_HOST_GLOBAL = 'https://auth.kimi.ai'
25
- const DEFAULT_BASE_URL_MAINLAND = 'https://api.kimi.com/coding/v1'
26
- const DEFAULT_BASE_URL_GLOBAL = 'https://api.kimi.ai/coding/v1'
27
-
28
- const DEVICE_AUTH_PATH = '/api/oauth/device_authorization'
29
- const DEVICE_TOKEN_PATH = '/api/oauth/token'
30
- const CHAT_PATH = '/chat/completions'
31
- const MODELS_PATH = '/models'
32
- const USAGE_PATH = '/usages'
33
-
34
- const REQUEST_TIMEOUT_MS = 30_000
35
- const MODELS_TIMEOUT_MS = 20_000
36
- const BODY_READ_TIMEOUT_MS = 15_000
37
- const DEVICE_AUTH_EXPIRES_MS = 300_000 // 5 分钟
38
- const DEVICE_AUTH_INTERVAL_MS = 5_000
39
- const POLL_MAX_FAILURES = 5
40
- const REFRESH_LEAD_MS = 60 * 60_000 // 过期前 1 小时续期
41
- const MAX_OUTPUT_TOKENS = 943_718
42
-
43
- const FREE_ID_SUFFIX = ':free'
44
- const FREE_ID_PREFIX = 'kimi-free/'
45
-
46
- /**
47
- * 模型消耗倍率(Kimi Code 官方文档口径,基准 k3-256k = 1)。
48
- * 上游 /models 不返回任何价格/倍率字段(已实测 include_pricing 与各类 quota/pricing 端点均无),
49
- * 因此倍率只能按文档口径折算;只补 rate,不参与模型清单,清单仍只认实时 /models。
50
- */
51
- const MODEL_RATES = {
52
- k3: 2, // 文档:k3(1M 上下文)消耗约为 k3-256k 两倍
53
- 'k3-256k': 1,
54
- 'kimi-for-coding': 1, // K2.8 Preview,与 k3-256k 同档
55
- 'kimi-for-coding-highspeed': 3, // 文档:高速版 6 倍速、3 倍消耗
56
- }
57
-
58
- // 无内置兜底模型表:清单只认上游实时 /models,拉不到即报错。
59
-
60
- export const meta = { id: 'kimi', label: 'Kimi', loginMode: 'device-code' }
61
-
62
- // ── 小工具 ──────────────────────────────────────────────────────────────────
63
-
64
- function readStringField(source, key) {
65
- const value = source?.[key]
66
- if (typeof value === 'string' && value.trim().length > 0) return value.trim()
67
- return ''
68
- }
69
-
70
- function parseTimestamp(value) {
71
- if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
72
- return value < 1e12 ? Math.round(value * 1000) : Math.round(value)
73
- }
74
- if (typeof value === 'string' && value.trim().length > 0) {
75
- const parsed = Date.parse(value)
76
- if (Number.isFinite(parsed)) return parsed
77
- }
78
- return undefined
79
- }
80
-
81
- /** token 响应解析。
82
- * 注意:expires_in 是相对秒数,需换算为绝对毫秒时间戳(OMR 约定 expire_time=毫秒)。 */
83
- function tokenFromResponse(res) {
84
- if (!res || typeof res !== 'object') return { accessToken: '' }
85
- const accessToken = readStringField(res, 'access_token') || readStringField(res, 'accessToken')
86
- const refreshToken = readStringField(res, 'refresh_token') || readStringField(res, 'refreshToken')
87
- const expiresInSec = typeof res.expires_in === 'number' && Number.isFinite(res.expires_in) ? res.expires_in : NaN
88
- // OMR 约定 expire_time 为毫秒;协议用的是秒。统一换算为毫秒。
89
- const expiresAt = Number.isFinite(expiresInSec)
90
- ? Date.now() + Math.round(expiresInSec * 1000)
91
- : (parseTimestamp(res.expires_at) ?? parseTimestamp(res.expiresAt))
92
- const scope = readStringField(res, 'scope')
93
- const tokenType = readStringField(res, 'token_type')
94
-
95
- return { accessToken, refreshToken, expiresAt, scope, tokenType }
96
- }
97
-
98
- /** 构造持久化凭据(从 tokenFromResponse 结果或手动粘贴)。 */
99
- function buildCredential(payload, region = 'mainland-cn') {
100
- const nickname = payload.email || payload.displayName || payload.accountId || ''
101
- return {
102
- region,
103
- access_token: payload.accessToken,
104
- ...(payload.refreshToken ? { refresh_token: payload.refreshToken } : {}),
105
- ...(payload.expiresAt !== undefined ? { expire_time: payload.expiresAt } : {}),
106
- ...(payload.accountId ? { account_id: payload.accountId } : {}),
107
- ...(payload.email ? { email: payload.email } : {}),
108
- ...(payload.displayName ? { displayName: payload.displayName } : {}),
109
- ...(payload.scope ? { scope: payload.scope } : {}),
110
- ...(payload.tokenType ? { tokenType: payload.tokenType } : {}),
111
- ...(nickname ? { nickname } : {}),
112
- }
113
- }
114
-
115
- /** 续期结果合并回既有凭据。 */
116
- function applyRefresh(credential, payload) {
117
- const next = { ...credential, access_token: payload.accessToken }
118
- if (payload.refreshToken) next.refresh_token = payload.refreshToken
119
- if (payload.expiresAt !== undefined) next.expire_time = payload.expiresAt
120
- if (payload.accountId) next.account_id = payload.accountId
121
- if (payload.email) next.email = payload.email
122
- return next
123
- }
124
-
125
- /** 睡眠(可被 signal 中断)。 */
126
- function sleep(ms, signal) {
127
- return new Promise((resolve, reject) => {
128
- if (signal?.aborted) { reject(new Error('登录已取消')); return }
129
- const timer = setTimeout(() => {
130
- signal?.removeEventListener('abort', onAbort)
131
- resolve()
132
- }, ms)
133
- const onAbort = () => { clearTimeout(timer); reject(new Error('登录已取消')) }
134
- signal?.addEventListener('abort', onAbort, { once: true })
135
- })
136
- }
137
-
138
- // ── 登录(设备码 OAuth)─────────────────────────────────────────────────────
139
-
140
- /** 请求设备码授权(OAuth 端点恒为 form 编码)。 */
141
- async function requestDeviceAuthorization(signal, oauthHost) {
142
- const response = await httpFetch(`${oauthHost}${DEVICE_AUTH_PATH}`, {
143
- method: 'POST',
144
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
145
- body: new URLSearchParams({ client_id: CLIENT_ID }).toString(),
146
- signal,
147
- }, REQUEST_TIMEOUT_MS)
148
- const payload = await response.json().catch(() => ({}))
149
- if (!response.ok) {
150
- const detail = typeof payload.error_description === 'string' ? ` - ${payload.error_description}` : ''
151
- throw new Error(`设备码授权失败(HTTP ${response.status})${detail}`)
152
- }
153
- const deviceCode = readStringField(payload, 'device_code')
154
- const userCode = readStringField(payload, 'user_code')
155
- const verificationUri = readStringField(payload, 'verification_uri')
156
- const verificationUriComplete = readStringField(payload, 'verification_uri_complete')
157
- // expires_in / interval 是秒数
158
- const toMs = (value, fallback) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value * 1000 : fallback)
159
- if (!deviceCode || !userCode || !verificationUriComplete) {
160
- throw new Error('设备码授权响应缺少必要字段')
161
- }
162
-
163
- return {
164
- deviceCode,
165
- userCode,
166
- verificationUri,
167
- verificationUriComplete,
168
- expiresInMs: toMs(payload.expires_in, DEVICE_AUTH_EXPIRES_MS),
169
- intervalMs: toMs(payload.interval, DEVICE_AUTH_INTERVAL_MS),
170
- }
171
- }
172
-
173
- /** 轮询 device token。 */
174
- async function pollDeviceToken(authorization, signal, oauthHost) {
175
- const deadline = Date.now() + authorization.expiresInMs
176
- let intervalMs = Math.max(1_000, authorization.intervalMs)
177
- let failures = 0
178
-
179
- while (Date.now() <= deadline) {
180
- if (signal?.aborted) throw new Error('登录已取消')
181
- try {
182
- const response = await httpFetch(`${oauthHost}${DEVICE_TOKEN_PATH}`, {
183
- method: 'POST',
184
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
185
- body: new URLSearchParams({
186
- client_id: CLIENT_ID,
187
- device_code: authorization.deviceCode,
188
- grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
189
- }).toString(),
190
- signal,
191
- }, REQUEST_TIMEOUT_MS)
192
- const payload = await response.json().catch(() => ({}))
193
- failures = 0
194
- if (response.ok) {
195
- const token = tokenFromResponse(payload)
196
- if (!token.accessToken) throw new Error('token 响应缺少 access_token')
197
- return token
198
- }
199
- const errorCode = readStringField(payload, 'error')
200
- if (errorCode === 'authorization_pending') {
201
- await sleep(intervalMs, signal)
202
- continue
203
- }
204
- if (errorCode === 'slow_down') {
205
- intervalMs += 1_000
206
- await sleep(intervalMs, signal)
207
- continue
208
- }
209
- if (errorCode === 'access_denied' || errorCode === 'expired_token' || errorCode === 'invalid_grant') {
210
- throw new Error(readStringField(payload, 'error_description') || '设备码授权失败')
211
- }
212
- throw new Error(`token 轮询失败(HTTP ${response.status})`)
213
- } catch (error) {
214
- if (signal?.aborted) throw new Error('登录已取消')
215
- if (error instanceof Error && !/fetch failed|network|ECONN|ENOTFOUND|ETIMEDOUT|timeout/i.test(error.message)) throw error
216
- failures += 1
217
- if (failures >= POLL_MAX_FAILURES) {
218
- throw new Error(`无法连接 Kimi 登录服务(连续 ${failures} 次失败):${error?.message ?? error}`)
219
- }
220
- await sleep(intervalMs, signal)
221
- }
222
- }
223
- throw new Error('登录等待已超时,请重新发起登录')
224
- }
225
-
226
- /** 启动设备码登录。options.region: 'mainland-cn'(默认)| 'global'。 */
227
- export function startLogin(options = {}) {
228
- const controller = new AbortController()
229
- const signal = controller.signal
230
- let readyAuth = null
231
-
232
- const region = options.region === 'global' ? 'global' : 'mainland-cn'
233
- const oauthHost = region === 'mainland-cn' ? DEFAULT_OAUTH_HOST_MAINLAND : DEFAULT_OAUTH_HOST_GLOBAL
234
-
235
- const loginUrlReady = requestDeviceAuthorization(signal, oauthHost)
236
- .then(auth => {
237
- readyAuth = auth
238
- // 返回实际的授权 URL(用户手动输入)
239
- return auth.verificationUriComplete || auth.verificationUri
240
- })
241
-
242
- const promise = (async () => {
243
- await loginUrlReady
244
- // pollDeviceToken 已解析出 token(accessToken/refreshToken/expiresAt)
245
- const token = await pollDeviceToken(readyAuth, signal, oauthHost)
246
- return buildCredential(token, region)
247
- })()
248
- promise.catch(() => {})
249
-
250
- let settled = false
251
- return {
252
- loginUrl: '',
253
- loginUrlReady,
254
- promise,
255
- cancel: () => {
256
- if (settled) return
257
- settled = true
258
- controller.abort()
259
- },
260
- }
261
- }
262
-
263
- /** 手动粘贴凭据的规范化。 */
264
- export function normalizeCredential(raw) {
265
- let value = raw
266
- if (typeof value === 'string') {
267
- try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
268
- }
269
- if (value === null || typeof value !== 'object' || Array.isArray(value)) {
270
- throw new Error('凭据必须是 JSON 对象')
271
- }
272
- const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken')
273
- const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken')
274
- if (!accessToken && !refreshToken) throw new Error('凭据缺少 access_token / refresh_token')
275
- const expiresAt = parseTimestamp(value.expire_time ?? value.expiresAt ?? value.expires_at)
276
- return {
277
- ...value,
278
- access_token: accessToken,
279
- ...(refreshToken ? { refresh_token: refreshToken } : {}),
280
- ...(expiresAt !== undefined ? { expire_time: expiresAt } : {}),
281
- }
282
- }
283
-
284
- /** 静默续期。 */
285
- export async function refreshCredential(credential) {
286
- if (!credential?.refresh_token) {
287
- throw { kind: 'auth', retryable: false, terminal: true, message: '无 refresh_token,请重新登录' }
288
- }
289
- const { oauthHost } = resolveHosts(credential)
290
-
291
- let response
292
- try {
293
- response = await httpFetch(`${oauthHost}${DEVICE_TOKEN_PATH}`, {
294
- method: 'POST',
295
- headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
296
- body: new URLSearchParams({
297
- client_id: CLIENT_ID,
298
- grant_type: 'refresh_token',
299
- refresh_token: credential.refresh_token,
300
- }).toString(),
301
- }, REQUEST_TIMEOUT_MS)
302
- } catch (error) {
303
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Kimi 续期网络失败:${error?.message ?? error}` }
304
- }
305
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
306
- if (response.status === 401 || response.status === 403 || text.includes('invalid_grant')) {
307
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `Kimi 续期被拒绝(HTTP ${response.status}),请重新登录` }
308
- }
309
- let parsed
310
- try { parsed = JSON.parse(text) } catch {
311
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Kimi 续期响应不是 JSON(HTTP ${response.status})` }
312
- }
313
- if (!response.ok) {
314
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Kimi 续期失败(HTTP ${response.status}):${text.slice(0, 200)}` }
315
- }
316
- const payload = tokenFromResponse(parsed)
317
- if (!payload.accessToken) {
318
- throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: 'Kimi 续期响应缺少访问令牌,请重新登录' }
319
- }
320
- return applyRefresh(credential, payload)
321
- }
322
-
323
- /** 描述凭据。 */
324
- export function describeCredential(credential) {
325
- const nickname = readStringField(credential, 'nickname')
326
- const email = readStringField(credential, 'email')
327
- const accountId = readStringField(credential, 'account_id')
328
- return {
329
- label: nickname || email || accountId || 'Kimi 账号',
330
- expiresAt: credential?.expire_time ?? 0,
331
- refreshable: !!credential?.refresh_token,
332
- }
333
- }
334
-
335
- export function credentialIdentity(credential) {
336
- return readStringField(credential, 'account_id')
337
- }
338
-
339
- /** 续期判定:过期前 1 小时即刷新。 */
340
- export function credentialExpiresAtMs(credential) {
341
- const value = credential?.expire_time
342
- return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined
343
- }
344
-
345
- export function isRefreshable(credential) {
346
- return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
347
- }
348
-
349
- export function needsRefresh(credential) {
350
- if (!isRefreshable(credential)) return false
351
- const expiresAt = credentialExpiresAtMs(credential)
352
- if (expiresAt === undefined) return false
353
- return Date.now() >= expiresAt - REFRESH_LEAD_MS
354
- }
355
-
356
- /** 由 region 推导 OAuth 宿主与 API 基址。 */
357
- function resolveHosts(credential) {
358
- const region = readStringField(credential, 'region') || 'mainland-cn'
359
- const isMainland = region !== 'global'
360
- return {
361
- region,
362
- oauthHost: isMainland ? DEFAULT_OAUTH_HOST_MAINLAND : DEFAULT_OAUTH_HOST_GLOBAL,
363
- baseUrl: isMainland ? DEFAULT_BASE_URL_MAINLAND : DEFAULT_BASE_URL_GLOBAL,
364
- }
365
- }
366
-
367
- // ── 模型清单 ───────────────────────────────────────────────────────────────
368
-
369
- function isFreeModel(id, remoteFreeIds) {
370
- if (remoteFreeIds.has(id)) return true
371
- if (id.endsWith(FREE_ID_SUFFIX)) return true
372
- if (id.startsWith(FREE_ID_PREFIX)) return true
373
- return false
374
- }
375
-
376
- function nameFromId(id) {
377
- const slash = id.indexOf('/')
378
- const tail = slash >= 0 ? id.slice(slash + 1) : id
379
- return tail.replace(FREE_ID_SUFFIX, '').replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
380
- }
381
-
382
- /** 解析远端模型条目(保留上游 display_name / context_length 等元数据)。 */
383
- function parseRemoteModels(value) {
384
- if (!Array.isArray(value?.data)) return []
385
- const out = []
386
- for (const item of value.data) {
387
- if (item === null || typeof item !== 'object') continue
388
- if (typeof item.id !== 'string' || item.id.trim().length === 0) continue
389
- const id = item.id.trim()
390
- const entry = { id, name: readStringField(item, 'display_name') || nameFromId(id) }
391
- const contextLength = item.context_length ?? item?.limit?.context
392
- if (typeof contextLength === 'number' && Number.isFinite(contextLength) && contextLength > 0) {
393
- entry.contextWindow = Math.round(contextLength)
394
- }
395
- if (typeof item.supports_image_in === 'boolean') entry.supportsImage = item.supports_image_in
396
- if (typeof item.supports_reasoning === 'boolean') entry.supportsReasoning = item.supports_reasoning
397
- out.push(entry)
398
- }
399
- return out
400
- }
401
-
402
- /**
403
- * 查询 Kimi 实时模型清单。拉不到一律抛错(UI 勾选与目录只认实时清单,
404
- * 不设兜底快照 —— 兜底会把已下架模型重新列出来)。
405
- */
406
- export async function fetchModels(credential) {
407
- if (!credential?.access_token) throw new Error('Kimi 凭据缺少 access_token,请先重新登录')
408
- const { baseUrl } = resolveHosts(credential)
409
- const response = await httpFetch(`${baseUrl}${MODELS_PATH}`, {
410
- method: 'GET',
411
- headers: {
412
- Authorization: `Bearer ${credential.access_token}`,
413
- Accept: 'application/json',
414
- },
415
- }, MODELS_TIMEOUT_MS)
416
- if (!response.ok) {
417
- const text = await response.text().catch(() => '')
418
- throw new Error(`Kimi 模型清单请求失败(HTTP ${response.status}):${extractMessage(text) || text.slice(0, 200) || '无响应体'}`)
419
- }
420
- const data = await response.json().catch(() => null)
421
- if (!data) throw new Error('Kimi 模型清单响应不是合法 JSON')
422
- const models = parseRemoteModels(data)
423
- if (models.length === 0) throw new Error('Kimi 未返回任何模型(账号无权益或上游清单为空)')
424
- const freeSet = new Set(models.filter(m => m.id.endsWith(FREE_ID_SUFFIX)).map(m => m.id))
425
- return models.map(model => {
426
- const entry = { ...model, isFree: isFreeModel(model.id, freeSet) }
427
- const rate = MODEL_RATES[model.id]
428
- if (typeof rate === 'number' && Number.isFinite(rate)) entry.rate = rate
429
- return entry
430
- })
431
- }
432
-
433
- // ── 对话 ───────────────────────────────────────────────────────────────────
434
-
435
- /**
436
- * 错误分类 → OMR 失败对象(带 rotate/terminal 字段,供 providers 轮换判断)。
437
- * 429 / 402 / 额度文案 → 可换号(rotate)
438
- * 401 / 403 → 凭据失效(rotate + terminal,需重新登录)
439
- * 404 → 模型不存在(不可换号)
440
- * 5xx → 可重试
441
- */
442
- function failureFrom(status, bodyText) {
443
- const lower = String(bodyText ?? '').toLowerCase()
444
- const message = extractMessage(bodyText) || `Kimi HTTP ${status}`
445
- if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
446
- if (status === 402 || /insufficient|quota|额度不足|余额不足|exceeded|limit/.test(lower)) {
447
- return { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message }
448
- }
449
- if (status === 401 || status === 403) {
450
- return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
451
- }
452
- if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
453
- if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
454
- if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
455
- return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
456
- }
457
-
458
- /** 从错误体抽人可读消息(JSON error/message/msg → 原文截断)。 */
459
- function extractMessage(bodyText) {
460
- const text = String(bodyText ?? '').trim()
461
- if (text === '') return ''
462
- try {
463
- const parsed = JSON.parse(text)
464
- const found = [
465
- typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
466
- typeof parsed?.message === 'string' ? parsed.message : '',
467
- typeof parsed?.error === 'string' ? parsed.error : '',
468
- typeof parsed?.msg === 'string' ? parsed.msg : '',
469
- ].filter(v => v.length > 0)
470
- if (found.length > 0) return found.join(' ').slice(0, 300)
471
- } catch { /* 非 JSON */ }
472
- return text.slice(0, 300)
473
- }
474
-
475
- function buildChatBody(openaiBody) {
476
- const body = { ...openaiBody, stream: true } // 恒流式,本地聚合
477
- if (typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0) {
478
- body.max_tokens = Math.min(Math.floor(body.max_tokens), MAX_OUTPUT_TOKENS)
479
- } else {
480
- delete body.max_tokens
481
- }
482
- return body
483
- }
484
-
485
- /** 单账号一轮对话。 */
486
- export async function complete(credential, body, { signal, onData, headerTimeoutMs = 60_000 } = {}) {
487
- const payload = JSON.stringify(buildChatBody(body))
488
- const model = typeof body.model === 'string' ? body.model : ''
489
- const { baseUrl } = resolveHosts(credential)
490
-
491
- const response = await httpFetch(`${baseUrl}${CHAT_PATH}`, {
492
- method: 'POST',
493
- headers: {
494
- Authorization: `Bearer ${credential.access_token}`,
495
- 'Content-Type': 'application/json',
496
- Accept: 'text/event-stream',
497
- },
498
- body: payload,
499
- signal,
500
- }, headerTimeoutMs)
501
-
502
- if (!response.ok) {
503
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
504
- throw failureFrom(response.status, text)
505
- }
506
- if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Kimi 返回空响应体' }
507
-
508
- const chunks = []
509
- await readSseData(response.body, data => {
510
- chunks.push(data)
511
- onData?.(data)
512
- }, signal)
513
- const merged = mergeSseChunks(chunks)
514
- if (!merged || !merged.choices?.[0]) {
515
- throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Kimi 流结束但没有内容帧' }
516
- }
517
- if (merged.model !== undefined) merged.model = model
518
- return { status: response.status, json: merged }
519
- }
520
-
521
- // ── 积分/配额余额 ──────────────────────────────────────────────────────────
522
-
523
- /** 查询配额使用情况(/usages 返回 limit5h / limit7d / monthTotal / monthCode 等百分比窗口)。 */
524
- export async function fetchCreditBalance(credential) {
525
- const { baseUrl } = resolveHosts(credential)
526
-
527
- try {
528
- const response = await httpFetch(`${baseUrl}${USAGE_PATH}`, {
529
- method: 'GET',
530
- headers: {
531
- Authorization: `Bearer ${credential.access_token}`,
532
- Accept: 'application/json',
533
- },
534
- }, REQUEST_TIMEOUT_MS)
535
- const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
536
- if (!response.ok) return null
537
- let parsed
538
- try { parsed = JSON.parse(text) } catch { return null }
539
- if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
540
-
541
- // 百分比窗口:已使用比例(0–100)
542
- const pct = key => {
543
- const val = parsed?.[key]
544
- if (typeof val === 'number' && Number.isFinite(val)) return Math.min(100, Math.max(0, Math.round(val)))
545
- if (typeof val === 'string' && val.trim() !== '') {
546
- const n = Number(val.replace('%', ''))
547
- if (Number.isFinite(n)) return Math.min(100, Math.max(0, Math.round(n)))
548
- }
549
- return 0
550
- }
551
-
552
- const used5h = pct('limit5h')
553
- const used7d = pct('limit7d')
554
- const usedMonth = pct('monthTotal')
555
-
556
- const pkg = {
557
- name: 'Kimi 配额(5h / 7d / 月度)',
558
- unit: '%',
559
- remaining: 100 - Math.max(used5h, used7d),
560
- total: 100,
561
- used: Math.max(used5h, used7d),
562
- active: true,
563
- cycleStartTime: '',
564
- cycleEndTime: '',
565
- expiredTime: '',
566
- note: `5h 已用 ${used5h}%,7d 已用 ${used7d}%,月度已用 ${usedMonth}%`,
567
- }
568
- return { total: 100, packages: [pkg], expiredTotal: 0 }
569
- } catch {
570
- return null
571
- }
572
- }
1
+ /**
2
+ * Kimi (Moonshot) 直连渠道 —— oauth 设备码登录。
3
+ *
4
+ * 协议要点:
5
+ * - 认证:`Bearer {accessToken}`
6
+ * - 登录:设备码 OAuth(无本地端口回调)
7
+ * ① POST {oauthHost}/api/oauth/device_authorization (body: client_id)
8
+ * ② 轮询 POST {oauthHost}/api/oauth/token (body: client_id + device_code + grant_type=urn:ietf:params:oauth:grant-type:device_code)
9
+ * - 401/403 或 200 缺 token → 终态失效需重新登录
10
+ * ③ 续期:POST {oauthHost}/api/oauth/token (body: client_id + grant_type=refresh_token + refresh_token)
11
+ * - 宿主:大陆 https://auth.kimi.com + https://api.kimi.com/coding/v1
12
+ * 全球 https://auth.kimi.ai + https://api.kimi.ai/coding/v1
13
+ * - 对话:{baseUrl}/chat/completions(OpenAI 兼容)
14
+ * - 配额:{baseUrl}/usages(返回 limit5h, limit7d, monthTotal, monthCode)
15
+ * - 错误:429/402/额度文案 → 可换号;403+地域文案 → 地域限制判死
16
+ */
17
+
18
+ import { httpFetch, readBodyText, readSseData, mergeSseChunks } from '../util.js'
19
+
20
+ // ── 产品常量 ────────────────────────────────────────────────────────────────
21
+
22
+ const CLIENT_ID = '17e5f671-d194-4dfb-9706-5516cb48c098'
23
+ const DEFAULT_OAUTH_HOST_MAINLAND = 'https://auth.kimi.com'
24
+ const DEFAULT_OAUTH_HOST_GLOBAL = 'https://auth.kimi.ai'
25
+ const DEFAULT_BASE_URL_MAINLAND = 'https://api.kimi.com/coding/v1'
26
+ const DEFAULT_BASE_URL_GLOBAL = 'https://api.kimi.ai/coding/v1'
27
+
28
+ const DEVICE_AUTH_PATH = '/api/oauth/device_authorization'
29
+ const DEVICE_TOKEN_PATH = '/api/oauth/token'
30
+ const CHAT_PATH = '/chat/completions'
31
+ const MODELS_PATH = '/models'
32
+ const USAGE_PATH = '/usages'
33
+
34
+ const REQUEST_TIMEOUT_MS = 30_000
35
+ const MODELS_TIMEOUT_MS = 20_000
36
+ const BODY_READ_TIMEOUT_MS = 15_000
37
+ const DEVICE_AUTH_EXPIRES_MS = 300_000 // 5 分钟
38
+ const DEVICE_AUTH_INTERVAL_MS = 5_000
39
+ const POLL_MAX_FAILURES = 5
40
+ const REFRESH_LEAD_MS = 60 * 60_000 // 过期前 1 小时续期
41
+ const MAX_OUTPUT_TOKENS = 943_718
42
+
43
+ const FREE_ID_SUFFIX = ':free'
44
+ const FREE_ID_PREFIX = 'kimi-free/'
45
+
46
+ /**
47
+ * 模型消耗倍率(Kimi Code 官方文档口径,基准 k3-256k = 1)。
48
+ * 上游 /models 不返回任何价格/倍率字段(已实测 include_pricing 与各类 quota/pricing 端点均无),
49
+ * 因此倍率只能按文档口径折算;只补 rate,不参与模型清单,清单仍只认实时 /models。
50
+ */
51
+ const MODEL_RATES = {
52
+ k3: 2, // 文档:k3(1M 上下文)消耗约为 k3-256k 两倍
53
+ 'k3-256k': 1,
54
+ 'kimi-for-coding': 1, // K2.8 Preview,与 k3-256k 同档
55
+ 'kimi-for-coding-highspeed': 3, // 文档:高速版 6 倍速、3 倍消耗
56
+ }
57
+
58
+ // 无内置兜底模型表:清单只认上游实时 /models,拉不到即报错。
59
+
60
+ export const meta = { id: 'kimi', label: 'Kimi', loginMode: 'device-code' }
61
+
62
+ // ── 小工具 ──────────────────────────────────────────────────────────────────
63
+
64
+ function readStringField(source, key) {
65
+ const value = source?.[key]
66
+ if (typeof value === 'string' && value.trim().length > 0) return value.trim()
67
+ return ''
68
+ }
69
+
70
+ function parseTimestamp(value) {
71
+ if (typeof value === 'number' && Number.isFinite(value) && value > 0) {
72
+ return value < 1e12 ? Math.round(value * 1000) : Math.round(value)
73
+ }
74
+ if (typeof value === 'string' && value.trim().length > 0) {
75
+ const parsed = Date.parse(value)
76
+ if (Number.isFinite(parsed)) return parsed
77
+ }
78
+ return undefined
79
+ }
80
+
81
+ /** token 响应解析。
82
+ * 注意:expires_in 是相对秒数,需换算为绝对毫秒时间戳(OMR 约定 expire_time=毫秒)。 */
83
+ function tokenFromResponse(res) {
84
+ if (!res || typeof res !== 'object') return { accessToken: '' }
85
+ const accessToken = readStringField(res, 'access_token') || readStringField(res, 'accessToken')
86
+ const refreshToken = readStringField(res, 'refresh_token') || readStringField(res, 'refreshToken')
87
+ const expiresInSec = typeof res.expires_in === 'number' && Number.isFinite(res.expires_in) ? res.expires_in : NaN
88
+ // OMR 约定 expire_time 为毫秒;协议用的是秒。统一换算为毫秒。
89
+ const expiresAt = Number.isFinite(expiresInSec)
90
+ ? Date.now() + Math.round(expiresInSec * 1000)
91
+ : (parseTimestamp(res.expires_at) ?? parseTimestamp(res.expiresAt))
92
+ const scope = readStringField(res, 'scope')
93
+ const tokenType = readStringField(res, 'token_type')
94
+
95
+ return { accessToken, refreshToken, expiresAt, scope, tokenType }
96
+ }
97
+
98
+ /** 构造持久化凭据(从 tokenFromResponse 结果或手动粘贴)。 */
99
+ function buildCredential(payload, region = 'mainland-cn') {
100
+ const nickname = payload.email || payload.displayName || payload.accountId || ''
101
+ return {
102
+ region,
103
+ access_token: payload.accessToken,
104
+ ...(payload.refreshToken ? { refresh_token: payload.refreshToken } : {}),
105
+ ...(payload.expiresAt !== undefined ? { expire_time: payload.expiresAt } : {}),
106
+ ...(payload.accountId ? { account_id: payload.accountId } : {}),
107
+ ...(payload.email ? { email: payload.email } : {}),
108
+ ...(payload.displayName ? { displayName: payload.displayName } : {}),
109
+ ...(payload.scope ? { scope: payload.scope } : {}),
110
+ ...(payload.tokenType ? { tokenType: payload.tokenType } : {}),
111
+ ...(nickname ? { nickname } : {}),
112
+ }
113
+ }
114
+
115
+ /** 续期结果合并回既有凭据。 */
116
+ function applyRefresh(credential, payload) {
117
+ const next = { ...credential, access_token: payload.accessToken }
118
+ if (payload.refreshToken) next.refresh_token = payload.refreshToken
119
+ if (payload.expiresAt !== undefined) next.expire_time = payload.expiresAt
120
+ if (payload.accountId) next.account_id = payload.accountId
121
+ if (payload.email) next.email = payload.email
122
+ return next
123
+ }
124
+
125
+ /** 睡眠(可被 signal 中断)。 */
126
+ function sleep(ms, signal) {
127
+ return new Promise((resolve, reject) => {
128
+ if (signal?.aborted) { reject(new Error('登录已取消')); return }
129
+ const timer = setTimeout(() => {
130
+ signal?.removeEventListener('abort', onAbort)
131
+ resolve()
132
+ }, ms)
133
+ const onAbort = () => { clearTimeout(timer); reject(new Error('登录已取消')) }
134
+ signal?.addEventListener('abort', onAbort, { once: true })
135
+ })
136
+ }
137
+
138
+ // ── 登录(设备码 OAuth)─────────────────────────────────────────────────────
139
+
140
+ /** 请求设备码授权(OAuth 端点恒为 form 编码)。 */
141
+ async function requestDeviceAuthorization(signal, oauthHost) {
142
+ const response = await httpFetch(`${oauthHost}${DEVICE_AUTH_PATH}`, {
143
+ method: 'POST',
144
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
145
+ body: new URLSearchParams({ client_id: CLIENT_ID }).toString(),
146
+ signal,
147
+ }, REQUEST_TIMEOUT_MS)
148
+ const payload = await response.json().catch(() => ({}))
149
+ if (!response.ok) {
150
+ const detail = typeof payload.error_description === 'string' ? ` - ${payload.error_description}` : ''
151
+ throw new Error(`设备码授权失败(HTTP ${response.status})${detail}`)
152
+ }
153
+ const deviceCode = readStringField(payload, 'device_code')
154
+ const userCode = readStringField(payload, 'user_code')
155
+ const verificationUri = readStringField(payload, 'verification_uri')
156
+ const verificationUriComplete = readStringField(payload, 'verification_uri_complete')
157
+ // expires_in / interval 是秒数
158
+ const toMs = (value, fallback) => (typeof value === 'number' && Number.isFinite(value) && value > 0 ? value * 1000 : fallback)
159
+ if (!deviceCode || !userCode || !verificationUriComplete) {
160
+ throw new Error('设备码授权响应缺少必要字段')
161
+ }
162
+
163
+ return {
164
+ deviceCode,
165
+ userCode,
166
+ verificationUri,
167
+ verificationUriComplete,
168
+ expiresInMs: toMs(payload.expires_in, DEVICE_AUTH_EXPIRES_MS),
169
+ intervalMs: toMs(payload.interval, DEVICE_AUTH_INTERVAL_MS),
170
+ }
171
+ }
172
+
173
+ /** 轮询 device token。 */
174
+ async function pollDeviceToken(authorization, signal, oauthHost) {
175
+ const deadline = Date.now() + authorization.expiresInMs
176
+ let intervalMs = Math.max(1_000, authorization.intervalMs)
177
+ let failures = 0
178
+
179
+ while (Date.now() <= deadline) {
180
+ if (signal?.aborted) throw new Error('登录已取消')
181
+ try {
182
+ const response = await httpFetch(`${oauthHost}${DEVICE_TOKEN_PATH}`, {
183
+ method: 'POST',
184
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
185
+ body: new URLSearchParams({
186
+ client_id: CLIENT_ID,
187
+ device_code: authorization.deviceCode,
188
+ grant_type: 'urn:ietf:params:oauth:grant-type:device_code',
189
+ }).toString(),
190
+ signal,
191
+ }, REQUEST_TIMEOUT_MS)
192
+ const payload = await response.json().catch(() => ({}))
193
+ failures = 0
194
+ if (response.ok) {
195
+ const token = tokenFromResponse(payload)
196
+ if (!token.accessToken) throw new Error('token 响应缺少 access_token')
197
+ return token
198
+ }
199
+ const errorCode = readStringField(payload, 'error')
200
+ if (errorCode === 'authorization_pending') {
201
+ await sleep(intervalMs, signal)
202
+ continue
203
+ }
204
+ if (errorCode === 'slow_down') {
205
+ intervalMs += 1_000
206
+ await sleep(intervalMs, signal)
207
+ continue
208
+ }
209
+ if (errorCode === 'access_denied' || errorCode === 'expired_token' || errorCode === 'invalid_grant') {
210
+ throw new Error(readStringField(payload, 'error_description') || '设备码授权失败')
211
+ }
212
+ throw new Error(`token 轮询失败(HTTP ${response.status})`)
213
+ } catch (error) {
214
+ if (signal?.aborted) throw new Error('登录已取消')
215
+ if (error instanceof Error && !/fetch failed|network|ECONN|ENOTFOUND|ETIMEDOUT|timeout/i.test(error.message)) throw error
216
+ failures += 1
217
+ if (failures >= POLL_MAX_FAILURES) {
218
+ throw new Error(`无法连接 Kimi 登录服务(连续 ${failures} 次失败):${error?.message ?? error}`)
219
+ }
220
+ await sleep(intervalMs, signal)
221
+ }
222
+ }
223
+ throw new Error('登录等待已超时,请重新发起登录')
224
+ }
225
+
226
+ /** 启动设备码登录。options.region: 'mainland-cn'(默认)| 'global'。 */
227
+ export function startLogin(options = {}) {
228
+ const controller = new AbortController()
229
+ const signal = controller.signal
230
+ let readyAuth = null
231
+
232
+ const region = options.region === 'global' ? 'global' : 'mainland-cn'
233
+ const oauthHost = region === 'mainland-cn' ? DEFAULT_OAUTH_HOST_MAINLAND : DEFAULT_OAUTH_HOST_GLOBAL
234
+
235
+ const loginUrlReady = requestDeviceAuthorization(signal, oauthHost)
236
+ .then(auth => {
237
+ readyAuth = auth
238
+ // 返回实际的授权 URL(用户手动输入)
239
+ return auth.verificationUriComplete || auth.verificationUri
240
+ })
241
+
242
+ const promise = (async () => {
243
+ await loginUrlReady
244
+ // pollDeviceToken 已解析出 token(accessToken/refreshToken/expiresAt)
245
+ const token = await pollDeviceToken(readyAuth, signal, oauthHost)
246
+ return buildCredential(token, region)
247
+ })()
248
+ promise.catch(() => {})
249
+
250
+ let settled = false
251
+ return {
252
+ loginUrl: '',
253
+ loginUrlReady,
254
+ promise,
255
+ cancel: () => {
256
+ if (settled) return
257
+ settled = true
258
+ controller.abort()
259
+ },
260
+ }
261
+ }
262
+
263
+ /** 手动粘贴凭据的规范化。 */
264
+ export function normalizeCredential(raw) {
265
+ let value = raw
266
+ if (typeof value === 'string') {
267
+ try { value = JSON.parse(value) } catch { throw new Error('凭据不是合法 JSON') }
268
+ }
269
+ if (value === null || typeof value !== 'object' || Array.isArray(value)) {
270
+ throw new Error('凭据必须是 JSON 对象')
271
+ }
272
+ const accessToken = readStringField(value, 'access_token') || readStringField(value, 'accessToken')
273
+ const refreshToken = readStringField(value, 'refresh_token') || readStringField(value, 'refreshToken')
274
+ if (!accessToken && !refreshToken) throw new Error('凭据缺少 access_token / refresh_token')
275
+ const expiresAt = parseTimestamp(value.expire_time ?? value.expiresAt ?? value.expires_at)
276
+ return {
277
+ ...value,
278
+ access_token: accessToken,
279
+ ...(refreshToken ? { refresh_token: refreshToken } : {}),
280
+ ...(expiresAt !== undefined ? { expire_time: expiresAt } : {}),
281
+ }
282
+ }
283
+
284
+ /** 静默续期。 */
285
+ export async function refreshCredential(credential) {
286
+ if (!credential?.refresh_token) {
287
+ throw { kind: 'auth', retryable: false, terminal: true, message: '无 refresh_token,请重新登录' }
288
+ }
289
+ const { oauthHost } = resolveHosts(credential)
290
+
291
+ let response
292
+ try {
293
+ response = await httpFetch(`${oauthHost}${DEVICE_TOKEN_PATH}`, {
294
+ method: 'POST',
295
+ headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
296
+ body: new URLSearchParams({
297
+ client_id: CLIENT_ID,
298
+ grant_type: 'refresh_token',
299
+ refresh_token: credential.refresh_token,
300
+ }).toString(),
301
+ }, REQUEST_TIMEOUT_MS)
302
+ } catch (error) {
303
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Kimi 续期网络失败:${error?.message ?? error}` }
304
+ }
305
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
306
+ if (response.status === 401 || response.status === 403 || text.includes('invalid_grant')) {
307
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: `Kimi 续期被拒绝(HTTP ${response.status}),请重新登录` }
308
+ }
309
+ let parsed
310
+ try { parsed = JSON.parse(text) } catch {
311
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Kimi 续期响应不是 JSON(HTTP ${response.status})` }
312
+ }
313
+ if (!response.ok) {
314
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, message: `Kimi 续期失败(HTTP ${response.status}):${text.slice(0, 200)}` }
315
+ }
316
+ const payload = tokenFromResponse(parsed)
317
+ if (!payload.accessToken) {
318
+ throw { kind: 'auth', retryable: false, terminal: true, cooldownMs: 10 * 60_000, message: 'Kimi 续期响应缺少访问令牌,请重新登录' }
319
+ }
320
+ return applyRefresh(credential, payload)
321
+ }
322
+
323
+ /** 描述凭据。 */
324
+ export function describeCredential(credential) {
325
+ const nickname = readStringField(credential, 'nickname')
326
+ const email = readStringField(credential, 'email')
327
+ const accountId = readStringField(credential, 'account_id')
328
+ return {
329
+ label: nickname || email || accountId || 'Kimi 账号',
330
+ expiresAt: credential?.expire_time ?? 0,
331
+ refreshable: !!credential?.refresh_token,
332
+ }
333
+ }
334
+
335
+ export function credentialIdentity(credential) {
336
+ return readStringField(credential, 'account_id')
337
+ }
338
+
339
+ /** 续期判定:过期前 1 小时即刷新。 */
340
+ export function credentialExpiresAtMs(credential) {
341
+ const value = credential?.expire_time
342
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : undefined
343
+ }
344
+
345
+ export function isRefreshable(credential) {
346
+ return typeof credential?.refresh_token === 'string' && credential.refresh_token.length > 0
347
+ }
348
+
349
+ export function needsRefresh(credential) {
350
+ if (!isRefreshable(credential)) return false
351
+ const expiresAt = credentialExpiresAtMs(credential)
352
+ if (expiresAt === undefined) return false
353
+ return Date.now() >= expiresAt - REFRESH_LEAD_MS
354
+ }
355
+
356
+ /** 由 region 推导 OAuth 宿主与 API 基址。 */
357
+ function resolveHosts(credential) {
358
+ const region = readStringField(credential, 'region') || 'mainland-cn'
359
+ const isMainland = region !== 'global'
360
+ return {
361
+ region,
362
+ oauthHost: isMainland ? DEFAULT_OAUTH_HOST_MAINLAND : DEFAULT_OAUTH_HOST_GLOBAL,
363
+ baseUrl: isMainland ? DEFAULT_BASE_URL_MAINLAND : DEFAULT_BASE_URL_GLOBAL,
364
+ }
365
+ }
366
+
367
+ // ── 模型清单 ───────────────────────────────────────────────────────────────
368
+
369
+ function isFreeModel(id, remoteFreeIds) {
370
+ if (remoteFreeIds.has(id)) return true
371
+ if (id.endsWith(FREE_ID_SUFFIX)) return true
372
+ if (id.startsWith(FREE_ID_PREFIX)) return true
373
+ return false
374
+ }
375
+
376
+ function nameFromId(id) {
377
+ const slash = id.indexOf('/')
378
+ const tail = slash >= 0 ? id.slice(slash + 1) : id
379
+ return tail.replace(FREE_ID_SUFFIX, '').replace(/-/g, ' ').replace(/\b\w/g, c => c.toUpperCase())
380
+ }
381
+
382
+ /** 解析远端模型条目(保留上游 display_name / context_length 等元数据)。 */
383
+ function parseRemoteModels(value) {
384
+ if (!Array.isArray(value?.data)) return []
385
+ const out = []
386
+ for (const item of value.data) {
387
+ if (item === null || typeof item !== 'object') continue
388
+ if (typeof item.id !== 'string' || item.id.trim().length === 0) continue
389
+ const id = item.id.trim()
390
+ const entry = { id, name: readStringField(item, 'display_name') || nameFromId(id) }
391
+ const contextLength = item.context_length ?? item?.limit?.context
392
+ if (typeof contextLength === 'number' && Number.isFinite(contextLength) && contextLength > 0) {
393
+ entry.contextWindow = Math.round(contextLength)
394
+ }
395
+ if (typeof item.supports_image_in === 'boolean') entry.supportsImage = item.supports_image_in
396
+ if (typeof item.supports_reasoning === 'boolean') entry.supportsReasoning = item.supports_reasoning
397
+ out.push(entry)
398
+ }
399
+ return out
400
+ }
401
+
402
+ /**
403
+ * 查询 Kimi 实时模型清单。拉不到一律抛错(UI 勾选与目录只认实时清单,
404
+ * 不设兜底快照 —— 兜底会把已下架模型重新列出来)。
405
+ */
406
+ export async function fetchModels(credential) {
407
+ if (!credential?.access_token) throw new Error('Kimi 凭据缺少 access_token,请先重新登录')
408
+ const { baseUrl } = resolveHosts(credential)
409
+ const response = await httpFetch(`${baseUrl}${MODELS_PATH}`, {
410
+ method: 'GET',
411
+ headers: {
412
+ Authorization: `Bearer ${credential.access_token}`,
413
+ Accept: 'application/json',
414
+ },
415
+ }, MODELS_TIMEOUT_MS)
416
+ if (!response.ok) {
417
+ const text = await response.text().catch(() => '')
418
+ throw new Error(`Kimi 模型清单请求失败(HTTP ${response.status}):${extractMessage(text) || text.slice(0, 200) || '无响应体'}`)
419
+ }
420
+ const data = await response.json().catch(() => null)
421
+ if (!data) throw new Error('Kimi 模型清单响应不是合法 JSON')
422
+ const models = parseRemoteModels(data)
423
+ if (models.length === 0) throw new Error('Kimi 未返回任何模型(账号无权益或上游清单为空)')
424
+ const freeSet = new Set(models.filter(m => m.id.endsWith(FREE_ID_SUFFIX)).map(m => m.id))
425
+ return models.map(model => {
426
+ const entry = { ...model, isFree: isFreeModel(model.id, freeSet) }
427
+ const rate = MODEL_RATES[model.id]
428
+ if (typeof rate === 'number' && Number.isFinite(rate)) entry.rate = rate
429
+ return entry
430
+ })
431
+ }
432
+
433
+ // ── 对话 ───────────────────────────────────────────────────────────────────
434
+
435
+ /**
436
+ * 错误分类 → OMR 失败对象(带 rotate/terminal 字段,供 providers 轮换判断)。
437
+ * 429 / 402 / 额度文案 → 可换号(rotate)
438
+ * 401 / 403 → 凭据失效(rotate + terminal,需重新登录)
439
+ * 404 → 模型不存在(不可换号)
440
+ * 5xx → 可重试
441
+ */
442
+ function failureFrom(status, bodyText) {
443
+ const lower = String(bodyText ?? '').toLowerCase()
444
+ const message = extractMessage(bodyText) || `Kimi HTTP ${status}`
445
+ if (status === 429) return { kind: 'rate_limit', retryable: true, cooldownMs: 60_000, rotate: true, message }
446
+ if (status === 402 || /insufficient|quota|额度不足|余额不足|exceeded|limit/.test(lower)) {
447
+ return { kind: 'quota', retryable: false, cooldownMs: 30 * 60_000, rotate: true, message }
448
+ }
449
+ if (status === 401 || status === 403) {
450
+ return { kind: 'auth', retryable: false, cooldownMs: 10 * 60_000, rotate: true, terminal: true, message }
451
+ }
452
+ if (status === 404) return { kind: 'not_found', retryable: false, cooldownMs: 5 * 60_000, rotate: false, message }
453
+ if (status >= 500) return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
454
+ if (status >= 400) return { kind: 'request', retryable: false, cooldownMs: 60_000, rotate: false, message }
455
+ return { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message }
456
+ }
457
+
458
+ /** 从错误体抽人可读消息(JSON error/message/msg → 原文截断)。 */
459
+ function extractMessage(bodyText) {
460
+ const text = String(bodyText ?? '').trim()
461
+ if (text === '') return ''
462
+ try {
463
+ const parsed = JSON.parse(text)
464
+ const found = [
465
+ typeof parsed?.error?.message === 'string' ? parsed.error.message : '',
466
+ typeof parsed?.message === 'string' ? parsed.message : '',
467
+ typeof parsed?.error === 'string' ? parsed.error : '',
468
+ typeof parsed?.msg === 'string' ? parsed.msg : '',
469
+ ].filter(v => v.length > 0)
470
+ if (found.length > 0) return found.join(' ').slice(0, 300)
471
+ } catch { /* 非 JSON */ }
472
+ return text.slice(0, 300)
473
+ }
474
+
475
+ function buildChatBody(openaiBody) {
476
+ const body = { ...openaiBody, stream: true } // 恒流式,本地聚合
477
+ if (typeof body.max_tokens === 'number' && Number.isFinite(body.max_tokens) && body.max_tokens > 0) {
478
+ body.max_tokens = Math.min(Math.floor(body.max_tokens), MAX_OUTPUT_TOKENS)
479
+ } else {
480
+ delete body.max_tokens
481
+ }
482
+ return body
483
+ }
484
+
485
+ /** 单账号一轮对话。 */
486
+ export async function complete(credential, body, { signal, onData, headerTimeoutMs = 60_000 } = {}) {
487
+ const payload = JSON.stringify(buildChatBody(body))
488
+ const model = typeof body.model === 'string' ? body.model : ''
489
+ const { baseUrl } = resolveHosts(credential)
490
+
491
+ const response = await httpFetch(`${baseUrl}${CHAT_PATH}`, {
492
+ method: 'POST',
493
+ headers: {
494
+ Authorization: `Bearer ${credential.access_token}`,
495
+ 'Content-Type': 'application/json',
496
+ Accept: 'text/event-stream',
497
+ },
498
+ body: payload,
499
+ signal,
500
+ }, headerTimeoutMs)
501
+
502
+ if (!response.ok) {
503
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
504
+ throw failureFrom(response.status, text)
505
+ }
506
+ if (!response.body) throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Kimi 返回空响应体' }
507
+
508
+ const chunks = []
509
+ await readSseData(response.body, data => {
510
+ chunks.push(data)
511
+ onData?.(data)
512
+ }, signal)
513
+ const merged = mergeSseChunks(chunks)
514
+ if (!merged || !merged.choices?.[0]) {
515
+ throw { kind: 'server', retryable: true, cooldownMs: 30_000, rotate: true, message: 'Kimi 流结束但没有内容帧' }
516
+ }
517
+ if (merged.model !== undefined) merged.model = model
518
+ return { status: response.status, json: merged }
519
+ }
520
+
521
+ // ── 积分/配额余额 ──────────────────────────────────────────────────────────
522
+
523
+ /** 查询配额使用情况(/usages 返回 limit5h / limit7d / monthTotal / monthCode 等百分比窗口)。 */
524
+ export async function fetchCreditBalance(credential) {
525
+ const { baseUrl } = resolveHosts(credential)
526
+
527
+ try {
528
+ const response = await httpFetch(`${baseUrl}${USAGE_PATH}`, {
529
+ method: 'GET',
530
+ headers: {
531
+ Authorization: `Bearer ${credential.access_token}`,
532
+ Accept: 'application/json',
533
+ },
534
+ }, REQUEST_TIMEOUT_MS)
535
+ const text = await readBodyText(response, BODY_READ_TIMEOUT_MS).catch(() => '')
536
+ if (!response.ok) return null
537
+ let parsed
538
+ try { parsed = JSON.parse(text) } catch { return null }
539
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return null
540
+
541
+ // 百分比窗口:已使用比例(0–100)
542
+ const pct = key => {
543
+ const val = parsed?.[key]
544
+ if (typeof val === 'number' && Number.isFinite(val)) return Math.min(100, Math.max(0, Math.round(val)))
545
+ if (typeof val === 'string' && val.trim() !== '') {
546
+ const n = Number(val.replace('%', ''))
547
+ if (Number.isFinite(n)) return Math.min(100, Math.max(0, Math.round(n)))
548
+ }
549
+ return 0
550
+ }
551
+
552
+ const used5h = pct('limit5h')
553
+ const used7d = pct('limit7d')
554
+ const usedMonth = pct('monthTotal')
555
+
556
+ const pkg = {
557
+ name: 'Kimi 配额(5h / 7d / 月度)',
558
+ unit: '%',
559
+ remaining: 100 - Math.max(used5h, used7d),
560
+ total: 100,
561
+ used: Math.max(used5h, used7d),
562
+ active: true,
563
+ cycleStartTime: '',
564
+ cycleEndTime: '',
565
+ expiredTime: '',
566
+ note: `5h 已用 ${used5h}%,7d 已用 ${used7d}%,月度已用 ${usedMonth}%`,
567
+ }
568
+ return { total: 100, packages: [pkg], expiredTotal: 0 }
569
+ } catch {
570
+ return null
571
+ }
572
+ }