dsh-token-dash 0.0.0-stage → 1.0.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/src/core.js ADDED
@@ -0,0 +1,399 @@
1
+ /**
2
+ * Pure aggregation: day/month keys, provider/model buckets, budgets, currencies.
3
+ * No file or clock reads; `now` is injected.
4
+ */
5
+ import { priceFor } from './pricing.js'
6
+ import {
7
+ canBeSubscription,
8
+ DEFAULT_MODELS,
9
+ modelLabel,
10
+ normalizeModel,
11
+ normalizeProvider,
12
+ providerCurrency,
13
+ providerFromModel,
14
+ providerLabel,
15
+ } from './providers.js'
16
+
17
+ export function num(value) {
18
+ return typeof value === 'number' && Number.isFinite(value) && value > 0 ? value : 0
19
+ }
20
+
21
+ export function localDayKey(ts) {
22
+ const d = new Date(ts)
23
+ const y = d.getFullYear()
24
+ const m = String(d.getMonth() + 1).padStart(2, '0')
25
+ const day = String(d.getDate()).padStart(2, '0')
26
+ return `${y}-${m}-${day}`
27
+ }
28
+
29
+ export function localMonthKey(ts) {
30
+ return localDayKey(ts).slice(0, 7)
31
+ }
32
+
33
+ /** Kept for compatibility; priceFor handles peak/off-peak internally. */
34
+ export function isPeak(ts) {
35
+ const hour = new Date(ts + 8 * 60 * 60 * 1000).getUTCHours()
36
+ return (hour >= 9 && hour < 12) || (hour >= 14 && hour < 18)
37
+ }
38
+
39
+ export { normalizeProvider, providerLabel, normalizeModel, priceFor }
40
+ export const displayModel = modelLabel
41
+
42
+ export function priceForRecord(provider, model, ts) {
43
+ return priceFor(provider, model, ts)
44
+ }
45
+
46
+ /** Undefined price returns 0; the caller marks `priced=false`. */
47
+ export function costOf(record) {
48
+ const price = priceFor(record.provider ?? 'unknown', record.model, record.ts)
49
+ if (price === null) return 0
50
+ return (
51
+ (num(record.input) * price.input +
52
+ num(record.cacheRead) * price.cacheRead +
53
+ num(record.cacheWrite) * price.cacheWrite +
54
+ num(record.output) * price.output) /
55
+ 1e6
56
+ )
57
+ }
58
+
59
+ export function emptyState() {
60
+ return { version: 1, days: {}, watermarks: {}, headers: {}, currentProvider: null }
61
+ }
62
+
63
+ function dayBucket(state, dayKey) {
64
+ state.days[dayKey] ??= { models: {} }
65
+ return state.days[dayKey]
66
+ }
67
+
68
+ /** Only attribute old unknown rows when a model appeared under exactly one provider. */
69
+ export function reattributeUnknown(state, providerByModel) {
70
+ for (const bucket of Object.values(state.days ?? {})) {
71
+ const unknown = bucket?.providers?.unknown?.models
72
+ if (unknown === undefined) continue
73
+ for (const [model, row] of Object.entries(unknown)) {
74
+ const providers = providerByModel.get(model)
75
+ if (providers === undefined || providers.size !== 1) continue
76
+ const provider = normalizeProvider([...providers][0])
77
+ if (provider === 'unknown') continue
78
+ const targetBucket = (bucket.providers[provider] ??= { models: {} })
79
+ const target = targetBucket.models[model]
80
+ if (target === undefined) {
81
+ targetBucket.models[model] = row
82
+ } else {
83
+ target.input += num(row.input)
84
+ target.cacheRead += num(row.cacheRead)
85
+ target.cacheWrite += num(row.cacheWrite)
86
+ target.output += num(row.output)
87
+ target.requests += num(row.requests)
88
+ target.cost += num(row.cost)
89
+ target.priced = target.priced !== false && row.priced !== false
90
+ }
91
+ delete unknown[model]
92
+ }
93
+ if (Object.keys(unknown).length === 0) delete bucket.providers.unknown
94
+ }
95
+ }
96
+
97
+ export function addRecord(state, record) {
98
+ const day = localDayKey(record.ts)
99
+ const bucket = dayBucket(state, day)
100
+ if (bucket.providers === undefined) {
101
+ bucket.providers = { unknown: { models: bucket.models ?? {} } }
102
+ delete bucket.models
103
+ }
104
+ const provider = normalizeProvider(record.provider)
105
+ const providerBucket = (bucket.providers[provider] ??= { models: {} })
106
+ const model = normalizeModel(record.model)
107
+ const row = (providerBucket.models[model] ??= {
108
+ input: 0,
109
+ cacheRead: 0,
110
+ cacheWrite: 0,
111
+ output: 0,
112
+ requests: 0,
113
+ cost: 0,
114
+ priced: true,
115
+ })
116
+ row.input += num(record.input)
117
+ row.cacheRead += num(record.cacheRead)
118
+ row.cacheWrite += num(record.cacheWrite)
119
+ row.output += num(record.output)
120
+ row.requests += 1
121
+ const price = priceFor(provider, model, record.ts)
122
+ if (price === null) row.priced = false
123
+ row.cost += costOf({ ...record, provider })
124
+ state.currentProvider = provider
125
+ }
126
+
127
+ function budgetFor(prefs, providerId, currency) {
128
+ const map = prefs?.budgets?.[providerId]
129
+ let amount = num(map?.amount)
130
+ let state = 'unset'
131
+ if (map?.amount === 0) state = 'unset'
132
+ if (amount <= 0 && providerId === 'deepseek-official' && num(prefs?.budget?.amount) > 0) {
133
+ amount = num(prefs.budget.amount)
134
+ }
135
+ if (map?.amount === 0) amount = 0
136
+ return {
137
+ amount,
138
+ used: 0,
139
+ remaining: 0,
140
+ percent: 0,
141
+ state,
142
+ currency: map?.currency === 'USD' ? 'USD' : (currency ?? 'CNY'),
143
+ }
144
+ }
145
+
146
+ function providerEmpty(providerId) {
147
+ return {
148
+ id: providerId,
149
+ name: providerLabel(providerId),
150
+ kind: 'api',
151
+ canSubscribe: canBeSubscription(providerId),
152
+ currency: providerCurrency(providerId),
153
+ usage: { todayTokens: 0, monthTokens: 0, todayCost: 0, monthCost: 0, requests: 0 },
154
+ models: [],
155
+ }
156
+ }
157
+
158
+ function normalizeProviderInfo(input) {
159
+ if (Array.isArray(input)) return input
160
+ if (input === null || typeof input !== 'object') return []
161
+ return Object.entries(input).map(([id, value]) => ({ id, ...(value ?? {}) }))
162
+ }
163
+
164
+ export function buildSummary(state, prefs, now, providerInfoInput) {
165
+ const month = localMonthKey(now)
166
+ const todayKey = localDayKey(now)
167
+ const providerMap = new Map()
168
+ const modelsMap = new Map()
169
+ const providerInfo = normalizeProviderInfo(providerInfoInput)
170
+ // billingModes[id] === 'hide' 的 provider 整体不出现在 VM(卡片、费用表、用量表)。
171
+ const hidden = new Set(
172
+ Object.entries(prefs?.billingModes ?? {})
173
+ .filter(([, mode]) => mode === 'hide')
174
+ .map(([id]) => normalizeProvider(id)),
175
+ )
176
+
177
+ for (const info of providerInfo) {
178
+ const id = normalizeProvider(info.id ?? info.provider)
179
+ if (id === 'unknown' || hidden.has(id)) continue
180
+ const base = providerMap.get(id) ?? providerEmpty(id)
181
+ providerMap.set(id, {
182
+ ...base,
183
+ ...info,
184
+ id,
185
+ name: info.name ?? providerLabel(id),
186
+ kind: info.kind === 'subscription' || (info.kind === undefined && Array.isArray(info.plans) && info.plans.length > 0)
187
+ ? 'subscription'
188
+ : 'api',
189
+ canSubscribe: canBeSubscription(id),
190
+ currency: info.currency === 'USD' ? 'USD' : (info.currency === 'CNY' ? 'CNY' : providerCurrency(id)),
191
+ usage: { ...base.usage, ...(info.usage ?? {}) },
192
+ balance: info.balance ?? base.balance,
193
+ plans: info.plans ?? base.plans,
194
+ })
195
+ }
196
+
197
+ // #41/#42:unknown 行按模型名前缀视图层归因(不改 daily.json);models 与 provider.usage 均为当月口径(#42 回退跨月累计)
198
+ const accumulate = (providerId, modelId, row, isToday) => {
199
+ const provider = providerMap.get(providerId) ?? providerEmpty(providerId)
200
+ providerMap.set(providerId, provider)
201
+ const key = `${providerId}:${modelId}`
202
+ const entry = modelsMap.get(key) ?? {
203
+ name: modelId,
204
+ modelId,
205
+ providerId,
206
+ providerName: providerLabel(providerId),
207
+ displayName: modelLabel(modelId),
208
+ kind: provider.kind,
209
+ currency: provider.currency,
210
+ priced: true,
211
+ approximate: false,
212
+ requests: 0,
213
+ input: 0,
214
+ cacheRead: 0,
215
+ cacheWrite: 0,
216
+ output: 0,
217
+ cost: 0,
218
+ }
219
+ entry.requests += num(row.requests)
220
+ entry.input += num(row.input)
221
+ entry.cacheRead += num(row.cacheRead)
222
+ entry.cacheWrite += num(row.cacheWrite)
223
+ entry.output += num(row.output)
224
+ entry.cost += num(row.cost)
225
+ if (row.priced === false) entry.priced = false
226
+ const price = priceFor(providerId, modelId, now)
227
+ if (price?.approximate === true) entry.approximate = true
228
+ modelsMap.set(key, entry)
229
+ const tokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
230
+ provider.usage.monthTokens += tokens
231
+ provider.usage.monthCost += num(row.cost)
232
+ provider.usage.requests += num(row.requests)
233
+ if (isToday) {
234
+ provider.usage.todayTokens += tokens
235
+ provider.usage.todayCost += num(row.cost)
236
+ }
237
+ provider.models.push(entry.modelId)
238
+ }
239
+
240
+ for (const [dayKey, bucket] of Object.entries(state.days ?? {})) {
241
+ if (!dayKey.startsWith(`${month}-`)) continue
242
+ const isToday = dayKey === todayKey
243
+ const providers = bucket.providers ?? { unknown: { models: bucket.models ?? {} } }
244
+ for (const [rawProvider, providerBucket] of Object.entries(providers)) {
245
+ const providerId = normalizeProvider(rawProvider)
246
+ if (providerId === 'unknown') {
247
+ for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
248
+ const owner = providerFromModel(rawModel)
249
+ if (owner === null || hidden.has(owner)) continue
250
+ accumulate(owner, normalizeModel(rawModel), row, isToday)
251
+ }
252
+ continue
253
+ }
254
+ if (hidden.has(providerId)) continue
255
+ for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
256
+ accumulate(providerId, normalizeModel(rawModel), row, isToday)
257
+ }
258
+ }
259
+ }
260
+
261
+ // #44/#45:已配置 provider 本月无真实模型行时补默认模型行(数值 0)——"配置即可见",
262
+ // 与严格本月口径兼容(不引入跨月数据);真实行优先不重复补;
263
+ // '-' 占位(中转无默认模型)在该 provider 出现任何真实模型行后不再补
264
+ for (const info of providerInfo) {
265
+ const id = normalizeProvider(info.id ?? info.provider)
266
+ if (id === 'unknown' || hidden.has(id)) continue
267
+ const fallbackModel = DEFAULT_MODELS[id]
268
+ if (fallbackModel === undefined) continue
269
+ if (fallbackModel === '-' && [...modelsMap.keys()].some((k) => k.startsWith(`${id}:`))) continue
270
+ const key = `${id}:${fallbackModel}`
271
+ if (modelsMap.has(key)) continue
272
+ const provider = providerMap.get(id)
273
+ modelsMap.set(key, {
274
+ name: fallbackModel,
275
+ modelId: fallbackModel,
276
+ providerId: id,
277
+ providerName: providerLabel(id),
278
+ displayName: modelLabel(fallbackModel),
279
+ kind: provider?.kind === 'subscription' ? 'subscription' : 'api',
280
+ currency: provider?.currency ?? providerCurrency(id),
281
+ priced: true,
282
+ approximate: false,
283
+ requests: 0,
284
+ input: 0,
285
+ cacheRead: 0,
286
+ cacheWrite: 0,
287
+ output: 0,
288
+ cost: 0,
289
+ })
290
+ }
291
+
292
+ const models = [...modelsMap.values()].map((entry) => {
293
+ const tokens = entry.input + entry.cacheRead + entry.cacheWrite + entry.output
294
+ entry.tokens = { input: entry.input, cacheRead: entry.cacheRead, output: entry.output, total: tokens }
295
+ entry.hitRate = entry.input + entry.cacheWrite + entry.cacheRead > 0
296
+ ? entry.cacheRead / (entry.input + entry.cacheWrite + entry.cacheRead)
297
+ : null
298
+ entry.cost = round2(entry.cost)
299
+ entry.share = 0
300
+ return entry
301
+ })
302
+ models.sort((a, b) => b.cost - a.cost)
303
+
304
+ const providers = [...providerMap.values()].map((provider) => {
305
+ const budget = provider.kind === 'api' ? budgetFor(prefs, provider.id, provider.currency) : undefined
306
+ if (budget !== undefined) {
307
+ budget.used = round2(provider.usage.monthCost)
308
+ budget.remaining = round2(Math.max(0, budget.amount - budget.used))
309
+ budget.percent = budget.amount > 0 ? Math.min(9.99, budget.used / budget.amount) : 0
310
+ budget.state = budget.amount <= 0 ? 'unset' : budget.percent >= 1 ? 'over' : budget.percent >= 0.8 ? 'warn' : 'ok'
311
+ }
312
+ provider.usage.todayCost = round2(provider.usage.todayCost)
313
+ provider.usage.monthCost = round2(provider.usage.monthCost)
314
+ return { ...provider, budget }
315
+ })
316
+ providers.sort((a, b) => {
317
+ if (a.id === state.currentProvider) return -1
318
+ if (b.id === state.currentProvider) return 1
319
+ return b.usage.todayCost - a.usage.todayCost
320
+ })
321
+
322
+ const modelsByCurrency = new Map()
323
+ for (const row of models) {
324
+ if (row.kind !== 'api') continue
325
+ const bucket = modelsByCurrency.get(row.currency) ?? { total: 0 }
326
+ bucket.total += row.cost
327
+ modelsByCurrency.set(row.currency, bucket)
328
+ }
329
+ for (const row of models) {
330
+ if (row.kind !== 'api') continue
331
+ const total = modelsByCurrency.get(row.currency)?.total ?? 0
332
+ row.share = total > 0 ? Math.min(1, row.cost / total) : 0
333
+ }
334
+
335
+ const apiTotals = {}
336
+ for (const provider of providers) {
337
+ if (provider.kind !== 'api') continue
338
+ const currency = provider.currency
339
+ const total = apiTotals[currency] ?? { today: 0, month: 0, budget: 0, remaining: 0 }
340
+ total.today += provider.usage.todayCost
341
+ total.month += provider.usage.monthCost
342
+ total.budget += provider.budget?.amount ?? 0
343
+ total.remaining += provider.budget?.remaining ?? 0
344
+ apiTotals[currency] = total
345
+ }
346
+ for (const total of Object.values(apiTotals)) {
347
+ total.today = round2(total.today)
348
+ total.month = round2(total.month)
349
+ total.budget = round2(total.budget)
350
+ total.remaining = round2(total.remaining)
351
+ }
352
+
353
+ const totalCost = round2(models.reduce((sum, row) => sum + (row.kind === 'api' ? row.cost : 0), 0))
354
+ const unpricedModels = models.filter((row) => row.priced === false).map((row) => `${row.providerId}:${row.modelId}`)
355
+ const totals = models.reduce((out, row) => ({
356
+ input: out.input + row.input,
357
+ cacheRead: out.cacheRead + row.cacheRead,
358
+ cacheWrite: out.cacheWrite + row.cacheWrite,
359
+ output: out.output + row.output,
360
+ requests: out.requests + row.requests,
361
+ }), { input: 0, cacheRead: 0, cacheWrite: 0, output: 0, requests: 0 })
362
+ const totalTokens = totals.input + totals.cacheRead + totals.cacheWrite + totals.output
363
+ const hitRate = totals.input + totals.cacheWrite + totals.cacheRead > 0
364
+ ? totals.cacheRead / (totals.input + totals.cacheWrite + totals.cacheRead)
365
+ : null
366
+ const today = providers.reduce((sum, provider) => ({
367
+ tokens: sum.tokens + provider.usage.todayTokens,
368
+ cost: sum.cost + provider.usage.todayCost,
369
+ requests: sum.requests + provider.usage.requests,
370
+ }), { tokens: 0, cost: 0, requests: 0 })
371
+ const current = state.currentProvider ?? providers[0]?.id ?? null
372
+
373
+ return {
374
+ month,
375
+ tokens: {
376
+ input: totals.input,
377
+ cacheRead: totals.cacheRead,
378
+ cacheWrite: totals.cacheWrite,
379
+ output: totals.output,
380
+ total: totalTokens,
381
+ hitRate,
382
+ },
383
+ cost: { estimated: totalCost, currency: 'CNY', unpricedModels },
384
+ today: { tokens: today.tokens, cost: round2(today.cost), requests: today.requests },
385
+ requests: { month: totals.requests, today: today.requests },
386
+ providers,
387
+ apiTotals,
388
+ currentProviderId: current,
389
+ breakdown: { models },
390
+ showBalance: prefs?.showBalance !== false,
391
+ showMonthTokens: prefs?.showMonthTokens !== false,
392
+ updatedAt: now,
393
+ stale: false,
394
+ }
395
+ }
396
+
397
+ export function round2(value) {
398
+ return Math.round((Number(value) + Number.EPSILON) * 100) / 100
399
+ }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Diagnostic JSONL log: module prefixes, redaction, rotation and export.
3
+ * Never writes credentials, prompts, bodies or full URLs.
4
+ */
5
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs'
6
+ import { join } from 'node:path'
7
+
8
+ export const MAX_FILE = 5 * 1024 * 1024
9
+ export const MAX_EXPORT = 10 * 1024 * 1024
10
+ const KEEP_FILES = 3
11
+
12
+ const SECRET_PATTERNS = [
13
+ /sk-[a-zA-Z0-9_-]{8,}/g,
14
+ /Bearer\s+[^\s"']+/gi,
15
+ /("?(?:api[_-]?key|authorization|cookie|token|secret)"?\s*[:=]\s*")[^"]+"/gi,
16
+ ]
17
+
18
+ export function redact(value) {
19
+ let text = String(value ?? '')
20
+ for (const pattern of SECRET_PATTERNS) text = text.replace(pattern, (match, prefix) => prefix === undefined ? '[REDACTED]' : `${prefix}[REDACTED]"`)
21
+ return text
22
+ }
23
+
24
+ export function hasSecret(value) {
25
+ return SECRET_PATTERNS.some((pattern) => {
26
+ pattern.lastIndex = 0
27
+ return pattern.test(String(value ?? ''))
28
+ })
29
+ }
30
+
31
+ function pad(value) {
32
+ return String(value).padStart(2, '0')
33
+ }
34
+
35
+ export function logFileFor(ts, dir) {
36
+ const d = new Date(ts)
37
+ return join(dir, `dsh-token-dash-${d.getFullYear()}${pad(d.getMonth() + 1)}${pad(d.getDate())}.log`)
38
+ }
39
+
40
+ function rotate(file) {
41
+ try {
42
+ if (!existsSync(file) || statSync(file).size < MAX_FILE) return
43
+ const base = file.replace(/\.log$/, '')
44
+ for (let index = KEEP_FILES - 1; index >= 1; index -= 1) {
45
+ const from = index === 1 ? file : `${base}.${index - 1}.log`
46
+ const to = `${base}.${index}.log`
47
+ if (existsSync(from)) writeFileSync(to, readFileSync(from))
48
+ }
49
+ writeFileSync(file, '')
50
+ } catch {
51
+ // logging must never break the plugin
52
+ }
53
+ }
54
+
55
+ export function createLogger({ dir, level = 'info', version = '0.2.0', dshVersion = '0.2.1-rc.5' } = {}) {
56
+ if (dir === undefined) return { log() {}, info() {}, warn() {}, error() {}, file: null }
57
+ mkdirSync(dir, { recursive: true })
58
+ const file = logFileFor(Date.now(), dir)
59
+ const header = {
60
+ type: 'header',
61
+ plugin: 'dsh-token-dash',
62
+ version,
63
+ dshVersion,
64
+ platform: process.platform,
65
+ exportedAt: new Date().toISOString(),
66
+ }
67
+ let wroteHeader = false
68
+ const write = (module, event, fields = {}, levelName = 'info') => {
69
+ if (level !== 'debug' && levelName === 'debug') return
70
+ try {
71
+ rotate(file)
72
+ if (!wroteHeader) {
73
+ appendFileSync(file, `${JSON.stringify(header)}\n`, 'utf8')
74
+ wroteHeader = true
75
+ }
76
+ const line = {
77
+ ts: new Date().toISOString(),
78
+ level: levelName,
79
+ module,
80
+ event,
81
+ ...Object.fromEntries(Object.entries(fields).map(([key, value]) => [key, typeof value === 'string' ? redact(value) : value])),
82
+ }
83
+ appendFileSync(file, `${JSON.stringify(line)}\n`, 'utf8')
84
+ } catch {
85
+ // ignore
86
+ }
87
+ }
88
+ return {
89
+ file,
90
+ log: write,
91
+ info: (module, event, fields) => write(module, event, fields, 'info'),
92
+ warn: (module, event, fields) => write(module, event, fields, 'warn'),
93
+ error: (module, event, fields) => write(module, event, fields, 'error'),
94
+ debug: (module, event, fields) => write(module, event, fields, 'debug'),
95
+ }
96
+ }
97
+
98
+ export function exportLog(dir, logger) {
99
+ const file = logger?.file ?? (dir === undefined ? null : logFileFor(Date.now(), dir))
100
+ if (file === null || !existsSync(file)) {
101
+ return { file, content: `${JSON.stringify({ type: 'header', plugin: 'dsh-token-dash', exportedAt: new Date().toISOString() })}\n`, bytes: 0 }
102
+ }
103
+ let content = readFileSync(file, 'utf8')
104
+ if (Buffer.byteLength(content, 'utf8') > MAX_EXPORT) content = content.slice(-MAX_EXPORT)
105
+ const redacted = redact(content)
106
+ if (hasSecret(content)) return { file, content: redacted, bytes: Buffer.byteLength(redacted, 'utf8'), redacted: true }
107
+ return { file, content, bytes: Buffer.byteLength(content, 'utf8'), redacted: false }
108
+ }
109
+
110
+ export function clearLog(dir, logger) {
111
+ const file = logger?.file ?? (dir === undefined ? null : logFileFor(Date.now(), dir))
112
+ if (file !== null && existsSync(file)) writeFileSync(file, '')
113
+ }