dsh-token-dash 2.1.0 → 2.3.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
@@ -19,7 +19,16 @@ import { isNewer } from './src/version.js'
19
19
  export const name = 'dsh-token-dash'
20
20
 
21
21
  const ROUTE_PREFIX = '/token-dash/api'
22
- const CURRENT_VERSION = JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version
22
+ /**
23
+ * 当前版本:默认取 package.json。TOKEN_DASH_CURRENT_VERSION 可覆盖,
24
+ * 供 e2e 用「真实 GitHub/npm 已发布版本」跑完整更新链路(不必真的装一个旧包)。
25
+ * 但「安装」环节仍走真实 CLI,因此覆盖值只影响比对基准,不影响安装目标。
26
+ */
27
+ const CURRENT_VERSION = (() => {
28
+ const override = process.env.TOKEN_DASH_CURRENT_VERSION
29
+ if (typeof override === 'string' && override !== '') return override
30
+ return JSON.parse(readFileSync(new URL('./package.json', import.meta.url), 'utf8')).version
31
+ })()
23
32
  const LOOPBACK_HOSTS = new Set(['127.0.0.1', 'localhost', '[::1]', '::1'])
24
33
 
25
34
  /** 宿主版本:优先环境变量,其次 Electron asar 内的 package.json;读不到时写 unknown,避免硬编码过期。 */
@@ -42,6 +51,8 @@ function hostVersion() {
42
51
  return 'unknown'
43
52
  }
44
53
  let updateCache = { at: 0, data: null }
54
+ /** 允许 client 上报日志的模块白名单:只放已知来源,避免任意日志注入。 */
55
+ const CLIENT_LOG_MODULES = new Set(['slot', 'update'])
45
56
 
46
57
  /** Locate the bundled dsh CLI (same layout scripts/e2e.mjs relies on). */
