dsh-token-dash 2.0.2 → 2.1.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
@@ -108,6 +108,9 @@ async function requestJson(url, headers) {
108
108
  const error = new Error(`http-${response.status}`)
109
109
  error.status = response.status
110
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
111
114
  throw error
112
115
  }
113
116
  return body
@@ -116,7 +119,12 @@ async function requestJson(url, headers) {
116
119
  /** #47:错误分类(http+状态码 / timeout / network)——挂在条目 `_error`/`_quotaError` 上供日志还原原因。 */
117
120
  function errorDetail(error) {
118
121
  if (error?.status !== undefined) {
119
- return { kind: 'http', status: error.status, ...(error.status >= 500 ? { upstream: true } : {}) }
122
+ return {
123
+ kind: 'http',
124
+ status: error.status,
125
+ ...(error.status >= 500 ? { upstream: true } : {}),
126
+ ...(error.retryAfter === undefined ? {} : { retryAfter: error.retryAfter }),
127
+ }
120
128
  }
121
129
  const name = `${error?.name ?? ''} ${error?.message ?? ''}`
122
130
  if (name.includes('Timeout') || name.includes('abort') || name.includes('Abort')) return { kind: 'timeout' }
@@ -266,10 +274,25 @@ function withQuery(url, query) {
266
274
  return `${url}${url.includes('?') ? '&' : '?'}${query}`
267
275
  }
268
276
 
269
- async function readDeclarativeSource(ctx, prefs, source) {
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) {
270
291
  const hit = await resolveCredential(ctx, source.credential)
271
292
  if (hit === undefined) return null
272
- const base = { id: source.id, name: providerLabel(source.id), kind: source.kind, mode: 'subscription', currency: source.currency }
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 }
273
296
  const query = await sourceQuery(ctx, source)
274
297
  let body
275
298
  try {
@@ -280,21 +303,38 @@ async function readDeclarativeSource(ctx, prefs, source) {
280
303
  body = await requestJson(withQuery(source.quota.fallbackUrl, query), { authorization: `Bearer ${hit.value}` })
281
304
  }
282
305
  } catch (error) {
283
- return { ...base, windows: [], _quotaError: errorDetail(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
+ }
284
318
  }
285
319
  const parsed = source.quota.parse(body)
286
320
  const windows = normalizeWindows(Array.isArray(parsed) ? parsed : parsed?.windows)
287
321
  const balance = Array.isArray(parsed) ? undefined : parsed?.balance
288
- if (windows.length === 0 && balance === undefined) return { ...base, windows: [], _quotaError: { kind: 'parse' } }
289
- return { ...base, windows, ...(balance === undefined ? {} : { 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 }
290
330
  }
291
331
 
292
- async function readSource(ctx, prefs, source) {
332
+ async function readSource(ctx, prefs, source, previous) {
293
333
  if (source.legacy !== undefined) {
294
334
  const reader = LEGACY_READERS[source.legacy]
295
335
  return reader(ctx, prefs)
296
336
  }
297
- return readDeclarativeSource(ctx, prefs, source)
337
+ return readDeclarativeSource(ctx, prefs, source, previous)
298
338
  }
299
339
 
300
340
  /** 订阅重查专用:Kimi 只查 Coding 配额,不请求 moonshot 余额。 */
@@ -308,22 +348,30 @@ async function readKimiSubscription(ctx, prefs) {
308
348
  const TTL_OK = 60000
309
349
  const TTL_FAIL = 10000
310
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
+
311
358
  async function readCachedSource(ctx, prefs, source, cache) {
312
359
  const now = Date.now()
313
360
  const cached = cache.get(source.id)
314
- const ttl = cached?.ok === true ? TTL_OK : TTL_FAIL
315
- if (cached !== undefined && cached.promise === null && now - cached.at < ttl) return cached.data
361
+ if (cached !== undefined && cached.promise === null && now < (cached.until ?? now)) return cached.data
316
362
  if (cached?.promise !== undefined && cached.promise !== null) return cached.promise
317
- const promise = readSource(ctx, prefs, source)
363
+ const promise = readSource(ctx, prefs, source, cached?.data ?? null)
318
364
  .then((data) => {
319
- cache.set(source.id, { at: Date.now(), ok: data !== null, data, promise: null })
365
+ const at = Date.now()
366
+ cache.set(source.id, { at, ok: data !== null && data?._rateLimited !== true, data, promise: null, until: cacheExpiry(data, at) })
320
367
  return data
321
368
  })
322
369
  .catch((error) => {
323
- cache.set(source.id, { at: Date.now(), ok: false, data: null, promise: null })
370
+ const at = Date.now()
371
+ cache.set(source.id, { at, ok: false, data: null, promise: null, until: at + TTL_FAIL })
324
372
  throw error
325
373
  })
326
- cache.set(source.id, { at: cached?.at ?? 0, ok: cached?.ok === true, data: cached?.data ?? null, promise })
374
+ cache.set(source.id, { at: cached?.at ?? 0, ok: cached?.ok === true, data: cached?.data ?? null, promise, until: cached?.until ?? null })
327
375
  return promise
328
376
  }
329
377
 
@@ -350,6 +398,10 @@ export function toSnapshot(entry) {
350
398
  currency: entry.currency,
351
399
  status,
352
400
  balance,
401
+ // 渠道侧只读用量与限流标记:仅展示用,不参与计价(REQ-04)
402
+ ...(entry.channel === undefined ? {} : { channel: entry.channel }),
403
+ ...(entry._channelError === undefined ? {} : { channelError: entry._channelError }),
404
+ rateLimited: entry._rateLimited === true,
353
405
  mode: entry.mode === 'subscription' || entry.mode === 'api' ? entry.mode : 'unknown',
354
406
  windows: Array.isArray(entry.windows) ? entry.windows : Array.isArray(entry.plans) ? entry.plans : [],
355
407
  error,
@@ -418,7 +470,11 @@ export async function readSubscriptions(ctx, prefs) {
418
470
  export function logAdapterEvents(log, providers) {
419
471
  const info = (module, event, meta) => log.info(module, event, meta)
420
472
  // 错误详情合并进 meta:kind=http 时带 status,便于报障还原原因
421
- const errorMeta = (detail) => (detail === null || detail === undefined ? {} : detail.kind === 'http' ? { errorKind: detail.kind, httpStatus: detail.status } : { errorKind: detail.kind })
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 })
422
478
  for (const item of providers) {
423
479
  if (item.id === 'deepseek-official') {
424
480
  if (item.balance?.status === 'ok') info('adapter.deepseek', 'balance.ok', { amount: item.balance.amount })
@@ -458,6 +514,15 @@ export function logAdapterEvents(log, providers) {
458
514
  else if (item.quotaError?.kind === 'parse') info(module, 'quota.parse', {})
459
515
  else info(module, 'quota.fail', { windows: 0, ...errorMeta(item.quotaError) })
460
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))
461
526
  }
462
527
  }
463
528
  }
@@ -472,6 +537,14 @@ const FAILURE_MODULES = {
472
537
  'command-code': 'adapter.commandcode',
473
538
  }
474
539
 
540
+ /**
541
+ * 探测结果签名:miss 清单不变时无需重复记日志,避免每轮刷新刷屏。
542
+ * 返回 `id:none,id:hidden,...` 的稳定字符串;无 miss 时为空串。
543
+ */
544
+ export function missSignature(providers) {
545
+ return (providers?.misses ?? []).join(',')
546
+ }
547
+
475
548
  /** Promise.allSettled 的拒绝项没有 entry,单独补 adapter.<id> 失败日志。 */
476
549
  export function logAdapterFailures(log, failures = []) {
477
550
  for (const item of failures) {
package/src/catalog.js ADDED
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Price catalog normalization: model-only entries, no provider dimension.
3
+ * Community feed / bundled catalog / OpenRouter router prices all normalize here
4
+ * so `match.js` only ever sees one shape.
5
+ */
6
+ import { normalizeModel } from './providers.js'
7
+
8
+ const NUMERIC_NOISE = /^\d{3,}$/
9
+
10
+ function finite(value) {
11
+ return typeof value === 'number' && Number.isFinite(value) && value >= 0 ? value : null
12
+ }
13
+
14
+ function firstNumber(...values) {
15
+ for (const value of values) {
16
+ const parsed = finite(value)
17
+ if (parsed !== null) return parsed
18
+ }
19
+ return null
20
+ }
21
+
22
+ function pricesOf(raw) {
23
+ return {
24
+ input: firstNumber(raw?.input, raw?.inputCostPerMillion),
25
+ cacheRead: firstNumber(raw?.cacheRead, raw?.cacheReadCostPerMillion) ?? 0,
26
+ cacheWrite: firstNumber(raw?.cacheWrite, raw?.cacheCreationCostPerMillion) ?? 0,
27
+ output: firstNumber(raw?.output, raw?.outputCostPerMillion),
28
+ }
29
+ }
30
+
31
+ function complete(prices) {
32
+ return prices !== null && prices.input !== null && prices.output !== null
33
+ }
34
+
35
+ /**
36
+ * Community feed expresses peak/off-peak through `dailySlots`; only the standard
37
+ * weekday windows (09:00-12:00 / 14:00-18:00) are recognized, everything else
38
+ * stays flat instead of pretending to be tiered.
39
+ */
40
+ export function tieredPrices(raw) {
41
+ const slots = Array.isArray(raw?.dailySlots) ? raw.dailySlots : []
42
+ const slot = slots.find((item) => Array.isArray(item?.windows) && item.windows.length === 2)
43
+ if (slot === undefined) return null
44
+ const windows = slot.windows.map((item) => [Number(item?.startMinute), Number(item?.endMinute)])
45
+ const standard = windows[0][0] === 540 && windows[0][1] === 720 && windows[1][0] === 840 && windows[1][1] === 1080
46
+ const days = Array.isArray(slot.daysOfWeek) ? slot.daysOfWeek.map(Number) : [1, 2, 3, 4, 5]
47
+ const weekdays = days.length === 5 && [1, 2, 3, 4, 5].every((day) => days.includes(day))
48
+ if (!standard || !weekdays) return null
49
+ const peak = pricesOf(slot)
50
+ const offPeak = pricesOf(raw)
51
+ if (!complete(peak) || !complete(offPeak)) return null
52
+ return { peak, offPeak }
53
+ }
54
+
55
+ /** Already-normalized `peak` / `offPeak` blocks (bundled catalog, tests). */
56
+ function explicitTiers(raw) {
57
+ if (raw?.peak == null || raw?.offPeak == null) return null
58
+ const peak = pricesOf(raw.peak)
59
+ const offPeak = pricesOf(raw.offPeak)
60
+ return complete(peak) && complete(offPeak) ? { peak, offPeak } : null
61
+ }
62
+
63
+ function toEntry(raw, source) {
64
+ const modelId = normalizeModel(raw?.modelId ?? raw?.model)
65
+ if (modelId === 'unknown') return null
66
+ const tiers = tieredPrices(raw) ?? explicitTiers(raw)
67
+ const flat = pricesOf(raw?.prices !== undefined ? raw.prices : raw)
68
+ if (tiers === null && !complete(flat)) return null
69
+ const aliases = Array.isArray(raw?.aliases) ? raw.aliases.map((alias) => normalizeModel(alias)) : []
70
+ // Pre-compile once: one malformed pattern must not disable the rest.
71
+ const regexps = []
72
+ for (const pattern of Array.isArray(raw?.aliasPatterns) ? raw.aliasPatterns : []) {
73
+ if (typeof pattern !== 'string') continue
74
+ try {
75
+ regexps.push(new RegExp(pattern, 'i'))
76
+ } catch {
77
+ // dropped on purpose; reported by the caller through catalogInfo/logs
78
+ }
79
+ }
80
+ return {
81
+ modelId,
82
+ displayName: String(raw?.displayName ?? raw?.modelId ?? raw?.model ?? modelId),
83
+ family: String(raw?.family ?? ''),
84
+ aliases: aliases.filter((alias) => alias !== 'unknown' && alias !== modelId),
85
+ regexps,
86
+ parsed: null,
87
+ source,
88
+ prices: tiers === null ? flat : null,
89
+ peak: tiers?.peak ?? null,
90
+ offPeak: tiers?.offPeak ?? null,
91
+ currency: raw?.currency === 'USD' ? 'USD' : 'CNY',
92
+ }
93
+ }
94
+
95
+ /**
96
+ * Normalize one source into `{ entries, currency, updatedAt, source }`.
97
+ * Entries are deduped by `modelId` so `find` never depends on array order.
98
+ */
99
+ export function loadCatalog(raw, source = 'community') {
100
+ const entries = []
101
+ const seen = new Set()
102
+ let dropped = 0
103
+ for (const item of Array.isArray(raw?.models) ? raw.models : []) {
104
+ const entry = toEntry(item, source)
105
+ if (entry === null) {
106
+ dropped += 1
107
+ continue
108
+ }
109
+ if (seen.has(entry.modelId)) {
110
+ dropped += 1
111
+ continue
112
+ }
113
+ seen.add(entry.modelId)
114
+ entries.push(entry)
115
+ }
116
+ return {
117
+ entries,
118
+ dropped,
119
+ currency: raw?.currency === 'USD' ? 'USD' : 'CNY',
120
+ updatedAt: raw?.updatedAt === undefined ? null : String(raw.updatedAt),
121
+ source,
122
+ }
123
+ }
124
+
125
+ /** Router prices arrive per-token; fold into the same per-million shape. */
126
+ export function routerModels(raw) {
127
+ const models = []
128
+ for (const item of Array.isArray(raw?.data) ? raw.data : []) {
129
+ const input = Number(item?.pricing?.prompt)
130
+ const output = Number(item?.pricing?.completion)
131
+ if (!Number.isFinite(input) || !Number.isFinite(output)) continue
132
+ models.push({
133
+ modelId: normalizeModel(item.id),
134
+ displayName: String(item.name ?? item.id),
135
+ family: String(item.id).split('/')[0] ?? '',
136
+ input: input * 1_000_000,
137
+ cacheRead: Number(item?.pricing?.input_cache_read ?? 0) * 1_000_000,
138
+ cacheWrite: Number(item?.pricing?.input_cache_write ?? 0) * 1_000_000,
139
+ output: output * 1_000_000,
140
+ currency: 'USD',
141
+ })
142
+ }
143
+ return models
144
+ }
145
+
146
+ export { NUMERIC_NOISE }
package/src/collect.js CHANGED
@@ -30,8 +30,8 @@ export function headerFromEvent(event) {
30
30
  return { provider, model }
31
31
  }
32
32
 
33
- /** 入账一条事件;返回记录或 undefined。 */
34
- export function ingest(state, sessionId, event, seedFloor = 0) {
33
+ /** 入账一条事件;返回记录或 undefined。`kindOf` 缺省时 `addRecord` 走 registry 兜底。 */
34
+ export function ingest(state, sessionId, event, seedFloor = 0, kindOf) {
35
35
  const seq = num(event?.seq)
36
36
  const mark = num(state.watermarks[sessionId])
37
37
  if (seq > 0 && seq <= mark) return undefined
@@ -55,12 +55,12 @@ export function ingest(state, sessionId, event, seedFloor = 0) {
55
55
  if (record.model === '' && fallback.model !== undefined) record.model = fallback.model
56
56
  }
57
57
  }
58
- addRecord(state, record)
58
+ addRecord(state, record, kindOf)
59
59
  if (seq > 0) state.watermarks[sessionId] = seq
60
60
  return record
61
61
  }
62
62
 
63
- export async function backfill(ctx, state) {
63
+ export async function backfill(ctx, state, kindOf) {
64
64
  const persistence = ctx.get?.('sessionPersistence')
65
65
  if (persistence === undefined || typeof persistence.list !== 'function') {
66
66
  return { sessions: 0, records: 0, degraded: 'no-session-persistence' }
@@ -86,7 +86,7 @@ export async function backfill(ctx, state) {
86
86
  providers.add(source.provider)
87
87
  providerByModel.set(model, providers)
88
88
  }
89
- if (ingest(state, id, event, seed) !== undefined) records += 1
89
+ if (ingest(state, id, event, seed, kindOf) !== undefined) records += 1
90
90
  }
91
91
  } catch {
92
92
  // 单个会话失败不影响其余会话