dsh-notify-tray 0.1.11 → 0.1.13
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/README.en.md +9 -9
- package/README.md +9 -9
- package/README.zh-CN.md +9 -9
- package/assets/mascot-peeking.prompt.txt +6 -6
- package/assets/notify-icon.png +0 -0
- package/assets/tray-darwin.js +283 -283
- package/cordis.patch.yml +6 -6
- package/lib/ToastActivator.cs +33 -0
- package/lib/catalog.js +448 -448
- package/lib/client.js +65 -132
- package/lib/format.js +284 -284
- package/lib/host/context.js +11 -3
- package/lib/host/notify.js +26 -21
- package/lib/host/routes.js +9 -42
- package/lib/host/spend.js +190 -190
- package/lib/host/tray.js +120 -120
- package/lib/icon.js +159 -159
- package/lib/index.js +2 -7
- package/lib/ledger.js +285 -285
- package/lib/models-dev.json +2684 -2684
- package/lib/notices.js +3 -4
- package/lib/pricing.js +302 -302
- package/lib/quota.js +290 -290
- package/lib/system.js +11 -22
- package/lib/tracker.js +250 -250
- package/lib/tray/index.js +142 -142
- package/lib/tray/linux.js +393 -393
- package/lib/voice.js +76 -76
- package/lib/whale.js +396 -396
- package/lib/windows-toast.js +92 -0
- package/locale/en.json +7 -7
- package/locale/zh.json +7 -7
- package/package.json +2 -1
package/lib/ledger.js
CHANGED
|
@@ -1,285 +1,285 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Daily spend ledger.
|
|
3
|
-
*
|
|
4
|
-
* Two independent sources, both kept per local day:
|
|
5
|
-
* - tokens: folded from `assistant/message` / `assistant/attempt` usage
|
|
6
|
-
* samples with token-meter's dedupe rule (each (turn, step) slot keeps its
|
|
7
|
-
* last sample; `llm/retry-started` opens a new slot), filed under the
|
|
8
|
-
* `provider/model` route the session's latest `request/header` announced
|
|
9
|
-
* and priced by a resolver (see pricing.js) per million tokens; DeepSeek
|
|
10
|
-
* tokens used off-peak are also counted apart (`offPeak`), so the
|
|
11
|
-
* resolver's `offPeakFactor` can discount them;
|
|
12
|
-
* - balance: polled DeepSeek account balance; the day's spend is the sum of
|
|
13
|
-
* balance drops, so a top-up never reads as negative spend.
|
|
14
|
-
*/
|
|
15
|
-
import { readFileSync } from 'node:fs'
|
|
16
|
-
import { mkdir, rename, writeFile } from 'node:fs/promises'
|
|
17
|
-
import { dirname } from 'node:path'
|
|
18
|
-
import { isDeepseekOffPeak, providerForRoute } from './catalog.js'
|
|
19
|
-
import { localDate } from './tracker.js'
|
|
20
|
-
|
|
21
|
-
/** Days of history kept on disk. */
|
|
22
|
-
const KEEP_DAYS = 31
|
|
23
|
-
|
|
24
|
-
const zero = () => ({ input: 0, cacheRead: 0, cacheWrite: 0, output: 0 })
|
|
25
|
-
|
|
26
|
-
/** The usage one assistant settlement reports, if any. */
|
|
27
|
-
export function usageOf(event) {
|
|
28
|
-
if (event.type === 'assistant/message' && event.data?.usage !== undefined) return event.data.usage
|
|
29
|
-
if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') return undefined
|
|
30
|
-
const stream = event.data?.stream
|
|
31
|
-
if (!Array.isArray(stream)) return undefined
|
|
32
|
-
for (let i = stream.length - 1; i >= 0; i -= 1) {
|
|
33
|
-
const record = stream[i]
|
|
34
|
-
if (record?.type === 'chunk' && record.chunk?.type === 'usage') return record.chunk.usage
|
|
35
|
-
}
|
|
36
|
-
return undefined
|
|
37
|
-
}
|
|
38
|
-
|
|
39
|
-
const bucketsOf = usage => ({
|
|
40
|
-
input: usage.inputTokens ?? 0,
|
|
41
|
-
cacheRead: usage.cacheReadTokens ?? 0,
|
|
42
|
-
cacheWrite: usage.cacheWriteTokens ?? 0,
|
|
43
|
-
output: usage.outputTokens ?? 0,
|
|
44
|
-
})
|
|
45
|
-
|
|
46
|
-
/** `provider/model` route key the ledger files usage under; the bare model when the provider is unknown. */
|
|
47
|
-
export function routeKey(provider, model) {
|
|
48
|
-
return provider ? `${provider}/${model}` : model
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
/** Split a route key back into its halves. */
|
|
52
|
-
export function splitRoute(key) {
|
|
53
|
-
const slash = key.indexOf('/')
|
|
54
|
-
return slash === -1 ? { provider: undefined, model: key } : { provider: key.slice(0, slash), model: key.slice(slash + 1) }
|
|
55
|
-
}
|
|
56
|
-
|
|
57
|
-
/** The provider/model a `request/header` event announces, if any (DSH nests it under `header.config`). */
|
|
58
|
-
export function routeOf(event) {
|
|
59
|
-
const config = event.data?.header?.config ?? event.data?.config
|
|
60
|
-
const model = config?.model
|
|
61
|
-
if (!model) return undefined
|
|
62
|
-
return { provider: config.provider, model }
|
|
63
|
-
}
|
|
64
|
-
|
|
65
|
-
/**
|
|
66
|
-
* Find a price row in a user table for a route key (`provider/model`) or a
|
|
67
|
-
* bare model id: exact route, exact model, then the longest prefix of either.
|
|
68
|
-
*/
|
|
69
|
-
export function priceFor(table, key) {
|
|
70
|
-
if (!table || !key) return undefined
|
|
71
|
-
const { model } = splitRoute(key)
|
|
72
|
-
if (table[key]) return table[key]
|
|
73
|
-
if (table[model]) return table[model]
|
|
74
|
-
let best
|
|
75
|
-
for (const candidate of Object.keys(table)) {
|
|
76
|
-
if ((key.startsWith(candidate) || model.startsWith(candidate)) && (best === undefined || candidate.length > best.length)) best = candidate
|
|
77
|
-
}
|
|
78
|
-
return best === undefined ? undefined : table[best]
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
export function costOf(buckets, price) {
|
|
82
|
-
if (!price) return 0
|
|
83
|
-
const m = 1e6
|
|
84
|
-
return (buckets.input * (price.input ?? 0)
|
|
85
|
-
+ buckets.cacheRead * (price.cacheRead ?? price.input ?? 0)
|
|
86
|
-
+ buckets.cacheWrite * (price.cacheWrite ?? price.input ?? 0)
|
|
87
|
-
+ buckets.output * (price.output ?? 0)) / m
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
export class Ledger {
|
|
91
|
-
constructor({ file, now = () => Date.now() } = {}) {
|
|
92
|
-
this.file = file
|
|
93
|
-
this.now = now
|
|
94
|
-
/** @type {Record<string, any>} date → day record */
|
|
95
|
-
this.days = {}
|
|
96
|
-
/** session id → { turn, step, buckets } of the open replacement slot */
|
|
97
|
-
this.slots = new Map()
|
|
98
|
-
/** session id → route key from the latest request header */
|
|
99
|
-
this.routes = new Map()
|
|
100
|
-
/** The route the most recent request header anywhere announced: "the current model". */
|
|
101
|
-
this.lastRoute = undefined
|
|
102
|
-
this.revision = 0
|
|
103
|
-
this.savedRevision = 0
|
|
104
|
-
this.writing = Promise.resolve()
|
|
105
|
-
this.listeners = new Set()
|
|
106
|
-
}
|
|
107
|
-
|
|
108
|
-
onChange(listener) {
|
|
109
|
-
this.listeners.add(listener)
|
|
110
|
-
return () => this.listeners.delete(listener)
|
|
111
|
-
}
|
|
112
|
-
|
|
113
|
-
changed() {
|
|
114
|
-
this.revision += 1
|
|
115
|
-
for (const listener of this.listeners) listener()
|
|
116
|
-
}
|
|
117
|
-
|
|
118
|
-
today() {
|
|
119
|
-
const date = localDate(this.now())
|
|
120
|
-
let day = this.days[date]
|
|
121
|
-
if (day === undefined) {
|
|
122
|
-
day = { date, tokens: zero(), byModel: {}, offPeak: {}, balanceSpend: {}, balanceLast: {} }
|
|
123
|
-
// Carry the last known balance across midnight so the first poll of the day diffs against it.
|
|
124
|
-
const previous = Object.keys(this.days).sort().pop()
|
|
125
|
-
if (previous !== undefined) day.balanceLast = { ...this.days[previous].balanceLast }
|
|
126
|
-
this.days[date] = day
|
|
127
|
-
}
|
|
128
|
-
return day
|
|
129
|
-
}
|
|
130
|
-
|
|
131
|
-
// Read once at startup, before any session or balance callbacks can run.
|
|
132
|
-
load() {
|
|
133
|
-
if (!this.file) return
|
|
134
|
-
try {
|
|
135
|
-
const parsed = JSON.parse(readFileSync(this.file, 'utf8'))
|
|
136
|
-
if (parsed?.days && typeof parsed.days === 'object' && !Array.isArray(parsed.days)) this.days = parsed.days
|
|
137
|
-
if (typeof parsed?.lastRoute === 'object' && parsed.lastRoute?.model) this.lastRoute = parsed.lastRoute
|
|
138
|
-
} catch {
|
|
139
|
-
// first run or unreadable file: start fresh
|
|
140
|
-
}
|
|
141
|
-
}
|
|
142
|
-
|
|
143
|
-
save() {
|
|
144
|
-
const write = async () => {
|
|
145
|
-
const revision = this.revision
|
|
146
|
-
if (!this.file || this.savedRevision === revision) return
|
|
147
|
-
const dates = Object.keys(this.days).sort()
|
|
148
|
-
for (const date of dates.slice(0, Math.max(0, dates.length - KEEP_DAYS))) delete this.days[date]
|
|
149
|
-
const snapshot = JSON.stringify({ version: 1, days: this.days, lastRoute: this.lastRoute })
|
|
150
|
-
await mkdir(dirname(this.file), { recursive: true })
|
|
151
|
-
const tmp = `${this.file}.tmp`
|
|
152
|
-
await writeFile(tmp, snapshot)
|
|
153
|
-
await rename(tmp, this.file)
|
|
154
|
-
this.savedRevision = revision
|
|
155
|
-
}
|
|
156
|
-
// The periodic flush and the last flush at unload share one writer, including after a failure.
|
|
157
|
-
this.writing = this.writing.then(write, write)
|
|
158
|
-
return this.writing
|
|
159
|
-
}
|
|
160
|
-
|
|
161
|
-
sessionEvent(session, event) {
|
|
162
|
-
const id = session.id
|
|
163
|
-
if (event.type === 'request/header') {
|
|
164
|
-
const route = routeOf(event)
|
|
165
|
-
if (route) {
|
|
166
|
-
this.routes.set(id, routeKey(route.provider, route.model))
|
|
167
|
-
if (this.lastRoute?.provider !== route.provider || this.lastRoute?.model !== route.model) {
|
|
168
|
-
this.lastRoute = route
|
|
169
|
-
this.changed()
|
|
170
|
-
}
|
|
171
|
-
}
|
|
172
|
-
return
|
|
173
|
-
}
|
|
174
|
-
if (event.type === 'llm/retry-started') {
|
|
175
|
-
const slot = this.slots.get(id)
|
|
176
|
-
if (slot && slot.turn === event.data?.turn && slot.step === event.data?.step) this.slots.delete(id)
|
|
177
|
-
return
|
|
178
|
-
}
|
|
179
|
-
const usage = usageOf(event)
|
|
180
|
-
if (usage === undefined) return
|
|
181
|
-
const { turn, step } = event.data
|
|
182
|
-
const next = bucketsOf(usage)
|
|
183
|
-
const key = this.routes.get(id) ?? 'unknown'
|
|
184
|
-
const slot = this.slots.get(id)
|
|
185
|
-
const previous = slot && slot.turn === turn && slot.step === step ? slot : undefined
|
|
186
|
-
const day = this.today()
|
|
187
|
-
const byModel = (day.byModel[key] ??= zero())
|
|
188
|
-
// Days recorded before off-peak tracking have no `offPeak` map.
|
|
189
|
-
const offPeak = billedToDeepseek(key) && isDeepseekOffPeak(this.now()) ? ((day.offPeak ??= {})[key] ??= zero()) : undefined
|
|
190
|
-
for (const bucket of Object.keys(next)) {
|
|
191
|
-
const delta = next[bucket] - (previous?.buckets[bucket] ?? 0)
|
|
192
|
-
day.tokens[bucket] += delta
|
|
193
|
-
byModel[bucket] += delta
|
|
194
|
-
if (offPeak) offPeak[bucket] += delta
|
|
195
|
-
}
|
|
196
|
-
this.slots.set(id, { turn, step, buckets: next })
|
|
197
|
-
this.changed()
|
|
198
|
-
}
|
|
199
|
-
|
|
200
|
-
/** Record one balance reading; returns true when it changed the ledger. */
|
|
201
|
-
balance(wallets) {
|
|
202
|
-
const day = this.today()
|
|
203
|
-
let changed = false
|
|
204
|
-
for (const wallet of wallets) {
|
|
205
|
-
const value = Number(wallet.balance)
|
|
206
|
-
if (!Number.isFinite(value)) continue
|
|
207
|
-
const last = day.balanceLast[wallet.currency]
|
|
208
|
-
if (last !== undefined && value < last) {
|
|
209
|
-
day.balanceSpend[wallet.currency] = round((day.balanceSpend[wallet.currency] ?? 0) + last - value)
|
|
210
|
-
}
|
|
211
|
-
if (last !== value) changed = true
|
|
212
|
-
day.balanceLast[wallet.currency] = value
|
|
213
|
-
}
|
|
214
|
-
if (changed) this.changed()
|
|
215
|
-
return changed
|
|
216
|
-
}
|
|
217
|
-
|
|
218
|
-
forgetSession(id) {
|
|
219
|
-
this.slots.delete(id)
|
|
220
|
-
this.routes.delete(id)
|
|
221
|
-
}
|
|
222
|
-
|
|
223
|
-
/**
|
|
224
|
-
* Today's totals. `pricing` is either a user price table (per million tokens,
|
|
225
|
-
* keyed by route / model id / prefix) or a resolver
|
|
226
|
-
* `(routeKey) => { price, source } | undefined` whose price is already in the
|
|
227
|
-
* display currency. A hit with `offPeakFactor` bills the route's off-peak
|
|
228
|
-
* tokens at that fraction of its price. The estimate is undefined until at
|
|
229
|
-
* least one route priced.
|
|
230
|
-
*/
|
|
231
|
-
summary(pricing, currency) {
|
|
232
|
-
const day = this.today()
|
|
233
|
-
const resolve = typeof pricing === 'function' ? pricing : key => {
|
|
234
|
-
const price = priceFor(pricing, key)
|
|
235
|
-
return price ? { price, source: 'table' } : undefined
|
|
236
|
-
}
|
|
237
|
-
let estimate = 0
|
|
238
|
-
let deepseekEstimate = 0
|
|
239
|
-
let priced = false
|
|
240
|
-
const sources = new Set()
|
|
241
|
-
const byModel = []
|
|
242
|
-
for (const [key, buckets] of Object.entries(day.byModel)) {
|
|
243
|
-
const hit = resolve(key)
|
|
244
|
-
const offPeak = hit?.offPeakFactor !== undefined ? day.offPeak?.[key] : undefined
|
|
245
|
-
const cost = hit
|
|
246
|
-
? round(costOf(buckets, hit.price) - (offPeak ? costOf(offPeak, hit.price) * (1 - hit.offPeakFactor) : 0))
|
|
247
|
-
: undefined
|
|
248
|
-
if (hit) {
|
|
249
|
-
priced = true
|
|
250
|
-
sources.add(hit.source)
|
|
251
|
-
estimate += cost
|
|
252
|
-
if (billedToDeepseek(key)) deepseekEstimate += cost
|
|
253
|
-
}
|
|
254
|
-
byModel.push({ ...splitRoute(key), key, tokens: buckets, cost, source: hit?.source })
|
|
255
|
-
}
|
|
256
|
-
byModel.sort((a, b) => sumOf(b.tokens) - sumOf(a.tokens))
|
|
257
|
-
const totalTokens = sumOf(day.tokens)
|
|
258
|
-
return {
|
|
259
|
-
date: day.date,
|
|
260
|
-
tokens: { ...day.tokens, total: totalTokens },
|
|
261
|
-
byModel,
|
|
262
|
-
estimate: priced ? round(estimate) : undefined,
|
|
263
|
-
estimateSources: [...sources],
|
|
264
|
-
// The part of the estimate the DeepSeek account balance also pays for (DeepSeek routes).
|
|
265
|
-
estimateDeepseek: priced ? round(deepseekEstimate) : undefined,
|
|
266
|
-
balance: day.balanceLast[currency],
|
|
267
|
-
balanceSpend: day.balanceSpend[currency],
|
|
268
|
-
currency,
|
|
269
|
-
route: this.lastRoute,
|
|
270
|
-
}
|
|
271
|
-
}
|
|
272
|
-
}
|
|
273
|
-
|
|
274
|
-
/** Does usage filed under this route key come out of the DeepSeek account balance? */
|
|
275
|
-
export function billedToDeepseek(key) {
|
|
276
|
-
const { provider, model } = splitRoute(key)
|
|
277
|
-
if (provider) return providerForRoute(provider) === 'deepseek'
|
|
278
|
-
return /^deepseek/iu.test(model)
|
|
279
|
-
}
|
|
280
|
-
|
|
281
|
-
const sumOf = t => t.input + t.cacheRead + t.cacheWrite + t.output
|
|
282
|
-
|
|
283
|
-
function round(value) {
|
|
284
|
-
return Math.round(value * 10000) / 10000
|
|
285
|
-
}
|
|
1
|
+
/**
|
|
2
|
+
* Daily spend ledger.
|
|
3
|
+
*
|
|
4
|
+
* Two independent sources, both kept per local day:
|
|
5
|
+
* - tokens: folded from `assistant/message` / `assistant/attempt` usage
|
|
6
|
+
* samples with token-meter's dedupe rule (each (turn, step) slot keeps its
|
|
7
|
+
* last sample; `llm/retry-started` opens a new slot), filed under the
|
|
8
|
+
* `provider/model` route the session's latest `request/header` announced
|
|
9
|
+
* and priced by a resolver (see pricing.js) per million tokens; DeepSeek
|
|
10
|
+
* tokens used off-peak are also counted apart (`offPeak`), so the
|
|
11
|
+
* resolver's `offPeakFactor` can discount them;
|
|
12
|
+
* - balance: polled DeepSeek account balance; the day's spend is the sum of
|
|
13
|
+
* balance drops, so a top-up never reads as negative spend.
|
|
14
|
+
*/
|
|
15
|
+
import { readFileSync } from 'node:fs'
|
|
16
|
+
import { mkdir, rename, writeFile } from 'node:fs/promises'
|
|
17
|
+
import { dirname } from 'node:path'
|
|
18
|
+
import { isDeepseekOffPeak, providerForRoute } from './catalog.js'
|
|
19
|
+
import { localDate } from './tracker.js'
|
|
20
|
+
|
|
21
|
+
/** Days of history kept on disk. */
|
|
22
|
+
const KEEP_DAYS = 31
|
|
23
|
+
|
|
24
|
+
const zero = () => ({ input: 0, cacheRead: 0, cacheWrite: 0, output: 0 })
|
|
25
|
+
|
|
26
|
+
/** The usage one assistant settlement reports, if any. */
|
|
27
|
+
export function usageOf(event) {
|
|
28
|
+
if (event.type === 'assistant/message' && event.data?.usage !== undefined) return event.data.usage
|
|
29
|
+
if (event.type !== 'assistant/message' && event.type !== 'assistant/attempt') return undefined
|
|
30
|
+
const stream = event.data?.stream
|
|
31
|
+
if (!Array.isArray(stream)) return undefined
|
|
32
|
+
for (let i = stream.length - 1; i >= 0; i -= 1) {
|
|
33
|
+
const record = stream[i]
|
|
34
|
+
if (record?.type === 'chunk' && record.chunk?.type === 'usage') return record.chunk.usage
|
|
35
|
+
}
|
|
36
|
+
return undefined
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const bucketsOf = usage => ({
|
|
40
|
+
input: usage.inputTokens ?? 0,
|
|
41
|
+
cacheRead: usage.cacheReadTokens ?? 0,
|
|
42
|
+
cacheWrite: usage.cacheWriteTokens ?? 0,
|
|
43
|
+
output: usage.outputTokens ?? 0,
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
/** `provider/model` route key the ledger files usage under; the bare model when the provider is unknown. */
|
|
47
|
+
export function routeKey(provider, model) {
|
|
48
|
+
return provider ? `${provider}/${model}` : model
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Split a route key back into its halves. */
|
|
52
|
+
export function splitRoute(key) {
|
|
53
|
+
const slash = key.indexOf('/')
|
|
54
|
+
return slash === -1 ? { provider: undefined, model: key } : { provider: key.slice(0, slash), model: key.slice(slash + 1) }
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** The provider/model a `request/header` event announces, if any (DSH nests it under `header.config`). */
|
|
58
|
+
export function routeOf(event) {
|
|
59
|
+
const config = event.data?.header?.config ?? event.data?.config
|
|
60
|
+
const model = config?.model
|
|
61
|
+
if (!model) return undefined
|
|
62
|
+
return { provider: config.provider, model }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Find a price row in a user table for a route key (`provider/model`) or a
|
|
67
|
+
* bare model id: exact route, exact model, then the longest prefix of either.
|
|
68
|
+
*/
|
|
69
|
+
export function priceFor(table, key) {
|
|
70
|
+
if (!table || !key) return undefined
|
|
71
|
+
const { model } = splitRoute(key)
|
|
72
|
+
if (table[key]) return table[key]
|
|
73
|
+
if (table[model]) return table[model]
|
|
74
|
+
let best
|
|
75
|
+
for (const candidate of Object.keys(table)) {
|
|
76
|
+
if ((key.startsWith(candidate) || model.startsWith(candidate)) && (best === undefined || candidate.length > best.length)) best = candidate
|
|
77
|
+
}
|
|
78
|
+
return best === undefined ? undefined : table[best]
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function costOf(buckets, price) {
|
|
82
|
+
if (!price) return 0
|
|
83
|
+
const m = 1e6
|
|
84
|
+
return (buckets.input * (price.input ?? 0)
|
|
85
|
+
+ buckets.cacheRead * (price.cacheRead ?? price.input ?? 0)
|
|
86
|
+
+ buckets.cacheWrite * (price.cacheWrite ?? price.input ?? 0)
|
|
87
|
+
+ buckets.output * (price.output ?? 0)) / m
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
export class Ledger {
|
|
91
|
+
constructor({ file, now = () => Date.now() } = {}) {
|
|
92
|
+
this.file = file
|
|
93
|
+
this.now = now
|
|
94
|
+
/** @type {Record<string, any>} date → day record */
|
|
95
|
+
this.days = {}
|
|
96
|
+
/** session id → { turn, step, buckets } of the open replacement slot */
|
|
97
|
+
this.slots = new Map()
|
|
98
|
+
/** session id → route key from the latest request header */
|
|
99
|
+
this.routes = new Map()
|
|
100
|
+
/** The route the most recent request header anywhere announced: "the current model". */
|
|
101
|
+
this.lastRoute = undefined
|
|
102
|
+
this.revision = 0
|
|
103
|
+
this.savedRevision = 0
|
|
104
|
+
this.writing = Promise.resolve()
|
|
105
|
+
this.listeners = new Set()
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
onChange(listener) {
|
|
109
|
+
this.listeners.add(listener)
|
|
110
|
+
return () => this.listeners.delete(listener)
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
changed() {
|
|
114
|
+
this.revision += 1
|
|
115
|
+
for (const listener of this.listeners) listener()
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
today() {
|
|
119
|
+
const date = localDate(this.now())
|
|
120
|
+
let day = this.days[date]
|
|
121
|
+
if (day === undefined) {
|
|
122
|
+
day = { date, tokens: zero(), byModel: {}, offPeak: {}, balanceSpend: {}, balanceLast: {} }
|
|
123
|
+
// Carry the last known balance across midnight so the first poll of the day diffs against it.
|
|
124
|
+
const previous = Object.keys(this.days).sort().pop()
|
|
125
|
+
if (previous !== undefined) day.balanceLast = { ...this.days[previous].balanceLast }
|
|
126
|
+
this.days[date] = day
|
|
127
|
+
}
|
|
128
|
+
return day
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
// Read once at startup, before any session or balance callbacks can run.
|
|
132
|
+
load() {
|
|
133
|
+
if (!this.file) return
|
|
134
|
+
try {
|
|
135
|
+
const parsed = JSON.parse(readFileSync(this.file, 'utf8'))
|
|
136
|
+
if (parsed?.days && typeof parsed.days === 'object' && !Array.isArray(parsed.days)) this.days = parsed.days
|
|
137
|
+
if (typeof parsed?.lastRoute === 'object' && parsed.lastRoute?.model) this.lastRoute = parsed.lastRoute
|
|
138
|
+
} catch {
|
|
139
|
+
// first run or unreadable file: start fresh
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
save() {
|
|
144
|
+
const write = async () => {
|
|
145
|
+
const revision = this.revision
|
|
146
|
+
if (!this.file || this.savedRevision === revision) return
|
|
147
|
+
const dates = Object.keys(this.days).sort()
|
|
148
|
+
for (const date of dates.slice(0, Math.max(0, dates.length - KEEP_DAYS))) delete this.days[date]
|
|
149
|
+
const snapshot = JSON.stringify({ version: 1, days: this.days, lastRoute: this.lastRoute })
|
|
150
|
+
await mkdir(dirname(this.file), { recursive: true })
|
|
151
|
+
const tmp = `${this.file}.tmp`
|
|
152
|
+
await writeFile(tmp, snapshot)
|
|
153
|
+
await rename(tmp, this.file)
|
|
154
|
+
this.savedRevision = revision
|
|
155
|
+
}
|
|
156
|
+
// The periodic flush and the last flush at unload share one writer, including after a failure.
|
|
157
|
+
this.writing = this.writing.then(write, write)
|
|
158
|
+
return this.writing
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
sessionEvent(session, event) {
|
|
162
|
+
const id = session.id
|
|
163
|
+
if (event.type === 'request/header') {
|
|
164
|
+
const route = routeOf(event)
|
|
165
|
+
if (route) {
|
|
166
|
+
this.routes.set(id, routeKey(route.provider, route.model))
|
|
167
|
+
if (this.lastRoute?.provider !== route.provider || this.lastRoute?.model !== route.model) {
|
|
168
|
+
this.lastRoute = route
|
|
169
|
+
this.changed()
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
return
|
|
173
|
+
}
|
|
174
|
+
if (event.type === 'llm/retry-started') {
|
|
175
|
+
const slot = this.slots.get(id)
|
|
176
|
+
if (slot && slot.turn === event.data?.turn && slot.step === event.data?.step) this.slots.delete(id)
|
|
177
|
+
return
|
|
178
|
+
}
|
|
179
|
+
const usage = usageOf(event)
|
|
180
|
+
if (usage === undefined) return
|
|
181
|
+
const { turn, step } = event.data
|
|
182
|
+
const next = bucketsOf(usage)
|
|
183
|
+
const key = this.routes.get(id) ?? 'unknown'
|
|
184
|
+
const slot = this.slots.get(id)
|
|
185
|
+
const previous = slot && slot.turn === turn && slot.step === step ? slot : undefined
|
|
186
|
+
const day = this.today()
|
|
187
|
+
const byModel = (day.byModel[key] ??= zero())
|
|
188
|
+
// Days recorded before off-peak tracking have no `offPeak` map.
|
|
189
|
+
const offPeak = billedToDeepseek(key) && isDeepseekOffPeak(this.now()) ? ((day.offPeak ??= {})[key] ??= zero()) : undefined
|
|
190
|
+
for (const bucket of Object.keys(next)) {
|
|
191
|
+
const delta = next[bucket] - (previous?.buckets[bucket] ?? 0)
|
|
192
|
+
day.tokens[bucket] += delta
|
|
193
|
+
byModel[bucket] += delta
|
|
194
|
+
if (offPeak) offPeak[bucket] += delta
|
|
195
|
+
}
|
|
196
|
+
this.slots.set(id, { turn, step, buckets: next })
|
|
197
|
+
this.changed()
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/** Record one balance reading; returns true when it changed the ledger. */
|
|
201
|
+
balance(wallets) {
|
|
202
|
+
const day = this.today()
|
|
203
|
+
let changed = false
|
|
204
|
+
for (const wallet of wallets) {
|
|
205
|
+
const value = Number(wallet.balance)
|
|
206
|
+
if (!Number.isFinite(value)) continue
|
|
207
|
+
const last = day.balanceLast[wallet.currency]
|
|
208
|
+
if (last !== undefined && value < last) {
|
|
209
|
+
day.balanceSpend[wallet.currency] = round((day.balanceSpend[wallet.currency] ?? 0) + last - value)
|
|
210
|
+
}
|
|
211
|
+
if (last !== value) changed = true
|
|
212
|
+
day.balanceLast[wallet.currency] = value
|
|
213
|
+
}
|
|
214
|
+
if (changed) this.changed()
|
|
215
|
+
return changed
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
forgetSession(id) {
|
|
219
|
+
this.slots.delete(id)
|
|
220
|
+
this.routes.delete(id)
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/**
|
|
224
|
+
* Today's totals. `pricing` is either a user price table (per million tokens,
|
|
225
|
+
* keyed by route / model id / prefix) or a resolver
|
|
226
|
+
* `(routeKey) => { price, source } | undefined` whose price is already in the
|
|
227
|
+
* display currency. A hit with `offPeakFactor` bills the route's off-peak
|
|
228
|
+
* tokens at that fraction of its price. The estimate is undefined until at
|
|
229
|
+
* least one route priced.
|
|
230
|
+
*/
|
|
231
|
+
summary(pricing, currency) {
|
|
232
|
+
const day = this.today()
|
|
233
|
+
const resolve = typeof pricing === 'function' ? pricing : key => {
|
|
234
|
+
const price = priceFor(pricing, key)
|
|
235
|
+
return price ? { price, source: 'table' } : undefined
|
|
236
|
+
}
|
|
237
|
+
let estimate = 0
|
|
238
|
+
let deepseekEstimate = 0
|
|
239
|
+
let priced = false
|
|
240
|
+
const sources = new Set()
|
|
241
|
+
const byModel = []
|
|
242
|
+
for (const [key, buckets] of Object.entries(day.byModel)) {
|
|
243
|
+
const hit = resolve(key)
|
|
244
|
+
const offPeak = hit?.offPeakFactor !== undefined ? day.offPeak?.[key] : undefined
|
|
245
|
+
const cost = hit
|
|
246
|
+
? round(costOf(buckets, hit.price) - (offPeak ? costOf(offPeak, hit.price) * (1 - hit.offPeakFactor) : 0))
|
|
247
|
+
: undefined
|
|
248
|
+
if (hit) {
|
|
249
|
+
priced = true
|
|
250
|
+
sources.add(hit.source)
|
|
251
|
+
estimate += cost
|
|
252
|
+
if (billedToDeepseek(key)) deepseekEstimate += cost
|
|
253
|
+
}
|
|
254
|
+
byModel.push({ ...splitRoute(key), key, tokens: buckets, cost, source: hit?.source })
|
|
255
|
+
}
|
|
256
|
+
byModel.sort((a, b) => sumOf(b.tokens) - sumOf(a.tokens))
|
|
257
|
+
const totalTokens = sumOf(day.tokens)
|
|
258
|
+
return {
|
|
259
|
+
date: day.date,
|
|
260
|
+
tokens: { ...day.tokens, total: totalTokens },
|
|
261
|
+
byModel,
|
|
262
|
+
estimate: priced ? round(estimate) : undefined,
|
|
263
|
+
estimateSources: [...sources],
|
|
264
|
+
// The part of the estimate the DeepSeek account balance also pays for (DeepSeek routes).
|
|
265
|
+
estimateDeepseek: priced ? round(deepseekEstimate) : undefined,
|
|
266
|
+
balance: day.balanceLast[currency],
|
|
267
|
+
balanceSpend: day.balanceSpend[currency],
|
|
268
|
+
currency,
|
|
269
|
+
route: this.lastRoute,
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Does usage filed under this route key come out of the DeepSeek account balance? */
|
|
275
|
+
export function billedToDeepseek(key) {
|
|
276
|
+
const { provider, model } = splitRoute(key)
|
|
277
|
+
if (provider) return providerForRoute(provider) === 'deepseek'
|
|
278
|
+
return /^deepseek/iu.test(model)
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
const sumOf = t => t.input + t.cacheRead + t.cacheWrite + t.output
|
|
282
|
+
|
|
283
|
+
function round(value) {
|
|
284
|
+
return Math.round(value * 10000) / 10000
|
|
285
|
+
}
|