47
58
  function findDshCli() {
@@ -77,12 +88,19 @@ async function fetchLatest() {
77
88
  const meta = await response.json()
78
89
  if (typeof meta?.version !== 'string') throw new Error('invalid-registry-response')
79
90
  return { current: CURRENT_VERSION, latest: meta.version, hasUpdate: isNewer(meta.version, CURRENT_VERSION), published: true }
91
+ if (typeof meta?.version !== 'string') throw new Error('invalid-registry-response')
92
+ return { current: CURRENT_VERSION, latest: meta.version, hasUpdate: isNewer(meta.version, CURRENT_VERSION), published: true, source: 'registry' }
80
93
  }
81
94
 
82
- /** Run `dsh plugin --profile <p> add dsh-token-dash@<version> --save-exact`; resolves with { ok, reason?, command, output }. */
95
+ /** 安装 spec:默认按 npm 版本号安装,仍走与真实更新完全相同的 CLI 路径。 */
96
+ function updateSpec(version) {
97
+ return `dsh-token-dash@${version}`
98
+ }
99
+
100
+ /** Run `dsh plugin --profile <p> add <spec> --save-exact`; resolves with { ok, reason?, command, output }. */
83
101
  function runPluginUpdate(profile, version) {
84
102
  return new Promise((resolve) => {
85
- const spec = `dsh-token-dash@${version}`
103
+ const spec = updateSpec(version)
86
104
  const command = `dsh plugin --profile ${profile} add ${spec} --save-exact`
87
105
  const cli = findDshCli()
88
106
  if (cli === null) {
@@ -450,6 +468,9 @@ export function apply(ctx) {
450
468
  billable: usage.models.filter((item) => item.billable === true).length,
451
469
  tokens: usage.total.tokens,
452
470
  currencies: Object.keys(usage.totals).length,
471
+ grain: usage.grain,
472
+ points: usage.series.length,
473
+ seriesCurrencies: Object.keys(usage.series.reduce((acc, point) => Object.assign(acc, point.cost), {})).length,
453
474
  probeMs,
454
475
  durationMs: Date.now() - startedAt,
455
476
  })
@@ -526,54 +547,94 @@ export function apply(ctx) {
526
547
  return
527
548
  }
528
549
  if (url.pathname === `${ROUTE_PREFIX}/log` && req.method === 'POST') {
529
- // #46:client 端 slot 挂载上报落盘——模块白名单仅 slot,防日志注入
550
+ // client 端上报落盘:模块白名单(slot 挂载 / update 调度),防日志注入
530
551
  const body = JSON.parse((await readBody(req)) || '{}')
531
- if (body?.module !== 'slot' || typeof body?.event !== 'string') {
552
+ if (!CLIENT_LOG_MODULES.has(body?.module) || typeof body?.event !== 'string') {
532
553
  json(res, 400, { ok: false, reason: 'invalid-log' })
533
554
  return
534
555
  }
535
- logger.info('slot', body.event, typeof body.meta === 'object' && body.meta !== null ? body.meta : {})
556
+ logger.info(body.module, body.event, typeof body.meta === 'object' && body.meta !== null ? body.meta : {})
536
557
  json(res, 200, { ok: true, data: { logged: true } })
537
558
  return
538
559
  }
539
560
  if (url.pathname === `${ROUTE_PREFIX}/update/install` && req.method === 'POST') {
540
561
  const profile = typeof process.env.DSH_PROFILE === 'string' && process.env.DSH_PROFILE !== '' ? process.env.DSH_PROFILE : 'desktop'
541
- const latest = (await fetchLatest()).latest
542
- if (latest === null) {
562
+ // 优先安装客户端展示过的那个版本:用户看到的与真正装上的必须是同一个,
563
+ // 否则两次查询 registry 之间若发版,会出现「提示 A 装成 B」。
564
+ // 未带 version 时(旧客户端)回退查询 registry,保持向后兼容。
565
+ let target = null
566
+ try {
567
+ const body = JSON.parse((await readBody(req)) || '{}')
568
+ if (typeof body?.version === 'string' && body.version !== '') target = body.version
569
+ } catch { /* 空 body 或非法 JSON 按未指定处理 */ }
570
+ if (target === null) target = (await fetchLatest()).latest
571
+ if (target === null) {
543
572
  logger.info('update', 'install.fail', { profile, reason: 'unpublished' })
544
- json(res, 200, { ok: false, reason: 'unpublished', data: { reason: 'unpublished', command: '' } })
573
+ json(res, 400, { ok: false, reason: 'unpublished' })
574
+ return
575
+ }
576
+ // 版本号必须是合法 semver:既防注入,也防把任意字符串拼进 CLI 参数
577
+ if (/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(target) === false) {
578
+ logger.info('update', 'install.fail', { profile, reason: 'invalid-version', target })
579
+ json(res, 400, { ok: false, reason: 'invalid-version' })
545
580
  return
546
581
  }
547
- if (/^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)?$/.test(latest) === false) throw new Error('invalid-latest-version')
548
582
  const home = resolveHome(scoped)
549
583
  const from = installedVersion(home, profile) ?? CURRENT_VERSION
550
- const result = await runPluginUpdate(profile, latest)
584
+ const result = await runPluginUpdate(profile, target)
551
585
  const to = installedVersion(home, profile)
552
- const changed = to === latest
586
+ const changed = to === target
553
587
  const ok = result.ok === true && changed
554
588
  const failReason = result.ok === true ? 'version-unchanged' : result.reason ?? 'install-failed'
555
589
  logger.info('update', ok ? 'install.ok' : 'install.fail', {
556
590
  profile,
557
591
  from,
558
592
  to,
593
+ target,
559
594
  reason: ok ? null : failReason,
560
595
  ...(ok ? {} : { output: String(result.output ?? '').slice(-500) }),
561
596
  })
562
597
  updateCache = { at: 0, data: null }
563
- json(res, 200, {
598
+ json(res, ok ? 200 : 500, {
564
599
  ok,
565
- data: { ...result, from, to, latest, ...(ok ? {} : { reason: failReason }) },
600
+ data: { ...result, from, to, latest: target, ...(ok ? {} : { reason: failReason }) },
566
601
  ...(ok ? {} : { reason: failReason }),
567
602
  })
568
603
  return
569
604
  }
570
605
  if (url.pathname === `${ROUTE_PREFIX}/update` && req.method === 'GET') {
571
- if (updateCache.data !== null && Date.now() - updateCache.at < 300000) {
606
+ // ?refresh=1 跳过 5min 缓存。启动检测与手动点击都带这个参数:
607
+ // 用户要求「每次启动无条件检查」,命中旧缓存就等于没检查。
608
+ const forceRefresh = url.searchParams.get('refresh') === '1'
609
+ if (!forceRefresh && updateCache.data !== null && Date.now() - updateCache.at < 300000) {
572
610
  json(res, 200, { ok: true, data: updateCache.data })
573
611
  return
574
612
  }
575
- const data = await fetchLatest()
613
+ let data
614
+ try {
615
+ data = await fetchLatest()
616
+ } catch (error) {
617
+ // 失败不吞:带 errorKind / httpStatus 落日志,客户端也能据此显示「更新检查失败」
618
+ const message = String(error?.message ?? error)
619
+ const statusMatch = /registry-(\d+)/.exec(message)
620
+ const errorKind = statusMatch !== null ? 'http' : (message.includes('timeout') || message.includes('abort') ? 'timeout' : 'network')
621
+ logger.error('update', 'check.fail', {
622
+ source: 'registry',
623
+ errorKind,
624
+ httpStatus: statusMatch === null ? null : Number(statusMatch[1]),
625
+ reason: message,
626
+ })
627
+ json(res, 502, { ok: false, reason: errorKind })
628
+ return
629
+ }
576
630
  updateCache = { at: Date.now(), data }
631
+ logger.info('update', 'check.ok', {
632
+ source: data.source ?? 'registry',
633
+ current: data.current,
634
+ latest: data.latest,
635
+ hasUpdate: data.hasUpdate,
636
+ published: data.published,
637
+ })
577
638
  json(res, 200, { ok: true, data })
578
639
  return
579
640
  }
@@ -621,4 +682,4 @@ export function apply(ctx) {
621
682
  })
622
683
  return off
623
684
  })
624
- }
685
+ }
package/locale/en.json CHANGED
@@ -91,7 +91,6 @@
91
91
  "已是最新": "Up to date",
92
92
  "发现 {version}": "Found {version}",
93
93
  "更新": "Update",
94
- "取消": "Cancel",
95
94
  "复制命令": "Copy command",
96
95
  "命令已复制": "Command copied",
97
96
  "复制失败": "Copy failed",
@@ -118,5 +117,25 @@
118
117
  "周期至 {time}": "Cycle ends {time}",
119
118
  "限流中": "Rate limited",
120
119
  "渠道用量 {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"
120
+ "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "Price table is CNY while this provider bills in USD; add a USD priceOverrides entry",
121
+ "总请求数": "Total requests",
122
+ "缓存命中率": "Cache hit rate",
123
+ "{n} 个币种": "{n} currencies",
124
+ "范围内全部模型": "All models in range",
125
+ "创建 {a} · 命中 {b}": "Created {a} · hit {b}",
126
+ "趋势指标": "Trend metric",
127
+ "使用趋势 · {metric}": "Trend · {metric}",
128
+ "按天": "Daily",
129
+ "按月": "Monthly",
130
+ "与上方卡片同口径": "Same scope as cards above",
131
+ "命中率": "Hit rate",
132
+ "无数据": "No data",
133
+ "多币种下成本柱不可用,请切换其他指标": "Cost bars unavailable with multiple currencies; switch metric",
134
+ "万": "K",
135
+ "更新中": "Updating",
136
+ "更新检查失败": "Update check failed",
137
+ "版本号不合法": "Invalid version",
138
+ "该版本未发布": "Version not published",
139
+ "版本未变化": "Version unchanged",
140
+ "未找到 dsh 命令": "dsh command not found"
122
141
  }
package/locale/zh.json CHANGED
@@ -91,7 +91,6 @@
91
91
  "已是最新": "已是最新",
92
92
  "发现 {version}": "发现 {version}",
93
93
  "更新": "更新",
94
- "取消": "取消",
95
94
  "复制命令": "复制命令",
96
95
  "命令已复制": "命令已复制",
97
96
  "复制失败": "复制失败",
@@ -118,5 +117,25 @@
118
117
  "周期至 {time}": "周期至 {time}",
119
118
  "限流中": "限流中",
120
119
  "渠道用量 {value}": "渠道用量 {value}",
121
- "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价"
120
+ "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价",
121
+ "总请求数": "总请求数",
122
+ "缓存命中率": "缓存命中率",
123
+ "{n} 个币种": "{n} 个币种",
124
+ "范围内全部模型": "范围内全部模型",
125
+ "创建 {a} · 命中 {b}": "创建 {a} · 命中 {b}",
126
+ "趋势指标": "趋势指标",
127
+ "使用趋势 · {metric}": "使用趋势 · {metric}",
128
+ "按天": "按天",
129
+ "按月": "按月",
130
+ "与上方卡片同口径": "与上方卡片同口径",
131
+ "命中率": "命中率",
132
+ "无数据": "无数据",
133
+ "多币种下成本柱不可用,请切换其他指标": "多币种下成本柱不可用,请切换其他指标",
134
+ "万": "万",
135
+ "更新中": "更新中",
136
+ "更新检查失败": "更新检查失败",
137
+ "版本号不合法": "版本号不合法",
138
+ "该版本未发布": "该版本未发布",
139
+ "版本未变化": "版本未变化",
140
+ "未找到 dsh 命令": "未找到 dsh 命令"
122
141
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-token-dash",
3
- "version": "2.1.0",
3
+ "version": "2.3.0",
4
4
  "description": "DeepSeek Harness Token 看板:月度预算与订阅配额、账户余额、时间范围费用与真实 Tokens 明细,支持本地 JSON 导出 / 导入备份。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
@@ -66,4 +66,4 @@
66
66
  "devDependencies": {
67
67
  "playwright": "1.64.1"
68
68
  }
69
- }
69
+ }
package/src/core.js CHANGED
@@ -79,6 +79,25 @@ function dayStartTs(dayKey) {
79
79
  return new Date(year, month - 1, day).getTime()
80
80
  }
