dsh-token-dash 2.0.1 → 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/README.en.md +21 -16
- package/README.md +17 -13
- package/client.js +107 -27
- package/index.js +122 -16
- package/locale/en.json +13 -1
- package/locale/zh.json +13 -1
- package/package.json +1 -1
- package/src/adapters.js +88 -15
- package/src/catalog.js +146 -0
- package/src/collect.js +5 -5
- package/src/core.js +177 -38
- package/src/match.js +119 -0
- package/src/pricing.js +146 -204
- package/src/providers.js +13 -1
- package/src/quota-sources.js +101 -0
- package/src/store.js +55 -2
package/index.js
CHANGED
|
@@ -5,13 +5,14 @@ import { readFileSync } from 'node:fs'
|
|
|
5
5
|
import { existsSync } from 'node:fs'
|
|
6
6
|
import { spawn } from 'node:child_process'
|
|
7
7
|
import { dirname, join } from 'node:path'
|
|
8
|
-
import { buildSummary, buildUsage, emptyState, localMonthKey, num, repriceState, stampProviderKinds } from './src/core.js'
|
|
8
|
+
import { buildSummary, buildUsage, emptyState, localMonthKey, num, repriceState, repriceUnpriced, resolveProviderKind, stampProviderKinds } from './src/core.js'
|
|
9
9
|
import { ingest, backfill } from './src/collect.js'
|
|
10
|
-
import { REFRESH_OPTIONS, createFlusher, dataDir, loadPrefs, loadState, logsDir, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
|
|
10
|
+
import { REFRESH_OPTIONS, createFlusher, dataDir, loadPrefs, loadState, logsDir, normalizeCurrencyMap, normalizeOverrides, recoverState, resolveHome, saveJson, saveMonths } from './src/store.js'
|
|
11
11
|
import { buildExport, mergeImportDays, validateBundle } from './src/backup.js'
|
|
12
|
-
import { logAdapterEvents, logAdapterFailures, readProviders, readSubscriptions } from './src/adapters.js'
|
|
12
|
+
import { logAdapterEvents, logAdapterFailures, missSignature, readProviders, readSubscriptions } from './src/adapters.js'
|
|
13
13
|
import { PROVIDER_SOURCES } from './src/quota-sources.js'
|
|
14
|
-
import { catalogInfo, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
|
|
14
|
+
import { catalogInfo, configurePricing, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
|
|
15
|
+
import { providerCurrency } from './src/providers.js'
|
|
15
16
|
import { clearLog, createLogger, exportLog } from './src/diagnostics.js'
|
|
16
17
|
import { isNewer } from './src/version.js'
|
|
17
18
|
|
|
@@ -149,6 +150,8 @@ function normalizePrefs(input, base) {
|
|
|
149
150
|
billingModes: { ...(base.billingModes ?? {}) },
|
|
150
151
|
refreshMs: base.refreshMs,
|
|
151
152
|
showBalance: base.showBalance,
|
|
153
|
+
priceOverrides: normalizeOverrides(base.priceOverrides),
|
|
154
|
+
providerCurrency: normalizeCurrencyMap(base.providerCurrency),
|
|
152
155
|
}
|
|
153
156
|
if (input?.budgets !== undefined) {
|
|
154
157
|
if (input.budgets === null || typeof input.budgets !== 'object') throw new Error('invalid-budgets')
|
|
@@ -173,6 +176,13 @@ function normalizePrefs(input, base) {
|
|
|
173
176
|
prefs.refreshMs = refresh
|
|
174
177
|
}
|
|
175
178
|
if (input?.showBalance !== undefined) prefs.showBalance = input.showBalance === true
|
|
179
|
+
// 两个"仅认文件"的键:随 PUT /prefs 与导入一起透传,非法条目静默丢弃(不阻塞保存)
|
|
180
|
+
prefs.priceOverrides = input?.priceOverrides !== undefined
|
|
181
|
+
? normalizeOverrides(input.priceOverrides)
|
|
182
|
+
: normalizeOverrides(base.priceOverrides)
|
|
183
|
+
prefs.providerCurrency = input?.providerCurrency !== undefined
|
|
184
|
+
? normalizeCurrencyMap(input.providerCurrency)
|
|
185
|
+
: normalizeCurrencyMap(base.providerCurrency)
|
|
176
186
|
return prefs
|
|
177
187
|
}
|
|
178
188
|
|
|
@@ -198,11 +208,26 @@ export function apply(ctx) {
|
|
|
198
208
|
let prefs
|
|
199
209
|
let state
|
|
200
210
|
let providerCache = new Map()
|
|
201
|
-
let providerCacheMeta = { at: 0, hadProviders: false, degraded: false }
|
|
211
|
+
let providerCacheMeta = { at: 0, hadProviders: false, degraded: false, missSignature: null }
|
|
202
212
|
const cacheData = () => [...providerCache.values()].map((entry) => entry.data).filter((item) => item !== null && item !== undefined)
|
|
203
213
|
const clearProviderCache = () => {
|
|
204
214
|
providerCache.clear()
|
|
205
|
-
providerCacheMeta = { at: 0, hadProviders: false, degraded: false }
|
|
215
|
+
providerCacheMeta = { at: 0, hadProviders: false, degraded: false, missSignature: null }
|
|
216
|
+
}
|
|
217
|
+
const metaOf = (id) => cacheData().find((item) => item.id === id)
|
|
218
|
+
/** 形态判定:把当前快照交给 core,prefs / registry 的优先级由 core 决定。 */
|
|
219
|
+
const kindOf = (id) => resolveProviderKind(state, prefs, id, metaOf(id))
|
|
220
|
+
/** 币种判定:声明 > 快照 > registry(BND-10,不做换算)。 */
|
|
221
|
+
const currencyOf = (id) => prefs?.providerCurrency?.[id] ?? metaOf(id)?.currency ?? providerCurrency(id)
|
|
222
|
+
let pricingConfigLogged = ''
|
|
223
|
+
const applyPricingConfig = () => {
|
|
224
|
+
configurePricing({ overrides: prefs?.priceOverrides ?? {}, currencyOf })
|
|
225
|
+
const overrides = Object.keys(prefs?.priceOverrides ?? {}).length
|
|
226
|
+
const currencies = Object.keys(prefs?.providerCurrency ?? {}).length
|
|
227
|
+
const signature = `${overrides}/${currencies}`
|
|
228
|
+
if (signature === pricingConfigLogged) return // 启动期会被调用两次,日志只在变化时打
|
|
229
|
+
pricingConfigLogged = signature
|
|
230
|
+
logger.info('pricing', 'config', { overrides, currencies })
|
|
206
231
|
}
|
|
207
232
|
const ready = Promise.all([loadState(dir, logger), loadPrefs(dir, logger)]).then(([loadedState, loadedPrefs]) => {
|
|
208
233
|
state = loadedState ?? emptyState()
|
|
@@ -247,8 +272,29 @@ export function apply(ctx) {
|
|
|
247
272
|
.then((ok) => logger.info('pricing', 'router.loaded', { ok }))
|
|
248
273
|
.catch((error) => logger.warn('pricing', 'router.fail', { message: String(error?.message ?? error) })),
|
|
249
274
|
])
|
|
275
|
+
applyPricingConfig()
|
|
250
276
|
})
|
|
251
277
|
|
|
278
|
+
/** 有界就绪门:超时降级用当前表,绝不无限阻塞记账(RSK-05)。 */
|
|
279
|
+
let pricingSettled = false
|
|
280
|
+
function pricingGate() {
|
|
281
|
+
if (pricingSettled) return Promise.resolve()
|
|
282
|
+
let settled = false
|
|
283
|
+
return new Promise((resolve) => {
|
|
284
|
+
const finish = (degraded) => {
|
|
285
|
+
if (settled) return
|
|
286
|
+
settled = true
|
|
287
|
+
pricingSettled = true
|
|
288
|
+
if (degraded) logger.warn('pricing', 'ready', { waitedMs: 5000, source: 'timeout-degraded' })
|
|
289
|
+
resolve()
|
|
290
|
+
}
|
|
291
|
+
const timer = setTimeout(() => finish(true), 5000)
|
|
292
|
+
timer.unref?.()
|
|
293
|
+
// 表已就绪时同步收敛,并清掉定时器——否则孤儿定时器会在 5s 后误报降级
|
|
294
|
+
pricingReady.then(() => { clearTimeout(timer); finish(false) }, () => { clearTimeout(timer); finish(false) })
|
|
295
|
+
})
|
|
296
|
+
}
|
|
297
|
+
|
|
252
298
|
ctx.inject(['sessionPersistence'], (scoped) => {
|
|
253
299
|
ready
|
|
254
300
|
.then(async () => {
|
|
@@ -261,10 +307,17 @@ export function apply(ctx) {
|
|
|
261
307
|
}),
|
|
262
308
|
])
|
|
263
309
|
// 不丢聚合:先并回 1.0.3 迁移备份,再按日级 token 重算旧计价成本
|
|
310
|
+
applyPricingConfig()
|
|
264
311
|
const recovery = await recoverState(dir, state, logger)
|
|
265
|
-
|
|
312
|
+
// 旧计价模型(costVersion < 3)一次性重算,保留给 v2 历史数据
|
|
313
|
+
const repriced = repriceState(state, kindOf)
|
|
266
314
|
if (repriced.repriced) logger.info('boot', 'state.reprice', { rows: repriced.rows, recovered: recovery.recovered })
|
|
267
|
-
const result = await backfill(scoped, state)
|
|
315
|
+
const result = await backfill(scoped, state, kindOf)
|
|
316
|
+
// 启动补算:只补 priced=false,已计价 / 订阅 / 零消耗一律不动(REQ-09)
|
|
317
|
+
const unpriced = repriceUnpriced(state, {}, kindOf)
|
|
318
|
+
if (unpriced.rows > 0 || Object.values(unpriced.skipped).some((count) => count > 0)) {
|
|
319
|
+
logger.info('pricing', 'reprice', unpriced)
|
|
320
|
+
}
|
|
268
321
|
if (flushReady === undefined) {
|
|
269
322
|
await saveJson(dir, 'daily.json', state)
|
|
270
323
|
await saveMonths(dir, state)
|
|
@@ -280,9 +333,12 @@ export function apply(ctx) {
|
|
|
280
333
|
'session/event',
|
|
281
334
|
(session, event) => {
|
|
282
335
|
if (state === undefined) return
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
336
|
+
void pricingGate().then(() => {
|
|
337
|
+
if (state === undefined) return
|
|
338
|
+
const sessionId = session?.id ?? session?.header?.id ?? 'live'
|
|
339
|
+
const record = ingest(state, sessionId, event, num(session?.header?.seedLength), kindOf)
|
|
340
|
+
if (record !== undefined) flushReady?.schedule?.()
|
|
341
|
+
})
|
|
286
342
|
},
|
|
287
343
|
{ global: true },
|
|
288
344
|
)
|
|
@@ -297,6 +353,7 @@ export function apply(ctx) {
|
|
|
297
353
|
const data = await readProviders(scoped, prefs, providerCache)
|
|
298
354
|
const hadProviders = providerCacheMeta.hadProviders === true || data.length > 0
|
|
299
355
|
providerCacheMeta = {
|
|
356
|
+
...providerCacheMeta,
|
|
300
357
|
at: Date.now(),
|
|
301
358
|
hadProviders,
|
|
302
359
|
degraded: data.length === 0 && hadProviders,
|
|
@@ -310,7 +367,17 @@ export function apply(ctx) {
|
|
|
310
367
|
}
|
|
311
368
|
logAdapterEvents(logger, data)
|
|
312
369
|
logAdapterFailures(logger, data.failures)
|
|
313
|
-
|
|
370
|
+
// 只在探测清单变化时记一次:启动首轮必打,之后配 Key / 断网导致清单变动才再打,避免每轮刷屏
|
|
371
|
+
const signature = missSignature(data)
|
|
372
|
+
if (signature !== providerCacheMeta.missSignature) {
|
|
373
|
+
providerCacheMeta = { ...providerCacheMeta, missSignature: signature }
|
|
374
|
+
logger.info('provider', 'cache.state', {
|
|
375
|
+
entries: providerCache.size,
|
|
376
|
+
providers: data.length,
|
|
377
|
+
configured: data.map((item) => item.id),
|
|
378
|
+
misses: data.misses ?? [],
|
|
379
|
+
})
|
|
380
|
+
}
|
|
314
381
|
if (stampProviderKinds(state, data)) {
|
|
315
382
|
logger.info('provider', 'kind.stamp', { ids: Object.keys(state.providerKinds) })
|
|
316
383
|
flusher.schedule()
|
|
@@ -341,13 +408,25 @@ export function apply(ctx) {
|
|
|
341
408
|
try {
|
|
342
409
|
await ready
|
|
343
410
|
if (url.pathname === `${ROUTE_PREFIX}/summary` && req.method === 'GET') {
|
|
344
|
-
|
|
411
|
+
const startedAt = Date.now()
|
|
412
|
+
let probeMs = 0
|
|
413
|
+
if (Date.now() - providerCacheMeta.at > 5000) {
|
|
414
|
+
const probeStartedAt = Date.now()
|
|
415
|
+
await refreshProviderCache()
|
|
416
|
+
probeMs = Date.now() - probeStartedAt
|
|
417
|
+
}
|
|
345
418
|
const summary = buildSummary(state, prefs, Date.now(), cacheData())
|
|
346
419
|
summary.version = CURRENT_VERSION
|
|
347
420
|
summary.refreshMs = prefs.refreshMs
|
|
348
421
|
summary.providersDegraded = providerCacheMeta.degraded === true
|
|
349
422
|
summary.catalog = catalogInfo()
|
|
350
|
-
logger.info('vm', 'build', {
|
|
423
|
+
logger.info('vm', 'build', {
|
|
424
|
+
providers: summary.providers.length,
|
|
425
|
+
api: summary.providers.filter((item) => item.kind === 'api').length,
|
|
426
|
+
subscription: summary.providers.filter((item) => item.kind === 'subscription').length,
|
|
427
|
+
probeMs,
|
|
428
|
+
durationMs: Date.now() - startedAt,
|
|
429
|
+
})
|
|
351
430
|
json(res, 200, { ok: true, data: summary })
|
|
352
431
|
return
|
|
353
432
|
}
|
|
@@ -357,7 +436,13 @@ export function apply(ctx) {
|
|
|
357
436
|
json(res, 400, { ok: false, reason: 'invalid-range' })
|
|
358
437
|
return
|
|
359
438
|
}
|
|
360
|
-
|
|
439
|
+
const startedAt = Date.now()
|
|
440
|
+
let probeMs = 0
|
|
441
|
+
if (Date.now() - providerCacheMeta.at > 5000) {
|
|
442
|
+
const probeStartedAt = Date.now()
|
|
443
|
+
await refreshProviderCache()
|
|
444
|
+
probeMs = Date.now() - probeStartedAt
|
|
445
|
+
}
|
|
361
446
|
const usage = buildUsage(state, prefs, range, Date.now(), cacheData())
|
|
362
447
|
logger.info('vm', 'usage', {
|
|
363
448
|
range,
|
|
@@ -365,6 +450,8 @@ export function apply(ctx) {
|
|
|
365
450
|
billable: usage.models.filter((item) => item.billable === true).length,
|
|
366
451
|
tokens: usage.total.tokens,
|
|
367
452
|
currencies: Object.keys(usage.totals).length,
|
|
453
|
+
probeMs,
|
|
454
|
+
durationMs: Date.now() - startedAt,
|
|
368
455
|
})
|
|
369
456
|
json(res, 200, { ok: true, data: usage })
|
|
370
457
|
return
|
|
@@ -386,6 +473,19 @@ export function apply(ctx) {
|
|
|
386
473
|
json(res, 200, { ok: true, data: { refreshed: subs.map((item) => item.id) } })
|
|
387
474
|
return
|
|
388
475
|
}
|
|
476
|
+
if (url.pathname === `${ROUTE_PREFIX}/pricing/reprice` && req.method === 'POST') {
|
|
477
|
+
// 排障入口(无 UI):只补 priced=false,scope 缺省 = 全部
|
|
478
|
+
const scope = url.searchParams.get('scope')
|
|
479
|
+
if (scope !== null && scope !== 'all' && /^\d{4}-\d{2}$/.test(scope) === false) {
|
|
480
|
+
json(res, 400, { ok: false, reason: 'invalid-scope' })
|
|
481
|
+
return
|
|
482
|
+
}
|
|
483
|
+
const result = repriceUnpriced(state, scope === null || scope === 'all' ? {} : { month: scope }, kindOf)
|
|
484
|
+
await flusher.flush()
|
|
485
|
+
logger.info('pricing', 'reprice', result)
|
|
486
|
+
json(res, 200, { ok: true, data: result })
|
|
487
|
+
return
|
|
488
|
+
}
|
|
389
489
|
if (url.pathname === `${ROUTE_PREFIX}/export` && req.method === 'GET') {
|
|
390
490
|
const data = buildExport(state, prefs, Date.now(), cacheData())
|
|
391
491
|
logger.info('data', 'export', { month: data.month, days: Object.keys(data.days).length, models: data.usage.all.models.length })
|
|
@@ -486,7 +586,13 @@ export function apply(ctx) {
|
|
|
486
586
|
prefs = normalizePrefs(body, prefs)
|
|
487
587
|
await saveJson(dir, 'prefs.json', prefs)
|
|
488
588
|
clearProviderCache()
|
|
489
|
-
|
|
589
|
+
applyPricingConfig()
|
|
590
|
+
logger.info('boot', 'prefs.saved', {
|
|
591
|
+
budgets: Object.keys(prefs.budgets).length,
|
|
592
|
+
modes: Object.keys(prefs.billingModes).length,
|
|
593
|
+
overrides: Object.keys(prefs.priceOverrides).length,
|
|
594
|
+
currencies: Object.keys(prefs.providerCurrency).length,
|
|
595
|
+
})
|
|
490
596
|
json(res, 200, { ok: true, data: prefs })
|
|
491
597
|
return
|
|
492
598
|
}
|
package/locale/en.json
CHANGED
|
@@ -106,5 +106,17 @@
|
|
|
106
106
|
"{name} · {action} Token 看板": "{name} · {action} Token dashboard",
|
|
107
107
|
"{name} 月度预算": "{name} monthly budget",
|
|
108
108
|
"{name},按量 API,{budget},今日 {today}{balance}": "{name}, pay-as-you-go, {budget}, today {today}{balance}",
|
|
109
|
-
"{name},订阅,账户套餐,{value}": "{name}, subscription, account plan, {value}"
|
|
109
|
+
"{name},订阅,账户套餐,{value}": "{name}, subscription, account plan, {value}",
|
|
110
|
+
"按社区表 CNY": "Community table (CNY)",
|
|
111
|
+
"价格取社区价目表(人民币),与渠道账单可能有差异": "Priced from the community table (CNY); may differ from your provider bill",
|
|
112
|
+
"无匹配价目": "No matching price",
|
|
113
|
+
"候选模型不唯一": "Ambiguous model match",
|
|
114
|
+
"模型名无效": "Invalid model name",
|
|
115
|
+
"订阅不计价": "Subscription, not billed",
|
|
116
|
+
"套餐已用": "Plan used",
|
|
117
|
+
"购买余额": "Purchased credits",
|
|
118
|
+
"周期至 {time}": "Cycle ends {time}",
|
|
119
|
+
"限流中": "Rate limited",
|
|
120
|
+
"渠道用量 {value}": "Channel usage {value}",
|
|
121
|
+
"价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "Price table is CNY while this provider bills in USD; add a USD priceOverrides entry"
|
|
110
122
|
}
|
package/locale/zh.json
CHANGED
|
@@ -106,5 +106,17 @@
|
|
|
106
106
|
"{name} · {action} Token 看板": "{name} · {action} Token 看板",
|
|
107
107
|
"{name} 月度预算": "{name} 月度预算",
|
|
108
108
|
"{name},按量 API,{budget},今日 {today}{balance}": "{name},按量 API,{budget},今日 {today}{balance}",
|
|
109
|
-
"{name},订阅,账户套餐,{value}": "{name},订阅,账户套餐,{value}"
|
|
109
|
+
"{name},订阅,账户套餐,{value}": "{name},订阅,账户套餐,{value}",
|
|
110
|
+
"按社区表 CNY": "按社区表 CNY",
|
|
111
|
+
"价格取社区价目表(人民币),与渠道账单可能有差异": "价格取社区价目表(人民币),与渠道账单可能有差异",
|
|
112
|
+
"无匹配价目": "无匹配价目",
|
|
113
|
+
"候选模型不唯一": "候选模型不唯一",
|
|
114
|
+
"模型名无效": "模型名无效",
|
|
115
|
+
"订阅不计价": "订阅不计价",
|
|
116
|
+
"套餐已用": "套餐已用",
|
|
117
|
+
"购买余额": "购买余额",
|
|
118
|
+
"周期至 {time}": "周期至 {time}",
|
|
119
|
+
"限流中": "限流中",
|
|
120
|
+
"渠道用量 {value}": "渠道用量 {value}",
|
|
121
|
+
"价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价"
|
|
110
122
|
}
|
package/package.json
CHANGED
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 {
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
-
|
|
289
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
// 单个会话失败不影响其余会话
|