@angelyeye/dsh-cost-tracker 1.10.0 → 1.11.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/index.js CHANGED
@@ -9,7 +9,7 @@
9
9
  import { readFileSync, writeFileSync, mkdirSync, renameSync, existsSync, realpathSync } from 'node:fs'
10
10
  import { join, dirname } from 'node:path'
11
11
  import { homedir } from 'node:os'
12
- import { createStore, collectTotals, DETAIL_DAYS, MAX_AXIS_DAYS } from './store.js'
12
+ import { createStore, collectTotals, DETAIL_DAYS, MAX_AXIS_DAYS, PRIVATE_DIR_MODE, PRIVATE_FILE_MODE } from './store.js'
13
13
  import { PRICE_ERAS, V41_EFFECTIVE_AT, exactModelsAt, eraAt, SUBSCRIPTION_RATES, PROVIDER_RATES, GENERIC_RATES, PEAK_WINDOWS, PEAK_HOUR_WINDOWS, isPeak, peakPhaseAt, priceFor, computeCost, normalizeTokens, subscriptionPlanFor, volcenginePlanModels, VOLCENGINE_PLAN_PROVIDER_KEYS, VOLCENGINE_PLAN_RATES, setSyncedEras, getSyncedEras, setPriceOverrides, getPriceOverrides, setPeakHolidays, getPeakHolidays } from './pricing.js'
