dsh-token-dash 1.0.7 → 1.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/core.js CHANGED
@@ -61,7 +61,15 @@ export function costOf(record) {
61
61
  }
62
62
 
63
63
  export function emptyState() {
64
- return { version: 1, costVersion: 3, days: {}, watermarks: {}, headers: {}, currentProvider: null }
64
+ return {
65
+ version: 1,
66
+ costVersion: 3,
67
+ days: {},
68
+ watermarks: {},
69
+ headers: {},
70
+ currentProvider: null,
71
+ providerKinds: {},
72
+ }
65
73
  }
66
74
 
67
75
  function dayStartTs(dayKey) {
@@ -163,22 +171,25 @@ export function addRecord(state, record) {
163
171
  state.currentProvider = provider
164
172
  }
165
173
 
174
+ /** 未填写时的默认预算,按 provider 币种;只在 VM 内生效,不写盘。 */
175
+ export const DEFAULT_BUDGET = 100
176
+
166
177
  function budgetFor(prefs, providerId, currency) {
167
178
  const map = prefs?.budgets?.[providerId]
179
+ const explicitZero = map?.amount === 0
168
180
  let amount = num(map?.amount)
169
181
  let state = 'unset'
170
- if (map?.amount === 0) state = 'unset'
171
- if (amount <= 0 && providerId === 'deepseek-official' && num(prefs?.budget?.amount) > 0) {
172
- amount = num(prefs.budget.amount)
173
- }
174
- if (map?.amount === 0) amount = 0
182
+ // 未填写(新装、新增 provider、老用户无显式配置)统一按 100;显式 0 才是"未设置"
183
+ if (amount <= 0 && !explicitZero) amount = DEFAULT_BUDGET
184
+ if (explicitZero) amount = 0
175
185
  return {
176
186
  amount,
177
187
  used: 0,
178
188
  remaining: 0,
179
189
  percent: 0,
180
190
  state,
181
- currency: map?.currency === 'USD' ? 'USD' : (currency ?? 'CNY'),
191
+ // 预算币种只跟 provider 当前币种,落盘的 budgets[id].currency 不参与计算
192
+ currency: currency === 'USD' ? 'USD' : 'CNY',
182
193
  }
183
194
  }
184
195
 
@@ -201,6 +212,193 @@ function normalizeProviderInfo(input) {
201
212
  return Object.entries(input).map(([id, value]) => ({ id, ...(value ?? {}) }))
202
213
  }
203
214
 
215
+ const BILLING_MODES = new Set(['api', 'subscription'])
216
+
217
+ function emptyTotals() {
218
+ return { cost: 0, requests: 0, input: 0, cacheRead: 0, cacheWrite: 0, output: 0, hitRate: null }
219
+ }
220
+
221
+ /** 行内与 0 桶共用:快照币种优先,缺失回退 registry,不写死 CNY。 */
222
+ function usageCurrency(providerId, meta) {
223
+ if (meta?.currency === 'USD') return 'USD'
224
+ if (meta?.currency === 'CNY') return 'CNY'
225
+ return providerCurrency(providerId)
226
+ }
227
+
228
+ /** prefs 显式覆盖 > 快照确定的 mode > 历史固化值 > 快照 kind > api。 */
229
+ export function resolveProviderKind(state, prefs, providerId, meta) {
230
+ const id = normalizeProvider(providerId)
231
+ const explicit = prefs?.billingModes?.[id]
232
+ if (BILLING_MODES.has(explicit)) return explicit
233
+ if (BILLING_MODES.has(meta?.mode)) return meta.mode
234
+ const stamped = state?.providerKinds?.[id]
235
+ if (BILLING_MODES.has(stamped)) return stamped
236
+ return meta?.kind === 'subscription' ? 'subscription' : 'api'
237
+ }
238
+
239
+ /** 只固化"探测确定"的形态;unknown 不覆盖历史,返回是否有变化。 */
240
+ export function stampProviderKinds(state, snapshots) {
241
+ state.providerKinds ??= {}
242
+ let changed = false
243
+ for (const item of snapshots ?? []) {
244
+ const id = normalizeProvider(item?.id ?? item?.provider)
245
+ if (id === 'unknown' || !BILLING_MODES.has(item?.mode)) continue
246
+ if (state.providerKinds[id] === item.mode) continue
247
+ state.providerKinds[id] = item.mode
248
+ changed = true
249
+ }
250
+ return changed
251
+ }
252
+
253
+ /**
254
+ * Range-only aggregation for P2. Unlike buildSummary this never adds
255
+ * "configured but unused" default rows, and it does not touch month budgets.
256
+ */
257
+ export function buildUsage(state, prefs, range, now, providerInfoInput) {
258
+ const allowed = new Set(['today', '7d', '30d', 'all'])
259
+ const selected = allowed.has(range) ? range : 'today'
260
+ const todayKey = localDayKey(now)
261
+ const dayKeys = Object.keys(state.days ?? {}).filter((key) => /^\d{4}-\d{2}-\d{2}$/.test(key)).sort()
262
+ const startKey = selected === 'all'
263
+ ? (dayKeys[0] ?? todayKey)
264
+ : localDayKey(now - (selected === '30d' ? 29 : selected === '7d' ? 6 : 0) * 86400000)
265
+ const hidden = new Set(
266
+ Object.entries(prefs?.billingModes ?? {})
267
+ .filter(([, mode]) => mode === 'hide')
268
+ .map(([id]) => normalizeProvider(id)),
269
+ )
270
+ const info = new Map()
271
+ for (const item of normalizeProviderInfo(providerInfoInput)) {
272
+ const id = normalizeProvider(item.id ?? item.provider)
273
+ if (id === 'unknown') continue
274
+ info.set(id, item)
275
+ }
276
+ const models = new Map()
277
+ const totals = {}
278
+ const add = (providerId, modelId, row) => {
279
+ if (hidden.has(providerId)) return
280
+ const meta = info.get(providerId)
281
+ const kind = resolveProviderKind(state, prefs, providerId, meta)
282
+ const billable = kind === 'api'
283
+ const currency = usageCurrency(providerId, meta)
284
+ const key = `${providerId}:${modelId}`
285
+ const entry = models.get(key) ?? {
286
+ providerId,
287
+ providerName: meta?.name ?? providerLabel(providerId),
288
+ modelId,
289
+ displayName: modelLabel(modelId),
290
+ kind,
291
+ currency,
292
+ billable,
293
+ requests: 0,
294
+ input: 0,
295
+ cacheRead: 0,
296
+ cacheWrite: 0,
297
+ output: 0,
298
+ cost: 0,
299
+ priced: true,
300
+ }
301
+ entry.requests += num(row.requests)
302
+ entry.input += num(row.input)
303
+ entry.cacheRead += num(row.cacheRead)
304
+ entry.cacheWrite += num(row.cacheWrite)
305
+ entry.output += num(row.output)
306
+ entry.billable = billable
307
+ // 订阅模型按目录价算出的 cost 不是真实支出,VM 内归零,保证费用框与 Tokens 框同一集合
308
+ entry.cost += billable ? num(row.cost) : 0
309
+ if (row.priced === false) entry.priced = false
310
+ entry.kind = kind
311
+ entry.currency = currency
312
+ models.set(key, entry)
313
+ }
314
+
315
+ for (const dayKey of dayKeys) {
316
+ if (dayKey < startKey || dayKey > todayKey) continue
317
+ const bucket = state.days[dayKey]
318
+ const providers = bucket.providers ?? { unknown: { models: bucket.models ?? {} } }
319
+ for (const [rawProvider, providerBucket] of Object.entries(providers)) {
320
+ const providerId = normalizeProvider(rawProvider)
321
+ if (providerId === 'unknown') {
322
+ for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
323
+ const owner = providerFromModel(rawModel)
324
+ if (owner !== null) add(owner, normalizeModel(rawModel), row)
325
+ }
326
+ continue
327
+ }
328
+ for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
329
+ add(providerId, normalizeModel(rawModel), row)
330
+ }
331
+ }
332
+ }
333
+
334
+ const rows = [...models.values()].map((entry) => {
335
+ const total = entry.input + entry.cacheRead + entry.cacheWrite + entry.output
336
+ const denominator = entry.input + entry.cacheRead + entry.cacheWrite
337
+ return {
338
+ ...entry,
339
+ tokens: {
340
+ input: entry.input,
341
+ cacheRead: entry.cacheRead,
342
+ cacheWrite: entry.cacheWrite,
343
+ output: entry.output,
344
+ cache: entry.cacheRead + entry.cacheWrite,
345
+ total,
346
+ },
347
+ hitRate: denominator > 0 ? entry.cacheRead / denominator : null,
348
+ cost: round2(entry.cost),
349
+ approximate: entry.billable && priceFor(entry.providerId, entry.modelId, now)?.approximate === true,
350
+ }
351
+ })
352
+ rows.sort((a, b) => b.cost - a.cost)
353
+
354
+ // 已检测 provider 先占位 0 桶:范围无消耗(或只有订阅)时两格卡仍要显示 ¥0.00 而不是空白
355
+ for (const [providerId, meta] of info) {
356
+ if (hidden.has(providerId)) continue
357
+ totals[usageCurrency(providerId, meta)] ??= emptyTotals()
358
+ }
359
+ if (Object.keys(totals).length === 0) totals.CNY = emptyTotals()
360
+ for (const row of rows) {
361
+ if (row.billable !== true) continue
362
+ const bucket = totals[row.currency] ?? emptyTotals()
363
+ bucket.cost += row.cost
364
+ bucket.requests += row.requests
365
+ bucket.input += row.input
366
+ bucket.cacheRead += row.cacheRead
367
+ bucket.cacheWrite += row.cacheWrite
368
+ bucket.output += row.output
369
+ totals[row.currency] = bucket
370
+ }
371
+ for (const bucket of Object.values(totals)) {
372
+ bucket.cost = round2(bucket.cost)
373
+ const denominator = bucket.input + bucket.cacheRead + bucket.cacheWrite
374
+ bucket.hitRate = denominator > 0 ? bucket.cacheRead / denominator : null
375
+ }
376
+
377
+ const total = rows.reduce((sum, row) => ({
378
+ tokens: sum.tokens + row.tokens.total,
379
+ input: sum.input + row.input,
380
+ cacheRead: sum.cacheRead + row.cacheRead,
381
+ cacheWrite: sum.cacheWrite + row.cacheWrite,
382
+ cache: sum.cache + row.tokens.cache,
383
+ output: sum.output + row.output,
384
+ requests: sum.requests + num(row.requests),
385
+ }), { tokens: 0, input: 0, cacheRead: 0, cacheWrite: 0, cache: 0, output: 0, requests: 0 })
386
+ total.hitRate = total.input + total.cacheRead + total.cacheWrite > 0
387
+ ? total.cacheRead / (total.input + total.cacheRead + total.cacheWrite)
388
+ : null
389
+
390
+ return {
391
+ range: selected,
392
+ startAt: dayStartTs(startKey) ?? now,
393
+ endAt: now,
394
+ startKey,
395
+ endKey: todayKey,
396
+ totals,
397
+ total,
398
+ models: rows,
399
+ }
400
+ }
401
+
204
402
  export function buildSummary(state, prefs, now, providerInfoInput) {
205
403
  const month = localMonthKey(now)
206
404
  const todayKey = localDayKey(now)
@@ -215,7 +413,8 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
215
413
  )
