dsh-cost-meter 1.8.19 → 1.8.21

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.
@@ -0,0 +1,99 @@
1
+ /** Billing by recorded execution step. No message text is classified or retained. */
2
+ import { statSync } from 'node:fs'
3
+ import { join } from 'node:path'
4
+ import { setImmediate } from 'node:timers/promises'
5
+ import { resolveDshHome } from '@deepseek-ai/dsh-home-paths'
6
+ import { listSessionLogs, iterateSessionRecords, replaySessionRecords } from './backfill.js'
7
+ import { sessionUsageRecords, costFromSamples } from './turn-cost.js'
8
+ import { sessionCostIds } from './session-tree.js'
9
+ import { nativeSearchRecordsFor } from './native-search-history.js'
10
+
11
+ const caches = new WeakMap()
12
+ const valid = n => Number.isSafeInteger(n) && n >= 0
13
+ const keyOf = (turn, step) => JSON.stringify([turn, step])
14
+
15
+ export async function scanStepTools(records) {
16
+ const steps = new Map(), seen = new Set()
17
+ let turn = null, step = null, createdAt = 0, count = 0
18
+ for await (const event of records) {
19
+ if (++count > 500000) throw new Error('Session exceeds the step limit')
20
+ if (count % 2048 === 0) await setImmediate()
21
+ if (event.type === 'session') { createdAt = Number(event.createdAt) || 0; continue }
22
+ if (createdAt > 0 && event.time > 0 && event.time < createdAt) continue
23
+ const d = event.data ?? {}
24
+ if (event.type === 'turn/start') { turn = valid(d.turn) ? d.turn : null; step = null }
25
+ if (event.type === 'step/start' || event.type === 'assistant/message') { turn = valid(d.turn) ? d.turn : turn; step = valid(d.step) ? d.step : null }
26
+ if (['tool/call', 'tool/code-dispatch-start', 'tool/ptc-dispatch-start'].includes(event.type)) {
27
+ const t = valid(d.turn) ? d.turn : turn, s = valid(d.step) ? d.step : step
28
+ const key = keyOf(t, s), id = String(d.callId ?? d.subCallId ?? event.seq)
29
+ if (!seen.has(key + ':' + id)) {
30
+ seen.add(key + ':' + id)
31
+ const names = steps.get(key) ?? new Set()
32
+ if (typeof d.name === 'string' && d.name) names.add(d.name.slice(0, 240))
33
+ steps.set(key, names)
34
+ }
35
+ }
36
+ if (event.type === 'turn/end') { turn = null; step = null }
37
+ }
38
+ return new Map([...steps].map(([key, names]) => [key, [...names].sort()]))
39
+ }
40
+
41
+ async function stepTools(ctx, id) {
42
+ const session = ctx?.get?.('sessions')?.get?.(id), live = session?.snapshotEvents?.()
43
+ let key, records
44
+ if (Array.isArray(live)) {
45
+ key = `${id}:${session.header?.createdAt ?? 0}:${live.length}:${live.at(-1)?.seq}:${live.at(-1)?.time}`
46
+ records = [{ type: 'session', createdAt: session.header?.createdAt ?? 0 }, ...live]
47
+ } else {
48
+ const path = listSessionLogs(join(resolveDshHome(), 'sessions'), new Set([id]))[0]
49
+ if (!path) return new Map()
50
+ const info = statSync(path); key = `${path}:${info.size}:${info.mtimeMs}`; records = iterateSessionRecords(path)
51
+ }
52
+ const owner = ctx && typeof ctx === 'object' ? ctx : null
53
+ if (!owner) return scanStepTools(records)
54
+ if (!caches.has(owner)) caches.set(owner, new Map())
55
+ const cache = caches.get(owner), prior = cache.get(id)
56
+ if (prior?.key === key && (!live || Date.now() - prior.at < 1500)) return prior.value
57
+ const value = scanStepTools(records); cache.set(id, { key, at: Date.now(), value })
58
+ if (cache.size > 8) cache.delete(cache.keys().next().value)
59
+ value.catch(() => { if (cache.get(id)?.value === value) cache.delete(id) })
60
+ return value
61
+ }
62
+
63
+ export async function getSessionTrajectory(ledger, ctx, query) {
64
+ if (!query || typeof query.sessionId !== 'string' || !query.sessionId || query.sessionId.length > 512) throw new Error('invalid step billing session')
65
+ const offset = query.offset ?? 0, basis = query.basis ?? 'total'
66
+ if (!['api', 'plan', 'total'].includes(basis)) throw new Error('invalid step billing basis')
67
+ if (!valid(offset) || offset > 1e7) throw new Error('invalid step billing offset')
68
+ const ids = await sessionCostIds(ledger, ctx, query.sessionId), steps = [], groups = new Map()
69
+ let cost = 0, apiCost = 0
70
+ for (const id of ids) {
71
+ const [tools, records, native] = await Promise.all([stepTools(ctx, id), sessionUsageRecords(ctx, id), nativeSearchRecordsFor(ledger.path, id)])
72
+ const samples = replaySessionRecords([...records, ...native], ledger.config, null, true).samples.filter(row => !row.seed)
73
+ const grouped = new Map()
74
+ for (const sample of samples) {
75
+ // Unknown step identities cannot safely be merged with neighbouring steps.
76
+ const key = JSON.stringify([sample.kind, sample.turn, sample.step, sample.step == null ? sample.logSeq ?? sample.atMs : null])
77
+ if (!grouped.has(key)) grouped.set(key, [])
78
+ grouped.get(key).push(sample)
79
+ }
80
+ for (const [key, samples] of grouped) {
81
+ const detail = costFromSamples(samples, ledger.config), first = detail.calls[0]
82
+ const names = first.kind === 'model' && first.step != null ? tools.get(keyOf(first.turn, first.step)) ?? [] : []
83
+ const row = { key: id + ':' + key, sessionId: id, turn: first.turn, step: first.step, kind: first.kind, tools: names, atMs: first.atMs,
84
+ cost: detail.cost, apiCost: detail.apiCost, calls: detail.calls.length, unpriced: detail.calls.some(call => !call.priced && (basis === 'total' || (basis === 'plan' ? call.plan : !call.plan))), rows: detail.rows }
85
+ steps.push(row); cost += row.cost; apiCost += row.apiCost
86
+ // A multi-tool step is a single group; never multiply its model cost by tool count.
87
+ const groupKey = JSON.stringify([row.kind, names]), group = groups.get(groupKey) ?? { key: groupKey, kind: row.kind, tools: names, steps: 0, cost: 0, apiCost: 0, unpriced: false }
88
+ group.steps++; group.cost += row.cost; group.apiCost += row.apiCost; group.unpriced ||= row.unpriced
89
+ groups.set(groupKey, group)
90
+ }
91
+ }
92
+ steps.sort((a, b) => a.atMs - b.atMs)
93
+ const amount = row => basis === 'api' ? row.apiCost : basis === 'plan' ? Math.max(0, row.cost - row.apiCost) : row.cost
94
+ const ranked = [...steps].sort((a, b) => amount(b) - amount(a))
95
+ const shares = ranked.slice(0, 20).map(({ key, sessionId, turn, step, kind, tools, cost, apiCost, unpriced }) => ({ key, sessionId, turn, step, kind, tools, cost, apiCost, unpriced, other: false, count: 1 }))
96
+ if (ranked.length > 20) shares.push({ key: 'other', sessionId: '', turn: null, step: null, kind: 'other', tools: [], other: true, count: ranked.length - 20,
97
+ cost: ranked.slice(20).reduce((n, row) => n + row.cost, 0), apiCost: ranked.slice(20).reduce((n, row) => n + row.apiCost, 0), unpriced: ranked.slice(20).some(row => row.unpriced) })
98
+ return { cost, apiCost, shares, totalSteps: steps.length, offset, steps: steps.slice(offset, offset + 100), groups: [...groups.values()] }
99
+ }
package/lib/turn-cost.js CHANGED
@@ -42,6 +42,7 @@ export function costFromSamples(samples, config) {
42
42
  row.tokens += tokens; row.cost += tokens * rate / 1e6
43
43
  parts.set(key, row)
44
44
  }