14
14
  import {
15
15
  normalizePeakConfig, defaultPeakConfig, peakEffective,
@@ -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.0'
44
+ const PLUGIN_VERSION = '1.11.0'
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) })
@@ -317,9 +324,9 @@ export default {
317
324
 
318
325
  function saveConfig() {
319
326
  try {
320
- mkdirSync(dirname(CONFIG_FILE), { recursive: true })
327
+ mkdirSync(dirname(CONFIG_FILE), { recursive: true, mode: PRIVATE_DIR_MODE })
321
328
  const tmp = CONFIG_FILE + '.tmp'
322
- writeFileSync(tmp, JSON.stringify(Object.assign({}, peakConfig, cloudConfig, uiConfig, volcengineConfig, billingConfig, importConfig, priceSyncConfig, securityConfig)), 'utf8')
329
+ writeFileSync(tmp, JSON.stringify(Object.assign({}, peakConfig, cloudConfig, uiConfig, volcengineConfig, billingConfig, importConfig, priceSyncConfig, securityConfig)), { encoding: 'utf8', mode: PRIVATE_FILE_MODE })
323
330
  renameSync(tmp, CONFIG_FILE)
324
331
  return true
325
332
  } catch (e) {
@@ -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,
@@ -1483,14 +1546,19 @@ export default {
1483
1546
  else if (Number.isFinite(a.since) && a.since >= 0) since = a.since
1484
1547
  const apply = a.apply === true
1485
1548
  const byModel = {}
1486
- let scanned = 0, changed = 0, oldCost = 0, newCost = 0, estimatedFlips = 0
1549
+ let scanned = 0, changed = 0, oldCost = 0, newCost = 0, estimatedFlips = 0, markerOnlyFlips = 0
1487
1550
  for (const r of records) {
1488
1551
  if (!(r.ts >= since)) continue
1489
1552
  scanned += 1
1490
1553
  const np = normProvider(r.provider)
1491
1554
  // v1.9.0:重算与实时记账共用 priceForAt —— 同步时代 / 目录 / 覆盖价 /
1492
1555
  // 订阅归类覆盖在补账时同样生效(口径完全一致,重算后不会有双标)。
1493
- const p = priceForAt(np, r.model, r.ts, r.tokens)
1556
+ // v1.11.0:记录上带 serviceTier:'fast' 的按 Fast 档重算;旧记录(无该字段)
1557
+ // 仍按标准档,结果与 1.10.x 完全一致。
1558
+ const tier = r.serviceTier === 'fast'
1559
+ ? { tier: 'fast', source: 'record', ultrafast: r.ultrafast === true }
1560
+ : { tier: 'standard', source: 'record' }
1561
+ const p = priceForAt(np, r.model, r.ts, r.tokens, tier)
1494
1562
  const cost = p.cost
1495
1563
  const model = p.model
1496
1564
  const period = p.period
@@ -1504,6 +1572,10 @@ export default {
1504
1572
  if (!(Math.abs(cost - r.cost) > 1e-9 || model !== r.model || period !== r.period || flip)) continue
1505
1573
  changed += 1
1506
1574
  if (flip) estimatedFlips += 1
1575
+ // v1.11.0:区分「只订正标记」与「金额也变了」。旧文案把两者混为一谈,
1576
+ // 出现过「7010 条仅订正估算标记,金额不变」与实际金额 +182 自相矛盾的输出。
1577
+ const markerOnly = flip && Math.abs(cost - r.cost) <= 1e-9 && model === r.model && period === r.period
1578
+ if (markerOnly) markerOnlyFlips += 1
1507
1579
  const key = r.provider + '|' + r.model + '|' + model
1508
1580
  const m = byModel[key] || (byModel[key] = { provider: r.provider, from: r.model, to: model, calls: 0, oldCost: 0, newCost: 0, flips: 0 })
1509
1581
  m.calls += 1
@@ -1532,6 +1604,7 @@ export default {
1532
1604
  scanned,
1533
1605
  changed,
1534
1606
  estimatedFlips,
1607
+ markerOnlyFlips,
1535
1608
  oldCost: r4(oldCost),
1536
1609
  newCost: r4(newCost),
1537
1610
  delta: r4(newCost - oldCost),
@@ -1539,7 +1612,7 @@ export default {
1539
1612
  note: changed === 0
1540
1613
  ? '没有需要重算的记录'
1541
1614
  : (apply
1542
- ? '已重算并落盘' + (estimatedFlips ? '(其中 ' + estimatedFlips + ' 条仅订正「估算」标记,金额不变)' : '')
1615
+ ? '已重算并落盘' + (markerOnlyFlips ? '(其中 ' + markerOnlyFlips + ' 条仅订正「估算」标记,金额不变)' : '')
1543
1616
  : '试算结果,未落盘(传 apply: true 生效)'),
1544
1617
  }
1545
1618
  }
@@ -1603,9 +1676,9 @@ export default {
1603
1676
  }
1604
1677
  function savePriceState() {
1605
1678
  try {
1606
- mkdirSync(dirname(PRICES_FILE), { recursive: true })
1679
+ mkdirSync(dirname(PRICES_FILE), { recursive: true, mode: PRIVATE_DIR_MODE })
1607
1680
  const tmp = PRICES_FILE + '.tmp'
1608
- writeFileSync(tmp, JSON.stringify(priceState), 'utf8')
1681
+ writeFileSync(tmp, JSON.stringify(priceState), { encoding: 'utf8', mode: PRIVATE_FILE_MODE })
1609
1682
  renameSync(tmp, PRICES_FILE)
1610
1683
  return true
1611
1684
  } catch (e) {
@@ -1695,9 +1768,9 @@ export default {
1695
1768
  }
1696
1769
  function saveImportManifest() {
1697
1770
  try {
1698
- mkdirSync(dirname(IMPORT_MANIFEST_FILE), { recursive: true })
1771
+ mkdirSync(dirname(IMPORT_MANIFEST_FILE), { recursive: true, mode: PRIVATE_DIR_MODE })
1699
1772
  const tmp = IMPORT_MANIFEST_FILE + '.tmp'
1700
- writeFileSync(tmp, JSON.stringify(importManifest), 'utf8')
1773
+ writeFileSync(tmp, JSON.stringify(importManifest), { encoding: 'utf8', mode: PRIVATE_FILE_MODE })
1701
1774
  renameSync(tmp, IMPORT_MANIFEST_FILE)
1702
1775
  return true
1703
1776
  } catch (e) {
@@ -1734,8 +1807,10 @@ export default {
1734
1807
  importLastResult = { at: Date.now(), imported: 0, files: 0, scanned: 0, note: '未找到会话日志目录(' + root + ')' }
1735
1808
  return { ok: true, imported: 0, files: 0, scanned: 0, note: '未找到会话日志' }
1736
1809
  }
1737
- const priceFn = (np, model, ts, tokens) => {
1738
- const p = priceForAt(np, model, ts, tokens)
1810
+ const priceFn = (np, model, ts, tokens, sessionId) => {
1811
+ // v1.11.0:历史导入按该会话在日志里的档位选择计 Fast 价(无选择则标准档)
1812
+ const tier = resolveTier(null, tierResolver, sessionId)
1813
+ const p = priceForAt(np, model, ts, tokens, tier)
1739
1814
  return { cost: p.cost, estimated: p.estimated, subscription: p.subscription, period: p.period, model: p.model }
1740
1815
  }
1741
1816
  const results = await planAndBuildImports(records, rollups, logs, importManifest, { priceFn, normProvider })
@@ -2147,7 +2222,30 @@ export default {
2147
2222
  }
2148
2223
  lines.push('视觉模型 deepseek-v4-flash-vision-exp:图片按官方规则换算 token(每张上限 384),以接口用量计费(已含在 inputTokens 内)。')
2149
2224
  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。')
2225
+ 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。')
2226
+ // ---- v1.11.0:多厂商目录概览 + GPT Fast 档价格 ----
2227
+ if (v.catalog) {
2228
+ const c = v.catalog
2229
+ const meta = c.meta || {}
2230
+ const total = (c.providers || []).reduce((n, p) => n + (Number(p.count) || 0), 0)
2231
+ lines.push('', '【多厂商价格目录】' + (meta.generatedAt || '') + ' · ' + (c.providers || []).length + ' 家 / ' + total + ' 条 · USD→CNY 汇率 ' + c.fxRate + '(匹配:' + c.match + ')')
2232
+ const fast = c.fast || { models: [] }
2233
+ if (fast.models && fast.models.length) {
2234
+ lines.push('', '【OpenAI Fast 档(service_tier: fast / priority)】核实日期 ' + (fast.checkedAt || '') + ' · 汇率 ' + fast.fxRate + ' · 共 ' + fast.models.length + ' 个模型可区分档位')
2235
+ for (const m of fast.models) {
2236
+ const std = m.standardCny || {}
2237
+ const f = m.fastCny || {}
2238
+ lines.push(' ' + m.model + ':标准 ¥' + std.input + ' / ¥' + std.cachedInput + ' / ¥' + std.output
2239
+ + ' → Fast ¥' + f.input + ' / ¥' + f.cachedInput + ' / ¥' + f.output
2240
+ + '(USD ' + m.standard.input + '/' + m.standard.cachedInput + '/' + m.standard.output
2241
+ + ' → ' + m.fast.input + '/' + m.fast.cachedInput + '/' + m.fast.output + ')'
2242
+ + (m.longContext ? ';>272K 另行计档' : '') + ';来源 ' + (m.confidence || 'official'))
2243
+ }
2244
+ lines.push('Fast 档判定:请求参数 > 会话在 dsh-fast-tier 里的选择;识别不到档位时按标准价计(不会凭空 ×2)。ultrafast 按 Fast 价计,实际倍率更高,属已知偏低。')
2245
+ } else {
2246
+ lines.push('【OpenAI Fast 档】目录中暂无登记 fast 块价的模型。')
2247
+ }
2248
+ }
2151
2249
  return [{ type: 'text', text: lines.join('\n') }]
2152
2250
  },
2153
2251
  },
@@ -2188,7 +2286,7 @@ export default {
2188
2286
  : ('自 ' + new Date(v.since + 28800000).toISOString().replace('T', ' ').slice(0, 16).replace(/-/g, '/') + ' 北京起 · era=' + v.era)
2189
2287
  const lines = [
2190
2288
  '费用重算(' + scope + ')',
2191
- '扫描 ' + v.scanned + ' 条,需修正 ' + v.changed + ' 条' + (v.estimatedFlips ? '(其中 ' + v.estimatedFlips + ' 条仅订正「估算」标记,金额不变)' : ''),
2289
+ '扫描 ' + v.scanned + ' 条,需修正 ' + v.changed + ' 条' + (v.markerOnlyFlips ? '(其中 ' + v.markerOnlyFlips + ' 条仅订正「估算」标记,金额不变)' : ''),
2192
2290
  '合计:¥' + v.oldCost + ' → ¥' + v.newCost + '(' + (v.delta >= 0 ? '+' : '') + v.delta + ')',
2193
2291
  ]
2194
2292
  for (const m of (v.byModel || []).slice(0, 8)) {
@@ -2262,11 +2360,11 @@ export default {
2262
2360
  const lines = ['花费统计(' + (v.days === 0 ? '全部' : '近 ' + v.days + ' 天') + ')']
2263
2361
  if (v.local) {
2264
2362
  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 + '(订阅已覆盖,仅供参考)')
2363
+ + (v.local.flatCost > 0 ? ' · 不分峰谷 ¥' + v.local.flatCost : '') + ')· 请求 ' + v.local.realCalls + ' 次 · Token ' + formatTokenCN(v.local.realTokens))
2364
+ lines.push('【本机】订阅套餐:请求 ' + v.local.subCalls + ' 次 · Token ' + formatTokenCN(v.local.subTokens) + ' · 等效 ¥' + v.local.subEquivalent + '(订阅已覆盖,仅供参考)')
2267
2365
  }
2268
2366
  if (v.cloud && v.cloud.ok) {
2269
- lines.push('【云端汇总】按量消费:¥' + v.cloud.realCost + ' · 请求 ' + v.cloud.realCalls + ' 次 · Tokens ' + v.cloud.realTokens
2367
+ lines.push('【云端汇总】按量消费:¥' + v.cloud.realCost + ' · 请求 ' + v.cloud.realCalls + ' 次 · Token ' + formatTokenCN(v.cloud.realTokens)
2270
2368
  + '(' + (v.cloud.devices || []).map((d) => d.name).join(' / ') + ')')
2271
2369
  if (v.cloud.sources && v.cloud.sources.length) {
2272
2370
  lines.push('【云端汇总】按 Agent:' + v.cloud.sources.map((s) => s.source + ' ¥' + s.cost).join(' · '))
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@angelyeye/dsh-cost-tracker",
3
- "version": "1.10.0",
3
+ "version": "1.11.0",
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",
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/store.js CHANGED
@@ -76,6 +76,17 @@ function sleepSync(ms) {
76
76
  }
77
77
  }
78
78
 
79
+ /**
80
+ * 私有目录 / 文件的创建模式:POSIX 上 owner-only(0o700 / 0o600)。
81
+ *
82
+ * 为什么需要:`~/.dsh/storages` 里的记录含**完整用量明细**(会话、模型、token、
83
+ * 花费,未脱敏时还有 sessionId),而默认 umask(常见 022)会让同机其他用户可读。
84
+ * Windows 会忽略 mode,行为不变;POSIX 上显式收紧到 owner-only。
85
+ * 已有文件不会被 chmod 改写(只影响新建),避免动到用户既有部署的权限策略。
86
+ */
87
+ export const PRIVATE_DIR_MODE = 0o700
88
+ export const PRIVATE_FILE_MODE = 0o600
89
+
79
90
  /**
80
91
  * 原子落盘:写临时文件 → rename 覆盖目标。
81
92
  *
@@ -96,8 +107,8 @@ export function writeFileAtomic(filePath, data, opts) {
96
107
  const tmp = filePath + '.' + process.pid + '.tmp'
97
108
  const cleanup = () => { try { fs.unlinkSync(tmp) } catch (e) { /* 已被 rename 走或从未创建 */ } }
98
109
  try {
99
- fs.mkdirSync(dirname(filePath), { recursive: true })
100
- fs.writeFileSync(tmp, data, 'utf8')
110
+ fs.mkdirSync(dirname(filePath), { recursive: true, mode: PRIVATE_DIR_MODE })
111
+ fs.writeFileSync(tmp, data, { encoding: 'utf8', mode: PRIVATE_FILE_MODE })
101
112
  } catch (e) {
102
113
  cleanup()
103
114
  return { ok: false, attempts: 0, mode: 'failed', error: e, transient: isTransientRenameError(e) }
@@ -173,8 +184,8 @@ export function checkStoreLock(filePath, opts) {
173
184
  export function writeStoreLock(filePath, opts) {
174
185
  const o = opts || {}
175
186
  try {
176
- mkdirSync(dirname(filePath), { recursive: true })
177
- writeFileSync(filePath + '.lock', JSON.stringify({ pid: process.pid, at: Date.now(), version: o.version || '' }), 'utf8')
187
+ mkdirSync(dirname(filePath), { recursive: true, mode: PRIVATE_DIR_MODE })
188
+ writeFileSync(filePath + '.lock', JSON.stringify({ pid: process.pid, at: Date.now(), version: o.version || '' }), { encoding: 'utf8', mode: PRIVATE_FILE_MODE })
178
189
  return true
179
190
  } catch (e) {
180
191
  return false
package/sync.js CHANGED
@@ -47,6 +47,25 @@ export function dataDir(env) {
47
47
  export function identityPath(env) { return join(dataDir(env), 'device.json') }
48
48
  export function syncStatePath(storageDir) { return join(storageDir, 'cost-tracker-sync.json') }
49
49
 
50
+ /**
51
+ * 同步身份/游标文件的私有权限:POSIX 上 owner-only(0o700 / 0o600)。
52
+ * device.json 含 machineId(主机名+用户名的哈希)与设备名,游标文件含最近同步
53
+ * 结果,都不该让同机其他用户可读;Windows 忽略 mode,行为不变。
54
+ */
55
+ export const PRIVATE_DIR_MODE = 0o700
56
+ export const PRIVATE_FILE_MODE = 0o600
57
+
58
+ function ensurePrivateDir(dir) {
59
+ mkdirSync(dir, { recursive: true, mode: PRIVATE_DIR_MODE })
60
+ }
61
+
62
+ /** 写临时文件(0600)→ rename,避免读者看到半个 JSON */
63
+ function writePrivateJson(file, value) {
64
+ const tmp = file + '.tmp'
65
+ writeFileSync(tmp, JSON.stringify(value, null, 2), { encoding: 'utf8', mode: PRIVATE_FILE_MODE })
66
+ renameSync(tmp, file)
67
+ }
68
+
50
69
  function defaultMachineId(env) {
51
70
  const e = env || process.env
52
71
  const host = e.COMPUTERNAME || e.HOSTNAME || e.HOST || 'unknown-host'
@@ -81,8 +100,8 @@ export function loadIdentity(opts) {
81
100
  nameLocked: false,
82
101
  }
83
102
  try {
84
- mkdirSync(dir, { recursive: true })
85
- writeFileSync(file, JSON.stringify(id, null, 2), 'utf8')
103
+ ensurePrivateDir(dir)
104
+ writeFileSync(file, JSON.stringify(id, null, 2), { encoding: 'utf8', mode: PRIVATE_FILE_MODE })
86
105
  } catch (e) { /* 只读环境:内存态继续工作 */ }
87
106
  return id
88
107
  }
@@ -91,11 +110,8 @@ export function saveIdentity(id, opts) {
91
110
  const env = (opts && opts.env) || process.env
92
111
  const dir = (opts && opts.dir) || dataDir(env)
93
112
  try {
94
- mkdirSync(dir, { recursive: true })
95
- const file = join(dir, 'device.json')
96
- const tmp = file + '.tmp'
97
- writeFileSync(tmp, JSON.stringify(id, null, 2), 'utf8')
98
- renameSync(tmp, file)
113
+ ensurePrivateDir(dir)
114
+ writePrivateJson(join(dir, 'device.json'), id)
99
115
  return true
100
116
  } catch (e) {
101
117
  return false
@@ -222,11 +238,8 @@ export function readSyncState(storageDir) {
222
238
 
223
239
  export function writeSyncState(storageDir, state) {
224
240
  try {
225
- mkdirSync(storageDir, { recursive: true })
226
- const file = syncStatePath(storageDir)
227
- const tmp = file + '.tmp'
228
- writeFileSync(tmp, JSON.stringify(state, null, 2), 'utf8')
229
- renameSync(tmp, file)
241
+ ensurePrivateDir(storageDir)
242
+ writePrivateJson(syncStatePath(storageDir), state)
230
243
  return true
231
244
  } catch (e) {
232
245
  return false
@@ -367,6 +380,16 @@ export function createSyncEngine(deps) {
367
380
  subscription: r.subscription === true,
368
381
  period: r.period || 'flat',
369
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
+ }
370
393
  // 去重键按**原始记录**计算(服务端也按原始字段算),脱敏只影响上送字段
371
394
  rec.dedupKey = dedupKeyOf(r, resetEpoch)
372
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
+ }