@angelyeye/dsh-cost-tracker 1.10.1 → 1.11.1

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/index.js CHANGED
@@ -27,7 +27,11 @@ import {
27
27
  } from './volcengine.js'
28
28
  import { createSyncEngine, setPluginVersion, SOURCE as SYNC_SOURCE, SYNC_VERSION, loadIdentity } from './sync.js'
29
29
  import { Schema } from './schema.js'
30
- import { catalogEntryFor, CATALOG_META, catalogProviders, catalogFingerprint, CATALOG_FX_DEFAULT } from './vendor-catalog.js'
30
+ import { catalogEntryFor, CATALOG_META, catalogProviders, catalogFingerprint, CATALOG_FX_DEFAULT, catalogFastTiers } from './vendor-catalog.js'
31
+ // v1.11.0:GPT Fast 档识别(读 dsh-fast-tier 写在会话日志里的档位选择,只读)
32
+ import { createTierResolver, resolveTier } from './fast-tier.js'
33
+ // v1.11.0:token 数量统一中文单位(万 / 亿),工具输出与看板同一口径
34
+ import { formatTokenCN } from './token-format.js'
31
35
  import { fetchOfficialPrices, buildSyncedEra, diffAgainstEra } from './price-sync.js'
32
36
  import { createCredSeam, migrateLegacySecrets, safeFetch, CRED_REFS, hostnameOf } from './credstore.js'
33
37
  // 账号登录态(DSH 0.2.1-rc.2+)余额投影:纯函数,单独成文件便于单测
@@ -37,7 +41,7 @@ import { readSettingsSection } from './settings.js'
37
41
  import { listSessionLogs, planAndBuildImports, loadManifest, IMPORT_SOURCE } from './import.js'
38
42
 
39
43
  /** 插件版本(写入上报信封,便于云端排查版本差异) */
40
- const PLUGIN_VERSION = '1.10.1'
44
+ const PLUGIN_VERSION = '1.11.1'
41
45
  setPluginVersion(PLUGIN_VERSION)
42
46
 
43
47
  /** 配置面板可写的字段(与 settings 命名空间一致)。
@@ -192,6 +196,9 @@ export function ensureNavIconPatch(opts) {
192
196
  export default {
193
197
  name: 'cost-tracker',
194
198
  inject: ['tools', 'webServer'],
199
+ // v1.11.0:会话与投影服务用于识别 GPT Fast 档;两者都是**可选依赖**,
200
+ // 缺失时档位解析降级为 standard,记账与其它功能不受影响。
201
+ optional: ['sessions', 'sessionProjections'],
195
202
  apply(ctx) {
196
203
  // 侧边栏图标补丁自愈(DSH 升级覆盖外壳后自动重打;失败静默跳过)
197
204
  ensureNavIconPatch({ log: (m) => startupLog('[cost-tracker] nav-icon ' + m) })
@@ -588,19 +595,37 @@ export default {
588
595
  // ---------- recording ----------
589
596
  /** 计价运行时注入项:手动覆盖价 + 目录匹配(随 billingConfig 实时更新) */
590
597
  let priceRuntimeOpts = null
598
+ /** v1.11.0:会话档位解析器(读 dsh-fast-tier 的选择;依赖缺失时恒 standard) */
599
+ let tierResolver = null
600
+ // sessions / sessionProjections 是可选依赖,缺失时解析器恒返回 standard
601
+ // (记账照常,只是不区分 Fast 价),因此这里必须容错。
602
+ try {
603
+ tierResolver = createTierResolver(ctx)
604
+ } catch (e) {
605
+ tierResolver = null
606
+ }
591
607
  function applyPricingRuntime() {
592
608
  setPriceOverrides(billingConfig.priceOverrides || {})
593
609
  priceRuntimeOpts = {
594
- catalog: (np, m) => catalogEntryFor(np, m, { mode: billingConfig.priceMatch, fx: billingConfig.catalogFxRate }),
610
+ catalog: (np, m, extra) => catalogEntryFor(np, m, {
611
+ mode: billingConfig.priceMatch,
612
+ fx: billingConfig.catalogFxRate,
613
+ serviceTier: extra && extra.serviceTier,
614
+ tokens: extra && extra.tokens,
615
+ }),
595
616
  overrides: getPriceOverrides(),
596
617
  planOverrides: billingConfig.planOverrides || {},
597
618
  }
598
619
  }
599
620
 
600
621
  /** 某时刻的计价三件套(实时记账与历史导入共用,保证口径一致) */