45
+ call.logSeq = sample.logSeq ?? null
45
46
  calls.push(call)
46
47
  }
47
48
  calls.sort((a, b) => a.atMs - b.atMs)
@@ -54,7 +55,7 @@ export async function getTurnCost(ledger, ctx, sessionId, startSeq, endSeq) {
54
55
  return turnCostFromRecords(records, ledger.config, startSeq, endSeq, await nativeSearchRecordsFor(ledger.path, sessionId))
55
56
  }
56
57
 
57
- async function sessionUsageRecords(ctx, sessionId) {
58
+ export async function sessionUsageRecords(ctx, sessionId) {
58
59
  const session = ctx?.get?.('sessions')?.get?.(sessionId)
59
60
  const live = session?.snapshotEvents?.()
60
61
  if (Array.isArray(live)) return [{ type: 'session', id: sessionId, createdAt: session.header?.createdAt ?? 0 }, ...live]
@@ -82,7 +82,7 @@ export const billingStatisticsSchema = z.object({
82
82
  sessionCount: num, offset: num, unassignedCost: num, unmodeledCost: num,
83
83
  })
84
84
  export const sessionBillingSchema = turnCostSchema.extend({ totalCalls: num, offset: num, recorded: statisticsBuckets,
85
- calls: z.array(turnCostSchema.shape.calls.element.extend({ sessionId: z.string().default(''), turn: num.nullable(), step: num.nullable() })),
85
+ calls: z.array(turnCostSchema.shape.calls.element.extend({ sessionId: z.string().default(''), turn: num.nullable(), step: num.nullable(), logSeq: num.nullable().default(null) })),
86
86
  agents: z.array(statisticsBuckets.extend({ id: z.string(), title: z.string() })).default([]),
87
87
  kinds: z.array(statisticsBuckets.extend({ kind: z.string(), unpriced: z.boolean() })),
88
88
  turns: z.array(statisticsBuckets.extend({ sessionId: z.string().default(''), turn: num.nullable(), unpriced: z.boolean() })),
@@ -95,6 +95,14 @@ export const turnInspectionSchema = z.object({ found: z.boolean(), turn: num, in
95
95
  tools: z.array(z.object({ seq: num, step: num.nullable(), name: z.string(), callId: z.string(), atMs: num, arguments: z.string(), result: z.string(), truncated: z.boolean(), status: z.enum(['pending', 'complete', 'error']) })) })
96
96
 
97
97
  export const contextCostsQuerySchema = z.object({ sessionId: z.string().min(1).max(512) })
98
+ export const trajectoryQuerySchema = contextCostsQuerySchema.extend({ basis: z.enum(['api', 'plan', 'total']).default('total'), offset: z.number().int().min(0).max(1e7).default(0) })
99
+ export const trajectorySchema = z.object({ cost: num, apiCost: num, totalSteps: num, offset: num,
100
+ shares: z.array(z.object({ key: z.string(), sessionId: z.string(), turn: num.nullable(), step: num.nullable(), kind: z.string(), tools: z.array(z.string()), cost: num, apiCost: num, unpriced: z.boolean(), other: z.boolean(), count: num })),
101
+ groups: z.array(z.object({ key: z.string(), kind: z.string(), tools: z.array(z.string()), steps: num, cost: num, apiCost: num, unpriced: z.boolean() })),
102
+ steps: z.array(z.object({ key: z.string(), sessionId: z.string(), turn: num.nullable(), step: num.nullable(), kind: z.string(), tools: z.array(z.string()), atMs: num, calls: num, cost: num, apiCost: num, unpriced: z.boolean(), rows: turnCostSchema.shape.rows })) })
103
+ export const callInspectionQuerySchema = z.object({ sessionId: z.string().min(1).max(512), seq: z.number().int().min(0), atMs: z.number().finite().positive(), offset: z.number().int().min(0).max(1e7).optional() })
104
+ export const callInspectionSchema = z.object({ found: z.boolean(), kind: z.string(), input: z.string(), injected: z.string(), skills: z.string(), precedingTools: z.string(), output: z.string(), reasoning: z.string(), truncated: z.boolean(),
105
+ tools: z.array(turnInspectionSchema.shape.tools.element.extend({ durationMs: num.nullable().default(null) })), totalTools: num, offset: num })
98
106
  const contextRateSchema = z.object(Object.fromEntries(['input', 'cacheRead', 'cacheWrite', 'output', 'reasoning'].map(key => [key, z.number().finite().nonnegative()])))
99
107
  export const contextCostsSchema = z.object({
100
108
  status: z.enum(['ready', 'unavailable', 'session-unavailable', 'meter-unavailable', 'route-unavailable']),
@@ -210,6 +218,7 @@ const configSchema = z.object({
210
218
  contextCostsPromptSeen: z.boolean().optional(),
211
219
  sidebarTodayMetric: z.enum(['cost', 'tokens']).optional(),
212
220
  // 「含 Plan 总额」全局开关(v1.6.0):开启后全部金额展示按总等值(cost)计。
221
+ statisticsBasis: z.enum(['auto', 'api', 'plan', 'total']).optional(),
213
222
  showTotalWithPlan: z.boolean().optional(),
214
223
  includeSubagentCost: z.boolean().optional(),
215
224
  codexQuotaEnabled: z.boolean().optional(),
@@ -772,6 +781,11 @@ export const TYPERT = {
772
781
  })),
773
782
  { id: 'dsh-cost-meter#costMeter/getTurnInspection', service: 'costMeter', namespace: 'costMeter', method: 'getTurnInspection', invocation: { kind: 'direct' },
774
783
  parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('TurnInspectionQuery', turnInspectionQuerySchema) }], result: strictCodec('TurnInspection', turnInspectionSchema) },
784
+ { id: 'dsh-cost-meter#costMeter/getCallInspection', service: 'costMeter', namespace: 'costMeter', method: 'getCallInspection', invocation: { kind: 'direct' },
785
+ parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('CallInspectionQuery', callInspectionQuerySchema) }], result: strictCodec('CallInspection', callInspectionSchema) },
786
+ ...[['getSessionTrajectory', 'Trajectory', trajectoryQuerySchema, trajectorySchema]].map(([method, name, query, schema]) => ({
787
+ id: 'dsh-cost-meter#costMeter/' + method, service: 'costMeter', namespace: 'costMeter', method, invocation: { kind: 'direct' },
788
+ parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec(name + 'Query', query) }], result: strictCodec(name, schema) })),
775
789
  { id: 'dsh-cost-meter#costMeter/getContextCosts', service: 'costMeter', namespace: 'costMeter', method: 'getContextCosts', invocation: { kind: 'direct' },
776
790
  parameters: [{ name: 'query', wire: 'query', source: 'json', codec: strictCodec('ContextCostsQuery', contextCostsQuerySchema) }], result: strictCodec('ContextCosts', contextCostsSchema) },
