dsh-token-dash 2.3.1 → 2.4.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/src/adapters.js CHANGED
@@ -1,561 +1,568 @@
1
- /**
2
- * External provider adapters. Endpoints and response semantics are copied from
3
- * the reference plugins; do not invent fields or percentages.
4
- */
5
- import { normalizeProvider, providerCurrency, providerLabel } from './providers.js'
6
- import { PROVIDER_SOURCES } from './quota-sources.js'
7
-
8
- const TIMEOUT = 6000
9
- const GLM_QUOTA = 'https://bigmodel.cn/api/monitor/usage/quota/limit'
10
- const KIMI_USAGES = 'https://api.kimi.com/coding/v1/usages'
11
- const KIMI_BALANCE = 'https://api.moonshot.cn/v1/users/me/balance'
12
- const OPENROUTER_CREDITS = 'https://openrouter.ai/api/v1/credits'
13
-
14
- export function clampPercent(value) {
15
- const n = Number(value)
16
- if (!Number.isFinite(n)) return null
17
- return Math.max(0, Math.min(100, n))
18
- }
19
-
20
- export function parseGlmQuota(body) {
21
- const data = body?.data ?? body
22
- const rows = Array.isArray(data?.limits) ? data.limits : []
23
- const windows = []
24
- for (const row of rows) {
25
- if (String(row?.type ?? '').toUpperCase() !== 'TOKENS_LIMIT') continue
26
- const unit = Number(row.unit)
27
- const key = unit === 3 ? '5h' : unit === 6 ? 'week' : null
28
- if (key === null) continue
29
- const percent = clampPercent(row.percentage)
30
- if (percent === null) continue
31
- windows.push({ key, usedPercent: percent, resetAt: Number(row.nextResetTime) || undefined, source: 'official' })
32
- }
33
- return windows
34
- }
35
-
36
- function ratioWindow(key, raw) {
37
- const used = clampPercent(raw?.used_ratio)
38
- if (used === null) return undefined
39
- return { key, usedPercent: used, resetAt: Number(raw?.reset_time) || undefined, source: 'official' }
40
- }
41
-
42
- export function parseKimiQuota(body) {
43
- const record = body?.data ?? body
44
- const windows = []
45
- const usages = record?.usages
46
- if (usages !== null && typeof usages === 'object') {
47
- const five = ratioWindow('5h', usages.limit_5h)
48
- const month = ratioWindow('month', usages.limit_month_code) ?? ratioWindow('month', usages.limit_month_total)
49
- if (five) windows.push(five)
50
- if (month) windows.push(month)
51
- }
52
- const weekly = ratioWindow('week', record?.usage)
53
- if (weekly) windows.push(weekly)
54
- if (windows.length === 0) {
55
- const limits = Array.isArray(record?.limits) ? record.limits : []
56
- const five = limits
57
- .map((item) => {
58
- const detail = item?.detail ?? item
59
- const limit = Number(detail?.limit)
60
- const used = detail?.used !== undefined ? Number(detail.used) : (limit - Number(detail?.remaining))
61
- const percent = limit > 0 && Number.isFinite(used) ? clampPercent((used / limit) * 100) : null
62
- return percent === null ? null : { key: '5h', usedPercent: percent, resetAt: Number(detail?.resetTime) || undefined, source: 'official' }
63
- })
64
- .filter(Boolean)
65
- .sort((left, right) => (right.resetAt ?? 0) - (left.resetAt ?? 0))
66
- if (five[0]) windows.push(five[0])
67
- const usage = record?.usage
68
- const limit = Number(usage?.limit)
69
- const used = Number(usage?.used)
70
- if (limit > 0 && Number.isFinite(used)) windows.push({ key: 'week', usedPercent: clampPercent((used / limit) * 100), resetAt: Number(usage.resetTime) || undefined, source: 'official' })
71
- }
72
- return windows
73
- }
74
-
75
- export function parseOpenRouterCredits(body) {
76
- const data = body?.data ?? body
77
- const total = Number(data?.total_credits)
78
- const usage = Number(data?.total_usage)
79
- if (!Number.isFinite(total) || !Number.isFinite(usage)) return null
80
- return { amount: Math.max(0, total - usage), currency: 'USD', status: 'ok', updatedAt: Date.now() }
81
- }
82
-
83
- async function resolveCredential(ctx, credential) {
84
- if (credential === undefined || credential === null) return undefined
85
- if (credential.type !== 'bearer' && credential.type !== 'oauth-reuse') return undefined
86
- return resolveKey(ctx, credential.refs ?? [])
87
- }
88
-
89
- async function resolveKey(ctx, names) {
90
- const credentials = ctx.get?.('credentials')
91
- if (credentials === undefined || typeof credentials.resolve !== 'function') return undefined
92
- for (const name of names) {
93
- try {
94
- const hit = await credentials.resolve(name)
95
- const value = hit?.value
96
- if (typeof value === 'string' && value.trim() !== '') return { value: value.trim(), name }
97
- } catch {
98
- // try next name
99
- }
100
- }
101
- return undefined
102
- }
103
-
104
- async function requestJson(url, headers) {
105
- const response = await fetch(url, { headers: { accept: 'application/json', ...headers }, signal: AbortSignal.timeout(TIMEOUT) })
106
- const body = await response.json().catch(() => null)
107
- if (!response.ok) {
108
- const error = new Error(`http-${response.status}`)
109
- error.status = response.status
110
- error.body = body
111
- // 429 带整数秒的 Retry-After,属于源级退避输入,不进任何展示文案
112
- const retryAfter = Number(response.headers?.get?.('retry-after'))
113
- if (Number.isFinite(retryAfter) && retryAfter > 0) error.retryAfter = retryAfter
114
- throw error
115
- }
116
- return body
117
- }
118
-
119
- /** #47:错误分类(http+状态码 / timeout / network)——挂在条目 `_error`/`_quotaError` 上供日志还原原因。 */
120
- function errorDetail(error) {
121
- if (error?.status !== undefined) {
122
- return {
123
- kind: 'http',
124
- status: error.status,
125
- ...(error.status >= 500 ? { upstream: true } : {}),
126
- ...(error.retryAfter === undefined ? {} : { retryAfter: error.retryAfter }),
127
- }
128
- }
129
- const name = `${error?.name ?? ''} ${error?.message ?? ''}`
130
- if (name.includes('Timeout') || name.includes('abort') || name.includes('Abort')) return { kind: 'timeout' }
131
- return { kind: 'network' }
132
- }
133
-
134
- async function deepseek(ctx) {
135
- const account = ctx.get?.('deepseekAccount')
136
- if (account !== undefined && typeof account.getBalance === 'function') {
137
- try {
138
- const data = await account.getBalance({ version: '1.0.2', locale: 'zh-CN', timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60 })
139
- if (data?.status === 'ready') {
140
- const wallets = [...(Array.isArray(data.value) ? data.value : Object.values(data.value ?? {})), ...(data.bonusWallets ?? [])]
141
- const amount = wallets.filter((wallet) => wallet?.currency === undefined || wallet.currency === 'CNY')
142
- .reduce((sum, wallet) => sum + (Number(wallet?.balance ?? wallet?.amount) || 0), 0)
143
- return { id: 'deepseek-official', kind: 'api', currency: 'CNY', balance: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() } }
144
- }
145
- } catch {
146
- // fall through to key
147
- }
148
- }
149
- const key = await resolveKey(ctx, ['DEEPSEEK_API_KEY'])
150
- if (key === undefined) return null
151
- try {
152
- const body = await requestJson('https://api.deepseek.com/user/balance', { authorization: `Bearer ${key.value}` })
153
- const amount = (body?.balance_infos ?? []).reduce((sum, item) => sum + (Number(item?.total_balance) || 0), 0)
154
- return { id: 'deepseek-official', kind: 'api', currency: 'CNY', balance: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() } }
155
- } catch (error) {
156
- return { id: 'deepseek-official', kind: 'api', currency: 'CNY', _error: errorDetail(error), balance: { amount: null, status: error.status === 401 ? 'unconfigured' : 'error', currency: 'CNY', updatedAt: Date.now() } }
157
- }
158
- }
159
-
160
- async function glm(ctx, prefs) {
161
- const key = await resolveKey(ctx, ['ZHIPU_API_KEY', 'GLM_API_KEY', 'ZAI_API_KEY'])
162
- if (key === undefined) return null
163
- const mode = prefs?.billingModes?.zhipu
164
- if (mode === 'api') return { id: 'zhipu', kind: 'api', mode: 'api', currency: 'CNY' }
165
- // 手动覆盖为订阅时,quota 失败/无窗口仍保留订阅卡(显示“套餐查询失败”),不回落 api。
166
- const subscriptionFallback = mode === 'subscription'
167
- ? { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: [] }
168
- : null
169
- try {
170
- const body = await requestJson(GLM_QUOTA, { authorization: key.value })
171
- const windows = parseGlmQuota(body)
172
- if (windows.length > 0) return { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: windows }
173
- // 响应可解析但无窗口:解析问题(quota.parse),非网络错误
174
- return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', mode: 'unknown', currency: 'CNY' }), _quotaError: { kind: 'parse' } }
175
- } catch (error) {
176
- return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', mode: 'unknown', currency: 'CNY' }), _quotaError: errorDetail(error) }
177
- }
178
- }
179
-
180
- /**
181
- * Kimi Coding 配额查询。
182
- * 返回 { state }:'no-key'(无 Coding Key 或显式 api 模式)、'ok'(含 entry)、'fallback'(自动模式下配额失败,走按量路径)。
183
- */
184
- async function kimiCodingQuota(ctx, prefs) {
185
- const coding = await resolveKey(ctx, ['KIMI_API_KEY', 'KIMI_CODING_API_KEY'])
186
- if (coding === undefined) return { state: 'no-key' }
187
- const mode = prefs?.billingModes?.moonshot
188
- if (mode === 'api') return { state: 'no-key' }
189
- let quotaError = null
190
- try {
191
- const body = await requestJson(KIMI_USAGES, { authorization: `Bearer ${coding.value}` })
192
- const windows = parseKimiQuota(body)
193
- if (windows.length > 0) return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: windows } }
194
- quotaError = { kind: 'parse' }
195
- } catch (error) {
196
- quotaError = errorDetail(error)
197
- }
198
- if (mode === 'subscription') return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: [], _quotaError: quotaError } }
199
- return { state: 'fallback', quotaError }
200
- return { state: 'fallback' }
201
- }
202
-
203
- async function kimi(ctx, prefs) {
204
- const quota = await kimiCodingQuota(ctx, prefs)
205
- if (quota.state === 'ok') return quota.entry
206
- const quotaError = quota.quotaError ?? null
207
- const normal = await resolveKey(ctx, ['MOONSHOT_API_KEY'])
208
- if (normal === undefined) return quota.state === 'no-key' ? null : { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError }
209
- try {
210
- const body = await requestJson(KIMI_BALANCE, { authorization: `Bearer ${normal.value}` })
211
- const amount = Number(body?.data?.available_balance)
212
- const ok = Number.isFinite(amount)
213
- return {
214
- id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError,
215
- balance: { amount: ok ? amount : null, status: ok ? 'ok' : 'error', currency: 'CNY', updatedAt: Date.now(), ...(ok ? {} : { _error: { kind: 'parse' } }) },
216
- }
217
- } catch (error) {
218
- return { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError, _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'CNY', updatedAt: Date.now() } }
219
- }
220
- }
221
-
222
- async function openrouter(ctx) {
223
- const key = await resolveKey(ctx, ['OPENROUTER_API_KEY'])
224
- if (key === undefined) return null
225
- try {
226
- const body = await requestJson(OPENROUTER_CREDITS, { authorization: `Bearer ${key.value}` })
227
- const balance = parseOpenRouterCredits(body)
228
- return { id: 'openrouter', kind: 'api', currency: 'USD', balance: balance ?? { amount: null, status: 'error', currency: 'USD', updatedAt: Date.now(), _error: { kind: 'parse' } } }
229
- } catch (error) {
230
- return { id: 'openrouter', kind: 'api', currency: 'USD', _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'USD', updatedAt: Date.now() } }
231
- }
232
- }
233
-
234
- /** Qwen 仅按量;国际站 Key(DASHSCOPE_INTL_API_KEY)按 USD,其余 CNY。无 quota 请求。 */
235
- async function qwen(ctx) {
236
- const key = await resolveKey(ctx, ['DASHSCOPE_INTL_API_KEY', 'DASHSCOPE_API_KEY', 'QWEN_API_KEY'])
237
- if (key === undefined) return null
238
- const intl = key.name === 'DASHSCOPE_INTL_API_KEY'
239
- const currency = intl ? 'USD' : 'CNY'
240
- return { id: 'qwen', kind: 'api', currency, balance: { amount: null, status: 'unsupported', currency, updatedAt: Date.now() } }
241
- }
242
-
243
- const LEGACY_READERS = { deepseek, glm, kimi, openrouter, qwen }
244
- const WINDOW_KEYS = new Set(['5h', 'week', 'month'])
245
-
246
- function normalizeWindows(windows) {
247
- if (!Array.isArray(windows)) return []
248
- const out = []
249
- const seen = new Set()
250
- for (const item of windows) {
251
- if (item === null || item === undefined || !WINDOW_KEYS.has(item.key) || seen.has(item.key)) continue
252
- const usedPercent = clampPercent(item.usedPercent)
253
- if (usedPercent === null) continue
254
- seen.add(item.key)
255
- out.push({ ...item, usedPercent })
256
- }
257
- return out
258
- }
259
-
260
- /** 通用 preflight:凭据存在才拼 query;异常返回空串,不阻断主请求。 */
261
- async function sourceQuery(ctx, source) {
262
- if (source.preflight === undefined) return ''
263
- try {
264
- const hit = await resolveKey(ctx, source.preflight.refs ?? [])
265
- if (hit === undefined) return ''
266
- return `${source.preflight.param}=${encodeURIComponent(hit.value)}`
267
- } catch {
268
- return ''
269
- }
270
- }
271
-
272
- function withQuery(url, query) {
273
- if (query === '') return url
274
- return `${url}${url.includes('?') ? '&' : '?'}${query}`
275
- }
276
-
277
- /** 可选 usage 钩子:失败只留错误详情,绝不影响余额结果与账本。 */
278
- async function readSourceUsage(source, hit) {
279
- if (source.usage === undefined) return { channel: undefined, error: undefined }
280
- try {
281
- const query = source.usage.range === undefined ? '' : `range=${encodeURIComponent(source.usage.range)}`
282
- const body = await requestJson(withQuery(source.usage.url, query), { authorization: `Bearer ${hit.value}` })
283
- const parsed = source.usage.parse(body)
284
- return { channel: parsed?.channel ?? undefined, error: undefined }
285
- } catch (error) {
286
- return { channel: undefined, error: errorDetail(error) }
287
- }
288
- }
289
-
290
- async function readDeclarativeSource(ctx, prefs, source, previous) {
291
- const hit = await resolveCredential(ctx, source.credential)
292
- if (hit === undefined) return null
293
- const subscription = source.kind === 'subscription'
294
- // mode 必须由 kind 派生:声明式订阅源才是订阅;写成常量会把 api 源固化成订阅(cost=0)
295
- const base = { id: source.id, name: providerLabel(source.id), kind: source.kind, mode: subscription ? 'subscription' : 'api', currency: source.currency }
296
- const query = await sourceQuery(ctx, source)
297
- let body
298
- try {
299
- try {
300
- body = await requestJson(withQuery(source.quota.url, query), { authorization: `Bearer ${hit.value}` })
301
- } catch (error) {
302
- if (source.quota.fallbackUrl === undefined || (error.status !== 404 && error.status !== 405)) throw error
303
- body = await requestJson(withQuery(source.quota.fallbackUrl, query), { authorization: `Bearer ${hit.value}` })
304
- }
305
- } catch (error) {
306
- const detail = errorDetail(error)
307
- // 限流复用上一份快照,避免卡片在 429 时闪成「查询失败」;退避由缓存 until 承担
308
- if (error.status === 429 && previous !== null && previous !== undefined) {
309
- return { ...previous, _quotaError: detail, _rateLimited: true, fetchedAt: Date.now() }
310
- }
311
- const status = error.status === 401 ? 'unconfigured' : 'error'
312
- return {
313
- ...base,
314
- windows: [],
315
- ...(subscription ? {} : { balance: { amount: null, status, currency: source.currency, updatedAt: Date.now() } }),
316
- _quotaError: detail,
317
- }
318
- }
319
- const parsed = source.quota.parse(body)
320
- const windows = normalizeWindows(Array.isArray(parsed) ? parsed : parsed?.windows)
321
- const balance = Array.isArray(parsed) ? undefined : parsed?.balance
322
- const usage = await readSourceUsage(source, hit)
323
- const extra = {
324
- ...(balance === undefined ? {} : { balance }),
325
- ...(usage.channel === undefined ? {} : { channel: usage.channel }),
326
- ...(usage.error === undefined ? {} : { _channelError: usage.error }),
327
- }
328
- if (windows.length === 0 && balance === undefined) return { ...base, windows: [], _quotaError: { kind: 'parse' }, ...extra }
329
- return { ...base, windows, ...extra }
330
- }
331
-
332
- async function readSource(ctx, prefs, source, previous) {
333
- if (source.legacy !== undefined) {
334
- const reader = LEGACY_READERS[source.legacy]
335
- return reader(ctx, prefs)
336
- }
337
- return readDeclarativeSource(ctx, prefs, source, previous)
338
- }
339
-
340
- /** 订阅重查专用:Kimi 只查 Coding 配额,不请求 moonshot 余额。 */
341
- async function readKimiSubscription(ctx, prefs) {
342
- const quota = await kimiCodingQuota(ctx, prefs)
343
- if (quota.state === 'ok') return quota.entry
344
- if (quota.state === 'fallback') return { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quota.quotaError ?? null }
345
- return null
346
- }
347
-
348
- const TTL_OK = 60000
349
- const TTL_FAIL = 10000
350
-
351
- /** 限流条目按 Retry-After 延后重试,成功 60s / 失败 10s 的基线不变。 */
352
- function cacheExpiry(data, now) {
353
- const retryAfter = data?._rateLimited === true ? Number(data?._quotaError?.retryAfter) : NaN
354
- if (Number.isFinite(retryAfter) && retryAfter > 0) return now + Math.max(TTL_FAIL, retryAfter * 1000)
355
- return now + (data === null || data?._rateLimited === true ? TTL_FAIL : TTL_OK)
356
- }
357
-
358
- async function readCachedSource(ctx, prefs, source, cache) {
359
- const now = Date.now()
360
- const cached = cache.get(source.id)
361
- if (cached !== undefined && cached.promise === null && now < (cached.until ?? now)) return cached.data
362
- if (cached?.promise !== undefined && cached.promise !== null) return cached.promise
363
- const promise = readSource(ctx, prefs, source, cached?.data ?? null)
364
- .then((data) => {
365
- const at = Date.now()
366
- cache.set(source.id, { at, ok: data !== null && data?._rateLimited !== true, data, promise: null, until: cacheExpiry(data, at) })
367
- return data
368
- })
369
- .catch((error) => {
370
- const at = Date.now()
371
- cache.set(source.id, { at, ok: false, data: null, promise: null, until: at + TTL_FAIL })
372
- throw error
373
- })
374
- cache.set(source.id, { at: cached?.at ?? 0, ok: cached?.ok === true, data: cached?.data ?? null, promise, until: cached?.until ?? null })
375
- return promise
376
- }
377
-
378
- function visibleEntry(entry, prefs) {
379
- return entry !== null && prefs?.billingModes?.[entry.id] !== 'hide'
380
- }
381
-
382
- /** Adapter → VM boundary: normalize ad-hoc adapter rows into ProviderSnapshot. */
383
- export function toSnapshot(entry) {
384
- const error = entry.error ?? entry._error ?? null
385
- const quotaError = entry.quotaError ?? entry._quotaError ?? null
386
- const balance = entry.balance ?? null
387
- const status = error !== null
388
- ? 'error'
389
- : balance?.status === 'unconfigured'
390
- ? 'unconfigured'
391
- : balance?.status === 'error'
392
- ? 'error'
393
- : 'ok'
394
- return {
395
- id: entry.id,
396
- name: entry.name,
397
- kind: entry.kind === 'subscription' ? 'subscription' : 'api',
398
- currency: entry.currency,
399
- status,
400
- balance,
401
- // 渠道侧只读用量与限流标记:仅展示用,不参与计价(REQ-04)
402
- ...(entry.channel === undefined ? {} : { channel: entry.channel }),
403
- ...(entry._channelError === undefined ? {} : { channelError: entry._channelError }),
404
- rateLimited: entry._rateLimited === true,
405
- mode: entry.mode === 'subscription' || entry.mode === 'api' ? entry.mode : 'unknown',
406
- windows: Array.isArray(entry.windows) ? entry.windows : Array.isArray(entry.plans) ? entry.plans : [],
407
- error,
408
- quotaError,
409
- fetchedAt: entry.fetchedAt ?? Date.now(),
410
- }
411
- }
412
-
413
- /**
414
- * Query configured providers; each failure is isolated. Balance/credits are always requested
415
- * (P2 shows them regardless of the P1-only toggle, #31). 空档原因挂在返回数组的 `misses` 上:
416
- * `<id>:none` 未配置、`:error` 请求失败、`:hidden` 被计费模式隐藏。
417
- * 缓存按源保存在调用方传入的 Map 中:成功 60s、失败 10s,并发复用 promise。
418
- */
419
- export async function readProviders(ctx, prefs, cache = new Map()) {
420
- const results = await Promise.allSettled(PROVIDER_SOURCES.map((source) => readCachedSource(ctx, prefs, source, cache)))
421
- const out = []
422
- const misses = []
423
- const failures = []
424
- results.forEach((result, index) => {
425
- const id = PROVIDER_SOURCES[index].id
426
- if (result.status !== 'fulfilled') {
427
- misses.push(`${id}:error`)
428
- failures.push({ id, error: errorDetail(result.reason) })
429
- return
430
- }
431
- if (result.value === null) { misses.push(`${id}:none`); return }
432
- if (visibleEntry(result.value, prefs) !== true) { misses.push(`${id}:hidden`); return }
433
- const value = result.value
434
- value.currency = value.currency ?? providerCurrency(normalizeProvider(value.id))
435
- out.push(toSnapshot(value))
436
- })
437
- out.misses = misses
438
- out.failures = failures
439
- return out
440
- }
441
-
442
- /**
443
- * P3「重新检测」专用:只重查订阅 provider 的配额,绕过缓存。
444
- * 仅返回 subscription 条目;无 Key 的 provider 不返回(由调用方从缓存移除)。
445
- */
446
- export async function readSubscriptions(ctx, prefs) {
447
- const sources = PROVIDER_SOURCES.filter((source) => source.kind === 'subscription')
448
- const results = await Promise.allSettled(sources.map((source) => (
449
- source.legacy === 'kimi' ? readKimiSubscription(ctx, prefs) : readSource(ctx, prefs, source)
450
- )))
451
- const out = []
452
- const failures = []
453
- results.forEach((result, index) => {
454
- if (result.status !== 'fulfilled') {
455
- failures.push({ id: sources[index].id, error: errorDetail(result.reason) })
456
- return
457
- }
458
- if (result.value === null) return
459
- // 旧源(GLM / Kimi)配额失败时可能回落 API 条目,保留旧行为;新源只保留订阅条目。
460
- const legacy = sources[index].legacy !== undefined
461
- if (result.value.kind !== 'subscription' && legacy !== true) return
462
- if (visibleEntry(result.value, prefs) !== true) return
463
- out.push(toSnapshot(result.value))
464
- })
465
- out.failures = failures
466
- return out
467
- }
468
-
469
- /** #46/#47:按 §2.5 adapter.* 事件表记侦测结果与错误原因——只记状态/计数/错误分类,不记 Key/响应体(脱敏约束)。 */
470
- export function logAdapterEvents(log, providers) {
471
- const info = (module, event, meta) => log.info(module, event, meta)
472
- // 错误详情合并进 meta:kind=http 时带 status,便于报障还原原因
473
- const errorMeta = (detail) => (detail === null || detail === undefined
474
- ? {}
475
- : detail.kind === 'http'
476
- ? { errorKind: detail.kind, httpStatus: detail.status, ...(detail.retryAfter === undefined ? {} : { retryAfter: detail.retryAfter }) }
477
- : { errorKind: detail.kind })
478
- for (const item of providers) {
479
- if (item.id === 'deepseek-official') {
480
- if (item.balance?.status === 'ok') info('adapter.deepseek', 'balance.ok', { amount: item.balance.amount })
481
- else if (item.balance?.status === 'unconfigured') info('adapter.deepseek', 'balance.auth', errorMeta(item.error))
482
- else if (item.balance !== undefined) info('adapter.deepseek', 'balance.error', { status: item.balance.status, ...errorMeta(item.error ?? item.balance._error) })
483
- continue
484
- }
485
- if (item.id === 'zhipu' || item.id === 'moonshot') {
486
- const module = item.id === 'zhipu' ? 'adapter.glm' : 'adapter.kimi'
487
- if (item.kind === 'subscription') {
488
- const windows = (item.windows ?? []).length
489
- if (windows > 0) info(module, 'quota.ok', { windows })
490
- else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
491
- else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
492
- } else if (item.quotaError !== undefined && item.quotaError !== null) {
493
- info(module, 'quota.fail', { ...errorMeta(item.quotaError) })
494
- } else {
495
- info(module, 'quota.miss', {})
496
- }
497
- if (item.id === 'moonshot' && item.balance?.status === 'ok') info('adapter.kimi', 'balance.ok', { amount: item.balance.amount })
498
- if (item.id === 'moonshot' && item.balance?.status === 'error') info('adapter.kimi', 'balance.error', { status: 'error', ...errorMeta(item.error ?? item.balance._error) })
499
- continue
500
- }
501
- if (item.id === 'openrouter') {
502
- if (item.balance?.status === 'ok') info('adapter.openrouter', 'credits.ok', { amount: item.balance.amount })
503
- else if (item.balance !== undefined) info('adapter.openrouter', 'credits.error', { status: item.balance.status, ...errorMeta(item.error ?? item.balance._error) })
504
- continue
505
- }
506
- if (item.id === 'qwen') {
507
- info('adapter.qwen', item.currency === 'USD' ? 'currency.usd' : 'detected', {})
508
- continue
509
- }
510
- if (item.id === 'opencode-go' || item.id === 'command-code') {
511
- const module = item.id === 'opencode-go' ? 'adapter.opencode' : 'adapter.commandcode'
512
- const windows = (item.windows ?? []).length
513
- if (windows > 0) info(module, 'quota.ok', { windows })
514
- else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
515
- else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
516
- if (item.balance?.status === 'ok') info(module, 'credits.ok', { amount: item.balance.amount })
517
- continue
518
- }
519
- if (item.id === 'ollama') {
520
- const balance = item.balance
521
- if (balance?.status === 'ok') info('adapter.ollama', 'quota.ok', { amount: balance.amount, purchased: balance.purchased ?? 0, legacy: balance.legacy === true })
522
- else if (balance?.status === 'unconfigured') info('adapter.ollama', 'quota.auth', {})
523
- else info('adapter.ollama', 'quota.fail', { status: balance?.status ?? 'error', ...errorMeta(item.quotaError ?? item.error) })
524
- if (item.channel !== undefined) info('adapter.ollama', 'usage', { range: item.channel.range, usageUsd: item.channel.usageUsd })
525
- else if (item.channelError !== undefined) info('adapter.ollama', 'usage.fail', errorMeta(item.channelError))
526
- }
527
- }
528
- }
529
-
530
- const FAILURE_MODULES = {
531
- 'deepseek-official': 'adapter.deepseek',
532
- zhipu: 'adapter.glm',
533
- moonshot: 'adapter.kimi',
534
- openrouter: 'adapter.openrouter',
535
- qwen: 'adapter.qwen',
536
- 'opencode-go': 'adapter.opencode',
537
- 'command-code': 'adapter.commandcode',
538
- }
539
-
540
- /**
541
- * 探测结果签名:miss 清单不变时无需重复记日志,避免每轮刷新刷屏。
542
- * 返回 `id:none,id:hidden,...` 的稳定字符串;无 miss 时为空串。
543
- */
544
- export function missSignature(providers) {
545
- return (providers?.misses ?? []).join(',')
546
- }
547
-
548
- /** Promise.allSettled 的拒绝项没有 entry,单独补 adapter.<id> 失败日志。 */
549
- export function logAdapterFailures(log, failures = []) {
550
- for (const item of failures) {
551
- const module = FAILURE_MODULES[item.id] ?? `adapter.${item.id}`
552
- const error = item.error ?? { kind: 'network' }
553
- log.warn(module, 'detect.fail', {
554
- errorKind: error.kind,
555
- ...(error.status === undefined ? {} : { httpStatus: error.status }),
556
- ...(error.upstream === true ? { upstream: true } : {}),
557
- })
558
- }
559
- }
560
-
561
- export { KIMI_USAGES, GLM_QUOTA, KIMI_BALANCE, OPENROUTER_CREDITS }
1
+ /**
2
+ * External provider adapters. Endpoints and response semantics are copied from
3
+ * the reference plugins; do not invent fields or percentages.
4
+ */
5
+ import { normalizeProvider, providerCurrency, providerLabel } from './providers.js'
6
+ import { PROVIDER_SOURCES } from './quota-sources.js'
7
+
8
+ const TIMEOUT = 6000
9
+ const GLM_QUOTA = 'https://bigmodel.cn/api/monitor/usage/quota/limit'
10
+ const KIMI_USAGES = 'https://api.kimi.com/coding/v1/usages'
11
+ const KIMI_BALANCE = 'https://api.moonshot.cn/v1/users/me/balance'
12
+ const OPENROUTER_CREDITS = 'https://openrouter.ai/api/v1/credits'
13
+
14
+ export function clampPercent(value) {
15
+ const n = Number(value)
16
+ if (!Number.isFinite(n)) return null
17
+ return Math.max(0, Math.min(100, n))
18
+ }
19
+
20
+ export function parseGlmQuota(body) {
21
+ const data = body?.data ?? body
22
+ const rows = Array.isArray(data?.limits) ? data.limits : []
23
+ const windows = []
24
+ for (const row of rows) {
25
+ if (String(row?.type ?? '').toUpperCase() !== 'TOKENS_LIMIT') continue
26
+ const unit = Number(row.unit)
27
+ const key = unit === 3 ? '5h' : unit === 6 ? 'week' : null
28
+ if (key === null) continue
29
+ const percent = clampPercent(row.percentage)
30
+ if (percent === null) continue
31
+ windows.push({ key, usedPercent: percent, resetAt: Number(row.nextResetTime) || undefined, source: 'official' })
32
+ }
33
+ return windows
34
+ }
35
+
36
+ function ratioWindow(key, raw) {
37
+ const used = clampPercent(raw?.used_ratio)
38
+ if (used === null) return undefined
39
+ return { key, usedPercent: used, resetAt: Number(raw?.reset_time) || undefined, source: 'official' }
40
+ }
41
+
42
+ export function parseKimiQuota(body) {
43
+ const record = body?.data ?? body
44
+ const windows = []
45
+ const usages = record?.usages
46
+ if (usages !== null && typeof usages === 'object') {
47
+ const five = ratioWindow('5h', usages.limit_5h)
48
+ const month = ratioWindow('month', usages.limit_month_code) ?? ratioWindow('month', usages.limit_month_total)
49
+ if (five) windows.push(five)
50
+ if (month) windows.push(month)
51
+ }
52
+ const weekly = ratioWindow('week', record?.usage)
53
+ if (weekly) windows.push(weekly)
54
+ if (windows.length === 0) {
55
+ const limits = Array.isArray(record?.limits) ? record.limits : []
56
+ const five = limits
57
+ .map((item) => {
58
+ const detail = item?.detail ?? item
59
+ const limit = Number(detail?.limit)
60
+ const used = detail?.used !== undefined ? Number(detail.used) : (limit - Number(detail?.remaining))
61
+ const percent = limit > 0 && Number.isFinite(used) ? clampPercent((used / limit) * 100) : null
62
+ return percent === null ? null : { key: '5h', usedPercent: percent, resetAt: Number(detail?.resetTime) || undefined, source: 'official' }
63
+ })
64
+ .filter(Boolean)
65
+ .sort((left, right) => (right.resetAt ?? 0) - (left.resetAt ?? 0))
66
+ if (five[0]) windows.push(five[0])
67
+ const usage = record?.usage
68
+ const limit = Number(usage?.limit)
69
+ const used = Number(usage?.used)
70
+ if (limit > 0 && Number.isFinite(used)) windows.push({ key: 'week', usedPercent: clampPercent((used / limit) * 100), resetAt: Number(usage.resetTime) || undefined, source: 'official' })
71
+ }
72
+ return windows
73
+ }
74
+
75
+ export function parseOpenRouterCredits(body) {
76
+ const data = body?.data ?? body
77
+ const total = Number(data?.total_credits)
78
+ const usage = Number(data?.total_usage)
79
+ if (!Number.isFinite(total) || !Number.isFinite(usage)) return null
80
+ return { amount: Math.max(0, total - usage), currency: 'USD', status: 'ok', updatedAt: Date.now() }
81
+ }
82
+
83
+ async function resolveCredential(ctx, credential) {
84
+ if (credential === undefined || credential === null) return undefined
85
+ if (credential.type !== 'bearer' && credential.type !== 'oauth-reuse') return undefined
86
+ return resolveKey(ctx, credential.refs ?? [])
87
+ }
88
+
89
+ async function resolveKey(ctx, names) {
90
+ const credentials = ctx.get?.('credentials')
91
+ if (credentials === undefined || typeof credentials.resolve !== 'function') return undefined
92
+ for (const name of names) {
93
+ try {
94
+ const hit = await credentials.resolve(name)
95
+ const value = hit?.value
96
+ if (typeof value === 'string' && value.trim() !== '') return { value: value.trim(), name }
97
+ } catch {
98
+ // try next name
99
+ }
100
+ }
101
+ return undefined
102
+ }
103
+
104
+ async function requestJson(url, headers) {
105
+ const response = await fetch(url, { headers: { accept: 'application/json', ...headers }, signal: AbortSignal.timeout(TIMEOUT) })
106
+ const body = await response.json().catch(() => null)
107
+ if (!response.ok) {
108
+ const error = new Error(`http-${response.status}`)
109
+ error.status = response.status
110
+ error.body = body
111
+ // 429 带整数秒的 Retry-After,属于源级退避输入,不进任何展示文案
112
+ const retryAfter = Number(response.headers?.get?.('retry-after'))
113
+ if (Number.isFinite(retryAfter) && retryAfter > 0) error.retryAfter = retryAfter
114
+ throw error
115
+ }
116
+ return body
117
+ }
118
+
119
+ /** #47:错误分类(http+状态码 / timeout / network)——挂在条目 `_error`/`_quotaError` 上供日志还原原因。 */
120
+ function errorDetail(error) {
121
+ if (error?.status !== undefined) {
122
+ return {
123
+ kind: 'http',
124
+ status: error.status,
125
+ ...(error.status >= 500 ? { upstream: true } : {}),
126
+ ...(error.retryAfter === undefined ? {} : { retryAfter: error.retryAfter }),
127
+ }
128
+ }
129
+ const name = `${error?.name ?? ''} ${error?.message ?? ''}`
130
+ if (name.includes('Timeout') || name.includes('abort') || name.includes('Abort')) return { kind: 'timeout' }
131
+ return { kind: 'network' }
132
+ }
133
+
134
+ async function deepseek(ctx) {
135
+ const account = ctx.get?.('deepseekAccount')
136
+ if (account !== undefined && typeof account.getBalance === 'function') {
137
+ try {
138
+ const data = await account.getBalance({ version: '1.0.2', locale: 'zh-CN', timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60 })
139
+ if (data?.status === 'ready') {
140
+ const wallets = [...(Array.isArray(data.value) ? data.value : Object.values(data.value ?? {})), ...(data.bonusWallets ?? [])]
141
+ const amount = wallets.filter((wallet) => wallet?.currency === undefined || wallet.currency === 'CNY')
142
+ .reduce((sum, wallet) => sum + (Number(wallet?.balance ?? wallet?.amount) || 0), 0)
143
+ return { id: 'deepseek-official', kind: 'api', currency: 'CNY', balance: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() } }
144
+ }
145
+ } catch {
146
+ // fall through to key
147
+ }
148
+ }
149
+ const key = await resolveKey(ctx, ['DEEPSEEK_API_KEY'])
150
+ if (key === undefined) return null
151
+ try {
152
+ const body = await requestJson('https://api.deepseek.com/user/balance', { authorization: `Bearer ${key.value}` })
153
+ const amount = (body?.balance_infos ?? []).reduce((sum, item) => sum + (Number(item?.total_balance) || 0), 0)
154
+ return { id: 'deepseek-official', kind: 'api', currency: 'CNY', balance: { amount, status: 'ok', currency: 'CNY', updatedAt: Date.now() } }
155
+ } catch (error) {
156
+ return { id: 'deepseek-official', kind: 'api', currency: 'CNY', _error: errorDetail(error), balance: { amount: null, status: error.status === 401 ? 'unconfigured' : 'error', currency: 'CNY', updatedAt: Date.now() } }
157
+ }
158
+ }
159
+
160
+ async function glm(ctx, prefs) {
161
+ const key = await resolveKey(ctx, ['ZHIPU_API_KEY', 'GLM_API_KEY', 'ZAI_API_KEY'])
162
+ if (key === undefined) return null
163
+ const mode = prefs?.billingModes?.zhipu
164
+ if (mode === 'api') return { id: 'zhipu', kind: 'api', mode: 'api', currency: 'CNY' }
165
+ // 手动覆盖为订阅时,quota 失败/无窗口仍保留订阅卡(显示“套餐查询失败”),不回落 api。
166
+ const subscriptionFallback = mode === 'subscription'
167
+ ? { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: [] }
168
+ : null
169
+ try {
170
+ const body = await requestJson(GLM_QUOTA, { authorization: key.value })
171
+ const windows = parseGlmQuota(body)
172
+ if (windows.length > 0) return { id: 'zhipu', name: 'GLM Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: windows }
173
+ // 响应可解析但无窗口:解析问题(quota.parse),非网络错误
174
+ return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', mode: 'unknown', currency: 'CNY' }), _quotaError: { kind: 'parse' } }
175
+ } catch (error) {
176
+ return { ...(subscriptionFallback ?? { id: 'zhipu', kind: 'api', mode: 'unknown', currency: 'CNY' }), _quotaError: errorDetail(error) }
177
+ }
178
+ }
179
+
180
+ /**
181
+ * Kimi Coding 配额查询。
182
+ * 返回 { state }:'no-key'(无 Coding Key 或显式 api 模式)、'ok'(含 entry)、'fallback'(自动模式下配额失败,走按量路径)。
183
+ */
184
+ async function kimiCodingQuota(ctx, prefs) {
185
+ const coding = await resolveKey(ctx, ['KIMI_API_KEY', 'KIMI_CODING_API_KEY'])
186
+ if (coding === undefined) return { state: 'no-key' }
187
+ const mode = prefs?.billingModes?.moonshot
188
+ if (mode === 'api') return { state: 'no-key' }
189
+ let quotaError = null
190
+ try {
191
+ const body = await requestJson(KIMI_USAGES, { authorization: `Bearer ${coding.value}` })
192
+ const windows = parseKimiQuota(body)
193
+ if (windows.length > 0) return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: windows } }
194
+ quotaError = { kind: 'parse' }
195
+ } catch (error) {
196
+ quotaError = errorDetail(error)
197
+ }
198
+ if (mode === 'subscription') return { state: 'ok', entry: { id: 'moonshot', name: 'Kimi Coding', kind: 'subscription', mode: 'subscription', currency: 'CNY', plans: [], _quotaError: quotaError } }
199
+ return { state: 'fallback', quotaError }
200
+ return { state: 'fallback' }
201
+ }
202
+
203
+ async function kimi(ctx, prefs) {
204
+ const quota = await kimiCodingQuota(ctx, prefs)
205
+ if (quota.state === 'ok') return quota.entry
206
+ const quotaError = quota.quotaError ?? null
207
+ const normal = await resolveKey(ctx, ['MOONSHOT_API_KEY'])
208
+ if (normal === undefined) return quota.state === 'no-key' ? null : { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError }
209
+ try {
210
+ const body = await requestJson(KIMI_BALANCE, { authorization: `Bearer ${normal.value}` })
211
+ const amount = Number(body?.data?.available_balance)
212
+ const ok = Number.isFinite(amount)
213
+ return {
214
+ id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError,
215
+ balance: { amount: ok ? amount : null, status: ok ? 'ok' : 'error', currency: 'CNY', updatedAt: Date.now(), ...(ok ? {} : { _error: { kind: 'parse' } }) },
216
+ }
217
+ } catch (error) {
218
+ return { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quotaError, _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'CNY', updatedAt: Date.now() } }
219
+ }
220
+ }
221
+
222
+ async function openrouter(ctx) {
223
+ const key = await resolveKey(ctx, ['OPENROUTER_API_KEY'])
224
+ if (key === undefined) return null
225
+ try {
226
+ const body = await requestJson(OPENROUTER_CREDITS, { authorization: `Bearer ${key.value}` })
227
+ const balance = parseOpenRouterCredits(body)
228
+ return { id: 'openrouter', kind: 'api', currency: 'USD', balance: balance ?? { amount: null, status: 'error', currency: 'USD', updatedAt: Date.now(), _error: { kind: 'parse' } } }
229
+ } catch (error) {
230
+ return { id: 'openrouter', kind: 'api', currency: 'USD', _error: errorDetail(error), balance: { amount: null, status: 'error', currency: 'USD', updatedAt: Date.now() } }
231
+ }
232
+ }
233
+
234
+ /** Qwen 仅按量;国际站 Key(DASHSCOPE_INTL_API_KEY)按 USD,其余 CNY。无 quota 请求。 */
235
+ async function qwen(ctx) {
236
+ const key = await resolveKey(ctx, ['DASHSCOPE_INTL_API_KEY', 'DASHSCOPE_API_KEY', 'QWEN_API_KEY'])
237
+ if (key === undefined) return null
238
+ const intl = key.name === 'DASHSCOPE_INTL_API_KEY'
239
+ const currency = intl ? 'USD' : 'CNY'
240
+ return { id: 'qwen', kind: 'api', currency, balance: { amount: null, status: 'unsupported', currency, updatedAt: Date.now() } }
241
+ }
242
+
243
+ const LEGACY_READERS = { deepseek, glm, kimi, openrouter, qwen }
244
+ const WINDOW_KEYS = new Set(['5h', 'week', 'month'])
245
+
246
+ function normalizeWindows(windows) {
247
+ if (!Array.isArray(windows)) return []
248
+ const out = []
249
+ const seen = new Set()
250
+ for (const item of windows) {
251
+ if (item === null || item === undefined || !WINDOW_KEYS.has(item.key) || seen.has(item.key)) continue
252
+ const usedPercent = clampPercent(item.usedPercent)
253
+ if (usedPercent === null) continue
254
+ seen.add(item.key)
255
+ out.push({ ...item, usedPercent })
256
+ }
257
+ return out
258
+ }
259
+
260
+ /** 通用 preflight:凭据存在才拼 query;异常返回空串,不阻断主请求。 */
261
+ async function sourceQuery(ctx, source) {
262
+ if (source.preflight === undefined) return ''
263
+ try {
264
+ const hit = await resolveKey(ctx, source.preflight.refs ?? [])
265
+ if (hit === undefined) return ''
266
+ return `${source.preflight.param}=${encodeURIComponent(hit.value)}`
267
+ } catch {
268
+ return ''
269
+ }
270
+ }
271
+
272
+ function withQuery(url, query) {
273
+ if (query === '') return url
274
+ return `${url}${url.includes('?') ? '&' : '?'}${query}`
275
+ }
276
+
277
+ /** 可选 usage 钩子:失败只留错误详情,绝不影响余额结果与账本。 */
278
+ async function readSourceUsage(source, hit) {
279
+ if (source.usage === undefined) return { channel: undefined, error: undefined }
280
+ try {
281
+ const query = source.usage.range === undefined ? '' : `range=${encodeURIComponent(source.usage.range)}`
282
+ const body = await requestJson(withQuery(source.usage.url, query), { authorization: `Bearer ${hit.value}` })
283
+ const parsed = source.usage.parse(body)
284
+ return { channel: parsed?.channel ?? undefined, error: undefined }
285
+ } catch (error) {
286
+ return { channel: undefined, error: errorDetail(error) }
287
+ }
288
+ }
289
+
290
+ async function readDeclarativeSource(ctx, prefs, source, previous) {
291
+ const hit = await resolveCredential(ctx, source.credential)
292
+ if (hit === undefined) return null
293
+ const subscription = source.kind === 'subscription'
294
+ // mode 必须由 kind 派生:声明式订阅源才是订阅;写成常量会把 api 源固化成订阅(cost=0)
295
+ const base = { id: source.id, name: providerLabel(source.id), kind: source.kind, mode: subscription ? 'subscription' : 'api', currency: source.currency }
296
+ const query = await sourceQuery(ctx, source)
297
+ let body
298
+ try {
299
+ try {
300
+ body = await requestJson(withQuery(source.quota.url, query), { authorization: `Bearer ${hit.value}` })
301
+ } catch (error) {
302
+ if (source.quota.fallbackUrl === undefined || (error.status !== 404 && error.status !== 405)) throw error
303
+ body = await requestJson(withQuery(source.quota.fallbackUrl, query), { authorization: `Bearer ${hit.value}` })
304
+ }
305
+ } catch (error) {
306
+ const detail = errorDetail(error)
307
+ // 限流复用上一份快照,避免卡片在 429 时闪成「查询失败」;退避由缓存 until 承担
308
+ if (error.status === 429 && previous !== null && previous !== undefined) {
309
+ return { ...previous, _quotaError: detail, _rateLimited: true, fetchedAt: Date.now() }
310
+ }
311
+ const status = error.status === 401 ? 'unconfigured' : 'error'
312
+ return {
313
+ ...base,
314
+ windows: [],
315
+ ...(subscription ? {} : { balance: { amount: null, status, currency: source.currency, updatedAt: Date.now() } }),
316
+ _quotaError: detail,
317
+ }
318
+ }
319
+ const parsed = source.quota.parse(body)
320
+ const windows = normalizeWindows(Array.isArray(parsed) ? parsed : parsed?.windows)
321
+ const balance = Array.isArray(parsed) ? undefined : parsed?.balance
322
+ const usage = await readSourceUsage(source, hit)
323
+ const extra = {
324
+ ...(balance === undefined ? {} : { balance }),
325
+ ...(usage.channel === undefined ? {} : { channel: usage.channel }),
326
+ ...(usage.error === undefined ? {} : { _channelError: usage.error }),
327
+ }
328
+ if (windows.length === 0 && balance === undefined) return { ...base, windows: [], _quotaError: { kind: 'parse' }, ...extra }
329
+ return { ...base, windows, ...extra }
330
+ }
331
+
332
+ async function readSource(ctx, prefs, source, previous) {
333
+ if (source.legacy !== undefined) {
334
+ const reader = LEGACY_READERS[source.legacy]
335
+ return reader(ctx, prefs)
336
+ }
337
+ return readDeclarativeSource(ctx, prefs, source, previous)
338
+ }
339
+
340
+ /** 订阅重查专用:Kimi 只查 Coding 配额,不请求 moonshot 余额。 */
341
+ async function readKimiSubscription(ctx, prefs) {
342
+ const quota = await kimiCodingQuota(ctx, prefs)
343
+ if (quota.state === 'ok') return quota.entry
344
+ if (quota.state === 'fallback') return { id: 'moonshot', kind: 'api', mode: 'unknown', currency: 'CNY', _quotaError: quota.quotaError ?? null }
345
+ return null
346
+ }
347
+
348
+ const TTL_OK = 60000
349
+ const TTL_FAIL = 10000
350
+
351
+ /** 限流条目按 Retry-After 延后重试,成功 60s / 失败 10s 的基线不变。 */
352
+ function cacheExpiry(data, now) {
353
+ const retryAfter = data?._rateLimited === true ? Number(data?._quotaError?.retryAfter) : NaN
354
+ if (Number.isFinite(retryAfter) && retryAfter > 0) return now + Math.max(TTL_FAIL, retryAfter * 1000)
355
+ return now + (data === null || data?._rateLimited === true ? TTL_FAIL : TTL_OK)
356
+ }
357
+
358
+ async function readCachedSource(ctx, prefs, source, cache) {
359
+ const now = Date.now()
360
+ const cached = cache.get(source.id)
361
+ if (cached !== undefined && cached.promise === null && now < (cached.until ?? now)) return cached.data
362
+ if (cached?.promise !== undefined && cached.promise !== null) return cached.promise
363
+ const promise = readSource(ctx, prefs, source, cached?.data ?? null)
364
+ .then((data) => {
365
+ const at = Date.now()
366
+ cache.set(source.id, { at, ok: data !== null && data?._rateLimited !== true, data, promise: null, until: cacheExpiry(data, at) })
367
+ return data
368
+ })
369
+ .catch((error) => {
370
+ const at = Date.now()
371
+ cache.set(source.id, { at, ok: false, data: null, promise: null, until: at + TTL_FAIL })
372
+ throw error
373
+ })
374
+ cache.set(source.id, { at: cached?.at ?? 0, ok: cached?.ok === true, data: cached?.data ?? null, promise, until: cached?.until ?? null })
375
+ return promise
376
+ }
377
+
378
+ function visibleEntry(entry, prefs) {
379
+ return entry !== null && prefs?.billingModes?.[entry.id] !== 'hide'
380
+ }
381
+
382
+ /** Adapter → VM boundary: normalize ad-hoc adapter rows into ProviderSnapshot. */
383
+ export function toSnapshot(entry) {
384
+ const error = entry.error ?? entry._error ?? null
385
+ const quotaError = entry.quotaError ?? entry._quotaError ?? null
386
+ const balance = entry.balance ?? null
387
+ const status = error !== null
388
+ ? 'error'
389
+ : balance?.status === 'unconfigured'
390
+ ? 'unconfigured'
391
+ : balance?.status === 'error'
392
+ ? 'error'
393
+ : 'ok'
394
+ return {
395
+ id: entry.id,
396
+ name: entry.name,
397
+ kind: entry.kind === 'subscription' ? 'subscription' : 'api',
398
+ currency: entry.currency,
399
+ status,
400
+ balance,
401
+ // 渠道侧只读用量与限流标记:仅展示用,不参与计价(REQ-04)
402
+ ...(entry.channel === undefined ? {} : { channel: entry.channel }),
403
+ ...(entry._channelError === undefined ? {} : { channelError: entry._channelError }),
404
+ rateLimited: entry._rateLimited === true,
405
+ mode: entry.mode === 'subscription' || entry.mode === 'api' ? entry.mode : 'unknown',
406
+ windows: Array.isArray(entry.windows) ? entry.windows : Array.isArray(entry.plans) ? entry.plans : [],
407
+ error,
408
+ quotaError,
409
+ fetchedAt: entry.fetchedAt ?? Date.now(),
410
+ }
411
+ }
412
+
413
+ /**
414
+ * Query configured providers; each failure is isolated. Balance/credits are always requested
415
+ * (P2 shows them regardless of the P1-only toggle, #31). 空档原因挂在返回数组的 `misses` 上:
416
+ * `<id>:none` 未配置、`:error` 请求失败、`:hidden` 被计费模式隐藏。
417
+ * 缓存按源保存在调用方传入的 Map 中:成功 60s、失败 10s,并发复用 promise。
418
+ */
419
+ export async function readProviders(ctx, prefs, cache = new Map()) {
420
+ const results = await Promise.allSettled(PROVIDER_SOURCES.map((source) => readCachedSource(ctx, prefs, source, cache)))
421
+ const out = []
422
+ const misses = []
423
+ const failures = []
424
+ results.forEach((result, index) => {
425
+ const id = PROVIDER_SOURCES[index].id
426
+ if (result.status !== 'fulfilled') {
427
+ misses.push(`${id}:error`)
428
+ failures.push({ id, error: errorDetail(result.reason) })
429
+ return
430
+ }
431
+ if (result.value === null) {
432
+ // 声明式源返回 null 即凭据未命中;并入 failures 以便 detect.fail 归因(不改变 :none 契约)
433
+ const refs = PROVIDER_SOURCES[index].credential?.refs ?? []
434
+ misses.push(`${id}:none`)
435
+ if (refs.length > 0) failures.push({ id, error: { kind: 'missing-credential', refs } })
436
+ return
437
+ }
438
+ if (visibleEntry(result.value, prefs) !== true) { misses.push(`${id}:hidden`); return }
439
+ const value = result.value
440
+ value.currency = value.currency ?? providerCurrency(normalizeProvider(value.id))
441
+ out.push(toSnapshot(value))
442
+ })
443
+ out.misses = misses
444
+ out.failures = failures
445
+ return out
446
+ }
447
+
448
+ /**
449
+ * P3「重新检测」专用:只重查订阅 provider 的配额,绕过缓存。
450
+ * 仅返回 subscription 条目;无 Key 的 provider 不返回(由调用方从缓存移除)。
451
+ */
452
+ export async function readSubscriptions(ctx, prefs) {
453
+ const sources = PROVIDER_SOURCES.filter((source) => source.kind === 'subscription')
454
+ const results = await Promise.allSettled(sources.map((source) => (
455
+ source.legacy === 'kimi' ? readKimiSubscription(ctx, prefs) : readSource(ctx, prefs, source)
456
+ )))
457
+ const out = []
458
+ const failures = []
459
+ results.forEach((result, index) => {
460
+ if (result.status !== 'fulfilled') {
461
+ failures.push({ id: sources[index].id, error: errorDetail(result.reason) })
462
+ return
463
+ }
464
+ if (result.value === null) return
465
+ // 旧源(GLM / Kimi)配额失败时可能回落 API 条目,保留旧行为;新源只保留订阅条目。
466
+ const legacy = sources[index].legacy !== undefined
467
+ if (result.value.kind !== 'subscription' && legacy !== true) return
468
+ if (visibleEntry(result.value, prefs) !== true) return
469
+ out.push(toSnapshot(result.value))
470
+ })
471
+ out.failures = failures
472
+ return out
473
+ }
474
+
475
+ /** #46/#47:按 §2.5 adapter.* 事件表记侦测结果与错误原因——只记状态/计数/错误分类,不记 Key/响应体(脱敏约束)。 */
476
+ export function logAdapterEvents(log, providers) {
477
+ const info = (module, event, meta) => log.info(module, event, meta)
478
+ // 错误详情合并进 meta:kind=http 时带 status,便于报障还原原因
479
+ const errorMeta = (detail) => (detail === null || detail === undefined
480
+ ? {}
481
+ : detail.kind === 'http'
482
+ ? { errorKind: detail.kind, httpStatus: detail.status, ...(detail.retryAfter === undefined ? {} : { retryAfter: detail.retryAfter }) }
483
+ : { errorKind: detail.kind })
484
+ for (const item of providers) {
485
+ if (item.id === 'deepseek-official') {
486
+ if (item.balance?.status === 'ok') info('adapter.deepseek', 'balance.ok', { amount: item.balance.amount })
487
+ else if (item.balance?.status === 'unconfigured') info('adapter.deepseek', 'balance.auth', errorMeta(item.error))
488
+ else if (item.balance !== undefined) info('adapter.deepseek', 'balance.error', { status: item.balance.status, ...errorMeta(item.error ?? item.balance._error) })
489
+ continue
490
+ }
491
+ if (item.id === 'zhipu' || item.id === 'moonshot') {
492
+ const module = item.id === 'zhipu' ? 'adapter.glm' : 'adapter.kimi'
493
+ if (item.kind === 'subscription') {
494
+ const windows = (item.windows ?? []).length
495
+ if (windows > 0) info(module, 'quota.ok', { windows })
496
+ else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
497
+ else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
498
+ } else if (item.quotaError !== undefined && item.quotaError !== null) {
499
+ info(module, 'quota.fail', { ...errorMeta(item.quotaError) })
500
+ } else {
501
+ info(module, 'quota.miss', {})
502
+ }
503
+ if (item.id === 'moonshot' && item.balance?.status === 'ok') info('adapter.kimi', 'balance.ok', { amount: item.balance.amount })
504
+ if (item.id === 'moonshot' && item.balance?.status === 'error') info('adapter.kimi', 'balance.error', { status: 'error', ...errorMeta(item.error ?? item.balance._error) })
505
+ continue
506
+ }
507
+ if (item.id === 'openrouter') {
508
+ if (item.balance?.status === 'ok') info('adapter.openrouter', 'credits.ok', { amount: item.balance.amount })
509
+ else if (item.balance !== undefined) info('adapter.openrouter', 'credits.error', { status: item.balance.status, ...errorMeta(item.error ?? item.balance._error) })
510
+ continue
511
+ }
512
+ if (item.id === 'qwen') {
513
+ info('adapter.qwen', item.currency === 'USD' ? 'currency.usd' : 'detected', {})
514
+ continue
515
+ }
516
+ if (item.id === 'opencode-go' || item.id === 'command-code') {
517
+ const module = item.id === 'opencode-go' ? 'adapter.opencode' : 'adapter.commandcode'
518
+ const windows = (item.windows ?? []).length
519
+ if (windows > 0) info(module, 'quota.ok', { windows })
520
+ else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
521
+ else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
522
+ if (item.balance?.status === 'ok') info(module, 'credits.ok', { amount: item.balance.amount })
523
+ continue
524
+ }
525
+ if (item.id === 'ollama') {
526
+ const balance = item.balance
527
+ if (balance?.status === 'ok') info('adapter.ollama', 'quota.ok', { amount: balance.amount, purchased: balance.purchased ?? 0, legacy: balance.legacy === true })
528
+ else if (balance?.status === 'unconfigured') info('adapter.ollama', 'quota.auth', {})
529
+ else info('adapter.ollama', 'quota.fail', { status: balance?.status ?? 'error', ...errorMeta(item.quotaError ?? item.error) })
530
+ if (item.channel !== undefined) info('adapter.ollama', 'usage', { range: item.channel.range, usageUsd: item.channel.usageUsd })
531
+ else if (item.channelError !== undefined) info('adapter.ollama', 'usage.fail', errorMeta(item.channelError))
532
+ }
533
+ }
534
+ }
535
+
536
+ const FAILURE_MODULES = {
537
+ 'deepseek-official': 'adapter.deepseek',
538
+ zhipu: 'adapter.glm',
539
+ moonshot: 'adapter.kimi',
540
+ openrouter: 'adapter.openrouter',
541
+ qwen: 'adapter.qwen',
542
+ 'opencode-go': 'adapter.opencode',
543
+ 'command-code': 'adapter.commandcode',
544
+ }
545
+
546
+ /**
547
+ * 探测结果签名:miss 清单不变时无需重复记日志,避免每轮刷新刷屏。
548
+ * 返回 `id:none,id:hidden,...` 的稳定字符串;无 miss 时为空串。
549
+ */
550
+ export function missSignature(providers) {
551
+ return (providers?.misses ?? []).join(',')
552
+ }
553
+
554
+ /** Promise.allSettled 的拒绝项没有 entry,单独补 adapter.<id> 失败日志。 */
555
+ export function logAdapterFailures(log, failures = []) {
556
+ for (const item of failures) {
557
+ const module = FAILURE_MODULES[item.id] ?? `adapter.${item.id}`
558
+ const error = item.error ?? { kind: 'network' }
559
+ log.warn(module, 'detect.fail', {
560
+ errorKind: error.kind,
561
+ ...(Array.isArray(error.refs) ? { refs: error.refs } : {}),
562
+ ...(error.status === undefined ? {} : { httpStatus: error.status }),
563
+ ...(error.upstream === true ? { upstream: true } : {}),
564
+ })
565
+ }
566
+ }
567
+
568
+ export { KIMI_USAGES, GLM_QUOTA, KIMI_BALANCE, OPENROUTER_CREDITS }