dsh-token-dash 2.5.0 → 2.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +2 -2
- package/README.en.md +55 -91
- package/README.md +54 -91
- package/client.js +134 -33
- package/index.js +19 -2
- package/locale/en.json +10 -1
- package/locale/zh.json +10 -1
- package/package.json +8 -3
- package/src/adapters.js +394 -84
- package/src/collect.js +39 -12
- package/src/core.js +26 -5
- package/src/providers.js +19 -1
- package/src/quota-sources.js +132 -3
- package/src/store.js +15 -0
package/src/adapters.js
CHANGED
|
@@ -3,7 +3,13 @@
|
|
|
3
3
|
* the reference plugins; do not invent fields or percentages.
|
|
4
4
|
*/
|
|
5
5
|
import { normalizeProvider, providerCurrency, providerLabel } from './providers.js'
|
|
6
|
-
import {
|
|
6
|
+
import {
|
|
7
|
+
GLM_QUOTA_CN,
|
|
8
|
+
KIMI_USAGES_CN,
|
|
9
|
+
MOONSHOT_BALANCE_CN,
|
|
10
|
+
PROVIDER_SOURCES,
|
|
11
|
+
REGION_PROFILES,
|
|
12
|
+
} from './quota-sources.js'
|
|
7
13
|
|
|
8
14
|
const TIMEOUT = 6000
|
|
9
15
|
// 宿主服务调用没有内置超时(2026-11-23:deepseekAccount.getBalance 曾挂起 30s)。
|
|
@@ -28,9 +34,13 @@ async function withHostTimeout(promise, label) {
|
|
|
28
34
|
clearTimeout(timer)
|
|
29
35
|
}
|
|
30
36
|
}
|
|
31
|
-
|
|
32
|
-
const
|
|
33
|
-
const
|
|
37
|
+
// 区域端点在 quota-sources.js 的 REGION_PROFILES 里;这里保留 CN 主域别名给旧导出与测试用
|
|
38
|
+
const GLM_QUOTA = GLM_QUOTA_CN
|
|
39
|
+
const KIMI_USAGES = KIMI_USAGES_CN
|
|
40
|
+
// 社区与官方 CLI 实测:缺该身份头时 usages 可能直接 404(Issue #1)
|
|
41
|
+
const KIMI_UA = 'KimiCLI/1.6'
|
|
42
|
+
const KIMI_BALANCE = MOONSHOT_BALANCE_CN
|
|
43
|
+
const REGION_IDS = ['cn', 'global']
|
|
34
44
|
const OPENROUTER_CREDITS = 'https://openrouter.ai/api/v1/credits'
|
|
35
45
|
|
|
36
46
|
export function clampPercent(value) {
|
|
@@ -55,42 +65,52 @@ export function parseGlmQuota(body) {
|
|
|
55
65
|
return windows
|
|
56
66
|
}
|
|
57
67
|
|
|
58
|
-
|
|
59
|
-
|
|
68
|
+
/** Kimi 单个窗口:官方线上报文是 snake_case,官方 schema 名是 camelCase,两套都接。 */
|
|
69
|
+
function kimiWindow(key, raw) {
|
|
70
|
+
if (raw === null || raw === undefined || typeof raw !== 'object') return undefined
|
|
71
|
+
const used = clampPercent(raw.used_ratio ?? raw.usedRatio ?? raw.used_percent ?? raw.usedPercent)
|
|
60
72
|
if (used === null) return undefined
|
|
61
|
-
return { key, usedPercent: used, resetAt:
|
|
73
|
+
return { key, usedPercent: used, resetAt: kimiReset(raw), source: 'official' }
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** reset_time 可能是毫秒数、数字串或 ISO 字符串(官方 schema 为 string)。 */
|
|
77
|
+
function kimiReset(raw) {
|
|
78
|
+
const value = raw?.reset_time ?? raw?.resetTime ?? raw?.reset_at ?? raw?.resetAt
|
|
79
|
+
if (value === undefined || value === null) return undefined
|
|
80
|
+
const numeric = Number(value)
|
|
81
|
+
if (Number.isFinite(numeric) && numeric > 0) return numeric
|
|
82
|
+
const parsed = typeof value === 'string' ? Date.parse(value) : NaN
|
|
83
|
+
return Number.isFinite(parsed) ? parsed : undefined
|
|
62
84
|
}
|
|
63
85
|
|
|
64
86
|
export function parseKimiQuota(body) {
|
|
65
87
|
const record = body?.data ?? body
|
|
66
|
-
const windows = []
|
|
67
88
|
const usages = record?.usages
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
const
|
|
75
|
-
if (
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
}
|
|
89
|
+
// 线上:usages.limit_5h / limit_7d / limit_month_total / limit_month_code;
|
|
90
|
+
// 官方 schema 名:limit5h / limit7d / monthTotal / monthCode。顺序统一为 5h / week / month。
|
|
91
|
+
const five = kimiWindow('5h', usages?.limit_5h ?? usages?.limit5h)
|
|
92
|
+
const week = kimiWindow('week', usages?.limit_7d ?? usages?.limit7d) ?? kimiWindow('week', record?.usage)
|
|
93
|
+
const month = kimiWindow('month', usages?.limit_month_code ?? usages?.monthCode)
|
|
94
|
+
?? kimiWindow('month', usages?.limit_month_total ?? usages?.monthTotal)
|
|
95
|
+
const windows = [five, week, month].filter(Boolean)
|
|
96
|
+
if (windows.length > 0) return windows
|
|
97
|
+
// 旧结构兜底:limits[] + usage.limit / used
|
|
98
|
+
const limits = Array.isArray(record?.limits) ? record.limits : []
|
|
99
|
+
const legacyFive = limits
|
|
100
|
+
.map((item) => {
|
|
101
|
+
const detail = item?.detail ?? item
|
|
102
|
+
const limit = Number(detail?.limit)
|
|
103
|
+
const used = detail?.used !== undefined ? Number(detail.used) : (limit - Number(detail?.remaining))
|
|
104
|
+
const percent = limit > 0 && Number.isFinite(used) ? clampPercent((used / limit) * 100) : null
|
|
105
|
+
return percent === null ? null : { key: '5h', usedPercent: percent, resetAt: kimiReset(detail), source: 'official' }
|
|
106
|
+
})
|
|
107
|
+
.filter(Boolean)
|
|
108
|
+
.sort((left, right) => (right.resetAt ?? 0) - (left.resetAt ?? 0))
|
|
109
|
+
if (legacyFive[0]) windows.push(legacyFive[0])
|
|
110
|
+
const usage = record?.usage
|
|
111
|
+
const limit = Number(usage?.limit)
|
|
112
|
+
const used = Number(usage?.used)
|
|
113
|
+
if (limit > 0 && Number.isFinite(used)) windows.push({ key: 'week', usedPercent: clampPercent((used / limit) * 100), resetAt: kimiReset(usage), source: 'official' })
|
|
94
114
|
return windows
|
|
95
115
|
}
|
|
96
116
|
|
|
@@ -123,8 +143,8 @@ async function resolveKey(ctx, names) {
|
|
|
123
143
|
return undefined
|
|
124
144
|
}
|
|
125
145
|
|
|
126
|
-
async function requestJson(url, headers) {
|
|
127
|
-
const response = await fetch(url, { headers: { accept: 'application/json', ...headers }, signal: AbortSignal.timeout(
|
|
146
|
+
async function requestJson(url, headers, timeoutMs = TIMEOUT) {
|
|
147
|
+
const response = await fetch(url, { headers: { accept: 'application/json', ...headers }, signal: AbortSignal.timeout(timeoutMs) })
|
|
128
148
|
const body = await response.json().catch(() => null)
|
|
129
149
|
if (!response.ok) {
|
|
130
150
|
const error = new Error(`http-${response.status}`)
|
|
@@ -180,23 +200,99 @@ async function deepseek(ctx) {
|
|
|
180
200
|
}
|
|
181
201
|
}
|
|
182
202
|
|
|
203
|
+
function sourceOf(id) {
|
|
204
|
+
return PROVIDER_SOURCES.find((item) => item.id === id)
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function regionProfileOf(providerId, region) {
|
|
208
|
+
return REGION_PROFILES[providerId]?.[region]
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** 解析 refs 中所有可用 Key(用于按区域挑凭据)。 */
|
|
212
|
+
async function resolveKeys(ctx, names) {
|
|
213
|
+
const keys = []
|
|
214
|
+
for (const name of names) {
|
|
215
|
+
const hit = await resolveKey(ctx, [name])
|
|
216
|
+
if (hit !== undefined) keys.push(hit)
|
|
217
|
+
}
|
|
218
|
+
return keys
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/**
|
|
222
|
+
* 区域只来自三个来源:prefs.providerRegion → 凭据名 hint → 默认 cn。
|
|
223
|
+
* 不看响应判断(GLM 恒 200、Kimi 401 不指向区域、Qwen 无请求),MiniMax 例外。
|
|
224
|
+
*/
|
|
225
|
+
function resolveRegion(providerId, names, source, prefs) {
|
|
226
|
+
const manual = prefs?.providerRegion?.[providerId]
|
|
227
|
+
if (manual === 'cn' || manual === 'global') return { region: manual, source: 'manual' }
|
|
228
|
+
const hinted = names.map((name) => source?.hint?.[name]).find((region) => region !== undefined)
|
|
229
|
+
if (hinted !== undefined) return { region: hinted, source: 'hint' }
|
|
230
|
+
return { region: 'cn', source: 'default' }
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** hint 命中该区的 Key 优先;该区没有对应凭据时退回第一把,切错区由鉴权失败暴露。 */
|
|
234
|
+
function pickKey(keys, source, region) {
|
|
235
|
+
return keys.find((key) => source?.hint?.[key.name] === region) ?? keys[0]
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** GLM 恒 200:鉴权与业务失败都在 body 里,code 0 / 200 视为成功。 */
|
|
239
|
+
function glmBusinessError(body) {
|
|
240
|
+
const code = Number(body?.code)
|
|
241
|
+
if (Number.isFinite(code) && code !== 0 && code !== 200) {
|
|
242
|
+
const kind = code === 401 || code === 403 || code === 1001 ? 'auth' : 'business'
|
|
243
|
+
return { kind, bodyCode: code }
|
|
244
|
+
}
|
|
245
|
+
if (body?.success === false) return { kind: 'business' }
|
|
246
|
+
return null
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** 同区主域失败按回退矩阵换备域;不跨区。 */
|
|
250
|
+
async function requestFirstOk(urls, headers, timeoutMs) {
|
|
251
|
+
const list = Array.isArray(urls) ? urls : []
|
|
252
|
+
let lastError
|
|
253
|
+
for (const [index, url] of list.entries()) {
|
|
254
|
+
try {
|
|
255
|
+
return await requestJson(url, headers, timeoutMs)
|
|
256
|
+
} catch (error) {
|
|
257
|
+
lastError = error
|
|
258
|
+
if (index === list.length - 1 || isFallbackError(error) !== true) throw error
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
throw lastError ?? new Error('no-endpoint')
|
|
262
|
+
}
|
|
263
|
+
|
|
183
264
|
async function glm(ctx, prefs) {
|
|
184
|
-
const
|
|
185
|
-
|
|
265
|
+
const source = sourceOf('zhipu')
|
|
266
|
+
const keys = await resolveKeys(ctx, ['ZAI_CODING_CN_API_KEY', 'ZHIPU_API_KEY', 'GLM_API_KEY', 'ZAI_API_KEY'])
|
|
267
|
+
if (keys.length === 0) return null
|
|
268
|
+
const resolved = resolveRegion('zhipu', keys.map((key) => key.name), source, prefs)
|
|
269
|
+
const key = pickKey(keys, source, resolved.region)
|
|
270
|
+
const profile = regionProfileOf('zhipu', resolved.region) ?? { currency: 'CNY', quota: [GLM_QUOTA] }
|
|
271
|
+
const currency = profile.currency
|
|
272
|
+
const base = {
|
|
273
|
+
id: 'zhipu',
|
|
274
|
+
currency,
|
|
275
|
+
region: resolved.region,
|
|
276
|
+
regions: source?.regions ?? REGION_IDS,
|
|
277
|
+
regionSource: resolved.source,
|
|
278
|
+
}
|
|
186
279
|
const mode = prefs?.billingModes?.zhipu
|
|
187
|
-
if (mode === 'api') return {
|
|
280
|
+
if (mode === 'api') return { ...base, kind: 'api', mode: 'api' }
|
|
188
281
|
// 手动覆盖为订阅时,quota 失败/无窗口仍保留订阅卡(显示“套餐查询失败”),不回落 api。
|
|
189
|
-
const
|
|
190
|
-
|
|
191
|
-
|
|
282
|
+
const subscription = { ...base, name: 'GLM Coding', kind: 'subscription', mode: 'subscription' }
|
|
283
|
+
const subscriptionFallback = mode === 'subscription' ? { ...subscription, plans: [] } : null
|
|
284
|
+
const unknown = { ...base, kind: 'api', mode: 'unknown' }
|
|
192
285
|
try {
|
|
193
|
-
const body = await
|
|
286
|
+
const body = await requestFirstOk(profile.quota, { authorization: key.value })
|
|
287
|
+
// 鉴权 / 业务失败都是 200 + body.code(GLM 恒 200),必须先分类再看窗口
|
|
288
|
+
const business = glmBusinessError(body)
|
|
289
|
+
if (business !== null) return { ...(subscriptionFallback ?? unknown), _quotaError: business }
|
|
194
290
|
const windows = parseGlmQuota(body)
|
|
195
|
-
if (windows.length > 0) return {
|
|
291
|
+
if (windows.length > 0) return { ...subscription, plans: windows }
|
|
196
292
|
// 响应可解析但无窗口:解析问题(quota.parse),非网络错误
|
|
197
|
-
return { ...(subscriptionFallback ??
|
|
293
|
+
return { ...(subscriptionFallback ?? unknown), _quotaError: { kind: 'parse' } }
|
|
198
294
|
} catch (error) {
|
|
199
|
-
return { ...(subscriptionFallback ??
|
|
295
|
+
return { ...(subscriptionFallback ?? unknown), _quotaError: errorDetail(error) }
|
|
200
296
|
}
|
|
201
297
|
}
|
|
202
298
|
|
|
@@ -205,22 +301,33 @@ async function glm(ctx, prefs) {
|
|
|
205
301
|
* 返回 { state }:'no-key'(无 Coding Key 或显式 api 模式)、'ok'(含 entry)、'fallback'(自动模式下配额失败,走按量路径)。
|
|
206
302
|
*/
|
|
207
303
|
async function kimiCodingQuota(ctx, prefs) {
|
|
208
|
-
const
|
|
209
|
-
|
|
304
|
+
const source = sourceOf('moonshot')
|
|
305
|
+
const keys = await resolveKeys(ctx, ['KIMI_API_KEY', 'KIMI_CODING_API_KEY'])
|
|
306
|
+
if (keys.length === 0) return { state: 'no-key' }
|
|
210
307
|
const mode = prefs?.billingModes?.moonshot
|
|
211
308
|
if (mode === 'api') return { state: 'no-key' }
|
|
309
|
+
const resolved = resolveRegion('moonshot', keys.map((key) => key.name), source, prefs)
|
|
310
|
+
const key = pickKey(keys, source, resolved.region)
|
|
311
|
+
const profile = regionProfileOf('moonshot', resolved.region) ?? { currency: 'CNY', quota: [KIMI_USAGES] }
|
|
312
|
+
const base = {
|
|
313
|
+
id: 'moonshot',
|
|
314
|
+
name: 'Kimi Coding',
|
|
315
|
+
currency: profile.currency,
|
|
316
|
+
region: resolved.region,
|
|
317
|
+
regions: source?.regions ?? REGION_IDS,
|
|
318
|
+
regionSource: resolved.source,
|
|
319
|
+
}
|
|
212
320
|
let quotaError = null
|
|
213
321
|
try {
|
|
214
|
-
const body = await
|
|
322
|
+
const body = await requestFirstOk(profile.quota, { authorization: `Bearer ${key.value}`, 'user-agent': KIMI_UA })
|
|
215
323
|
const windows = parseKimiQuota(body)
|
|
216
|
-
if (windows.length > 0) return { state: 'ok', entry: {
|
|
324
|
+
if (windows.length > 0) return { state: 'ok', entry: { ...base, kind: 'subscription', mode: 'subscription', plans: windows } }
|
|
217
325
|
quotaError = { kind: 'parse' }
|
|
218
326
|
} catch (error) {
|
|
219
327
|
quotaError = errorDetail(error)
|
|
220
328
|
}
|
|
221
|
-
if (mode === 'subscription') return { state: 'ok', entry: {
|
|
222
|
-
return { state: 'fallback', quotaError }
|
|
223
|
-
return { state: 'fallback' }
|
|
329
|
+
if (mode === 'subscription') return { state: 'ok', entry: { ...base, kind: 'subscription', mode: 'subscription', plans: [], _quotaError: quotaError } }
|
|
330
|
+
return { state: 'fallback', quotaError, region: resolved.region, regionSource: resolved.source, currency: profile.currency }
|
|
224
331
|
}
|
|
225
332
|
|
|
226
333
|
async function kimi(ctx, prefs) {
|
|
@@ -228,17 +335,31 @@ async function kimi(ctx, prefs) {
|
|
|
228
335
|
if (quota.state === 'ok') return quota.entry
|
|
229
336
|
const quotaError = quota.quotaError ?? null
|
|
230
337
|
const normal = await resolveKey(ctx, ['MOONSHOT_API_KEY'])
|
|
231
|
-
if (normal === undefined)
|
|
338
|
+
if (normal === undefined) {
|
|
339
|
+
return quota.state === 'no-key'
|
|
340
|
+
? null
|
|
341
|
+
: { id: 'moonshot', kind: 'api', mode: 'unknown', currency: quota.currency ?? 'CNY', region: quota.region, regions: sourceOf('moonshot')?.regions ?? REGION_IDS, _quotaError: quotaError }
|
|
342
|
+
}
|
|
343
|
+
const source = sourceOf('moonshot')
|
|
344
|
+
// 余额 host 随区域:Kimi Coding 与 Moonshot 平台同区配对
|
|
345
|
+
const resolved = resolveRegion('moonshot', [normal.name], source, prefs)
|
|
346
|
+
const profile = regionProfileOf('moonshot', resolved.region) ?? { currency: 'CNY', balanceHost: KIMI_BALANCE }
|
|
347
|
+
const currency = profile.currency
|
|
348
|
+
const base = {
|
|
349
|
+
id: 'moonshot', kind: 'api', mode: 'unknown', currency,
|
|
350
|
+
region: resolved.region, regions: source?.regions ?? REGION_IDS, regionSource: resolved.source,
|
|
351
|
+
_quotaError: quotaError,
|
|
352
|
+
}
|
|
232
353
|
try {
|
|
233
|
-
const body = await requestJson(
|
|
354
|
+
const body = await requestJson(profile.balanceHost, { authorization: `Bearer ${normal.value}` })
|
|
234
355
|
const amount = Number(body?.data?.available_balance)
|
|
235
356
|
const ok = Number.isFinite(amount)
|
|
236
357
|
return {
|
|
237
|
-
|
|
238
|
-
balance: { amount: ok ? amount : null, status: ok ? 'ok' : 'error', currency
|
|
358
|
+
...base,
|
|
359
|
+
balance: { amount: ok ? amount : null, status: ok ? 'ok' : 'error', currency, updatedAt: Date.now(), ...(ok ? {} : { _error: { kind: 'parse' } }) },
|
|
239
360
|
}
|
|
240
361
|
} catch (error) {
|
|
241
|
-
return {
|
|
362
|
+
return { ...base, _error: errorDetail(error), balance: { amount: null, status: 'error', currency, updatedAt: Date.now() } }
|
|
242
363
|
}
|
|
243
364
|
}
|
|
244
365
|
|
|
@@ -254,13 +375,106 @@ async function openrouter(ctx) {
|
|
|
254
375
|
}
|
|
255
376
|
}
|
|
256
377
|
|
|
257
|
-
/** Qwen
|
|
258
|
-
async function qwen(ctx) {
|
|
259
|
-
const
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
const
|
|
263
|
-
|
|
378
|
+
/** Qwen 仅按量;区域由凭据名决定(国际站 Key → global / USD),无请求。 */
|
|
379
|
+
async function qwen(ctx, prefs) {
|
|
380
|
+
const source = sourceOf('qwen')
|
|
381
|
+
const keys = await resolveKeys(ctx, ['DASHSCOPE_INTL_API_KEY', 'DASHSCOPE_API_KEY', 'QWEN_API_KEY'])
|
|
382
|
+
if (keys.length === 0) return null
|
|
383
|
+
const resolved = resolveRegion('qwen', keys.map((key) => key.name), source, prefs)
|
|
384
|
+
const currency = regionProfileOf('qwen', resolved.region)?.currency ?? 'CNY'
|
|
385
|
+
return {
|
|
386
|
+
id: 'qwen', kind: 'api', currency,
|
|
387
|
+
region: resolved.region, regions: source?.regions ?? REGION_IDS, regionSource: resolved.source,
|
|
388
|
+
balance: { amount: null, status: 'unsupported', currency, updatedAt: Date.now() },
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** 区内只有「换个域名可能成功」的失败才换备域;鉴权 / 限流 / 业务错误不在此列。 */
|
|
393
|
+
function isFallbackError(error) {
|
|
394
|
+
if (error?.status === undefined) return true
|
|
395
|
+
return error.status === 404 || error.status === 405 || error.status >= 500
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
/** 解析 refs 中所有可用的 Key(refs 顺序);region 提示同时用于探测顺序与「哪个区用哪把 Key」。 */
|
|
399
|
+
async function resolveCredentialSet(ctx, source) {
|
|
400
|
+
const hits = []
|
|
401
|
+
for (const ref of source.credential?.refs ?? []) {
|
|
402
|
+
const hit = await resolveKey(ctx, [ref])
|
|
403
|
+
if (hit !== undefined) hits.push({ ...hit, region: source.quota.hint?.[ref] })
|
|
404
|
+
}
|
|
405
|
+
return hits
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
const REGION_PINS = new Map()
|
|
409
|
+
export function resetRegionPins() { REGION_PINS.clear() }
|
|
410
|
+
|
|
411
|
+
/** 区域 → 凭据:手动(该区有 Key 才生效)→ pin → 有 Key 的区域 → 其余。 */
|
|
412
|
+
function regionCandidates(source, prefs, hits) {
|
|
413
|
+
const ids = Object.keys(source.quota.regions ?? {})
|
|
414
|
+
if (ids.length === 0) return [{ region: null, hit: hits[0] }]
|
|
415
|
+
const byRegion = new Map()
|
|
416
|
+
for (const hit of hits) {
|
|
417
|
+
if (hit.region !== undefined && !byRegion.has(hit.region)) byRegion.set(hit.region, hit)
|
|
418
|
+
}
|
|
419
|
+
const manual = prefs?.providerRegion?.[source.id]
|
|
420
|
+
if (manual !== undefined && byRegion.has(manual)) return [{ region: manual, hit: byRegion.get(manual) }]
|
|
421
|
+
const pinned = REGION_PINS.get(`${source.id}:${hits[0].name}`)
|
|
422
|
+
const first = [pinned, hits[0].region, ...ids].find((id) => id !== undefined && byRegion.has(id)) ?? ids[0]
|
|
423
|
+
return [first, ...ids.filter((id) => id !== first)].map((region) => ({ region, hit: byRegion.get(region) ?? hits[0] }))
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
function keyKindOf(source, key) {
|
|
427
|
+
for (const [prefix, kind] of source.quota.keyKinds ?? []) {
|
|
428
|
+
if (key.startsWith(prefix)) return kind
|
|
429
|
+
}
|
|
430
|
+
return null
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** 一个区域的请求:主域失败按回退矩阵换同区备域,不跨区。 */
|
|
434
|
+
async function fetchRegion(urls, query, key, timeoutMs) {
|
|
435
|
+
let lastError
|
|
436
|
+
for (const [index, url] of urls.entries()) {
|
|
437
|
+
try {
|
|
438
|
+
return await requestJson(withQuery(url, query), { authorization: `Bearer ${key}` }, timeoutMs)
|
|
439
|
+
} catch (error) {
|
|
440
|
+
lastError = error
|
|
441
|
+
if (index === urls.length - 1 || isFallbackError(error) !== true) throw error
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
throw lastError ?? new Error('no-endpoint')
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
/** sk-api-:查余额而不是套餐;区域探测与订阅一致,命中即 pin。 */
|
|
448
|
+
async function readPaygoBalance(ctx, prefs, source, hits) {
|
|
449
|
+
const order = regionCandidates(source, prefs, hits).filter((item) => item.region !== null)
|
|
450
|
+
const regionIds = [...new Set(hits.map((item) => item.region).filter(Boolean))]
|
|
451
|
+
const base = {
|
|
452
|
+
id: source.id, name: providerLabel(source.id), kind: 'api', mode: 'api',
|
|
453
|
+
...(regionIds.length > 0 ? { regions: regionIds } : {}),
|
|
454
|
+
}
|
|
455
|
+
let lastError = null
|
|
456
|
+
for (const { region, hit } of order) {
|
|
457
|
+
const cfg = source.quota.regions[region]
|
|
458
|
+
try {
|
|
459
|
+
const body = await requestJson(cfg.balanceUrl, { authorization: `Bearer ${hit.value}` })
|
|
460
|
+
const parsed = source.quota.paygo.parse(body)
|
|
461
|
+
if (parsed.balance.status === 'ok') {
|
|
462
|
+
REGION_PINS.set(`${source.id}:${hits[0].name}`, region)
|
|
463
|
+
return { ...base, currency: cfg.currency, region, windows: [], balance: { ...parsed.balance, currency: cfg.currency } }
|
|
464
|
+
}
|
|
465
|
+
lastError = parsed.balance._error ?? { kind: 'parse' }
|
|
466
|
+
} catch (error) {
|
|
467
|
+
lastError = errorDetail(error)
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
const currency = order[0] === undefined ? source.currency : source.quota.regions[order[0].region].currency
|
|
471
|
+
return {
|
|
472
|
+
...base,
|
|
473
|
+
currency,
|
|
474
|
+
windows: [],
|
|
475
|
+
balance: { amount: null, status: 'error', currency, updatedAt: Date.now(), ...(lastError === null ? {} : { _error: lastError }) },
|
|
476
|
+
_quotaError: { kind: 'paygo' },
|
|
477
|
+
}
|
|
264
478
|
}
|
|
265
479
|
|
|
266
480
|
const LEGACY_READERS = { deepseek, glm, kimi, openrouter, qwen }
|
|
@@ -311,19 +525,79 @@ async function readSourceUsage(source, hit) {
|
|
|
311
525
|
}
|
|
312
526
|
|
|
313
527
|
async function readDeclarativeSource(ctx, prefs, source, previous) {
|
|
314
|
-
const
|
|
315
|
-
if (
|
|
528
|
+
const hits = await resolveCredentialSet(ctx, source)
|
|
529
|
+
if (hits.length === 0) return null
|
|
530
|
+
const hit = hits[0]
|
|
316
531
|
const subscription = source.kind === 'subscription'
|
|
532
|
+
const manual = prefs?.providerRegion?.[source.id]
|
|
533
|
+
const manualMiss = manual !== undefined && !hits.some((item) => item.region === manual)
|
|
534
|
+
const regionIds = [...new Set(hits.map((item) => item.region).filter(Boolean))]
|
|
317
535
|
// mode 必须由 kind 派生:声明式订阅源才是订阅;写成常量会把 api 源固化成订阅(cost=0)
|
|
318
|
-
const base = {
|
|
536
|
+
const base = {
|
|
537
|
+
id: source.id,
|
|
538
|
+
name: providerLabel(source.id),
|
|
539
|
+
kind: source.kind,
|
|
540
|
+
mode: subscription ? 'subscription' : 'api',
|
|
541
|
+
currency: source.currency,
|
|
542
|
+
...(regionIds.length > 0 ? { regions: regionIds } : {}),
|
|
543
|
+
...(manualMiss ? { manualMiss: true } : {}),
|
|
544
|
+
}
|
|
545
|
+
// 按量 Key:不查套餐,改查余额(regionCandidates 复用)
|
|
546
|
+
if (keyKindOf(source, hit.value) === 'paygo') return readPaygoBalance(ctx, prefs, source, hits)
|
|
319
547
|
const query = await sourceQuery(ctx, source)
|
|
548
|
+
const order = regionCandidates(source, prefs, hits)
|
|
320
549
|
let body
|
|
550
|
+
let parsedBody = null
|
|
551
|
+
let chosen = null
|
|
552
|
+
let auth = null
|
|
553
|
+
let lastError = null
|
|
321
554
|
try {
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
555
|
+
for (const { region: regionId, hit: cred } of order) {
|
|
556
|
+
const urls = (regionId === null
|
|
557
|
+
? [source.quota.url, source.quota.fallbackUrl]
|
|
558
|
+
: source.quota.regions[regionId].urls).filter((url) => typeof url === 'string')
|
|
559
|
+
try {
|
|
560
|
+
const candidate = await fetchRegion(urls, query, cred.value, source.quota.probeTimeoutMs)
|
|
561
|
+
const parsed = source.quota.parse(candidate)
|
|
562
|
+
if (parsed?.businessError !== undefined) {
|
|
563
|
+
auth = { ...parsed.businessError, region: regionId }
|
|
564
|
+
// 鉴权失败是「这把 Key 不属于该区」的唯一可靠信号,继续探下一区
|
|
565
|
+
if (parsed.businessError.kind === 'auth' && regionId !== null) continue
|
|
566
|
+
break
|
|
567
|
+
}
|
|
568
|
+
body = candidate
|
|
569
|
+
parsedBody = parsed
|
|
570
|
+
chosen = regionId
|
|
571
|
+
break
|
|
572
|
+
} catch (error) {
|
|
573
|
+
// 只有多区域源才把 401/403 当作「Key 不属于该区」;单区域源交给失败收尾
|
|
574
|
+
if (regionId !== null && (error.status === 401 || error.status === 403)) {
|
|
575
|
+
auth = { kind: 'auth', status: error.status, region: regionId }
|
|
576
|
+
continue
|
|
577
|
+
}
|
|
578
|
+
// 网络 / 5xx / 429 / 单区域鉴权失败都不是区域证据,停止探测
|
|
579
|
+
lastError = error
|
|
580
|
+
break
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
if (body === undefined) {
|
|
584
|
+
if (auth?.kind === 'auth') REGION_PINS.delete(`${source.id}:${hits[0].name}`)
|
|
585
|
+
if (subscription && lastError === null && auth !== null) {
|
|
586
|
+
const cfg = source.quota.regions?.[auth.region]
|
|
587
|
+
const manualHit = prefs?.providerRegion?.[source.id] === auth.region
|
|
588
|
+
return {
|
|
589
|
+
...base,
|
|
590
|
+
windows: [],
|
|
591
|
+
...(cfg === undefined ? {} : { currency: cfg.currency }),
|
|
592
|
+
_quotaError: { ...auth, tried: order.length, manual: manualHit },
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
throw lastError ?? Object.assign(new Error('auth'), { status: 401 })
|
|
596
|
+
}
|
|
597
|
+
if (chosen !== null) {
|
|
598
|
+
REGION_PINS.set(`${source.id}:${hits[0].name}`, chosen)
|
|
599
|
+
base.currency = source.quota.regions[chosen].currency
|
|
600
|
+
base.region = chosen
|
|
327
601
|
}
|
|
328
602
|
} catch (error) {
|
|
329
603
|
const detail = errorDetail(error)
|
|
@@ -335,11 +609,13 @@ async function readDeclarativeSource(ctx, prefs, source, previous) {
|
|
|
335
609
|
return {
|
|
336
610
|
...base,
|
|
337
611
|
windows: [],
|
|
338
|
-
...(subscription ? {} : { balance: { amount: null, status, currency:
|
|
612
|
+
...(subscription ? {} : { balance: { amount: null, status, currency: base.currency, updatedAt: Date.now() } }),
|
|
339
613
|
_quotaError: detail,
|
|
340
614
|
}
|
|
341
615
|
}
|
|
342
|
-
const parsed = source.quota.parse(body)
|
|
616
|
+
const parsed = parsedBody ?? source.quota.parse(body)
|
|
617
|
+
if (parsed?.businessError !== undefined) return { ...base, windows: [], _quotaError: parsed.businessError }
|
|
618
|
+
if (parsed?.unlimited === true) return { ...base, windows: [], _quotaError: { kind: 'unlimited' } }
|
|
343
619
|
const windows = normalizeWindows(Array.isArray(parsed) ? parsed : parsed?.windows)
|
|
344
620
|
const balance = Array.isArray(parsed) ? undefined : parsed?.balance
|
|
345
621
|
const usage = await readSourceUsage(source, hit)
|
|
@@ -431,6 +707,10 @@ export function toSnapshot(entry) {
|
|
|
431
707
|
rateLimited: entry._rateLimited === true,
|
|
432
708
|
stale: entry._stale === true,
|
|
433
709
|
mode: entry.mode === 'subscription' || entry.mode === 'api' ? entry.mode : 'unknown',
|
|
710
|
+
...(entry.region === undefined ? {} : { region: entry.region }),
|
|
711
|
+
...(entry.regions === undefined ? {} : { regions: entry.regions }),
|
|
712
|
+
...(entry.regionSource === undefined ? {} : { regionSource: entry.regionSource }),
|
|
713
|
+
...(entry.manualMiss === true ? { manualMiss: true } : {}),
|
|
434
714
|
windows: Array.isArray(entry.windows) ? entry.windows : Array.isArray(entry.plans) ? entry.plans : [],
|
|
435
715
|
error,
|
|
436
716
|
quotaError,
|
|
@@ -518,7 +798,7 @@ export function logAdapterEvents(log, providers) {
|
|
|
518
798
|
? {}
|
|
519
799
|
: detail.kind === 'http'
|
|
520
800
|
? { errorKind: detail.kind, httpStatus: detail.status, ...(detail.retryAfter === undefined ? {} : { retryAfter: detail.retryAfter }) }
|
|
521
|
-
: { errorKind: detail.kind })
|
|
801
|
+
: { errorKind: detail.kind, ...(detail.bodyCode === undefined ? {} : { bodyCode: detail.bodyCode }) })
|
|
522
802
|
for (const item of providers) {
|
|
523
803
|
if (item.id === 'deepseek-official') {
|
|
524
804
|
if (item.balance?.status === 'ok') info('adapter.deepseek', 'balance.ok', { amount: item.balance.amount })
|
|
@@ -528,18 +808,22 @@ export function logAdapterEvents(log, providers) {
|
|
|
528
808
|
}
|
|
529
809
|
if (item.id === 'zhipu' || item.id === 'moonshot') {
|
|
530
810
|
const module = item.id === 'zhipu' ? 'adapter.glm' : 'adapter.kimi'
|
|
811
|
+
const regionInfo = regionLogMeta(item)
|
|
812
|
+
if (item.region !== undefined) info(module, 'region.pick', { region: item.region, source: item.regionSource ?? 'default', ...(regionInfo.host === undefined ? {} : { host: regionInfo.host }) })
|
|
531
813
|
if (item.kind === 'subscription') {
|
|
532
814
|
const windows = (item.windows ?? []).length
|
|
533
|
-
if (windows > 0) info(module, 'quota.ok', { windows })
|
|
534
|
-
else if (item.quotaError?.kind === '
|
|
535
|
-
else info(module, 'quota.
|
|
815
|
+
if (windows > 0) info(module, 'quota.ok', { windows, ...regionInfo })
|
|
816
|
+
else if (item.quotaError?.kind === 'auth') info(module, 'region.auth-fail', { ...regionInfo, ...errorMeta(item.quotaError) })
|
|
817
|
+
else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', regionInfo)
|
|
818
|
+
else info(module, 'quota.fail', { windows: 0, ...regionInfo, ...errorMeta(item.quotaError) })
|
|
536
819
|
} else if (item.quotaError !== undefined && item.quotaError !== null) {
|
|
537
|
-
info(module, '
|
|
820
|
+
if (item.quotaError.kind === 'auth') info(module, 'region.auth-fail', { ...regionInfo, ...errorMeta(item.quotaError) })
|
|
821
|
+
else info(module, 'quota.fail', { ...regionInfo, ...errorMeta(item.quotaError) })
|
|
538
822
|
} else {
|
|
539
|
-
info(module, 'quota.miss',
|
|
823
|
+
info(module, 'quota.miss', regionInfo)
|
|
540
824
|
}
|
|
541
|
-
if (item.id === 'moonshot' && item.balance?.status === 'ok') info('adapter.kimi', 'balance.ok', { amount: item.balance.amount })
|
|
542
|
-
if (item.id === 'moonshot' && item.balance?.status === 'error') info('adapter.kimi', 'balance.error', { status: 'error', ...errorMeta(item.error ?? item.balance._error) })
|
|
825
|
+
if (item.id === 'moonshot' && item.balance?.status === 'ok') info('adapter.kimi', 'balance.ok', { ...regionInfo, amount: item.balance.amount })
|
|
826
|
+
if (item.id === 'moonshot' && item.balance?.status === 'error') info('adapter.kimi', 'balance.error', { status: 'error', ...regionInfo, ...errorMeta(item.error ?? item.balance._error) })
|
|
543
827
|
continue
|
|
544
828
|
}
|
|
545
829
|
if (item.id === 'openrouter') {
|
|
@@ -548,7 +832,9 @@ export function logAdapterEvents(log, providers) {
|
|
|
548
832
|
continue
|
|
549
833
|
}
|
|
550
834
|
if (item.id === 'qwen') {
|
|
551
|
-
|
|
835
|
+
const regionInfo = regionLogMeta(item)
|
|
836
|
+
if (item.region !== undefined) info('adapter.qwen', 'region.pick', { region: item.region, source: item.regionSource ?? 'default' })
|
|
837
|
+
info('adapter.qwen', item.currency === 'USD' ? 'currency.usd' : 'detected', regionInfo)
|
|
552
838
|
continue
|
|
553
839
|
}
|
|
554
840
|
if (item.id === 'opencode-go' || item.id === 'command-code') {
|
|
@@ -568,6 +854,29 @@ export function logAdapterEvents(log, providers) {
|
|
|
568
854
|
if (item.channel !== undefined) info('adapter.ollama', 'usage', { range: item.channel.range, usageUsd: item.channel.usageUsd })
|
|
569
855
|
else if (item.channelError !== undefined) info('adapter.ollama', 'usage.fail', errorMeta(item.channelError))
|
|
570
856
|
}
|
|
857
|
+
if (item.id === 'minimax') {
|
|
858
|
+
const windows = (item.windows ?? []).length
|
|
859
|
+
const meta = { ...(item.region === undefined ? {} : { region: item.region }) }
|
|
860
|
+
if (item.manualMiss === true) info('adapter.minimax', 'quota.manual-miss', { manual: true })
|
|
861
|
+
if (item.quotaError?.kind === 'paygo') info('adapter.minimax', 'quota.paygo', { prefix: 'sk-api-' })
|
|
862
|
+
else if (windows > 0) info('adapter.minimax', 'quota.ok', { ...meta, windows })
|
|
863
|
+
else if (item.quotaError?.kind === 'unlimited') info('adapter.minimax', 'quota.unlimited', meta)
|
|
864
|
+
else if (item.quotaError?.kind === 'auth') info('adapter.minimax', 'quota.auth', { ...meta, tried: item.quotaError.tried ?? 1, statusCode: item.quotaError.statusCode, manual: item.quotaError.manual === true })
|
|
865
|
+
else if (item.quotaError?.kind === 'parse') info('adapter.minimax', 'quota.parse', meta)
|
|
866
|
+
else info('adapter.minimax', 'quota.fail', { ...meta, ...errorMeta(item.quotaError) })
|
|
867
|
+
const balance = item.balance
|
|
868
|
+
if (balance?.status === 'ok') info('adapter.minimax', 'balance.ok', { ...meta, amount: balance.amount, currency: balance.currency })
|
|
869
|
+
else if (item.quotaError?.kind === 'paygo') info('adapter.minimax', 'balance.fail', { ...meta, ...errorMeta(item.error ?? balance?._error) })
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
/** 日志用:区域 + 该区首个 quota host(从 REGION_PROFILES 反查,不额外透传)。 */
|
|
875
|
+
function regionLogMeta(item) {
|
|
876
|
+
const host = REGION_PROFILES[item.id]?.[item.region]?.quota?.[0]
|
|
877
|
+
return {
|
|
878
|
+
...(item.region === undefined ? {} : { region: item.region }),
|
|
879
|
+
...(host === undefined ? {} : { host }),
|
|
571
880
|
}
|
|
572
881
|
}
|
|
573
882
|
|
|
@@ -579,6 +888,7 @@ const FAILURE_MODULES = {
|
|
|
579
888
|
qwen: 'adapter.qwen',
|
|
580
889
|
'opencode-go': 'adapter.opencode',
|
|
581
890
|
'command-code': 'adapter.commandcode',
|
|
891
|
+
minimax: 'adapter.minimax',
|
|
582
892
|
}
|
|
583
893
|
|
|
584
894
|
/**
|