601
- function priceForAt(np, model, ts, tokens) {
602
- const price = priceFor(np, model, ts, priceRuntimeOpts || undefined)
622
+ function priceForAt(np, model, ts, tokens, tier) {
623
+ const price = priceFor(np, model, ts, Object.assign({}, priceRuntimeOpts || {}, {
624
+ serviceTier: tier && tier.tier === 'fast' ? 'fast' : 'standard',
625
+ tokens,
626
+ }))
603
627
  const peak = peakEffective(peakConfig, ts) ? isPeak(ts) : false
628
+ const catalog = price.catalog || {}
604
629
  return {
605
630
  cost: computeCost(price.rates, price.tiered, peak, tokens),
606
631
  estimated: price.estimated,
@@ -608,6 +633,13 @@ export default {
608
633
  period: price.tiered ? (peak ? 'peak' : 'off-peak') : 'flat',
609
634
  model: price.model || model,
610
635
  source: price.source || '',
636
+ // v1.11.0:服务档位(GPT Fast)与目录口径,旧记录没有这些字段时按 standard 读
637
+ serviceTier: tier && tier.tier === 'fast' ? 'fast' : 'standard',
638
+ tierSource: (tier && tier.source) || '',
639
+ tierPriceSource: catalog.tierPriceSource || '',
640
+ contextTier: catalog.contextTier || '',
641
+ ultrafast: tier ? tier.ultrafast === true : false,
642
+ tierNote: catalog.tierNote || '',
611
643
  }
612
644
  }
613
645
 
@@ -622,12 +654,15 @@ export default {
622
654
  // 视觉模型(deepseek-v4-flash-vision-exp)的图片 token 已含在接口
623
655
  // prompt_tokens 中(每张≤384 tokens),由 normalizeTokens 归入 input
624
656
  const tokens = normalizeTokens(usage)
625
- const price = priceForAt(np, model, ts, tokens)
657
+ const sessionId = toStr(options && options.sessionId)
658
+ // v1.11.0:GPT Fast 档(请求参数优先,其次该会话在 dsh-fast-tier 里的选择)
659
+ const tier = resolveTier(options, tierResolver, sessionId)
660
+ const price = priceForAt(np, model, ts, tokens, tier)
626
661
  store.add({
627
662
  // 被路由的请求以「实际计费模型规范名」入账(如 V4-Pro → deepseek-flash、
628
663
  // 旧名 deepseek-v4-flash → deepseek-flash),使按模型聚合看到的就是真实计费口径。
629
664
  ts, provider, model: price.model,
630
- sessionId: toStr(options && options.sessionId),
665
+ sessionId,
631
666
  purpose: toStr(options && options.purpose),
632
667
  cost: price.cost,
633
668
  estimated: price.estimated,
@@ -635,6 +670,15 @@ export default {
635
670
  tokens,
636
671
  subscription: price.subscription,
637
672
  source: 'live', // v1.9.0:与历史导入(source:'import')区分,覆盖判定只认 live
673
+ // v1.11.0(可选字段):Fast 档与目录口径;仅 fast 时写入,标准档保持旧记录形状
674
+ ...(tier.tier === 'fast' ? {
675
+ serviceTier: 'fast',
676
+ tierSource: tier.source,
677
+ tierPriceSource: price.tierPriceSource,
678
+ contextTier: price.contextTier,
679
+ ...(tier.ultrafast ? { ultrafast: true } : {}),
680
+ ...(price.tierNote ? { tierNote: price.tierNote } : {}),
681
+ } : {}),
638
682
  })
639
683
  schedulePersist()
640
684
  scheduleSync(4000)
@@ -1186,6 +1230,23 @@ export default {
1186
1230
  }
1187
1231
 
1188
1232
  // ---------- prices ----------
1233
+ /**
1234
+ * v1.11.0:GPT Fast 档价格摘要(USD 原价 + CNY 折算),供工具与设置页展示。
1235
+ * 只放目录里**确实登记了** fast 块的模型,绝不按倍率推算。
1236
+ */
1237
+ function fastTierPriceInfo(fx) {
1238
+ try {
1239
+ const info = catalogFastTiers(fx)
1240
+ return {
1241
+ fxRate: info.fx,
1242
+ checkedAt: info.checkedAt,
1243
+ count: info.models.length,
1244
+ models: info.models,
1245
+ }
1246
+ } catch (e) {
1247
+ return { fxRate: Number(fx) || CATALOG_FX_DEFAULT, checkedAt: '', count: 0, models: [] }
1248
+ }
1249
+ }
1189
1250
  function prices() {
1190
1251
  const now = Date.now()
1191
1252
  const era = eraAt(now)
@@ -1219,6 +1280,8 @@ export default {
1219
1280
  providers: catalogProviders(),
1220
1281
  fxRate: billingConfig.catalogFxRate,
1221
1282
  match: billingConfig.priceMatch,
1283
+ // v1.11.0:GPT Fast 档(service_tier: fast/priority)可用模型与官方价
1284
+ fast: fastTierPriceInfo(billingConfig.catalogFxRate),
1222
1285
  },
1223
1286
  priceSync: {
1224
1287
  url: priceSyncConfig.priceSyncUrl,
@@ -1245,11 +1308,30 @@ export default {
1245
1308
  return out
1246
1309
  }
1247
1310
 
1311
+ /**
1312
+ * 把界面的「天数」换算成查询区间起点(毫秒)。
1313
+ * 本机 buildDashboard 与云端 fetchCloud 必须共用这一份规则,
1314
+ * 否则「本机 + 云端」视图的两半会落在不同区间,卡片数字自相矛盾。
1315
+ *
1316
+ * · days = 1 → 北京时间当日 00:00(「今天」,与「今日费用」卡同口径)
1317
+ * · days > 1 → now - days * 86400000 滚动窗口
1318
+ * · days <= 0 → 0(不限起点,即全部)
1319
+ */
1320
+ function windowCutoff(days, now) {
1321
+ const n = typeof days === 'number' && isFinite(days) ? Math.max(0, Math.floor(days)) : 7
1322
+ if (n <= 0) return 0
1323
+ if (n === 1) {
1324
+ const k = dayKey(now)
1325
+ return Date.UTC(toInt(k.slice(0, 4)), toInt(k.slice(5, 7)) - 1, toInt(k.slice(8, 10))) - 28800000
1326
+ }
1327
+ return now - n * 86400000
1328
+ }
1329
+
1248
1330
  function buildDashboard(args) {
1249
1331
  const days = args && typeof args.days === 'number' && isFinite(args.days) ? Math.max(0, Math.floor(args.days)) : 7
1250
1332
  const now = Date.now()
1251
1333
  const todayKey = dayKey(now)
1252
- const cutoff = days > 0 ? now - days * 86400000 : 0
1334
+ const cutoff = windowCutoff(days, now)
1253
1335
  const filt = []
1254
1336
  for (const r of records) if (r.ts >= cutoff) filt.push(r)
1255
1337
  // 保留窗口外的日汇总(按天+模型),仅取落在查询范围内的天
@@ -1483,14 +1565,19 @@ export default {
1483
1565
  else if (Number.isFinite(a.since) && a.since >= 0) since = a.since
1484
1566
  const apply = a.apply === true
1485
1567
  const byModel = {}
1486
- let scanned = 0, changed = 0, oldCost = 0, newCost = 0, estimatedFlips = 0
1568
+ let scanned = 0, changed = 0, oldCost = 0, newCost = 0, estimatedFlips = 0, markerOnlyFlips = 0
1487
1569
  for (const r of records) {
1488
1570
  if (!(r.ts >= since)) continue
1489
1571
  scanned += 1
1490
1572
  const np = normProvider(r.provider)
1491
1573
  // v1.9.0:重算与实时记账共用 priceForAt —— 同步时代 / 目录 / 覆盖价 /
1492
1574
  // 订阅归类覆盖在补账时同样生效(口径完全一致,重算后不会有双标)。
1493
- const p = priceForAt(np, r.model, r.ts, r.tokens)
1575
+ // v1.11.0:记录上带 serviceTier:'fast' 的按 Fast 档重算;旧记录(无该字段)
1576
+ // 仍按标准档,结果与 1.10.x 完全一致。
1577
+ const tier = r.serviceTier === 'fast'
1578
+ ? { tier: 'fast', source: 'record', ultrafast: r.ultrafast === true }
1579
+ : { tier: 'standard', source: 'record' }
1580
+ const p = priceForAt(np, r.model, r.ts, r.tokens, tier)
1494
1581
  const cost = p.cost
1495
1582
  const model = p.model
1496
1583
  const period = p.period
@@ -1504,6 +1591,10 @@ export default {
1504
1591
  if (!(Math.abs(cost - r.cost) > 1e-9 || model !== r.model || period !== r.period || flip)) continue
1505
1592
  changed += 1
1506
1593
  if (flip) estimatedFlips += 1
1594
+ // v1.11.0:区分「只订正标记」与「金额也变了」。旧文案把两者混为一谈,
1595
+ // 出现过「7010 条仅订正估算标记,金额不变」与实际金额 +182 自相矛盾的输出。
1596
+ const markerOnly = flip && Math.abs(cost - r.cost) <= 1e-9 && model === r.model && period === r.period
1597
+ if (markerOnly) markerOnlyFlips += 1
1507
1598
  const key = r.provider + '|' + r.model + '|' + model
1508
1599
  const m = byModel[key] || (byModel[key] = { provider: r.provider, from: r.model, to: model, calls: 0, oldCost: 0, newCost: 0, flips: 0 })
1509
1600
  m.calls += 1
@@ -1532,6 +1623,7 @@ export default {
1532
1623
  scanned,
1533
1624
  changed,
1534
1625
  estimatedFlips,
1626
+ markerOnlyFlips,
1535
1627
  oldCost: r4(oldCost),
1536
1628
  newCost: r4(newCost),
1537
1629
  delta: r4(newCost - oldCost),
@@ -1539,7 +1631,7 @@ export default {
1539
1631
  note: changed === 0
1540
1632
  ? '没有需要重算的记录'
1541
1633
  : (apply
1542
- ? '已重算并落盘' + (estimatedFlips ? '(其中 ' + estimatedFlips + ' 条仅订正「估算」标记,金额不变)' : '')
1634
+ ? '已重算并落盘' + (markerOnlyFlips ? '(其中 ' + markerOnlyFlips + ' 条仅订正「估算」标记,金额不变)' : '')
1543
1635
  : '试算结果,未落盘(传 apply: true 生效)'),
1544
1636
  }
1545
1637
  }
@@ -1734,8 +1826,10 @@ export default {
1734
1826
  importLastResult = { at: Date.now(), imported: 0, files: 0, scanned: 0, note: '未找到会话日志目录(' + root + ')' }
1735
1827
  return { ok: true, imported: 0, files: 0, scanned: 0, note: '未找到会话日志' }
1736
1828
  }
1737
- const priceFn = (np, model, ts, tokens) => {
1738
- const p = priceForAt(np, model, ts, tokens)
1829
+ const priceFn = (np, model, ts, tokens, sessionId) => {
1830
+ // v1.11.0:历史导入按该会话在日志里的档位选择计 Fast 价(无选择则标准档)
1831
+ const tier = resolveTier(null, tierResolver, sessionId)
1832
+ const p = priceForAt(np, model, ts, tokens, tier)
1739
1833
  return { cost: p.cost, estimated: p.estimated, subscription: p.subscription, period: p.period, model: p.model }
1740
1834
  }
1741
1835
  const results = await planAndBuildImports(records, rollups, logs, importManifest, { priceFn, normProvider })
@@ -1893,6 +1987,29 @@ export default {
1893
1987
  const qs = new URLSearchParams()
1894
1988
  qs.set('range', query.range || '7d')
1895
1989
  if (query.days) qs.set('days', String(query.days))
1990
+ // 自定义区间:云端 resolveRange() 优先识别 from=… & to=…(可写 from),
1991
+ // 一旦命中就返回 { range:'custom', fromMs, toMs },不受 range 枚举限制。
1992
+ //
1993
+ // 为什么必须走 from/to 而不是 range 枚举:云端只认 today / 7d / 30d / 90d /
1994
+ // month / year / all,**其余值静默降级成 all**(实测 1d、14d 都变全时段)。
1995
+ // 界面上「近 14 天」若只传 range=14d,会拿到全时段累计且没有任何报错 —— 这种
1996
+ // 静默错值比报错更难发现,所以凡是有精确区间的地方一律传 from/to。
1997
+ //
1998
+ // 语义必须与本地 buildDashboard 的 cutoff 保持一致(否则本机 + 云端两半对不齐):
1999
+ // · days=1 → 北京时间当日 00:00 起(「今天」,与「今日费用」卡同口径)
2000
+ // · days>1 → now - days*86400000 滚动窗口
2001
+ // · days<=0 → 不传,交给 range(调用方会传 all)
2002
+ // 调用方显式给了 from 就用 from;否则若给了 days>0,用 windowCutoff 自动推导,
2003
+ // 这样 client 只需继续传 days,不必关心云端的 range 枚举。
2004
+ let fromMs = typeof query.from === 'number' && isFinite(query.from) ? query.from : null
2005
+ if (fromMs === null && typeof query.days === 'number' && isFinite(query.days) && query.days > 0) {
2006
+ fromMs = windowCutoff(query.days, Date.now())
2007
+ }
2008
+ if (fromMs !== null) {
2009
+ qs.set('from', String(Math.max(0, Math.floor(fromMs))))
2010
+ const toMs = typeof query.to === 'number' && isFinite(query.to) ? query.to : Date.now()
2011
+ qs.set('to', String(Math.floor(toMs)))
2012
+ }
1896
2013
  if (query.groupBy) qs.set('groupBy', query.groupBy)
1897
2014
  if (query.bucket) qs.set('bucket', query.bucket)
1898
2015
  if (Array.isArray(query.sources) && query.sources.length) qs.set('sources', query.sources.join(','))
@@ -2078,7 +2195,16 @@ export default {
2078
2195
  if (rest.cloudEnabled === true) scheduleSync(500)
2079
2196
  return Object.assign({ ok: true }, syncEngine.status())
2080
2197
  },
2081
- cloud: (args) => fetchCloud(Object.assign({ route: 'overview', range: '7d' }, args || {})),
2198
+ // range 默认值只在调用方两者都没给时才兜底成 7d:
2199
+ // 调用方给了 days>0 → fetchCloud 会用 windowCutoff 推导 from/to(精确区间,优先);
2200
+ // 调用方给了 days=0 → 这里传 all。
2201
+ // 此前无条件写死 range:'7d',导致客户端只传 days 时云端永远按近 7 天算,
2202
+ // 界面切「近 30 天 / 全部」云端那一半却纹丝不动。
2203
+ cloud: (args) => {
2204
+ const a = args || {}
2205
+ const range = a.range || (a.days === 0 ? 'all' : '7d')
2206
+ return fetchCloud(Object.assign({ route: 'overview' }, a, { range }))
2207
+ },
2082
2208
  }
2083
2209
 
2084
2210
  async function handleRoute(req, res) {
@@ -2147,7 +2273,30 @@ export default {
2147
2273
  }
2148
2274
  lines.push('视觉模型 deepseek-v4-flash-vision-exp:图片按官方规则换算 token(每张上限 384),以接口用量计费(已含在 inputTokens 内)。')
2149
2275
  lines.push('kimi-coding(订阅等效,估算):输入 6.5 / 缓存命中(含缓存写入)1.1 / 输出 27.0')
2150
- lines.push('缓存写入(cache write)按缓存命中价计费,与官方规则一致。其他 provider 兜底为估算平价(openai 10/30/5,anthropic 15/75/1.5,gemini 2.5/10/0.625,未知 2/8/0.5);ollama/local 为 0。')
2276
+ lines.push('缓存写入(cache write):DeepSeek 与缓存命中同价;目录中带独立缓存写价的模型(OpenAI / Anthropic)按条目 cacheWriteInput 计费。其他 provider 兜底为估算平价(openai 10/30/5,anthropic 15/75/1.5,gemini 2.5/10/0.625,未知 2/8/0.5);ollama/local 为 0。')
2277
+ // ---- v1.11.0:多厂商目录概览 + GPT Fast 档价格 ----
2278
+ if (v.catalog) {
2279
+ const c = v.catalog
2280
+ const meta = c.meta || {}
2281
+ const total = (c.providers || []).reduce((n, p) => n + (Number(p.count) || 0), 0)
2282
+ lines.push('', '【多厂商价格目录】' + (meta.generatedAt || '') + ' · ' + (c.providers || []).length + ' 家 / ' + total + ' 条 · USD→CNY 汇率 ' + c.fxRate + '(匹配:' + c.match + ')')
2283
+ const fast = c.fast || { models: [] }
2284
+ if (fast.models && fast.models.length) {
2285
+ lines.push('', '【OpenAI Fast 档(service_tier: fast / priority)】核实日期 ' + (fast.checkedAt || '') + ' · 汇率 ' + fast.fxRate + ' · 共 ' + fast.models.length + ' 个模型可区分档位')
2286
+ for (const m of fast.models) {
2287
+ const std = m.standardCny || {}
2288
+ const f = m.fastCny || {}
2289
+ lines.push(' ' + m.model + ':标准 ¥' + std.input + ' / ¥' + std.cachedInput + ' / ¥' + std.output
2290
+ + ' → Fast ¥' + f.input + ' / ¥' + f.cachedInput + ' / ¥' + f.output
2291
+ + '(USD ' + m.standard.input + '/' + m.standard.cachedInput + '/' + m.standard.output
2292
+ + ' → ' + m.fast.input + '/' + m.fast.cachedInput + '/' + m.fast.output + ')'
2293
+ + (m.longContext ? ';>272K 另行计档' : '') + ';来源 ' + (m.confidence || 'official'))
2294
+ }
2295
+ lines.push('Fast 档判定:请求参数 > 会话在 dsh-fast-tier 里的选择;识别不到档位时按标准价计(不会凭空 ×2)。ultrafast 按 Fast 价计,实际倍率更高,属已知偏低。')
2296
+ } else {
2297
+ lines.push('【OpenAI Fast 档】目录中暂无登记 fast 块价的模型。')
2298
+ }
2299
+ }
2151
2300
  return [{ type: 'text', text: lines.join('\n') }]
2152
2301
  },
2153
2302
  },
@@ -2188,7 +2337,7 @@ export default {
2188
2337
  : ('自 ' + new Date(v.since + 28800000).toISOString().replace('T', ' ').slice(0, 16).replace(/-/g, '/') + ' 北京起 · era=' + v.era)
2189
2338
  const lines = [
2190
2339
  '费用重算(' + scope + ')',
2191
- '扫描 ' + v.scanned + ' 条,需修正 ' + v.changed + ' 条' + (v.estimatedFlips ? '(其中 ' + v.estimatedFlips + ' 条仅订正「估算」标记,金额不变)' : ''),
2340
+ '扫描 ' + v.scanned + ' 条,需修正 ' + v.changed + ' 条' + (v.markerOnlyFlips ? '(其中 ' + v.markerOnlyFlips + ' 条仅订正「估算」标记,金额不变)' : ''),
2192
2341
  '合计:¥' + v.oldCost + ' → ¥' + v.newCost + '(' + (v.delta >= 0 ? '+' : '') + v.delta + ')',
2193
2342
  ]
2194
2343
  for (const m of (v.byModel || []).slice(0, 8)) {
@@ -2262,11 +2411,11 @@ export default {
2262
2411
  const lines = ['花费统计(' + (v.days === 0 ? '全部' : '近 ' + v.days + ' 天') + ')']
2263
2412
  if (v.local) {
2264
2413
  lines.push('【本机】按量消费:¥' + v.local.realTotal + '(高峰 ¥' + v.local.peakCost + ' · 闲时 ¥' + v.local.offCost
2265
- + (v.local.flatCost > 0 ? ' · 不分峰谷 ¥' + v.local.flatCost : '') + ')· 请求 ' + v.local.realCalls + ' 次 · Tokens ' + v.local.realTokens)
2266
- lines.push('【本机】订阅套餐:请求 ' + v.local.subCalls + ' 次 · Tokens ' + v.local.subTokens + ' · 等效 ¥' + v.local.subEquivalent + '(订阅已覆盖,仅供参考)')
2414
+ + (v.local.flatCost > 0 ? ' · 不分峰谷 ¥' + v.local.flatCost : '') + ')· 请求 ' + v.local.realCalls + ' 次 · Token ' + formatTokenCN(v.local.realTokens))
2415
+ lines.push('【本机】订阅套餐:请求 ' + v.local.subCalls + ' 次 · Token ' + formatTokenCN(v.local.subTokens) + ' · 等效 ¥' + v.local.subEquivalent + '(订阅已覆盖,仅供参考)')
2267
2416
  }
2268
2417
  if (v.cloud && v.cloud.ok) {
2269
- lines.push('【云端汇总】按量消费:¥' + v.cloud.realCost + ' · 请求 ' + v.cloud.realCalls + ' 次 · Tokens ' + v.cloud.realTokens
2418
+ lines.push('【云端汇总】按量消费:¥' + v.cloud.realCost + ' · 请求 ' + v.cloud.realCalls + ' 次 · Token ' + formatTokenCN(v.cloud.realTokens)
2270
2419
  + '(' + (v.cloud.devices || []).map((d) => d.name).join(' / ') + ')')
2271
2420
  if (v.cloud.sources && v.cloud.sources.length) {
2272
2421
  lines.push('【云端汇总】按 Agent:' + v.cloud.sources.map((s) => s.source + ' ¥' + s.cost).join(' · '))
@@ -2294,6 +2443,8 @@ export default {
2294
2443
  }
2295
2444
  if (scope === 'cloud' || scope === 'both') {
2296
2445
  const c = await fetchCloud({ route: 'overview', range: days === 0 ? 'all' : '7d', days })
2446
+ // 注:days>0 时 fetchCloud 会用 windowCutoff 推导 from/to,range 只作兜底展示;
2447
+ // days===0 时走 range=all。两条路都与本地 buildDashboard 的窗口语义一致。
2297
2448
  // 云端响应有两种形状,必须都认:
2298
2449
  // · /api/v1/overview → 金额摊在 c.summary.{realCost,subEquivalent,...}
2299
2450
  // · /api/v1/plugin-view → 没有 summary,字段直接摊在顶层(宿主在云端支持
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angelyeye/dsh-cost-tracker",
3
- "version": "1.10.1",
3
+ "version": "1.11.1",
4
4
  "description": "DeepSeek Harness (DSH) plugin: LLM token usage & cost tracking with a settings dashboard, agent tools, HTTP API, persistent storage, multi-device cloud sync, session-log history import, official price sync and a multi-vendor price catalog.",
5
5
  "type": "module",
6
6
  "main": "index.js",
@@ -23,7 +23,9 @@
23
23
  "docs/provider-pricing.json",
24
24
  "docs/THIRD-PARTY-NOTICES.md",
25
25
  "cordis.patch.yml",
26
- "CHANGELOG.md"
26
+ "CHANGELOG.md",
27
+ "token-format.js",
28
+ "fast-tier.js"
27
29
  ],
28
30
  "exports": {
29
31
  ".": "./index.js",
@@ -35,7 +37,7 @@
35
37
  "./package.json": "./package.json"
36
38
  },
37
39
  "scripts": {
38
- "test": "node test/storage.test.js && node test/pricing.test.js && node test/peak-holidays.test.js && node test/volcengine-plan.test.js && node test/volcengine-host.test.js && node test/config.test.js && node test/recompute.test.js && node test/credstore.test.js && node test/vendor-catalog.test.js && node test/price-sync.test.js && node test/import.test.js && node test/balance-account.test.js && node test/session-log-v4.test.js && node test/settings-compat.test.js && node test/client-registration.test.js && node test/ui-display.test.js && node test/client-render.test.js && node test/cloud-read.test.js && node --no-warnings test/cloud-view-e2e.test.js && node test/sync.test.js && node test/view.test.js && node test/release-notes.test.js"
40
+ "test": "node test/storage.test.js && node test/pricing.test.js && node test/peak-holidays.test.js && node test/volcengine-plan.test.js && node test/volcengine-host.test.js && node test/config.test.js && node test/recompute.test.js && node test/credstore.test.js && node test/vendor-catalog.test.js && node test/price-sync.test.js && node test/import.test.js && node test/balance-account.test.js && node test/session-log-v4.test.js && node test/settings-compat.test.js && node test/client-registration.test.js && node test/ui-display.test.js && node test/client-render.test.js && node test/cloud-read.test.js && node --no-warnings test/cloud-view-e2e.test.js && node test/sync.test.js && node test/view.test.js && node test/time-range.test.js && node test/release-notes.test.js"
39
41
  },
40
42
  "keywords": [
41
43
  "dsh-plugin",
package/pricing.js CHANGED
@@ -126,6 +126,31 @@ function eraIndex(era) {
126
126
  * 某模型在指定时代下命中的**计费模型规范名**:先按别名表归一,再查本时代单价表,
127
127
  * 最后查路由表(路由目标须在本时代单价表内);均未命中返回 null。
128
128
  */
129
+ /** 尾部的版本/日期后缀:`-1017`(MMDD)、`-261017`(YYMMDD)、`-2026-09`(YYYY-MM) */
130
+ const TRAILING_VERSION_RE = /-(?:\d{4}-\d{2}|\d{4}(?:\d{2})?)$/
131
+
132
+ /**
133
+ * 去掉模型名尾部的版本后缀后再试一次。
134
+ *
135
+ * 真实流量里的模型 id 常带发布批次(`deepseek-v4.1-flash-1017`、
136
+ * `deepseek-v4-1-flash-261017`),而价表只有基础名。归一化后仍带数字尾巴,
137
+ * 就会错过精确价并掉到通用兜底(缓存读 0.5 vs 官方 0.04,差 12.5 倍)。
138
+ *
139
+ * 只对 deepseek 系生效:这些都是同一个模型的不同批次,价格一致;
140
+ * 其它厂商的尾号可能代表不同档位(如 gpt-5.4-mini),不能一概剥离。
141
+ *
142
+ * @param {string} model
143
+ * @returns {string[]} 依次尝试的候选名(不含原名)
144
+ */
145
+ function suffixCandidates(model) {
146
+ const raw = String(model == null ? '' : model).toLowerCase()
147
+ if (!raw.startsWith('deepseek')) return []
148
+ const out = []
149
+ const m = raw.match(TRAILING_VERSION_RE)
150
+ if (m) out.push(raw.slice(0, m.index))
151
+ return out
152
+ }
153
+
129
154
  export function resolveModelInEra(era, model) {
130
155
  if (!era) return null
131
156
  let n = normalizeModelName(model)
@@ -138,6 +163,18 @@ export function resolveModelInEra(era, model) {
138
163
  const hit = idx.models.get(normalizeModelName(target))
139
164
  if (hit) return hit
140
165
  }
166
+ // v1.11.0:带发布批次号的 deepseek 模型名,去掉尾部版本号再试(见 suffixCandidates)
167
+ for (const cand of suffixCandidates(model)) {
168
+ let c = normalizeModelName(cand)
169
+ if (!c) continue
170
+ if (MODEL_ALIASES[c]) c = normalizeModelName(MODEL_ALIASES[c])
171
+ if (idx.models.has(c)) return idx.models.get(c)
172
+ const t = idx.routes.get(c)
173
+ if (t) {
174
+ const hit = idx.models.get(normalizeModelName(t))
175
+ if (hit) return hit
176
+ }
177
+ }
141
178
  return null
142
179
  }
143
180
 
@@ -643,11 +680,13 @@ export function peakPhaseAt(ts, spanDays) {
643
680
  * @param {string} model - 模型名(如 deepseek-v4-flash-vision-exp)
644
681
  * @param {number} [ts] - 调用发生时刻(epoch ms);决定用哪一版单价表。
645
682
  * 缺省用当前时间——注意历史/测试场景应显式传入,否则跨价格时代会错。
646
- * @param {{catalog?:Function, overrides?:Map, planOverrides?:object}} [opts]
647
- * · catalog(np, model) → 目录命中对象 | null(vendor-catalog.catalogEntryFor,
648
- * 由调用方注入以保持本模块可独立测试);
683
+ * @param {{catalog?:Function, overrides?:Map, planOverrides?:object,
684
+ * serviceTier?:'standard'|'fast', tokens?:object}} [opts]
685
+ * · catalog(np, model, extra) → 目录命中对象 | null(vendor-catalog.catalogEntryFor,
686
+ * 由调用方注入以保持本模块可独立测试;extra 携带 serviceTier 与 tokens 供 Fast/长档定价);
649
687
  * · overrides:setPriceOverrides 注入的手动覆盖价(不传则用模块态);
650
- * · planOverrides:订阅归类覆盖 {'provider/model'|'provider/*': 'plan'|'api'}。
688
+ * · planOverrides:订阅归类覆盖 {'provider/model'|'provider/*': 'plan'|'api'};
689
+ * · serviceTier / tokens:v1.11.0 起用于 GPT Fast 档与长上下文分档。
651
690
  * @returns {{rates:object, tiered:boolean, estimated:boolean, subscription:boolean,
652
691
  * model:string, era:string|null, source:string}}
653
692
  * model 为**计费模型规范名**:命中路由时是被路由到的模型(如 V4-Pro → V4.1 Flash),
@@ -701,8 +740,18 @@ function resolveNonPlanPrice(np, model, ts, o) {
701
740
  if (exact) return { rates: era.models[exact], tiered: true, estimated: false, subscription: false, model: exact, era: era.id, source: era.synced ? 'synced' : 'exact' }
702
741
  if (typeof o.catalog === 'function') {
703
742
  try {
704
- const c = o.catalog(np, model)
705
- if (c && c.rates) return { rates: c.rates, tiered: false, estimated: false, subscription: false, model, era: era.id, source: 'catalog', catalog: { provider: c.provider, sourceUrl: c.sourceUrl || '', checkedAt: c.checkedAt || '', via: c.via || '' } }
743
+ // v1.11.0:把服务档位与本次用量一并交给目录层(Fast 档价 + 长上下文分档)
744
+ const c = o.catalog(np, model, { serviceTier: o.serviceTier, tokens: o.tokens })
745
+ if (c && c.rates) {
746
+ return {
747
+ rates: c.rates, tiered: false, estimated: false, subscription: false, model, era: era.id, source: 'catalog',
748
+ catalog: {
749
+ provider: c.provider, sourceUrl: c.sourceUrl || '', checkedAt: c.checkedAt || '', via: c.via || '',
750
+ serviceTier: c.serviceTier || 'standard', tierPriceSource: c.tierPriceSource || '', contextTier: c.contextTier || 'short',
751
+ ...(c.tierNote ? { tierNote: c.tierNote } : {}),
752
+ },
753
+ }
754
+ }
706
755
  } catch (e) { /* 目录读取失败不阻断计费,落到 provider 兜底 */ }
707
756
  }
708
757
  const p = PROVIDER_RATES[np]
@@ -713,7 +762,8 @@ function resolveNonPlanPrice(np, model, ts, o) {
713
762
  /**
714
763
  * 计算一次调用的费用(CNY)。
715
764
  * @param {object} rates - {input, output, cacheRead, cacheWrite, reasoning?}(CNY / 1M tokens)
716
- * cacheRead 与 cacheWrite 同价(均为缓存命中价),输入用未命中价,reasoning 缺省 0。
765
+ * 输入用未命中价;cacheRead 为缓存命中价;cacheWrite 为缓存写入价
766
+ * (v1.11.0 起可独立给出,缺省与旧行为一致 = 与 cacheRead 同价);reasoning 缺省 0。
717
767
  * @param {boolean} tiered - 是否峰谷计价(false 时按表内价)
718
768
  * @param {boolean} peak - 是否高峰时段(tiered 且非高峰时 ×0.5)
719
769
  * @param {{input:number, output:number, cacheRead:number, cacheWrite:number, reasoning?:number}} t - token 用量
@@ -721,7 +771,12 @@ function resolveNonPlanPrice(np, model, ts, o) {
721
771
  export function computeCost(rates, tiered, peak, t) {
722
772
  const f = tiered && !peak ? 0.5 : 1
723
773
  const reasoning = toNum(t.reasoning) * (toNum(rates.reasoning))
724
- return (t.input * rates.input + t.output * rates.output + (t.cacheRead + t.cacheWrite) * rates.cacheRead + reasoning) * f / 1000000
774
+ // v1.11.0:缓存读与缓存写分开计价(OpenAI/Anthropic 写价比读价高);
775
+ // 未提供 cacheWrite 时沿用缓存读价,DeepSeek 等读写同价模型的结果完全不变。
776
+ const writePrice = rates.cacheWrite === undefined ? toNum(rates.cacheRead) : toNum(rates.cacheWrite)
777
+ return (t.input * toNum(rates.input) + t.output * toNum(rates.output)
778
+ + t.cacheRead * toNum(rates.cacheRead) + t.cacheWrite * writePrice
779
+ + reasoning) * f / 1000000
725
780
  }
726
781
 
727
782
  function toNum(x) { const n = Number(x); return isNaN(n) ? 0 : n }
package/sync.js CHANGED
@@ -380,6 +380,16 @@ export function createSyncEngine(deps) {
380
380
  subscription: r.subscription === true,
381
381
  period: r.period || 'flat',
382
382
  }
383
+ // v1.11.0:GPT Fast 档标记随 meta 上报(≤1KB 契约内),云端据此按同一档位重算;
384
+ // 标准档记录不带该字段,旧服务端忽略未知 meta 也照常工作。
385
+ if (r.serviceTier === 'fast') {
386
+ rec.meta = {
387
+ serviceTier: 'fast',
388
+ ...(r.tierPriceSource ? { tierPriceSource: String(r.tierPriceSource) } : {}),
389
+ ...(r.contextTier ? { contextTier: String(r.contextTier) } : {}),
390
+ ...(r.ultrafast === true ? { ultrafast: true } : {}),
391
+ }
392
+ }
383
393
  // 去重键按**原始记录**计算(服务端也按原始字段算),脱敏只影响上送字段
384
394
  rec.dedupKey = dedupKeyOf(r, resetEpoch)
385
395
  const size = JSON.stringify(rec).length
@@ -0,0 +1,61 @@
1
+ // ============================================================
2
+ // DSH 花费统计插件 —— Token 数量的中文单位显示(纯逻辑,可独立测试)
3
+ //
4
+ // 背景:以往 UI 把 token 显示成 `1.5M` / `314K`(英文单位),中英混排且
5
+ // 中文用户读起来不直观。v1.11.0 起统一为中文口径:
6
+ //
7
+ // < 1万 千分位整数 9,300
8
+ // ≥ 1万 <1亿 X.X万(≥100万取整) 31.4万 / 150万 / 3,138万
9
+ // ≥ 1亿 X.XX亿(≥10亿 1 位) 1.50亿 / 327.7亿
10
+ //
11
+ // 设计取舍:
12
+ // • 千分位分组**只用于** 1 万以下的原始整数(「9,300」易读),
13
+ // 万/亿口径里的数字不带分组(「3,138万」比「3,138万」更接近中文习惯,
14
+ // 实际取「3,138万」会与「万」字挤在一起,故超过 4 位时也不加逗号)。
15
+ // • 单位与数字之间**不留空格**,便于在窄容器(气泡、胶囊、坐标轴)里换行。
16
+ // • 纯函数、无 Intl 依赖:Node 与浏览器表现一致,单测可逐值断言。
17
+ // • 精确数值(tooltip、CSV)另有 formatTokenExact,避免丢精度。
18
+ // ============================================================
19
+
20
+ /** 1 万 / 1 亿 */
21
+ export const WAN = 10000
22
+ export const YI = 100000000
23
+
24
+ /** 千分位(仅用于安全整数范围) */
25
+ function group3(n) {
26
+ return String(n).replace(/\B(?=(\d{3})+(?!\d))/g, ',')
27
+ }
28
+
29
+ /** 去掉多余的尾随 0(1.50 → 1.5,2.0 → 2) */
30
+ function trimZeros(s) {
31
+ return s.indexOf('.') >= 0 ? s.replace(/\.?0+$/, '') : s
32
+ }
33
+
34
+ /**
35
+ * 把一个 token 数格式化为中文单位。
36
+ * @param {number|string} value - token 数量(负数按 0 处理,非数按 0 处理)
37
+ * @param {{exact?:boolean}} [opts] - exact=true 时返回完整千分位整数(不换算单位)
38
+ * @returns {string} 例如 `0` / `9,300` / `31.4万` / `3,138万` / `1.5亿` / `327.7亿`
39
+ */
40
+ export function formatTokenCN(value, opts) {
41
+ const raw = Number(value)
42
+ const v = Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : 0
43
+ if (opts && opts.exact === true) return group3(v)
44
+ if (v < WAN) return group3(v)
45
+ if (v < YI) {
46
+ const w = v / WAN
47
+ // ≥100 万不再保留小数:四舍五入到整数「万」
48
+ return (w >= 100 ? String(Math.round(w)) : trimZeros(w.toFixed(1))) + '万'
49
+ }
50
+ const y = v / YI
51
+ return (y >= 10 ? trimZeros(y.toFixed(1)) : trimZeros(y.toFixed(2))) + '亿'
52
+ }
53
+
54
+ /**
55
+ * 相同语义的精确显示:完整千分位整数(用于 tooltip / CSV / 明细)。
56
+ * @param {number|string} value
57
+ * @returns {string}
58
+ */
59
+ export function formatTokenExact(value) {
60
+ return formatTokenCN(value, { exact: true })
61
+ }