dsh-notify-tray 0.1.5 → 0.1.7
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.md +12 -8
- package/README.zh-CN.md +12 -8
- package/lib/catalog.js +26 -3
- package/lib/client.js +62 -9
- package/lib/format.js +1 -1
- package/lib/host/context.js +89 -0
- package/lib/host/notify.js +89 -0
- package/lib/host/routes.js +155 -0
- package/lib/host/spend.js +159 -0
- package/lib/host/tray.js +120 -0
- package/lib/index.js +16 -423
- package/lib/ledger.js +15 -5
- package/lib/models-dev.json +2684 -0
- package/lib/notices.js +119 -0
- package/lib/pricing.js +121 -14
- package/lib/quota.js +46 -2
- package/lib/system.js +116 -10
- package/lib/tracker.js +7 -0
- package/lib/tray/linux.js +34 -7
- package/lib/voice.js +19 -1
- package/package.json +4 -2
package/lib/index.js
CHANGED
|
@@ -15,45 +15,22 @@
|
|
|
15
15
|
* browser half, which shows native notifications from the DSH window and
|
|
16
16
|
* renders the settings page; when no window is polling, the host falls
|
|
17
17
|
* back to OS notifications itself.
|
|
18
|
+
*
|
|
19
|
+
* Each concern lives in lib/host/ and shares one `host` object (context.js):
|
|
20
|
+
* tray.js, notify.js, spend.js, routes.js.
|
|
18
21
|
*/
|
|
19
22
|
import z from '@deepseek-ai/schemastery'
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
import { fetchQuota } from './quota.js'
|
|
28
|
-
import { openUrl, showApp, systemNotify } from './system.js'
|
|
29
|
-
import { startTray } from './tray/index.js'
|
|
30
|
-
import { Tracker } from './tracker.js'
|
|
31
|
-
import { speak } from './voice.js'
|
|
32
|
-
import { iconSpec } from './whale.js'
|
|
23
|
+
import { createHost } from './host/context.js'
|
|
24
|
+
import { setupNotifications } from './host/notify.js'
|
|
25
|
+
import { setupRoutes } from './host/routes.js'
|
|
26
|
+
import { setupSpend } from './host/spend.js'
|
|
27
|
+
import { setupTray } from './host/tray.js'
|
|
28
|
+
|
|
29
|
+
export { TRAY_PLATFORMS } from './host/tray.js'
|
|
33
30
|
|
|
34
31
|
export const name = 'notify-tray'
|
|
35
32
|
export const inject = ['agents']
|
|
36
33
|
|
|
37
|
-
const STATE_PATH = '/notify-tray/state'
|
|
38
|
-
const CATALOG_PATH = '/notify-tray/catalog'
|
|
39
|
-
const REFRESH_PATH = '/notify-tray/refresh'
|
|
40
|
-
const TRAY_PATH = '/notify-tray/tray'
|
|
41
|
-
/** Harness version sent as account client metadata (what the built-in settings page sends). */
|
|
42
|
-
const DSH_VERSION = '0.2.1-rc.2'
|
|
43
|
-
/** A window that polled within this window counts as "listening". */
|
|
44
|
-
const CLIENT_FRESH_MS = 8000
|
|
45
|
-
/** Platforms with a status bar the whale can live in. */
|
|
46
|
-
export const TRAY_PLATFORMS = new Set(['darwin', 'linux', 'freebsd'])
|
|
47
|
-
/** The whale's colour on a notification of each kind. */
|
|
48
|
-
const EVENT_STATE = { completed: 'done', failed: 'error', approval: 'attention', choice: 'attention', input: 'attention' }
|
|
49
|
-
const EVENT_SWITCH = {
|
|
50
|
-
completed: 'notifyCompleted',
|
|
51
|
-
failed: 'notifyFailed',
|
|
52
|
-
approval: 'notifyApproval',
|
|
53
|
-
choice: 'notifyChoice',
|
|
54
|
-
input: 'notifyInput',
|
|
55
|
-
}
|
|
56
|
-
|
|
57
34
|
const price = z.object({
|
|
58
35
|
input: z.number().min(0).description('未命中缓存输入,每百万 token 价格'),
|
|
59
36
|
cacheRead: z.number().min(0).description('缓存命中输入,每百万 token 价格'),
|
|
@@ -123,196 +100,13 @@ export const Config = z.object({
|
|
|
123
100
|
quotaPollMinutes: z.number().min(1).max(240).default(10).description('额度刷新间隔(分钟)').volatile(),
|
|
124
101
|
})
|
|
125
102
|
|
|
126
|
-
function storageDir() {
|
|
127
|
-
const home = process.env.DSH_HOME?.trim() || join(homedir(), '.dsh')
|
|
128
|
-
return join(home, 'storages', 'dsh-notify-tray')
|
|
129
|
-
}
|
|
130
|
-
|
|
131
103
|
export function apply(ctx, config) {
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
get: (_, key) => {
|
|
136
|
-
const value = config?.[key]
|
|
137
|
-
return value !== null && typeof value === 'object' && typeof value.get === 'function' ? value.get() : value
|
|
138
|
-
},
|
|
139
|
-
})
|
|
140
|
-
const logger = ctx.logger?.('notify-tray') ?? console
|
|
141
|
-
const dir = storageDir()
|
|
142
|
-
const tracker = new Tracker()
|
|
143
|
-
const ledger = new Ledger({ file: join(dir, 'ledger.json') })
|
|
144
|
-
const account = { usageUrl: undefined }
|
|
145
|
-
/** pi-ai's model catalog (prices), once loaded. */
|
|
146
|
-
let pi
|
|
147
|
-
/** Latest plan quota reading: { ok, at, data | error, signature }. */
|
|
148
|
-
let quota
|
|
149
|
-
/** The web GUI's origin, once the web server is up: where "open DSH" goes when there is no desktop window. */
|
|
150
|
-
let webOrigin = () => undefined
|
|
151
|
-
let tray
|
|
152
|
-
/** Identifies this host run, so clients reset their cursor after a restart. */
|
|
153
|
-
const boot = `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`
|
|
154
|
-
let lastClientPoll = 0
|
|
155
|
-
/** Session ids a tray click asked the window to open, consumed by the next poll. */
|
|
156
|
-
let focusQueue = []
|
|
157
|
-
|
|
158
|
-
/** Set DSH_NOTIFY_TRAY_DEBUG=1 to trace tracked events into storages/dsh-notify-tray/debug.log. */
|
|
159
|
-
const debug = process.env.DSH_NOTIFY_TRAY_DEBUG
|
|
160
|
-
? (...parts) => {
|
|
161
|
-
try {
|
|
162
|
-
mkdirSync(dir, { recursive: true })
|
|
163
|
-
appendFileSync(join(dir, 'debug.log'), `${new Date().toISOString()} ${parts.map(p => typeof p === 'string' ? p : JSON.stringify(p)).join(' ')}\n`)
|
|
164
|
-
} catch {}
|
|
165
|
-
}
|
|
166
|
-
: () => {}
|
|
167
|
-
|
|
168
|
-
/** Which endpoint the plan's quota comes from, and what identifies one reading as current. */
|
|
169
|
-
const quotaSpec = () => quotaSpecFor(cfg.planProvider, cfg.planId, cfg.planQuotaUrl)
|
|
170
|
-
const quotaSignature = () => `${cfg.planProvider}|${cfg.planId}|${cfg.planApiKeyEnv ?? ''}|${cfg.planQuotaUrl ?? ''}`
|
|
171
|
-
/** The route in use: the latest request header anywhere, else DSH's default model selection. */
|
|
172
|
-
const currentRoute = () => {
|
|
173
|
-
if (ledger.lastRoute) return ledger.lastRoute
|
|
174
|
-
try {
|
|
175
|
-
const selection = ctx.get('agentDefaultModel')?.currentSelection?.()
|
|
176
|
-
if (selection?.model) return { provider: selection.provider, model: selection.model }
|
|
177
|
-
} catch {}
|
|
178
|
-
return undefined
|
|
179
|
-
}
|
|
180
|
-
const usage = () => ({
|
|
181
|
-
...ledger.summary(makeResolver({ cfg, models: pi?.models }), cfg.currency),
|
|
182
|
-
usageUrl: account.usageUrl,
|
|
183
|
-
route: currentRoute(),
|
|
184
|
-
})
|
|
185
|
-
// A reading taken for another provider / key is never shown as this one's.
|
|
186
|
-
const plan = () => planView(cfg, quota && quota.signature === quotaSignature() ? quota : undefined)
|
|
187
|
-
const pricing = () => describeRoute({ cfg, models: pi?.models, route: currentRoute() })
|
|
188
|
-
const view = () => buildView(tracker.summary(), usage(), cfg, Date.now(), plan())
|
|
189
|
-
|
|
190
|
-
// ---- tray -------------------------------------------------------------
|
|
191
|
-
let refreshTimer
|
|
192
|
-
const refresh = () => {
|
|
193
|
-
if (refreshTimer) return
|
|
194
|
-
// Coalesce bursts (streaming usage samples) into one tray update.
|
|
195
|
-
refreshTimer = setTimeout(() => {
|
|
196
|
-
refreshTimer = undefined
|
|
197
|
-
try { tray?.update(view()) } catch (error) { logger.warn('更新状态栏失败', error) }
|
|
198
|
-
}, 300)
|
|
199
|
-
}
|
|
200
|
-
tracker.onChange(refresh)
|
|
201
|
-
ledger.onChange(refresh)
|
|
202
|
-
// "已运行 n 分钟" in the menu ticks even when nothing else changes.
|
|
203
|
-
ctx.effect(() => {
|
|
204
|
-
const timer = setInterval(() => { if (tracker.summary().running > 0) refresh() }, 60_000)
|
|
205
|
-
return () => clearInterval(timer)
|
|
206
|
-
}, 'notify-tray: minute tick')
|
|
207
|
-
|
|
208
|
-
const open = () => showApp({ webOrigin }).catch(() => false)
|
|
209
|
-
const onAction = action => {
|
|
210
|
-
if (action === 'show-app') return void open()
|
|
211
|
-
if (action === 'usage-page' && account.usageUrl) return void openUrl(account.usageUrl)
|
|
212
|
-
if (action === 'refresh-quota') return void pollQuota(true)
|
|
213
|
-
if (action.startsWith('url:')) return void openUrl(action.slice(4))
|
|
214
|
-
if (action === 'hide-tray') {
|
|
215
|
-
// Hidden for this run only: the settings page offers to bring it back.
|
|
216
|
-
trayHidden = true
|
|
217
|
-
syncTray()
|
|
218
|
-
return
|
|
219
|
-
}
|
|
220
|
-
if (action.startsWith('open:')) {
|
|
221
|
-
focusQueue.push(action.slice(5))
|
|
222
|
-
open()
|
|
223
|
-
}
|
|
224
|
-
}
|
|
225
|
-
|
|
226
|
-
// Windows has no status bar to live in (and the desktop app keeps a tray
|
|
227
|
-
// icon of its own): there the plugin is notifications only.
|
|
228
|
-
// The icon follows the `tray` setting live, and "隐藏状态栏图标" in its menu
|
|
229
|
-
// hides it until the settings page (or a restart) brings it back.
|
|
230
|
-
let trayHidden = false
|
|
231
|
-
let trayStarting
|
|
232
|
-
let trayDisposed = false
|
|
233
|
-
/** A start that failed (no D-Bus, no tray host…) is not retried until the setting or the page asks again. */
|
|
234
|
-
let trayFailed = false
|
|
235
|
-
const trayWanted = () => Boolean(cfg.tray) && !trayHidden && !trayDisposed && TRAY_PLATFORMS.has(process.platform)
|
|
236
|
-
const stopTray = () => {
|
|
237
|
-
const t = tray
|
|
238
|
-
tray = undefined
|
|
239
|
-
return t?.stop()
|
|
240
|
-
}
|
|
241
|
-
const syncTray = () => {
|
|
242
|
-
if (trayStarting) return trayStarting
|
|
243
|
-
if (!trayWanted()) return stopTray()
|
|
244
|
-
if (tray) return undefined
|
|
245
|
-
trayStarting = startTray({ stateDir: dir, icon: iconSpec(), onAction, logger })
|
|
246
|
-
.then(t => {
|
|
247
|
-
if (!trayWanted()) return void t.stop()
|
|
248
|
-
tray = t
|
|
249
|
-
tray.update(view())
|
|
250
|
-
})
|
|
251
|
-
.catch(error => {
|
|
252
|
-
trayFailed = true
|
|
253
|
-
logger.warn('状态栏图标启动失败,只保留通知功能', error)
|
|
254
|
-
})
|
|
255
|
-
.finally(() => {
|
|
256
|
-
trayStarting = undefined
|
|
257
|
-
// The setting may have flipped while the helper was starting.
|
|
258
|
-
if (!trayFailed && Boolean(tray) !== trayWanted()) syncTray()
|
|
259
|
-
})
|
|
260
|
-
return trayStarting
|
|
261
|
-
}
|
|
262
|
-
const trayStatus = () => ({
|
|
263
|
-
supported: TRAY_PLATFORMS.has(process.platform),
|
|
264
|
-
enabled: Boolean(cfg.tray),
|
|
265
|
-
hidden: trayHidden,
|
|
266
|
-
shown: Boolean(tray),
|
|
267
|
-
failed: trayFailed,
|
|
268
|
-
})
|
|
269
|
-
ctx.effect(() => {
|
|
270
|
-
trayDisposed = false
|
|
271
|
-
syncTray()
|
|
272
|
-
// Settings fields are read live; a cheap check picks up a flipped toggle without a restart.
|
|
273
|
-
let enabled = Boolean(cfg.tray)
|
|
274
|
-
const timer = setInterval(() => {
|
|
275
|
-
if (Boolean(cfg.tray) !== enabled) {
|
|
276
|
-
enabled = Boolean(cfg.tray)
|
|
277
|
-
trayFailed = false
|
|
278
|
-
// Switching the setting back on also undoes a hide from the tray menu.
|
|
279
|
-
if (enabled) trayHidden = false
|
|
280
|
-
}
|
|
281
|
-
if (!trayFailed && !trayStarting && Boolean(tray) !== trayWanted()) syncTray()
|
|
282
|
-
}, 2000)
|
|
283
|
-
return () => {
|
|
284
|
-
trayDisposed = true
|
|
285
|
-
clearInterval(timer)
|
|
286
|
-
clearTimeout(refreshTimer)
|
|
287
|
-
stopTray()
|
|
288
|
-
}
|
|
289
|
-
}, 'notify-tray: tray')
|
|
290
|
-
|
|
291
|
-
// ---- notifications ----------------------------------------------------
|
|
292
|
-
tracker.onEvent(event => {
|
|
293
|
-
debug('event', event)
|
|
294
|
-
// The celebration / error pose expires on its own: refresh once it does.
|
|
295
|
-
if (event.type === 'completed') setTimeout(refresh, DONE_HOLD_MS + 200).unref?.()
|
|
296
|
-
if (event.type === 'failed') setTimeout(refresh, Math.max(0, cfg.errorHoldMinutes) * 60_000 + 200).unref?.()
|
|
297
|
-
if (!cfg[EVENT_SWITCH[event.type]]) return
|
|
298
|
-
const clientListening = Date.now() - lastClientPoll < CLIENT_FRESH_MS
|
|
299
|
-
const channel = cfg.channel
|
|
300
|
-
const systemSide = channel === 'system' || channel === 'both' || (channel === 'auto' && !clientListening)
|
|
301
|
-
debug('deliver', { channel, clientListening, systemSide })
|
|
302
|
-
if (!systemSide) return // the window picks it up from the event queue
|
|
303
|
-
const said = speak(event)
|
|
304
|
-
systemNotify({
|
|
305
|
-
title: said.title,
|
|
306
|
-
body: said.body,
|
|
307
|
-
sound: cfg.sound,
|
|
308
|
-
webOrigin,
|
|
309
|
-
state: EVENT_STATE[event.type],
|
|
310
|
-
iconDir: join(dir, 'icons'),
|
|
311
|
-
onClick: () => onAction(`open:${event.sessionId}`),
|
|
312
|
-
}).then(ok => debug('system notify', ok)).catch(error => logger.warn('系统通知失败', error))
|
|
313
|
-
})
|
|
104
|
+
const host = createHost(ctx, config)
|
|
105
|
+
setupTray(ctx, host)
|
|
106
|
+
setupNotifications(ctx, host)
|
|
314
107
|
|
|
315
108
|
// ---- DSH events -------------------------------------------------------
|
|
109
|
+
const { tracker, ledger, logger, debug } = host
|
|
316
110
|
tracker.seed(ctx.agents.list())
|
|
317
111
|
ctx.on('agent/status', ({ agent, status }) => tracker.agentStatus(agent, status))
|
|
318
112
|
ctx.on('agent/disposed', ({ agent }) => {
|
|
@@ -329,207 +123,6 @@ export function apply(ctx, config) {
|
|
|
329
123
|
}
|
|
330
124
|
})
|
|
331
125
|
|
|
332
|
-
|
|
333
|
-
ctx
|
|
334
|
-
ledger.load().then(refresh)
|
|
335
|
-
const timer = setInterval(() => ledger.save().catch(() => {}), 30_000)
|
|
336
|
-
return () => {
|
|
337
|
-
clearInterval(timer)
|
|
338
|
-
ledger.save().catch(() => {})
|
|
339
|
-
}
|
|
340
|
-
}, 'notify-tray: ledger')
|
|
341
|
-
|
|
342
|
-
// ---- pi-ai price catalog (the one DSH's model selector reads) -------------
|
|
343
|
-
ctx.effect(() => {
|
|
344
|
-
let disposed = false
|
|
345
|
-
loadPiCatalog().then(loaded => {
|
|
346
|
-
if (disposed || !loaded) return
|
|
347
|
-
pi = loaded
|
|
348
|
-
debug('pi catalog', loaded.file)
|
|
349
|
-
refresh()
|
|
350
|
-
}).catch(() => {})
|
|
351
|
-
return () => { disposed = true }
|
|
352
|
-
}, 'notify-tray: price catalog')
|
|
353
|
-
|
|
354
|
-
// ---- plan quota polling ---------------------------------------------------
|
|
355
|
-
let polling
|
|
356
|
-
const pollQuota = async (force = false) => {
|
|
357
|
-
const spec = quotaSpec()
|
|
358
|
-
const ref = (cfg.planApiKeyEnv ?? '').trim()
|
|
359
|
-
const signature = quotaSignature()
|
|
360
|
-
if (!spec || !ref || (!force && !cfg.planAutoQuota)) {
|
|
361
|
-
if (quota !== undefined) { quota = undefined; refresh() }
|
|
362
|
-
return undefined
|
|
363
|
-
}
|
|
364
|
-
if (polling) return polling
|
|
365
|
-
polling = (async () => {
|
|
366
|
-
let key
|
|
367
|
-
try {
|
|
368
|
-
const credentials = ctx.get('credentials')
|
|
369
|
-
key = credentials ? (await credentials.resolve(ref))?.value : undefined
|
|
370
|
-
if (!key) key = process.env[ref]
|
|
371
|
-
} catch (error) {
|
|
372
|
-
key = process.env[ref]
|
|
373
|
-
debug('credential', String(error))
|
|
374
|
-
}
|
|
375
|
-
const at = Date.now()
|
|
376
|
-
const reading = key
|
|
377
|
-
? await fetchQuota(spec, key)
|
|
378
|
-
: { ok: false, at, error: `没找到 API Key:${ref} 没有保存,也没有设置为环境变量` }
|
|
379
|
-
quota = { ...reading, signature, spec: { kind: spec.kind, url: spec.url } }
|
|
380
|
-
debug('quota', quota)
|
|
381
|
-
refresh()
|
|
382
|
-
return quota
|
|
383
|
-
})().finally(() => { polling = undefined })
|
|
384
|
-
return polling
|
|
385
|
-
}
|
|
386
|
-
ctx.effect(() => {
|
|
387
|
-
let timer
|
|
388
|
-
let lastSignature = quotaSignature()
|
|
389
|
-
let lastPoll = 0
|
|
390
|
-
const tick = () => {
|
|
391
|
-
const signature = quotaSignature()
|
|
392
|
-
const due = Date.now() - lastPoll >= Math.max(1, cfg.quotaPollMinutes) * 60_000
|
|
393
|
-
if (signature !== lastSignature || due) {
|
|
394
|
-
lastSignature = signature
|
|
395
|
-
lastPoll = Date.now()
|
|
396
|
-
pollQuota().catch(() => {})
|
|
397
|
-
}
|
|
398
|
-
timer = setTimeout(tick, 15_000)
|
|
399
|
-
}
|
|
400
|
-
tick()
|
|
401
|
-
return () => clearTimeout(timer)
|
|
402
|
-
}, 'notify-tray: quota poll')
|
|
403
|
-
|
|
404
|
-
// ---- DeepSeek account balance (optional service) ------------------------
|
|
405
|
-
ctx.inject(['deepseekAccount'], (ctx) => {
|
|
406
|
-
const client = {
|
|
407
|
-
// Mirrors DSH's own settings page: the harness version and the UI locale.
|
|
408
|
-
version: DSH_VERSION,
|
|
409
|
-
locale: 'zh-CN',
|
|
410
|
-
timezoneOffsetSeconds: -new Date().getTimezoneOffset() * 60,
|
|
411
|
-
}
|
|
412
|
-
const poll = async () => {
|
|
413
|
-
try {
|
|
414
|
-
const balance = await ctx.deepseekAccount.getBalance(client)
|
|
415
|
-
if (balance?.status === 'ready') ledger.balance(balance.value)
|
|
416
|
-
if (account.usageUrl === undefined) {
|
|
417
|
-
const state = await ctx.deepseekAccount.getState?.()
|
|
418
|
-
account.usageUrl = state?.links?.usageUrl
|
|
419
|
-
}
|
|
420
|
-
} catch (error) {
|
|
421
|
-
logger.debug?.('读取账户余额失败', error)
|
|
422
|
-
}
|
|
423
|
-
}
|
|
424
|
-
ctx.effect(() => {
|
|
425
|
-
let timer
|
|
426
|
-
const loop = () => {
|
|
427
|
-
poll()
|
|
428
|
-
timer = setTimeout(loop, Math.max(1, cfg.balancePollMinutes) * 60_000)
|
|
429
|
-
}
|
|
430
|
-
loop()
|
|
431
|
-
return () => clearTimeout(timer)
|
|
432
|
-
}, 'notify-tray: balance poll')
|
|
433
|
-
// A finished turn is when spend lands; refresh shortly after.
|
|
434
|
-
ctx.on('agent/status', ({ status }) => {
|
|
435
|
-
if (status === 'idle') setTimeout(poll, 5000)
|
|
436
|
-
})
|
|
437
|
-
})
|
|
438
|
-
|
|
439
|
-
// ---- routes for the browser half ------------------------------------------
|
|
440
|
-
ctx.inject(['webServer', 'connection'], (ctx) => {
|
|
441
|
-
webOrigin = () => ctx.webServer.getOrigin?.()
|
|
442
|
-
const guard = (req, res, method) => {
|
|
443
|
-
const rejection = ctx.connection.requestRejection(req)
|
|
444
|
-
if (rejection !== undefined) {
|
|
445
|
-
res.statusCode = rejection
|
|
446
|
-
res.end()
|
|
447
|
-
return false
|
|
448
|
-
}
|
|
449
|
-
if (req.method !== method) {
|
|
450
|
-
res.statusCode = 405
|
|
451
|
-
res.setHeader('allow', method)
|
|
452
|
-
res.end()
|
|
453
|
-
return false
|
|
454
|
-
}
|
|
455
|
-
return true
|
|
456
|
-
}
|
|
457
|
-
const json = (res, body) => {
|
|
458
|
-
res.statusCode = 200
|
|
459
|
-
res.setHeader('content-type', 'application/json; charset=utf-8')
|
|
460
|
-
res.setHeader('cache-control', 'no-store')
|
|
461
|
-
res.end(JSON.stringify(body))
|
|
462
|
-
}
|
|
463
|
-
ctx.effect(() => ctx.webServer.register({
|
|
464
|
-
kind: 'exact',
|
|
465
|
-
path: STATE_PATH,
|
|
466
|
-
handler: (req, res) => {
|
|
467
|
-
if (!guard(req, res, 'GET')) return
|
|
468
|
-
const url = new URL(String(req.url), 'http://localhost')
|
|
469
|
-
// Only a window that can actually show notifications counts as listening;
|
|
470
|
-
// a browser tab without permission must not silence the system channel.
|
|
471
|
-
if (url.searchParams.get('notify') === '1') lastClientPoll = Date.now()
|
|
472
|
-
const after = Number(url.searchParams.get('after') ?? '-1')
|
|
473
|
-
const channel = cfg.channel
|
|
474
|
-
const clientSide = channel === 'auto' || channel === 'client' || channel === 'both'
|
|
475
|
-
const currentUsage = usage()
|
|
476
|
-
const enabled = Object.fromEntries(Object.entries(EVENT_SWITCH).map(([type, key]) => [type, Boolean(cfg[key])]))
|
|
477
|
-
const body = {
|
|
478
|
-
boot,
|
|
479
|
-
// The settings page shows only what this OS has (no status-bar section on Windows).
|
|
480
|
-
platform: process.platform,
|
|
481
|
-
seq: tracker.seq,
|
|
482
|
-
// A first poll (after = -1) only learns the cursor; history is never replayed.
|
|
483
|
-
// Each event carries its wording, so the window shows exactly what the host would.
|
|
484
|
-
events: clientSide && after >= 0
|
|
485
|
-
? tracker.eventsAfter(after).filter(e => enabled[e.type]).map(e => ({ ...e, display: speak(e) }))
|
|
486
|
-
: [],
|
|
487
|
-
titles: TITLES,
|
|
488
|
-
suppressWhenFocused: cfg.suppressWhenFocused,
|
|
489
|
-
focus: focusQueue,
|
|
490
|
-
summary: tracker.summary(),
|
|
491
|
-
usage: currentUsage,
|
|
492
|
-
// Today's figure exactly as the tray shows it, for the settings page's spend card.
|
|
493
|
-
spend: spendOf(currentUsage, cfg.spendSource) ?? null,
|
|
494
|
-
pricing: pricing(),
|
|
495
|
-
plan: plan(),
|
|
496
|
-
catalogLoaded: Boolean(pi),
|
|
497
|
-
tray: trayStatus(),
|
|
498
|
-
}
|
|
499
|
-
focusQueue = []
|
|
500
|
-
json(res, body)
|
|
501
|
-
},
|
|
502
|
-
}), `notify-tray: GET ${STATE_PATH}`)
|
|
503
|
-
ctx.effect(() => ctx.webServer.register({
|
|
504
|
-
kind: 'exact',
|
|
505
|
-
path: CATALOG_PATH,
|
|
506
|
-
handler: (req, res) => {
|
|
507
|
-
if (!guard(req, res, 'GET')) return
|
|
508
|
-
json(res, { providers: publicCatalog(), piLoaded: Boolean(pi), piFile: pi?.file })
|
|
509
|
-
},
|
|
510
|
-
}), `notify-tray: GET ${CATALOG_PATH}`)
|
|
511
|
-
ctx.effect(() => ctx.webServer.register({
|
|
512
|
-
kind: 'exact',
|
|
513
|
-
path: REFRESH_PATH,
|
|
514
|
-
handler: (req, res) => {
|
|
515
|
-
if (!guard(req, res, 'POST')) return
|
|
516
|
-
pollQuota(true)
|
|
517
|
-
.then(result => json(res, { quota: result ?? null, plan: plan() }))
|
|
518
|
-
.catch(error => json(res, { quota: { ok: false, at: Date.now(), error: String(error?.message ?? error) }, plan: plan() }))
|
|
519
|
-
},
|
|
520
|
-
}), `notify-tray: POST ${REFRESH_PATH}`)
|
|
521
|
-
// The settings page's "show the whale again": undoes the tray menu's hide.
|
|
522
|
-
ctx.effect(() => ctx.webServer.register({
|
|
523
|
-
kind: 'exact',
|
|
524
|
-
path: TRAY_PATH,
|
|
525
|
-
handler: (req, res) => {
|
|
526
|
-
if (!guard(req, res, 'POST')) return
|
|
527
|
-
trayHidden = false
|
|
528
|
-
trayFailed = false
|
|
529
|
-
Promise.resolve(syncTray())
|
|
530
|
-
.catch(() => {})
|
|
531
|
-
.then(() => json(res, { tray: trayStatus() }))
|
|
532
|
-
},
|
|
533
|
-
}), `notify-tray: POST ${TRAY_PATH}`)
|
|
534
|
-
})
|
|
126
|
+
setupSpend(ctx, host)
|
|
127
|
+
setupRoutes(ctx, host)
|
|
535
128
|
}
|
package/lib/ledger.js
CHANGED
|
@@ -6,13 +6,15 @@
|
|
|
6
6
|
* samples with token-meter's dedupe rule (each (turn, step) slot keeps its
|
|
7
7
|
* last sample; `llm/retry-started` opens a new slot), filed under the
|
|
8
8
|
* `provider/model` route the session's latest `request/header` announced
|
|
9
|
-
* and priced by a resolver (see pricing.js) per million tokens;
|
|
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;
|
|
10
12
|
* - balance: polled DeepSeek account balance; the day's spend is the sum of
|
|
11
13
|
* balance drops, so a top-up never reads as negative spend.
|
|
12
14
|
*/
|
|
13
15
|
import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
|
|
14
16
|
import { dirname } from 'node:path'
|
|
15
|
-
import { providerForRoute } from './catalog.js'
|
|
17
|
+
import { isDeepseekOffPeak, providerForRoute } from './catalog.js'
|
|
16
18
|
import { localDate } from './tracker.js'
|
|
17
19
|
|
|
18
20
|
/** Days of history kept on disk. */
|
|
@@ -114,7 +116,7 @@ export class Ledger {
|
|
|
114
116
|
const date = localDate(this.now())
|
|
115
117
|
let day = this.days[date]
|
|
116
118
|
if (day === undefined) {
|
|
117
|
-
day = { date, tokens: zero(), byModel: {}, balanceSpend: {}, balanceLast: {} }
|
|
119
|
+
day = { date, tokens: zero(), byModel: {}, offPeak: {}, balanceSpend: {}, balanceLast: {} }
|
|
118
120
|
// Carry the last known balance across midnight so the first poll of the day diffs against it.
|
|
119
121
|
const previous = Object.keys(this.days).sort().pop()
|
|
120
122
|
if (previous !== undefined) day.balanceLast = { ...this.days[previous].balanceLast }
|
|
@@ -172,10 +174,13 @@ export class Ledger {
|
|
|
172
174
|
const previous = slot && slot.turn === turn && slot.step === step ? slot : undefined
|
|
173
175
|
const day = this.today()
|
|
174
176
|
const byModel = (day.byModel[key] ??= zero())
|
|
177
|
+
// Days recorded before off-peak tracking have no `offPeak` map.
|
|
178
|
+
const offPeak = billedToDeepseek(key) && isDeepseekOffPeak(this.now()) ? ((day.offPeak ??= {})[key] ??= zero()) : undefined
|
|
175
179
|
for (const bucket of Object.keys(next)) {
|
|
176
180
|
const delta = next[bucket] - (previous?.buckets[bucket] ?? 0)
|
|
177
181
|
day.tokens[bucket] += delta
|
|
178
182
|
byModel[bucket] += delta
|
|
183
|
+
if (offPeak) offPeak[bucket] += delta
|
|
179
184
|
}
|
|
180
185
|
this.slots.set(id, { turn, step, buckets: next })
|
|
181
186
|
this.changed()
|
|
@@ -208,7 +213,9 @@ export class Ledger {
|
|
|
208
213
|
* Today's totals. `pricing` is either a user price table (per million tokens,
|
|
209
214
|
* keyed by route / model id / prefix) or a resolver
|
|
210
215
|
* `(routeKey) => { price, source } | undefined` whose price is already in the
|
|
211
|
-
* display currency.
|
|
216
|
+
* display currency. A hit with `offPeakFactor` bills the route's off-peak
|
|
217
|
+
* tokens at that fraction of its price. The estimate is undefined until at
|
|
218
|
+
* least one route priced.
|
|
212
219
|
*/
|
|
213
220
|
summary(pricing, currency) {
|
|
214
221
|
const day = this.today()
|
|
@@ -223,7 +230,10 @@ export class Ledger {
|
|
|
223
230
|
const byModel = []
|
|
224
231
|
for (const [key, buckets] of Object.entries(day.byModel)) {
|
|
225
232
|
const hit = resolve(key)
|
|
226
|
-
const
|
|
233
|
+
const offPeak = hit?.offPeakFactor !== undefined ? day.offPeak?.[key] : undefined
|
|
234
|
+
const cost = hit
|
|
235
|
+
? round(costOf(buckets, hit.price) - (offPeak ? costOf(offPeak, hit.price) * (1 - hit.offPeakFactor) : 0))
|
|
236
|
+
: undefined
|
|
227
237
|
if (hit) {
|
|
228
238
|
priced = true
|
|
229
239
|
sources.add(hit.source)
|