777
791
  {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-cost-meter",
3
- "version": "1.8.19",
3
+ "version": "1.8.21",
4
4
  "description": "DeepSeek Harness 会话费用统计插件:本会话成本、当日费用、历史记录与官方价格同步,支持多厂商多模型价格计费(内置 170+ 模型 ID 价格目录与自动匹配)、主流 Coding Plan 订阅额度查询与显示(11 家,含小米 MiMo Token Plan 控制台 Cookie 查询、SCNet Token Plan 本地 Credits 计量与火山方舟 Volcano Ark Coding Plan AK/SK 签名查询)、自定义 Provider 余额查询(可配任意 HTTP 端点)与余额进度条、峰谷计价时段显示与切换前弹窗/系统通知提醒(位置/提前量/类型可配),界面中英双语。Session cost tracking plugin for DeepSeek Harness: per-conversation cost, daily totals, history and official price sync, with multi-vendor model pricing (built-in 170+ model-ID catalog with auto-matching), Coding Plan quota queries & display for 11 vendors (incl. Xiaomi MiMo Token Plan via console cookie, local credits metering for the SCNet Token Plan and Volcano Ark Coding Plan via AK/SK signature), plan/API dual-track billing with per-1% & full-window Token Plan usage estimates, custom provider balance lookup (configurable HTTP endpoint) and balance progress bar, plus peak/off-peak pricing display with pre-switch popup & system-notification alerts (position / lead time / type configurable), in a bilingual (Chinese/English) UI.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -105,6 +105,8 @@
105
105
  "docs/context-costs-design.md",
106
106
  "docs/context-costs-preview.png",
107
107
  "docs/cost-share-overview.png",
108
+ "docs/call-detail-preview.png",
109
+ "docs/step-billing-preview.png",
108
110
  "docs/maintenance-review-2026-10-10.md"
109
111
  ],
110
112
  "dependencies": {