81
81
 
82
+ /**
83
+ * 枚举 [startKey, endKey] 内的全部本地日键(含两端)。
84
+ * 用 setDate 逐日推进而不是加 86400000,跨夏令时切换时日期才不会漂。
85
+ */
86
+ export function eachDayKey(startKey, endKey) {
87
+ const start = dayStartTs(startKey)
88
+ if (start === null || String(endKey) < String(startKey)) return []
89
+ const out = []
90
+ const cursor = new Date(start)
91
+ // 账本不可能超过 100 年;非法 key 时也靠这个上限兜底退出,避免死循环
92
+ for (let guard = 0; guard < 36600; guard += 1) {
93
+ const key = localDayKey(cursor.getTime())
94
+ if (key > endKey) break
95
+ out.push(key)
96
+ cursor.setDate(cursor.getDate() + 1)
97
+ }
98
+ return out
99
+ }
100
+
82
101
  /**
83
102
  * 旧计价模型的成本在入账时写死;定价修复后按日级 token 与当日 00:00 价目重算。
84
103
  * 日级聚合没有单条记录时间,峰谷只能按 00:00(闲时)代表,结果属于估算。
@@ -346,6 +365,54 @@ export function stampProviderKinds(state, snapshots) {
346
365
  return changed
347
366
  }
348
367
 
368
+ /** 日点数超过这个值就切「按月」桶:柱数稳定在 12 上下,避免柱子被压成线。 */
369
+ const MONTHLY_GRAIN_THRESHOLD = 60
370
+
371
+ /**
372
+ * 日序列超过阈值时按月合并:柱数稳定在 12 上下,避免柱子被压成线。
373
+ * 只做加法,口径与日序列完全一致;命中率按当月总量重算,不是日命中率的平均。
374
+ */
375
+ export function buildMonthlySeries(series) {
376
+ if (!Array.isArray(series) || series.length <= MONTHLY_GRAIN_THRESHOLD) return { grain: 'day', series }
377
+ const byMonth = new Map()
378
+ for (const point of series) {
379
+ const month = String(point.dayKey).slice(0, 7)
380
+ let entry = byMonth.get(month)
381
+ if (entry === undefined) {
382
+ entry = {
383
+ dayKey: month,
384
+ cost: {},
385
+ requests: 0,
386
+ input: 0,
387
+ cacheRead: 0,
388
+ cacheWrite: 0,
389
+ output: 0,
390
+ tokens: 0,
391
+ hitRate: null,
392
+ }
393
+ byMonth.set(month, entry)
394
+ }
395
+ entry.requests += point.requests
396
+ entry.input += point.input
397
+ entry.cacheRead += point.cacheRead
398
+ entry.cacheWrite += point.cacheWrite
399
+ entry.output += point.output
400
+ entry.tokens += point.tokens
401
+ for (const [currency, bucket] of Object.entries(point.cost)) {
402
+ const target = (entry.cost[currency] ??= { cost: 0, requests: 0 })
403
+ target.cost += bucket.cost
404
+ target.requests += bucket.requests
405
+ }
406
+ }
407
+ const merged = [...byMonth.values()]
408
+ for (const entry of merged) {
409
+ for (const bucket of Object.values(entry.cost)) bucket.cost = round2(bucket.cost)
410
+ const denominator = entry.input + entry.cacheRead + entry.cacheWrite
411
+ entry.hitRate = denominator > 0 ? entry.cacheRead / denominator : null
412
+ }
413
+ return { grain: 'month', series: merged }
414
+ }
415
+
349
416
  /**
350
417
  * Range-only aggregation for P2. Unlike buildSummary this never adds
351
418
  * "configured but unused" default rows, and it does not touch month budgets.
@@ -371,7 +438,26 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
371
438
  }
372
439
  const models = new Map()
373
440
  const totals = {}
374
- const add = (providerId, modelId, row) => {
441
+ // 逐日点:口径与 P3 两格卡一致——cost 只累 billable 行,其余字段累全部行(含订阅)
442
+ const points = new Map()
443
+ const pointOf = (dayKey) => {
444
+ const existing = points.get(dayKey)
445
+ if (existing !== undefined) return existing
446
+ const point = {
447
+ dayKey,
448
+ cost: {},
449
+ requests: 0,
450
+ input: 0,
451
+ cacheRead: 0,
452
+ cacheWrite: 0,
453
+ output: 0,
454
+ tokens: 0,
455
+ hitRate: null,
456
+ }
457
+ points.set(dayKey, point)
458
+ return point
459
+ }
460
+ const add = (providerId, modelId, row, point) => {
375
461
  if (hidden.has(providerId)) return
376
462
  const meta = info.get(providerId)
377
463
  const kind = resolveProviderKind(state, prefs, providerId, meta)
@@ -409,10 +495,23 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
409
495
  entry.currency = currency
410
496
  entry.currencySource = currencySourceOf(prefs, providerId, meta)
411
497
  models.set(key, entry)
498
+ const rowTokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
499
+ point.requests += num(row.requests)
500
+ point.input += num(row.input)
501
+ point.cacheRead += num(row.cacheRead)
502
+ point.cacheWrite += num(row.cacheWrite)
503
+ point.output += num(row.output)
504
+ point.tokens += rowTokens
505
+ if (billable) {
506
+ const bucket = (point.cost[currency] ??= { cost: 0, requests: 0 })
507
+ bucket.cost += num(row.cost)
508
+ bucket.requests += num(row.requests)
509
+ }
412
510
  }
413
511
 
414
512
  for (const dayKey of dayKeys) {
415
513
  if (dayKey < startKey || dayKey > todayKey) continue
514
+ const point = pointOf(dayKey)
416
515
  const bucket = state.days[dayKey]
417
516
  const providers = bucket.providers ?? { unknown: { models: bucket.models ?? {} } }
418
517
  for (const [rawProvider, providerBucket] of Object.entries(providers)) {
@@ -420,12 +519,12 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
420
519
  if (providerId === 'unknown') {
421
520
  for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
422
521
  const owner = providerFromModel(rawModel)
423
- if (owner !== null) add(owner, normalizeModel(rawModel), row)
522
+ if (owner !== null) add(owner, normalizeModel(rawModel), row, point)
424
523
  }
425
524
  continue
426
525
  }
427
526
  for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
428
- add(providerId, normalizeModel(rawModel), row)
527
+ add(providerId, normalizeModel(rawModel), row, point)
429
528
  }
430
529
  }
431
530
  }
@@ -491,6 +590,16 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
491
590
  ? total.cacheRead / (total.input + total.cacheRead + total.cacheWrite)
492
591
  : null
493
592
 
593
+ // 等距连续:窗口内没有数据的日补零,柱距才不会塌;hitRate 留 null 表示「无数据」而不是 0%
594
+ const daySeries = eachDayKey(startKey, todayKey).map((dayKey) => {
595
+ const point = pointOf(dayKey)
596
+ for (const bucket of Object.values(point.cost)) bucket.cost = round2(bucket.cost)
597
+ const denominator = point.input + point.cacheRead + point.cacheWrite
598
+ point.hitRate = denominator > 0 ? point.cacheRead / denominator : null
599
+ return point
600
+ })
601
+ const { grain, series } = buildMonthlySeries(daySeries)
602
+
494
603
  return {
495
604
  range: selected,
496
605
  startAt: dayStartTs(startKey) ?? now,
@@ -500,6 +609,8 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
500
609
  totals,
501
610
  total,
502
611
  models: rows,
612
+ series,
613
+ grain,
503
614
  }
504
615
  }
505
616