216
414
 
217
415
  for (const item of providerInfo) {
218
- const { plans: legacyPlans, ...info } = item
416
+ // mode 是快照内部字段,剥离后不进入 VM
417
+ const { plans: legacyPlans, mode: _mode, ...info } = item
219
418
  const id = normalizeProvider(info.id ?? info.provider)
220
419
  if (id === 'unknown' || hidden.has(id)) continue
221
420
  const base = providerMap.get(id) ?? providerEmpty(id)
@@ -224,9 +423,7 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
224
423
  ...info,
225
424
  id,
226
425
  name: info.name ?? providerLabel(id),
227
- kind: info.kind === 'subscription' || (info.kind === undefined && (info.windows ?? legacyPlans ?? []).length > 0)
228
- ? 'subscription'
229
- : 'api',
426
+ kind: resolveProviderKind(state, prefs, id, item),
230
427
  canSubscribe: canBeSubscription(id),
231
428
  currency: info.currency === 'USD' ? 'USD' : (info.currency === 'CNY' ? 'CNY' : providerCurrency(id)),
232
429
  usage: { ...base.usage, ...(info.usage ?? {}) },
@@ -430,7 +627,6 @@ export function buildSummary(state, prefs, now, providerInfoInput) {
430
627
  breakdown: { models },
431
628
  pricingLinks: pricingLinks(),
432
629
  showBalance: prefs?.showBalance !== false,
433
- showMonthTokens: prefs?.showMonthTokens !== false,
434
630
  updatedAt: now,
435
631
  stale: false,
436
632
  }
package/src/pricing.js CHANGED
@@ -8,11 +8,14 @@ import { normalizeModel, normalizeProvider, providerCurrency } from './providers
8
8
  const BUNDLED = JSON.parse(readFileSync(new URL('./catalog.json', import.meta.url), 'utf8'))
9
9
  const GITEE = 'https://gitee.com/oyw125/model-price-table/raw/master/model_pricing.json'
10
10
  const GITHUB = 'https://raw.githubusercontent.com/LaoYueHanNi/model-price-table/master/model_pricing.json'
11
+ const GITEE_PAGE = 'https://gitee.com/oyw125/model-price-table'
12
+ const GITHUB_PAGE = 'https://github.com/LaoYueHanNi/model-price-table'
11
13
  const ROUTER = 'https://openrouter.ai/api/v1/models'
12
14
 
13
15
  let catalog = normalizeCatalog(BUNDLED)
14
16
  let catalogUpdatedAt = BUNDLED.updatedAt ?? null
15
17
  let catalogSource = 'bundled'
18
+ let catalogUrl = null
16
19
  let routerPrices = null
17
20
  let communityCache = { at: 0, value: null }
18
21
 
@@ -148,7 +151,7 @@ export function priceFor(provider, model, ts = Date.now()) {
148
151
  }
149
152
 
150
153
  export function catalogInfo() {
151
- return { source: catalogSource, updatedAt: catalogUpdatedAt, models: allEntries().length }
154
+ return { version: catalog.version ?? null, source: catalogSource, updatedAt: catalogUpdatedAt, url: catalogUrl, models: allEntries().length }
152
155
  }
153
156
 
154
157
  export function setCatalogForTests(models) {
@@ -209,6 +212,7 @@ export async function loadCommunityPricing({ force = false } = {}) {
209
212
  if (parsed.models.length === 0) throw new Error('empty-catalog')
210
213
  catalog = parsed
211
214
  catalogSource = url === GITEE ? 'community-gitee' : 'community-github'
215
+ catalogUrl = url === GITEE ? GITEE_PAGE : GITHUB_PAGE
212
216
  catalogUpdatedAt = raw?.updatedAt === undefined ? null : String(raw.updatedAt)
213
217
  communityCache = { at: Date.now(), value: catalogInfo() }
214
218
  return catalogInfo()
package/src/store.js CHANGED
@@ -8,15 +8,15 @@ export const COST_MODEL_VERSION = 3
8
8
 
9
9
  export const DEFAULT_PREFS = {
10
10
  version: 1,
11
- budget: { amount: 3500, currency: 'CNY' },
12
11
  budgets: {},
13
12
  billingModes: {},
14
13
  refreshMs: 60000,
15
14
  showBalance: true,
16
- showMonthTokens: true,
17
- logLevel: 'info',
18
15
  }
19
16
 
17
+ /** 刷新间隔唯一枚举:loadPrefs 归一与 normalizePrefs 校验共用。 */
18
+ export const REFRESH_OPTIONS = [30000, 60000, 300000]
19
+
20
20
  export function resolveHome(ctx) {
21
21
  try {
22
22
  const fn = ctx.get?.('dshHomePath')
@@ -79,6 +79,7 @@ export async function loadState(dir, logger) {
79
79
  state.watermarks ??= {}
80
80
  state.headers ??= {}
81
81
  state.currentProvider ??= null
82
+ state.providerKinds ??= {}
82
83
  // 月度账本是独立文件:daily.json 缺失/被重置时从这里恢复本月历史
83
84
  const months = await loadMonths(dir, logger)
84
85
  let loaded = 0
@@ -223,17 +224,22 @@ function mergeBackup(target, source) {
223
224
  target.costVersion = Math.min(target.costVersion ?? COST_MODEL_VERSION, source.costVersion ?? 1)
224
225
  }
225
226
 
227
+ /** 返回对象即白名单:legacy `budget`、已删字段与未知键都不进入运行时。 */
226
228
  export async function loadPrefs(dir, logger) {
227
229
  const prefs = await readJson(join(dir, 'prefs.json'), DEFAULT_PREFS, (file, backup) => {
228
230
  logger?.warn('boot', 'state.corrupt', { file, backup })
229
231
  })
232
+ const rawRefresh = Number(prefs?.refreshMs)
233
+ const refreshMs = REFRESH_OPTIONS.includes(rawRefresh) ? rawRefresh : DEFAULT_PREFS.refreshMs
234
+ if (prefs?.refreshMs !== undefined && refreshMs !== rawRefresh) {
235
+ logger?.warn('boot', 'prefs.normalize', { field: 'refreshMs', value: prefs.refreshMs, used: refreshMs })
236
+ }
230
237
  return {
231
- ...DEFAULT_PREFS,
232
- ...prefs,
233
- budget: { ...DEFAULT_PREFS.budget, ...(prefs?.budget ?? {}) },
238
+ version: 1,
234
239
  budgets: { ...(prefs?.budgets ?? {}) },
235
240
  billingModes: { ...(prefs?.billingModes ?? {}) },
236
- logLevel: prefs?.logLevel === 'debug' ? 'debug' : 'info',
241
+ refreshMs,
242
+ showBalance: prefs?.showBalance !== false,
237
243
  }
238
244
  }
239
245